"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.parseSelectedIds = parseSelectedIds; exports.listReportCatalog = listReportCatalog; exports.queryReport = queryReport; exports.exportReport = exportReport; exports.resolveUserIdsForBulkAction = resolveUserIdsForBulkAction; exports.runReportBulkAction = runReportBulkAction; const definitions_1 = require("../reports/definitions"); const bulkActions_1 = require("../reports/bulkActions"); const reportsRepository = __importStar(require("../repositories/reportsRepository")); const adminService = __importStar(require("./adminService")); const adminUserListQuery_1 = require("../utils/adminUserListQuery"); const queryResilience_1 = require("../utils/queryResilience"); function parseSelectedIds(source) { 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, queryResilience_1.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, queryResilience_1.MAX_SELECTED_IDS) : undefined; } return undefined; } function listReportCatalog() { return { categories: Object.entries(definitions_1.REPORT_CATEGORY_LABELS).map(([id, label]) => ({ id, label, reports: definitions_1.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: (0, bulkActions_1.getBulkActionsForReport)(r), })), })), }; } async function queryUsersReport(def, query) { 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 = (0, queryResilience_1.clampReportPagination)(parseInt(String(query.limit ?? '50'), 10) || 50, parseInt(String(query.offset ?? '0'), 10) || 0); const opts = (0, adminUserListQuery_1.parseAdminUserListOptions)(merged, { limit: selectedIds?.length ? Math.min(selectedIds.length, queryResilience_1.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 = []; 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, }; } async function queryReport(reportKey, query) { const def = (0, definitions_1.getReportDefinition)(reportKey); if (!def) throw new Error('Report not found'); const metaWarnings = []; const pagination = (0, queryResilience_1.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: (0, bulkActions_1.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, queryResilience_1.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: (0, bulkActions_1.getBulkActionsForReport)(def), meta: metaWarnings.length ? { warnings: metaWarnings } : undefined, }; } async function exportReport(reportKey, query) { const selectedIds = parseSelectedIds(query); return queryReport(reportKey, { ...query, limit: selectedIds?.length ? Math.min(selectedIds.length, queryResilience_1.MAX_EXPORT_ROWS) : Math.min(parseInt(String(query.limit ?? '5000'), 10) || 5000, queryResilience_1.MAX_EXPORT_ROWS), offset: 0, ids: selectedIds, selectedIds, userIds: selectedIds, }); } async function resolveUserIdsForBulkAction(reportKey, rowIds) { const def = (0, definitions_1.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) { return def.category === 'users' || def.key === 'financial-wallet-balances'; } async function runReportBulkAction(reportKey, action, rowIds, options) { const def = (0, definitions_1.getReportDefinition)(reportKey); if (!def) throw new Error('Report not found'); if (!(0, bulkActions_1.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, queryResilience_1.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'); } } //# sourceMappingURL=reportsService.js.map