After adding the option to grant commission for solo prediction
This commit is contained in:
parent
cefaab29f1
commit
ea6174420b
67
backend/src/controllers/soloEncouragementController.ts
Normal file
67
backend/src/controllers/soloEncouragementController.ts
Normal file
@ -0,0 +1,67 @@
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
import * as soloEncouragementService from '../services/soloEncouragementService';
|
||||
|
||||
export async function getAdminConfig(_req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await soloEncouragementService.getSettingsForAdmin());
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateAdminConfig(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const body = req.body as {
|
||||
enabled?: boolean;
|
||||
minConsecutiveSolo?: number;
|
||||
refundPercent?: number;
|
||||
autoGrant?: boolean;
|
||||
walletTypeId?: number;
|
||||
};
|
||||
res.json(await soloEncouragementService.updateSettings(body));
|
||||
} catch (e) {
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Update failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listActiveStreaks(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const limit = Math.min(parseInt((req.query.limit as string) || '50', 10), 200);
|
||||
const offset = parseInt((req.query.offset as string) || '0', 10);
|
||||
res.json(await soloEncouragementService.listActiveStreaksForAdmin(limit, offset));
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function listGrants(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const status = (req.query.status as string) || undefined;
|
||||
const limit = Math.min(parseInt((req.query.limit as string) || '50', 10), 200);
|
||||
const offset = parseInt((req.query.offset as string) || '0', 10);
|
||||
res.json(await soloEncouragementService.listGrantsForAdmin({ status, limit, offset }));
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function grantBonus(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const grantId = String(req.params.grantId ?? '');
|
||||
const result = await soloEncouragementService.grantEligibleBonus(grantId, req.user!.userId);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Grant failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function rejectBonus(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const grantId = String(req.params.grantId ?? '');
|
||||
const result = await soloEncouragementService.rejectEligibleBonus(grantId, req.user!.userId);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Reject failed' });
|
||||
}
|
||||
}
|
||||
@ -1175,6 +1175,55 @@ CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_user_test_created
|
||||
ON candle_predict_bets (user_id, created_at DESC)
|
||||
WHERE stake_account_kind = 'test';
|
||||
|
||||
-- Solo real-money encouragement bonus (exclude Test Wallet)
|
||||
CREATE TABLE IF NOT EXISTS solo_encouragement_settings (
|
||||
id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
min_consecutive_solo INTEGER NOT NULL DEFAULT 3 CHECK (min_consecutive_solo >= 1),
|
||||
refund_percent NUMERIC(8, 4) NOT NULL DEFAULT 20 CHECK (refund_percent >= 0 AND refund_percent <= 100),
|
||||
auto_grant BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
INSERT INTO solo_encouragement_settings (id, wallet_type_id)
|
||||
SELECT 1, id FROM wallet_types WHERE code = 'USDT_TRC20'
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS solo_encouragement_user_state (
|
||||
user_id UUID PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
consecutive_solo_count INTEGER NOT NULL DEFAULT 0 CHECK (consecutive_solo_count >= 0),
|
||||
loss_raw_sum BIGINT NOT NULL DEFAULT 0 CHECK (loss_raw_sum >= 0),
|
||||
last_candle_open_ms BIGINT,
|
||||
last_bet_ids UUID[] NOT NULL DEFAULT '{}',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS solo_encouragement_grants (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
streak_count INTEGER NOT NULL CHECK (streak_count >= 1),
|
||||
loss_raw BIGINT NOT NULL CHECK (loss_raw >= 0),
|
||||
refund_percent NUMERIC(8, 4) NOT NULL,
|
||||
credit_raw BIGINT NOT NULL CHECK (credit_raw >= 0),
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'eligible'
|
||||
CHECK (status IN ('eligible', 'granted', 'rejected', 'skipped')),
|
||||
bet_ids UUID[] NOT NULL DEFAULT '{}',
|
||||
candle_open_ms_list BIGINT[] NOT NULL DEFAULT '{}',
|
||||
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
|
||||
granted_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
granted_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_solo_encouragement_grants_user
|
||||
ON solo_encouragement_grants(user_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_solo_encouragement_grants_status
|
||||
ON solo_encouragement_grants(status, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_solo_encouragement_user_state_streak
|
||||
ON solo_encouragement_user_state(consecutive_solo_count DESC)
|
||||
WHERE consecutive_solo_count > 0;
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
r RECORD;
|
||||
@ -2139,6 +2188,8 @@ BEGIN
|
||||
WHEN 'candle_predict_rounds' THEN 'high'
|
||||
WHEN 'test_wallet_credits' THEN 'high'
|
||||
WHEN 'test_wallet_settings' THEN 'high'
|
||||
WHEN 'solo_encouragement_settings' THEN 'high'
|
||||
WHEN 'solo_encouragement_grants' THEN 'high'
|
||||
WHEN 'share_card_settings' THEN 'medium'
|
||||
WHEN 'referral_program_settings' THEN 'high'
|
||||
WHEN 'platform_bonus_pools' THEN 'high'
|
||||
@ -2328,6 +2379,7 @@ BEGIN
|
||||
'candle_predict_config', 'candle_predict_intervals', 'candle_predict_multi_levels',
|
||||
'candle_predict_bets', 'candle_predict_rounds', 'candle_predict_daily_revenue',
|
||||
'test_wallet_credits', 'test_wallet_settings',
|
||||
'solo_encouragement_settings', 'solo_encouragement_user_state', 'solo_encouragement_grants',
|
||||
'referral_program_settings', 'platform_bonus_pools', 'exchange_funding',
|
||||
'system_settings', 'withdrawal_locks', 'deposit_scanner_state',
|
||||
'security_alerts', 'refresh_tokens',
|
||||
|
||||
@ -26,6 +26,7 @@ import {
|
||||
} from '../../services/gameTimingService';
|
||||
import * as multiService from '../../services/candlePredictMultiService';
|
||||
import * as testWalletService from '../../services/testWalletService';
|
||||
import * as soloEncouragementService from '../../services/soloEncouragementService';
|
||||
import {
|
||||
pickRandomDirectionalOutcome,
|
||||
projectMajorityWinSettlement,
|
||||
@ -1386,6 +1387,10 @@ async function settleMaturityAtOpenMs(
|
||||
longPool
|
||||
);
|
||||
}
|
||||
|
||||
void soloEncouragementService.onMaturitySettled(candleOpenMs).catch((e) =>
|
||||
console.error('[solo-encouragement] onMaturitySettled failed:', e)
|
||||
);
|
||||
};
|
||||
|
||||
if (outcomeMode === 'pool') {
|
||||
|
||||
303
backend/src/repositories/soloEncouragementRepository.ts
Normal file
303
backend/src/repositories/soloEncouragementRepository.ts
Normal file
@ -0,0 +1,303 @@
|
||||
/**
|
||||
* Solo real-money encouragement bonus: settings, user streaks, and grants.
|
||||
*/
|
||||
|
||||
import { query } from '../db/connection';
|
||||
|
||||
export type SoloEncouragementSettingsRow = {
|
||||
id: number;
|
||||
enabled: boolean;
|
||||
min_consecutive_solo: number;
|
||||
refund_percent: string;
|
||||
auto_grant: boolean;
|
||||
wallet_type_id: number;
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
export type SoloEncouragementUserStateRow = {
|
||||
user_id: string;
|
||||
consecutive_solo_count: number;
|
||||
loss_raw_sum: string;
|
||||
last_candle_open_ms: string | null;
|
||||
last_bet_ids: string[];
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
export type SoloEncouragementGrantRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
streak_count: number;
|
||||
loss_raw: string;
|
||||
refund_percent: string;
|
||||
credit_raw: string;
|
||||
status: 'eligible' | 'granted' | 'rejected' | 'skipped';
|
||||
bet_ids: string[];
|
||||
candle_open_ms_list: string[];
|
||||
wallet_type_id: number;
|
||||
granted_by: string | null;
|
||||
granted_at: Date | null;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
export type SettledRealMoneyBetRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
stake_raw: string;
|
||||
status: 'won' | 'lost' | 'refunded';
|
||||
wallet_type_id: number;
|
||||
stake_account_kind: 'main' | 'bonus';
|
||||
};
|
||||
|
||||
const SETTINGS_SELECT = `id, enabled, min_consecutive_solo, refund_percent::text, auto_grant,
|
||||
wallet_type_id, updated_at`;
|
||||
|
||||
const STATE_SELECT = `user_id, consecutive_solo_count, loss_raw_sum::text, last_candle_open_ms::text,
|
||||
COALESCE(last_bet_ids, '{}') AS last_bet_ids, updated_at`;
|
||||
|
||||
const GRANT_SELECT = `id, user_id, streak_count, loss_raw::text, refund_percent::text, credit_raw::text,
|
||||
status, COALESCE(bet_ids, '{}') AS bet_ids,
|
||||
COALESCE(candle_open_ms_list, '{}') AS candle_open_ms_list,
|
||||
wallet_type_id, granted_by, granted_at, created_at`;
|
||||
|
||||
export async function getSettings(): Promise<SoloEncouragementSettingsRow> {
|
||||
const rows = await query<SoloEncouragementSettingsRow[]>(
|
||||
`SELECT ${SETTINGS_SELECT} FROM solo_encouragement_settings WHERE id = 1`
|
||||
);
|
||||
if (!rows[0]) throw new Error('Solo encouragement settings are not configured');
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
export async function updateSettings(input: {
|
||||
enabled?: boolean;
|
||||
minConsecutiveSolo?: number;
|
||||
refundPercent?: number;
|
||||
autoGrant?: boolean;
|
||||
walletTypeId?: number;
|
||||
}): Promise<SoloEncouragementSettingsRow> {
|
||||
const current = await getSettings();
|
||||
const rows = await query<SoloEncouragementSettingsRow[]>(
|
||||
`UPDATE solo_encouragement_settings SET
|
||||
enabled = COALESCE($1, enabled),
|
||||
min_consecutive_solo = COALESCE($2, min_consecutive_solo),
|
||||
refund_percent = COALESCE($3, refund_percent),
|
||||
auto_grant = COALESCE($4, auto_grant),
|
||||
wallet_type_id = COALESCE($5, wallet_type_id),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
RETURNING ${SETTINGS_SELECT}`,
|
||||
[
|
||||
input.enabled ?? null,
|
||||
input.minConsecutiveSolo ?? null,
|
||||
input.refundPercent ?? null,
|
||||
input.autoGrant ?? null,
|
||||
input.walletTypeId ?? null,
|
||||
]
|
||||
);
|
||||
return rows[0] ?? current;
|
||||
}
|
||||
|
||||
/** Settled single/auto real-money bets for a maturity (Test excluded). */
|
||||
export async function listSettledRealMoneyBetsForMaturity(
|
||||
candleOpenMs: number
|
||||
): Promise<SettledRealMoneyBetRow[]> {
|
||||
return query<SettledRealMoneyBetRow[]>(
|
||||
`SELECT b.id, b.user_id, b.stake_raw::text, b.status, b.wallet_type_id, b.stake_account_kind
|
||||
FROM candle_predict_bets b
|
||||
INNER JOIN candle_predict_rounds r ON r.id = b.round_id
|
||||
WHERE r.candle_open_ms = $1
|
||||
AND b.prediction_mode = 'single'
|
||||
AND b.stake_account_kind IN ('main', 'bonus')
|
||||
AND b.status IN ('won', 'lost', 'refunded')`,
|
||||
[candleOpenMs]
|
||||
);
|
||||
}
|
||||
|
||||
export async function getUserState(userId: string): Promise<SoloEncouragementUserStateRow | null> {
|
||||
const rows = await query<SoloEncouragementUserStateRow[]>(
|
||||
`SELECT ${STATE_SELECT} FROM solo_encouragement_user_state WHERE user_id = $1`,
|
||||
[userId]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function upsertUserState(input: {
|
||||
userId: string;
|
||||
consecutiveSoloCount: number;
|
||||
lossRawSum: string;
|
||||
lastCandleOpenMs: number | null;
|
||||
lastBetIds: string[];
|
||||
}): Promise<SoloEncouragementUserStateRow> {
|
||||
const rows = await query<SoloEncouragementUserStateRow[]>(
|
||||
`INSERT INTO solo_encouragement_user_state (
|
||||
user_id, consecutive_solo_count, loss_raw_sum, last_candle_open_ms, last_bet_ids, updated_at
|
||||
) VALUES ($1, $2, $3::bigint, $4, $5::uuid[], NOW())
|
||||
ON CONFLICT (user_id) DO UPDATE SET
|
||||
consecutive_solo_count = EXCLUDED.consecutive_solo_count,
|
||||
loss_raw_sum = EXCLUDED.loss_raw_sum,
|
||||
last_candle_open_ms = EXCLUDED.last_candle_open_ms,
|
||||
last_bet_ids = EXCLUDED.last_bet_ids,
|
||||
updated_at = NOW()
|
||||
RETURNING ${STATE_SELECT}`,
|
||||
[
|
||||
input.userId,
|
||||
input.consecutiveSoloCount,
|
||||
input.lossRawSum,
|
||||
input.lastCandleOpenMs,
|
||||
input.lastBetIds,
|
||||
]
|
||||
);
|
||||
return rows[0]!;
|
||||
}
|
||||
|
||||
export async function resetUserState(userId: string): Promise<void> {
|
||||
await query(
|
||||
`INSERT INTO solo_encouragement_user_state (
|
||||
user_id, consecutive_solo_count, loss_raw_sum, last_candle_open_ms, last_bet_ids, updated_at
|
||||
) VALUES ($1, 0, 0, NULL, '{}', NOW())
|
||||
ON CONFLICT (user_id) DO UPDATE SET
|
||||
consecutive_solo_count = 0,
|
||||
loss_raw_sum = 0,
|
||||
last_candle_open_ms = NULL,
|
||||
last_bet_ids = '{}',
|
||||
updated_at = NOW()`,
|
||||
[userId]
|
||||
);
|
||||
}
|
||||
|
||||
export async function createGrant(input: {
|
||||
userId: string;
|
||||
streakCount: number;
|
||||
lossRaw: string;
|
||||
refundPercent: number;
|
||||
creditRaw: string;
|
||||
status: 'eligible' | 'granted' | 'skipped';
|
||||
betIds: string[];
|
||||
candleOpenMsList: number[];
|
||||
walletTypeId: number;
|
||||
grantedBy?: string | null;
|
||||
}): Promise<SoloEncouragementGrantRow> {
|
||||
const rows = await query<SoloEncouragementGrantRow[]>(
|
||||
`INSERT INTO solo_encouragement_grants (
|
||||
user_id, streak_count, loss_raw, refund_percent, credit_raw, status,
|
||||
bet_ids, candle_open_ms_list, wallet_type_id, granted_by, granted_at
|
||||
) VALUES (
|
||||
$1, $2, $3::bigint, $4, $5::bigint, $6,
|
||||
$7::uuid[], $8::bigint[], $9, $10,
|
||||
CASE WHEN $6 = 'granted' THEN NOW() ELSE NULL END
|
||||
)
|
||||
RETURNING ${GRANT_SELECT}`,
|
||||
[
|
||||
input.userId,
|
||||
input.streakCount,
|
||||
input.lossRaw,
|
||||
input.refundPercent,
|
||||
input.creditRaw,
|
||||
input.status,
|
||||
input.betIds,
|
||||
input.candleOpenMsList,
|
||||
input.walletTypeId,
|
||||
input.grantedBy ?? null,
|
||||
]
|
||||
);
|
||||
return rows[0]!;
|
||||
}
|
||||
|
||||
export async function getGrantById(id: string): Promise<SoloEncouragementGrantRow | null> {
|
||||
const rows = await query<SoloEncouragementGrantRow[]>(
|
||||
`SELECT ${GRANT_SELECT} FROM solo_encouragement_grants WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function markGrantGranted(
|
||||
id: string,
|
||||
grantedBy: string | null
|
||||
): Promise<SoloEncouragementGrantRow | null> {
|
||||
const rows = await query<SoloEncouragementGrantRow[]>(
|
||||
`UPDATE solo_encouragement_grants
|
||||
SET status = 'granted', granted_by = $2, granted_at = NOW()
|
||||
WHERE id = $1 AND status = 'eligible'
|
||||
RETURNING ${GRANT_SELECT}`,
|
||||
[id, grantedBy]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function markGrantRejected(
|
||||
id: string,
|
||||
grantedBy: string | null
|
||||
): Promise<SoloEncouragementGrantRow | null> {
|
||||
const rows = await query<SoloEncouragementGrantRow[]>(
|
||||
`UPDATE solo_encouragement_grants
|
||||
SET status = 'rejected', granted_by = $2, granted_at = NOW()
|
||||
WHERE id = $1 AND status = 'eligible'
|
||||
RETURNING ${GRANT_SELECT}`,
|
||||
[id, grantedBy]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export type SoloEncouragementGrantListRow = SoloEncouragementGrantRow & {
|
||||
user_email: string | null;
|
||||
};
|
||||
|
||||
export async function listGrants(input: {
|
||||
status?: string;
|
||||
limit: number;
|
||||
offset: number;
|
||||
}): Promise<{ items: SoloEncouragementGrantListRow[]; total: number }> {
|
||||
const params: unknown[] = [];
|
||||
let where = '';
|
||||
if (input.status) {
|
||||
params.push(input.status);
|
||||
where = `WHERE g.status = $${params.length}`;
|
||||
}
|
||||
const countRows = await query<{ count: string }[]>(
|
||||
`SELECT COUNT(*)::text AS count FROM solo_encouragement_grants g ${where}`,
|
||||
params
|
||||
);
|
||||
const limitIdx = params.length + 1;
|
||||
const offsetIdx = params.length + 2;
|
||||
params.push(input.limit, input.offset);
|
||||
const items = await query<SoloEncouragementGrantListRow[]>(
|
||||
`SELECT g.id, g.user_id, g.streak_count, g.loss_raw::text, g.refund_percent::text,
|
||||
g.credit_raw::text, g.status, COALESCE(g.bet_ids, '{}') AS bet_ids,
|
||||
COALESCE(g.candle_open_ms_list, '{}') AS candle_open_ms_list,
|
||||
g.wallet_type_id, g.granted_by, g.granted_at, g.created_at,
|
||||
u.email AS user_email
|
||||
FROM solo_encouragement_grants g
|
||||
LEFT JOIN users u ON u.id = g.user_id
|
||||
${where}
|
||||
ORDER BY g.created_at DESC
|
||||
LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
|
||||
params
|
||||
);
|
||||
return { items, total: parseInt(countRows[0]?.count ?? '0', 10) || 0 };
|
||||
}
|
||||
|
||||
export type SoloEncouragementActiveStreakRow = SoloEncouragementUserStateRow & {
|
||||
user_email: string | null;
|
||||
};
|
||||
|
||||
export async function listActiveStreaks(input: {
|
||||
limit: number;
|
||||
offset: number;
|
||||
}): Promise<{ items: SoloEncouragementActiveStreakRow[]; total: number }> {
|
||||
const countRows = await query<{ count: string }[]>(
|
||||
`SELECT COUNT(*)::text AS count FROM solo_encouragement_user_state
|
||||
WHERE consecutive_solo_count > 0`
|
||||
);
|
||||
const items = await query<SoloEncouragementActiveStreakRow[]>(
|
||||
`SELECT s.user_id, s.consecutive_solo_count, s.loss_raw_sum::text,
|
||||
s.last_candle_open_ms::text, COALESCE(s.last_bet_ids, '{}') AS last_bet_ids,
|
||||
s.updated_at, u.email AS user_email
|
||||
FROM solo_encouragement_user_state s
|
||||
LEFT JOIN users u ON u.id = s.user_id
|
||||
WHERE s.consecutive_solo_count > 0
|
||||
ORDER BY s.consecutive_solo_count DESC, s.loss_raw_sum DESC
|
||||
LIMIT $1 OFFSET $2`,
|
||||
[input.limit, input.offset]
|
||||
);
|
||||
return { items, total: parseInt(countRows[0]?.count ?? '0', 10) || 0 };
|
||||
}
|
||||
@ -73,6 +73,7 @@ import {
|
||||
advertisementUpdateBodySchema,
|
||||
testWalletConfigBodySchema,
|
||||
shareCardSettingsBodySchema,
|
||||
soloEncouragementConfigBodySchema,
|
||||
supportConversationUpdateBodySchema,
|
||||
faqCategoryCreateBodySchema,
|
||||
faqCategoryUpdateBodySchema,
|
||||
@ -110,6 +111,7 @@ import * as notificationController from '../controllers/notificationController';
|
||||
import * as referralController from '../controllers/referralController';
|
||||
import * as adminCreditController from '../controllers/adminCreditController';
|
||||
import * as testWalletController from '../controllers/testWalletController';
|
||||
import * as soloEncouragementController from '../controllers/soloEncouragementController';
|
||||
import * as shareCardController from '../controllers/shareCardController';
|
||||
import * as countryController from '../controllers/countryController';
|
||||
import * as presenceController from '../controllers/presenceController';
|
||||
@ -437,6 +439,13 @@ router.get('/admin/test-wallet/credits', requireRoles('admin'), requirePermissio
|
||||
router.get('/admin/share-cards/settings', requireRoles('admin'), requirePermissions('settings.admin'), shareCardController.getAdminSettings);
|
||||
router.patch('/admin/share-cards/settings', requireRoles('admin'), requirePermissions('settings.admin'), validateBody(shareCardSettingsBodySchema), shareCardController.updateAdminSettings);
|
||||
|
||||
router.get('/admin/solo-encouragement/config', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.getAdminConfig);
|
||||
router.patch('/admin/solo-encouragement/config', requireRoles('admin'), requirePermissions('settings.admin'), validateBody(soloEncouragementConfigBodySchema), soloEncouragementController.updateAdminConfig);
|
||||
router.get('/admin/solo-encouragement/streaks', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.listActiveStreaks);
|
||||
router.get('/admin/solo-encouragement/grants', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.listGrants);
|
||||
router.post('/admin/solo-encouragement/grants/:grantId/grant', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.grantBonus);
|
||||
router.post('/admin/solo-encouragement/grants/:grantId/reject', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.rejectBonus);
|
||||
|
||||
router.get('/admin/countries', requireRoles('admin'), requirePermissions('settings.admin'), countryController.listCountriesAdmin);
|
||||
router.post('/admin/countries/sync', requireRoles('admin'), requirePermissions('settings.admin'), countryController.syncCountriesAdmin);
|
||||
router.patch('/admin/countries/:code', requireRoles('admin'), requirePermissions('settings.admin'), validateBody(countryRegistrationBodySchema), countryController.updateCountryRegistration);
|
||||
|
||||
@ -30,6 +30,7 @@ export const AUTHORIZED_LEDGER_TYPES = new Set([
|
||||
'referral_clawback',
|
||||
'bonus_to_main',
|
||||
'test_credit',
|
||||
'solo_encouragement_bonus',
|
||||
]);
|
||||
|
||||
export class SecurityBlockedError extends Error {
|
||||
|
||||
353
backend/src/services/soloEncouragementService.ts
Normal file
353
backend/src/services/soloEncouragementService.ts
Normal file
@ -0,0 +1,353 @@
|
||||
/**
|
||||
* 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';
|
||||
|
||||
export class SoloEncouragementError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'SoloEncouragementError';
|
||||
}
|
||||
}
|
||||
|
||||
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(lossRaw: bigint, refundPercent: number): bigint {
|
||||
if (lossRaw <= 0n || refundPercent <= 0) return 0n;
|
||||
// credit = floor(loss * percent / 100)
|
||||
return (lossRaw * 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 = exactly one distinct real-money bettor at this candle_open_ms.
|
||||
*/
|
||||
export async function onMaturitySettled(candleOpenMs: number): Promise<void> {
|
||||
let settings: Awaited<ReturnType<typeof soloRepo.getSettings>>;
|
||||
try {
|
||||
settings = await soloRepo.getSettings();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!settings.enabled) return;
|
||||
|
||||
const bets = await soloRepo.listSettledRealMoneyBetsForMaturity(candleOpenMs);
|
||||
if (!bets.length) return;
|
||||
|
||||
const byUser = new Map<string, typeof bets>();
|
||||
for (const bet of bets) {
|
||||
const list = byUser.get(bet.user_id) ?? [];
|
||||
list.push(bet);
|
||||
byUser.set(bet.user_id, list);
|
||||
}
|
||||
const userIds = [...byUser.keys()];
|
||||
const isSolo = userIds.length === 1;
|
||||
|
||||
if (!isSolo) {
|
||||
for (const userId of userIds) {
|
||||
await soloRepo.resetUserState(userId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const userId = userIds[0]!;
|
||||
const userBets = byUser.get(userId)!;
|
||||
const prev = await soloRepo.getUserState(userId);
|
||||
|
||||
// Idempotency: same maturity already applied
|
||||
if (prev?.last_candle_open_ms && Number(prev.last_candle_open_ms) === candleOpenMs) {
|
||||
return;
|
||||
}
|
||||
|
||||
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 nextLoss = BigInt(prev?.loss_raw_sum ?? '0') + lossThisMaturity;
|
||||
const prevBetIds = prev?.last_bet_ids ?? [];
|
||||
const allBetIds = [...prevBetIds, ...betIds];
|
||||
|
||||
await soloRepo.upsertUserState({
|
||||
userId,
|
||||
consecutiveSoloCount: nextCount,
|
||||
lossRawSum: nextLoss.toString(),
|
||||
lastCandleOpenMs: candleOpenMs,
|
||||
lastBetIds: allBetIds.slice(-50),
|
||||
});
|
||||
|
||||
if (nextCount < settings.min_consecutive_solo) return;
|
||||
|
||||
const refundPercent = Number(settings.refund_percent);
|
||||
const creditRaw = computeCreditRaw(nextLoss, refundPercent);
|
||||
const candleList = [candleOpenMs];
|
||||
|
||||
if (creditRaw <= 0n) {
|
||||
await soloRepo.createGrant({
|
||||
userId,
|
||||
streakCount: nextCount,
|
||||
lossRaw: nextLoss.toString(),
|
||||
refundPercent,
|
||||
creditRaw: '0',
|
||||
status: 'skipped',
|
||||
betIds: allBetIds.slice(-50),
|
||||
candleOpenMsList: candleList,
|
||||
walletTypeId: settings.wallet_type_id,
|
||||
});
|
||||
await soloRepo.resetUserState(userId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (settings.auto_grant) {
|
||||
const grant = await soloRepo.createGrant({
|
||||
userId,
|
||||
streakCount: nextCount,
|
||||
lossRaw: nextLoss.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: nextLoss.toString(),
|
||||
streakCount: nextCount,
|
||||
refundPercent,
|
||||
});
|
||||
await soloRepo.resetUserState(userId);
|
||||
return;
|
||||
}
|
||||
|
||||
await soloRepo.createGrant({
|
||||
userId,
|
||||
streakCount: nextCount,
|
||||
lossRaw: nextLoss.toString(),
|
||||
refundPercent,
|
||||
creditRaw: creditRaw.toString(),
|
||||
status: 'eligible',
|
||||
betIds: allBetIds.slice(-50),
|
||||
candleOpenMsList: candleList,
|
||||
walletTypeId: settings.wallet_type_id,
|
||||
});
|
||||
await soloRepo.resetUserState(userId);
|
||||
}
|
||||
|
||||
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: 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: 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 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 };
|
||||
}
|
||||
@ -206,6 +206,16 @@ export const shareCardSettingsBodySchema = atLeastOneField(
|
||||
})
|
||||
);
|
||||
|
||||
export const soloEncouragementConfigBodySchema = atLeastOneField(
|
||||
z.object({
|
||||
enabled: z.boolean().optional(),
|
||||
minConsecutiveSolo: z.number().int().min(1).max(1000).optional(),
|
||||
refundPercent: z.number().min(0).max(100).optional(),
|
||||
autoGrant: z.boolean().optional(),
|
||||
walletTypeId: z.number().int().positive().optional(),
|
||||
})
|
||||
);
|
||||
|
||||
// —— Support ——
|
||||
|
||||
export const supportConversationUpdateBodySchema = atLeastOneField(
|
||||
|
||||
@ -27,6 +27,7 @@ import { ReferralPage } from '../../features/referral/ReferralPage';
|
||||
import { ReferralFraudDashboardPage } from '../../features/referral/ReferralFraudDashboardPage';
|
||||
import { TestWalletAdminPage } from '../../features/test-wallet/TestWalletAdminPage';
|
||||
import { ShareCardsAdminPage } from '../../features/share-cards/ShareCardsAdminPage';
|
||||
import { SoloEncouragementAdminPage } from '../../features/solo-encouragement/SoloEncouragementAdminPage';
|
||||
import { ShareResultVerifyPage } from '../../features/share-cards/ShareResultVerifyPage';
|
||||
import { SecurityAdminPage } from '../../features/security/SecurityAdminPage';
|
||||
import { ReportsHubPage } from '../../features/reports/ReportsHubPage';
|
||||
@ -110,6 +111,7 @@ export const router = createBrowserRouter([
|
||||
{ path: 'admin/referral/fraud', element: <ReferralFraudDashboardPage /> },
|
||||
{ path: 'admin/test-wallet', element: <TestWalletAdminPage /> },
|
||||
{ path: 'admin/share-cards', element: <ShareCardsAdminPage /> },
|
||||
{ path: 'admin/solo-encouragement', element: <SoloEncouragementAdminPage /> },
|
||||
{ path: 'admin/countries', element: <CountriesAdminPage /> },
|
||||
{ path: 'admin/network', element: <NetworkStatusPage /> },
|
||||
],
|
||||
|
||||
@ -11,6 +11,7 @@ import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceW
|
||||
import GroupAddRoundedIcon from '@mui/icons-material/GroupAddRounded';
|
||||
import ScienceRoundedIcon from '@mui/icons-material/ScienceRounded';
|
||||
import IosShareRoundedIcon from '@mui/icons-material/IosShareRounded';
|
||||
import VolunteerActivismRoundedIcon from '@mui/icons-material/VolunteerActivismRounded';
|
||||
import PublicRoundedIcon from '@mui/icons-material/PublicRounded';
|
||||
import LanRoundedIcon from '@mui/icons-material/LanRounded';
|
||||
import SecurityRoundedIcon from '@mui/icons-material/SecurityRounded';
|
||||
@ -29,6 +30,7 @@ type OptionCardKey =
|
||||
| 'referralFraud'
|
||||
| 'testWallet'
|
||||
| 'shareCards'
|
||||
| 'soloEncouragement'
|
||||
| 'security'
|
||||
| 'network'
|
||||
| 'faq'
|
||||
@ -119,6 +121,15 @@ const OPTION_CARDS: OptionCardConfig[] = [
|
||||
bg: 'rgba(41,182,246,0.16)',
|
||||
border: 'rgba(41,182,246,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'soloEncouragement',
|
||||
path: '/admin/solo-encouragement',
|
||||
icon: VolunteerActivismRoundedIcon,
|
||||
badgeKey: 'soloBonus',
|
||||
badgeColor: 'secondary',
|
||||
bg: 'rgba(236,72,153,0.14)',
|
||||
border: 'rgba(236,72,153,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'security',
|
||||
path: '/admin/security',
|
||||
|
||||
@ -0,0 +1,366 @@
|
||||
/**
|
||||
* Admin: solo real-money encouragement bonus settings, active streaks, and grants.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
Chip,
|
||||
FormControlLabel,
|
||||
Stack,
|
||||
Switch,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import VolunteerActivismRoundedIcon from '@mui/icons-material/VolunteerActivismRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
import { rawToHuman } from '../wallet/utils/walletFormat';
|
||||
|
||||
type SoloConfig = {
|
||||
enabled: boolean;
|
||||
minConsecutiveSolo: number;
|
||||
refundPercent: number;
|
||||
autoGrant: boolean;
|
||||
walletTypeId: number;
|
||||
walletCode: string | null;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
type StreakItem = {
|
||||
userId: string;
|
||||
userEmail: string | null;
|
||||
consecutiveSoloCount: number;
|
||||
lossRaw: string;
|
||||
projectedCreditRaw: string;
|
||||
nearEligible: boolean;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
type GrantItem = {
|
||||
id: string;
|
||||
userId: string;
|
||||
userEmail: string | null;
|
||||
streakCount: number;
|
||||
lossRaw: string;
|
||||
refundPercent: number;
|
||||
creditRaw: string;
|
||||
status: string;
|
||||
createdAt: string;
|
||||
grantedAt: string | null;
|
||||
};
|
||||
|
||||
const USDT_DECIMALS = 6;
|
||||
|
||||
export function SoloEncouragementAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [form, setForm] = useState<SoloConfig | null>(null);
|
||||
const [grantFilter, setGrantFilter] = useState<'eligible' | 'granted' | 'all'>('eligible');
|
||||
|
||||
const configQ = useQuery({
|
||||
queryKey: ['admin-solo-encouragement-config'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<SoloConfig>('/api/v1/admin/solo-encouragement/config');
|
||||
setForm(res.data);
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
const streaksQ = useQuery({
|
||||
queryKey: ['admin-solo-encouragement-streaks'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<{ items: StreakItem[]; total: number; minConsecutiveSolo: number }>(
|
||||
'/api/v1/admin/solo-encouragement/streaks?limit=50'
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
const grantsQ = useQuery({
|
||||
queryKey: ['admin-solo-encouragement-grants', grantFilter],
|
||||
queryFn: async () => {
|
||||
const status = grantFilter === 'all' ? '' : `status=${grantFilter}&`;
|
||||
const res = await api.get<{ items: GrantItem[]; total: number }>(
|
||||
`/api/v1/admin/solo-encouragement/grants?${status}limit=50`
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (configQ.data && !form) setForm(configQ.data);
|
||||
}, [configQ.data, form]);
|
||||
|
||||
const saveMut = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!form) return;
|
||||
const res = await api.patch<SoloConfig>('/api/v1/admin/solo-encouragement/config', {
|
||||
enabled: form.enabled,
|
||||
minConsecutiveSolo: form.minConsecutiveSolo,
|
||||
refundPercent: form.refundPercent,
|
||||
autoGrant: form.autoGrant,
|
||||
walletTypeId: form.walletTypeId,
|
||||
});
|
||||
return res.data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
if (data) setForm(data);
|
||||
void qc.invalidateQueries({ queryKey: ['admin-solo-encouragement-config'] });
|
||||
},
|
||||
});
|
||||
|
||||
const grantMut = useMutation({
|
||||
mutationFn: async (grantId: string) => {
|
||||
await api.post(`/api/v1/admin/solo-encouragement/grants/${grantId}/grant`);
|
||||
},
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: ['admin-solo-encouragement-grants'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-solo-encouragement-streaks'] });
|
||||
},
|
||||
});
|
||||
|
||||
const rejectMut = useMutation({
|
||||
mutationFn: async (grantId: string) => {
|
||||
await api.post(`/api/v1/admin/solo-encouragement/grants/${grantId}/reject`);
|
||||
},
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: ['admin-solo-encouragement-grants'] });
|
||||
},
|
||||
});
|
||||
|
||||
if (configQ.isLoading || !form) {
|
||||
return <Typography sx={{ p: 2 }}>{t('admin.soloEncouragement.loading')}</Typography>;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={0.75} sx={{ mb: 2.5 }}>
|
||||
<Stack direction="row" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<VolunteerActivismRoundedIcon color="secondary" />
|
||||
<Typography variant="h4" sx={{ fontWeight: 900, fontSize: { xs: '1.65rem', sm: '2.125rem' } }}>
|
||||
{t('admin.soloEncouragement.title')}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
label={form.enabled ? t('admin.soloEncouragement.enabled') : t('admin.soloEncouragement.disabled')}
|
||||
color={form.enabled ? 'success' : 'default'}
|
||||
/>
|
||||
</Stack>
|
||||
<Typography sx={{ opacity: 0.7 }}>{t('admin.soloEncouragement.subtitle')}</Typography>
|
||||
</Stack>
|
||||
|
||||
<Card sx={{ borderRadius: 3, mb: 3 }}>
|
||||
<CardContent>
|
||||
<Stack spacing={2}>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.enabled}
|
||||
onChange={(e) => setForm({ ...form, enabled: e.target.checked })}
|
||||
/>
|
||||
}
|
||||
label={t('admin.soloEncouragement.enableFeature')}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.soloEncouragement.minConsecutive')}
|
||||
type="number"
|
||||
value={form.minConsecutiveSolo}
|
||||
onChange={(e) =>
|
||||
setForm({ ...form, minConsecutiveSolo: Math.max(1, Number(e.target.value) || 1) })
|
||||
}
|
||||
helperText={t('admin.soloEncouragement.minConsecutiveHelper')}
|
||||
fullWidth
|
||||
disabled={!form.enabled}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.soloEncouragement.refundPercent')}
|
||||
type="number"
|
||||
value={form.refundPercent}
|
||||
onChange={(e) =>
|
||||
setForm({
|
||||
...form,
|
||||
refundPercent: Math.min(100, Math.max(0, Number(e.target.value) || 0)),
|
||||
})
|
||||
}
|
||||
helperText={t('admin.soloEncouragement.refundPercentHelper')}
|
||||
fullWidth
|
||||
disabled={!form.enabled}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Switch
|
||||
checked={form.autoGrant}
|
||||
onChange={(e) => setForm({ ...form, autoGrant: e.target.checked })}
|
||||
disabled={!form.enabled}
|
||||
/>
|
||||
}
|
||||
label={t('admin.soloEncouragement.autoGrant')}
|
||||
/>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mt: -1 }}>
|
||||
{t('admin.soloEncouragement.autoGrantHelper')}
|
||||
</Typography>
|
||||
|
||||
{saveMut.isError && (
|
||||
<Alert severity="error">
|
||||
{(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data
|
||||
?.error ?? t('admin.soloEncouragement.saveFailed')}
|
||||
</Alert>
|
||||
)}
|
||||
{saveMut.isSuccess && <Alert severity="success">{t('admin.soloEncouragement.saved')}</Alert>}
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => saveMut.mutate()}
|
||||
disabled={saveMut.isPending}
|
||||
sx={{ alignSelf: 'flex-start' }}
|
||||
>
|
||||
{saveMut.isPending ? t('admin.soloEncouragement.saving') : t('admin.soloEncouragement.save')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, mb: 1.5 }}>
|
||||
{t('admin.soloEncouragement.activeStreaks')}
|
||||
</Typography>
|
||||
<Card sx={{ borderRadius: 3, mb: 3 }}>
|
||||
<CardContent sx={{ p: 0, '&:last-child': { pb: 0 } }}>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.soloEncouragement.user')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.streak')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.loss')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.projectedBonus')}</TableCell>
|
||||
<TableCell>{t('admin.soloEncouragement.status')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{(streaksQ.data?.items ?? []).map((row) => (
|
||||
<TableRow key={row.userId}>
|
||||
<TableCell>{row.userEmail ?? row.userId}</TableCell>
|
||||
<TableCell align="right">{row.consecutiveSoloCount}</TableCell>
|
||||
<TableCell align="right">
|
||||
{rawToHuman(row.lossRaw, USDT_DECIMALS)} USDT
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
{rawToHuman(row.projectedCreditRaw, USDT_DECIMALS)} USDT
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{row.nearEligible ? (
|
||||
<Chip size="small" color="warning" label={t('admin.soloEncouragement.nearEligible')} />
|
||||
) : (
|
||||
<Chip size="small" variant="outlined" label={t('admin.soloEncouragement.inProgress')} />
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{!streaksQ.data?.items?.length && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} sx={{ opacity: 0.7 }}>
|
||||
{t('admin.soloEncouragement.noStreaks')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 1.5, flexWrap: 'wrap' }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 900, mr: 1 }}>
|
||||
{t('admin.soloEncouragement.grants')}
|
||||
</Typography>
|
||||
{(['eligible', 'granted', 'all'] as const).map((f) => (
|
||||
<Chip
|
||||
key={f}
|
||||
size="small"
|
||||
label={t(`admin.soloEncouragement.filter.${f}`)}
|
||||
color={grantFilter === f ? 'primary' : 'default'}
|
||||
variant={grantFilter === f ? 'filled' : 'outlined'}
|
||||
onClick={() => setGrantFilter(f)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 0, '&:last-child': { pb: 0 } }}>
|
||||
<ScrollableTable>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.soloEncouragement.date')}</TableCell>
|
||||
<TableCell>{t('admin.soloEncouragement.user')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.streak')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.loss')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.bonus')}</TableCell>
|
||||
<TableCell>{t('admin.soloEncouragement.status')}</TableCell>
|
||||
<TableCell align="right">{t('admin.soloEncouragement.actions')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{(grantsQ.data?.items ?? []).map((row) => (
|
||||
<TableRow key={row.id}>
|
||||
<TableCell>{new Date(row.createdAt).toLocaleString()}</TableCell>
|
||||
<TableCell>{row.userEmail ?? row.userId}</TableCell>
|
||||
<TableCell align="right">{row.streakCount}</TableCell>
|
||||
<TableCell align="right">
|
||||
{rawToHuman(row.lossRaw, USDT_DECIMALS)} USDT
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
{rawToHuman(row.creditRaw, USDT_DECIMALS)} USDT ({row.refundPercent}%)
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Chip size="small" label={row.status} color={row.status === 'eligible' ? 'warning' : row.status === 'granted' ? 'success' : 'default'} />
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
{row.status === 'eligible' && (
|
||||
<Stack direction="row" spacing={0.5} sx={{ justifyContent: 'flex-end' }}>
|
||||
<Button
|
||||
size="small"
|
||||
variant="contained"
|
||||
color="success"
|
||||
disabled={grantMut.isPending}
|
||||
onClick={() => grantMut.mutate(row.id)}
|
||||
>
|
||||
{t('admin.soloEncouragement.grant')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
color="inherit"
|
||||
disabled={rejectMut.isPending}
|
||||
onClick={() => rejectMut.mutate(row.id)}
|
||||
>
|
||||
{t('admin.soloEncouragement.reject')}
|
||||
</Button>
|
||||
</Stack>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{!grantsQ.data?.items?.length && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} sx={{ opacity: 0.7 }}>
|
||||
{t('admin.soloEncouragement.noGrants')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@ -919,6 +919,7 @@ export const en = {
|
||||
levelsBonus: 'Levels / Bonus',
|
||||
sybilReview: 'Sybil / Review / Clawback',
|
||||
playMoney: 'Play money',
|
||||
soloBonus: 'Solo bonus',
|
||||
alertsLedger: 'Alerts / Ledger',
|
||||
staff: 'Staff',
|
||||
registration: 'Registration',
|
||||
@ -959,6 +960,10 @@ export const en = {
|
||||
title: 'Share Cards',
|
||||
description: 'Allow players to share prediction results with preview cards and authenticity QR.',
|
||||
},
|
||||
soloEncouragement: {
|
||||
title: 'Solo encouragement',
|
||||
description: 'Bonus refunds for users who keep playing alone with real funds (Main/Bonus).',
|
||||
},
|
||||
security: {
|
||||
title: 'Security',
|
||||
description: 'Integrity checks, security alerts, in-app notifications, and approved ledger credits.',
|
||||
@ -1799,6 +1804,47 @@ export const en = {
|
||||
saveFailed: 'Save failed',
|
||||
saved: 'Settings saved.',
|
||||
},
|
||||
soloEncouragement: {
|
||||
title: 'Solo encouragement bonus',
|
||||
enabled: 'Enabled',
|
||||
disabled: 'Disabled',
|
||||
subtitle:
|
||||
'Reward players who keep placing real-money predictions alone (Main or Bonus wallet). Test Wallet stakes are ignored.',
|
||||
loading: 'Loading solo encouragement settings…',
|
||||
enableFeature: 'Enable solo encouragement tracking',
|
||||
minConsecutive: 'Min consecutive solo predictions',
|
||||
minConsecutiveHelper: 'e.g. 3 — user must play alone this many maturities in a row',
|
||||
refundPercent: 'Refund percent of losses (%)',
|
||||
refundPercentHelper: 'Bonus = percent × total stake lost during the solo streak',
|
||||
autoGrant: 'Auto-grant bonus when threshold is reached',
|
||||
autoGrantHelper:
|
||||
'When off, eligible bonuses appear below for manual approval. When on, credit bonus wallet automatically and notify the user.',
|
||||
save: 'Save settings',
|
||||
saving: 'Saving…',
|
||||
saved: 'Settings saved.',
|
||||
saveFailed: 'Save failed',
|
||||
activeStreaks: 'Active solo streaks',
|
||||
grants: 'Encouragement grants',
|
||||
user: 'User',
|
||||
streak: 'Streak',
|
||||
loss: 'Losses',
|
||||
projectedBonus: 'Projected bonus',
|
||||
bonus: 'Bonus',
|
||||
status: 'Status',
|
||||
date: 'Date',
|
||||
actions: 'Actions',
|
||||
nearEligible: 'Near eligible',
|
||||
inProgress: 'In progress',
|
||||
noStreaks: 'No active solo streaks.',
|
||||
noGrants: 'No grants yet.',
|
||||
grant: 'Grant',
|
||||
reject: 'Reject',
|
||||
filter: {
|
||||
eligible: 'Eligible',
|
||||
granted: 'Granted',
|
||||
all: 'All',
|
||||
},
|
||||
},
|
||||
network: {
|
||||
title: 'Network & environment',
|
||||
subtitle:
|
||||
|
||||
@ -933,6 +933,7 @@ export const fr = {
|
||||
levelsBonus: 'Niveaux / Bonus',
|
||||
sybilReview: 'Sybil / Revue / Récupération',
|
||||
playMoney: 'Argent fictif',
|
||||
soloBonus: 'Bonus solo',
|
||||
alertsLedger: 'Alertes / Grand livre',
|
||||
staff: 'Équipe',
|
||||
registration: 'Inscription',
|
||||
@ -974,6 +975,11 @@ export const fr = {
|
||||
description:
|
||||
'Autoriser les joueurs à partager leurs résultats de prédiction avec carte et QR d’authenticité.',
|
||||
},
|
||||
soloEncouragement: {
|
||||
title: 'Encouragement solo',
|
||||
description:
|
||||
'Bonus de remboursement pour les joueurs qui continuent seuls avec des fonds réels (Main/Bonus).',
|
||||
},
|
||||
security: {
|
||||
title: 'Sécurité',
|
||||
description: 'Contrôles d’intégrité, alertes sécurité, notifications in-app et crédits grand livre approuvés.',
|
||||
@ -1815,6 +1821,47 @@ export const fr = {
|
||||
saveFailed: 'Échec de l’enregistrement',
|
||||
saved: 'Paramètres enregistrés.',
|
||||
},
|
||||
soloEncouragement: {
|
||||
title: 'Bonus d’encouragement solo',
|
||||
enabled: 'Activé',
|
||||
disabled: 'Désactivé',
|
||||
subtitle:
|
||||
'Récompensez les joueurs qui continuent à placer des prédictions seuls avec des fonds réels (Main ou Bonus). Les mises Test sont ignorées.',
|
||||
loading: 'Chargement des paramètres d’encouragement solo…',
|
||||
enableFeature: 'Activer le suivi d’encouragement solo',
|
||||
minConsecutive: 'Prédictions solo successives minimales',
|
||||
minConsecutiveHelper: 'ex. 3 — l’utilisateur doit jouer seul pendant autant d’échéances d’affilée',
|
||||
refundPercent: 'Pourcentage de remboursement des pertes (%)',
|
||||
refundPercentHelper: 'Bonus = pourcentage × total des mises perdues pendant la série solo',
|
||||
autoGrant: 'Attribuer automatiquement le bonus au seuil',
|
||||
autoGrantHelper:
|
||||
'Si désactivé, les bonus éligibles apparaissent ci-dessous pour validation manuelle. Si activé, crédit automatique sur le wallet bonus + notification.',
|
||||
save: 'Enregistrer les paramètres',
|
||||
saving: 'Enregistrement…',
|
||||
saved: 'Paramètres enregistrés.',
|
||||
saveFailed: 'Échec de l’enregistrement',
|
||||
activeStreaks: 'Séries solo actives',
|
||||
grants: 'Bonus d’encouragement',
|
||||
user: 'Utilisateur',
|
||||
streak: 'Série',
|
||||
loss: 'Pertes',
|
||||
projectedBonus: 'Bonus projeté',
|
||||
bonus: 'Bonus',
|
||||
status: 'Statut',
|
||||
date: 'Date',
|
||||
actions: 'Actions',
|
||||
nearEligible: 'Presque éligible',
|
||||
inProgress: 'En cours',
|
||||
noStreaks: 'Aucune série solo active.',
|
||||
noGrants: 'Aucun bonus pour l’instant.',
|
||||
grant: 'Accorder',
|
||||
reject: 'Refuser',
|
||||
filter: {
|
||||
eligible: 'Éligibles',
|
||||
granted: 'Accordés',
|
||||
all: 'Tous',
|
||||
},
|
||||
},
|
||||
network: {
|
||||
title: 'Réseau & environnement',
|
||||
subtitle:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user