After changing about commission dispatch
This commit is contained in:
parent
a6886512b7
commit
b7a360109e
@ -100,6 +100,7 @@ export async function updateAdminReferralSettings(req: AuthRequest, res: Respons
|
||||
slackAlertsEnabled?: boolean;
|
||||
depositCommissionsEnabled?: boolean;
|
||||
withdrawalCommissionsEnabled?: boolean;
|
||||
predictionCommissionsEnabled?: boolean;
|
||||
minFirstDepositRaw?: string;
|
||||
commissionWalletTypeId?: number;
|
||||
};
|
||||
@ -122,6 +123,7 @@ export async function updateAdminReferralSettings(req: AuthRequest, res: Respons
|
||||
slackAlertsEnabled: body.slackAlertsEnabled,
|
||||
depositCommissionsEnabled: body.depositCommissionsEnabled,
|
||||
withdrawalCommissionsEnabled: body.withdrawalCommissionsEnabled,
|
||||
predictionCommissionsEnabled: body.predictionCommissionsEnabled,
|
||||
minFirstDepositRaw: body.minFirstDepositRaw,
|
||||
commissionWalletTypeId: body.commissionWalletTypeId,
|
||||
});
|
||||
|
||||
@ -1877,7 +1877,7 @@ BEGIN
|
||||
AND column_name = 'deposit_commissions_enabled'
|
||||
) THEN
|
||||
ALTER TABLE referral_program_settings
|
||||
ADD COLUMN deposit_commissions_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
ADD COLUMN deposit_commissions_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
ALTER TABLE referral_program_settings
|
||||
ADD COLUMN withdrawal_commissions_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
END IF;
|
||||
@ -2389,3 +2389,60 @@ INSERT INTO system_settings (key, value) VALUES
|
||||
('login_risk_auto_suspend_threshold', '70'),
|
||||
('encryption_key_rotated_at', '')
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- Referral commissions on each validated prediction (stake-based)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'referral_program_settings'
|
||||
AND column_name = 'prediction_commissions_enabled'
|
||||
) THEN
|
||||
ALTER TABLE referral_program_settings
|
||||
ADD COLUMN prediction_commissions_enabled BOOLEAN NOT NULL DEFAULT TRUE;
|
||||
-- One-shot: switch primary mode to prediction for existing installs
|
||||
UPDATE referral_program_settings
|
||||
SET deposit_commissions_enabled = FALSE,
|
||||
withdrawal_commissions_enabled = FALSE,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1;
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = 'referral_commission_payouts'
|
||||
AND column_name = 'candle_predict_bet_id'
|
||||
) THEN
|
||||
ALTER TABLE referral_commission_payouts
|
||||
ADD COLUMN candle_predict_bet_id UUID REFERENCES candle_predict_bets(id);
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
DECLARE r record;
|
||||
BEGIN
|
||||
-- Recreate commission_source check to allow 'prediction'
|
||||
FOR r IN
|
||||
SELECT conname FROM pg_constraint
|
||||
WHERE conrelid = 'public.referral_commission_payouts'::regclass
|
||||
AND contype = 'c'
|
||||
AND pg_get_constraintdef(oid) LIKE '%commission_source%'
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE referral_commission_payouts DROP CONSTRAINT %I', r.conname);
|
||||
END LOOP;
|
||||
ALTER TABLE referral_commission_payouts
|
||||
ADD CONSTRAINT referral_commission_payouts_commission_source_check
|
||||
CHECK (commission_source IN ('deposit', 'withdrawal', 'prediction'));
|
||||
END $$;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_referral_payouts_prediction_unique
|
||||
ON referral_commission_payouts (candle_predict_bet_id, beneficiary_user_id, level_number)
|
||||
WHERE commission_source = 'prediction' AND candle_predict_bet_id IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_referral_payouts_prediction_bet
|
||||
ON referral_commission_payouts (candle_predict_bet_id)
|
||||
WHERE candle_predict_bet_id IS NOT NULL;
|
||||
|
||||
|
||||
@ -8,6 +8,7 @@ import * as settingsRepository from '../../repositories/settingsRepository';
|
||||
import { assertPositiveStakeAmount, parseStakeAmountFromBody } from '../../utils/stakeAmountValidation';
|
||||
import { queueUserAdminStatsRefresh } from '../../services/userAdminStatsService';
|
||||
import * as predictionAuditService from '../../services/predictionAuditService';
|
||||
import { processPredictionReferralCommissions } from '../../services/referralService';
|
||||
import {
|
||||
generateSyntheticCandle,
|
||||
defaultSeedCandle,
|
||||
@ -2002,6 +2003,14 @@ export async function executePlaceBetInternal(
|
||||
|
||||
queueUserAdminStatsRefresh(userId);
|
||||
|
||||
void processPredictionReferralCommissions({
|
||||
betId: bet.id,
|
||||
referredUserId: userId,
|
||||
stakeRaw,
|
||||
stakeAccountKind,
|
||||
walletTypeId: walletType.id,
|
||||
}).catch((e) => console.error('[referral] prediction commission failed:', e));
|
||||
|
||||
const mapped = mapBet(bet);
|
||||
if (config.redis.enabled) {
|
||||
const betVersion = await bumpUserBetVersionSafe(userId, interval.intervalMinutes);
|
||||
@ -2417,6 +2426,14 @@ export async function placeMultiCandleBet(
|
||||
|
||||
queueUserAdminStatsRefresh(userId);
|
||||
|
||||
void processPredictionReferralCommissions({
|
||||
betId: bet.id,
|
||||
referredUserId: userId,
|
||||
stakeRaw,
|
||||
stakeAccountKind,
|
||||
walletTypeId: walletType.id,
|
||||
}).catch((e) => console.error('[referral] prediction commission failed:', e));
|
||||
|
||||
if (config.redis.enabled) {
|
||||
const betVersion = await bumpUserBetVersionSafe(userId, interval.intervalMinutes);
|
||||
await publishRoundSnapshot(interval.intervalMinutes, timing.openMs);
|
||||
|
||||
@ -24,6 +24,7 @@ export type ReferralProgramSettings = {
|
||||
slack_alerts_enabled: boolean;
|
||||
deposit_commissions_enabled: boolean;
|
||||
withdrawal_commissions_enabled: boolean;
|
||||
prediction_commissions_enabled: boolean;
|
||||
min_first_deposit_raw: string;
|
||||
commission_wallet_type_id: number;
|
||||
updated_at: Date;
|
||||
@ -39,7 +40,7 @@ export type ReferralLevel = {
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
export type ReferralCommissionSource = 'deposit' | 'withdrawal';
|
||||
export type ReferralCommissionSource = 'deposit' | 'withdrawal' | 'prediction';
|
||||
|
||||
export type ReferralCommissionPayoutRow = {
|
||||
id: string;
|
||||
@ -49,6 +50,7 @@ export type ReferralCommissionPayoutRow = {
|
||||
commission_source: ReferralCommissionSource;
|
||||
first_deposit_transaction_id: string | null;
|
||||
withdrawal_transaction_id: string | null;
|
||||
candle_predict_bet_id: string | null;
|
||||
deposit_amount: string;
|
||||
commission_percent: string;
|
||||
commission_amount: string;
|
||||
@ -68,7 +70,8 @@ export type ReferralCommissionPayoutRow = {
|
||||
|
||||
const PAYOUT_COLUMNS = `
|
||||
id, beneficiary_user_id, referred_user_id, level_number, commission_source,
|
||||
first_deposit_transaction_id, withdrawal_transaction_id, deposit_amount::text, commission_percent::text,
|
||||
first_deposit_transaction_id, withdrawal_transaction_id, candle_predict_bet_id,
|
||||
deposit_amount::text, commission_percent::text,
|
||||
commission_amount::text, wallet_type_id, status, eligible_at, paid_at,
|
||||
rejection_reason, sybil_score, sybil_signals, reviewed_by, reviewed_at,
|
||||
review_note, created_at, updated_at
|
||||
@ -92,6 +95,7 @@ export async function getSettings(): Promise<ReferralProgramSettings> {
|
||||
max_commission_amount_per_referrer_month_raw::text,
|
||||
max_commissions_per_referrer_month, slack_alerts_enabled,
|
||||
deposit_commissions_enabled, withdrawal_commissions_enabled,
|
||||
COALESCE(prediction_commissions_enabled, TRUE) AS prediction_commissions_enabled,
|
||||
min_first_deposit_raw::text, commission_wallet_type_id, updated_at
|
||||
FROM referral_program_settings WHERE id = 1`
|
||||
);
|
||||
@ -117,6 +121,7 @@ export async function updateSettings(input: Partial<{
|
||||
slackAlertsEnabled: boolean;
|
||||
depositCommissionsEnabled: boolean;
|
||||
withdrawalCommissionsEnabled: boolean;
|
||||
predictionCommissionsEnabled: boolean;
|
||||
minFirstDepositRaw: string;
|
||||
commissionWalletTypeId: number;
|
||||
}>): Promise<ReferralProgramSettings> {
|
||||
@ -143,6 +148,7 @@ export async function updateSettings(input: Partial<{
|
||||
['slackAlertsEnabled', 'slack_alerts_enabled'],
|
||||
['depositCommissionsEnabled', 'deposit_commissions_enabled'],
|
||||
['withdrawalCommissionsEnabled', 'withdrawal_commissions_enabled'],
|
||||
['predictionCommissionsEnabled', 'prediction_commissions_enabled'],
|
||||
['minFirstDepositRaw', 'min_first_deposit_raw'],
|
||||
['commissionWalletTypeId', 'commission_wallet_type_id'],
|
||||
];
|
||||
@ -258,6 +264,7 @@ export async function recordCommissionPayout(input: {
|
||||
commissionSource?: ReferralCommissionSource;
|
||||
firstDepositTransactionId?: string | null;
|
||||
withdrawalTransactionId?: string | null;
|
||||
candlePredictBetId?: string | null;
|
||||
baseAmount: bigint;
|
||||
commissionPercent: number;
|
||||
commissionAmount: bigint;
|
||||
@ -271,10 +278,10 @@ export async function recordCommissionPayout(input: {
|
||||
const rows = await query<{ id: string }[]>(
|
||||
`INSERT INTO referral_commission_payouts
|
||||
(beneficiary_user_id, referred_user_id, level_number, commission_source,
|
||||
first_deposit_transaction_id, withdrawal_transaction_id,
|
||||
first_deposit_transaction_id, withdrawal_transaction_id, candle_predict_bet_id,
|
||||
deposit_amount, commission_percent, commission_amount, wallet_type_id,
|
||||
status, eligible_at, sybil_score, sybil_signals)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING id`,
|
||||
[
|
||||
@ -284,6 +291,7 @@ export async function recordCommissionPayout(input: {
|
||||
source,
|
||||
input.firstDepositTransactionId ?? null,
|
||||
input.withdrawalTransactionId ?? null,
|
||||
input.candlePredictBetId ?? null,
|
||||
input.baseAmount.toString(),
|
||||
input.commissionPercent,
|
||||
input.commissionAmount.toString(),
|
||||
|
||||
@ -40,6 +40,8 @@ export type ReferralEligibilityInput = {
|
||||
beneficiaryUnderSurveillance: boolean;
|
||||
beneficiaryEmailVerified: boolean;
|
||||
beneficiaryHasDeposited: boolean;
|
||||
/** Prediction commissions pay immediately — skip min_referred_predictions. */
|
||||
commissionSource?: ReferralCommissionPayoutRow['commission_source'];
|
||||
settings: Pick<
|
||||
ReferralProgramSettings,
|
||||
| 'referrer_must_be_verified'
|
||||
@ -64,7 +66,11 @@ export function evaluateReferralCommissionEligibility(
|
||||
if (input.settings.referred_must_be_verified && !input.referredEmailVerified) {
|
||||
reasons.push('referred_email_not_verified');
|
||||
}
|
||||
if (input.referredRealPredictionCount < input.settings.min_referred_predictions) {
|
||||
const skipMinPredictions = input.commissionSource === 'prediction';
|
||||
if (
|
||||
!skipMinPredictions &&
|
||||
input.referredRealPredictionCount < input.settings.min_referred_predictions
|
||||
) {
|
||||
reasons.push('insufficient_referred_predictions');
|
||||
}
|
||||
|
||||
@ -162,8 +168,9 @@ export async function assertReferrerEligible(referrerId: string): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
function calcCommission(depositAmount: bigint, percent: number): bigint {
|
||||
return (depositAmount * BigInt(Math.round(percent * 10000))) / 1000000n;
|
||||
/** Percent of base amount in raw units (e.g. stake or deposit). */
|
||||
export function calcCommission(baseAmount: bigint, percent: number): bigint {
|
||||
return (baseAmount * BigInt(Math.round(percent * 10000))) / 1000000n;
|
||||
}
|
||||
|
||||
function addDays(from: Date, days: number): Date {
|
||||
@ -449,6 +456,177 @@ export async function processFirstDepositReferralCommissions(input: {
|
||||
await markFirstDeposit(input.userId, input.depositTransactionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Credits multi-level referral commissions on each validated prediction (stake-based).
|
||||
* Pays immediately to the referrer bonus wallet after Sybil / caps / pool checks.
|
||||
* Test stakes are excluded; win/lose/refund do not affect the calculation.
|
||||
*/
|
||||
export async function processPredictionReferralCommissions(input: {
|
||||
betId: string;
|
||||
referredUserId: string;
|
||||
stakeRaw: bigint;
|
||||
stakeAccountKind: 'main' | 'bonus' | 'test';
|
||||
walletTypeId: number;
|
||||
}): Promise<void> {
|
||||
if (input.stakeAccountKind === 'test') return;
|
||||
if (input.stakeRaw <= 0n) return;
|
||||
|
||||
const settings = await referralRepository.getSettings();
|
||||
if (!settings.enabled || !settings.prediction_commissions_enabled) return;
|
||||
|
||||
const userRows = await query<Array<{ referred_by_user_id: string | null }>>(
|
||||
'SELECT referred_by_user_id FROM users WHERE id = $1',
|
||||
[input.referredUserId]
|
||||
);
|
||||
const user = userRows[0];
|
||||
if (!user?.referred_by_user_id) return;
|
||||
|
||||
const commissionWalletTypeId = settings.commission_wallet_type_id;
|
||||
if (input.walletTypeId !== commissionWalletTypeId) 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.referredUserId, maxLevel);
|
||||
const eligibleAt = new Date();
|
||||
|
||||
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.stakeRaw, percent);
|
||||
if (commissionAmount <= 0n) continue;
|
||||
|
||||
const sybil = await evaluateSybilForCommission(settings, beneficiaryId, input.referredUserId);
|
||||
|
||||
if (sybil.disposition === 'blocked') {
|
||||
await auditLogRepository.create({
|
||||
userId: beneficiaryId,
|
||||
action: 'referral_commission_blocked',
|
||||
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,
|
||||
sybil_score: sybil.score,
|
||||
sybil_signals: sybil.signals,
|
||||
},
|
||||
});
|
||||
await raiseAlert({
|
||||
userId: beneficiaryId,
|
||||
severity: 'high',
|
||||
alertType: 'referral_commission_blocked',
|
||||
title: 'Referral commission blocked (Sybil score)',
|
||||
details: `Auto-blocked prediction commission for referred user ${input.referredUserId}. Score: ${sybil.score}.`,
|
||||
metadata: {
|
||||
referred_user_id: input.referredUserId,
|
||||
level,
|
||||
commission_source: 'prediction',
|
||||
candle_predict_bet_id: input.betId,
|
||||
sybil_score: sybil.score,
|
||||
sybil_signals: sybil.signals,
|
||||
},
|
||||
});
|
||||
void maybeAutoSuspendForSybilFraud(beneficiaryId, sybil.score, sybil.signals, {
|
||||
referredUserId: input.referredUserId,
|
||||
}).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.referredUserId,
|
||||
commissionAmount,
|
||||
cap.reason!,
|
||||
level,
|
||||
cap.capSource ?? 'global',
|
||||
input.betId
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const debited = await bonusPoolRepository.debitPool(commissionWalletTypeId, commissionAmount);
|
||||
if (!debited) {
|
||||
console.error(
|
||||
`[referral] Insufficient bonus pool for level ${level} prediction commission to ${beneficiaryId}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const initialStatus = sybil.disposition === 'review' ? 'review' : 'pending';
|
||||
const payoutId = await referralRepository.recordCommissionPayout({
|
||||
beneficiaryUserId: beneficiaryId,
|
||||
referredUserId: input.referredUserId,
|
||||
levelNumber: level,
|
||||
commissionSource: 'prediction',
|
||||
candlePredictBetId: input.betId,
|
||||
baseAmount: input.stakeRaw,
|
||||
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.referredUserId,
|
||||
level,
|
||||
amount: commissionAmount.toString(),
|
||||
commission_source: 'prediction',
|
||||
candle_predict_bet_id: input.betId,
|
||||
eligible_at: eligibleAt.toISOString(),
|
||||
sybil_score: sybil.score,
|
||||
sybil_signals: sybil.signals,
|
||||
},
|
||||
});
|
||||
|
||||
if (initialStatus === 'review') {
|
||||
await notifyReviewRequired(
|
||||
payoutId,
|
||||
beneficiaryId,
|
||||
input.referredUserId,
|
||||
sybil.score,
|
||||
sybil.signals
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const payout = await referralRepository.findCommissionPayoutById(payoutId);
|
||||
if (!payout) {
|
||||
console.error(`[referral] Prediction payout ${payoutId} missing after insert`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const paid = await payPendingCommission(payout, settings);
|
||||
if (!paid) {
|
||||
console.error(
|
||||
`[referral] Failed immediate pay for prediction commission ${payoutId} (left pending)`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates pending multi-level referral commissions on withdrawal.
|
||||
* Base = commissionable prediction gains (main account), not deposited principal.
|
||||
@ -666,7 +844,11 @@ export async function getUserReferralDashboard(
|
||||
directReferrals: number;
|
||||
bonusWithdrawable: boolean;
|
||||
programEnabled: boolean;
|
||||
commissionModes: { depositEnabled: boolean; withdrawalEnabled: boolean };
|
||||
commissionModes: {
|
||||
depositEnabled: boolean;
|
||||
withdrawalEnabled: boolean;
|
||||
predictionEnabled: boolean;
|
||||
};
|
||||
levels: Array<{ levelNumber: number; commissionPercent: number }>;
|
||||
maxNetworkDepth: number;
|
||||
referrer: {
|
||||
@ -704,6 +886,7 @@ export async function getUserReferralDashboard(
|
||||
commissionModes: {
|
||||
depositEnabled: settings.deposit_commissions_enabled,
|
||||
withdrawalEnabled: settings.withdrawal_commissions_enabled,
|
||||
predictionEnabled: settings.prediction_commissions_enabled,
|
||||
},
|
||||
levels: activeLevels.map((l) => ({
|
||||
levelNumber: l.level_number,
|
||||
@ -777,6 +960,7 @@ async function loadEligibilityContext(
|
||||
beneficiaryUnderSurveillance: beneficiary?.under_surveillance ?? true,
|
||||
beneficiaryEmailVerified: beneficiary?.email_verified ?? false,
|
||||
beneficiaryHasDeposited,
|
||||
commissionSource: payout.commission_source,
|
||||
settings,
|
||||
};
|
||||
}
|
||||
@ -1216,6 +1400,7 @@ export async function getProgramSettingsForAdmin() {
|
||||
slackAlertsEnabled: settings.slack_alerts_enabled,
|
||||
depositCommissionsEnabled: settings.deposit_commissions_enabled,
|
||||
withdrawalCommissionsEnabled: settings.withdrawal_commissions_enabled,
|
||||
predictionCommissionsEnabled: settings.prediction_commissions_enabled,
|
||||
minFirstDepositRaw: settings.min_first_deposit_raw,
|
||||
commissionWalletTypeId: settings.commission_wallet_type_id,
|
||||
updatedAt: settings.updated_at,
|
||||
|
||||
@ -61,6 +61,40 @@ describe('referral commission eligibility', () => {
|
||||
assert.ok(result.reasons.includes('insufficient_referred_predictions'));
|
||||
});
|
||||
|
||||
test('prediction source skips min referred predictions gate', () => {
|
||||
const result = evaluateReferralCommissionEligibility({
|
||||
referredEmailVerified: true,
|
||||
referredIsEnabled: true,
|
||||
referredUnderSurveillance: false,
|
||||
referredRealPredictionCount: 0,
|
||||
beneficiaryIsEnabled: true,
|
||||
beneficiaryUnderSurveillance: false,
|
||||
beneficiaryEmailVerified: true,
|
||||
beneficiaryHasDeposited: true,
|
||||
commissionSource: 'prediction',
|
||||
settings: baseSettings,
|
||||
});
|
||||
assert.equal(result.eligible, true);
|
||||
assert.deepEqual(result.reasons, []);
|
||||
});
|
||||
|
||||
test('prediction source still requires referrer deposit when configured', () => {
|
||||
const result = evaluateReferralCommissionEligibility({
|
||||
referredEmailVerified: true,
|
||||
referredIsEnabled: true,
|
||||
referredUnderSurveillance: false,
|
||||
referredRealPredictionCount: 0,
|
||||
beneficiaryIsEnabled: true,
|
||||
beneficiaryUnderSurveillance: false,
|
||||
beneficiaryEmailVerified: true,
|
||||
beneficiaryHasDeposited: false,
|
||||
commissionSource: 'prediction',
|
||||
settings: baseSettings,
|
||||
});
|
||||
assert.equal(result.eligible, false);
|
||||
assert.ok(result.reasons.includes('beneficiary_no_deposit'));
|
||||
});
|
||||
|
||||
test('blocks beneficiary under surveillance', () => {
|
||||
const result = evaluateReferralCommissionEligibility({
|
||||
referredEmailVerified: true,
|
||||
|
||||
27
backend/src/tests/referralPredictionCommission.test.ts
Normal file
27
backend/src/tests/referralPredictionCommission.test.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { calcCommission } from '../services/referralService';
|
||||
|
||||
describe('prediction referral commissions', () => {
|
||||
test('calcCommission applies percent to stake raw units', () => {
|
||||
// 10 USDT stake (6 decimals) at 20% => 2 USDT
|
||||
assert.equal(calcCommission(10_000_000n, 20), 2_000_000n);
|
||||
// 5 USDT at 10% => 0.5 USDT
|
||||
assert.equal(calcCommission(5_000_000n, 10), 500_000n);
|
||||
// tiny stake floors via integer division
|
||||
assert.equal(calcCommission(1n, 20), 0n);
|
||||
});
|
||||
|
||||
test('test stake kind is excluded by processPredictionReferralCommissions gate', async () => {
|
||||
// Gate is the first check in processPredictionReferralCommissions; importing and calling
|
||||
// with test stake must no-op without DB access when stakeAccountKind === 'test'.
|
||||
const { processPredictionReferralCommissions } = await import('../services/referralService');
|
||||
await processPredictionReferralCommissions({
|
||||
betId: '00000000-0000-0000-0000-000000000001',
|
||||
referredUserId: '00000000-0000-0000-0000-000000000002',
|
||||
stakeRaw: 10_000_000n,
|
||||
stakeAccountKind: 'test',
|
||||
walletTypeId: 2,
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -188,6 +188,7 @@ export const referralSettingsBodySchema = z.object({
|
||||
slackAlertsEnabled: z.boolean().optional(),
|
||||
depositCommissionsEnabled: z.boolean().optional(),
|
||||
withdrawalCommissionsEnabled: z.boolean().optional(),
|
||||
predictionCommissionsEnabled: z.boolean().optional(),
|
||||
minFirstDepositRaw: z.string().trim().max(64).optional(),
|
||||
commissionWalletTypeId: z.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
@ -47,6 +47,7 @@ type ReferralConfig = {
|
||||
slackAlertsEnabled: boolean;
|
||||
depositCommissionsEnabled: boolean;
|
||||
withdrawalCommissionsEnabled: boolean;
|
||||
predictionCommissionsEnabled: boolean;
|
||||
minFirstDepositRaw: string;
|
||||
commissionWalletTypeId: number;
|
||||
};
|
||||
@ -151,6 +152,7 @@ export function ReferralAdminPage() {
|
||||
slackAlertsEnabled: body.slackAlertsEnabled,
|
||||
depositCommissionsEnabled: body.depositCommissionsEnabled,
|
||||
withdrawalCommissionsEnabled: body.withdrawalCommissionsEnabled,
|
||||
predictionCommissionsEnabled: body.predictionCommissionsEnabled,
|
||||
minFirstDepositRaw: body.minFirstDepositRaw,
|
||||
commissionWalletTypeId: body.commissionWalletTypeId,
|
||||
}),
|
||||
@ -334,10 +336,24 @@ export function ReferralAdminPage() {
|
||||
<Typography variant="subtitle2" sx={{ fontWeight: 700, pt: 1 }}>
|
||||
{t('admin.referralAdmin.commissionModes')}
|
||||
</Typography>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: -0.5 }}>
|
||||
{t('admin.referralAdmin.commissionModesHelper')}
|
||||
</Typography>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={s.depositCommissionsEnabled ?? true}
|
||||
checked={s.predictionCommissionsEnabled ?? true}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, predictionCommissionsEnabled: e.target.checked })
|
||||
}
|
||||
/>
|
||||
}
|
||||
label={t('admin.referralAdmin.predictionCommissions')}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={s.depositCommissionsEnabled ?? false}
|
||||
onChange={(e) =>
|
||||
setSettingsForm({ ...s, depositCommissionsEnabled: e.target.checked })
|
||||
}
|
||||
|
||||
@ -87,7 +87,10 @@ export function ReferralPage() {
|
||||
|
||||
const commissionModeLabel = () => {
|
||||
if (!data) return '';
|
||||
const { depositEnabled, withdrawalEnabled } = data.commissionModes;
|
||||
const { depositEnabled, withdrawalEnabled, predictionEnabled } = data.commissionModes;
|
||||
const legacyCount = Number(depositEnabled) + Number(withdrawalEnabled);
|
||||
if (predictionEnabled && legacyCount === 0) return t('referralPage.modes.prediction');
|
||||
if (predictionEnabled && legacyCount > 0) return t('referralPage.modes.predictionPlusLegacy');
|
||||
if (depositEnabled && withdrawalEnabled) return t('referralPage.modes.both');
|
||||
if (depositEnabled) return t('referralPage.modes.deposit');
|
||||
if (withdrawalEnabled) return t('referralPage.modes.withdrawal');
|
||||
@ -270,6 +273,7 @@ export function ReferralPage() {
|
||||
))}
|
||||
</Stack>
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1.5 }}>
|
||||
{data.commissionModes.predictionEnabled && t('referralPage.referrer.predictionHint')}
|
||||
{data.commissionModes.depositEnabled && t('referralPage.referrer.depositHint')}
|
||||
{data.commissionModes.withdrawalEnabled && t('referralPage.referrer.withdrawalHint')}
|
||||
</Typography>
|
||||
|
||||
@ -60,9 +60,11 @@ export function ReferralCommissionsPanel({ items }: ReferralCommissionsPanelProp
|
||||
size="small"
|
||||
variant="outlined"
|
||||
label={
|
||||
c.commissionSource === 'deposit'
|
||||
? t('referralPage.commissions.deposit')
|
||||
: t('referralPage.commissions.withdrawal')
|
||||
c.commissionSource === 'prediction'
|
||||
? t('referralPage.commissions.prediction')
|
||||
: c.commissionSource === 'deposit'
|
||||
? t('referralPage.commissions.deposit')
|
||||
: t('referralPage.commissions.withdrawal')
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
|
||||
@ -28,6 +28,7 @@ export type ReferralDashboard = {
|
||||
commissionModes: {
|
||||
depositEnabled: boolean;
|
||||
withdrawalEnabled: boolean;
|
||||
predictionEnabled: boolean;
|
||||
};
|
||||
levels: Array<{ levelNumber: number; commissionPercent: number }>;
|
||||
maxNetworkDepth: number;
|
||||
@ -52,7 +53,7 @@ export type ReferralCommissionItem = {
|
||||
referredUserId: string;
|
||||
referredDisplayName: string;
|
||||
levelNumber: number;
|
||||
commissionSource: 'deposit' | 'withdrawal';
|
||||
commissionSource: 'deposit' | 'withdrawal' | 'prediction';
|
||||
baseAmountRaw: string;
|
||||
commissionAmountRaw: string;
|
||||
commissionPercent: number;
|
||||
|
||||
@ -718,6 +718,8 @@ export const en = {
|
||||
depositHint: 'Deposit commissions apply on eligible first deposits. ',
|
||||
withdrawalHint:
|
||||
'Withdrawal commissions apply only on prediction gains withdrawn from the main account (not deposited principal).',
|
||||
predictionHint:
|
||||
'Prediction commissions apply on each validated stake (main/bonus). Test stakes are excluded.',
|
||||
},
|
||||
network: {
|
||||
title: 'Your referral network',
|
||||
@ -731,6 +733,8 @@ export const en = {
|
||||
both: 'Deposits + withdrawal gains',
|
||||
deposit: 'First deposits',
|
||||
withdrawal: 'Withdrawal gains (prediction profits)',
|
||||
prediction: 'Prediction stakes',
|
||||
predictionPlusLegacy: 'Predictions + legacy modes',
|
||||
paused: 'Commissions paused',
|
||||
},
|
||||
table: {
|
||||
@ -768,6 +772,7 @@ export const en = {
|
||||
date: 'Date',
|
||||
deposit: 'Deposit',
|
||||
withdrawal: 'Withdrawal gains',
|
||||
prediction: 'Prediction',
|
||||
percentOf: '{{percent}}% of {{amount}}',
|
||||
},
|
||||
},
|
||||
@ -1682,13 +1687,17 @@ export const en = {
|
||||
referrerDeposited: 'Referrer must have deposited',
|
||||
referredVerified: 'Referred user must have verified email (before payout)',
|
||||
commissionHold: 'Commission hold (days)',
|
||||
commissionHoldHelper: 'Delay after first deposit before commission can be paid',
|
||||
minPredictions: 'Min real-money predictions (referred user)',
|
||||
commissionHoldHelper:
|
||||
'Delay after first deposit / withdrawal before legacy commissions can be paid (prediction commissions pay immediately)',
|
||||
minPredictions: 'Min real-money predictions (referred user, legacy hold settlement)',
|
||||
maxPendingDays: 'Max pending days',
|
||||
maxPendingHelper: 'Expire unpaid commissions if eligibility is still not met',
|
||||
commissionModes: 'Commission modes',
|
||||
depositCommissions: 'Deposit commissions (first deposit of referred users)',
|
||||
withdrawalCommissions: 'Withdrawal commissions (prediction gains from main account only)',
|
||||
commissionModesHelper:
|
||||
'Level percentages apply to the referred user’s stake on each validated prediction (main/bonus). Test stakes are excluded.',
|
||||
predictionCommissions: 'Prediction commissions (on stake at place)',
|
||||
depositCommissions: 'Deposit commissions (legacy — first deposit of referred users)',
|
||||
withdrawalCommissions: 'Withdrawal commissions (legacy — prediction gains from main account only)',
|
||||
slackAlerts: 'Slack alerts',
|
||||
slackEnabled: 'Slack alerts enabled (referral channel: cap blocks, clawbacks, Sybil review)',
|
||||
slackHint:
|
||||
@ -1712,7 +1721,7 @@ export const en = {
|
||||
saveSettings: 'Save settings',
|
||||
levelsTitle: 'Commission levels',
|
||||
level: 'Level',
|
||||
percentDeposit: '% of first deposit',
|
||||
percentDeposit: '% of stake (or legacy base)',
|
||||
maxAmountMonthCol: 'Max amount / month (raw)',
|
||||
maxCountMonthCol: 'Max count / month',
|
||||
active: 'Active',
|
||||
|
||||
@ -731,6 +731,8 @@ export const fr = {
|
||||
depositHint: 'Les commissions sur dépôt s’appliquent aux premiers dépôts éligibles. ',
|
||||
withdrawalHint:
|
||||
'Les commissions sur retrait s’appliquent uniquement aux gains de prédiction retirés du compte principal (pas au capital déposé).',
|
||||
predictionHint:
|
||||
'Les commissions sur prédiction s’appliquent à chaque mise validée (principal/bonus). Les mises test sont exclues.',
|
||||
},
|
||||
network: {
|
||||
title: 'Votre réseau de parrainage',
|
||||
@ -744,6 +746,8 @@ export const fr = {
|
||||
both: 'Dépôts + gains de retrait',
|
||||
deposit: 'Premiers dépôts',
|
||||
withdrawal: 'Gains de retrait (profits de prédiction)',
|
||||
prediction: 'Mises de prédiction',
|
||||
predictionPlusLegacy: 'Prédictions + modes legacy',
|
||||
paused: 'Commissions suspendues',
|
||||
},
|
||||
table: {
|
||||
@ -781,6 +785,7 @@ export const fr = {
|
||||
date: 'Date',
|
||||
deposit: 'Dépôt',
|
||||
withdrawal: 'Gains de retrait',
|
||||
prediction: 'Prédiction',
|
||||
percentOf: '{{percent}} % de {{amount}}',
|
||||
},
|
||||
},
|
||||
@ -1696,13 +1701,17 @@ export const fr = {
|
||||
referrerDeposited: 'Le parrain doit avoir déposé',
|
||||
referredVerified: 'Le filleul doit avoir un e-mail vérifié (avant paiement)',
|
||||
commissionHold: 'Délai de rétention commission (jours)',
|
||||
commissionHoldHelper: 'Délai après le premier dépôt avant paiement de la commission',
|
||||
minPredictions: 'Prédictions argent réel min (filleul)',
|
||||
commissionHoldHelper:
|
||||
'Délai après le premier dépôt / retrait avant paiement des commissions legacy (les commissions prédiction sont payées immédiatement)',
|
||||
minPredictions: 'Prédictions argent réel min (filleul, règlement hold legacy)',
|
||||
maxPendingDays: 'Jours max en attente',
|
||||
maxPendingHelper: 'Expirer les commissions impayées si l’éligibilité n’est toujours pas atteinte',
|
||||
commissionModes: 'Modes de commission',
|
||||
depositCommissions: 'Commissions sur dépôt (premier dépôt des filleuls)',
|
||||
withdrawalCommissions: 'Commissions sur retrait (gains prédictions compte principal uniquement)',
|
||||
commissionModesHelper:
|
||||
'Les pourcentages de niveau s’appliquent à la mise du filleul à chaque prédiction validée (principal/bonus). Les mises test sont exclues.',
|
||||
predictionCommissions: 'Commissions sur prédiction (sur la mise à la place)',
|
||||
depositCommissions: 'Commissions sur dépôt (legacy — premier dépôt des filleuls)',
|
||||
withdrawalCommissions: 'Commissions sur retrait (legacy — gains prédictions compte principal uniquement)',
|
||||
slackAlerts: 'Alertes Slack',
|
||||
slackEnabled: 'Alertes Slack activées (canal parrainage : plafonds, clawbacks, revue Sybil)',
|
||||
slackHint:
|
||||
@ -1726,7 +1735,7 @@ export const fr = {
|
||||
saveSettings: 'Enregistrer les paramètres',
|
||||
levelsTitle: 'Niveaux de commission',
|
||||
level: 'Niveau',
|
||||
percentDeposit: '% du premier dépôt',
|
||||
percentDeposit: '% de la mise (ou base legacy)',
|
||||
maxAmountMonthCol: 'Montant max / mois (brut)',
|
||||
maxCountMonthCol: 'Nombre max / mois',
|
||||
active: 'Actif',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user