games_app/backend/src/services/soloEncouragementService.ts

477 lines
16 KiB
TypeScript

/**
* Solo real-money encouragement: track consecutive solo maturities and grant bonus refunds.
*/
import * as soloRepo from '../repositories/soloEncouragementRepository';
import * as ledgerRepository from '../repositories/ledgerRepository';
import * as walletRepository from '../repositories/walletRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import * as transactionRepository from '../repositories/transactionRepository';
import * as userSecurityNotificationRepository from '../repositories/userSecurityNotificationRepository';
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
import { decrypt } from '../utils/crypto';
import { buildReportXlsxBuffer } from './reportExportService';
export class SoloEncouragementError extends Error {
constructor(message: string) {
super(message);
this.name = 'SoloEncouragementError';
}
}
function safeDecryptEmail(encrypted: string | null): string | null {
if (!encrypted) return null;
try {
return decrypt(encrypted);
} catch {
return null;
}
}
function formatUsdt(raw: string | bigint, decimals = 6): string {
const s = typeof raw === 'bigint' ? raw.toString() : raw.trim() || '0';
const neg = s.startsWith('-');
const digits = neg ? s.slice(1) : s;
const padded = digits.padStart(decimals + 1, '0');
const whole = padded.slice(0, -decimals) || '0';
const frac = padded.slice(-decimals).replace(/0+$/, '');
const out = frac ? `${whole}.${frac}` : whole;
return neg ? `-${out}` : out;
}
async function resolveWalletType(walletTypeId: number) {
const types = await walletRepository.getWalletTypes();
return types.find((t) => t.id === walletTypeId) ?? null;
}
export async function getSettingsForAdmin() {
const settings = await soloRepo.getSettings();
const walletType = await resolveWalletType(settings.wallet_type_id);
return {
enabled: settings.enabled,
minConsecutiveSolo: settings.min_consecutive_solo,
refundPercent: Number(settings.refund_percent),
autoGrant: settings.auto_grant,
walletTypeId: settings.wallet_type_id,
walletCode: walletType?.code ?? null,
updatedAt: settings.updated_at,
};
}
export async function updateSettings(input: {
enabled?: boolean;
minConsecutiveSolo?: number;
refundPercent?: number;
autoGrant?: boolean;
walletTypeId?: number;
}) {
if (input.minConsecutiveSolo !== undefined && input.minConsecutiveSolo < 1) {
throw new SoloEncouragementError('minConsecutiveSolo must be at least 1');
}
if (
input.refundPercent !== undefined &&
(input.refundPercent < 0 || input.refundPercent > 100)
) {
throw new SoloEncouragementError('refundPercent must be between 0 and 100');
}
if (input.walletTypeId !== undefined) {
const wt = await resolveWalletType(input.walletTypeId);
if (!wt) throw new SoloEncouragementError('Wallet type not found');
}
await soloRepo.updateSettings(input);
return getSettingsForAdmin();
}
function computeCreditRaw(baseRaw: bigint, refundPercent: number): bigint {
if (baseRaw <= 0n || refundPercent <= 0) return 0n;
// credit = floor(base * percent / 100)
return (baseRaw * BigInt(Math.round(refundPercent * 10000))) / 1_000_000n;
}
async function creditEncouragementBonus(input: {
userId: string;
grantId: string;
creditRaw: bigint;
walletTypeId: number;
lossRaw: string;
streakCount: number;
refundPercent: number;
}): Promise<void> {
if (input.creditRaw <= 0n) return;
const bonusAccount = await ledgerRepository.getOrCreateBonusAccount(
input.userId,
input.walletTypeId
);
await ledgerRepository.credit(
bonusAccount.id,
input.creditRaw,
'solo_encouragement_bonus',
'solo_encouragement_grant',
input.grantId
);
await transactionRepository.create({
userId: input.userId,
walletTypeId: input.walletTypeId,
type: 'bonus',
amount: input.creditRaw,
status: 'completed',
metadata: {
source: 'solo_encouragement',
grant_id: input.grantId,
streak_count: input.streakCount,
loss_raw: input.lossRaw,
refund_percent: input.refundPercent,
},
});
await auditLogRepository.create({
userId: input.userId,
action: 'solo_encouragement_bonus_granted',
resourceType: 'solo_encouragement_grant',
resourceId: input.grantId,
metadata: {
credit_raw: input.creditRaw.toString(),
loss_raw: input.lossRaw,
streak_count: input.streakCount,
refund_percent: input.refundPercent,
},
});
const amountLabel = formatUsdt(input.creditRaw);
try {
await userSecurityNotificationRepository.createUserSecurityNotification({
userId: input.userId,
eventType: 'solo_encouragement_bonus',
title: 'Encouragement bonus received',
body: `You received an encouragement bonus of ${amountLabel} USDT for continuing to play alone with real funds.`,
metadata: {
grantId: input.grantId,
amountRaw: input.creditRaw.toString(),
amountUsdt: amountLabel,
streakCount: input.streakCount,
lossRaw: input.lossRaw,
refundPercent: input.refundPercent,
},
});
} catch (e) {
console.error('[solo-encouragement] notification failed:', e);
}
queueUserAdminStatsRefresh(input.userId);
}
/**
* Called after a maturity is fully settled (single/auto real-money bets).
* Solo = for each interval chart at this candle_open_ms, exactly one distinct
* real-money bettor. A user advances their streak once per maturity when every
* interval they played was solo (no contested chart). Contested intervals reset
* all participants on those charts.
*/
export async function onMaturitySettled(candleOpenMs: number): Promise<void> {
let settings: Awaited<ReturnType<typeof soloRepo.getSettings>>;
try {
settings = await soloRepo.getSettings();
} catch (e) {
console.warn('[solo-encouragement] settings unavailable, skip:', e);
return;
}
if (!settings.enabled) {
console.debug('[solo-encouragement] disabled, skip candle', candleOpenMs);
return;
}
const bets = await soloRepo.listSettledRealMoneyBetsForMaturity(candleOpenMs);
if (!bets.length) {
console.debug('[solo-encouragement] no real-money single bets for candle', candleOpenMs);
return;
}
const byInterval = new Map<number, typeof bets>();
for (const bet of bets) {
const key = Number(bet.interval_minutes) || 0;
const list = byInterval.get(key) ?? [];
list.push(bet);
byInterval.set(key, list);
}
const usersToReset = new Set<string>();
const soloBetsByUser = new Map<string, typeof bets>();
for (const [, intervalBets] of byInterval) {
const userIds = [...new Set(intervalBets.map((b) => b.user_id))];
if (userIds.length !== 1) {
for (const userId of userIds) usersToReset.add(userId);
continue;
}
const userId = userIds[0]!;
const list = soloBetsByUser.get(userId) ?? [];
list.push(...intervalBets);
soloBetsByUser.set(userId, list);
}
for (const userId of usersToReset) {
soloBetsByUser.delete(userId);
await soloRepo.resetUserState(userId);
}
if (usersToReset.size > 0) {
console.debug(
'[solo-encouragement] reset %d contested user(s) for candle %s',
usersToReset.size,
candleOpenMs
);
}
for (const [userId, userBets] of soloBetsByUser) {
const prev = await soloRepo.getUserState(userId);
// Idempotency: same maturity already applied
if (prev?.last_candle_open_ms && Number(prev.last_candle_open_ms) === candleOpenMs) {
console.debug('[solo-encouragement] already applied candle', candleOpenMs, 'user', userId);
continue;
}
// Pool neutrality often refunds true solo play (no "lost" status). Encourage on
// cumulative real-money stake volume during the solo streak; when losses exist,
// prefer cumulative losses so contested-style pain is still refunded preferentially.
const stakeThisMaturity = userBets.reduce((sum, b) => sum + BigInt(b.stake_raw), 0n);
const lossThisMaturity = userBets
.filter((b) => b.status === 'lost')
.reduce((sum, b) => sum + BigInt(b.stake_raw), 0n);
const betIds = userBets.map((b) => b.id);
const nextCount = (prev?.consecutive_solo_count ?? 0) + 1;
const prevBase = BigInt(prev?.loss_raw_sum ?? '0');
const nextBase = prevBase + (lossThisMaturity > 0n ? lossThisMaturity : stakeThisMaturity);
const prevBetIds = prev?.last_bet_ids ?? [];
const allBetIds = [...prevBetIds, ...betIds];
await soloRepo.upsertUserState({
userId,
consecutiveSoloCount: nextCount,
lossRawSum: nextBase.toString(),
lastCandleOpenMs: candleOpenMs,
lastBetIds: allBetIds.slice(-50),
});
if (nextCount < settings.min_consecutive_solo) {
console.info(
'[solo-encouragement] streak %d/%d user=%s candle=%s loss+%s stake+%s base=%s',
nextCount,
settings.min_consecutive_solo,
userId,
candleOpenMs,
lossThisMaturity.toString(),
stakeThisMaturity.toString(),
nextBase.toString()
);
continue;
}
const refundPercent = Number(settings.refund_percent);
const creditRaw = computeCreditRaw(nextBase, refundPercent);
const candleList = [candleOpenMs];
if (creditRaw <= 0n) {
await soloRepo.createGrant({
userId,
streakCount: nextCount,
lossRaw: nextBase.toString(),
refundPercent,
creditRaw: '0',
status: 'skipped',
betIds: allBetIds.slice(-50),
candleOpenMsList: candleList,
walletTypeId: settings.wallet_type_id,
});
await soloRepo.resetUserState(userId);
console.info('[solo-encouragement] skipped grant (zero credit) user=%s streak=%d', userId, nextCount);
continue;
}
if (settings.auto_grant) {
const grant = await soloRepo.createGrant({
userId,
streakCount: nextCount,
lossRaw: nextBase.toString(),
refundPercent,
creditRaw: creditRaw.toString(),
status: 'granted',
betIds: allBetIds.slice(-50),
candleOpenMsList: candleList,
walletTypeId: settings.wallet_type_id,
grantedBy: null,
});
await creditEncouragementBonus({
userId,
grantId: grant.id,
creditRaw,
walletTypeId: settings.wallet_type_id,
lossRaw: nextBase.toString(),
streakCount: nextCount,
refundPercent,
});
await soloRepo.resetUserState(userId);
console.info(
'[solo-encouragement] auto-granted %s user=%s streak=%d',
creditRaw.toString(),
userId,
nextCount
);
continue;
}
await soloRepo.createGrant({
userId,
streakCount: nextCount,
lossRaw: nextBase.toString(),
refundPercent,
creditRaw: creditRaw.toString(),
status: 'eligible',
betIds: allBetIds.slice(-50),
candleOpenMsList: candleList,
walletTypeId: settings.wallet_type_id,
});
await soloRepo.resetUserState(userId);
console.info(
'[solo-encouragement] eligible grant credit=%s user=%s streak=%d',
creditRaw.toString(),
userId,
nextCount
);
}
}
export async function listActiveStreaksForAdmin(limit = 50, offset = 0) {
const settings = await soloRepo.getSettings();
const { items, total } = await soloRepo.listActiveStreaks({ limit, offset });
return {
minConsecutiveSolo: settings.min_consecutive_solo,
refundPercent: Number(settings.refund_percent),
total,
items: items.map((row) => {
const lossRaw = BigInt(row.loss_raw_sum);
const projected = computeCreditRaw(lossRaw, Number(settings.refund_percent));
return {
userId: row.user_id,
userEmail: safeDecryptEmail(row.user_email),
consecutiveSoloCount: row.consecutive_solo_count,
lossRaw: row.loss_raw_sum,
projectedCreditRaw: projected.toString(),
lastCandleOpenMs: row.last_candle_open_ms,
updatedAt: row.updated_at,
nearEligible: row.consecutive_solo_count >= Math.max(1, settings.min_consecutive_solo - 1),
};
}),
};
}
export async function listGrantsForAdmin(input: {
status?: string;
limit?: number;
offset?: number;
}) {
const limit = Math.min(input.limit ?? 50, 200);
const offset = input.offset ?? 0;
const { items, total } = await soloRepo.listGrants({
status: input.status,
limit,
offset,
});
return {
total,
items: items.map((g) => ({
id: g.id,
userId: g.user_id,
userEmail: safeDecryptEmail(g.user_email),
streakCount: g.streak_count,
lossRaw: g.loss_raw,
refundPercent: Number(g.refund_percent),
creditRaw: g.credit_raw,
status: g.status,
betIds: g.bet_ids,
walletTypeId: g.wallet_type_id,
grantedBy: g.granted_by,
grantedAt: g.granted_at,
createdAt: g.created_at,
})),
};
}
/** Export filtered grants as XLSX (paginated fetch, max 10_000 rows). */
export async function exportGrantsXlsx(status?: string): Promise<Buffer> {
const pageSize = 200;
const maxRows = 10_000;
const all: Awaited<ReturnType<typeof listGrantsForAdmin>>['items'] = [];
let offset = 0;
let total = Infinity;
while (offset < total && all.length < maxRows) {
const page = await listGrantsForAdmin({
status: status && status !== 'all' ? status : undefined,
limit: pageSize,
offset,
});
total = page.total;
all.push(...page.items);
if (page.items.length === 0) break;
offset += page.items.length;
}
const columns = [
{ field: 'createdAt', headerName: 'Date', type: 'date' as const },
{ field: 'userId', headerName: 'User ID', type: 'string' as const },
{ field: 'userEmail', headerName: 'User email', type: 'string' as const },
{ field: 'streakCount', headerName: 'Streak', type: 'number' as const },
{ field: 'lossRaw', headerName: 'Losses / stake base (USDT)', type: 'money' as const },
{ field: 'refundPercent', headerName: 'Refund %', type: 'number' as const },
{ field: 'creditRaw', headerName: 'Bonus (USDT)', type: 'money' as const },
{ field: 'status', headerName: 'Status', type: 'string' as const },
{ field: 'grantedAt', headerName: 'Granted at', type: 'date' as const },
{ field: 'id', headerName: 'Grant ID', type: 'string' as const },
];
return buildReportXlsxBuffer({
title: 'Solo encouragement grants',
reportKey: 'solo-encouragement-grants',
columns,
items: all.map((g) => ({
id: g.id,
userId: g.userId,
userEmail: g.userEmail,
streakCount: g.streakCount,
lossRaw: g.lossRaw,
refundPercent: g.refundPercent,
creditRaw: g.creditRaw,
status: g.status,
grantedAt: g.grantedAt,
createdAt: g.createdAt,
})),
});
}
export async function grantEligibleBonus(grantId: string, adminUserId: string) {
const grant = await soloRepo.getGrantById(grantId);
if (!grant) throw new SoloEncouragementError('Grant not found');
if (grant.status !== 'eligible') {
throw new SoloEncouragementError('Grant is not eligible for approval');
}
const creditRaw = BigInt(grant.credit_raw);
if (creditRaw <= 0n) throw new SoloEncouragementError('Credit amount is zero');
const marked = await soloRepo.markGrantGranted(grantId, adminUserId);
if (!marked) throw new SoloEncouragementError('Grant already processed');
await creditEncouragementBonus({
userId: grant.user_id,
grantId: grant.id,
creditRaw,
walletTypeId: grant.wallet_type_id,
lossRaw: grant.loss_raw,
streakCount: grant.streak_count,
refundPercent: Number(grant.refund_percent),
});
return { id: grant.id, creditRaw: grant.credit_raw, status: 'granted' as const };
}
export async function rejectEligibleBonus(grantId: string, adminUserId: string) {
const marked = await soloRepo.markGrantRejected(grantId, adminUserId);
if (!marked) throw new SoloEncouragementError('Grant not found or already processed');
return { id: marked.id, status: 'rejected' as const };
}