Files
Pay2Gateway/app/api/merchants/route.ts

89 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
export async function POST(req: NextRequest) {
try {
const { name, webhook_url, payment_provider, provider_config, fee_percent } = await req.json();
if (!name) {
return NextResponse.json(
{ error: 'Firma adı zorunludur.' },
{ status: 400 }
);
}
// Generate a 8-character short ID (e.g., P2C-A1B2C3)
const generateShortId = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < 8; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
};
const shortId = generateShortId();
const provider = payment_provider || 'stripe';
const configStr = provider_config ? JSON.stringify(provider_config) : '{}';
const result = await db.query(
`INSERT INTO merchants (name, webhook_url, short_id, payment_provider, provider_config, fee_percent)
VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
[name, webhook_url, shortId, provider, configStr, fee_percent || 1.0]
);
if (result.rows.length === 0) {
throw new Error('Could not insert merchant');
}
return NextResponse.json(result.rows[0]);
} catch (err: any) {
console.error('Internal Error:', err);
return NextResponse.json(
{ error: `Internal Server Error: ${err.message}` },
{ status: 500 }
);
}
}
export async function GET() {
try {
const merchantsResult = await db.query('SELECT * FROM merchants ORDER BY created_at DESC');
const merchants = merchantsResult.rows;
// Fetch breakdown per merchant
const breakdownResult = await db.query(`
SELECT
merchant_id,
COALESCE(paid_network, 'SİSTEM') as network,
COALESCE(paid_token, 'TRY') as token,
SUM(CAST(COALESCE(paid_amount_crypto, '0') AS numeric)) as amount
FROM transactions
WHERE status = 'succeeded' AND paid_network IS NOT NULL
GROUP BY merchant_id, paid_network, paid_token
`);
const breakdowns = breakdownResult.rows.reduce((acc: any, row: any) => {
if (!acc[row.merchant_id]) acc[row.merchant_id] = [];
acc[row.merchant_id].push({
network: row.network,
token: row.token,
amount: row.amount
});
return acc;
}, {});
const merchantsWithBreakdown = merchants.map(m => ({
...m,
balance_breakdown: breakdowns[m.id] || []
}));
return NextResponse.json(merchantsWithBreakdown);
} catch (err: any) {
return NextResponse.json(
{ error: `Internal Server Error: ${err.message}` },
{ status: 500 }
);
}
}