/** * Approved manual ledger credits (bonus / admin adjustment). * Sole authorized path for crediting user balances outside deposits, games, and transfers. */ import { getClient, beginAuthorizedTransaction } from '../db/connection'; import * as ledgerAdjustmentRepository from '../repositories/ledgerAdjustmentRepository'; import * as userRepository from '../repositories/userRepository'; import * as walletRepository from '../repositories/walletRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; import { AUTHORIZED_LEDGER_TYPES } from './securityService'; import { queueUserAdminStatsRefresh } from './userAdminStatsService'; import { encryptSensitive } from '../utils/crypto'; export class AdminCreditError extends Error { constructor(message: string) { super(message); this.name = 'AdminCreditError'; } } export type GrantLedgerCreditResult = { adjustmentId: string; transactionId: string; accountKind: 'main' | 'bonus'; availableBalanceRaw: string; }; export async function grantLedgerCredit(input: { userId: string; walletTypeId: number; adjustmentType: 'bonus' | 'admin_adjustment'; amountRaw: string; reason: string; approvedBy: string; }): Promise { if (!AUTHORIZED_LEDGER_TYPES.has(input.adjustmentType)) { throw new AdminCreditError(`Invalid adjustment type: ${input.adjustmentType}`); } const reason = input.reason?.trim(); if (!reason || reason.length < 3) { throw new AdminCreditError('A reason of at least 3 characters is required'); } let amount: bigint; try { amount = BigInt(input.amountRaw); } catch { throw new AdminCreditError('Invalid amount'); } if (amount <= 0n) { throw new AdminCreditError('Amount must be positive'); } const user = await userRepository.findById(input.userId); if (!user) throw new AdminCreditError('User not found'); const walletTypes = await walletRepository.getWalletTypes(); const walletType = walletTypes.find((w) => w.id === input.walletTypeId); if (!walletType) throw new AdminCreditError('Wallet type not found'); const accountKind: 'main' | 'bonus' = input.adjustmentType === 'bonus' ? 'bonus' : 'main'; const client = await getClient(); try { await beginAuthorizedTransaction(client); await client.query( `INSERT INTO ledger_accounts (user_id, wallet_type_id, account_kind) VALUES ($1, $2, $3) ON CONFLICT (user_id, wallet_type_id, account_kind) DO NOTHING`, [input.userId, input.walletTypeId, accountKind] ); const accountResult = await client.query<{ id: string; available_balance: string; }>( `SELECT id, available_balance::text FROM ledger_accounts WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = $3 FOR UPDATE`, [input.userId, input.walletTypeId, accountKind] ); const account = accountResult.rows[0]; if (!account) { throw new AdminCreditError('Ledger account not found'); } const adjustmentResult = await client.query<{ id: string }>( `INSERT INTO ledger_adjustments (user_id, wallet_type_id, adjustment_type, amount, reason_encrypted, approved_by) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id`, [ input.userId, input.walletTypeId, input.adjustmentType, amount.toString(), encryptSensitive(reason), input.approvedBy, ] ); const adjustmentId = adjustmentResult.rows[0]?.id; if (!adjustmentId) throw new AdminCreditError('Failed to record adjustment'); const txResult = await client.query<{ id: string }>( `INSERT INTO transactions (user_id, wallet_type_id, type, amount, status, metadata) VALUES ($1, $2, $3, $4, 'completed', $5) RETURNING id`, [ input.userId, input.walletTypeId, input.adjustmentType, amount.toString(), JSON.stringify({ adjustment_id: adjustmentId, approved_by: input.approvedBy, reason_summary: reason.slice(0, 120), }), ] ); const transactionId = txResult.rows[0]?.id; if (!transactionId) throw new AdminCreditError('Failed to record transaction'); await client.query('UPDATE ledger_adjustments SET transaction_id = $1 WHERE id = $2', [ transactionId, adjustmentId, ]); const newBalance = BigInt(account.available_balance) + amount; await client.query( `UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2`, [newBalance.toString(), account.id] ); await client.query( `INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id) VALUES ($1, $2, $3, $4, 'ledger_adjustment', $5)`, [ account.id, input.adjustmentType, amount.toString(), newBalance.toString(), adjustmentId, ] ); await client.query('COMMIT'); await auditLogRepository.create({ userId: input.approvedBy, action: 'admin_ledger_credit', resourceType: 'ledger_adjustment', resourceId: adjustmentId, metadata: { target_user_id: input.userId, wallet_type_id: input.walletTypeId, account_kind: accountKind, adjustment_type: input.adjustmentType, amount_raw: amount.toString(), transaction_id: transactionId, available_balance_raw: newBalance.toString(), }, }); queueUserAdminStatsRefresh(input.userId); return { adjustmentId, transactionId, accountKind, availableBalanceRaw: newBalance.toString(), }; } catch (e) { await client.query('ROLLBACK'); if (e instanceof AdminCreditError) throw e; const msg = e instanceof Error ? e.message : 'Credit failed'; throw new AdminCreditError(msg); } finally { client.release(); } } export async function listLedgerCredits(opts: { userId?: string; limit?: number; offset?: number; }) { const result = await ledgerAdjustmentRepository.listAdjustments(opts); return { items: result.items.map((a) => ({ id: a.id, userId: a.user_id, walletTypeId: a.wallet_type_id, adjustmentType: a.adjustment_type, amount: a.amount, approvedBy: a.approved_by, transactionId: a.transaction_id, createdAt: a.created_at, })), total: result.total, }; }