"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.runReport = runReport; exports.exportReportRows = exportReportRows; const connection_1 = require("../db/connection"); const definitions_1 = require("../reports/definitions"); const reportPeriodBounds_1 = require("../utils/reportPeriodBounds"); const reportListCursor_1 = require("../utils/reportListCursor"); 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, dir, fallback) { const col = field && SORT_WHITELIST.has(field) ? field : fallback; const direction = dir === 'asc' ? 'ASC' : 'DESC'; return `${col} ${direction}`; } function dateClause(alias, from, to, startIdx = 1) { const parts = []; const values = []; 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, ids, values, paramIdx, cast = 'uuid') { 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) { return rows.map((r) => ({ ...r, created_at: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at, })); } function useKeysetPagination(reportKey, options) { if (options.ids?.length) return false; const sortBy = options.sortBy && SORT_WHITELIST.has(options.sortBy) ? options.sortBy : 'created_at'; if (!(0, reportListCursor_1.reportSupportsCursor)(reportKey, sortBy)) return false; return Boolean(options.cursor) || (options.offset ?? 0) === 0; } async function runReport(reportKey, options) { const def = (0, definitions_1.getReportDefinition)(reportKey); if (!def || def.source !== 'reports-api') { throw new Error('Unknown report'); } const normalized = (0, reportPeriodBounds_1.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-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) { return parseInt(v ?? '0', 10) || 0; } async function transactionSummary(where, filterValues) { const rows = await (0, connection_1.query)(`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, reportKey, options) { 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 = [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 ? (0, reportListCursor_1.decodeReportCursor)(options.cursor) : null; const keyset = (0, reportListCursor_1.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 (0, connection_1.query)(`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 (0, connection_1.query)(`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 ${(0, reportListCursor_1.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 ? (0, reportListCursor_1.buildCursorFromRow)(sortDir, items[items.length - 1]) : null; return { items, total, columns, nextCursor, hasMore, totalIsExact, summary }; } const sort = safeSort(options.sortBy, options.sortDir, 'created_at'); const countRows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS c FROM transactions t WHERE ${where}`, values); const offset = options.offset ?? 0; values.push(options.limit, offset); const rows = await (0, connection_1.query)(`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, options) { 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 = ['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 (0, connection_1.query)(`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 (0, connection_1.query)(`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 listBonuses(reportKey, options) { 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 ? (0, reportListCursor_1.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 (0, connection_1.query)(`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 (0, connection_1.query)(`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 ? (0, reportListCursor_1.buildCursorFromRow)(sortDir, items[items.length - 1]) : null; return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary }; } const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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, filterSql, filterValues) { const rows = await (0, connection_1.query)(`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, options) { 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 ? (0, reportListCursor_1.decodeReportCursor)(options.cursor) : null; const keyset = (0, reportListCursor_1.buildCreatedAtIdKeyset)('la', sortDir, decoded, values, i); i = keyset.nextParam; const includeTotal = options.includeTotal !== false && !options.cursor; let total = 0; if (includeTotal) { const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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 ${(0, reportListCursor_1.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 ? (0, reportListCursor_1.buildCursorFromRow)(sortDir, items[items.length - 1]) : null; return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary }; } const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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, filterValues) { const rows = await (0, connection_1.query)(`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) { 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 = []; 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 (0, connection_1.query)(`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 (0, connection_1.query)(`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) { 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, options) { 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 (0, connection_1.query)(`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 = { totalCount: num(sr?.total_count), uniqueUsers: num(sr?.unique_users), totalAmountRaw: num(sr?.total_stake), }; const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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, options) { 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 ? (0, reportListCursor_1.decodeReportCursor)(options.cursor) : null; const keyset = (0, reportListCursor_1.buildCreatedAtIdKeyset)('b', sortDir, decoded, values, i); i = keyset.nextParam; const includeTotal = options.includeTotal !== false && !options.cursor; let total = 0; if (includeTotal) { const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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 ${(0, reportListCursor_1.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 ? (0, reportListCursor_1.buildCursorFromRow)(sortDir, items[items.length - 1]) : null; return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal }; } const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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, options) { 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 = [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 = [...values]; const idParamIdx = idValues.length + 1; const idClause = idsFilter('g.country', options.ids, idValues, idParamIdx, 'text'); const countRows = await (0, connection_1.query)(`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 (0, connection_1.query)(`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, }; } async function exportReportRows(reportKey, options) { return runReport(reportKey, { ...options, limit: Math.min(options.limit, 10000), offset: 0 }); } //# sourceMappingURL=reportsRepository.js.map