games_app/backend/src/services/referralRegularizationService.ts
2026-10-26 14:18:55 +02:00

505 lines
16 KiB
TypeScript

/**
* Admin regularization of missed prediction referral commissions
* (eligible settled bets with no payout row — typically after an empty bonus pool).
*
* Rules:
* - Unit of work = (betId, beneficiaryUserId, level)
* - Idempotent via unique payout constraint / ON CONFLICT
* - Batch: refuse entirely when allowPartial=false and totalDue > pool
* - Partial: FIFO by bet.created_at ASC, then level ASC; stop at first insufficient pool
* - Never reduce a commission amount to fit the pool
*/
import { query, getClient } from '../db/connection';
import * as referralRepository from '../repositories/referralRepository';
import * as bonusPoolRepository from '../repositories/bonusPoolRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { decrypt } from '../utils/crypto';
import {
calcCommission,
processPredictionReferralCommissions,
} from './referralService';
const REGULARIZATION_ADVISORY_LOCK = 88442211;
export class ReferralRegularizationError extends Error {
constructor(
message: string,
public readonly code:
| 'INSUFFICIENT_POOL'
| 'NOTHING_TO_DO'
| 'INVALID_SELECTION'
| 'LOCKED' = 'INVALID_SELECTION'
) {
super(message);
this.name = 'ReferralRegularizationError';
}
}
export type RegularizationItem = {
itemKey: string;
betId: string;
referredUserId: string;
referredDisplayName: string;
beneficiaryUserId: string;
level: number;
stakeRaw: string;
commissionPercent: number;
commissionAmountRaw: string;
betStatus: 'won' | 'lost';
betCreatedAt: string;
stakeAccountKind: string;
};
export type RegularizationBeneficiary = {
beneficiaryUserId: string;
displayName: string;
email: string | null;
pendingCount: number;
amountDueRaw: string;
oldestCreatedAt: string;
items: RegularizationItem[];
};
export type RegularizationSnapshot = {
walletTypeId: number;
poolBalanceRaw: string;
totalDueRaw: string;
shortfallRaw: string;
pendingItemCount: number;
beneficiaryCount: number;
beneficiaries: RegularizationBeneficiary[];
};
type EligibleBetRow = {
id: string;
user_id: string;
status: 'won' | 'lost';
stake_raw: string;
stake_account_kind: string | null;
wallet_type_id: number;
created_at: Date;
};
type UserLabelRow = {
id: string;
email_encrypted: string | null;
first_name: string | null;
last_name: string | null;
};
function itemKey(betId: string, beneficiaryUserId: string, level: number): string {
return `${betId}:${beneficiaryUserId}:${level}`;
}
async function loadUserLabels(userIds: string[]): Promise<Map<string, UserLabelRow>> {
const map = new Map<string, UserLabelRow>();
if (userIds.length === 0) return map;
const rows = await query<UserLabelRow[]>(
`SELECT u.id, u.email_encrypted, u.first_name, u.last_name
FROM users u
WHERE u.id = ANY($1::uuid[])`,
[userIds]
);
for (const r of rows) map.set(r.id, r);
return map;
}
function labelOf(row: UserLabelRow | undefined, userId: string): {
displayName: string;
email: string | null;
} {
let email: string | null = null;
if (row?.email_encrypted) {
try {
email = decrypt(row.email_encrypted);
} catch {
email = null;
}
}
return {
displayName: referralRepository.formatUserDisplayName(
row?.first_name ?? null,
row?.last_name ?? null,
userId
),
email,
};
}
/** Build flat list of unpaid prediction commission items (eligible only). */
export async function listPendingRegularizationItems(options?: {
search?: string;
}): Promise<{
settingsWalletTypeId: number;
items: RegularizationItem[];
}> {
const settings = await referralRepository.getSettings();
if (!settings.enabled || !settings.prediction_commissions_enabled) {
return { settingsWalletTypeId: settings.commission_wallet_type_id, items: [] };
}
const levels = (await referralRepository.listLevels()).filter((l) => l.is_active);
if (levels.length === 0) {
return { settingsWalletTypeId: settings.commission_wallet_type_id, items: [] };
}
const maxLevel = Math.max(...levels.map((l) => l.level_number));
const levelByNumber = new Map(levels.map((l) => [l.level_number, l]));
const bets = await query<EligibleBetRow[]>(
`SELECT b.id, b.user_id, b.status, b.stake_raw::text, b.stake_account_kind,
b.wallet_type_id, b.created_at
FROM candle_predict_bets b
JOIN users u ON u.id = b.user_id
WHERE b.status IN ('won', 'lost')
AND COALESCE(b.stake_account_kind, 'main') <> 'test'
AND b.stake_raw > 0
AND u.referred_by_user_id IS NOT NULL
AND b.wallet_type_id = $1
ORDER BY b.created_at ASC
LIMIT 5000`,
[settings.commission_wallet_type_id]
);
if (bets.length === 0) {
return { settingsWalletTypeId: settings.commission_wallet_type_id, items: [] };
}
const betIds = bets.map((b) => b.id);
const existing = await query<
Array<{ candle_predict_bet_id: string; beneficiary_user_id: string; level_number: number }>
>(
`SELECT candle_predict_bet_id, beneficiary_user_id, level_number
FROM referral_commission_payouts
WHERE commission_source = 'prediction'
AND candle_predict_bet_id = ANY($1::uuid[])`,
[betIds]
);
const paidKeys = new Set(
existing.map((e) => itemKey(e.candle_predict_bet_id, e.beneficiary_user_id, e.level_number))
);
const pending: RegularizationItem[] = [];
const userIds = new Set<string>();
for (const bet of bets) {
const chain = await referralRepository.getReferralChain(bet.user_id, maxLevel);
for (const { userId: beneficiaryId, level } of chain) {
const key = itemKey(bet.id, beneficiaryId, level);
if (paidKeys.has(key)) continue;
const levelConfig = levelByNumber.get(level);
if (!levelConfig) continue;
const percent = Number(levelConfig.commission_percent);
if (percent <= 0) continue;
const amount = calcCommission(BigInt(bet.stake_raw), percent);
if (amount <= 0n) continue;
pending.push({
itemKey: key,
betId: bet.id,
referredUserId: bet.user_id,
referredDisplayName: '',
beneficiaryUserId: beneficiaryId,
level,
stakeRaw: bet.stake_raw,
commissionPercent: percent,
commissionAmountRaw: amount.toString(),
betStatus: bet.status,
betCreatedAt: bet.created_at.toISOString(),
stakeAccountKind: bet.stake_account_kind ?? 'main',
});
userIds.add(beneficiaryId);
userIds.add(bet.user_id);
}
}
const labels = await loadUserLabels([...userIds]);
for (const item of pending) {
item.referredDisplayName = labelOf(labels.get(item.referredUserId), item.referredUserId).displayName;
}
let filtered = pending;
const search = options?.search?.trim().toLowerCase();
if (search) {
filtered = pending.filter((item) => {
const ben = labelOf(labels.get(item.beneficiaryUserId), item.beneficiaryUserId);
const hay = [
item.beneficiaryUserId,
item.referredUserId,
item.betId,
ben.displayName,
ben.email ?? '',
item.referredDisplayName,
]
.join(' ')
.toLowerCase();
return hay.includes(search);
});
}
// Attach display names via labels map when building beneficiaries later
return { settingsWalletTypeId: settings.commission_wallet_type_id, items: filtered };
}
export async function getRegularizationSnapshot(options?: {
search?: string;
}): Promise<RegularizationSnapshot> {
const { settingsWalletTypeId, items } = await listPendingRegularizationItems(options);
const poolBalanceRaw = await bonusPoolRepository.getPoolBalance(settingsWalletTypeId);
const byBen = new Map<string, RegularizationItem[]>();
for (const item of items) {
const list = byBen.get(item.beneficiaryUserId) ?? [];
list.push(item);
byBen.set(item.beneficiaryUserId, list);
}
const labels = await loadUserLabels([...byBen.keys()]);
let totalDue = 0n;
const beneficiaries: RegularizationBeneficiary[] = [];
for (const [beneficiaryUserId, benItems] of byBen) {
benItems.sort(
(a, b) =>
a.betCreatedAt.localeCompare(b.betCreatedAt) ||
a.level - b.level ||
a.betId.localeCompare(b.betId)
);
let amount = 0n;
for (const it of benItems) amount += BigInt(it.commissionAmountRaw);
totalDue += amount;
const { displayName, email } = labelOf(labels.get(beneficiaryUserId), beneficiaryUserId);
beneficiaries.push({
beneficiaryUserId,
displayName,
email,
pendingCount: benItems.length,
amountDueRaw: amount.toString(),
oldestCreatedAt: benItems[0]?.betCreatedAt ?? new Date(0).toISOString(),
items: benItems,
});
}
beneficiaries.sort(
(a, b) =>
a.oldestCreatedAt.localeCompare(b.oldestCreatedAt) ||
a.beneficiaryUserId.localeCompare(b.beneficiaryUserId)
);
const pool = BigInt(poolBalanceRaw);
const shortfall = totalDue > pool ? totalDue - pool : 0n;
return {
walletTypeId: settingsWalletTypeId,
poolBalanceRaw,
totalDueRaw: totalDue.toString(),
shortfallRaw: shortfall.toString(),
pendingItemCount: items.length,
beneficiaryCount: beneficiaries.length,
beneficiaries,
};
}
export type RegularizeMode = 'one' | 'selected' | 'all';
export type RegularizeApplyInput = {
mode: RegularizeMode;
adminUserId: string;
beneficiaryUserIds?: string[];
allowPartial: boolean;
};
export type RegularizeApplyResult = {
paidCount: number;
paidAmountRaw: string;
reviewQueued: number;
remainingCount: number;
remainingAmountRaw: string;
skippedInsufficientPool: number;
skippedOther: number;
poolBalanceBeforeRaw: string;
poolBalanceAfterRaw: string;
shortfallRaw: string;
stoppedForInsufficientPool: boolean;
refused: boolean;
message: string;
};
async function withRegularizationLock<T>(fn: () => Promise<T>): Promise<T> {
const client = await getClient();
try {
await client.query('SELECT pg_advisory_lock($1)', [REGULARIZATION_ADVISORY_LOCK]);
return await fn();
} finally {
await client.query('SELECT pg_advisory_unlock($1)', [REGULARIZATION_ADVISORY_LOCK]).catch(() => undefined);
client.release();
}
}
export async function applyRegularization(
input: RegularizeApplyInput
): Promise<RegularizeApplyResult> {
return withRegularizationLock(async () => {
const snapshot = await getRegularizationSnapshot();
const poolBefore = BigInt(snapshot.poolBalanceRaw);
let selectedBeneficiaries: RegularizationBeneficiary[];
if (input.mode === 'all') {
selectedBeneficiaries = snapshot.beneficiaries;
} else {
const ids = [...new Set(input.beneficiaryUserIds ?? [])];
if (ids.length === 0) {
throw new ReferralRegularizationError(
'beneficiaryUserIds required for mode one/selected',
'INVALID_SELECTION'
);
}
if (input.mode === 'one' && ids.length !== 1) {
throw new ReferralRegularizationError(
'mode one requires exactly one beneficiaryUserId',
'INVALID_SELECTION'
);
}
const idSet = new Set(ids);
selectedBeneficiaries = snapshot.beneficiaries.filter((b) => idSet.has(b.beneficiaryUserId));
if (selectedBeneficiaries.length === 0) {
throw new ReferralRegularizationError('No pending commissions for selection', 'NOTHING_TO_DO');
}
}
const selectedItems = selectedBeneficiaries
.flatMap((b) => b.items)
.sort(
(a, b) =>
a.betCreatedAt.localeCompare(b.betCreatedAt) ||
a.level - b.level ||
a.betId.localeCompare(b.betId)
);
if (selectedItems.length === 0) {
throw new ReferralRegularizationError('Nothing to regularize', 'NOTHING_TO_DO');
}
let selectedTotal = 0n;
for (const it of selectedItems) selectedTotal += BigInt(it.commissionAmountRaw);
if (!input.allowPartial && selectedTotal > poolBefore) {
const shortfall = selectedTotal - poolBefore;
await auditLogRepository.create({
userId: input.adminUserId,
action: 'referral_commission_regularization_refused',
resourceType: 'referral_regularization',
resourceId: null,
metadata: {
mode: input.mode,
allow_partial: false,
selected_item_count: selectedItems.length,
selected_total_raw: selectedTotal.toString(),
pool_balance_raw: poolBefore.toString(),
shortfall_raw: shortfall.toString(),
beneficiary_ids: selectedBeneficiaries.map((b) => b.beneficiaryUserId),
},
});
throw new ReferralRegularizationError(
`Insufficient bonus pool: need ${selectedTotal.toString()}, available ${poolBefore.toString()}, shortfall ${shortfall.toString()}`,
'INSUFFICIENT_POOL'
);
}
// Group items by bet while preserving FIFO order of first appearance
const betOrder: string[] = [];
const itemsByBet = new Map<string, RegularizationItem[]>();
for (const it of selectedItems) {
if (!itemsByBet.has(it.betId)) {
itemsByBet.set(it.betId, []);
betOrder.push(it.betId);
}
itemsByBet.get(it.betId)!.push(it);
}
let paidCount = 0;
let paidAmount = 0n;
let reviewQueued = 0;
let skippedInsufficientPool = 0;
let skippedOther = 0;
let stoppedForInsufficientPool = false;
for (const betId of betOrder) {
if (stoppedForInsufficientPool) break;
const betItems = itemsByBet.get(betId)!;
const first = betItems[0]!;
const beneficiaryFilter = [...new Set(betItems.map((i) => i.beneficiaryUserId))];
const result = await processPredictionReferralCommissions({
betId,
referredUserId: first.referredUserId,
stakeRaw: BigInt(first.stakeRaw),
stakeAccountKind:
first.stakeAccountKind === 'bonus'
? 'bonus'
: first.stakeAccountKind === 'test'
? 'test'
: 'main',
walletTypeId: snapshot.walletTypeId,
betOutcome: first.betStatus,
onlyBeneficiaryIds: beneficiaryFilter,
stopOnInsufficientPool: true,
});
paidCount += result.paid;
paidAmount += BigInt(result.paidAmountRaw);
reviewQueued += result.reviewQueued;
skippedInsufficientPool += result.skippedInsufficientPool;
skippedOther += result.skippedOther;
if (result.hitInsufficientPool) {
stoppedForInsufficientPool = true;
}
}
const afterSnap = await getRegularizationSnapshot();
const poolAfter = BigInt(afterSnap.poolBalanceRaw);
const remainingItems = afterSnap.beneficiaries
.filter((b) =>
input.mode === 'all'
? true
: selectedBeneficiaries.some((s) => s.beneficiaryUserId === b.beneficiaryUserId)
)
.flatMap((b) => b.items);
let remainingAmount = 0n;
for (const it of remainingItems) remainingAmount += BigInt(it.commissionAmountRaw);
const result: RegularizeApplyResult = {
paidCount,
paidAmountRaw: paidAmount.toString(),
reviewQueued,
remainingCount: remainingItems.length,
remainingAmountRaw: remainingAmount.toString(),
skippedInsufficientPool,
skippedOther,
poolBalanceBeforeRaw: poolBefore.toString(),
poolBalanceAfterRaw: poolAfter.toString(),
shortfallRaw: remainingAmount > poolAfter ? (remainingAmount - poolAfter).toString() : '0',
stoppedForInsufficientPool,
refused: false,
message: stoppedForInsufficientPool
? 'Partial regularization stopped: bonus pool insufficient for next commission'
: 'Regularization completed',
};
await auditLogRepository.create({
userId: input.adminUserId,
action: 'referral_commission_regularization',
resourceType: 'referral_regularization',
resourceId: null,
metadata: {
mode: input.mode,
allow_partial: input.allowPartial,
...result,
beneficiary_ids: selectedBeneficiaries.map((b) => b.beneficiaryUserId),
},
});
return result;
});
}