954 lines
44 KiB
JavaScript
954 lines
44 KiB
JavaScript
"use strict";
|
|
/**
|
|
* Referral program: registration resolution, deferred first-deposit commissions, admin config.
|
|
*/
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || (function () {
|
|
var ownKeys = function(o) {
|
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
var ar = [];
|
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
return ar;
|
|
};
|
|
return ownKeys(o);
|
|
};
|
|
return function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.ReferralError = void 0;
|
|
exports.evaluateReferralCommissionEligibility = evaluateReferralCommissionEligibility;
|
|
exports.isCommissionPendingExpired = isCommissionPendingExpired;
|
|
exports.validateReferralCode = validateReferralCode;
|
|
exports.resolveReferrerId = resolveReferrerId;
|
|
exports.bootstrapReferralRootAtPlatformSetup = bootstrapReferralRootAtPlatformSetup;
|
|
exports.assertReferrerEligible = assertReferrerEligible;
|
|
exports.processFirstDepositReferralCommissions = processFirstDepositReferralCommissions;
|
|
exports.processWithdrawalReferralCommissions = processWithdrawalReferralCommissions;
|
|
exports.getUserReferralDashboard = getUserReferralDashboard;
|
|
exports.getUserReferralCommissions = getUserReferralCommissions;
|
|
exports.processPendingReferralCommissions = processPendingReferralCommissions;
|
|
exports.listReferralReviewQueue = listReferralReviewQueue;
|
|
exports.approveReferralCommissionReview = approveReferralCommissionReview;
|
|
exports.rejectReferralCommissionReview = rejectReferralCommissionReview;
|
|
exports.getReferralCommissionPollIntervalMs = getReferralCommissionPollIntervalMs;
|
|
exports.clawbackReferralCommission = clawbackReferralCommission;
|
|
exports.getReferralFraudDashboard = getReferralFraudDashboard;
|
|
exports.getUserReferralInfo = getUserReferralInfo;
|
|
exports.getProgramSettingsForAdmin = getProgramSettingsForAdmin;
|
|
const referralRepository = __importStar(require("../repositories/referralRepository"));
|
|
const bonusPoolRepository = __importStar(require("../repositories/bonusPoolRepository"));
|
|
const ledgerRepository = __importStar(require("../repositories/ledgerRepository"));
|
|
const userRepository = __importStar(require("../repositories/userRepository"));
|
|
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
|
|
const connection_1 = require("../db/connection");
|
|
const userAdminStatsService_1 = require("./userAdminStatsService");
|
|
const securityService_1 = require("./securityService");
|
|
const referralSybilService_1 = require("./referralSybilService");
|
|
const referralCapService_1 = require("./referralCapService");
|
|
const referralNotificationService_1 = require("./referralNotificationService");
|
|
const referralWithdrawalCommissionService_1 = require("./referralWithdrawalCommissionService");
|
|
const countryFormat_1 = require("../utils/countryFormat");
|
|
const fraudAutoBlockService_1 = require("./fraudAutoBlockService");
|
|
class ReferralError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.name = 'ReferralError';
|
|
}
|
|
}
|
|
exports.ReferralError = ReferralError;
|
|
function evaluateReferralCommissionEligibility(input) {
|
|
const reasons = [];
|
|
if (!input.referredIsEnabled)
|
|
reasons.push('referred_user_disabled');
|
|
if (input.referredUnderSurveillance)
|
|
reasons.push('referred_user_under_surveillance');
|
|
if (input.settings.referred_must_be_verified && !input.referredEmailVerified) {
|
|
reasons.push('referred_email_not_verified');
|
|
}
|
|
if (input.referredRealPredictionCount < input.settings.min_referred_predictions) {
|
|
reasons.push('insufficient_referred_predictions');
|
|
}
|
|
if (!input.beneficiaryIsEnabled)
|
|
reasons.push('beneficiary_disabled');
|
|
if (input.beneficiaryUnderSurveillance)
|
|
reasons.push('beneficiary_under_surveillance');
|
|
if (input.settings.referrer_must_be_verified && !input.beneficiaryEmailVerified) {
|
|
reasons.push('beneficiary_email_not_verified');
|
|
}
|
|
if (input.settings.referrer_must_have_deposited && !input.beneficiaryHasDeposited) {
|
|
reasons.push('beneficiary_no_deposit');
|
|
}
|
|
return { eligible: reasons.length === 0, reasons };
|
|
}
|
|
function isCommissionPendingExpired(createdAt, maxPendingDays, now = new Date()) {
|
|
const expiresAt = createdAt.getTime() + maxPendingDays * 24 * 60 * 60 * 1000;
|
|
return now.getTime() >= expiresAt;
|
|
}
|
|
async function validateReferralCode(code) {
|
|
const trimmed = code?.trim();
|
|
if (!trimmed)
|
|
return { valid: false };
|
|
const referrer = await referralRepository.findUserByReferralCode(trimmed);
|
|
if (!referrer)
|
|
return { valid: false };
|
|
return { valid: true, referrerId: referrer.id };
|
|
}
|
|
async function resolveReferrerId(referralCode) {
|
|
const settings = await referralRepository.getSettings();
|
|
if (!settings.enabled)
|
|
return null;
|
|
const trimmed = referralCode?.trim();
|
|
if (trimmed) {
|
|
const referrer = await referralRepository.findUserByReferralCode(trimmed);
|
|
if (referrer)
|
|
return referrer.id;
|
|
}
|
|
return settings.default_referrer_user_id;
|
|
}
|
|
/**
|
|
* Bootstraps the referral network root during initial platform setup.
|
|
* Assigns a unique referral code to the super admin and sets them as the default referrer.
|
|
*/
|
|
async function bootstrapReferralRootAtPlatformSetup(superAdminUserId) {
|
|
const referralCode = await referralRepository.ensureUserReferralCode(superAdminUserId);
|
|
await referralRepository.updateSettings({ defaultReferrerUserId: superAdminUserId });
|
|
return referralCode;
|
|
}
|
|
async function assertReferrerEligible(referrerId) {
|
|
const settings = await referralRepository.getSettings();
|
|
const referrer = await userRepository.findById(referrerId);
|
|
if (!referrer || !referrer.is_enabled) {
|
|
throw new ReferralError('Referrer account is not eligible');
|
|
}
|
|
if (referrer.under_surveillance) {
|
|
throw new ReferralError('Referrer account is not eligible');
|
|
}
|
|
if (settings.referrer_must_be_verified && !referrer.email_verified) {
|
|
throw new ReferralError('Referrer must have a verified email');
|
|
}
|
|
if (settings.referrer_must_have_deposited) {
|
|
const isDefaultRoot = settings.default_referrer_user_id === referrerId;
|
|
const hasDeposit = await referralRepository.beneficiaryHasCompletedDeposit(referrerId);
|
|
if (!hasDeposit && !isDefaultRoot) {
|
|
throw new ReferralError('Referrer must have completed at least one deposit');
|
|
}
|
|
}
|
|
try {
|
|
await (0, referralSybilService_1.assertReferralChainHasNoLoop)(referrerId);
|
|
}
|
|
catch {
|
|
throw new ReferralError('Referrer account is not eligible');
|
|
}
|
|
}
|
|
function calcCommission(depositAmount, percent) {
|
|
return (depositAmount * BigInt(Math.round(percent * 10000))) / 1000000n;
|
|
}
|
|
function addDays(from, days) {
|
|
return new Date(from.getTime() + days * 24 * 60 * 60 * 1000);
|
|
}
|
|
async function evaluateSybilForCommission(settings, beneficiaryUserId, referredUserId) {
|
|
if (!settings.sybil_detection_enabled) {
|
|
return { score: 0, signals: [], disposition: 'pending' };
|
|
}
|
|
const sybil = await (0, referralSybilService_1.detectReferralSybilSignals)({
|
|
beneficiaryUserId,
|
|
referredUserId,
|
|
maxReferralsPerDay: settings.max_referrals_per_day,
|
|
});
|
|
const disposition = (0, referralSybilService_1.resolveCommissionStatusFromSybilScore)(sybil.score, {
|
|
review: settings.sybil_review_threshold,
|
|
block: settings.sybil_block_threshold,
|
|
});
|
|
return { ...sybil, disposition };
|
|
}
|
|
async function notifyReviewRequired(payoutId, beneficiaryUserId, referredUserId, sybilScore, signals) {
|
|
await (0, securityService_1.raiseAlert)({
|
|
userId: beneficiaryUserId,
|
|
severity: sybilScore >= 5 ? 'high' : 'medium',
|
|
alertType: 'referral_commission_review',
|
|
title: 'Referral commission requires manual review',
|
|
details: `Commission ${payoutId} flagged for review (Sybil score ${sybilScore}).`,
|
|
metadata: {
|
|
payout_id: payoutId,
|
|
referred_user_id: referredUserId,
|
|
sybil_score: sybilScore,
|
|
sybil_signals: signals,
|
|
},
|
|
});
|
|
}
|
|
async function getEffectiveMonthlyCaps(settings, levelNumber) {
|
|
const global = {
|
|
maxAmountRaw: BigInt(settings.max_commission_amount_per_referrer_month_raw),
|
|
maxCount: settings.max_commissions_per_referrer_month,
|
|
};
|
|
const level = await referralRepository.getLevelByNumber(levelNumber);
|
|
return (0, referralCapService_1.resolveEffectiveLevelCaps)(global, level
|
|
? {
|
|
monthlyMaxAmountRaw: level.monthly_max_amount_raw,
|
|
monthlyMaxCount: level.monthly_max_count,
|
|
}
|
|
: null);
|
|
}
|
|
async function isMonthlyCapExceeded(beneficiaryUserId, additionalAmount, settings, levelNumber) {
|
|
const caps = await getEffectiveMonthlyCaps(settings, levelNumber);
|
|
const stats = await referralRepository.getBeneficiaryMonthlyCommissionStats(beneficiaryUserId, caps.source === 'level' ? levelNumber : undefined);
|
|
const result = (0, referralCapService_1.wouldExceedMonthlyCommissionCap)({
|
|
currentReservedAmount: stats.reservedAmount,
|
|
currentReservedCount: stats.reservedCount,
|
|
newCommissionAmount: additionalAmount,
|
|
maxAmountRaw: caps.maxAmountRaw,
|
|
maxCount: caps.maxCount,
|
|
});
|
|
return { ...result, capSource: caps.source };
|
|
}
|
|
async function logCapBlocked(beneficiaryUserId, referredUserId, amount, reason, levelNumber, capSource, resourceId) {
|
|
await auditLogRepository.create({
|
|
userId: beneficiaryUserId,
|
|
action: 'referral_commission_cap_blocked',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: resourceId ?? null,
|
|
metadata: {
|
|
referred_user_id: referredUserId,
|
|
amount: amount.toString(),
|
|
cap_reason: reason,
|
|
level_number: levelNumber,
|
|
cap_source: capSource,
|
|
},
|
|
});
|
|
void (0, referralNotificationService_1.notifyReferralSlack)({
|
|
title: 'Referral commission blocked (monthly cap)',
|
|
severity: 'medium',
|
|
alertType: 'referral_commission_cap_blocked',
|
|
userId: beneficiaryUserId,
|
|
details: `Level ${levelNumber} cap (${capSource}): ${reason}. Amount: ${amount.toString()} raw.`,
|
|
metadata: {
|
|
referred_user_id: referredUserId,
|
|
level_number: levelNumber,
|
|
cap_source: capSource,
|
|
cap_reason: reason,
|
|
},
|
|
});
|
|
}
|
|
/**
|
|
* Creates pending multi-level referral commissions on a user's first deposit.
|
|
* Pool funds are reserved immediately; bonus wallet credit happens after the hold period.
|
|
*/
|
|
async function processFirstDepositReferralCommissions(input) {
|
|
const settings = await referralRepository.getSettings();
|
|
if (!settings.enabled || !settings.deposit_commissions_enabled)
|
|
return;
|
|
const userRows = await (0, connection_1.query)('SELECT first_deposit_at, referred_by_user_id FROM users WHERE id = $1', [input.userId]);
|
|
const user = userRows[0];
|
|
if (!user || user.first_deposit_at)
|
|
return;
|
|
if (!user.referred_by_user_id)
|
|
return;
|
|
const minDeposit = BigInt(settings.min_first_deposit_raw);
|
|
if (input.depositAmount < minDeposit) {
|
|
await markFirstDeposit(input.userId, input.depositTransactionId);
|
|
return;
|
|
}
|
|
const commissionWalletTypeId = settings.commission_wallet_type_id;
|
|
if (input.walletTypeId !== commissionWalletTypeId) {
|
|
await markFirstDeposit(input.userId, input.depositTransactionId);
|
|
return;
|
|
}
|
|
const levels = (await referralRepository.listLevels()).filter((l) => l.is_active);
|
|
if (levels.length === 0) {
|
|
await markFirstDeposit(input.userId, input.depositTransactionId);
|
|
return;
|
|
}
|
|
const maxLevel = Math.max(...levels.map((l) => l.level_number));
|
|
const chain = await referralRepository.getReferralChain(input.userId, maxLevel);
|
|
const eligibleAt = addDays(new Date(), settings.commission_hold_days);
|
|
for (const { userId: beneficiaryId, level } of chain) {
|
|
const levelConfig = levels.find((l) => l.level_number === level);
|
|
if (!levelConfig)
|
|
continue;
|
|
const percent = Number(levelConfig.commission_percent);
|
|
if (percent <= 0)
|
|
continue;
|
|
const commissionAmount = calcCommission(input.depositAmount, percent);
|
|
if (commissionAmount <= 0n)
|
|
continue;
|
|
const sybil = await evaluateSybilForCommission(settings, beneficiaryId, input.userId);
|
|
if (sybil.disposition === 'blocked') {
|
|
await auditLogRepository.create({
|
|
userId: beneficiaryId,
|
|
action: 'referral_commission_blocked',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: input.depositTransactionId,
|
|
metadata: {
|
|
referred_user_id: input.userId,
|
|
level,
|
|
amount: commissionAmount.toString(),
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
await (0, securityService_1.raiseAlert)({
|
|
userId: beneficiaryId,
|
|
severity: 'high',
|
|
alertType: 'referral_commission_blocked',
|
|
title: 'Referral commission blocked (Sybil score)',
|
|
details: `Auto-blocked commission for referred user ${input.userId}. Score: ${sybil.score}.`,
|
|
metadata: {
|
|
referred_user_id: input.userId,
|
|
level,
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
void (0, fraudAutoBlockService_1.maybeAutoSuspendForSybilFraud)(beneficiaryId, sybil.score, sybil.signals, {
|
|
referredUserId: input.userId,
|
|
}).catch((e) => console.error('[referral] sybil auto-suspend failed:', e));
|
|
continue;
|
|
}
|
|
const cap = await isMonthlyCapExceeded(beneficiaryId, commissionAmount, settings, level);
|
|
if (cap.exceeded) {
|
|
await logCapBlocked(beneficiaryId, input.userId, commissionAmount, cap.reason, level, cap.capSource ?? 'global', input.depositTransactionId);
|
|
continue;
|
|
}
|
|
const debited = await bonusPoolRepository.debitPool(commissionWalletTypeId, commissionAmount);
|
|
if (!debited) {
|
|
console.error(`[referral] Insufficient bonus pool for level ${level} pending commission to ${beneficiaryId}`);
|
|
continue;
|
|
}
|
|
const initialStatus = sybil.disposition === 'review' ? 'review' : 'pending';
|
|
const payoutId = await referralRepository.recordCommissionPayout({
|
|
beneficiaryUserId: beneficiaryId,
|
|
referredUserId: input.userId,
|
|
levelNumber: level,
|
|
commissionSource: 'deposit',
|
|
firstDepositTransactionId: input.depositTransactionId,
|
|
baseAmount: input.depositAmount,
|
|
commissionPercent: percent,
|
|
commissionAmount,
|
|
walletTypeId: commissionWalletTypeId,
|
|
status: initialStatus,
|
|
eligibleAt,
|
|
sybilScore: sybil.score,
|
|
sybilSignals: sybil.signals,
|
|
});
|
|
if (!payoutId) {
|
|
await bonusPoolRepository.creditPool(commissionWalletTypeId, commissionAmount);
|
|
continue;
|
|
}
|
|
await auditLogRepository.create({
|
|
userId: beneficiaryId,
|
|
action: initialStatus === 'review' ? 'referral_commission_review' : 'referral_commission_pending',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: payoutId,
|
|
metadata: {
|
|
referred_user_id: input.userId,
|
|
level,
|
|
amount: commissionAmount.toString(),
|
|
deposit_transaction_id: input.depositTransactionId,
|
|
eligible_at: eligibleAt.toISOString(),
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
if (initialStatus === 'review') {
|
|
await notifyReviewRequired(payoutId, beneficiaryId, input.userId, sybil.score, sybil.signals);
|
|
}
|
|
}
|
|
await markFirstDeposit(input.userId, input.depositTransactionId);
|
|
}
|
|
/**
|
|
* Creates pending multi-level referral commissions on withdrawal.
|
|
* Base = commissionable prediction gains (main account), not deposited principal.
|
|
*/
|
|
async function processWithdrawalReferralCommissions(input) {
|
|
const settings = await referralRepository.getSettings();
|
|
if (!settings.enabled || !settings.withdrawal_commissions_enabled)
|
|
return;
|
|
const userRows = await (0, connection_1.query)('SELECT referred_by_user_id FROM users WHERE id = $1', [input.userId]);
|
|
const user = userRows[0];
|
|
if (!user?.referred_by_user_id)
|
|
return;
|
|
if (input.walletTypeId !== settings.commission_wallet_type_id)
|
|
return;
|
|
const [netProfit, alreadyCommissioned] = await Promise.all([
|
|
referralRepository.getMainAccountPredictionNetProfit(input.userId),
|
|
referralRepository.getWithdrawalGainsAlreadyCommissioned(input.userId),
|
|
]);
|
|
const commissionBase = (0, referralWithdrawalCommissionService_1.computeCommissionableWithdrawalBase)({
|
|
netMainPredictionProfit: netProfit,
|
|
alreadyCommissionedGains: alreadyCommissioned,
|
|
withdrawalAmount: input.withdrawalAmount,
|
|
});
|
|
if (commissionBase <= 0n)
|
|
return;
|
|
const levels = (await referralRepository.listLevels()).filter((l) => l.is_active);
|
|
if (levels.length === 0)
|
|
return;
|
|
const maxLevel = Math.max(...levels.map((l) => l.level_number));
|
|
const chain = await referralRepository.getReferralChain(input.userId, maxLevel);
|
|
const eligibleAt = addDays(new Date(), settings.commission_hold_days);
|
|
const commissionWalletTypeId = settings.commission_wallet_type_id;
|
|
for (const { userId: beneficiaryId, level } of chain) {
|
|
const levelConfig = levels.find((l) => l.level_number === level);
|
|
if (!levelConfig)
|
|
continue;
|
|
const percent = Number(levelConfig.commission_percent);
|
|
if (percent <= 0)
|
|
continue;
|
|
const commissionAmount = calcCommission(commissionBase, percent);
|
|
if (commissionAmount <= 0n)
|
|
continue;
|
|
const sybil = await evaluateSybilForCommission(settings, beneficiaryId, input.userId);
|
|
if (sybil.disposition === 'blocked') {
|
|
await auditLogRepository.create({
|
|
userId: beneficiaryId,
|
|
action: 'referral_commission_blocked',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: input.withdrawalTransactionId,
|
|
metadata: {
|
|
referred_user_id: input.userId,
|
|
level,
|
|
amount: commissionAmount.toString(),
|
|
commission_source: 'withdrawal',
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
await (0, securityService_1.raiseAlert)({
|
|
userId: beneficiaryId,
|
|
severity: 'high',
|
|
alertType: 'referral_commission_blocked',
|
|
title: 'Referral commission blocked (Sybil score)',
|
|
details: `Auto-blocked withdrawal commission for referred user ${input.userId}. Score: ${sybil.score}.`,
|
|
metadata: {
|
|
referred_user_id: input.userId,
|
|
level,
|
|
commission_source: 'withdrawal',
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
void (0, fraudAutoBlockService_1.maybeAutoSuspendForSybilFraud)(beneficiaryId, sybil.score, sybil.signals, {
|
|
referredUserId: input.userId,
|
|
}).catch((e) => console.error('[referral] sybil auto-suspend failed:', e));
|
|
continue;
|
|
}
|
|
const cap = await isMonthlyCapExceeded(beneficiaryId, commissionAmount, settings, level);
|
|
if (cap.exceeded) {
|
|
await logCapBlocked(beneficiaryId, input.userId, commissionAmount, cap.reason, level, cap.capSource ?? 'global', input.withdrawalTransactionId);
|
|
continue;
|
|
}
|
|
const debited = await bonusPoolRepository.debitPool(commissionWalletTypeId, commissionAmount);
|
|
if (!debited) {
|
|
console.error(`[referral] Insufficient bonus pool for level ${level} withdrawal commission to ${beneficiaryId}`);
|
|
continue;
|
|
}
|
|
const initialStatus = sybil.disposition === 'review' ? 'review' : 'pending';
|
|
const payoutId = await referralRepository.recordCommissionPayout({
|
|
beneficiaryUserId: beneficiaryId,
|
|
referredUserId: input.userId,
|
|
levelNumber: level,
|
|
commissionSource: 'withdrawal',
|
|
withdrawalTransactionId: input.withdrawalTransactionId,
|
|
baseAmount: commissionBase,
|
|
commissionPercent: percent,
|
|
commissionAmount,
|
|
walletTypeId: commissionWalletTypeId,
|
|
status: initialStatus,
|
|
eligibleAt,
|
|
sybilScore: sybil.score,
|
|
sybilSignals: sybil.signals,
|
|
});
|
|
if (!payoutId) {
|
|
await bonusPoolRepository.creditPool(commissionWalletTypeId, commissionAmount);
|
|
continue;
|
|
}
|
|
await auditLogRepository.create({
|
|
userId: beneficiaryId,
|
|
action: initialStatus === 'review' ? 'referral_commission_review' : 'referral_commission_pending',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: payoutId,
|
|
metadata: {
|
|
referred_user_id: input.userId,
|
|
level,
|
|
amount: commissionAmount.toString(),
|
|
commission_source: 'withdrawal',
|
|
withdrawal_transaction_id: input.withdrawalTransactionId,
|
|
commission_base: commissionBase.toString(),
|
|
eligible_at: eligibleAt.toISOString(),
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
if (initialStatus === 'review') {
|
|
await notifyReviewRequired(payoutId, beneficiaryId, input.userId, sybil.score, sybil.signals);
|
|
}
|
|
}
|
|
}
|
|
function mapReferralNetworkMember(row, countryMap) {
|
|
let status = 'registered';
|
|
if (!row.email_verified)
|
|
status = 'unverified';
|
|
else if (row.first_deposit_at)
|
|
status = 'active';
|
|
return {
|
|
userId: row.user_id,
|
|
parentUserId: row.parent_user_id,
|
|
levelNumber: row.level_number,
|
|
displayName: referralRepository.formatUserDisplayName(row.first_name, row.last_name, row.user_id),
|
|
referralCode: row.referral_code,
|
|
countryOfResidence: row.country_of_residence,
|
|
countryName: row.country_of_residence
|
|
? (0, countryFormat_1.formatCountryCode)(row.country_of_residence, countryMap) || null
|
|
: null,
|
|
registeredAt: row.created_at.toISOString(),
|
|
firstDepositAt: row.first_deposit_at?.toISOString() ?? null,
|
|
emailVerified: row.email_verified,
|
|
status,
|
|
directReferralsCount: Number(row.direct_referrals_count),
|
|
realPredictionsCount: Number(row.real_predictions_count),
|
|
commissionsGeneratedRaw: row.commissions_generated_raw,
|
|
commissionsPaidRaw: row.commissions_paid_raw,
|
|
commissionsPendingRaw: row.commissions_pending_raw,
|
|
};
|
|
}
|
|
async function getUserReferralDashboard(userId, maxDepth = 5) {
|
|
const settings = await referralRepository.getSettings();
|
|
const activeLevels = (await referralRepository.listLevels()).filter((l) => l.is_active);
|
|
const maxActiveLevel = activeLevels.length > 0 ? Math.max(...activeLevels.map((l) => l.level_number)) : 1;
|
|
const depth = Math.min(Math.max(1, maxDepth), Math.max(maxActiveLevel, 1), 10);
|
|
const [meInfo, referrer, summary, networkRows, countryMap] = await Promise.all([
|
|
getUserReferralInfo(userId),
|
|
referralRepository.getReferrerProfile(userId),
|
|
referralRepository.getBeneficiaryCommissionSummary(userId),
|
|
referralRepository.getReferralDownline(userId, depth),
|
|
(0, countryFormat_1.getCountryNameMap)(),
|
|
]);
|
|
return {
|
|
...meInfo,
|
|
programEnabled: settings.enabled,
|
|
commissionModes: {
|
|
depositEnabled: settings.deposit_commissions_enabled,
|
|
withdrawalEnabled: settings.withdrawal_commissions_enabled,
|
|
},
|
|
levels: activeLevels.map((l) => ({
|
|
levelNumber: l.level_number,
|
|
commissionPercent: Number(l.commission_percent),
|
|
})),
|
|
maxNetworkDepth: depth,
|
|
referrer: referrer
|
|
? {
|
|
displayName: referralRepository.formatUserDisplayName(referrer.firstName, referrer.lastName, referrer.userId),
|
|
referralCode: referrer.referralCode,
|
|
memberSince: referrer.createdAt.toISOString(),
|
|
}
|
|
: null,
|
|
summary: {
|
|
networkSize: summary.networkSize,
|
|
totalEarnedRaw: summary.totalEarnedRaw.toString(),
|
|
paidRaw: summary.paidRaw.toString(),
|
|
pendingRaw: summary.pendingRaw.toString(),
|
|
reviewRaw: summary.reviewRaw.toString(),
|
|
payoutCount: summary.payoutCount,
|
|
},
|
|
network: networkRows.map((row) => mapReferralNetworkMember(row, countryMap)),
|
|
};
|
|
}
|
|
async function getUserReferralCommissions(userId, opts) {
|
|
const result = await referralRepository.listBeneficiaryCommissions(userId, opts);
|
|
return {
|
|
total: result.total,
|
|
items: result.items.map((item) => ({
|
|
id: item.id,
|
|
referredUserId: item.referredUserId,
|
|
referredDisplayName: item.referredDisplayName,
|
|
levelNumber: item.levelNumber,
|
|
commissionSource: item.commissionSource,
|
|
baseAmountRaw: item.baseAmount,
|
|
commissionAmountRaw: item.commissionAmount,
|
|
commissionPercent: Number(item.commissionPercent),
|
|
status: item.status,
|
|
eligibleAt: item.eligibleAt.toISOString(),
|
|
paidAt: item.paidAt?.toISOString() ?? null,
|
|
createdAt: item.createdAt.toISOString(),
|
|
})),
|
|
};
|
|
}
|
|
async function loadEligibilityContext(payout, settings) {
|
|
const [referred, beneficiary, predictionCount, beneficiaryHasDeposited] = await Promise.all([
|
|
userRepository.findById(payout.referred_user_id),
|
|
userRepository.findById(payout.beneficiary_user_id),
|
|
referralRepository.countReferredUserRealPredictions(payout.referred_user_id),
|
|
referralRepository.beneficiaryHasCompletedDeposit(payout.beneficiary_user_id),
|
|
]);
|
|
return {
|
|
referredEmailVerified: referred?.email_verified ?? false,
|
|
referredIsEnabled: referred?.is_enabled ?? false,
|
|
referredUnderSurveillance: referred?.under_surveillance ?? true,
|
|
referredRealPredictionCount: predictionCount,
|
|
beneficiaryIsEnabled: beneficiary?.is_enabled ?? false,
|
|
beneficiaryUnderSurveillance: beneficiary?.under_surveillance ?? true,
|
|
beneficiaryEmailVerified: beneficiary?.email_verified ?? false,
|
|
beneficiaryHasDeposited,
|
|
settings,
|
|
};
|
|
}
|
|
async function payPendingCommission(payout, settings) {
|
|
const programSettings = settings ?? (await referralRepository.getSettings());
|
|
const caps = await getEffectiveMonthlyCaps(programSettings, payout.level_number);
|
|
const stats = await referralRepository.getBeneficiaryMonthlyCommissionStats(payout.beneficiary_user_id, caps.source === 'level' ? payout.level_number : undefined);
|
|
const cap = (0, referralCapService_1.wouldExceedMonthlyCapAtSettlement)({
|
|
reservedAmount: stats.reservedAmount,
|
|
reservedCount: stats.reservedCount,
|
|
maxAmountRaw: caps.maxAmountRaw,
|
|
maxCount: caps.maxCount,
|
|
});
|
|
if (cap.exceeded) {
|
|
await logCapBlocked(payout.beneficiary_user_id, payout.referred_user_id, BigInt(payout.commission_amount), cap.reason, payout.level_number, caps.source, payout.id);
|
|
return false;
|
|
}
|
|
const commissionAmount = BigInt(payout.commission_amount);
|
|
const bonusAccount = await ledgerRepository.getOrCreateBonusAccount(payout.beneficiary_user_id, payout.wallet_type_id);
|
|
const marked = await referralRepository.markCommissionPaid(payout.id);
|
|
if (!marked)
|
|
return false;
|
|
await ledgerRepository.credit(bonusAccount.id, commissionAmount, 'referral_bonus', 'referral_commission_payout', payout.id);
|
|
await auditLogRepository.create({
|
|
userId: payout.beneficiary_user_id,
|
|
action: 'referral_commission_paid',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: payout.id,
|
|
metadata: {
|
|
referred_user_id: payout.referred_user_id,
|
|
level: payout.level_number,
|
|
amount: commissionAmount.toString(),
|
|
deposit_transaction_id: payout.first_deposit_transaction_id,
|
|
},
|
|
});
|
|
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(payout.beneficiary_user_id);
|
|
return true;
|
|
}
|
|
async function rejectPendingCommission(payout, status, reason) {
|
|
const rejected = await referralRepository.rejectCommissionPayout(payout.id, status, reason);
|
|
if (!rejected)
|
|
return false;
|
|
await bonusPoolRepository.creditPool(payout.wallet_type_id, BigInt(payout.commission_amount));
|
|
await auditLogRepository.create({
|
|
userId: payout.beneficiary_user_id,
|
|
action: status === 'expired' ? 'referral_commission_expired' : 'referral_commission_rejected',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: payout.id,
|
|
metadata: {
|
|
referred_user_id: payout.referred_user_id,
|
|
level: payout.level_number,
|
|
amount: payout.commission_amount,
|
|
reason,
|
|
},
|
|
});
|
|
return true;
|
|
}
|
|
async function maybeEscalateToReview(payout, settings) {
|
|
const sybil = await evaluateSybilForCommission(settings, payout.beneficiary_user_id, payout.referred_user_id);
|
|
if (sybil.disposition === 'blocked') {
|
|
await rejectPendingCommission(payout, 'rejected', `sybil_blocked:${sybil.signals.join(',')}`);
|
|
await (0, securityService_1.raiseAlert)({
|
|
userId: payout.beneficiary_user_id,
|
|
severity: 'high',
|
|
alertType: 'referral_commission_blocked',
|
|
title: 'Referral commission blocked at settlement',
|
|
details: `Payout ${payout.id} blocked during auto-settlement (score ${sybil.score}).`,
|
|
metadata: {
|
|
payout_id: payout.id,
|
|
sybil_score: sybil.score,
|
|
sybil_signals: sybil.signals,
|
|
},
|
|
});
|
|
void (0, fraudAutoBlockService_1.maybeAutoSuspendForSybilFraud)(payout.beneficiary_user_id, sybil.score, sybil.signals, { referredUserId: payout.referred_user_id, payoutId: payout.id }).catch((e) => console.error('[referral] sybil auto-suspend failed:', e));
|
|
return 'blocked';
|
|
}
|
|
if (sybil.disposition === 'review') {
|
|
const moved = await referralRepository.moveCommissionToReview(payout.id, sybil.score, sybil.signals);
|
|
if (moved) {
|
|
await notifyReviewRequired(payout.id, payout.beneficiary_user_id, payout.referred_user_id, sybil.score, sybil.signals);
|
|
return 'review';
|
|
}
|
|
}
|
|
return 'unchanged';
|
|
}
|
|
/**
|
|
* Settles pending referral commissions whose hold period has elapsed.
|
|
* Returns the number of payouts paid or rejected/expired.
|
|
*/
|
|
async function processPendingReferralCommissions(limit = 100) {
|
|
const settings = await referralRepository.getSettings();
|
|
if (!settings.enabled)
|
|
return 0;
|
|
const pending = await referralRepository.listPendingCommissionsDue(limit);
|
|
let settled = 0;
|
|
for (const payout of pending) {
|
|
const escalation = await maybeEscalateToReview(payout, settings);
|
|
if (escalation !== 'unchanged') {
|
|
settled++;
|
|
continue;
|
|
}
|
|
const eligibility = await loadEligibilityContext(payout, settings);
|
|
const evaluation = evaluateReferralCommissionEligibility(eligibility);
|
|
if (evaluation.eligible) {
|
|
const paid = await payPendingCommission(payout, settings);
|
|
if (paid)
|
|
settled++;
|
|
continue;
|
|
}
|
|
if (isCommissionPendingExpired(payout.created_at, settings.commission_max_pending_days)) {
|
|
const reason = evaluation.reasons.join(',');
|
|
const rejected = await rejectPendingCommission(payout, 'expired', reason || 'eligibility_timeout');
|
|
if (rejected)
|
|
settled++;
|
|
}
|
|
}
|
|
return settled;
|
|
}
|
|
async function listReferralReviewQueue(opts) {
|
|
const { items, total } = await referralRepository.listReviewQueue(opts);
|
|
return {
|
|
total,
|
|
items: items.map((p) => ({
|
|
id: p.id,
|
|
beneficiaryUserId: p.beneficiary_user_id,
|
|
referredUserId: p.referred_user_id,
|
|
levelNumber: p.level_number,
|
|
depositAmount: p.deposit_amount,
|
|
commissionAmount: p.commission_amount,
|
|
commissionPercent: Number(p.commission_percent),
|
|
sybilScore: p.sybil_score,
|
|
sybilSignals: p.sybil_signals ?? [],
|
|
eligibleAt: p.eligible_at,
|
|
createdAt: p.created_at,
|
|
})),
|
|
};
|
|
}
|
|
async function approveReferralCommissionReview(input) {
|
|
const payout = await referralRepository.findCommissionPayoutById(input.payoutId);
|
|
if (!payout || payout.status !== 'review') {
|
|
throw new ReferralError('Commission not found in review queue');
|
|
}
|
|
const settings = await referralRepository.getSettings();
|
|
const eligibility = await loadEligibilityContext(payout, settings);
|
|
const evaluation = evaluateReferralCommissionEligibility(eligibility);
|
|
if (!evaluation.eligible) {
|
|
throw new ReferralError(`Commission not eligible: ${evaluation.reasons.join(', ')}`);
|
|
}
|
|
const sybil = await evaluateSybilForCommission(settings, payout.beneficiary_user_id, payout.referred_user_id);
|
|
if (sybil.disposition === 'blocked') {
|
|
throw new ReferralError(`Sybil score too high (${sybil.score}) for manual approval`);
|
|
}
|
|
const caps = await getEffectiveMonthlyCaps(settings, payout.level_number);
|
|
const stats = await referralRepository.getBeneficiaryMonthlyCommissionStats(payout.beneficiary_user_id, caps.source === 'level' ? payout.level_number : undefined);
|
|
const settlementCap = (0, referralCapService_1.wouldExceedMonthlyCapAtSettlement)({
|
|
reservedAmount: stats.reservedAmount,
|
|
reservedCount: stats.reservedCount,
|
|
maxAmountRaw: caps.maxAmountRaw,
|
|
maxCount: caps.maxCount,
|
|
});
|
|
if (settlementCap.exceeded) {
|
|
throw new ReferralError(`Monthly commission cap exceeded (${settlementCap.reason})`);
|
|
}
|
|
await referralRepository.recordCommissionReviewDecision({
|
|
payoutId: input.payoutId,
|
|
reviewerId: input.reviewerId,
|
|
approved: true,
|
|
note: input.note,
|
|
});
|
|
const paid = await payPendingCommission({ ...payout, status: 'review' }, settings);
|
|
if (!paid)
|
|
throw new ReferralError('Failed to pay commission after approval');
|
|
await auditLogRepository.create({
|
|
userId: input.reviewerId,
|
|
action: 'referral_commission_review_approved',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: input.payoutId,
|
|
metadata: { note: input.note ?? null },
|
|
});
|
|
}
|
|
async function rejectReferralCommissionReview(input) {
|
|
const payout = await referralRepository.findCommissionPayoutById(input.payoutId);
|
|
if (!payout || payout.status !== 'review') {
|
|
throw new ReferralError('Commission not found in review queue');
|
|
}
|
|
await referralRepository.recordCommissionReviewDecision({
|
|
payoutId: input.payoutId,
|
|
reviewerId: input.reviewerId,
|
|
approved: false,
|
|
note: input.reason,
|
|
});
|
|
const rejected = await rejectPendingCommission(payout, 'rejected', input.reason);
|
|
if (!rejected)
|
|
throw new ReferralError('Failed to reject commission');
|
|
await auditLogRepository.create({
|
|
userId: input.reviewerId,
|
|
action: 'referral_commission_review_rejected',
|
|
resourceType: 'referral_commission_payout',
|
|
resourceId: input.payoutId,
|
|
metadata: { reason: input.reason },
|
|
});
|
|
}
|
|
function getReferralCommissionPollIntervalMs() {
|
|
const raw = process.env.REFERRAL_COMMISSION_POLL_INTERVAL_MS;
|
|
const parsed = raw ? Number(raw) : 5 * 60 * 1000;
|
|
return Number.isFinite(parsed) && parsed >= 60000 ? parsed : 5 * 60 * 1000;
|
|
}
|
|
async function clawbackReferralCommission(input) {
|
|
const payout = await referralRepository.findCommissionPayoutById(input.payoutId);
|
|
if (!payout || payout.status !== 'paid') {
|
|
throw new ReferralError('Only paid commissions can be clawed back');
|
|
}
|
|
const bonusAccount = await ledgerRepository.getOrCreateBonusAccount(payout.beneficiary_user_id, payout.wallet_type_id);
|
|
const available = BigInt(bonusAccount.available_balance);
|
|
const requested = BigInt(payout.commission_amount);
|
|
const clawAmount = available < requested ? available : requested;
|
|
if (clawAmount <= 0n) {
|
|
throw new ReferralError('Beneficiary has no bonus balance available for clawback');
|
|
}
|
|
const clawbackId = await referralRepository.recordCommissionClawback({
|
|
payoutId: payout.id,
|
|
beneficiaryUserId: payout.beneficiary_user_id,
|
|
amount: clawAmount,
|
|
reason: input.reason,
|
|
clawedBy: input.adminId,
|
|
});
|
|
await ledgerRepository.debit(bonusAccount.id, clawAmount, 'referral_clawback', 'referral_commission_clawback', clawbackId);
|
|
await bonusPoolRepository.creditPool(payout.wallet_type_id, clawAmount);
|
|
await referralRepository.markCommissionClawedBack(payout.id);
|
|
await auditLogRepository.create({
|
|
userId: input.adminId,
|
|
action: 'referral_commission_clawed_back',
|
|
resourceType: 'referral_commission_clawback',
|
|
resourceId: clawbackId,
|
|
metadata: {
|
|
payout_id: payout.id,
|
|
beneficiary_user_id: payout.beneficiary_user_id,
|
|
amount: clawAmount.toString(),
|
|
reason: input.reason,
|
|
},
|
|
});
|
|
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(payout.beneficiary_user_id);
|
|
void (0, referralNotificationService_1.notifyReferralSlack)({
|
|
title: 'Referral commission clawed back',
|
|
severity: 'high',
|
|
alertType: 'referral_commission_clawed_back',
|
|
userId: payout.beneficiary_user_id,
|
|
details: `Clawback ${clawAmount.toString()} raw. Reason: ${input.reason}`,
|
|
metadata: {
|
|
payout_id: payout.id,
|
|
clawback_id: clawbackId,
|
|
amount: clawAmount.toString(),
|
|
level_number: payout.level_number,
|
|
},
|
|
});
|
|
return { clawbackId, amountClawed: clawAmount.toString() };
|
|
}
|
|
async function getReferralFraudDashboard() {
|
|
const [data, reviewQueue, settings] = await Promise.all([
|
|
referralRepository.getFraudDashboardData(),
|
|
referralRepository.listReviewQueue({ limit: 10 }),
|
|
referralRepository.getSettings(),
|
|
]);
|
|
return {
|
|
...data,
|
|
settings: {
|
|
maxCommissionAmountPerReferrerMonthRaw: settings.max_commission_amount_per_referrer_month_raw,
|
|
maxCommissionsPerReferrerMonth: settings.max_commissions_per_referrer_month,
|
|
},
|
|
reviewQueuePreview: reviewQueue.items.map((p) => ({
|
|
id: p.id,
|
|
beneficiaryUserId: p.beneficiary_user_id,
|
|
referredUserId: p.referred_user_id,
|
|
commissionAmount: p.commission_amount,
|
|
sybilScore: p.sybil_score,
|
|
sybilSignals: p.sybil_signals ?? [],
|
|
createdAt: p.created_at,
|
|
})),
|
|
};
|
|
}
|
|
async function markFirstDeposit(userId, transactionId) {
|
|
await (0, connection_1.query)(`UPDATE users SET first_deposit_at = COALESCE(first_deposit_at, NOW()),
|
|
first_deposit_transaction_id = COALESCE(first_deposit_transaction_id, $2),
|
|
updated_at = NOW()
|
|
WHERE id = $1`, [userId, transactionId]);
|
|
}
|
|
async function getUserReferralInfo(userId) {
|
|
const rows = await (0, connection_1.query)('SELECT referral_code FROM users WHERE id = $1', [userId]);
|
|
const code = rows[0]?.referral_code ?? null;
|
|
const settings = await referralRepository.getSettings();
|
|
const baseUrl = process.env.PUBLIC_WEB_URL || 'http://localhost:5173';
|
|
const referralLink = code ? `${baseUrl}/register?ref=${encodeURIComponent(code)}` : '';
|
|
const directReferrals = await referralRepository.countDirectReferrals(userId);
|
|
return {
|
|
referralCode: code,
|
|
referralLink,
|
|
directReferrals,
|
|
bonusWithdrawable: settings.bonus_withdrawable,
|
|
};
|
|
}
|
|
async function getProgramSettingsForAdmin() {
|
|
const settings = await referralRepository.getSettings();
|
|
const levels = await referralRepository.listLevels();
|
|
const pools = await bonusPoolRepository.listPools();
|
|
return {
|
|
settings: {
|
|
enabled: settings.enabled,
|
|
defaultReferrerUserId: settings.default_referrer_user_id,
|
|
bonusWithdrawable: settings.bonus_withdrawable,
|
|
referrerMustBeVerified: settings.referrer_must_be_verified,
|
|
referrerMustHaveDeposited: settings.referrer_must_have_deposited,
|
|
referredMustBeVerified: settings.referred_must_be_verified,
|
|
commissionHoldDays: settings.commission_hold_days,
|
|
minReferredPredictions: settings.min_referred_predictions,
|
|
commissionMaxPendingDays: settings.commission_max_pending_days,
|
|
sybilDetectionEnabled: settings.sybil_detection_enabled,
|
|
sybilReviewThreshold: settings.sybil_review_threshold,
|
|
sybilBlockThreshold: settings.sybil_block_threshold,
|
|
maxReferralsPerDay: settings.max_referrals_per_day,
|
|
maxCommissionAmountPerReferrerMonthRaw: settings.max_commission_amount_per_referrer_month_raw,
|
|
maxCommissionsPerReferrerMonth: settings.max_commissions_per_referrer_month,
|
|
slackAlertsEnabled: settings.slack_alerts_enabled,
|
|
depositCommissionsEnabled: settings.deposit_commissions_enabled,
|
|
withdrawalCommissionsEnabled: settings.withdrawal_commissions_enabled,
|
|
minFirstDepositRaw: settings.min_first_deposit_raw,
|
|
commissionWalletTypeId: settings.commission_wallet_type_id,
|
|
updatedAt: settings.updated_at,
|
|
},
|
|
levels: levels.map((l) => ({
|
|
levelNumber: l.level_number,
|
|
commissionPercent: Number(l.commission_percent),
|
|
isActive: l.is_active,
|
|
monthlyMaxAmountRaw: l.monthly_max_amount_raw,
|
|
monthlyMaxCount: l.monthly_max_count,
|
|
})),
|
|
pools: pools.map((p) => ({
|
|
walletTypeId: p.wallet_type_id,
|
|
availableBalance: p.available_balance,
|
|
})),
|
|
};
|
|
}
|
|
//# sourceMappingURL=referralService.js.map
|