import { REPORT_CATEGORY_LABELS, REPORT_DEFINITIONS, getReportDefinition, } from '../reports/definitions'; import { getBulkActionsForReport, isBulkActionAllowed, type ReportBulkAction } from '../reports/bulkActions'; import * as reportsRepository from '../repositories/reportsRepository'; import type { ReportSummary } from '../repositories/reportsRepository'; import * as adminService from './adminService'; import { parseAdminUserListOptions } from '../utils/adminUserListQuery'; import { MAX_EXPORT_ROWS, MAX_SELECTED_IDS, clampReportPagination, } from '../utils/queryResilience'; export function parseSelectedIds(source: Record): string[] | undefined { const raw = source.ids ?? source.selectedIds ?? source.userIds; if (Array.isArray(raw)) { const ids = raw.map(String).map((s) => s.trim()).filter(Boolean); return ids.length ? ids.slice(0, MAX_SELECTED_IDS) : undefined; } if (typeof raw === 'string' && raw.trim()) { const ids = raw.split(',').map((s) => s.trim()).filter(Boolean); return ids.length ? ids.slice(0, MAX_SELECTED_IDS) : undefined; } return undefined; } export function listReportCatalog() { return { categories: Object.entries(REPORT_CATEGORY_LABELS).map(([id, label]) => ({ id, label, reports: REPORT_DEFINITIONS.filter((r) => r.category === id).map((r) => ({ key: r.key, title: r.title, description: r.description, category: r.category, source: r.source, bulkActions: getBulkActionsForReport(r), })), })), }; } async function queryUsersReport( def: NonNullable>, query: Record ) { const merged = { ...query, ...(def.userQuery ?? {}) }; for (const [k, v] of Object.entries(def.userQuery ?? {})) { if (merged[k] === undefined) merged[k] = v; } const selectedIds = parseSelectedIds(query); const cursor = typeof query.cursor === 'string' && query.cursor.trim() ? query.cursor.trim() : undefined; const pagination = clampReportPagination( parseInt(String(query.limit ?? '50'), 10) || 50, parseInt(String(query.offset ?? '0'), 10) || 0 ); const opts = parseAdminUserListOptions(merged, { limit: selectedIds?.length ? Math.min(selectedIds.length, MAX_EXPORT_ROWS) : pagination.limit, offset: selectedIds?.length ? 0 : cursor ? undefined : pagination.offset, cursor, includeTotal: query.includeTotal !== false && !cursor && pagination.offset === 0, userIds: selectedIds, }); const metaWarnings: string[] = []; if (def.key === 'users-new-period' && (!opts.createdFrom || !opts.createdTo)) { metaWarnings.push( 'Sélectionnez une période (Du/Au) pour afficher les inscriptions de la période.' ); const emptyColumns = [ { field: 'id', headerName: 'ID', type: 'string' }, { field: 'email', headerName: 'Email', type: 'string' }, { field: 'role_name', headerName: 'Role', type: 'string' }, { field: 'country_of_residence', headerName: 'Pays', type: 'country' }, { field: 'email_verified', headerName: 'Email verified', type: 'string' }, { field: 'totp_enabled', headerName: '2FA', type: 'string' }, { field: 'main_balance_raw', headerName: 'Main (USDT)', type: 'money' }, { field: 'bonus_balance_raw', headerName: 'Bonus (USDT)', type: 'money' }, { field: 'prediction_count', headerName: 'Predictions', type: 'number' }, { field: 'net_pnl_raw', headerName: 'Net P/L (USDT)', type: 'money' }, { field: 'created_at', headerName: 'Registered', type: 'date' }, { field: 'last_login_at', headerName: 'Last login', type: 'date' }, ]; return { items: [], total: 0, columns: emptyColumns, nextCursor: null, hasMore: false, totalIsExact: true, metaWarnings, }; } const result = await adminService.listUsers(opts); const baseColumns = [ { field: 'id', headerName: 'ID', type: 'string' }, { field: 'email', headerName: 'Email', type: 'string' }, { field: 'role_name', headerName: 'Role', type: 'string' }, { field: 'country_of_residence', headerName: 'Pays', type: 'country' }, { field: 'email_verified', headerName: 'Email verified', type: 'string' }, { field: 'totp_enabled', headerName: '2FA', type: 'string' }, { field: 'main_balance_raw', headerName: 'Main (USDT)', type: 'money' }, { field: 'bonus_balance_raw', headerName: 'Bonus (USDT)', type: 'money' }, { field: 'prediction_count', headerName: 'Predictions', type: 'number' }, { field: 'net_pnl_raw', headerName: 'Net P/L (USDT)', type: 'money' }, { field: 'created_at', headerName: 'Registered', type: 'date' }, { field: 'last_login_at', headerName: 'Last login', type: 'date' }, ]; const staffColumns = [ { field: 'id', headerName: 'ID', type: 'string' }, { field: 'first_name', headerName: 'Prénom', type: 'string' }, { field: 'last_name', headerName: 'Nom', type: 'string' }, { field: 'email', headerName: 'Email', type: 'string' }, { field: 'role_name', headerName: 'Rôle', type: 'string' }, { field: 'account_status', headerName: 'Statut compte', type: 'string' }, { field: 'is_enabled', headerName: 'Activé', type: 'string' }, { field: 'email_verified', headerName: 'Email verified', type: 'string' }, { field: 'totp_enabled', headerName: '2FA', type: 'string' }, { field: 'last_login_at', headerName: 'Dernière connexion', type: 'date' }, { field: 'last_activity_at', headerName: 'Dernière activité', type: 'date' }, { field: 'created_at', headerName: 'Inscription', type: 'date' }, ]; const columns = def.key === 'users-staff' ? staffColumns : baseColumns; return { items: result.users.map((u) => ({ ...u, created_at: u.created_at instanceof Date ? u.created_at.toISOString() : u.created_at, last_login_at: u.last_login_at instanceof Date ? u.last_login_at.toISOString() : u.last_login_at, last_activity_at: u.last_activity_at instanceof Date ? u.last_activity_at.toISOString() : u.last_activity_at, email_verified: String(u.email_verified), totp_enabled: String(u.totp_enabled), is_enabled: String(u.is_enabled), account_status: u.account_status, })), total: result.total ?? result.users.length, columns, nextCursor: result.nextCursor, hasMore: result.hasMore, totalIsExact: result.totalIsExact, }; } export async function queryReport( reportKey: string, query: Record ): Promise<{ items: Record[]; total: number; columns: { field: string; headerName: string; type?: string }[]; definition: ReturnType; bulkActions: ReportBulkAction[]; meta?: { warnings: string[] }; summary?: ReportSummary; nextCursor?: string | null; hasMore?: boolean; totalIsExact?: boolean; }> { const def = getReportDefinition(reportKey); if (!def) throw new Error('Report not found'); const metaWarnings: string[] = []; const pagination = clampReportPagination( parseInt(String(query.limit ?? '50'), 10) || 50, parseInt(String(query.offset ?? '0'), 10) || 0 ); metaWarnings.push(...pagination.warnings); if (def.source === 'users-api') { const page = await queryUsersReport(def, query); const warnings = [...metaWarnings, ...(page.metaWarnings ?? [])]; const { metaWarnings: _drop, ...rest } = page; return { ...rest, definition: def, bulkActions: getBulkActionsForReport(def), meta: warnings.length ? { warnings } : undefined, }; } const selectedIds = parseSelectedIds(query); const cursor = typeof query.cursor === 'string' && query.cursor.trim() ? query.cursor.trim() : undefined; const includeTotal = query.includeTotal !== false && !cursor && pagination.offset === 0; const page = await reportsRepository.runReport(reportKey, { search: typeof query.search === 'string' ? query.search : undefined, from: typeof query.from === 'string' ? query.from : undefined, to: typeof query.to === 'string' ? query.to : undefined, sortBy: typeof query.sortBy === 'string' ? query.sortBy : def.defaultSortField, sortDir: query.sortDir === 'asc' || query.sortDir === 'desc' ? query.sortDir : def.defaultSortDir, limit: selectedIds?.length ? Math.min(selectedIds.length, MAX_EXPORT_ROWS) : pagination.limit, offset: selectedIds?.length ? 0 : cursor ? undefined : pagination.offset, cursor, includeTotal, preset: def.userQuery, ids: selectedIds, }); return { ...page, definition: def, bulkActions: getBulkActionsForReport(def), meta: metaWarnings.length ? { warnings: metaWarnings } : undefined, }; } export async function exportReport(reportKey: string, query: Record) { const selectedIds = parseSelectedIds(query); return queryReport(reportKey, { ...query, limit: selectedIds?.length ? Math.min(selectedIds.length, MAX_EXPORT_ROWS) : Math.min(parseInt(String(query.limit ?? '5000'), 10) || 5000, MAX_EXPORT_ROWS), offset: 0, ids: selectedIds, selectedIds, userIds: selectedIds, }); } export async function resolveUserIdsForBulkAction( reportKey: string, rowIds: string[] ): Promise { const def = getReportDefinition(reportKey); if (!def) throw new Error('Report not found'); if (rowIds.length === 0) throw new Error('No rows selected'); if (def.category === 'users' || def.key === 'financial-wallet-balances') { return [...new Set(rowIds)]; } const data = await queryReport(reportKey, { ids: rowIds, limit: rowIds.length, offset: 0, }); const userIds = new Set(); for (const row of data.items) { const uid = row.user_id ?? row.id; if (uid != null && String(uid).trim()) userIds.add(String(uid)); } if (userIds.size === 0) { throw new Error('No user accounts linked to the selected rows'); } return [...userIds]; } function isDirectUserReport(def: NonNullable>): boolean { return def.category === 'users' || def.key === 'financial-wallet-balances'; } export async function runReportBulkAction( reportKey: string, action: ReportBulkAction, rowIds: string[], options?: { reason?: string } ) { const def = getReportDefinition(reportKey); if (!def) throw new Error('Report not found'); if (!isBulkActionAllowed(def, action)) { throw new Error(`Action "${action}" is not allowed for this report`); } if (action === 'export-selection') { throw new Error('Use the export endpoint for export-selection'); } const uniqueIds = [...new Set(rowIds.filter(Boolean))].slice(0, MAX_SELECTED_IDS); if (uniqueIds.length === 0) throw new Error('No rows selected'); if (action === 'enable' || action === 'disable') { if (def.category !== 'users') { throw new Error('Enable/disable is only available on user reports'); } return adminService.batchUpdateUserAccountFlags(uniqueIds, { isEnabled: action === 'enable', }); } let userIds = uniqueIds; if (action === 'suspend-users') { userIds = await resolveUserIdsForBulkAction(reportKey, uniqueIds); } else if (!isDirectUserReport(def)) { throw new Error('This action is not supported for this report'); } switch (action) { case 'suspend': case 'suspend-users': return adminService.batchUpdateUserSecurity(userIds, { withdrawalsSuspended: true, underSurveillance: true, reason: options?.reason, }); case 'reactivate': return adminService.batchUpdateUserSecurity(userIds, { reactivateWithdrawals: true }); case 'surveillance-on': return adminService.batchUpdateUserSecurity(userIds, { underSurveillance: true, reason: options?.reason, }); case 'surveillance-off': return adminService.batchUpdateUserSecurity(userIds, { underSurveillance: false }); default: throw new Error('Unsupported action'); } }