Starting to resolve the issue on prediction4
This commit is contained in:
parent
844d1d62d5
commit
5469432bd6
@ -16,5 +16,7 @@ export declare function approveReferralCommission(req: AuthRequest, res: Respons
|
||||
export declare function rejectReferralCommission(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getReferralFraudDashboard(_req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function clawbackReferralCommission(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getReferralRegularization(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function applyReferralRegularization(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function exportReferralClawbacksCsv(req: AuthRequest, res: Response): Promise<void>;
|
||||
//# sourceMappingURL=referralController.d.ts.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"referralController.d.ts","sourceRoot":"","sources":["../../src/controllers/referralController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAOjD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOtF;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAO3F;AAED,wBAAsB,wBAAwB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAY7F;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAQrF;AAED,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBxF;AAED,wBAAsB,sBAAsB,CAAC,IAAI,EAAE,WAAW,E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AAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOtF;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BlF;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAS3F;AAED,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAa9F;AAED,wBAAsB,wBAAwB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAiB7F;AAED,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAO/F;AAED,wBAAsB,0BAA0B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAiB/F;AAED,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ9F;AAED,wBAAsB,2BAA2B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA+BhG;AAED,wBAAsB,0BAA0B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwB/F"}
|
||||
41
backend/dist/controllers/referralController.js
vendored
41
backend/dist/controllers/referralController.js
vendored
@ -49,11 +49,14 @@ exports.approveReferralCommission = approveReferralCommission;
|
||||
exports.rejectReferralCommission = rejectReferralCommission;
|
||||
exports.getReferralFraudDashboard = getReferralFraudDashboard;
|
||||
exports.clawbackReferralCommission = clawbackReferralCommission;
|
||||
exports.getReferralRegularization = getReferralRegularization;
|
||||
exports.applyReferralRegularization = applyReferralRegularization;
|
||||
exports.exportReferralClawbacksCsv = exportReferralClawbacksCsv;
|
||||
const referralService = __importStar(require("../services/referralService"));
|
||||
const bonusService = __importStar(require("../services/bonusService"));
|
||||
const referralRepository = __importStar(require("../repositories/referralRepository"));
|
||||
const referralExportService_1 = require("../services/referralExportService");
|
||||
const referralRegularizationService_1 = require("../services/referralRegularizationService");
|
||||
async function getMyReferralInfo(req, res) {
|
||||
try {
|
||||
const info = await referralService.getUserReferralInfo(req.user.userId);
|
||||
@ -294,6 +297,44 @@ async function clawbackReferralCommission(req, res) {
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Clawback failed' });
|
||||
}
|
||||
}
|
||||
async function getReferralRegularization(req, res) {
|
||||
try {
|
||||
const search = req.query.search ? String(req.query.search) : undefined;
|
||||
const snapshot = await (0, referralRegularizationService_1.getRegularizationSnapshot)({ search });
|
||||
res.json(snapshot);
|
||||
}
|
||||
catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' });
|
||||
}
|
||||
}
|
||||
async function applyReferralRegularization(req, res) {
|
||||
try {
|
||||
const body = req.body;
|
||||
if (!body.mode) {
|
||||
res.status(400).json({ error: 'mode is required' });
|
||||
return;
|
||||
}
|
||||
const result = await (0, referralRegularizationService_1.applyRegularization)({
|
||||
mode: body.mode,
|
||||
adminUserId: req.user.userId,
|
||||
beneficiaryUserIds: body.beneficiaryUserIds,
|
||||
allowPartial: Boolean(body.allowPartial),
|
||||
});
|
||||
res.json(result);
|
||||
}
|
||||
catch (e) {
|
||||
if (e instanceof referralRegularizationService_1.ReferralRegularizationError) {
|
||||
const status = e.code === 'INSUFFICIENT_POOL'
|
||||
? 409
|
||||
: e.code === 'NOTHING_TO_DO'
|
||||
? 404
|
||||
: 400;
|
||||
res.status(status).json({ error: e.message, code: e.code });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Regularization failed' });
|
||||
}
|
||||
}
|
||||
async function exportReferralClawbacksCsv(req, res) {
|
||||
try {
|
||||
const fromRaw = req.query.from ? String(req.query.from) : undefined;
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/domain/candle-predict/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,4CAA4C,CAAC;AACnE,OAAO,KAAK,gBAAgB,MAAM,qCAAqC,CAAC;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AA4BvE,OAAO,EAOL,KAAK,4BAA4B,EAClC,MAAM,2CAA2C,CAAC;AAsLnD,iBAAS,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;IA2B/C,8EAA8E;;;;;;;;EASjF;AAED,KAAK,eAAe,GAAG,IAAI,CACzB,UAAU,CAAC,OAAO,SAAS,CAAC,EAC1B,gBAAgB,GAChB,gBAAgB,GAChB,qBAAqB,GACrB,wBAAwB,GACxB,wBAAwB,GACxB,wBAAwB,GACxB,oBAAoB,GACpB,8BAA8B,CACjC,CAAC;AAiBF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,eAAe,EAAE,MAAM,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;IAClB,uBAAuB,EAAE,MAAM,CAAC;IAChC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,sBAAsB,EAAE,MAAM,CAAC;IAC/B,sBAAsB,EAAE,OAAO,CAAC;IAChC,sBAAsB,EAAE,OAAO,CAAC;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,MAAM,CAAC;IAC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backend/dist/domain/candle-predict/index.js
vendored
@ -1240,6 +1240,14 @@ async function finalizeIntervalCandleAtMaturity(round, interval, outcome, shortP
|
||||
});
|
||||
const nowMs = Date.now();
|
||||
const closeMs = openMs + interval.intervalMinutes * 60 * 1000;
|
||||
// Publish real time-to-next-betting so clients do not stick at 0s until refresh.
|
||||
const timingNext = (0, gameTimingService_1.getActiveRoundTiming)(nowMs, interval.intervalMinutes, interval.predictionWindowSeconds);
|
||||
const secondsToBettingEnd = timingNext.phase === 'betting'
|
||||
? Math.max(0, Math.ceil((timingNext.openMs - nowMs) / 1000))
|
||||
: 0;
|
||||
const secondsToBettingStart = timingNext.phase === 'betting'
|
||||
? 0
|
||||
: Math.max(0, Math.ceil((timingNext.nextBettingStartMs - nowMs) / 1000));
|
||||
const settledDto = {
|
||||
id: round.id,
|
||||
candleOpenMs: openMs,
|
||||
@ -1253,9 +1261,9 @@ async function finalizeIntervalCandleAtMaturity(round, interval, outcome, shortP
|
||||
closePrice: candle.close,
|
||||
settledAt: new Date().toISOString(),
|
||||
serverNowMs: nowMs,
|
||||
secondsToBettingEnd: 0,
|
||||
secondsToBettingStart: 0,
|
||||
secondsToClose: 0,
|
||||
secondsToBettingEnd,
|
||||
secondsToBettingStart,
|
||||
secondsToClose: Math.max(0, Math.ceil((closeMs - nowMs) / 1000)),
|
||||
};
|
||||
// Fire-and-forget Redis publish — must never block or kill the engine loop.
|
||||
const PUBLISH_TIMEOUT_MS = 5000;
|
||||
@ -1638,15 +1646,22 @@ async function executePlaceBetInternal(userId, input) {
|
||||
});
|
||||
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
|
||||
const mapped = mapBet(bet);
|
||||
// Redis fan-out must not fail the HTTP bet after ledger/DB commit succeeded.
|
||||
// A Redis replica READONLY error previously surfaced as a false "DB" failure.
|
||||
if (config_1.config.redis.enabled) {
|
||||
const betVersion = await (0, stateVersions_1.bumpUserBetVersionSafe)(userId, interval.intervalMinutes);
|
||||
await (0, pubsub_2.publishUserEvent)(userId, {
|
||||
type: 'bet.accepted',
|
||||
payload: {
|
||||
bet: mapped,
|
||||
...(betVersion != null ? { versions: { bet: betVersion } } : {}),
|
||||
},
|
||||
});
|
||||
try {
|
||||
const betVersion = await (0, stateVersions_1.bumpUserBetVersionSafe)(userId, interval.intervalMinutes);
|
||||
await (0, pubsub_2.publishUserEvent)(userId, {
|
||||
type: 'bet.accepted',
|
||||
payload: {
|
||||
bet: mapped,
|
||||
...(betVersion != null ? { versions: { bet: betVersion } } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
console.error('[candle-predict] post-bet Redis publish failed (bet already committed):', e instanceof Error ? e.message : e);
|
||||
}
|
||||
}
|
||||
return mapped;
|
||||
}
|
||||
@ -1707,9 +1722,14 @@ async function placeBet(userId, direction, stakeDisplay, intervalMinutes, stakeA
|
||||
stakeAccountKind: parseStakeAccountKind(stakeAccountKind),
|
||||
});
|
||||
if (config_1.config.redis.enabled) {
|
||||
const timingAfter = (0, gameTimingService_1.getActiveRoundTiming)(Date.now(), interval.intervalMinutes, interval.predictionWindowSeconds);
|
||||
if (timingAfter.phase === 'betting') {
|
||||
await publishRoundSnapshot(interval.intervalMinutes, timingAfter.openMs);
|
||||
try {
|
||||
const timingAfter = (0, gameTimingService_1.getActiveRoundTiming)(Date.now(), interval.intervalMinutes, interval.predictionWindowSeconds);
|
||||
if (timingAfter.phase === 'betting') {
|
||||
await publishRoundSnapshot(interval.intervalMinutes, timingAfter.openMs);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error('[candle-predict] post-bet round snapshot failed (bet already committed):', e instanceof Error ? e.message : e);
|
||||
}
|
||||
}
|
||||
return { status: 'accepted', bet };
|
||||
|
||||
File diff suppressed because one or more lines are too long
2
backend/dist/routes/index.d.ts.map
vendored
2
backend/dist/routes/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA+HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAodxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmIH,QAAA,MAAM,MAAM,4CAAW,CAAC;AA8fxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
8
backend/dist/routes/index.js
vendored
8
backend/dist/routes/index.js
vendored
@ -193,6 +193,12 @@ router.get('/admin/advertisements', (0, auth_1.requireRoles)('admin'), (0, auth_
|
||||
router.post('/admin/advertisements', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.advertisementCreateBodySchema), advertisementController.createAdvertisement);
|
||||
router.patch('/admin/advertisements/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.advertisementUpdateBodySchema), advertisementController.updateAdvertisement);
|
||||
router.delete('/admin/advertisements/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), advertisementController.deleteAdvertisement);
|
||||
router.get('/admin/marketing/live-activity-settings', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), marketingController.getLiveActivitySettings);
|
||||
router.patch('/admin/marketing/live-activity-settings', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.marketingLiveActivitySettingsBodySchema), marketingController.updateLiveActivitySettings);
|
||||
router.get('/admin/marketing/personas', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), marketingController.listPersonas);
|
||||
router.post('/admin/marketing/personas', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.marketingPersonaCreateBodySchema), marketingController.createPersona);
|
||||
router.patch('/admin/marketing/personas/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.marketingPersonaUpdateBodySchema), marketingController.updatePersona);
|
||||
router.delete('/admin/marketing/personas/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('games.admin'), marketingController.deletePersona);
|
||||
router.get('/admin/users', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('users.admin'), (0, validate_1.validateQuery)(querySchemas_1.adminUsersListQuerySchema), adminController.listUsers);
|
||||
router.post('/admin/users/export', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('users.admin'), (0, validate_1.validateBody)(adminSchemas_1.adminUsersExportBodySchema), adminController.startUsersExport);
|
||||
router.get('/admin/users/export/:jobId', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('users.admin'), adminController.getUsersExportStatus);
|
||||
@ -259,6 +265,8 @@ router.get('/admin/referral/fraud-dashboard', (0, auth_1.requireRoles)('admin'),
|
||||
router.get('/admin/referral/clawbacks/export.csv', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('referral.admin'), referralController.exportReferralClawbacksCsv);
|
||||
router.post('/admin/referral/commissions/:payoutId/clawback', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('referral.admin'), (0, validate_1.validateBody)(adminSchemas_1.referralReasonBodySchema), referralController.clawbackReferralCommission);
|
||||
router.post('/admin/referral/pool/fund', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('referral.admin'), (0, validate_1.validateBody)(adminSchemas_1.referralFundPoolBodySchema), referralController.fundBonusPool);
|
||||
router.get('/admin/referral/regularization', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('referral.admin'), referralController.getReferralRegularization);
|
||||
router.post('/admin/referral/regularization/apply', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('referral.admin'), (0, validate_1.validateBody)(adminSchemas_1.referralRegularizeBodySchema), referralController.applyReferralRegularization);
|
||||
router.get('/admin/test-wallet/config', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), testWalletController.getAdminConfig);
|
||||
router.patch('/admin/test-wallet/config', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.testWalletConfigBodySchema), testWalletController.updateAdminConfig);
|
||||
router.get('/admin/test-wallet/credits', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), testWalletController.listAdminCredits);
|
||||
|
||||
2
backend/dist/routes/index.js.map
vendored
2
backend/dist/routes/index.js.map
vendored
File diff suppressed because one or more lines are too long
22
backend/dist/services/referralService.d.ts
vendored
22
backend/dist/services/referralService.d.ts
vendored
@ -50,12 +50,16 @@ export declare function processFirstDepositReferralCommissions(input: {
|
||||
depositAmount: bigint;
|
||||
walletTypeId: number;
|
||||
}): Promise<void>;
|
||||
/**
|
||||
* Credits multi-level referral commissions on settled predictions (stake-based).
|
||||
* Only won/lost settlements qualify — neutral (refund) must never trigger this.
|
||||
* Pays immediately to the referrer bonus wallet after Sybil / caps / pool checks.
|
||||
* Test stakes are excluded. Deposit/withdrawal commission modes are unchanged.
|
||||
*/
|
||||
export type PredictionCommissionProcessResult = {
|
||||
attempted: number;
|
||||
paid: number;
|
||||
paidAmountRaw: string;
|
||||
reviewQueued: number;
|
||||
skippedInsufficientPool: number;
|
||||
skippedOther: number;
|
||||
/** True when a level could not be paid due to empty pool (FIFO stop signal). */
|
||||
hitInsufficientPool: boolean;
|
||||
};
|
||||
export declare function processPredictionReferralCommissions(input: {
|
||||
betId: string;
|
||||
referredUserId: string;
|
||||
@ -64,7 +68,11 @@ export declare function processPredictionReferralCommissions(input: {
|
||||
walletTypeId: number;
|
||||
/** Terminal bet outcome; neutral/refund must not call this. */
|
||||
betOutcome: 'won' | 'lost';
|
||||
}): Promise<void>;
|
||||
/** When set, only these referrer user ids are considered (regularization). */
|
||||
onlyBeneficiaryIds?: string[];
|
||||
/** When true, stop the level loop after the first insufficient-pool debit. */
|
||||
stopOnInsufficientPool?: boolean;
|
||||
}): Promise<PredictionCommissionProcessResult>;
|
||||
/**
|
||||
* Creates pending multi-level referral commissions on withdrawal.
|
||||
* Base = commissionable prediction gains (main account), not deposited principal.
|
||||
|
||||
File diff suppressed because one or more lines are too long
132
backend/dist/services/referralService.js
vendored
132
backend/dist/services/referralService.js
vendored
@ -403,39 +403,109 @@ async function processFirstDepositReferralCommissions(input) {
|
||||
* Pays immediately to the referrer bonus wallet after Sybil / caps / pool checks.
|
||||
* Test stakes are excluded. Deposit/withdrawal commission modes are unchanged.
|
||||
*/
|
||||
function logPredictionCommissionSkip(reason, details) {
|
||||
console.warn('[referral] prediction commission skipped:', reason, details);
|
||||
}
|
||||
async function processPredictionReferralCommissions(input) {
|
||||
if (input.betOutcome !== 'won' && input.betOutcome !== 'lost')
|
||||
return;
|
||||
if (input.stakeAccountKind === 'test')
|
||||
return;
|
||||
if (input.stakeRaw <= 0n)
|
||||
return;
|
||||
const empty = {
|
||||
attempted: 0,
|
||||
paid: 0,
|
||||
paidAmountRaw: '0',
|
||||
reviewQueued: 0,
|
||||
skippedInsufficientPool: 0,
|
||||
skippedOther: 0,
|
||||
hitInsufficientPool: false,
|
||||
};
|
||||
if (input.betOutcome !== 'won' && input.betOutcome !== 'lost') {
|
||||
logPredictionCommissionSkip('invalid_outcome', {
|
||||
betId: input.betId,
|
||||
betOutcome: input.betOutcome,
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
if (input.stakeAccountKind === 'test') {
|
||||
logPredictionCommissionSkip('test_stake', { betId: input.betId });
|
||||
return empty;
|
||||
}
|
||||
if (input.stakeRaw <= 0n) {
|
||||
logPredictionCommissionSkip('non_positive_stake', { betId: input.betId });
|
||||
return empty;
|
||||
}
|
||||
const settings = await referralRepository.getSettings();
|
||||
if (!settings.enabled || !settings.prediction_commissions_enabled)
|
||||
return;
|
||||
if (!settings.enabled || !settings.prediction_commissions_enabled) {
|
||||
logPredictionCommissionSkip('program_or_mode_disabled', {
|
||||
betId: input.betId,
|
||||
enabled: settings.enabled,
|
||||
predictionCommissionsEnabled: settings.prediction_commissions_enabled,
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
const userRows = await (0, connection_1.query)('SELECT referred_by_user_id FROM users WHERE id = $1', [input.referredUserId]);
|
||||
const user = userRows[0];
|
||||
if (!user?.referred_by_user_id)
|
||||
return;
|
||||
if (!user?.referred_by_user_id) {
|
||||
logPredictionCommissionSkip('no_referrer', {
|
||||
betId: input.betId,
|
||||
referredUserId: input.referredUserId,
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
const commissionWalletTypeId = settings.commission_wallet_type_id;
|
||||
if (input.walletTypeId !== commissionWalletTypeId)
|
||||
return;
|
||||
if (input.walletTypeId !== commissionWalletTypeId) {
|
||||
logPredictionCommissionSkip('wallet_type_mismatch', {
|
||||
betId: input.betId,
|
||||
betWalletTypeId: input.walletTypeId,
|
||||
commissionWalletTypeId,
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
const levels = (await referralRepository.listLevels()).filter((l) => l.is_active);
|
||||
if (levels.length === 0)
|
||||
return;
|
||||
if (levels.length === 0) {
|
||||
logPredictionCommissionSkip('no_active_levels', { betId: input.betId });
|
||||
return empty;
|
||||
}
|
||||
const maxLevel = Math.max(...levels.map((l) => l.level_number));
|
||||
const chain = await referralRepository.getReferralChain(input.referredUserId, maxLevel);
|
||||
if (chain.length === 0) {
|
||||
logPredictionCommissionSkip('empty_referral_chain', {
|
||||
betId: input.betId,
|
||||
referredUserId: input.referredUserId,
|
||||
});
|
||||
return empty;
|
||||
}
|
||||
const only = input.onlyBeneficiaryIds && input.onlyBeneficiaryIds.length > 0
|
||||
? new Set(input.onlyBeneficiaryIds)
|
||||
: null;
|
||||
const eligibleAt = new Date();
|
||||
const result = { ...empty };
|
||||
let paidAmount = 0n;
|
||||
for (const { userId: beneficiaryId, level } of chain) {
|
||||
if (only && !only.has(beneficiaryId))
|
||||
continue;
|
||||
const levelConfig = levels.find((l) => l.level_number === level);
|
||||
if (!levelConfig)
|
||||
continue;
|
||||
const percent = Number(levelConfig.commission_percent);
|
||||
if (percent <= 0)
|
||||
if (percent <= 0) {
|
||||
logPredictionCommissionSkip('zero_percent', {
|
||||
betId: input.betId,
|
||||
level,
|
||||
beneficiaryId,
|
||||
});
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
const commissionAmount = calcCommission(input.stakeRaw, percent);
|
||||
if (commissionAmount <= 0n)
|
||||
if (commissionAmount <= 0n) {
|
||||
logPredictionCommissionSkip('commission_rounds_to_zero', {
|
||||
betId: input.betId,
|
||||
level,
|
||||
stakeRaw: input.stakeRaw.toString(),
|
||||
percent,
|
||||
});
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
result.attempted += 1;
|
||||
const sybil = await evaluateSybilForCommission(settings, beneficiaryId, input.referredUserId);
|
||||
if (sybil.disposition === 'blocked') {
|
||||
await auditLogRepository.create({
|
||||
@ -471,16 +541,36 @@ async function processPredictionReferralCommissions(input) {
|
||||
void (0, fraudAutoBlockService_1.maybeAutoSuspendForSybilFraud)(beneficiaryId, sybil.score, sybil.signals, {
|
||||
referredUserId: input.referredUserId,
|
||||
}).catch((e) => console.error('[referral] sybil auto-suspend failed:', e));
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
const cap = await isMonthlyCapExceeded(beneficiaryId, commissionAmount, settings, level);
|
||||
if (cap.exceeded) {
|
||||
await logCapBlocked(beneficiaryId, input.referredUserId, commissionAmount, cap.reason, level, cap.capSource ?? 'global', input.betId);
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
const debited = await bonusPoolRepository.debitPool(commissionWalletTypeId, commissionAmount);
|
||||
if (!debited) {
|
||||
console.error(`[referral] Insufficient bonus pool for level ${level} prediction commission to ${beneficiaryId}`);
|
||||
await auditLogRepository.create({
|
||||
userId: beneficiaryId,
|
||||
action: 'referral_commission_pool_insufficient',
|
||||
resourceType: 'referral_commission_payout',
|
||||
resourceId: input.betId,
|
||||
metadata: {
|
||||
referred_user_id: input.referredUserId,
|
||||
level,
|
||||
amount: commissionAmount.toString(),
|
||||
commission_source: 'prediction',
|
||||
candle_predict_bet_id: input.betId,
|
||||
wallet_type_id: commissionWalletTypeId,
|
||||
},
|
||||
});
|
||||
result.skippedInsufficientPool += 1;
|
||||
result.hitInsufficientPool = true;
|
||||
if (input.stopOnInsufficientPool)
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
const initialStatus = sybil.disposition === 'review' ? 'review' : 'pending';
|
||||
@ -501,6 +591,7 @@ async function processPredictionReferralCommissions(input) {
|
||||
});
|
||||
if (!payoutId) {
|
||||
await bonusPoolRepository.creditPool(commissionWalletTypeId, commissionAmount);
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
await auditLogRepository.create({
|
||||
@ -521,18 +612,27 @@ async function processPredictionReferralCommissions(input) {
|
||||
});
|
||||
if (initialStatus === 'review') {
|
||||
await notifyReviewRequired(payoutId, beneficiaryId, input.referredUserId, sybil.score, sybil.signals);
|
||||
result.reviewQueued += 1;
|
||||
continue;
|
||||
}
|
||||
const payout = await referralRepository.findCommissionPayoutById(payoutId);
|
||||
if (!payout) {
|
||||
console.error(`[referral] Prediction payout ${payoutId} missing after insert`);
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
const paid = await payPendingCommission(payout, settings);
|
||||
if (!paid) {
|
||||
console.error(`[referral] Failed immediate pay for prediction commission ${payoutId} (left pending)`);
|
||||
result.skippedOther += 1;
|
||||
}
|
||||
else {
|
||||
result.paid += 1;
|
||||
paidAmount += commissionAmount;
|
||||
}
|
||||
}
|
||||
result.paidAmountRaw = paidAmount.toString();
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Creates pending multi-level referral commissions on withdrawal.
|
||||
|
||||
2
backend/dist/services/referralService.js.map
vendored
2
backend/dist/services/referralService.js.map
vendored
File diff suppressed because one or more lines are too long
@ -38,6 +38,8 @@
|
||||
"smoke-approval-policies:prod": "node dist/scripts/smokeApprovalPolicies.js",
|
||||
"set-forbid-self-approve": "ts-node --transpile-only src/scripts/setForbidSelfApprove.ts",
|
||||
"set-forbid-self-approve:prod": "node dist/scripts/setForbidSelfApprove.js",
|
||||
"backfill-missed-prediction-referral-commissions": "ts-node --transpile-only src/scripts/backfillMissedPredictionReferralCommissions.ts",
|
||||
"backfill-missed-prediction-referral-commissions:prod": "node dist/scripts/backfillMissedPredictionReferralCommissions.js",
|
||||
"verify-smtp": "ts-node --transpile-only src/scripts/verifySmtp.ts",
|
||||
"verify-smtp:prod": "node dist/scripts/verifySmtp.js",
|
||||
"rotate-encryption-key": "ts-node --transpile-only src/scripts/rotateEncryptionKey.ts",
|
||||
|
||||
@ -5,6 +5,11 @@ import * as bonusService from '../services/bonusService';
|
||||
import * as referralRepository from '../repositories/referralRepository';
|
||||
import * as bonusPoolRepository from '../repositories/bonusPoolRepository';
|
||||
import { buildClawbacksCsv } from '../services/referralExportService';
|
||||
import {
|
||||
applyRegularization,
|
||||
getRegularizationSnapshot,
|
||||
ReferralRegularizationError,
|
||||
} from '../services/referralRegularizationService';
|
||||
|
||||
export async function getMyReferralInfo(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
@ -286,6 +291,49 @@ export async function clawbackReferralCommission(req: AuthRequest, res: Response
|
||||
}
|
||||
}
|
||||
|
||||
export async function getReferralRegularization(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const search = req.query.search ? String(req.query.search) : undefined;
|
||||
const snapshot = await getRegularizationSnapshot({ search });
|
||||
res.json(snapshot);
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyReferralRegularization(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const body = req.body as {
|
||||
mode?: 'one' | 'selected' | 'all';
|
||||
beneficiaryUserIds?: string[];
|
||||
allowPartial?: boolean;
|
||||
};
|
||||
if (!body.mode) {
|
||||
res.status(400).json({ error: 'mode is required' });
|
||||
return;
|
||||
}
|
||||
const result = await applyRegularization({
|
||||
mode: body.mode,
|
||||
adminUserId: req.user!.userId,
|
||||
beneficiaryUserIds: body.beneficiaryUserIds,
|
||||
allowPartial: Boolean(body.allowPartial),
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
if (e instanceof ReferralRegularizationError) {
|
||||
const status =
|
||||
e.code === 'INSUFFICIENT_POOL'
|
||||
? 409
|
||||
: e.code === 'NOTHING_TO_DO'
|
||||
? 404
|
||||
: 400;
|
||||
res.status(status).json({ error: e.message, code: e.code });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Regularization failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportReferralClawbacksCsv(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const fromRaw = req.query.from ? String(req.query.from) : undefined;
|
||||
|
||||
@ -52,6 +52,7 @@ import {
|
||||
referralFundPoolBodySchema,
|
||||
referralReasonBodySchema,
|
||||
referralNoteBodySchema,
|
||||
referralRegularizeBodySchema,
|
||||
treasuryColdWalletBodySchema,
|
||||
treasuryFundingBodySchema,
|
||||
treasuryFundingConfirmBodySchema,
|
||||
@ -543,6 +544,8 @@ router.get('/admin/referral/fraud-dashboard', requireRoles('admin'), requirePerm
|
||||
router.get('/admin/referral/clawbacks/export.csv', requireRoles('admin'), requirePermissions('referral.admin'), referralController.exportReferralClawbacksCsv);
|
||||
router.post('/admin/referral/commissions/:payoutId/clawback', requireRoles('admin'), requirePermissions('referral.admin'), validateBody(referralReasonBodySchema), referralController.clawbackReferralCommission);
|
||||
router.post('/admin/referral/pool/fund', requireRoles('admin'), requirePermissions('referral.admin'), validateBody(referralFundPoolBodySchema), referralController.fundBonusPool);
|
||||
router.get('/admin/referral/regularization', requireRoles('admin'), requirePermissions('referral.admin'), referralController.getReferralRegularization);
|
||||
router.post('/admin/referral/regularization/apply', requireRoles('admin'), requirePermissions('referral.admin'), validateBody(referralRegularizeBodySchema), referralController.applyReferralRegularization);
|
||||
|
||||
router.get('/admin/test-wallet/config', requireRoles('admin'), requirePermissions('settings.admin'), testWalletController.getAdminConfig);
|
||||
router.patch('/admin/test-wallet/config', requireRoles('admin'), requirePermissions('settings.admin'), validateBody(testWalletConfigBodySchema), testWalletController.updateAdminConfig);
|
||||
|
||||
@ -0,0 +1,165 @@
|
||||
/**
|
||||
* List / backfill prediction referral commissions missed when the bonus pool was empty
|
||||
* (or otherwise never recorded a payout row).
|
||||
*
|
||||
* Dry-run (default):
|
||||
* npx ts-node --transpile-only src/scripts/backfillMissedPredictionReferralCommissions.ts
|
||||
*
|
||||
* Apply (pool must be funded first):
|
||||
* npx ts-node --transpile-only src/scripts/backfillMissedPredictionReferralCommissions.ts --apply
|
||||
*
|
||||
* Optional: --since=2026-10-01 (ISO date, inclusive on created_at)
|
||||
* Optional: --limit=500
|
||||
*
|
||||
* VPS:
|
||||
* sudo docker compose run --rm --no-deps --build backend \
|
||||
* node dist/scripts/backfillMissedPredictionReferralCommissions.js
|
||||
* sudo docker compose run --rm --no-deps --build backend \
|
||||
* node dist/scripts/backfillMissedPredictionReferralCommissions.js --apply
|
||||
*/
|
||||
|
||||
import './loadEnv';
|
||||
import { query } from '../db/connection';
|
||||
import { processPredictionReferralCommissions } from '../services/referralService';
|
||||
|
||||
type MissedBet = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
status: 'won' | 'lost';
|
||||
stake_raw: string;
|
||||
stake_account_kind: string | null;
|
||||
wallet_type_id: number;
|
||||
referred_by_user_id: string;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
function parseArgs(argv: string[]): { apply: boolean; since: string | null; limit: number } {
|
||||
let apply = false;
|
||||
let since: string | null = null;
|
||||
let limit = 500;
|
||||
for (const arg of argv) {
|
||||
if (arg === '--apply') apply = true;
|
||||
else if (arg.startsWith('--since=')) since = arg.slice('--since='.length).trim() || null;
|
||||
else if (arg.startsWith('--limit=')) {
|
||||
const n = Number(arg.slice('--limit='.length));
|
||||
if (Number.isFinite(n) && n > 0) limit = Math.min(Math.floor(n), 5000);
|
||||
}
|
||||
}
|
||||
return { apply, since, limit };
|
||||
}
|
||||
|
||||
async function listMissed(since: string | null, limit: number): Promise<MissedBet[]> {
|
||||
const params: unknown[] = [];
|
||||
let sinceClause = '';
|
||||
if (since) {
|
||||
params.push(since);
|
||||
sinceClause = `AND b.created_at >= $${params.length}::timestamptz`;
|
||||
}
|
||||
params.push(limit);
|
||||
const limitPlaceholder = `$${params.length}`;
|
||||
|
||||
return query<MissedBet[]>(
|
||||
`SELECT b.id, b.user_id, b.status, b.stake_raw::text, b.stake_account_kind, b.wallet_type_id,
|
||||
u.referred_by_user_id, b.created_at
|
||||
FROM candle_predict_bets b
|
||||
JOIN users u ON u.id = b.user_id
|
||||
CROSS JOIN referral_program_settings s
|
||||
WHERE s.id = 1
|
||||
AND s.enabled = TRUE
|
||||
AND COALESCE(s.prediction_commissions_enabled, TRUE) = TRUE
|
||||
AND 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 = s.commission_wallet_type_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM referral_commission_payouts p
|
||||
WHERE p.candle_predict_bet_id = b.id
|
||||
AND p.commission_source = 'prediction'
|
||||
)
|
||||
${sinceClause}
|
||||
ORDER BY b.created_at ASC
|
||||
LIMIT ${limitPlaceholder}`,
|
||||
params
|
||||
);
|
||||
}
|
||||
|
||||
async function poolBalance(): Promise<string> {
|
||||
const rows = await query<{ available_balance: string }[]>(
|
||||
`SELECT available_balance::text
|
||||
FROM platform_bonus_pools
|
||||
WHERE wallet_type_id = (
|
||||
SELECT commission_wallet_type_id FROM referral_program_settings WHERE id = 1
|
||||
)`
|
||||
);
|
||||
return rows[0]?.available_balance ?? '0';
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { apply, since, limit } = parseArgs(process.argv.slice(2));
|
||||
console.log('=== backfillMissedPredictionReferralCommissions ===');
|
||||
console.log(`mode=${apply ? 'APPLY' : 'DRY-RUN'} since=${since ?? '(all)'} limit=${limit}`);
|
||||
|
||||
const balance = await poolBalance();
|
||||
console.log(`bonus pool available_balance=${balance}`);
|
||||
|
||||
const missed = await listMissed(since, limit);
|
||||
console.log(`missed bets (no prediction payout row): ${missed.length}`);
|
||||
for (const b of missed) {
|
||||
console.log(
|
||||
` ${b.created_at.toISOString()} bet=${b.id} user=${b.user_id} status=${b.status} stake=${b.stake_raw} kind=${b.stake_account_kind ?? 'main'} referrer=${b.referred_by_user_id}`
|
||||
);
|
||||
}
|
||||
|
||||
if (!apply) {
|
||||
console.log('\nDry-run only. Fund the bonus pool, then re-run with --apply.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (missed.length === 0) {
|
||||
console.log('Nothing to backfill.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (BigInt(balance) <= 0n) {
|
||||
console.error('Refusing --apply: bonus pool balance is 0. Fund the pool first.');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
let ok = 0;
|
||||
let fail = 0;
|
||||
for (const b of missed) {
|
||||
try {
|
||||
await processPredictionReferralCommissions({
|
||||
betId: b.id,
|
||||
referredUserId: b.user_id,
|
||||
stakeRaw: BigInt(b.stake_raw),
|
||||
stakeAccountKind:
|
||||
b.stake_account_kind === 'bonus'
|
||||
? 'bonus'
|
||||
: b.stake_account_kind === 'test'
|
||||
? 'test'
|
||||
: 'main',
|
||||
walletTypeId: b.wallet_type_id,
|
||||
betOutcome: b.status,
|
||||
});
|
||||
ok += 1;
|
||||
console.log(`OK bet=${b.id}`);
|
||||
} catch (e) {
|
||||
fail += 1;
|
||||
console.error(`FAIL bet=${b.id}:`, e instanceof Error ? e.message : e);
|
||||
}
|
||||
}
|
||||
|
||||
const balanceAfter = await poolBalance();
|
||||
console.log(`\nDone. processed_ok=${ok} failed=${fail} pool_after=${balanceAfter}`);
|
||||
console.log('Re-check payouts: SELECT * FROM referral_commission_payouts ORDER BY created_at DESC LIMIT 50;');
|
||||
}
|
||||
|
||||
main()
|
||||
.then(() => process.exit(process.exitCode ?? 0))
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
504
backend/src/services/referralRegularizationService.ts
Normal file
504
backend/src/services/referralRegularizationService.ts
Normal file
@ -0,0 +1,504 @@
|
||||
/**
|
||||
* 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;
|
||||
});
|
||||
}
|
||||
@ -471,6 +471,17 @@ function logPredictionCommissionSkip(
|
||||
console.warn('[referral] prediction commission skipped:', reason, details);
|
||||
}
|
||||
|
||||
export type PredictionCommissionProcessResult = {
|
||||
attempted: number;
|
||||
paid: number;
|
||||
paidAmountRaw: string;
|
||||
reviewQueued: number;
|
||||
skippedInsufficientPool: number;
|
||||
skippedOther: number;
|
||||
/** True when a level could not be paid due to empty pool (FIFO stop signal). */
|
||||
hitInsufficientPool: boolean;
|
||||
};
|
||||
|
||||
export async function processPredictionReferralCommissions(input: {
|
||||
betId: string;
|
||||
referredUserId: string;
|
||||
@ -479,21 +490,35 @@ export async function processPredictionReferralCommissions(input: {
|
||||
walletTypeId: number;
|
||||
/** Terminal bet outcome; neutral/refund must not call this. */
|
||||
betOutcome: 'won' | 'lost';
|
||||
}): Promise<void> {
|
||||
/** When set, only these referrer user ids are considered (regularization). */
|
||||
onlyBeneficiaryIds?: string[];
|
||||
/** When true, stop the level loop after the first insufficient-pool debit. */
|
||||
stopOnInsufficientPool?: boolean;
|
||||
}): Promise<PredictionCommissionProcessResult> {
|
||||
const empty: PredictionCommissionProcessResult = {
|
||||
attempted: 0,
|
||||
paid: 0,
|
||||
paidAmountRaw: '0',
|
||||
reviewQueued: 0,
|
||||
skippedInsufficientPool: 0,
|
||||
skippedOther: 0,
|
||||
hitInsufficientPool: false,
|
||||
};
|
||||
|
||||
if (input.betOutcome !== 'won' && input.betOutcome !== 'lost') {
|
||||
logPredictionCommissionSkip('invalid_outcome', {
|
||||
betId: input.betId,
|
||||
betOutcome: input.betOutcome,
|
||||
});
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
if (input.stakeAccountKind === 'test') {
|
||||
logPredictionCommissionSkip('test_stake', { betId: input.betId });
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
if (input.stakeRaw <= 0n) {
|
||||
logPredictionCommissionSkip('non_positive_stake', { betId: input.betId });
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
|
||||
const settings = await referralRepository.getSettings();
|
||||
@ -503,7 +528,7 @@ export async function processPredictionReferralCommissions(input: {
|
||||
enabled: settings.enabled,
|
||||
predictionCommissionsEnabled: settings.prediction_commissions_enabled,
|
||||
});
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
|
||||
const userRows = await query<Array<{ referred_by_user_id: string | null }>>(
|
||||
@ -516,7 +541,7 @@ export async function processPredictionReferralCommissions(input: {
|
||||
betId: input.betId,
|
||||
referredUserId: input.referredUserId,
|
||||
});
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
|
||||
const commissionWalletTypeId = settings.commission_wallet_type_id;
|
||||
@ -526,13 +551,13 @@ export async function processPredictionReferralCommissions(input: {
|
||||
betWalletTypeId: input.walletTypeId,
|
||||
commissionWalletTypeId,
|
||||
});
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
|
||||
const levels = (await referralRepository.listLevels()).filter((l) => l.is_active);
|
||||
if (levels.length === 0) {
|
||||
logPredictionCommissionSkip('no_active_levels', { betId: input.betId });
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
|
||||
const maxLevel = Math.max(...levels.map((l) => l.level_number));
|
||||
@ -542,11 +567,20 @@ export async function processPredictionReferralCommissions(input: {
|
||||
betId: input.betId,
|
||||
referredUserId: input.referredUserId,
|
||||
});
|
||||
return;
|
||||
return empty;
|
||||
}
|
||||
|
||||
const only =
|
||||
input.onlyBeneficiaryIds && input.onlyBeneficiaryIds.length > 0
|
||||
? new Set(input.onlyBeneficiaryIds)
|
||||
: null;
|
||||
const eligibleAt = new Date();
|
||||
const result: PredictionCommissionProcessResult = { ...empty };
|
||||
let paidAmount = 0n;
|
||||
|
||||
for (const { userId: beneficiaryId, level } of chain) {
|
||||
if (only && !only.has(beneficiaryId)) continue;
|
||||
|
||||
const levelConfig = levels.find((l) => l.level_number === level);
|
||||
if (!levelConfig) continue;
|
||||
|
||||
@ -557,6 +591,7 @@ export async function processPredictionReferralCommissions(input: {
|
||||
level,
|
||||
beneficiaryId,
|
||||
});
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -568,9 +603,11 @@ export async function processPredictionReferralCommissions(input: {
|
||||
stakeRaw: input.stakeRaw.toString(),
|
||||
percent,
|
||||
});
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
result.attempted += 1;
|
||||
const sybil = await evaluateSybilForCommission(settings, beneficiaryId, input.referredUserId);
|
||||
|
||||
if (sybil.disposition === 'blocked') {
|
||||
@ -607,6 +644,7 @@ export async function processPredictionReferralCommissions(input: {
|
||||
void maybeAutoSuspendForSybilFraud(beneficiaryId, sybil.score, sybil.signals, {
|
||||
referredUserId: input.referredUserId,
|
||||
}).catch((e) => console.error('[referral] sybil auto-suspend failed:', e));
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -621,6 +659,7 @@ export async function processPredictionReferralCommissions(input: {
|
||||
cap.capSource ?? 'global',
|
||||
input.betId
|
||||
);
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -629,6 +668,23 @@ export async function processPredictionReferralCommissions(input: {
|
||||
console.error(
|
||||
`[referral] Insufficient bonus pool for level ${level} prediction commission to ${beneficiaryId}`
|
||||
);
|
||||
await auditLogRepository.create({
|
||||
userId: beneficiaryId,
|
||||
action: 'referral_commission_pool_insufficient',
|
||||
resourceType: 'referral_commission_payout',
|
||||
resourceId: input.betId,
|
||||
metadata: {
|
||||
referred_user_id: input.referredUserId,
|
||||
level,
|
||||
amount: commissionAmount.toString(),
|
||||
commission_source: 'prediction',
|
||||
candle_predict_bet_id: input.betId,
|
||||
wallet_type_id: commissionWalletTypeId,
|
||||
},
|
||||
});
|
||||
result.skippedInsufficientPool += 1;
|
||||
result.hitInsufficientPool = true;
|
||||
if (input.stopOnInsufficientPool) break;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -651,6 +707,7 @@ export async function processPredictionReferralCommissions(input: {
|
||||
|
||||
if (!payoutId) {
|
||||
await bonusPoolRepository.creditPool(commissionWalletTypeId, commissionAmount);
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -679,12 +736,14 @@ export async function processPredictionReferralCommissions(input: {
|
||||
sybil.score,
|
||||
sybil.signals
|
||||
);
|
||||
result.reviewQueued += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const payout = await referralRepository.findCommissionPayoutById(payoutId);
|
||||
if (!payout) {
|
||||
console.error(`[referral] Prediction payout ${payoutId} missing after insert`);
|
||||
result.skippedOther += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -693,8 +752,15 @@ export async function processPredictionReferralCommissions(input: {
|
||||
console.error(
|
||||
`[referral] Failed immediate pay for prediction commission ${payoutId} (left pending)`
|
||||
);
|
||||
result.skippedOther += 1;
|
||||
} else {
|
||||
result.paid += 1;
|
||||
paidAmount += commissionAmount;
|
||||
}
|
||||
}
|
||||
|
||||
result.paidAmountRaw = paidAmount.toString();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
51
backend/src/tests/referralRegularization.test.ts
Normal file
51
backend/src/tests/referralRegularization.test.ts
Normal file
@ -0,0 +1,51 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { calcCommission } from '../services/referralService';
|
||||
import { ReferralRegularizationError } from '../services/referralRegularizationService';
|
||||
import { referralRegularizeBodySchema } from '../validation/adminSchemas';
|
||||
|
||||
describe('referral regularization helpers', () => {
|
||||
test('calcCommission is used for due amounts (never truncates upward)', () => {
|
||||
// 1 USDT stake (6 decimals) at 10% = 0.1 USDT
|
||||
assert.equal(calcCommission(1_000_000n, 10).toString(), '100000');
|
||||
assert.equal(calcCommission(1n, 10).toString(), '0');
|
||||
});
|
||||
|
||||
test('referralRegularizeBodySchema enforces mode selection rules', () => {
|
||||
const idA = '11111111-1111-4111-8111-111111111111';
|
||||
const idB = '22222222-2222-4222-8222-222222222222';
|
||||
assert.equal(referralRegularizeBodySchema.safeParse({ mode: 'all' }).success, true);
|
||||
assert.equal(
|
||||
referralRegularizeBodySchema.safeParse({
|
||||
mode: 'one',
|
||||
beneficiaryUserIds: [idA],
|
||||
}).success,
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
referralRegularizeBodySchema.safeParse({
|
||||
mode: 'one',
|
||||
beneficiaryUserIds: [idA, idB],
|
||||
}).success,
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
referralRegularizeBodySchema.safeParse({ mode: 'selected', beneficiaryUserIds: [] }).success,
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
referralRegularizeBodySchema.safeParse({
|
||||
mode: 'selected',
|
||||
beneficiaryUserIds: [idA],
|
||||
allowPartial: true,
|
||||
}).success,
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('ReferralRegularizationError carries stable codes for HTTP mapping', () => {
|
||||
const e = new ReferralRegularizationError('pool low', 'INSUFFICIENT_POOL');
|
||||
assert.equal(e.code, 'INSUFFICIENT_POOL');
|
||||
assert.equal(e.name, 'ReferralRegularizationError');
|
||||
});
|
||||
});
|
||||
@ -251,6 +251,33 @@ export const referralNoteBodySchema = z.object({
|
||||
note: z.string().trim().max(2000).optional(),
|
||||
});
|
||||
|
||||
export const referralRegularizeBodySchema = z
|
||||
.object({
|
||||
mode: z.enum(['one', 'selected', 'all']),
|
||||
beneficiaryUserIds: z.array(z.string().uuid()).max(500).optional(),
|
||||
allowPartial: z.boolean().optional().default(false),
|
||||
})
|
||||
.superRefine((val, ctx) => {
|
||||
if (val.mode === 'one') {
|
||||
if (!val.beneficiaryUserIds || val.beneficiaryUserIds.length !== 1) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'mode one requires exactly one beneficiaryUserId',
|
||||
path: ['beneficiaryUserIds'],
|
||||
});
|
||||
}
|
||||
}
|
||||
if (val.mode === 'selected') {
|
||||
if (!val.beneficiaryUserIds || val.beneficiaryUserIds.length < 1) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'mode selected requires at least one beneficiaryUserId',
|
||||
path: ['beneficiaryUserIds'],
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const treasuryColdWalletBodySchema = z.object({
|
||||
walletTypeId: z.number().int().positive(),
|
||||
address: z.string().trim().min(10).max(255),
|
||||
|
||||
109
docs/REFERRAL-COMMISSION-BACKFILL.md
Normal file
109
docs/REFERRAL-COMMISSION-BACKFILL.md
Normal file
@ -0,0 +1,109 @@
|
||||
# Régularisation des commissions prédiction manquées
|
||||
|
||||
Quand le **pool bonus** est à 0, le settle win/loss tente bien de payer le parrain, mais **aucune ligne** n’est créée dans `referral_commission_payouts` (seul un log / audit). Après avoir rechargé le pool, il faut **identifier** puis **rejouer** ces paris.
|
||||
|
||||
## Interface admin (recommandé)
|
||||
|
||||
Page **Options → Régularisation des commissions** (`/admin/referral/regularization`) :
|
||||
|
||||
- liste des bénéficiaires avec montants dus + total + solde pool + déficit ;
|
||||
- régularisation **une personne** / **sélection** / **tout** ;
|
||||
- refus si solde insuffisant, ou **partiel FIFO** (plus ancien d’abord, jamais de montant réduit) ;
|
||||
- idempotent (pas de double paiement).
|
||||
|
||||
APIs : `GET /api/v1/admin/referral/regularization`, `POST /api/v1/admin/referral/regularization/apply`.
|
||||
|
||||
## 1. Lister les paris sans commission (SQL)
|
||||
|
||||
```sql
|
||||
SELECT b.id AS bet_id,
|
||||
b.created_at,
|
||||
b.user_id AS referred_user_id,
|
||||
u.referred_by_user_id AS referrer_user_id,
|
||||
b.status,
|
||||
b.stake_account_kind,
|
||||
b.stake_raw,
|
||||
b.wallet_type_id
|
||||
FROM candle_predict_bets b
|
||||
JOIN users u ON u.id = b.user_id
|
||||
CROSS JOIN referral_program_settings s
|
||||
WHERE s.id = 1
|
||||
AND 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 = s.commission_wallet_type_id
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM referral_commission_payouts p
|
||||
WHERE p.candle_predict_bet_id = b.id
|
||||
AND p.commission_source = 'prediction'
|
||||
)
|
||||
ORDER BY b.created_at ASC;
|
||||
```
|
||||
|
||||
Exclus volontairement : mises `test`, settle neutral/refund, utilisateurs sans parrain, wallet ≠ wallet de commission.
|
||||
|
||||
Audits futurs (après déploiement des logs) :
|
||||
|
||||
```sql
|
||||
SELECT * FROM audit_logs
|
||||
WHERE action = 'referral_commission_pool_insufficient'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 100;
|
||||
```
|
||||
|
||||
## 2. Vérifier / alimenter le pool
|
||||
|
||||
Admin → **Referrals** → **Fund pool**, puis :
|
||||
|
||||
```sql
|
||||
SELECT available_balance
|
||||
FROM platform_bonus_pools
|
||||
WHERE wallet_type_id = (
|
||||
SELECT commission_wallet_type_id FROM referral_program_settings WHERE id = 1
|
||||
);
|
||||
```
|
||||
|
||||
## 3. Script dry-run puis apply (VPS)
|
||||
|
||||
Dry-run (liste seulement) :
|
||||
|
||||
```bash
|
||||
cd ~/projects_repository/games-project
|
||||
sudo npm run phase-b:backfill-missed-prediction-referral-commissions
|
||||
# équivalent :
|
||||
# sudo docker compose run --rm --no-deps --build backend \
|
||||
# node dist/scripts/backfillMissedPredictionReferralCommissions.js
|
||||
```
|
||||
|
||||
Options :
|
||||
|
||||
```bash
|
||||
# Depuis une date (ISO)
|
||||
... backfillMissedPredictionReferralCommissions.js --since=2026-10-01
|
||||
|
||||
# Limiter le lot
|
||||
... backfillMissedPredictionReferralCommissions.js --limit=200
|
||||
```
|
||||
|
||||
Appliquer (crée / paie les commissions manquantes ; idempotent grâce à `ON CONFLICT`) :
|
||||
|
||||
```bash
|
||||
sudo docker compose run --rm --no-deps --build backend \
|
||||
node dist/scripts/backfillMissedPredictionReferralCommissions.js --apply
|
||||
```
|
||||
|
||||
Le script refuse `--apply` si le pool est à 0.
|
||||
|
||||
## 4. Contrôle après apply
|
||||
|
||||
```sql
|
||||
SELECT id, status, beneficiary_user_id, referred_user_id, level_number,
|
||||
commission_amount, candle_predict_bet_id, created_at
|
||||
FROM referral_commission_payouts
|
||||
WHERE commission_source = 'prediction'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 50;
|
||||
```
|
||||
|
||||
Relancer le dry-run : la liste des « missed » doit être vide (ou ne contenir que des cas encore bloqués : pool insuffisant pour le reste, sybil, cap, etc.).
|
||||
@ -30,6 +30,7 @@
|
||||
"phase-b:verify-deposit-addresses": "docker compose run --rm --no-deps --build backend node dist/scripts/verifyDepositAddresses.js",
|
||||
"phase-b:smoke-approval-policies": "docker compose run --rm --no-deps --build backend node dist/scripts/smokeApprovalPolicies.js",
|
||||
"phase-b:set-forbid-self-approve": "docker compose run --rm --no-deps --build backend node dist/scripts/setForbidSelfApprove.js",
|
||||
"phase-b:backfill-missed-prediction-referral-commissions": "docker compose run --rm --no-deps --build backend node dist/scripts/backfillMissedPredictionReferralCommissions.js",
|
||||
"docker:local:grant-super-admin": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/grantSuperAdminToAdmins.js",
|
||||
"docker:local:reset-password": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/resetDevPassword.js",
|
||||
"docker:local:disable-admin-2fa": "docker compose --env-file .env.docker run --rm --no-deps --build backend node dist/scripts/disableAdmin2faRequirement.js",
|
||||
|
||||
@ -24,6 +24,7 @@ import { TreasuryAdminPage } from '../../features/treasury/TreasuryAdminPage';
|
||||
import { ApprovalsPage } from '../../features/approvals/ApprovalsPage';
|
||||
import { ApprovalPoliciesPage } from '../../features/approvals/ApprovalPoliciesPage';
|
||||
import { ReferralAdminPage } from '../../features/referral/ReferralAdminPage';
|
||||
import { ReferralRegularizationPage } from '../../features/referral/ReferralRegularizationPage';
|
||||
import { ReferralPage } from '../../features/referral/ReferralPage';
|
||||
import { ReferralFraudDashboardPage } from '../../features/referral/ReferralFraudDashboardPage';
|
||||
import { TestWalletAdminPage } from '../../features/test-wallet/TestWalletAdminPage';
|
||||
@ -114,6 +115,7 @@ export const router = createBrowserRouter([
|
||||
{ path: 'admin/approval-policies', element: <ApprovalPoliciesPage /> },
|
||||
{ path: 'admin/security', element: <SecurityAdminPage /> },
|
||||
{ path: 'admin/referral', element: <ReferralAdminPage /> },
|
||||
{ path: 'admin/referral/regularization', element: <ReferralRegularizationPage /> },
|
||||
{ path: 'admin/referral/fraud', element: <ReferralFraudDashboardPage /> },
|
||||
{ path: 'admin/test-wallet', element: <TestWalletAdminPage /> },
|
||||
{ path: 'admin/share-cards', element: <ShareCardsAdminPage /> },
|
||||
|
||||
@ -34,6 +34,7 @@ type OptionCardKey =
|
||||
| 'treasury'
|
||||
| 'approvalPolicies'
|
||||
| 'referral'
|
||||
| 'referralRegularization'
|
||||
| 'referralFraud'
|
||||
| 'testWallet'
|
||||
| 'shareCards'
|
||||
@ -112,6 +113,15 @@ const OPTION_CARDS: OptionCardConfig[] = [
|
||||
bg: 'rgba(124,92,255,0.16)',
|
||||
border: 'rgba(124,92,255,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'referralRegularization',
|
||||
path: '/admin/referral/regularization',
|
||||
icon: AccountBalanceWalletRoundedIcon,
|
||||
badgeKey: 'missedPay',
|
||||
badgeColor: 'warning',
|
||||
bg: 'rgba(255,152,0,0.12)',
|
||||
border: 'rgba(255,152,0,0.28)',
|
||||
},
|
||||
{
|
||||
key: 'referralFraud',
|
||||
path: '/admin/referral/fraud',
|
||||
|
||||
@ -292,6 +292,9 @@ export function ReferralAdminPage() {
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1 }}>
|
||||
{t('admin.referralAdmin.title')}
|
||||
</Typography>
|
||||
<Button component={RouterLink} to="/admin/referral/regularization" variant="outlined" size="small">
|
||||
{t('admin.referralAdmin.regularization')}
|
||||
</Button>
|
||||
<Button component={RouterLink} to="/admin/referral/fraud" variant="outlined" size="small" color="warning">
|
||||
{t('admin.referralAdmin.fraudDashboard')}
|
||||
</Button>
|
||||
|
||||
557
prediqo_web/src/features/referral/ReferralRegularizationPage.tsx
Normal file
557
prediqo_web/src/features/referral/ReferralRegularizationPage.tsx
Normal file
@ -0,0 +1,557 @@
|
||||
/**
|
||||
* Admin page: list & regularize missed prediction referral commissions.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
Checkbox,
|
||||
Chip,
|
||||
Collapse,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
FormControlLabel,
|
||||
Grid,
|
||||
IconButton,
|
||||
Stack,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceWalletRounded';
|
||||
import ExpandMoreRoundedIcon from '@mui/icons-material/ExpandMoreRounded';
|
||||
import ExpandLessRoundedIcon from '@mui/icons-material/ExpandLessRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { Fragment, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
import { PermissionGate } from '../../shared/auth/PermissionGate';
|
||||
import { rawToHuman } from '../wallet/utils/walletFormat';
|
||||
|
||||
const USDT_DECIMALS = 6;
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
type RegularizationBeneficiary = {
|
||||
beneficiaryUserId: string;
|
||||
displayName: string;
|
||||
email: string | null;
|
||||
pendingCount: number;
|
||||
amountDueRaw: string;
|
||||
oldestCreatedAt: string;
|
||||
items: RegularizationItem[];
|
||||
};
|
||||
|
||||
type Snapshot = {
|
||||
walletTypeId: number;
|
||||
poolBalanceRaw: string;
|
||||
totalDueRaw: string;
|
||||
shortfallRaw: string;
|
||||
pendingItemCount: number;
|
||||
beneficiaryCount: number;
|
||||
beneficiaries: RegularizationBeneficiary[];
|
||||
};
|
||||
|
||||
type ApplyResult = {
|
||||
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;
|
||||
};
|
||||
|
||||
function formatUsdt(raw: string) {
|
||||
return `${rawToHuman(raw, USDT_DECIMALS)} USDT`;
|
||||
}
|
||||
|
||||
function StatCard({ label, value, warn }: { label: string; value: string; warn?: boolean }) {
|
||||
return (
|
||||
<Card sx={{ borderRadius: 2, height: '100%', border: warn ? '1px solid' : undefined, borderColor: warn ? 'warning.main' : undefined }}>
|
||||
<CardContent>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900 }} color={warn ? 'warning.main' : 'text.primary'}>
|
||||
{value}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
type ConfirmState =
|
||||
| { mode: 'one'; beneficiary: RegularizationBeneficiary }
|
||||
| { mode: 'selected'; beneficiaries: RegularizationBeneficiary[] }
|
||||
| { mode: 'all'; beneficiaries: RegularizationBeneficiary[] };
|
||||
|
||||
export function ReferralRegularizationPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [search, setSearch] = useState('');
|
||||
const [searchApplied, setSearchApplied] = useState('');
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
||||
const [confirm, setConfirm] = useState<ConfirmState | null>(null);
|
||||
const [allowPartial, setAllowPartial] = useState(false);
|
||||
const [lastResult, setLastResult] = useState<ApplyResult | null>(null);
|
||||
|
||||
const snapQ = useQuery({
|
||||
queryKey: ['admin', 'referral', 'regularization', searchApplied],
|
||||
queryFn: async () => {
|
||||
const qs = searchApplied ? `?search=${encodeURIComponent(searchApplied)}` : '';
|
||||
const res = await api.get<Snapshot>(`/api/v1/admin/referral/regularization${qs}`);
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
const applyMut = useMutation({
|
||||
mutationFn: async (body: {
|
||||
mode: 'one' | 'selected' | 'all';
|
||||
beneficiaryUserIds?: string[];
|
||||
allowPartial: boolean;
|
||||
}) => {
|
||||
const res = await api.post<ApplyResult>('/api/v1/admin/referral/regularization/apply', body);
|
||||
return res.data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
setLastResult(data);
|
||||
setConfirm(null);
|
||||
setSelected(new Set());
|
||||
void qc.invalidateQueries({ queryKey: ['admin', 'referral', 'regularization'] });
|
||||
},
|
||||
});
|
||||
|
||||
const beneficiaries = snapQ.data?.beneficiaries ?? [];
|
||||
const pool = BigInt(snapQ.data?.poolBalanceRaw ?? '0');
|
||||
const totalDue = BigInt(snapQ.data?.totalDueRaw ?? '0');
|
||||
const shortfall = BigInt(snapQ.data?.shortfallRaw ?? '0');
|
||||
|
||||
const confirmTotal = useMemo(() => {
|
||||
if (!confirm) return 0n;
|
||||
if (confirm.mode === 'one') return BigInt(confirm.beneficiary.amountDueRaw);
|
||||
return confirm.beneficiaries.reduce((acc, b) => acc + BigInt(b.amountDueRaw), 0n);
|
||||
}, [confirm]);
|
||||
|
||||
const confirmCount = useMemo(() => {
|
||||
if (!confirm) return 0;
|
||||
if (confirm.mode === 'one') return confirm.beneficiary.pendingCount;
|
||||
return confirm.beneficiaries.reduce((n, b) => n + b.pendingCount, 0);
|
||||
}, [confirm]);
|
||||
|
||||
const confirmBeneficiaryCount = useMemo(() => {
|
||||
if (!confirm) return 0;
|
||||
if (confirm.mode === 'one') return 1;
|
||||
return confirm.beneficiaries.length;
|
||||
}, [confirm]);
|
||||
|
||||
const confirmNeedsMore = confirmTotal > pool;
|
||||
const confirmShortfall = confirmNeedsMore ? confirmTotal - pool : 0n;
|
||||
|
||||
const toggleSelect = (id: string) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleExpand = (id: string) => {
|
||||
setExpanded((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const allSelected =
|
||||
beneficiaries.length > 0 && beneficiaries.every((b) => selected.has(b.beneficiaryUserId));
|
||||
|
||||
const selectedBeneficiaries = beneficiaries.filter((b) => selected.has(b.beneficiaryUserId));
|
||||
const selectedTotal = selectedBeneficiaries.reduce((acc, b) => acc + BigInt(b.amountDueRaw), 0n);
|
||||
|
||||
const openConfirm = (state: ConfirmState) => {
|
||||
setAllowPartial(false);
|
||||
setConfirm(state);
|
||||
};
|
||||
|
||||
const runApply = () => {
|
||||
if (!confirm) return;
|
||||
if (confirm.mode === 'one') {
|
||||
applyMut.mutate({
|
||||
mode: 'one',
|
||||
beneficiaryUserIds: [confirm.beneficiary.beneficiaryUserId],
|
||||
allowPartial,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (confirm.mode === 'selected') {
|
||||
applyMut.mutate({
|
||||
mode: 'selected',
|
||||
beneficiaryUserIds: confirm.beneficiaries.map((b) => b.beneficiaryUserId),
|
||||
allowPartial,
|
||||
});
|
||||
return;
|
||||
}
|
||||
applyMut.mutate({ mode: 'all', allowPartial });
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 2, flexWrap: 'wrap' }}>
|
||||
<AccountBalanceWalletRoundedIcon color="primary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, flex: 1 }}>
|
||||
{t('admin.referralRegularization.title')}
|
||||
</Typography>
|
||||
<Button component={RouterLink} to="/admin/referral" variant="outlined" size="small">
|
||||
{t('admin.referralRegularization.backToProgram')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
|
||||
{t('admin.referralRegularization.subtitle')}
|
||||
</Typography>
|
||||
|
||||
{snapQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
{t('admin.referralRegularization.loadError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{lastResult && (
|
||||
<Alert
|
||||
severity={lastResult.stoppedForInsufficientPool ? 'warning' : 'success'}
|
||||
onClose={() => setLastResult(null)}
|
||||
sx={{ mb: 2 }}
|
||||
>
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
|
||||
{lastResult.message}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
{t('admin.referralRegularization.resultSummary', {
|
||||
paid: lastResult.paidCount,
|
||||
amount: formatUsdt(lastResult.paidAmountRaw),
|
||||
remaining: lastResult.remainingCount,
|
||||
remainingAmount: formatUsdt(lastResult.remainingAmountRaw),
|
||||
shortfall: formatUsdt(lastResult.shortfallRaw),
|
||||
})}
|
||||
</Typography>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{applyMut.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }} onClose={() => applyMut.reset()}>
|
||||
{(applyMut.error as { response?: { data?: { error?: string } }; message?: string })?.response
|
||||
?.data?.error ||
|
||||
(applyMut.error as Error)?.message ||
|
||||
t('admin.referralRegularization.applyError')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<StatCard
|
||||
label={t('admin.referralRegularization.poolBalance')}
|
||||
value={formatUsdt(snapQ.data?.poolBalanceRaw ?? '0')}
|
||||
warn={pool < totalDue && totalDue > 0n}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<StatCard
|
||||
label={t('admin.referralRegularization.totalDue')}
|
||||
value={formatUsdt(snapQ.data?.totalDueRaw ?? '0')}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<StatCard
|
||||
label={t('admin.referralRegularization.shortfall')}
|
||||
value={formatUsdt(snapQ.data?.shortfallRaw ?? '0')}
|
||||
warn={shortfall > 0n}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12} sm={6} md={3}>
|
||||
<StatCard
|
||||
label={t('admin.referralRegularization.pendingPeople')}
|
||||
value={`${snapQ.data?.beneficiaryCount ?? 0} / ${snapQ.data?.pendingItemCount ?? 0}`}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5} sx={{ mb: 2, alignItems: { sm: 'center' } }}>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.referralRegularization.search')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') setSearchApplied(search.trim());
|
||||
}}
|
||||
sx={{ minWidth: 240, flex: 1 }}
|
||||
/>
|
||||
<Button variant="outlined" onClick={() => setSearchApplied(search.trim())}>
|
||||
{t('admin.referralRegularization.applySearch')}
|
||||
</Button>
|
||||
<PermissionGate permission="admin.referral.manage">
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={selectedBeneficiaries.length === 0}
|
||||
onClick={() => openConfirm({ mode: 'selected', beneficiaries: selectedBeneficiaries })}
|
||||
>
|
||||
{t('admin.referralRegularization.regularizeSelected', {
|
||||
count: selectedBeneficiaries.length,
|
||||
})}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
disabled={beneficiaries.length === 0}
|
||||
onClick={() => openConfirm({ mode: 'all', beneficiaries })}
|
||||
>
|
||||
{t('admin.referralRegularization.regularizeAll')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Stack>
|
||||
|
||||
{selectedBeneficiaries.length > 0 && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
{t('admin.referralRegularization.selectionSummary', {
|
||||
count: selectedBeneficiaries.length,
|
||||
amount: formatUsdt(selectedTotal.toString()),
|
||||
pool: formatUsdt(pool.toString()),
|
||||
})}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Card sx={{ borderRadius: 2 }}>
|
||||
<CardContent sx={{ p: 0, '&:last-child': { pb: 0 } }}>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell padding="checkbox">
|
||||
<Checkbox
|
||||
checked={allSelected}
|
||||
indeterminate={selected.size > 0 && !allSelected}
|
||||
onChange={() => {
|
||||
if (allSelected) setSelected(new Set());
|
||||
else setSelected(new Set(beneficiaries.map((b) => b.beneficiaryUserId)));
|
||||
}}
|
||||
disabled={beneficiaries.length === 0}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>{t('admin.referralRegularization.colBeneficiary')}</TableCell>
|
||||
<TableCell align="right">{t('admin.referralRegularization.colPending')}</TableCell>
|
||||
<TableCell align="right">{t('admin.referralRegularization.colAmount')}</TableCell>
|
||||
<TableCell>{t('admin.referralRegularization.colOldest')}</TableCell>
|
||||
<TableCell align="right">{t('admin.referralRegularization.colActions')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{snapQ.isLoading && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6}>
|
||||
<Typography color="text.secondary">{t('common.loading')}</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{!snapQ.isLoading && beneficiaries.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6}>
|
||||
<Typography color="text.secondary" sx={{ py: 2, px: 1 }}>
|
||||
{t('admin.referralRegularization.empty')}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
{beneficiaries.map((b) => {
|
||||
const open = expanded.has(b.beneficiaryUserId);
|
||||
return (
|
||||
<Fragment key={b.beneficiaryUserId}>
|
||||
<TableRow hover>
|
||||
<TableCell padding="checkbox">
|
||||
<Checkbox
|
||||
checked={selected.has(b.beneficiaryUserId)}
|
||||
onChange={() => toggleSelect(b.beneficiaryUserId)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Stack direction="row" spacing={0.5} alignItems="center">
|
||||
<IconButton size="small" onClick={() => toggleExpand(b.beneficiaryUserId)}>
|
||||
{open ? <ExpandLessRoundedIcon /> : <ExpandMoreRoundedIcon />}
|
||||
</IconButton>
|
||||
<Box>
|
||||
<Typography variant="body2" sx={{ fontWeight: 700 }}>
|
||||
{b.displayName}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
|
||||
{b.email || b.beneficiaryUserId}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Chip size="small" label={b.pendingCount} />
|
||||
</TableCell>
|
||||
<TableCell align="right" sx={{ fontWeight: 700 }}>
|
||||
{formatUsdt(b.amountDueRaw)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="caption">
|
||||
{new Date(b.oldestCreatedAt).toLocaleString()}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<PermissionGate permission="admin.referral.manage">
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onClick={() => openConfirm({ mode: 'one', beneficiary: b })}
|
||||
>
|
||||
{t('admin.referralRegularization.regularizeOne')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} sx={{ py: 0, borderBottom: open ? undefined : 'none' }}>
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<Box sx={{ py: 1, pl: 6 }}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.referralRegularization.colReferred')}</TableCell>
|
||||
<TableCell>Bet</TableCell>
|
||||
<TableCell>Lvl</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell align="right">%</TableCell>
|
||||
<TableCell align="right">
|
||||
{t('admin.referralRegularization.colAmount')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{b.items.map((it) => (
|
||||
<TableRow key={it.itemKey}>
|
||||
<TableCell>
|
||||
{it.referredDisplayName}
|
||||
<Typography variant="caption" display="block" color="text.secondary">
|
||||
{it.referredUserId.slice(0, 8)}…
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="caption">{it.betId.slice(0, 8)}…</Typography>
|
||||
</TableCell>
|
||||
<TableCell>{it.level}</TableCell>
|
||||
<TableCell>
|
||||
<Chip size="small" label={it.betStatus} />
|
||||
</TableCell>
|
||||
<TableCell align="right">{it.commissionPercent}</TableCell>
|
||||
<TableCell align="right">{formatUsdt(it.commissionAmountRaw)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Box>
|
||||
</Collapse>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={Boolean(confirm)} onClose={() => !applyMut.isPending && setConfirm(null)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{t('admin.referralRegularization.confirmTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
{confirm && (
|
||||
<Stack spacing={1.5} sx={{ pt: 1 }}>
|
||||
<Typography>
|
||||
{t('admin.referralRegularization.confirmBody', {
|
||||
people: confirmBeneficiaryCount,
|
||||
items: confirmCount,
|
||||
amount: formatUsdt(confirmTotal.toString()),
|
||||
pool: formatUsdt(pool.toString()),
|
||||
})}
|
||||
</Typography>
|
||||
{confirm.mode === 'one' && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{confirm.beneficiary.displayName} — {confirm.beneficiary.email || confirm.beneficiary.beneficiaryUserId}
|
||||
</Typography>
|
||||
)}
|
||||
{confirmNeedsMore && (
|
||||
<Alert severity="warning">
|
||||
{t('admin.referralRegularization.insufficientWarning', {
|
||||
shortfall: formatUsdt(confirmShortfall.toString()),
|
||||
})}
|
||||
</Alert>
|
||||
)}
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={allowPartial}
|
||||
onChange={(e) => setAllowPartial(e.target.checked)}
|
||||
disabled={!confirmNeedsMore}
|
||||
/>
|
||||
}
|
||||
label={t('admin.referralRegularization.allowPartial')}
|
||||
/>
|
||||
<Typography variant="caption" color="text.secondary">
|
||||
{t('admin.referralRegularization.fifoHint')}
|
||||
</Typography>
|
||||
</Stack>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setConfirm(null)} disabled={applyMut.isPending}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={applyMut.isPending || (confirmNeedsMore && !allowPartial)}
|
||||
onClick={runApply}
|
||||
>
|
||||
{applyMut.isPending
|
||||
? t('common.loading')
|
||||
: t('admin.referralRegularization.confirmAction')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@ -65,6 +65,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record<string, string> = {
|
||||
'/admin/approval-policies': 'admin.fund_operations.approve',
|
||||
'/admin/security': 'admin.security.view',
|
||||
'/admin/referral': 'admin.referral.view',
|
||||
'/admin/referral/regularization': 'admin.referral.view',
|
||||
'/admin/referral/fraud': 'admin.referral_fraud.view',
|
||||
'/admin/test-wallet': 'admin.test_wallet.view',
|
||||
'/admin/share-cards': 'admin.share_cards.view',
|
||||
@ -86,6 +87,7 @@ export const OPTIONS_CARD_PERMISSIONS: Record<string, string> = {
|
||||
// Visible to approvers too (session may predate approval_policy.* sync)
|
||||
approvalPolicies: 'admin.fund_operations.approve',
|
||||
referral: 'admin.referral.view',
|
||||
referralRegularization: 'admin.referral.view',
|
||||
referralFraud: 'admin.referral_fraud.view',
|
||||
testWallet: 'admin.test_wallet.view',
|
||||
shareCards: 'admin.share_cards.view',
|
||||
|
||||
@ -985,6 +985,7 @@ export const en = {
|
||||
coldHot: 'Cold / Hot',
|
||||
nOfM: 'N-of-M',
|
||||
levelsBonus: 'Levels / Bonus',
|
||||
missedPay: 'Missed payouts',
|
||||
sybilReview: 'Sybil / Review / Clawback',
|
||||
playMoney: 'Play money',
|
||||
soloBonus: 'Solo bonus',
|
||||
@ -1022,6 +1023,10 @@ export const en = {
|
||||
title: 'Referral program',
|
||||
description: 'Multi-level commissions, bonus pool, eligibility rules, and signup analytics.',
|
||||
},
|
||||
referralRegularization: {
|
||||
title: 'Commission regularization',
|
||||
description: 'Find missed prediction commissions and pay referrers after funding the bonus pool.',
|
||||
},
|
||||
referralFraud: {
|
||||
title: 'Referral fraud dashboard',
|
||||
description: 'Review queue, high-risk referrers, monthly caps, and commission clawbacks.',
|
||||
@ -2279,6 +2284,7 @@ export const en = {
|
||||
},
|
||||
referralAdmin: {
|
||||
title: 'Referral program',
|
||||
regularization: 'Commission regularization',
|
||||
fraudDashboard: 'Fraud dashboard',
|
||||
loadError: 'Failed to load referral configuration.',
|
||||
fundPending: 'Bonus pool funding submitted — pending super-admin approval',
|
||||
@ -2398,6 +2404,43 @@ export const en = {
|
||||
code: 'Code',
|
||||
commission: 'Commission',
|
||||
},
|
||||
referralRegularization: {
|
||||
title: 'Commission regularization',
|
||||
subtitle:
|
||||
'Eligible prediction commissions that were never paid (e.g. empty bonus pool). Paid commissions never appear here again.',
|
||||
backToProgram: 'Referral settings',
|
||||
loadError: 'Failed to load regularization queue.',
|
||||
applyError: 'Regularization failed.',
|
||||
poolBalance: 'Bonus pool available',
|
||||
totalDue: 'Total due (eligible)',
|
||||
shortfall: 'Extra funding needed',
|
||||
pendingPeople: 'Beneficiaries / items',
|
||||
search: 'Search beneficiary, email, id…',
|
||||
applySearch: 'Search',
|
||||
regularizeOne: 'Regularize',
|
||||
regularizeSelected: 'Regularize selected ({{count}})',
|
||||
regularizeAll: 'Regularize all',
|
||||
selectionSummary: '{{count}} selected — {{amount}} due (pool {{pool}})',
|
||||
colBeneficiary: 'Beneficiary (referrer)',
|
||||
colPending: 'Items',
|
||||
colAmount: 'Amount due',
|
||||
colOldest: 'Oldest pending',
|
||||
colActions: 'Actions',
|
||||
colReferred: 'Referred user',
|
||||
empty: 'No missed prediction commissions. Everything is up to date.',
|
||||
confirmTitle: 'Confirm regularization',
|
||||
confirmBody:
|
||||
'{{people}} beneficiary(ies), {{items}} commission(s), total {{amount}}. Pool available: {{pool}}.',
|
||||
insufficientWarning:
|
||||
'Insufficient bonus pool. Shortfall: {{shortfall}}. Fund the pool or enable partial FIFO payment.',
|
||||
allowPartial:
|
||||
'Allow partial regularization (oldest first; stop when the next full commission does not fit)',
|
||||
fifoHint:
|
||||
'Order: oldest bet first, then level. A commission is never reduced to fit the pool. Already-paid items are skipped.',
|
||||
confirmAction: 'Confirm payment',
|
||||
resultSummary:
|
||||
'Paid {{paid}} ({{amount}}). Remaining {{remaining}} ({{remainingAmount}}). Extra funding needed: {{shortfall}}.',
|
||||
},
|
||||
referralFraud: {
|
||||
title: 'Referral fraud dashboard',
|
||||
programSettings: 'Program settings',
|
||||
|
||||
@ -999,6 +999,7 @@ export const fr = {
|
||||
coldHot: 'Froid / Chaud',
|
||||
nOfM: 'N-sur-M',
|
||||
levelsBonus: 'Niveaux / Bonus',
|
||||
missedPay: 'Paiements manqués',
|
||||
sybilReview: 'Sybil / Revue / Récupération',
|
||||
playMoney: 'Argent fictif',
|
||||
soloBonus: 'Bonus solo',
|
||||
@ -1036,6 +1037,11 @@ export const fr = {
|
||||
title: 'Programme de parrainage',
|
||||
description: 'Commissions multi-niveaux, pool bonus, règles d’éligibilité et statistiques d’inscription.',
|
||||
},
|
||||
referralRegularization: {
|
||||
title: 'Régularisation des commissions',
|
||||
description:
|
||||
'Retrouver les commissions prédiction manquées et payer les parrains après avoir alimenté le pool bonus.',
|
||||
},
|
||||
referralFraud: {
|
||||
title: 'Tableau de bord fraude parrainage',
|
||||
description: 'File de revue, parrains à risque, plafonds mensuels et récupérations de commissions.',
|
||||
@ -2299,6 +2305,7 @@ export const fr = {
|
||||
},
|
||||
referralAdmin: {
|
||||
title: 'Programme de parrainage',
|
||||
regularization: 'Régularisation des commissions',
|
||||
fraudDashboard: 'Tableau de bord fraude',
|
||||
loadError: 'Impossible de charger la configuration parrainage.',
|
||||
fundPending: 'Alimentation du pool bonus soumise — en attente d’approbation super-admin',
|
||||
@ -2421,6 +2428,43 @@ export const fr = {
|
||||
code: 'Code',
|
||||
commission: 'Commission',
|
||||
},
|
||||
referralRegularization: {
|
||||
title: 'Régularisation des commissions',
|
||||
subtitle:
|
||||
'Commissions prédiction éligibles jamais payées (ex. pool bonus vide). Les commissions déjà payées n’apparaissent plus ici.',
|
||||
backToProgram: 'Paramètres parrainage',
|
||||
loadError: 'Impossible de charger la file de régularisation.',
|
||||
applyError: 'Échec de la régularisation.',
|
||||
poolBalance: 'Pool bonus disponible',
|
||||
totalDue: 'Total dû (éligible)',
|
||||
shortfall: 'Financement supplémentaire requis',
|
||||
pendingPeople: 'Bénéficiaires / éléments',
|
||||
search: 'Rechercher bénéficiaire, e-mail, id…',
|
||||
applySearch: 'Rechercher',
|
||||
regularizeOne: 'Régulariser',
|
||||
regularizeSelected: 'Régulariser la sélection ({{count}})',
|
||||
regularizeAll: 'Tout régulariser',
|
||||
selectionSummary: '{{count}} sélectionné(s) — {{amount}} dû (pool {{pool}})',
|
||||
colBeneficiary: 'Bénéficiaire (parrain)',
|
||||
colPending: 'Éléments',
|
||||
colAmount: 'Montant dû',
|
||||
colOldest: 'Plus ancien',
|
||||
colActions: 'Actions',
|
||||
colReferred: 'Filleul',
|
||||
empty: 'Aucune commission prédiction manquante. Tout est à jour.',
|
||||
confirmTitle: 'Confirmer la régularisation',
|
||||
confirmBody:
|
||||
'{{people}} bénéficiaire(s), {{items}} commission(s), total {{amount}}. Pool disponible : {{pool}}.',
|
||||
insufficientWarning:
|
||||
'Pool bonus insuffisant. Manque : {{shortfall}}. Alimentez le pool ou activez le paiement partiel FIFO.',
|
||||
allowPartial:
|
||||
'Autoriser une régularisation partielle (plus ancien d’abord ; arrêt si la prochaine commission entière ne passe pas)',
|
||||
fifoHint:
|
||||
'Ordre : paris les plus anciens, puis niveau. Une commission n’est jamais réduite pour tenir dans le pool. Les éléments déjà payés sont ignorés.',
|
||||
confirmAction: 'Confirmer le paiement',
|
||||
resultSummary:
|
||||
'Payé {{paid}} ({{amount}}). Restant {{remaining}} ({{remainingAmount}}). Financement manquant : {{shortfall}}.',
|
||||
},
|
||||
referralFraud: {
|
||||
title: 'Tableau de bord fraude parrainage',
|
||||
programSettings: 'Paramètres du programme',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user