games_app/backend/dist-test-faq/services/referralRegularizationService.js

382 lines
16 KiB
JavaScript

"use strict";
/**
* 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
*/
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.ReferralRegularizationError = void 0;
exports.listPendingRegularizationItems = listPendingRegularizationItems;
exports.getRegularizationSnapshot = getRegularizationSnapshot;
exports.applyRegularization = applyRegularization;
const connection_1 = require("../db/connection");
const referralRepository = __importStar(require("../repositories/referralRepository"));
const bonusPoolRepository = __importStar(require("../repositories/bonusPoolRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const crypto_1 = require("../utils/crypto");
const referralService_1 = require("./referralService");
const REGULARIZATION_ADVISORY_LOCK = 88442211;
class ReferralRegularizationError extends Error {
constructor(message, code = 'INVALID_SELECTION') {
super(message);
this.code = code;
this.name = 'ReferralRegularizationError';
}
}
exports.ReferralRegularizationError = ReferralRegularizationError;
function itemKey(betId, beneficiaryUserId, level) {
return `${betId}:${beneficiaryUserId}:${level}`;
}
async function loadUserLabels(userIds) {
const map = new Map();
if (userIds.length === 0)
return map;
const rows = await (0, connection_1.query)(`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, userId) {
let email = null;
if (row?.email_encrypted) {
try {
email = (0, crypto_1.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). */
async function listPendingRegularizationItems(options) {
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 (0, connection_1.query)(`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 (0, connection_1.query)(`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 = [];
const userIds = new Set();
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 = (0, referralService_1.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 };
}
async function getRegularizationSnapshot(options) {
const { settingsWalletTypeId, items } = await listPendingRegularizationItems(options);
const poolBalanceRaw = await bonusPoolRepository.getPoolBalance(settingsWalletTypeId);
const byBen = new Map();
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 = [];
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,
};
}
async function withRegularizationLock(fn) {
const client = await (0, connection_1.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();
}
}
async function applyRegularization(input) {
return withRegularizationLock(async () => {
const snapshot = await getRegularizationSnapshot();
const poolBefore = BigInt(snapshot.poolBalanceRaw);
let selectedBeneficiaries;
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 = [];
const itemsByBet = new Map();
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 (0, referralService_1.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 = {
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;
});
}
//# sourceMappingURL=referralRegularizationService.js.map