1074 lines
41 KiB
TypeScript
1074 lines
41 KiB
TypeScript
import { query } from '../db/connection';
|
|
import { getReportDefinition } from '../reports/definitions';
|
|
import { withNormalizedReportPeriod } from '../utils/reportPeriodBounds';
|
|
import {
|
|
buildCreatedAtIdKeyset,
|
|
buildCursorFromRow,
|
|
decodeReportCursor,
|
|
orderByCreatedAtId,
|
|
reportSupportsCursor,
|
|
} from '../utils/reportListCursor';
|
|
|
|
export type ReportQueryOptions = {
|
|
search?: string;
|
|
from?: string;
|
|
to?: string;
|
|
sortBy?: string;
|
|
sortDir?: 'asc' | 'desc';
|
|
limit: number;
|
|
offset?: number;
|
|
cursor?: string;
|
|
includeTotal?: boolean;
|
|
/** Extra filters from report preset (status, isAuto, etc.) */
|
|
preset?: Record<string, string | boolean | number>;
|
|
/** When set, return only rows whose primary key is in this list */
|
|
ids?: string[];
|
|
};
|
|
|
|
export type ReportSummary = {
|
|
totalCount?: number;
|
|
uniqueUsers?: number;
|
|
totalAmountRaw?: number;
|
|
};
|
|
|
|
export type ReportPageResult = {
|
|
items: Record<string, unknown>[];
|
|
total: number;
|
|
columns: { field: string; headerName: string; type?: string }[];
|
|
nextCursor?: string | null;
|
|
hasMore?: boolean;
|
|
totalIsExact?: boolean;
|
|
summary?: ReportSummary;
|
|
};
|
|
|
|
const SORT_WHITELIST = new Set([
|
|
'created_at',
|
|
'amount',
|
|
'user_id',
|
|
'country',
|
|
'users',
|
|
'deposits_raw',
|
|
'withdrawals_raw',
|
|
'net_pnl_raw',
|
|
'main_balance_raw',
|
|
'stake_raw',
|
|
'payout_raw',
|
|
'interval_minutes',
|
|
]);
|
|
|
|
function safeSort(field: string | undefined, dir: 'asc' | 'desc' | undefined, fallback: string): string {
|
|
const col = field && SORT_WHITELIST.has(field) ? field : fallback;
|
|
const direction = dir === 'asc' ? 'ASC' : 'DESC';
|
|
return `${col} ${direction}`;
|
|
}
|
|
|
|
function dateClause(alias: string, from?: string, to?: string, startIdx = 1): { sql: string; values: unknown[] } {
|
|
const parts: string[] = [];
|
|
const values: unknown[] = [];
|
|
let i = startIdx;
|
|
if (from) {
|
|
parts.push(`${alias} >= $${i++}::timestamptz`);
|
|
values.push(from);
|
|
}
|
|
if (to) {
|
|
parts.push(`${alias} <= $${i++}::timestamptz`);
|
|
values.push(to);
|
|
}
|
|
return { sql: parts.length ? parts.join(' AND ') : 'TRUE', values };
|
|
}
|
|
|
|
function idsFilter(
|
|
columnExpr: string,
|
|
ids: string[] | undefined,
|
|
values: unknown[],
|
|
paramIdx: number,
|
|
cast: 'uuid' | 'text' = 'uuid'
|
|
): { sql: string; nextIdx: number } {
|
|
if (!ids?.length) return { sql: '', nextIdx: paramIdx };
|
|
values.push(ids);
|
|
const castSuffix = cast === 'uuid' ? '::uuid[]' : '::text[]';
|
|
return { sql: ` AND ${columnExpr} = ANY($${paramIdx}${castSuffix})`, nextIdx: paramIdx + 1 };
|
|
}
|
|
|
|
function serializeDateRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {
|
|
return rows.map((r) => ({
|
|
...r,
|
|
created_at: r.created_at instanceof Date ? (r.created_at as Date).toISOString() : r.created_at,
|
|
}));
|
|
}
|
|
|
|
function useKeysetPagination(reportKey: string, options: ReportQueryOptions): boolean {
|
|
if (options.ids?.length) return false;
|
|
const sortBy = options.sortBy && SORT_WHITELIST.has(options.sortBy) ? options.sortBy : 'created_at';
|
|
if (!reportSupportsCursor(reportKey, sortBy)) return false;
|
|
return Boolean(options.cursor) || (options.offset ?? 0) === 0;
|
|
}
|
|
|
|
export async function runReport(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
const def = getReportDefinition(reportKey);
|
|
if (!def || def.source !== 'reports-api') {
|
|
throw new Error('Unknown report');
|
|
}
|
|
|
|
const normalized = withNormalizedReportPeriod(options);
|
|
|
|
switch (reportKey) {
|
|
case 'financial-deposits':
|
|
return listTransactions('deposit', reportKey, normalized);
|
|
case 'financial-withdrawals':
|
|
return listTransactions('withdrawal', reportKey, normalized);
|
|
case 'financial-deposit-users':
|
|
return listDepositUsers(reportKey, normalized);
|
|
case 'financial-bonuses':
|
|
return listBonuses(reportKey, normalized);
|
|
case 'financial-encouragement-grants':
|
|
return listEncouragementGrants(reportKey, normalized);
|
|
case 'financial-commission-history':
|
|
return listCommissionHistory(reportKey, normalized);
|
|
case 'financial-adjustments':
|
|
return listAdjustments(reportKey, normalized);
|
|
case 'financial-wallet-balances':
|
|
return listWalletBalances(normalized);
|
|
case 'games-participants':
|
|
case 'games-test-users':
|
|
return listPredictionUsers(reportKey, normalized);
|
|
case 'games-predictions':
|
|
case 'games-predictions-real':
|
|
case 'games-wins':
|
|
case 'games-losses':
|
|
case 'games-auto':
|
|
case 'games-manual':
|
|
case 'games-multi-candle':
|
|
case 'games-test':
|
|
return listPredictions(reportKey, normalized);
|
|
case 'geo-users':
|
|
case 'geo-deposits':
|
|
case 'geo-withdrawals':
|
|
case 'geo-pnl':
|
|
return listGeoReport(reportKey, normalized);
|
|
default:
|
|
throw new Error('Report not implemented');
|
|
}
|
|
}
|
|
|
|
function num(v: string | null | undefined): number {
|
|
return parseInt(v ?? '0', 10) || 0;
|
|
}
|
|
|
|
async function transactionSummary(
|
|
where: string,
|
|
filterValues: unknown[]
|
|
): Promise<ReportSummary> {
|
|
const rows = await query<
|
|
{ total_count: string; unique_users: string; total_amount: string }[]
|
|
>(
|
|
`SELECT COUNT(*)::text AS total_count,
|
|
COUNT(DISTINCT t.user_id)::text AS unique_users,
|
|
COALESCE(SUM(t.amount), 0)::text AS total_amount
|
|
FROM transactions t WHERE ${where}`,
|
|
filterValues
|
|
);
|
|
const r = rows[0];
|
|
return {
|
|
totalCount: num(r?.total_count),
|
|
uniqueUsers: num(r?.unique_users),
|
|
totalAmountRaw: num(r?.total_amount),
|
|
};
|
|
}
|
|
|
|
async function listTransactions(
|
|
type: 'deposit' | 'withdrawal',
|
|
reportKey: string,
|
|
options: ReportQueryOptions
|
|
): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'id', headerName: 'ID', type: 'string' },
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'amount', headerName: 'Montant (USDT)', type: 'money' },
|
|
{ field: 'status', headerName: 'Status', type: 'string' },
|
|
{ field: 'blockchain_tx_id', headerName: 'Tx ID', type: 'string' },
|
|
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
|
];
|
|
const date = dateClause('t.created_at', options.from, options.to, 2);
|
|
const values: unknown[] = [type, ...date.values];
|
|
let i = values.length + 1;
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(t.id::text ILIKE $${i} OR t.user_id::text ILIKE $${i} OR COALESCE(t.blockchain_tx_id, '') ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const idClause = idsFilter('t.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const where = `t.type = $1 AND t.status = 'completed' AND ${date.sql} AND ${searchSql}${idClause.sql}`;
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
const filterValues = [...values];
|
|
const summary = await transactionSummary(where, filterValues);
|
|
|
|
if (useKeysetPagination(reportKey, options)) {
|
|
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
|
const keyset = buildCreatedAtIdKeyset('t', sortDir, decoded, values, i);
|
|
i = keyset.nextParam;
|
|
const includeTotal = options.includeTotal !== false && !options.cursor;
|
|
let total = 0;
|
|
let totalIsExact = false;
|
|
if (includeTotal) {
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM transactions t WHERE ${where}`,
|
|
values.slice(0, keyset.nextParam - (decoded ? 2 : 0))
|
|
);
|
|
total = parseInt(countRows[0]?.c ?? '0', 10);
|
|
totalIsExact = true;
|
|
}
|
|
values.push(options.limit + 1);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT t.id, t.user_id, t.amount::text AS amount, t.status, t.blockchain_tx_id, t.created_at
|
|
FROM transactions t WHERE ${where}${keyset.sql}
|
|
ORDER BY ${orderByCreatedAtId('t', sortDir)}
|
|
LIMIT $${i}`,
|
|
values
|
|
);
|
|
const hasMore = rows.length > options.limit;
|
|
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
|
const nextCursor =
|
|
hasMore && items.length > 0
|
|
? buildCursorFromRow(sortDir, items[items.length - 1] as { created_at: unknown; id: unknown })
|
|
: null;
|
|
return { items, total, columns, nextCursor, hasMore, totalIsExact, summary };
|
|
}
|
|
|
|
const sort = safeSort(options.sortBy, options.sortDir, 'created_at');
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM transactions t WHERE ${where}`,
|
|
values
|
|
);
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT t.id, t.user_id, t.amount::text AS amount, t.status, t.blockchain_tx_id,
|
|
t.created_at
|
|
FROM transactions t WHERE ${where}
|
|
ORDER BY ${sort.replace('created_at', 't.created_at').replace('amount', 't.amount').replace('user_id', 't.user_id')}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function listDepositUsers(
|
|
reportKey: string,
|
|
options: ReportQueryOptions
|
|
): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'deposit_count', headerName: 'Nombre de dépôts', type: 'number' },
|
|
{ field: 'total_amount', headerName: 'Montant total (USDT)', type: 'money' },
|
|
{ field: 'last_deposit_at', headerName: 'Dernier dépôt', type: 'date' },
|
|
];
|
|
const date = dateClause('t.created_at', options.from, options.to, 2);
|
|
const values: unknown[] = ['deposit', ...date.values];
|
|
let i = values.length + 1;
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(t.user_id::text ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const where = `t.type = $1 AND t.status = 'completed' AND ${date.sql} AND ${searchSql}`;
|
|
const filterValues = [...values];
|
|
const summary = await transactionSummary(where, filterValues);
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM (
|
|
SELECT t.user_id FROM transactions t WHERE ${where} GROUP BY t.user_id
|
|
) d`,
|
|
filterValues
|
|
);
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT t.user_id,
|
|
COUNT(*)::text AS deposit_count,
|
|
COALESCE(SUM(t.amount), 0)::text AS total_amount,
|
|
MAX(t.created_at) AS last_deposit_at
|
|
FROM transactions t WHERE ${where}
|
|
GROUP BY t.user_id
|
|
ORDER BY COALESCE(SUM(t.amount), 0) ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function listEncouragementGrants(
|
|
reportKey: string,
|
|
options: ReportQueryOptions
|
|
): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'id', headerName: 'ID', type: 'string' },
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'status', headerName: 'Status', type: 'string' },
|
|
{ field: 'streak_count', headerName: 'Streak', type: 'number' },
|
|
{ field: 'loss_raw', headerName: 'Losses / stake base (USDT)', type: 'money' },
|
|
{ field: 'refund_percent', headerName: 'Refund %', type: 'number' },
|
|
{ field: 'credit_raw', headerName: 'Bonus (USDT)', type: 'money' },
|
|
{ field: 'granted_at', headerName: 'Granted at', type: 'date' },
|
|
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
|
];
|
|
const date = dateClause('g.created_at', options.from, options.to, 1);
|
|
const values = [...date.values];
|
|
let i = values.length + 1;
|
|
const parts = [date.sql];
|
|
if (options.search?.trim()) {
|
|
parts.push(`(g.id::text ILIKE $${i} OR g.user_id::text ILIKE $${i} OR g.status ILIKE $${i})`);
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const statusPreset = options.preset?.status;
|
|
if (typeof statusPreset === 'string' && statusPreset.trim()) {
|
|
parts.push(`g.status = $${i++}`);
|
|
values.push(statusPreset.trim());
|
|
}
|
|
const idClause = idsFilter('g.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const whereSql = `${parts.join(' AND ')}${idClause.sql}`;
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
|
|
const summaryRows = await query<
|
|
{ total_count: string; unique_users: string; total_amount: string }[]
|
|
>(
|
|
`SELECT COUNT(*)::text AS total_count,
|
|
COUNT(DISTINCT g.user_id)::text AS unique_users,
|
|
COALESCE(SUM(g.credit_raw), 0)::text AS total_amount
|
|
FROM solo_encouragement_grants g
|
|
WHERE ${whereSql}`,
|
|
values
|
|
);
|
|
const summary: ReportSummary = {
|
|
totalCount: num(summaryRows[0]?.total_count),
|
|
uniqueUsers: num(summaryRows[0]?.unique_users),
|
|
totalAmountRaw: num(summaryRows[0]?.total_amount),
|
|
};
|
|
|
|
if (useKeysetPagination(reportKey, options)) {
|
|
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
|
let keysetSql = '';
|
|
if (decoded) {
|
|
values.push(decoded.createdAt, decoded.id);
|
|
const op = sortDir === 'asc' ? '>' : '<';
|
|
keysetSql = ` AND (g.created_at, g.id) ${op} ($${i}::timestamptz, $${i + 1}::uuid)`;
|
|
i += 2;
|
|
}
|
|
const includeTotal = options.includeTotal !== false && !options.cursor;
|
|
const total = includeTotal ? summary.totalCount ?? 0 : 0;
|
|
values.push(options.limit + 1);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT g.id, g.user_id, g.status, g.streak_count,
|
|
g.loss_raw::text AS loss_raw, g.refund_percent::text AS refund_percent,
|
|
g.credit_raw::text AS credit_raw, g.granted_at, g.created_at
|
|
FROM solo_encouragement_grants g
|
|
WHERE ${whereSql}${keysetSql}
|
|
ORDER BY g.created_at ${sortDir === 'asc' ? 'ASC' : 'DESC'}, g.id ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
|
LIMIT $${i}`,
|
|
values
|
|
);
|
|
const hasMore = rows.length > options.limit;
|
|
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
|
const nextCursor =
|
|
hasMore && items.length > 0
|
|
? buildCursorFromRow(sortDir, items[items.length - 1] as { created_at: unknown; id: unknown })
|
|
: null;
|
|
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary };
|
|
}
|
|
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM solo_encouragement_grants g WHERE ${whereSql}`,
|
|
values
|
|
);
|
|
const allowedSort = new Set(['created_at', 'user_id', 'streak_count', 'loss_raw', 'credit_raw', 'status']);
|
|
const sortField =
|
|
options.sortBy && allowedSort.has(options.sortBy) ? options.sortBy : 'created_at';
|
|
const sortSql = `g.${sortField} ${sortDir === 'asc' ? 'ASC' : 'DESC'}`;
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT g.id, g.user_id, g.status, g.streak_count,
|
|
g.loss_raw::text AS loss_raw, g.refund_percent::text AS refund_percent,
|
|
g.credit_raw::text AS credit_raw, g.granted_at, g.created_at
|
|
FROM solo_encouragement_grants g
|
|
WHERE ${whereSql}
|
|
ORDER BY ${sortSql}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function listCommissionHistory(
|
|
reportKey: string,
|
|
options: ReportQueryOptions
|
|
): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'id', headerName: 'ID', type: 'string' },
|
|
{ field: 'beneficiary_user_id', headerName: 'Beneficiary user ID', type: 'string' },
|
|
{ field: 'referred_user_id', headerName: 'Referred user ID', type: 'string' },
|
|
{ field: 'level_number', headerName: 'Level', type: 'number' },
|
|
{ field: 'commission_source', headerName: 'Source', type: 'string' },
|
|
{ field: 'status', headerName: 'Status', type: 'string' },
|
|
{ field: 'base_amount', headerName: 'Base amount (USDT)', type: 'money' },
|
|
{ field: 'commission_percent', headerName: 'Commission %', type: 'number' },
|
|
{ field: 'commission_amount', headerName: 'Commission (USDT)', type: 'money' },
|
|
{ field: 'eligible_at', headerName: 'Eligible at', type: 'date' },
|
|
{ field: 'paid_at', headerName: 'Paid at', type: 'date' },
|
|
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
|
];
|
|
const date = dateClause('p.created_at', options.from, options.to, 1);
|
|
const values = [...date.values];
|
|
let i = values.length + 1;
|
|
const parts = [date.sql];
|
|
if (options.search?.trim()) {
|
|
parts.push(
|
|
`(p.id::text ILIKE $${i} OR p.beneficiary_user_id::text ILIKE $${i} OR p.referred_user_id::text ILIKE $${i} OR p.status ILIKE $${i} OR p.commission_source ILIKE $${i})`
|
|
);
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const statusPreset = options.preset?.status;
|
|
if (typeof statusPreset === 'string' && statusPreset.trim()) {
|
|
parts.push(`p.status = $${i++}`);
|
|
values.push(statusPreset.trim());
|
|
}
|
|
const sourcePreset = options.preset?.commission_source ?? options.preset?.source;
|
|
if (typeof sourcePreset === 'string' && sourcePreset.trim()) {
|
|
parts.push(`p.commission_source = $${i++}`);
|
|
values.push(sourcePreset.trim());
|
|
}
|
|
const idClause = idsFilter('p.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const whereSql = `${parts.join(' AND ')}${idClause.sql}`;
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
|
|
const summaryRows = await query<
|
|
{ total_count: string; unique_users: string; total_amount: string }[]
|
|
>(
|
|
`SELECT COUNT(*)::text AS total_count,
|
|
COUNT(DISTINCT p.beneficiary_user_id)::text AS unique_users,
|
|
COALESCE(SUM(p.commission_amount), 0)::text AS total_amount
|
|
FROM referral_commission_payouts p
|
|
WHERE ${whereSql}`,
|
|
values
|
|
);
|
|
const summary: ReportSummary = {
|
|
totalCount: num(summaryRows[0]?.total_count),
|
|
uniqueUsers: num(summaryRows[0]?.unique_users),
|
|
totalAmountRaw: num(summaryRows[0]?.total_amount),
|
|
};
|
|
|
|
const selectSql = `SELECT p.id, p.beneficiary_user_id, p.referred_user_id, p.level_number,
|
|
p.commission_source, p.status,
|
|
p.deposit_amount::text AS base_amount,
|
|
p.commission_percent::text AS commission_percent,
|
|
p.commission_amount::text AS commission_amount,
|
|
p.eligible_at, p.paid_at, p.created_at
|
|
FROM referral_commission_payouts p`;
|
|
|
|
const serializeCommissionRows = (rows: Record<string, unknown>[]): Record<string, unknown>[] =>
|
|
rows.map((r) => ({
|
|
...r,
|
|
created_at: r.created_at instanceof Date ? (r.created_at as Date).toISOString() : r.created_at,
|
|
eligible_at: r.eligible_at instanceof Date ? (r.eligible_at as Date).toISOString() : r.eligible_at,
|
|
paid_at: r.paid_at instanceof Date ? (r.paid_at as Date).toISOString() : r.paid_at,
|
|
}));
|
|
|
|
if (useKeysetPagination(reportKey, options)) {
|
|
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
|
let keysetSql = '';
|
|
if (decoded) {
|
|
values.push(decoded.createdAt, decoded.id);
|
|
const op = sortDir === 'asc' ? '>' : '<';
|
|
keysetSql = ` AND (p.created_at, p.id) ${op} ($${i}::timestamptz, $${i + 1}::uuid)`;
|
|
i += 2;
|
|
}
|
|
const includeTotal = options.includeTotal !== false && !options.cursor;
|
|
const total = includeTotal ? summary.totalCount ?? 0 : 0;
|
|
values.push(options.limit + 1);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`${selectSql}
|
|
WHERE ${whereSql}${keysetSql}
|
|
ORDER BY p.created_at ${sortDir === 'asc' ? 'ASC' : 'DESC'}, p.id ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
|
LIMIT $${i}`,
|
|
values
|
|
);
|
|
const hasMore = rows.length > options.limit;
|
|
const items = serializeCommissionRows(hasMore ? rows.slice(0, options.limit) : rows);
|
|
const last = items[items.length - 1];
|
|
const nextCursor =
|
|
hasMore && last
|
|
? buildCursorFromRow(sortDir, {
|
|
created_at: last.created_at,
|
|
id: last.id,
|
|
})
|
|
: null;
|
|
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary };
|
|
}
|
|
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM referral_commission_payouts p WHERE ${whereSql}`,
|
|
values
|
|
);
|
|
const allowedSort = new Set([
|
|
'created_at',
|
|
'beneficiary_user_id',
|
|
'referred_user_id',
|
|
'level_number',
|
|
'commission_amount',
|
|
'status',
|
|
'commission_source',
|
|
]);
|
|
const sortField =
|
|
options.sortBy && allowedSort.has(options.sortBy) ? options.sortBy : 'created_at';
|
|
const sortSql = `p.${sortField} ${sortDir === 'asc' ? 'ASC' : 'DESC'}`;
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`${selectSql}
|
|
WHERE ${whereSql}
|
|
ORDER BY ${sortSql}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeCommissionRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function listBonuses(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'id', headerName: 'ID', type: 'string' },
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'kind', headerName: 'Type', type: 'string' },
|
|
{ field: 'amount', headerName: 'Montant (USDT)', type: 'money' },
|
|
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
|
];
|
|
const date = dateClause('created_at', options.from, options.to, 1);
|
|
const values = [...date.values];
|
|
let i = values.length + 1;
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(id::text ILIKE $${i} OR user_id::text ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const idClause = idsFilter('x.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const base = `
|
|
SELECT la.id, la.user_id, 'manual_bonus' AS kind, la.amount::text AS amount, la.created_at
|
|
FROM ledger_adjustments la
|
|
WHERE la.adjustment_type = 'bonus' AND ${date.sql.replace(/created_at/g, 'la.created_at')}
|
|
UNION ALL
|
|
SELECT rc.id, rc.beneficiary_user_id AS user_id, 'referral' AS kind,
|
|
rc.commission_amount::text AS amount, COALESCE(rc.paid_at, rc.created_at) AS created_at
|
|
FROM referral_commission_payouts rc
|
|
WHERE rc.status = 'paid' AND ${date.sql.replace(/created_at/g, 'COALESCE(rc.paid_at, rc.created_at)')}
|
|
`;
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
const filterSql = `${searchSql}${idClause.sql}`;
|
|
const filterValues = [...values];
|
|
const summary = await bonusSummary(base, filterSql, filterValues);
|
|
|
|
if (useKeysetPagination(reportKey, options)) {
|
|
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
|
let keysetSql = '';
|
|
if (decoded) {
|
|
values.push(decoded.createdAt, decoded.id);
|
|
const op = sortDir === 'asc' ? '>' : '<';
|
|
keysetSql = ` AND (x.created_at, x.id) ${op} ($${i}::timestamptz, $${i + 1}::uuid)`;
|
|
i += 2;
|
|
}
|
|
const includeTotal = options.includeTotal !== false && !options.cursor;
|
|
let total = 0;
|
|
if (includeTotal) {
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM (${base}) x WHERE ${filterSql}`,
|
|
values.slice(0, i - (decoded ? 2 : 0))
|
|
);
|
|
total = parseInt(countRows[0]?.c ?? '0', 10);
|
|
}
|
|
values.push(options.limit + 1);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT * FROM (${base}) x WHERE ${filterSql}${keysetSql}
|
|
ORDER BY x.created_at ${sortDir === 'asc' ? 'ASC' : 'DESC'}, x.id ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
|
LIMIT $${i}`,
|
|
values
|
|
);
|
|
const hasMore = rows.length > options.limit;
|
|
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
|
const nextCursor =
|
|
hasMore && items.length > 0
|
|
? buildCursorFromRow(sortDir, items[items.length - 1] as { created_at: unknown; id: unknown })
|
|
: null;
|
|
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary };
|
|
}
|
|
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM (${base}) x WHERE ${filterSql}`,
|
|
values
|
|
);
|
|
const sort = safeSort(options.sortBy, options.sortDir, 'created_at');
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT * FROM (${base}) x WHERE ${filterSql} ORDER BY ${sort} LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function bonusSummary(
|
|
base: string,
|
|
filterSql: string,
|
|
filterValues: unknown[]
|
|
): Promise<ReportSummary> {
|
|
const rows = await query<
|
|
{ total_count: string; unique_users: string; total_amount: string }[]
|
|
>(
|
|
`SELECT COUNT(*)::text AS total_count,
|
|
COUNT(DISTINCT x.user_id)::text AS unique_users,
|
|
COALESCE(SUM(x.amount::bigint), 0)::text AS total_amount
|
|
FROM (${base}) x WHERE ${filterSql}`,
|
|
filterValues
|
|
);
|
|
const r = rows[0];
|
|
return {
|
|
totalCount: num(r?.total_count),
|
|
uniqueUsers: num(r?.unique_users),
|
|
totalAmountRaw: num(r?.total_amount),
|
|
};
|
|
}
|
|
|
|
async function listAdjustments(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'id', headerName: 'ID', type: 'string' },
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'amount', headerName: 'Montant (USDT)', type: 'money' },
|
|
{ field: 'approved_by', headerName: 'Approved by', type: 'string' },
|
|
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
|
];
|
|
const date = dateClause('la.created_at', options.from, options.to, 1);
|
|
const values = [...date.values];
|
|
let i = values.length + 1;
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(la.id::text ILIKE $${i} OR la.user_id::text ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const idClause = idsFilter('la.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const where = `la.adjustment_type = 'admin_adjustment' AND ${date.sql} AND ${searchSql}${idClause.sql}`;
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
const filterValues = [...values];
|
|
const summary = await adjustmentSummary(where, filterValues);
|
|
|
|
if (useKeysetPagination(reportKey, options)) {
|
|
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
|
const keyset = buildCreatedAtIdKeyset('la', sortDir, decoded, values, i);
|
|
i = keyset.nextParam;
|
|
const includeTotal = options.includeTotal !== false && !options.cursor;
|
|
let total = 0;
|
|
if (includeTotal) {
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM ledger_adjustments la WHERE ${where}`,
|
|
values.slice(0, keyset.nextParam - (decoded ? 2 : 0))
|
|
);
|
|
total = parseInt(countRows[0]?.c ?? '0', 10);
|
|
}
|
|
values.push(options.limit + 1);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT la.id, la.user_id, la.amount::text AS amount, la.approved_by, la.created_at
|
|
FROM ledger_adjustments la WHERE ${where}${keyset.sql}
|
|
ORDER BY ${orderByCreatedAtId('la', sortDir)}
|
|
LIMIT $${i}`,
|
|
values
|
|
);
|
|
const hasMore = rows.length > options.limit;
|
|
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
|
const nextCursor =
|
|
hasMore && items.length > 0
|
|
? buildCursorFromRow(sortDir, items[items.length - 1] as { created_at: unknown; id: unknown })
|
|
: null;
|
|
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary };
|
|
}
|
|
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM ledger_adjustments la WHERE ${where}`,
|
|
values
|
|
);
|
|
const sort = safeSort(options.sortBy, options.sortDir, 'created_at');
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT la.id, la.user_id, la.amount::text AS amount, la.approved_by, la.created_at
|
|
FROM ledger_adjustments la WHERE ${where}
|
|
ORDER BY ${sort.replace('created_at', 'la.created_at').replace('amount', 'la.amount')}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function adjustmentSummary(
|
|
where: string,
|
|
filterValues: unknown[]
|
|
): Promise<ReportSummary> {
|
|
const rows = await query<
|
|
{ total_count: string; unique_users: string; total_amount: string }[]
|
|
>(
|
|
`SELECT COUNT(*)::text AS total_count,
|
|
COUNT(DISTINCT la.user_id)::text AS unique_users,
|
|
COALESCE(SUM(la.amount), 0)::text AS total_amount
|
|
FROM ledger_adjustments la WHERE ${where}`,
|
|
filterValues
|
|
);
|
|
const r = rows[0];
|
|
return {
|
|
totalCount: num(r?.total_count),
|
|
uniqueUsers: num(r?.unique_users),
|
|
totalAmountRaw: num(r?.total_amount),
|
|
};
|
|
}
|
|
|
|
async function listWalletBalances(options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'country', headerName: 'Pays', type: 'country' },
|
|
{ field: 'main_balance_raw', headerName: 'Main (USDT)', type: 'money' },
|
|
{ field: 'bonus_balance_raw', headerName: 'Bonus (USDT)', type: 'money' },
|
|
{ field: 'test_balance_raw', headerName: 'Test (USDT)', type: 'money' },
|
|
];
|
|
let i = 1;
|
|
const values: unknown[] = [];
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(u.id::text ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const idClause = idsFilter('u.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const where = `${searchSql}${idClause.sql}`;
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM users u WHERE ${where}`,
|
|
values
|
|
);
|
|
const sort = safeSort(options.sortBy, options.sortDir, 'main_balance_raw');
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT u.id, u.id AS user_id, COALESCE(u.country_of_residence, 'XX') AS country,
|
|
COALESCE(sm.available_balance, 0)::text AS main_balance_raw,
|
|
COALESCE(sb.available_balance, 0)::text AS bonus_balance_raw,
|
|
COALESCE(st.available_balance, 0)::text AS test_balance_raw
|
|
FROM users u
|
|
CROSS JOIN (SELECT id FROM wallet_types WHERE code = 'USDT_TRC20' LIMIT 1) wt
|
|
LEFT JOIN ledger_accounts sm ON sm.user_id = u.id AND sm.wallet_type_id = wt.id AND sm.account_kind = 'main'
|
|
LEFT JOIN ledger_accounts sb ON sb.user_id = u.id AND sb.wallet_type_id = wt.id AND sb.account_kind = 'bonus'
|
|
LEFT JOIN ledger_accounts st ON st.user_id = u.id AND st.wallet_type_id = wt.id AND st.account_kind = 'test'
|
|
WHERE ${where}
|
|
ORDER BY ${sort}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return { items: rows, total: parseInt(countRows[0]?.c ?? '0', 10), columns, totalIsExact: true };
|
|
}
|
|
|
|
function predictionFilters(reportKey: string): string {
|
|
switch (reportKey) {
|
|
case 'games-wins':
|
|
return "AND b.status = 'won'";
|
|
case 'games-losses':
|
|
return "AND b.status = 'lost'";
|
|
case 'games-auto':
|
|
return 'AND b.is_auto = TRUE';
|
|
case 'games-manual':
|
|
return "AND b.is_auto = FALSE AND b.prediction_mode = 'single'";
|
|
case 'games-predictions-real':
|
|
return "AND b.stake_account_kind IN ('main', 'bonus')";
|
|
case 'games-multi-candle':
|
|
return "AND b.prediction_mode = 'multi_candle'";
|
|
case 'games-test':
|
|
return "AND b.stake_account_kind = 'test'";
|
|
default:
|
|
return '';
|
|
}
|
|
}
|
|
|
|
async function listPredictionUsers(
|
|
reportKey: string,
|
|
options: ReportQueryOptions
|
|
): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'prediction_count', headerName: 'Prédictions', type: 'number' },
|
|
{ field: 'total_stake_raw', headerName: 'Misé (USDT)', type: 'money' },
|
|
{ field: 'total_payout_raw', headerName: 'Gains (USDT)', type: 'money' },
|
|
{ field: 'net_pnl_raw', headerName: 'Net P/L (USDT)', type: 'money' },
|
|
{ field: 'last_bet_at', headerName: 'Dernière prédiction', type: 'date' },
|
|
];
|
|
const extra =
|
|
reportKey === 'games-test-users' ? "AND b.stake_account_kind = 'test'" : '';
|
|
const date = dateClause('b.created_at', options.from, options.to, 1);
|
|
const values = [...date.values];
|
|
let i = values.length + 1;
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(b.user_id::text ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const where = `${date.sql} ${extra} AND ${searchSql}`;
|
|
const filterValues = [...values];
|
|
const summaryRows = await query<
|
|
{ total_count: string; unique_users: string; total_stake: string }[]
|
|
>(
|
|
`SELECT COUNT(*)::text AS total_count,
|
|
COUNT(DISTINCT b.user_id)::text AS unique_users,
|
|
COALESCE(SUM(b.stake_raw), 0)::text AS total_stake
|
|
FROM candle_predict_bets b WHERE ${where}`,
|
|
filterValues
|
|
);
|
|
const sr = summaryRows[0];
|
|
const summary: ReportSummary = {
|
|
totalCount: num(sr?.total_count),
|
|
uniqueUsers: num(sr?.unique_users),
|
|
totalAmountRaw: num(sr?.total_stake),
|
|
};
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM (
|
|
SELECT b.user_id FROM candle_predict_bets b WHERE ${where} GROUP BY b.user_id
|
|
) d`,
|
|
filterValues
|
|
);
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT b.user_id,
|
|
COUNT(*)::text AS prediction_count,
|
|
COALESCE(SUM(b.stake_raw), 0)::text AS total_stake_raw,
|
|
COALESCE(SUM(b.payout_raw), 0)::text AS total_payout_raw,
|
|
(COALESCE(SUM(b.payout_raw), 0) - COALESCE(SUM(b.stake_raw), 0))::text AS net_pnl_raw,
|
|
MAX(b.created_at) AS last_bet_at
|
|
FROM candle_predict_bets b WHERE ${where}
|
|
GROUP BY b.user_id
|
|
ORDER BY COALESCE(SUM(b.stake_raw), 0) ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
summary,
|
|
};
|
|
}
|
|
|
|
async function listPredictions(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'id', headerName: 'ID', type: 'string' },
|
|
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
|
{ field: 'direction', headerName: 'Direction', type: 'string' },
|
|
{ field: 'stake_raw', headerName: 'Mise (USDT)', type: 'money' },
|
|
{ field: 'payout_raw', headerName: 'Gain (USDT)', type: 'money' },
|
|
{ field: 'status', headerName: 'Status', type: 'string' },
|
|
{ field: 'is_auto', headerName: 'Auto', type: 'string' },
|
|
{ field: 'prediction_mode', headerName: 'Mode', type: 'string' },
|
|
{ field: 'stake_account_kind', headerName: 'Wallet', type: 'string' },
|
|
{ field: 'interval_minutes', headerName: 'Interval', type: 'number' },
|
|
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
|
];
|
|
const extra = predictionFilters(reportKey);
|
|
const date = dateClause('b.created_at', options.from, options.to, 1);
|
|
const values = [...date.values];
|
|
let i = values.length + 1;
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `(b.id::text ILIKE $${i} OR b.user_id::text ILIKE $${i})`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
i += 1;
|
|
}
|
|
const idClause = idsFilter('b.id', options.ids, values, i);
|
|
i = idClause.nextIdx;
|
|
const where = `${date.sql} ${extra} AND ${searchSql}${idClause.sql}`;
|
|
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
|
|
|
if (useKeysetPagination(reportKey, options)) {
|
|
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
|
const keyset = buildCreatedAtIdKeyset('b', sortDir, decoded, values, i);
|
|
i = keyset.nextParam;
|
|
const includeTotal = options.includeTotal !== false && !options.cursor;
|
|
let total = 0;
|
|
if (includeTotal) {
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM candle_predict_bets b WHERE ${where}`,
|
|
values.slice(0, keyset.nextParam - (decoded ? 2 : 0))
|
|
);
|
|
total = parseInt(countRows[0]?.c ?? '0', 10);
|
|
}
|
|
values.push(options.limit + 1);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT b.id, b.user_id, b.direction, b.stake_raw::text AS stake_raw, b.payout_raw::text AS payout_raw,
|
|
b.status, b.is_auto::text AS is_auto, b.prediction_mode, b.stake_account_kind, b.interval_minutes, b.created_at
|
|
FROM candle_predict_bets b WHERE ${where}${keyset.sql}
|
|
ORDER BY ${orderByCreatedAtId('b', sortDir)}
|
|
LIMIT $${i}`,
|
|
values
|
|
);
|
|
const hasMore = rows.length > options.limit;
|
|
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
|
const nextCursor =
|
|
hasMore && items.length > 0
|
|
? buildCursorFromRow(sortDir, items[items.length - 1] as { created_at: unknown; id: unknown })
|
|
: null;
|
|
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal };
|
|
}
|
|
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM candle_predict_bets b WHERE ${where}`,
|
|
values
|
|
);
|
|
const sort = safeSort(options.sortBy, options.sortDir, 'created_at');
|
|
const offset = options.offset ?? 0;
|
|
values.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT b.id, b.user_id, b.direction, b.stake_raw::text AS stake_raw, b.payout_raw::text AS payout_raw,
|
|
b.status, b.is_auto::text AS is_auto, b.prediction_mode, b.stake_account_kind, b.interval_minutes, b.created_at
|
|
FROM candle_predict_bets b WHERE ${where}
|
|
ORDER BY ${sort.replace('created_at', 'b.created_at').replace('stake_raw', 'b.stake_raw')}
|
|
LIMIT $${i++} OFFSET $${i}`,
|
|
values
|
|
);
|
|
return {
|
|
items: serializeDateRows(rows),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
};
|
|
}
|
|
|
|
async function listGeoReport(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
const columns = [
|
|
{ field: 'country', headerName: 'Pays', type: 'country' },
|
|
{ field: 'users', headerName: 'Users', type: 'number' },
|
|
{ field: 'deposits_raw', headerName: 'Dépôts (USDT)', type: 'money' },
|
|
{ field: 'withdrawals_raw', headerName: 'Retraits (USDT)', type: 'money' },
|
|
{ field: 'net_pnl_raw', headerName: 'Net P/L (USDT)', type: 'money' },
|
|
];
|
|
const dateFrom = options.from ?? '1970-01-01';
|
|
const dateTo = options.to ?? new Date().toISOString();
|
|
const values: unknown[] = [dateFrom, dateTo];
|
|
let searchSql = 'TRUE';
|
|
if (options.search?.trim()) {
|
|
searchSql = `country ILIKE $3`;
|
|
values.push(`%${options.search.trim()}%`);
|
|
}
|
|
const base = `
|
|
WITH dep AS (
|
|
SELECT u.country_of_residence AS country, SUM(t.amount)::bigint AS total
|
|
FROM transactions t JOIN users u ON u.id = t.user_id
|
|
WHERE t.type = 'deposit' AND t.status = 'completed' AND t.created_at BETWEEN $1 AND $2
|
|
GROUP BY u.country_of_residence
|
|
),
|
|
wdr AS (
|
|
SELECT u.country_of_residence AS country, SUM(t.amount)::bigint AS total
|
|
FROM transactions t JOIN users u ON u.id = t.user_id
|
|
WHERE t.type = 'withdrawal' AND t.status = 'completed' AND t.created_at BETWEEN $1 AND $2
|
|
GROUP BY u.country_of_residence
|
|
)
|
|
SELECT COALESCE(u.country_of_residence, 'XX') AS country,
|
|
COUNT(DISTINCT u.id)::int AS users,
|
|
COALESCE(MAX(dep.total), 0)::text AS deposits_raw,
|
|
COALESCE(MAX(wdr.total), 0)::text AS withdrawals_raw,
|
|
COALESCE(SUM(s.net_pnl_raw), 0)::text AS net_pnl_raw
|
|
FROM users u
|
|
LEFT JOIN user_admin_stats s ON s.user_id = u.id
|
|
LEFT JOIN dep ON dep.country = u.country_of_residence
|
|
LEFT JOIN wdr ON wdr.country = u.country_of_residence
|
|
GROUP BY COALESCE(u.country_of_residence, 'XX')
|
|
`;
|
|
const idValues: unknown[] = [...values];
|
|
const idParamIdx = idValues.length + 1;
|
|
const idClause = idsFilter('g.country', options.ids, idValues, idParamIdx, 'text');
|
|
const countRows = await query<{ c: string }[]>(
|
|
`SELECT COUNT(*)::text AS c FROM (${base}) g WHERE ${searchSql}${idClause.sql}`,
|
|
idValues
|
|
);
|
|
const sortField =
|
|
reportKey === 'geo-deposits'
|
|
? 'deposits_raw'
|
|
: reportKey === 'geo-withdrawals'
|
|
? 'withdrawals_raw'
|
|
: reportKey === 'geo-pnl'
|
|
? 'net_pnl_raw'
|
|
: 'users';
|
|
const sort = safeSort(options.sortBy ?? sortField, options.sortDir, sortField);
|
|
const limitIdx = idValues.length + 1;
|
|
const offsetIdx = idValues.length + 2;
|
|
const offset = options.offset ?? 0;
|
|
idValues.push(options.limit, offset);
|
|
const rows = await query<Record<string, unknown>[]>(
|
|
`SELECT g.country AS id, g.* FROM (${base}) g WHERE ${searchSql}${idClause.sql} ORDER BY ${sort}
|
|
LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
|
|
idValues
|
|
);
|
|
return {
|
|
items: rows.map(({ country, ...rest }) => ({
|
|
id: country,
|
|
country,
|
|
...rest,
|
|
})),
|
|
total: parseInt(countRows[0]?.c ?? '0', 10),
|
|
columns,
|
|
totalIsExact: true,
|
|
};
|
|
}
|
|
|
|
export async function exportReportRows(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
|
return runReport(reportKey, { ...options, limit: Math.min(options.limit, 10_000), offset: 0 });
|
|
}
|