74 lines
2.5 KiB
TypeScript
74 lines
2.5 KiB
TypeScript
/**
|
|
* User bonus account operations: balances and transfer to main when allowed.
|
|
*/
|
|
|
|
import * as ledgerRepository from '../repositories/ledgerRepository';
|
|
import * as referralRepository from '../repositories/referralRepository';
|
|
import * as walletRepository from '../repositories/walletRepository';
|
|
import * as auditLogRepository from '../repositories/auditLogRepository';
|
|
import { randomUUID } from 'crypto';
|
|
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
|
|
|
|
export class BonusError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = 'BonusError';
|
|
}
|
|
}
|
|
|
|
export async function getUserBonusBalances(
|
|
userId: string
|
|
): Promise<Array<{ walletTypeId: number; walletCode: string; available: string }>> {
|
|
const types = await walletRepository.getWalletTypes();
|
|
const result: Array<{ walletTypeId: number; walletCode: string; available: string }> = [];
|
|
for (const wt of types) {
|
|
const account = await ledgerRepository.getAccount(userId, wt.id, 'bonus');
|
|
result.push({
|
|
walletTypeId: wt.id,
|
|
walletCode: wt.code,
|
|
available: account?.available_balance ?? '0',
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export async function transferBonusToMain(input: {
|
|
userId: string;
|
|
walletTypeId: number;
|
|
amountRaw: string;
|
|
}): Promise<void> {
|
|
const settings = await referralRepository.getSettings();
|
|
if (!settings.bonus_withdrawable) {
|
|
throw new BonusError('Bonus balance cannot be transferred to main account (platform policy)');
|
|
}
|
|
|
|
let amount: bigint;
|
|
try {
|
|
amount = BigInt(input.amountRaw);
|
|
} catch {
|
|
throw new BonusError('Invalid amount');
|
|
}
|
|
if (amount <= 0n) throw new BonusError('Amount must be positive');
|
|
|
|
const bonusAccount = await ledgerRepository.getOrCreateBonusAccount(input.userId, input.walletTypeId);
|
|
const mainAccount = await ledgerRepository.getOrCreateAccount(input.userId, input.walletTypeId, 'main');
|
|
const refId = randomUUID();
|
|
|
|
await ledgerRepository.debit(bonusAccount.id, amount, 'bonus_to_main', 'bonus_transfer', refId);
|
|
await ledgerRepository.credit(mainAccount.id, amount, 'bonus_to_main', 'bonus_transfer', refId);
|
|
|
|
await auditLogRepository.create({
|
|
userId: input.userId,
|
|
action: 'bonus_transferred_to_main',
|
|
resourceType: 'bonus_transfer',
|
|
resourceId: refId,
|
|
metadata: { wallet_type_id: input.walletTypeId, amount: amount.toString() },
|
|
});
|
|
queueUserAdminStatsRefresh(input.userId);
|
|
}
|
|
|
|
export async function isBonusWithdrawable(): Promise<boolean> {
|
|
const settings = await referralRepository.getSettings();
|
|
return settings.bonus_withdrawable;
|
|
}
|