After adding the option to grant commission for solo prediction3
This commit is contained in:
parent
da7c2f7866
commit
6ee8461734
2
backend/dist/reports/definitions.d.ts.map
vendored
2
backend/dist/reports/definitions.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"definitions.d.ts","sourceRoot":"","sources":["../../src/reports/definitions.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAEhE,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,WAAW,GAAG,OAAO,GAAG,WAAW,CAAC;AAE3E,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG,aAAa,CAAC;AAEvD,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;CAC/C,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,YAAY,CAAC;IACrB,mDAAmD;IACnD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC,CAAC;IACtD,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;CACjC,CAAC;AAEF,eAAO,MAAM,kBAAkB,EAAE,gBAAgB,EA+ShD,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAE7E;AAED,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,cAAc,EAAE,MAAM,CAKjE,CAAC"}
|
||||
{"version":3,"file":"definitions.d.ts","sourceRoot":"","sources":["../../src/reports/definitions.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAEhE,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,WAAW,GAAG,OAAO,GAAG,WAAW,CAAC;AAE3E,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG,aAAa,CAAC;AAEvD,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;CAC/C,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,cAAc,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,YAAY,CAAC;IACrB,mDAAmD;IACnD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC,CAAC;IACtD,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;CACjC,CAAC;AAEF,eAAO,MAAM,kBAAkB,EAAE,gBAAgB,EAyThD,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAE7E;AAED,eAAO,MAAM,sBAAsB,EAAE,MAAM,CAAC,cAAc,EAAE,MAAM,CAKjE,CAAC"}
|
||||
9
backend/dist/reports/definitions.js
vendored
9
backend/dist/reports/definitions.js
vendored
@ -151,6 +151,15 @@ exports.REPORT_DEFINITIONS = [
|
||||
defaultSortField: 'created_at',
|
||||
defaultSortDir: 'desc',
|
||||
},
|
||||
{
|
||||
key: 'financial-encouragement-grants',
|
||||
category: 'financial',
|
||||
title: 'Bonus d’encouragement solo',
|
||||
description: 'Grants d’encouragement solo (éligibles, accordés, refusés, ignorés) avec mises/pertes et crédit bonus.',
|
||||
source: 'reports-api',
|
||||
defaultSortField: 'created_at',
|
||||
defaultSortDir: 'desc',
|
||||
},
|
||||
{
|
||||
key: 'financial-adjustments',
|
||||
category: 'financial',
|
||||
|
||||
2
backend/dist/reports/definitions.js.map
vendored
2
backend/dist/reports/definitions.js.map
vendored
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"reportsRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/reportsRepository.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC,CAAC;IACnD,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAChE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,OAAO,CAAC,EAAE,aAAa,CAAC;CACzB,CAAC;AAiEF,wBAAsB,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAyCzG;AA2pBD,wBAAsB,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEhH"}
|
||||
{"version":3,"file":"reportsRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/reportsRepository.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC,CAAC;IACnD,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAChE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,OAAO,CAAC,EAAE,aAAa,CAAC;CACzB,CAAC;AAiEF,wBAAsB,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA2CzG;AAywBD,wBAAsB,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEhH"}
|
||||
89
backend/dist/repositories/reportsRepository.js
vendored
89
backend/dist/repositories/reportsRepository.js
vendored
@ -75,6 +75,8 @@ async function runReport(reportKey, options) {
|
||||
return listDepositUsers(reportKey, normalized);
|
||||
case 'financial-bonuses':
|
||||
return listBonuses(reportKey, normalized);
|
||||
case 'financial-encouragement-grants':
|
||||
return listEncouragementGrants(reportKey, normalized);
|
||||
case 'financial-adjustments':
|
||||
return listAdjustments(reportKey, normalized);
|
||||
case 'financial-wallet-balances':
|
||||
@ -221,6 +223,93 @@ async function listDepositUsers(reportKey, options) {
|
||||
summary,
|
||||
};
|
||||
}
|
||||
async function listEncouragementGrants(reportKey, options) {
|
||||
const columns = [
|
||||
{ field: 'id', headerName: 'ID', type: 'string' },
|
||||
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
||||
{ field: 'status', headerName: 'Status', type: 'string' },
|
||||
{ field: 'streak_count', headerName: 'Streak', type: 'number' },
|
||||
{ field: 'loss_raw', headerName: 'Losses / stake base (USDT)', type: 'money' },
|
||||
{ field: 'refund_percent', headerName: 'Refund %', type: 'number' },
|
||||
{ field: 'credit_raw', headerName: 'Bonus (USDT)', type: 'money' },
|
||||
{ field: 'granted_at', headerName: 'Granted at', type: 'date' },
|
||||
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
||||
];
|
||||
const date = dateClause('g.created_at', options.from, options.to, 1);
|
||||
const values = [...date.values];
|
||||
let i = values.length + 1;
|
||||
const parts = [date.sql];
|
||||
if (options.search?.trim()) {
|
||||
parts.push(`(g.id::text ILIKE $${i} OR g.user_id::text ILIKE $${i} OR g.status ILIKE $${i})`);
|
||||
values.push(`%${options.search.trim()}%`);
|
||||
i += 1;
|
||||
}
|
||||
const statusPreset = options.preset?.status;
|
||||
if (typeof statusPreset === 'string' && statusPreset.trim()) {
|
||||
parts.push(`g.status = $${i++}`);
|
||||
values.push(statusPreset.trim());
|
||||
}
|
||||
const idClause = idsFilter('g.id', options.ids, values, i);
|
||||
i = idClause.nextIdx;
|
||||
const whereSql = `${parts.join(' AND ')}${idClause.sql}`;
|
||||
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
||||
const summaryRows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS total_count,
|
||||
COUNT(DISTINCT g.user_id)::text AS unique_users,
|
||||
COALESCE(SUM(g.credit_raw), 0)::text AS total_amount
|
||||
FROM solo_encouragement_grants g
|
||||
WHERE ${whereSql}`, values);
|
||||
const summary = {
|
||||
totalCount: num(summaryRows[0]?.total_count),
|
||||
uniqueUsers: num(summaryRows[0]?.unique_users),
|
||||
totalAmountRaw: num(summaryRows[0]?.total_amount),
|
||||
};
|
||||
if (useKeysetPagination(reportKey, options)) {
|
||||
const decoded = options.cursor ? (0, reportListCursor_1.decodeReportCursor)(options.cursor) : null;
|
||||
let keysetSql = '';
|
||||
if (decoded) {
|
||||
values.push(decoded.createdAt, decoded.id);
|
||||
const op = sortDir === 'asc' ? '>' : '<';
|
||||
keysetSql = ` AND (g.created_at, g.id) ${op} ($${i}::timestamptz, $${i + 1}::uuid)`;
|
||||
i += 2;
|
||||
}
|
||||
const includeTotal = options.includeTotal !== false && !options.cursor;
|
||||
const total = includeTotal ? summary.totalCount ?? 0 : 0;
|
||||
values.push(options.limit + 1);
|
||||
const rows = await (0, connection_1.query)(`SELECT g.id, g.user_id, g.status, g.streak_count,
|
||||
g.loss_raw::text AS loss_raw, g.refund_percent::text AS refund_percent,
|
||||
g.credit_raw::text AS credit_raw, g.granted_at, g.created_at
|
||||
FROM solo_encouragement_grants g
|
||||
WHERE ${whereSql}${keysetSql}
|
||||
ORDER BY g.created_at ${sortDir === 'asc' ? 'ASC' : 'DESC'}, g.id ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
||||
LIMIT $${i}`, values);
|
||||
const hasMore = rows.length > options.limit;
|
||||
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
||||
const nextCursor = hasMore && items.length > 0
|
||||
? (0, reportListCursor_1.buildCursorFromRow)(sortDir, items[items.length - 1])
|
||||
: null;
|
||||
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary };
|
||||
}
|
||||
const countRows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS c FROM solo_encouragement_grants g WHERE ${whereSql}`, values);
|
||||
const allowedSort = new Set(['created_at', 'user_id', 'streak_count', 'loss_raw', 'credit_raw', 'status']);
|
||||
const sortField = options.sortBy && allowedSort.has(options.sortBy) ? options.sortBy : 'created_at';
|
||||
const sortSql = `g.${sortField} ${sortDir === 'asc' ? 'ASC' : 'DESC'}`;
|
||||
const offset = options.offset ?? 0;
|
||||
values.push(options.limit, offset);
|
||||
const rows = await (0, connection_1.query)(`SELECT g.id, g.user_id, g.status, g.streak_count,
|
||||
g.loss_raw::text AS loss_raw, g.refund_percent::text AS refund_percent,
|
||||
g.credit_raw::text AS credit_raw, g.granted_at, g.created_at
|
||||
FROM solo_encouragement_grants g
|
||||
WHERE ${whereSql}
|
||||
ORDER BY ${sortSql}
|
||||
LIMIT $${i++} OFFSET $${i}`, values);
|
||||
return {
|
||||
items: serializeDateRows(rows),
|
||||
total: parseInt(countRows[0]?.c ?? '0', 10),
|
||||
columns,
|
||||
totalIsExact: true,
|
||||
summary,
|
||||
};
|
||||
}
|
||||
async function listBonuses(reportKey, options) {
|
||||
const columns = [
|
||||
{ field: 'id', headerName: 'ID', type: 'string' },
|
||||
|
||||
File diff suppressed because one or more lines are too long
2
backend/dist/routes/index.d.ts.map
vendored
2
backend/dist/routes/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAkYxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAmYxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
1
backend/dist/routes/index.js
vendored
1
backend/dist/routes/index.js
vendored
@ -241,6 +241,7 @@ router.patch('/admin/share-cards/settings', (0, auth_1.requireRoles)('admin'), (
|
||||
router.get('/admin/solo-encouragement/config', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.getAdminConfig);
|
||||
router.patch('/admin/solo-encouragement/config', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.soloEncouragementConfigBodySchema), soloEncouragementController.updateAdminConfig);
|
||||
router.get('/admin/solo-encouragement/streaks', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.listActiveStreaks);
|
||||
router.get('/admin/solo-encouragement/grants/export', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.exportGrants);
|
||||
router.get('/admin/solo-encouragement/grants', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.listGrants);
|
||||
router.post('/admin/solo-encouragement/grants/:grantId/grant', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.grantBonus);
|
||||
router.post('/admin/solo-encouragement/grants/:grantId/reject', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.rejectBonus);
|
||||
|
||||
2
backend/dist/routes/index.js.map
vendored
2
backend/dist/routes/index.js.map
vendored
File diff suppressed because one or more lines are too long
2
backend/dist/utils/reportListCursor.d.ts.map
vendored
2
backend/dist/utils/reportListCursor.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"reportListCursor.d.ts","sourceRoot":"","sources":["../../src/utils/reportListCursor.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,MAAM,CAAC;AAE3C,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,EAAE,aAAa,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,eAAO,MAAM,4BAA4B,aAavC,CAAC;AAEH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAEhF;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAE/D;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAWrE;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,aAAa,EACtB,GAAG,EAAE;IAAE,UAAU,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,OAAO,CAAA;CAAE,GACxC,MAAM,CAWR;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,MAAM,CAGhF;AAED,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,aAAa,EACtB,MAAM,EAAE,YAAY,GAAG,IAAI,EAC3B,MAAM,EAAE,OAAO,EAAE,EACjB,UAAU,EAAE,MAAM,GACjB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAQpC"}
|
||||
{"version":3,"file":"reportListCursor.d.ts","sourceRoot":"","sources":["../../src/utils/reportListCursor.ts"],"names":[],"mappings":"AAAA,yEAAyE;AAEzE,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,MAAM,CAAC;AAE3C,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,EAAE,aAAa,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,EAAE,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,eAAO,MAAM,4BAA4B,aAcvC,CAAC;AAEH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAEhF;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAE/D;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAWrE;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,aAAa,EACtB,GAAG,EAAE;IAAE,UAAU,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,OAAO,CAAA;CAAE,GACxC,MAAM,CAWR;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,MAAM,CAGhF;AAED,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,aAAa,EACtB,MAAM,EAAE,YAAY,GAAG,IAAI,EAC3B,MAAM,EAAE,OAAO,EAAE,EACjB,UAAU,EAAE,MAAM,GACjB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAQpC"}
|
||||
1
backend/dist/utils/reportListCursor.js
vendored
1
backend/dist/utils/reportListCursor.js
vendored
@ -12,6 +12,7 @@ exports.CURSOR_PAGINATED_REPORT_KEYS = new Set([
|
||||
'financial-deposits',
|
||||
'financial-withdrawals',
|
||||
'financial-bonuses',
|
||||
'financial-encouragement-grants',
|
||||
'financial-adjustments',
|
||||
'games-predictions',
|
||||
'games-predictions-real',
|
||||
|
||||
2
backend/dist/utils/reportListCursor.js.map
vendored
2
backend/dist/utils/reportListCursor.js.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"reportListCursor.js","sourceRoot":"","sources":["../../src/utils/reportListCursor.ts"],"names":[],"mappings":"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"}
|
||||
{"version":3,"file":"reportListCursor.js","sourceRoot":"","sources":["../../src/utils/reportListCursor.ts"],"names":[],"mappings":"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"}
|
||||
@ -82,17 +82,32 @@ export async function validateReferralCode(req: Request, res: Response): Promise
|
||||
}
|
||||
|
||||
/**
|
||||
* Public captcha configuration for the login form (Turnstile).
|
||||
* Public captcha configuration for the login form (Turnstile or built-in math).
|
||||
*/
|
||||
export async function getCaptchaConfig(_req: Request, res: Response): Promise<void> {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
const afterFailures = settings.login_captcha_after_failures;
|
||||
const provider = captchaService.getCaptchaProvider();
|
||||
res.json({
|
||||
enabled: captchaService.isCaptchaConfigured(),
|
||||
siteKey: captchaService.getCaptchaSiteKey(),
|
||||
afterFailures: settings.login_captcha_after_failures,
|
||||
enabled: captchaService.isCaptchaAvailable(afterFailures),
|
||||
provider,
|
||||
siteKey: provider === 'turnstile' ? captchaService.getCaptchaSiteKey() : null,
|
||||
afterFailures,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Issues a fresh captcha challenge (math prompt, or Turnstile site key hint).
|
||||
*/
|
||||
export async function getCaptchaChallenge(_req: Request, res: Response): Promise<void> {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
if (!captchaService.isCaptchaAvailable(settings.login_captcha_after_failures)) {
|
||||
res.status(404).json({ error: 'Captcha is disabled' });
|
||||
return;
|
||||
}
|
||||
res.json(captchaService.createLoginCaptchaChallenge());
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates a user with email and password, optionally requiring a TOTP code when 2FA is enabled.
|
||||
* @param req - Request body: `email`, `password`, optional `totpCode`. IP and user-agent are forwarded for audit.
|
||||
@ -127,6 +142,9 @@ export async function login(req: Request, res: Response): Promise<void> {
|
||||
...((e as { retryAfterMinutes?: number }).retryAfterMinutes != null
|
||||
? { retryAfterMinutes: (e as { retryAfterMinutes: number }).retryAfterMinutes }
|
||||
: {}),
|
||||
...((e as { captcha?: unknown }).captcha
|
||||
? { captcha: (e as { captcha: unknown }).captcha }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,6 +46,26 @@ export async function listGrants(req: AuthRequest, res: Response): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportGrants(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const status = (req.query.status as string) || undefined;
|
||||
const buf = await soloEncouragementService.exportGrantsXlsx(status);
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
const suffix = status && status !== 'all' ? `-${status}` : '';
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
);
|
||||
res.setHeader(
|
||||
'Content-Disposition',
|
||||
`attachment; filename="solo-encouragement-grants${suffix}-${stamp}.xlsx"`
|
||||
);
|
||||
res.send(buf);
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : 'Export failed' });
|
||||
}
|
||||
}
|
||||
|
||||
export async function grantBonus(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const grantId = String(req.params.grantId ?? '');
|
||||
|
||||
@ -39,7 +39,7 @@ export interface SystemSettings {
|
||||
login_max_failed_attempts: number;
|
||||
/** Lockout duration in minutes after max failed attempts. */
|
||||
login_lockout_minutes: number;
|
||||
/** Require Turnstile captcha after this many prior failed logins (when configured). */
|
||||
/** Require captcha after this many prior failed logins (math built-in, or Turnstile when configured). */
|
||||
login_captcha_after_failures: number;
|
||||
/** When true, Sybil block threshold auto-suspends beneficiary accounts. */
|
||||
sybil_auto_suspend_accounts: boolean;
|
||||
|
||||
@ -174,6 +174,16 @@ export const REPORT_DEFINITIONS: ReportDefinition[] = [
|
||||
defaultSortField: 'created_at',
|
||||
defaultSortDir: 'desc',
|
||||
},
|
||||
{
|
||||
key: 'financial-encouragement-grants',
|
||||
category: 'financial',
|
||||
title: 'Bonus d’encouragement solo',
|
||||
description:
|
||||
'Grants d’encouragement solo (éligibles, accordés, refusés, ignorés) avec mises/pertes et crédit bonus.',
|
||||
source: 'reports-api',
|
||||
defaultSortField: 'created_at',
|
||||
defaultSortDir: 'desc',
|
||||
},
|
||||
{
|
||||
key: 'financial-adjustments',
|
||||
category: 'financial',
|
||||
|
||||
@ -121,6 +121,8 @@ export async function runReport(reportKey: string, options: ReportQueryOptions):
|
||||
return listDepositUsers(reportKey, normalized);
|
||||
case 'financial-bonuses':
|
||||
return listBonuses(reportKey, normalized);
|
||||
case 'financial-encouragement-grants':
|
||||
return listEncouragementGrants(reportKey, normalized);
|
||||
case 'financial-adjustments':
|
||||
return listAdjustments(reportKey, normalized);
|
||||
case 'financial-wallet-balances':
|
||||
@ -308,6 +310,116 @@ async function listDepositUsers(
|
||||
};
|
||||
}
|
||||
|
||||
async function listEncouragementGrants(
|
||||
reportKey: string,
|
||||
options: ReportQueryOptions
|
||||
): Promise<ReportPageResult> {
|
||||
const columns = [
|
||||
{ field: 'id', headerName: 'ID', type: 'string' },
|
||||
{ field: 'user_id', headerName: 'User ID', type: 'string' },
|
||||
{ field: 'status', headerName: 'Status', type: 'string' },
|
||||
{ field: 'streak_count', headerName: 'Streak', type: 'number' },
|
||||
{ field: 'loss_raw', headerName: 'Losses / stake base (USDT)', type: 'money' },
|
||||
{ field: 'refund_percent', headerName: 'Refund %', type: 'number' },
|
||||
{ field: 'credit_raw', headerName: 'Bonus (USDT)', type: 'money' },
|
||||
{ field: 'granted_at', headerName: 'Granted at', type: 'date' },
|
||||
{ field: 'created_at', headerName: 'Date', type: 'date' },
|
||||
];
|
||||
const date = dateClause('g.created_at', options.from, options.to, 1);
|
||||
const values = [...date.values];
|
||||
let i = values.length + 1;
|
||||
const parts = [date.sql];
|
||||
if (options.search?.trim()) {
|
||||
parts.push(`(g.id::text ILIKE $${i} OR g.user_id::text ILIKE $${i} OR g.status ILIKE $${i})`);
|
||||
values.push(`%${options.search.trim()}%`);
|
||||
i += 1;
|
||||
}
|
||||
const statusPreset = options.preset?.status;
|
||||
if (typeof statusPreset === 'string' && statusPreset.trim()) {
|
||||
parts.push(`g.status = $${i++}`);
|
||||
values.push(statusPreset.trim());
|
||||
}
|
||||
const idClause = idsFilter('g.id', options.ids, values, i);
|
||||
i = idClause.nextIdx;
|
||||
const whereSql = `${parts.join(' AND ')}${idClause.sql}`;
|
||||
const sortDir = options.sortDir === 'asc' ? 'asc' : 'desc';
|
||||
|
||||
const summaryRows = await query<
|
||||
{ total_count: string; unique_users: string; total_amount: string }[]
|
||||
>(
|
||||
`SELECT COUNT(*)::text AS total_count,
|
||||
COUNT(DISTINCT g.user_id)::text AS unique_users,
|
||||
COALESCE(SUM(g.credit_raw), 0)::text AS total_amount
|
||||
FROM solo_encouragement_grants g
|
||||
WHERE ${whereSql}`,
|
||||
values
|
||||
);
|
||||
const summary: ReportSummary = {
|
||||
totalCount: num(summaryRows[0]?.total_count),
|
||||
uniqueUsers: num(summaryRows[0]?.unique_users),
|
||||
totalAmountRaw: num(summaryRows[0]?.total_amount),
|
||||
};
|
||||
|
||||
if (useKeysetPagination(reportKey, options)) {
|
||||
const decoded = options.cursor ? decodeReportCursor(options.cursor) : null;
|
||||
let keysetSql = '';
|
||||
if (decoded) {
|
||||
values.push(decoded.createdAt, decoded.id);
|
||||
const op = sortDir === 'asc' ? '>' : '<';
|
||||
keysetSql = ` AND (g.created_at, g.id) ${op} ($${i}::timestamptz, $${i + 1}::uuid)`;
|
||||
i += 2;
|
||||
}
|
||||
const includeTotal = options.includeTotal !== false && !options.cursor;
|
||||
const total = includeTotal ? summary.totalCount ?? 0 : 0;
|
||||
values.push(options.limit + 1);
|
||||
const rows = await query<Record<string, unknown>[]>(
|
||||
`SELECT g.id, g.user_id, g.status, g.streak_count,
|
||||
g.loss_raw::text AS loss_raw, g.refund_percent::text AS refund_percent,
|
||||
g.credit_raw::text AS credit_raw, g.granted_at, g.created_at
|
||||
FROM solo_encouragement_grants g
|
||||
WHERE ${whereSql}${keysetSql}
|
||||
ORDER BY g.created_at ${sortDir === 'asc' ? 'ASC' : 'DESC'}, g.id ${sortDir === 'asc' ? 'ASC' : 'DESC'}
|
||||
LIMIT $${i}`,
|
||||
values
|
||||
);
|
||||
const hasMore = rows.length > options.limit;
|
||||
const items = serializeDateRows(hasMore ? rows.slice(0, options.limit) : rows);
|
||||
const nextCursor =
|
||||
hasMore && items.length > 0
|
||||
? buildCursorFromRow(sortDir, items[items.length - 1] as { created_at: unknown; id: unknown })
|
||||
: null;
|
||||
return { items, total, columns, nextCursor, hasMore, totalIsExact: includeTotal, summary };
|
||||
}
|
||||
|
||||
const countRows = await query<{ c: string }[]>(
|
||||
`SELECT COUNT(*)::text AS c FROM solo_encouragement_grants g WHERE ${whereSql}`,
|
||||
values
|
||||
);
|
||||
const allowedSort = new Set(['created_at', 'user_id', 'streak_count', 'loss_raw', 'credit_raw', 'status']);
|
||||
const sortField =
|
||||
options.sortBy && allowedSort.has(options.sortBy) ? options.sortBy : 'created_at';
|
||||
const sortSql = `g.${sortField} ${sortDir === 'asc' ? 'ASC' : 'DESC'}`;
|
||||
const offset = options.offset ?? 0;
|
||||
values.push(options.limit, offset);
|
||||
const rows = await query<Record<string, unknown>[]>(
|
||||
`SELECT g.id, g.user_id, g.status, g.streak_count,
|
||||
g.loss_raw::text AS loss_raw, g.refund_percent::text AS refund_percent,
|
||||
g.credit_raw::text AS credit_raw, g.granted_at, g.created_at
|
||||
FROM solo_encouragement_grants g
|
||||
WHERE ${whereSql}
|
||||
ORDER BY ${sortSql}
|
||||
LIMIT $${i++} OFFSET $${i}`,
|
||||
values
|
||||
);
|
||||
return {
|
||||
items: serializeDateRows(rows),
|
||||
total: parseInt(countRows[0]?.c ?? '0', 10),
|
||||
columns,
|
||||
totalIsExact: true,
|
||||
summary,
|
||||
};
|
||||
}
|
||||
|
||||
async function listBonuses(reportKey: string, options: ReportQueryOptions): Promise<ReportPageResult> {
|
||||
const columns = [
|
||||
{ field: 'id', headerName: 'ID', type: 'string' },
|
||||
|
||||
@ -138,6 +138,7 @@ router.get('/auth/referral/validate/:code', asyncHandler(authController.validate
|
||||
router.get('/countries', countryController.listRegistrationCountries);
|
||||
router.post('/auth/login', loginLimiter, validateBody(loginBodySchema), asyncHandler(authController.login));
|
||||
router.get('/auth/captcha-config', asyncHandler(authController.getCaptchaConfig));
|
||||
router.get('/auth/captcha-challenge', asyncHandler(authController.getCaptchaChallenge));
|
||||
router.post('/auth/refresh', validateBody(refreshBodySchema), authController.refresh);
|
||||
router.post('/auth/logout', validateBody(logoutBodySchema), authController.logout);
|
||||
router.post('/auth/verify-email', validateBody(verifyEmailBodySchema), authController.verifyEmail);
|
||||
@ -442,6 +443,7 @@ router.patch('/admin/share-cards/settings', requireRoles('admin'), requirePermis
|
||||
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/export', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.exportGrants);
|
||||
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);
|
||||
|
||||
@ -310,11 +310,13 @@ export async function login(
|
||||
|
||||
const settings = await settingsRepository.getSettings();
|
||||
const failedCount = await userRepository.getFailedLoginCount(user.id);
|
||||
if (
|
||||
captchaService.isCaptchaConfigured() &&
|
||||
failedCount >= settings.login_captcha_after_failures
|
||||
) {
|
||||
await captchaService.verifyCaptchaToken(captchaToken, auditIp);
|
||||
const afterFailures = settings.login_captcha_after_failures;
|
||||
if (afterFailures > 0 && failedCount >= afterFailures) {
|
||||
try {
|
||||
await captchaService.verifyCaptchaToken(captchaToken, auditIp);
|
||||
} catch (e) {
|
||||
throw captchaService.withCaptchaChallenge(e as Error & { code?: string });
|
||||
}
|
||||
}
|
||||
|
||||
if (user.is_enabled === false) {
|
||||
|
||||
@ -1,27 +1,148 @@
|
||||
/**
|
||||
* Optional Cloudflare Turnstile verification after repeated login failures.
|
||||
* Login captcha: Cloudflare Turnstile when configured, otherwise built-in math challenge.
|
||||
*/
|
||||
|
||||
import crypto from 'crypto';
|
||||
import { config } from '../config';
|
||||
|
||||
export function isCaptchaConfigured(): boolean {
|
||||
return Boolean(config.turnstile.secretKey);
|
||||
export type CaptchaProvider = 'turnstile' | 'math';
|
||||
|
||||
export type CaptchaChallengePayload = {
|
||||
provider: CaptchaProvider;
|
||||
siteKey?: string | null;
|
||||
challengeToken?: string;
|
||||
prompt?: string;
|
||||
};
|
||||
|
||||
type MathPayload = {
|
||||
a: number;
|
||||
b: number;
|
||||
exp: number;
|
||||
};
|
||||
|
||||
function captchaHmacSecret(): string {
|
||||
return config.turnstile.secretKey || config.jwt.secret || 'captcha-dev-secret';
|
||||
}
|
||||
|
||||
function b64url(buf: Buffer | string): string {
|
||||
const b = typeof buf === 'string' ? Buffer.from(buf, 'utf8') : buf;
|
||||
return b.toString('base64url');
|
||||
}
|
||||
|
||||
function signMathPayload(payload: MathPayload): string {
|
||||
const body = b64url(JSON.stringify(payload));
|
||||
const sig = crypto.createHmac('sha256', captchaHmacSecret()).update(body).digest('base64url');
|
||||
return `${body}.${sig}`;
|
||||
}
|
||||
|
||||
function parseMathChallengeToken(token: string): MathPayload | null {
|
||||
const [body, sig] = token.split('.');
|
||||
if (!body || !sig) return null;
|
||||
const expected = crypto.createHmac('sha256', captchaHmacSecret()).update(body).digest('base64url');
|
||||
const a = Buffer.from(sig);
|
||||
const b = Buffer.from(expected);
|
||||
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(Buffer.from(body, 'base64url').toString('utf8')) as MathPayload;
|
||||
if (
|
||||
typeof parsed?.a !== 'number' ||
|
||||
typeof parsed?.b !== 'number' ||
|
||||
typeof parsed?.exp !== 'number'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Turnstile is preferred when secret key is present. */
|
||||
export function getCaptchaProvider(): CaptchaProvider {
|
||||
return config.turnstile.secretKey ? 'turnstile' : 'math';
|
||||
}
|
||||
|
||||
export function getCaptchaSiteKey(): string | null {
|
||||
return config.turnstile.siteKey || null;
|
||||
}
|
||||
|
||||
/** Verifies a Turnstile token when captcha is configured. */
|
||||
export async function verifyCaptchaToken(
|
||||
token: string | undefined,
|
||||
remoteIp?: string
|
||||
): Promise<void> {
|
||||
if (!isCaptchaConfigured()) return;
|
||||
/** Captcha is available whenever the admin threshold is positive (math fallback always works). */
|
||||
export function isCaptchaAvailable(afterFailures: number): boolean {
|
||||
return afterFailures > 0;
|
||||
}
|
||||
|
||||
/** @deprecated Prefer isCaptchaAvailable(afterFailures) — kept for call sites during transition. */
|
||||
export function isCaptchaConfigured(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function createMathChallenge(): CaptchaChallengePayload {
|
||||
const a = 2 + crypto.randomInt(8); // 2..9
|
||||
const b = 2 + crypto.randomInt(8);
|
||||
const exp = Date.now() + 5 * 60 * 1000;
|
||||
const challengeToken = signMathPayload({ a, b, exp });
|
||||
return {
|
||||
provider: 'math',
|
||||
challengeToken,
|
||||
prompt: `${a} + ${b} = ?`,
|
||||
};
|
||||
}
|
||||
|
||||
export function createLoginCaptchaChallenge(): CaptchaChallengePayload {
|
||||
if (getCaptchaProvider() === 'turnstile') {
|
||||
return {
|
||||
provider: 'turnstile',
|
||||
siteKey: getCaptchaSiteKey(),
|
||||
};
|
||||
}
|
||||
return createMathChallenge();
|
||||
}
|
||||
|
||||
function captchaError(message: string, code: 'CAPTCHA_REQUIRED' | 'CAPTCHA_INVALID'): Error & {
|
||||
code: string;
|
||||
captcha?: CaptchaChallengePayload;
|
||||
} {
|
||||
const err = new Error(message) as Error & { code: string; captcha?: CaptchaChallengePayload };
|
||||
err.code = code;
|
||||
return err;
|
||||
}
|
||||
|
||||
function verifyMathToken(token: string | undefined): void {
|
||||
if (!token?.trim()) {
|
||||
const err = new Error('Captcha verification is required') as Error & { code?: string };
|
||||
err.code = 'CAPTCHA_REQUIRED';
|
||||
throw err;
|
||||
throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED');
|
||||
}
|
||||
const raw = token.trim();
|
||||
// Expected: math:<challengeToken>:<answer>
|
||||
if (!raw.startsWith('math:')) {
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
const rest = raw.slice('math:'.length);
|
||||
const lastColon = rest.lastIndexOf(':');
|
||||
if (lastColon <= 0) {
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
const challengeToken = rest.slice(0, lastColon);
|
||||
const answerRaw = rest.slice(lastColon + 1).trim();
|
||||
const payload = parseMathChallengeToken(challengeToken);
|
||||
if (!payload) {
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
if (Date.now() > payload.exp) {
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
const answer = Number.parseInt(answerRaw, 10);
|
||||
if (!Number.isFinite(answer) || answer !== payload.a + payload.b) {
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
async function verifyTurnstileToken(token: string | undefined, remoteIp?: string): Promise<void> {
|
||||
if (!token?.trim()) {
|
||||
throw captchaError('Captcha verification is required', 'CAPTCHA_REQUIRED');
|
||||
}
|
||||
if (token.trim().startsWith('math:')) {
|
||||
// Client sent math token while Turnstile is configured
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
|
||||
const body = new URLSearchParams({
|
||||
@ -42,8 +163,28 @@ export async function verifyCaptchaToken(
|
||||
|
||||
const data = (await res.json()) as { success?: boolean };
|
||||
if (!data.success) {
|
||||
const err = new Error('Captcha verification failed') as Error & { code?: string };
|
||||
err.code = 'CAPTCHA_INVALID';
|
||||
throw err;
|
||||
throw captchaError('Captcha verification failed', 'CAPTCHA_INVALID');
|
||||
}
|
||||
}
|
||||
|
||||
/** Verifies login captcha using Turnstile or built-in math challenge. */
|
||||
export async function verifyCaptchaToken(
|
||||
token: string | undefined,
|
||||
remoteIp?: string
|
||||
): Promise<void> {
|
||||
if (getCaptchaProvider() === 'turnstile') {
|
||||
await verifyTurnstileToken(token, remoteIp);
|
||||
return;
|
||||
}
|
||||
verifyMathToken(token);
|
||||
}
|
||||
|
||||
/** Attach a fresh challenge to captcha errors for the client. */
|
||||
export function withCaptchaChallenge<T extends Error & { code?: string; captcha?: CaptchaChallengePayload }>(
|
||||
err: T
|
||||
): T {
|
||||
if (err.code === 'CAPTCHA_REQUIRED' || err.code === 'CAPTCHA_INVALID') {
|
||||
err.captcha = createLoginCaptchaChallenge();
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
@ -10,6 +10,7 @@ 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) {
|
||||
@ -393,6 +394,57 @@ export async function listGrantsForAdmin(input: {
|
||||
};
|
||||
}
|
||||
|
||||
/** 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');
|
||||
|
||||
@ -13,6 +13,7 @@ export const CURSOR_PAGINATED_REPORT_KEYS = new Set([
|
||||
'financial-deposits',
|
||||
'financial-withdrawals',
|
||||
'financial-bonuses',
|
||||
'financial-encouragement-grants',
|
||||
'financial-adjustments',
|
||||
'games-predictions',
|
||||
'games-predictions-real',
|
||||
|
||||
@ -30,6 +30,8 @@ x-backend-common: &backend-common
|
||||
REDIS_ROUND_CACHE: ${REDIS_ROUND_CACHE:-true}
|
||||
BET_ASYNC: ${BET_ASYNC:-true}
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-}
|
||||
TURNSTILE_SECRET_KEY: ${TURNSTILE_SECRET_KEY:-}
|
||||
JWT_ACCESS_EXPIRY: ${JWT_ACCESS_EXPIRY:-15m}
|
||||
JWT_REFRESH_EXPIRY: ${JWT_REFRESH_EXPIRY:-7d}
|
||||
ENCRYPTION_KEY: ${ENCRYPTION_KEY}
|
||||
|
||||
@ -9,6 +9,7 @@ class AppException implements Exception {
|
||||
this.statusCode,
|
||||
this.code,
|
||||
this.retryAfterMinutes,
|
||||
this.captcha,
|
||||
});
|
||||
|
||||
final String message;
|
||||
@ -17,6 +18,8 @@ class AppException implements Exception {
|
||||
final String? code;
|
||||
/// Present for `ACCOUNT_LOCKED` responses.
|
||||
final int? retryAfterMinutes;
|
||||
/// Captcha challenge payload when login requires a security check.
|
||||
final Map<String, dynamic>? captcha;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
@ -84,6 +87,25 @@ class AppException implements Exception {
|
||||
retryAfterMinutes: retryAfterMinutes,
|
||||
);
|
||||
}
|
||||
if (code == 'CAPTCHA_REQUIRED' || code == 'CAPTCHA_INVALID') {
|
||||
final captchaRaw = data['captcha'];
|
||||
return AppException(
|
||||
code == 'CAPTCHA_REQUIRED'
|
||||
? _t(
|
||||
'Complete the security check below and try again.',
|
||||
'Complétez la vérification de sécurité ci-dessous et réessayez.',
|
||||
)
|
||||
: _t(
|
||||
'Security check failed. Please try again.',
|
||||
'Échec de la vérification de sécurité. Veuillez réessayer.',
|
||||
),
|
||||
statusCode: status,
|
||||
code: code is String ? code : null,
|
||||
captcha: captchaRaw is Map
|
||||
? Map<String, dynamic>.from(captchaRaw)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
if (code == 'TEST_PREDICTION_LIMIT') {
|
||||
final waitRaw = data['wait'];
|
||||
final wait = waitRaw is String && waitRaw.trim().isNotEmpty ? waitRaw.trim() : '24h';
|
||||
@ -97,11 +119,15 @@ class AppException implements Exception {
|
||||
);
|
||||
}
|
||||
if (msg is String && msg.isNotEmpty) {
|
||||
final captchaRaw = data['captcha'];
|
||||
return AppException(
|
||||
sanitizeApiMessage(msg, fallback: fallback),
|
||||
statusCode: status,
|
||||
code: code is String ? code : null,
|
||||
retryAfterMinutes: retryAfterMinutes,
|
||||
captcha: captchaRaw is Map
|
||||
? Map<String, dynamic>.from(captchaRaw)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -9,15 +9,22 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
final ApiClient _api;
|
||||
|
||||
@override
|
||||
Future<LoginResult> login(String email, String password, {String? totpCode}) async {
|
||||
Future<LoginResult> login(
|
||||
String email,
|
||||
String password, {
|
||||
String? totpCode,
|
||||
String? captchaToken,
|
||||
}) async {
|
||||
try {
|
||||
final trimmedTotp = totpCode?.trim();
|
||||
final trimmedCaptcha = captchaToken?.trim();
|
||||
final res = await _api.dio.post<Map<String, dynamic>>(
|
||||
'/api/v1/auth/login',
|
||||
data: {
|
||||
'email': email,
|
||||
'password': password,
|
||||
if (trimmedTotp != null && trimmedTotp.isNotEmpty) 'totpCode': trimmedTotp,
|
||||
if (trimmedCaptcha != null && trimmedCaptcha.isNotEmpty) 'captchaToken': trimmedCaptcha,
|
||||
},
|
||||
);
|
||||
final data = res.data!;
|
||||
|
||||
@ -43,7 +43,12 @@ class RegisterResult {
|
||||
}
|
||||
|
||||
abstract class AuthRepository {
|
||||
Future<LoginResult> login(String email, String password, {String? totpCode});
|
||||
Future<LoginResult> login(
|
||||
String email,
|
||||
String password, {
|
||||
String? totpCode,
|
||||
String? captchaToken,
|
||||
});
|
||||
Future<RegisterResult> register(RegisterRequest request);
|
||||
Future<List<CountryOption>> getCountries();
|
||||
Future<({bool valid, String? reason})> validateReferralCode(String code);
|
||||
|
||||
@ -47,7 +47,12 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
Future<void> _onLogin(AuthLoginRequested event, Emitter<AuthState> emit) async {
|
||||
emit(const AuthState.loading());
|
||||
try {
|
||||
final result = await _authRepo.login(event.email, event.password, totpCode: event.totpCode);
|
||||
final result = await _authRepo.login(
|
||||
event.email,
|
||||
event.password,
|
||||
totpCode: event.totpCode,
|
||||
captchaToken: event.captchaToken,
|
||||
);
|
||||
emit(AuthState.authenticated(userId: result.userId, role: result.role));
|
||||
} catch (e) {
|
||||
emit(_mapError(e));
|
||||
@ -167,6 +172,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
userId: userId,
|
||||
role: role,
|
||||
errorCode: e.code,
|
||||
captcha: e.captcha,
|
||||
);
|
||||
}
|
||||
return AuthState.error(e.toString(), userId: userId, role: role);
|
||||
|
||||
@ -12,12 +12,21 @@ class AuthCheckRequested extends AuthEvent {
|
||||
const AuthCheckRequested();
|
||||
}
|
||||
|
||||
/// Requests sign-in with credentials and optional two-factor code.
|
||||
/// Requests sign-in with credentials and optional two-factor / captcha tokens.
|
||||
class AuthLoginRequested extends AuthEvent {
|
||||
const AuthLoginRequested({required this.email, required this.password, this.totpCode});
|
||||
const AuthLoginRequested({
|
||||
required this.email,
|
||||
required this.password,
|
||||
this.totpCode,
|
||||
this.captchaToken,
|
||||
});
|
||||
final String email;
|
||||
final String password;
|
||||
final String? totpCode;
|
||||
final String? captchaToken;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [email, password, totpCode, captchaToken];
|
||||
}
|
||||
|
||||
/// Requests creation of a new user account (web-parity profile fields).
|
||||
|
||||
@ -25,6 +25,7 @@ class AuthState extends Equatable {
|
||||
this.registerMessage,
|
||||
this.emailVerificationRequired = false,
|
||||
this.recoveryCodes = const [],
|
||||
this.captcha,
|
||||
});
|
||||
|
||||
const AuthState.initial() : this();
|
||||
@ -57,12 +58,14 @@ class AuthState extends Equatable {
|
||||
String? userId,
|
||||
String? role,
|
||||
String? errorCode,
|
||||
Map<String, dynamic>? captcha,
|
||||
}) : this(
|
||||
status: AuthStatus.error,
|
||||
errorMessage: msg,
|
||||
userId: userId,
|
||||
role: role,
|
||||
errorCode: errorCode,
|
||||
captcha: captcha,
|
||||
);
|
||||
const AuthState.totpSetup(Map<String, dynamic> data, {String? userId, String? role})
|
||||
: this(status: AuthStatus.totpSetup, totpData: data, userId: userId, role: role);
|
||||
@ -77,6 +80,8 @@ class AuthState extends Equatable {
|
||||
final bool emailVerificationRequired;
|
||||
/// One-time recovery codes shown after enabling / regenerating 2FA.
|
||||
final List<String> recoveryCodes;
|
||||
/// Captcha challenge from the API when login is challenged.
|
||||
final Map<String, dynamic>? captcha;
|
||||
|
||||
/// Whether the signed-in user has administrator access (admin or super_admin).
|
||||
bool get isAdmin => role == 'admin' || role == 'super_admin';
|
||||
@ -90,6 +95,9 @@ class AuthState extends Equatable {
|
||||
|
||||
bool get isEmailNotVerified => errorCode == 'EMAIL_NOT_VERIFIED';
|
||||
|
||||
bool get isCaptchaChallenge =>
|
||||
errorCode == 'CAPTCHA_REQUIRED' || errorCode == 'CAPTCHA_INVALID';
|
||||
|
||||
AuthState copyWith({
|
||||
AuthStatus? status,
|
||||
String? userId,
|
||||
@ -100,9 +108,11 @@ class AuthState extends Equatable {
|
||||
String? registerMessage,
|
||||
bool? emailVerificationRequired,
|
||||
List<String>? recoveryCodes,
|
||||
Map<String, dynamic>? captcha,
|
||||
bool clearError = false,
|
||||
bool clearTotpData = false,
|
||||
bool clearRecoveryCodes = false,
|
||||
bool clearCaptcha = false,
|
||||
}) {
|
||||
return AuthState(
|
||||
status: status ?? this.status,
|
||||
@ -116,6 +126,7 @@ class AuthState extends Equatable {
|
||||
emailVerificationRequired ?? this.emailVerificationRequired,
|
||||
recoveryCodes:
|
||||
clearRecoveryCodes ? const [] : (recoveryCodes ?? this.recoveryCodes),
|
||||
captcha: clearCaptcha || clearError ? null : (captcha ?? this.captcha),
|
||||
);
|
||||
}
|
||||
|
||||
@ -130,5 +141,6 @@ class AuthState extends Equatable {
|
||||
registerMessage,
|
||||
emailVerificationRequired,
|
||||
recoveryCodes,
|
||||
captcha,
|
||||
];
|
||||
}
|
||||
|
||||
@ -26,12 +26,18 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
final _emailController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
final _totpController = TextEditingController();
|
||||
final _mathAnswerController = TextEditingController();
|
||||
bool _obscurePassword = true;
|
||||
/// Only kept on screen for EMAIL_NOT_VERIFIED (needs resend action).
|
||||
String? _verifyBanner;
|
||||
late bool _showVerifyHint;
|
||||
Timer? _bannerTimer;
|
||||
|
||||
/// Local captcha UI state (survives AuthClearFeedback).
|
||||
bool _captchaRequired = false;
|
||||
String? _mathPrompt;
|
||||
String? _mathChallengeToken;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@ -49,6 +55,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_totpController.dispose();
|
||||
_mathAnswerController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@ -56,6 +63,39 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
}
|
||||
|
||||
void _applyCaptchaChallenge(Map<String, dynamic>? captcha) {
|
||||
final provider = captcha?['provider']?.toString();
|
||||
final prompt = captcha?['prompt']?.toString();
|
||||
final token = captcha?['challengeToken']?.toString();
|
||||
setState(() {
|
||||
_captchaRequired = true;
|
||||
_mathAnswerController.clear();
|
||||
if (provider == 'math' && prompt != null && token != null && token.isNotEmpty) {
|
||||
_mathPrompt = prompt;
|
||||
_mathChallengeToken = token;
|
||||
}
|
||||
// Keep any existing math challenge when the error has no captcha payload.
|
||||
});
|
||||
}
|
||||
|
||||
String? _buildCaptchaToken() {
|
||||
if (!_captchaRequired) return null;
|
||||
final token = _mathChallengeToken;
|
||||
final answer = _mathAnswerController.text.trim();
|
||||
if (token == null || token.isEmpty || answer.isEmpty) return null;
|
||||
return 'math:$token:$answer';
|
||||
}
|
||||
|
||||
void _submitLogin() {
|
||||
setState(() => _verifyBanner = null);
|
||||
context.read<AuthBloc>().add(AuthLoginRequested(
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
totpCode: _totpController.text.isEmpty ? null : _totpController.text,
|
||||
captchaToken: _buildCaptchaToken(),
|
||||
));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
@ -77,12 +117,19 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status ||
|
||||
prev.errorMessage != curr.errorMessage ||
|
||||
prev.registerMessage != curr.registerMessage,
|
||||
prev.registerMessage != curr.registerMessage ||
|
||||
prev.captcha != curr.captcha,
|
||||
listener: (context, state) {
|
||||
if (!isCurrentRoute(context)) return;
|
||||
|
||||
if (state.status == AuthStatus.authenticated) {
|
||||
setState(() => _verifyBanner = null);
|
||||
setState(() {
|
||||
_verifyBanner = null;
|
||||
_captchaRequired = false;
|
||||
_mathPrompt = null;
|
||||
_mathChallengeToken = null;
|
||||
_mathAnswerController.clear();
|
||||
});
|
||||
_consumeFeedback();
|
||||
context.go('/home');
|
||||
return;
|
||||
@ -107,6 +154,12 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
|
||||
if (state.status == AuthStatus.error && state.errorMessage != null) {
|
||||
final msg = state.errorMessage!.replaceFirst('Exception: ', '');
|
||||
if (state.isCaptchaChallenge) {
|
||||
_applyCaptchaChallenge(state.captcha);
|
||||
} else if (_captchaRequired) {
|
||||
// Keep / refresh challenge after other login failures once captcha is active.
|
||||
_applyCaptchaChallenge(state.captcha);
|
||||
}
|
||||
if (state.isEmailNotVerified) {
|
||||
setState(() => _verifyBanner = msg);
|
||||
_bannerTimer = scheduleMessageClear(
|
||||
@ -223,6 +276,19 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
maxLength: 6,
|
||||
enabled: !loading,
|
||||
),
|
||||
if (_captchaRequired && _mathPrompt != null) ...[
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
key: const Key('login_captcha_math'),
|
||||
controller: _mathAnswerController,
|
||||
label: s.captchaMathLabel(_mathPrompt!),
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon: Icons.verified_user_outlined,
|
||||
enabled: !loading,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(s.captchaMathHelper, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
@ -237,14 +303,7 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
key: const Key('login_submit'),
|
||||
label: s.signIn,
|
||||
loading: loading,
|
||||
onPressed: () {
|
||||
setState(() => _verifyBanner = null);
|
||||
context.read<AuthBloc>().add(AuthLoginRequested(
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
totpCode: _totpController.text.isEmpty ? null : _totpController.text,
|
||||
));
|
||||
},
|
||||
onPressed: _submitLogin,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(onPressed: () => context.go('/register'), child: Text(s.signUp)),
|
||||
|
||||
@ -2,16 +2,85 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../data/repositories/auth_repository_impl.dart';
|
||||
import '../../../domain/repositories/repositories.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
class AccountScreen extends StatelessWidget {
|
||||
class AccountScreen extends StatefulWidget {
|
||||
const AccountScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AccountScreen> createState() => _AccountScreenState();
|
||||
}
|
||||
|
||||
class _AccountScreenState extends State<AccountScreen> {
|
||||
bool _loading = true;
|
||||
UserProfile? _profile;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() => _loading = true);
|
||||
try {
|
||||
final profile = await context.read<AuthRepository>().getProfile();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_profile = profile;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
String _displayName(AppStrings s) {
|
||||
final p = _profile;
|
||||
if (p == null) return s.accountTitle;
|
||||
final parts = [
|
||||
p.firstName?.trim(),
|
||||
p.middleName?.trim(),
|
||||
p.lastName?.trim(),
|
||||
].whereType<String>().where((v) => v.isNotEmpty).toList();
|
||||
if (parts.isNotEmpty) return parts.join(' ');
|
||||
final email = p.email?.trim();
|
||||
if (email != null && email.isNotEmpty) return email;
|
||||
return s.accountTitle;
|
||||
}
|
||||
|
||||
String _initials() {
|
||||
final p = _profile;
|
||||
if (p == null) return '?';
|
||||
final first = (p.firstName ?? '').trim();
|
||||
final last = (p.lastName ?? '').trim();
|
||||
if (first.isNotEmpty && last.isNotEmpty) {
|
||||
return '${first[0]}${last[0]}'.toUpperCase();
|
||||
}
|
||||
if (first.isNotEmpty) return first[0].toUpperCase();
|
||||
final email = (p.email ?? '').trim();
|
||||
if (email.isNotEmpty) return email[0].toUpperCase();
|
||||
return '?';
|
||||
}
|
||||
|
||||
Future<void> _openProfileEdit() async {
|
||||
await context.push('/account/profile');
|
||||
if (mounted) await _load();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final name = _displayName(s);
|
||||
final email = _profile?.email?.trim();
|
||||
final phone = _profile?.phone?.trim();
|
||||
final country = _profile?.countryOfResidence?.trim();
|
||||
|
||||
return BlocListener<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) => prev.status != curr.status,
|
||||
listener: (context, state) {
|
||||
@ -26,90 +95,180 @@ class AccountScreen extends StatelessWidget {
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
gradient: AppTheme.goldAccentGradient,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: AppColors.goldPrimary.withValues(alpha: 0.4),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 4),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: _load,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 88,
|
||||
height: 88,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
gradient: AppTheme.goldAccentGradient,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: AppColors.goldPrimary.withValues(alpha: 0.4),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: _loading
|
||||
? SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2.5,
|
||||
color: isDark ? AppColors.navy : Colors.white,
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
_initials(),
|
||||
style: TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: isDark ? AppColors.navy : Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
name,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (email != null && email.isNotEmpty && email != name) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
email,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
if (!_loading &&
|
||||
((phone != null && phone.isNotEmpty) ||
|
||||
(country != null && country.isNotEmpty))) ...[
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
if (phone != null && phone.isNotEmpty)
|
||||
_InfoChip(icon: Icons.phone_outlined, label: phone),
|
||||
if (country != null && country.isNotEmpty)
|
||||
_InfoChip(icon: Icons.public_outlined, label: country),
|
||||
if (_profile?.totpEnabled == true)
|
||||
_InfoChip(icon: Icons.verified_user_outlined, label: s.twoFactorEnabledShort),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
Icons.person_rounded,
|
||||
size: 48,
|
||||
color: isDark ? AppColors.navy : Colors.white,
|
||||
] else if (!_loading && _profile?.totpEnabled == true) ...[
|
||||
const SizedBox(height: 12),
|
||||
Center(
|
||||
child: _InfoChip(
|
||||
icon: Icons.verified_user_outlined,
|
||||
label: s.twoFactorEnabledShort,
|
||||
),
|
||||
),
|
||||
] else if (!_loading && (email == null || email.isEmpty)) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
s.accountSubtitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 28),
|
||||
_AccountTile(
|
||||
icon: Icons.badge_outlined,
|
||||
title: s.updateProfile,
|
||||
onTap: _openProfileEdit,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
s.accountTitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Text(
|
||||
s.accountSubtitle,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.lock_reset_rounded,
|
||||
title: s.changePassword,
|
||||
onTap: () => context.push('/account/change-password'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
_AccountTile(
|
||||
icon: Icons.badge_outlined,
|
||||
title: s.updateProfile,
|
||||
onTap: () => context.push('/account/profile'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.lock_reset_rounded,
|
||||
title: s.changePassword,
|
||||
onTap: () => context.push('/account/change-password'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.security_rounded,
|
||||
title: s.twoFactor,
|
||||
onTap: () => context.push('/totp-setup'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.card_giftcard_rounded,
|
||||
title: s.referralProgram,
|
||||
onTap: () => context.push('/referral'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.help_outline_rounded,
|
||||
title: s.helpFaq,
|
||||
onTap: () => context.push('/faq'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.logout_rounded,
|
||||
title: s.logout,
|
||||
isDestructive: true,
|
||||
onTap: () =>
|
||||
context.read<AuthBloc>().add(const AuthLogoutRequested()),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.security_rounded,
|
||||
title: s.twoFactor,
|
||||
onTap: () => context.push('/totp-setup'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.card_giftcard_rounded,
|
||||
title: s.referralProgram,
|
||||
onTap: () => context.push('/referral'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.help_outline_rounded,
|
||||
title: s.helpFaq,
|
||||
onTap: () => context.push('/faq'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_AccountTile(
|
||||
icon: Icons.logout_rounded,
|
||||
title: s.logout,
|
||||
isDestructive: true,
|
||||
onTap: () =>
|
||||
context.read<AuthBloc>().add(const AuthLogoutRequested()),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InfoChip extends StatelessWidget {
|
||||
const _InfoChip({required this.icon, required this.label});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = Theme.of(context).colorScheme.primary;
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: color.withValues(alpha: 0.25)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 14, color: color),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: color,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AccountTile extends StatelessWidget {
|
||||
const _AccountTile({
|
||||
required this.icon,
|
||||
@ -152,9 +311,9 @@ class _AccountTile extends StatelessWidget {
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: color,
|
||||
),
|
||||
fontWeight: FontWeight.w600,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
),
|
||||
Icon(Icons.chevron_right_rounded, color: color),
|
||||
|
||||
@ -17,7 +17,7 @@ class AppStrings {
|
||||
);
|
||||
|
||||
// Nav
|
||||
String get navHome => t('Dashboard', 'Dashboard');
|
||||
String get navHome => t('Home', 'Accueil');
|
||||
String get navPredict => t('Predict', 'Prédire');
|
||||
String get predictionGamesTitle => t('Prediction games', 'Jeux de prédiction');
|
||||
String get predictionGamesSubtitle => t(
|
||||
@ -161,6 +161,12 @@ class AppStrings {
|
||||
'E-mail de vérification envoyé. Consultez votre boîte de réception.',
|
||||
);
|
||||
String get totpCode => t('2FA code (if enabled)', 'Code 2FA (si activé)');
|
||||
String captchaMathLabel(String prompt) =>
|
||||
t('Security check: $prompt', 'Vérification : $prompt');
|
||||
String get captchaMathHelper => t(
|
||||
'Enter the result to continue after several failed attempts.',
|
||||
'Saisissez le résultat pour continuer après plusieurs échecs.',
|
||||
);
|
||||
String get logout => t('Log out', 'Déconnexion');
|
||||
String get forgotPassword => t('Forgot password?', 'Mot de passe oublié ?');
|
||||
String get forgotPasswordHint => t(
|
||||
@ -596,6 +602,7 @@ class AppStrings {
|
||||
);
|
||||
String get changePassword => t('Change password', 'Changer le mot de passe');
|
||||
String get twoFactor => t('Two-factor authentication (2FA)', 'Authentification à deux facteurs');
|
||||
String get twoFactorEnabledShort => t('2FA enabled', '2FA activée');
|
||||
String get twoFactorEnabled => t('2FA is enabled on your account.', 'La 2FA est activée sur votre compte.');
|
||||
String get twoFactorSetupHint => t(
|
||||
'Scan the QR code with an authenticator app, then enter the 6-digit code.',
|
||||
|
||||
@ -20,7 +20,7 @@ class PredBottomNav extends StatelessWidget {
|
||||
final s = context.strings;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final items = [
|
||||
_Item(Icons.dashboard_rounded, s.navHome),
|
||||
_Item(Icons.home_rounded, s.navHome),
|
||||
_Item(Icons.sports_esports_rounded, s.navPredict, highlight: true),
|
||||
_Item(Icons.account_balance_wallet_rounded, s.navWallet),
|
||||
_Item(Icons.person_rounded, s.navProfile),
|
||||
|
||||
@ -144,7 +144,12 @@ class FakeAuthRepository implements AuthRepository {
|
||||
String? _role;
|
||||
|
||||
@override
|
||||
Future<LoginResult> login(String email, String password, {String? totpCode}) async {
|
||||
Future<LoginResult> login(
|
||||
String email,
|
||||
String password, {
|
||||
String? totpCode,
|
||||
String? captchaToken,
|
||||
}) async {
|
||||
if (email.isEmpty || password.isEmpty) throw Exception('Invalid credentials');
|
||||
_loggedIn = true;
|
||||
_userId = 'e2e-user';
|
||||
|
||||
@ -29,6 +29,20 @@ type LoginResponse = {
|
||||
};
|
||||
};
|
||||
|
||||
type CaptchaChallenge = {
|
||||
provider: 'turnstile' | 'math';
|
||||
siteKey?: string | null;
|
||||
challengeToken?: string;
|
||||
prompt?: string;
|
||||
};
|
||||
|
||||
type CaptchaConfig = {
|
||||
enabled: boolean;
|
||||
provider: 'turnstile' | 'math';
|
||||
siteKey: string | null;
|
||||
afterFailures: number;
|
||||
};
|
||||
|
||||
/** Sign-in form with optional TOTP; redirects to `from` route on success. */
|
||||
export function LoginPage() {
|
||||
const { t } = useTranslation();
|
||||
@ -48,6 +62,8 @@ export function LoginPage() {
|
||||
|
||||
const [captchaToken, setCaptchaToken] = useState<string | null>(null);
|
||||
const [captchaRequired, setCaptchaRequired] = useState(false);
|
||||
const [mathChallenge, setMathChallenge] = useState<CaptchaChallenge | null>(null);
|
||||
const [mathAnswer, setMathAnswer] = useState('');
|
||||
|
||||
const from = loc.state?.from ?? '/home';
|
||||
const verifyHint = loc.state?.verifyEmail === true;
|
||||
@ -55,13 +71,34 @@ export function LoginPage() {
|
||||
const captchaQ = useQuery({
|
||||
queryKey: ['captcha-config'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<{ enabled: boolean; siteKey: string | null; afterFailures: number }>(
|
||||
'/api/v1/auth/captcha-config'
|
||||
);
|
||||
const res = await api.get<CaptchaConfig>('/api/v1/auth/captcha-config');
|
||||
return res.data;
|
||||
},
|
||||
});
|
||||
|
||||
const applyCaptchaChallenge = useCallback((challenge?: CaptchaChallenge | null) => {
|
||||
setCaptchaRequired(true);
|
||||
setCaptchaToken(null);
|
||||
setMathAnswer('');
|
||||
if (challenge?.provider === 'math' && challenge.challengeToken && challenge.prompt) {
|
||||
setMathChallenge(challenge);
|
||||
return;
|
||||
}
|
||||
if (challenge?.provider === 'turnstile') {
|
||||
setMathChallenge(null);
|
||||
return;
|
||||
}
|
||||
// Fallback: fetch a fresh math challenge when provider is math.
|
||||
void api
|
||||
.get<CaptchaChallenge>('/api/v1/auth/captcha-challenge')
|
||||
.then((res) => {
|
||||
if (res.data.provider === 'math') setMathChallenge(res.data);
|
||||
})
|
||||
.catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
}, []);
|
||||
|
||||
const onCaptchaToken = useCallback((token: string | null) => {
|
||||
setCaptchaToken(token);
|
||||
}, []);
|
||||
@ -108,11 +145,20 @@ export function LoginPage() {
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
let tokenToSend = captchaToken;
|
||||
if (
|
||||
captchaRequired &&
|
||||
mathChallenge?.provider === 'math' &&
|
||||
mathChallenge.challengeToken &&
|
||||
mathAnswer.trim()
|
||||
) {
|
||||
tokenToSend = `math:${mathChallenge.challengeToken}:${mathAnswer.trim()}`;
|
||||
}
|
||||
const res = await api.post<LoginResponse>('/api/v1/auth/login', {
|
||||
email: email.trim(),
|
||||
password,
|
||||
...(totpCode.trim() ? { totpCode: totpCode.trim() } : {}),
|
||||
...(captchaToken ? { captchaToken } : {}),
|
||||
...(tokenToSend ? { captchaToken: tokenToSend } : {}),
|
||||
});
|
||||
setAuth({
|
||||
accessToken: res.data.accessToken,
|
||||
@ -126,6 +172,7 @@ export function LoginPage() {
|
||||
} catch (e: any) {
|
||||
const code = e?.response?.data?.code;
|
||||
const retryAfterMinutes = e?.response?.data?.retryAfterMinutes;
|
||||
const challenge = e?.response?.data?.captcha as CaptchaChallenge | undefined;
|
||||
const msg =
|
||||
code === 'CAPTCHA_REQUIRED'
|
||||
? t('auth.captchaRequired')
|
||||
@ -142,7 +189,10 @@ export function LoginPage() {
|
||||
setError(String(msg));
|
||||
setEmailNotVerified(code === 'EMAIL_NOT_VERIFIED');
|
||||
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID') {
|
||||
setCaptchaRequired(true);
|
||||
applyCaptchaChallenge(challenge);
|
||||
} else if (captchaRequired) {
|
||||
// Refresh challenge after any failed attempt once captcha is active.
|
||||
applyCaptchaChallenge(challenge ?? null);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@ -216,8 +266,24 @@ export function LoginPage() {
|
||||
slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }}
|
||||
fullWidth
|
||||
/>
|
||||
{(captchaQ.data?.enabled && captchaQ.data.siteKey && captchaRequired) && (
|
||||
<TurnstileWidget siteKey={captchaQ.data.siteKey} onToken={onCaptchaToken} />
|
||||
{(captchaRequired &&
|
||||
(captchaQ.data?.provider === 'turnstile' || mathChallenge?.provider === 'turnstile') &&
|
||||
(captchaQ.data?.siteKey || mathChallenge?.siteKey)) && (
|
||||
<TurnstileWidget
|
||||
siteKey={(mathChallenge?.siteKey || captchaQ.data?.siteKey)!}
|
||||
onToken={onCaptchaToken}
|
||||
/>
|
||||
)}
|
||||
{captchaRequired && mathChallenge?.provider === 'math' && mathChallenge.prompt && (
|
||||
<TextField
|
||||
label={t('auth.captchaMathLabel', { prompt: mathChallenge.prompt })}
|
||||
value={mathAnswer}
|
||||
onChange={(e) => setMathAnswer(e.target.value)}
|
||||
helperText={t('auth.captchaMathHelper')}
|
||||
slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }}
|
||||
fullWidth
|
||||
autoFocus
|
||||
/>
|
||||
)}
|
||||
<Button variant="contained" onClick={submit} disabled={loading}>
|
||||
{loading ? t('auth.signingIn') : t('auth.signIn')}
|
||||
|
||||
@ -176,7 +176,6 @@ export function CandlePredictPage() {
|
||||
(!!state?.autoSettings?.enabled && state.autoSettings.stakeAccountKind === 'test');
|
||||
|
||||
const prevRoundStatusRef = useRef<string | null>(null);
|
||||
const prevSettlementKeyRef = useRef<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const prev = prevRoundStatusRef.current;
|
||||
@ -184,23 +183,13 @@ export function CandlePredictPage() {
|
||||
if (prev === 'betting' && next === 'locked') {
|
||||
void candlesQ.refetch();
|
||||
}
|
||||
if (prev === 'locked' && (next === 'settled' || round?.outcome)) {
|
||||
// One balances refresh on settle. Extra delayed refetches caused multi-second layout thrash.
|
||||
if (prev === 'locked' && (next === 'settled' || Boolean(round?.outcome))) {
|
||||
void balancesQ.refetch();
|
||||
window.setTimeout(() => void balancesQ.refetch(), 800);
|
||||
window.setTimeout(() => void balancesQ.refetch(), 2500);
|
||||
}
|
||||
prevRoundStatusRef.current = next;
|
||||
}, [round?.status, round?.outcome, candlesQ, balancesQ]);
|
||||
|
||||
useEffect(() => {
|
||||
const settlementKey = [round?.id, round?.settledAt, round?.outcome].filter(Boolean).join(':');
|
||||
if (!settlementKey) return;
|
||||
if (prevSettlementKeyRef.current && prevSettlementKeyRef.current !== settlementKey) {
|
||||
void balancesQ.refetch();
|
||||
}
|
||||
prevSettlementKeyRef.current = settlementKey;
|
||||
}, [round?.id, round?.settledAt, round?.outcome, balancesQ]);
|
||||
|
||||
const statusLabel = useMemo(() => {
|
||||
if (!round || !interval) return t('candlePredict.status.loading');
|
||||
if (round.status === 'betting') {
|
||||
@ -535,12 +524,6 @@ export function CandlePredictPage() {
|
||||
loading={balancesQ.isLoading && !balancesQ.data}
|
||||
/>
|
||||
|
||||
{(stateQ.isRefetching || balancesQ.isRefetching) && (
|
||||
<Alert severity="info" sx={{ mb: 2, borderRadius: 2 }}>
|
||||
Syncing live game state after connection changes…
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Paper
|
||||
elevation={0}
|
||||
sx={{
|
||||
@ -550,6 +533,8 @@ export function CandlePredictPage() {
|
||||
borderRadius: 2.5,
|
||||
border: `1px solid ${alpha('#D6B25E', 0.25)}`,
|
||||
background: alpha('#D6B25E', 0.06),
|
||||
// Keep status row height stable across betting/locked/settled text lengths.
|
||||
minHeight: { xs: 72, sm: 56 },
|
||||
}}
|
||||
>
|
||||
<IntervalSelector
|
||||
|
||||
@ -157,20 +157,26 @@ export const CandlestickChart = memo(function CandlestickChart({
|
||||
};
|
||||
chart.timeScale().subscribeVisibleLogicalRangeChange(onRangeChange);
|
||||
|
||||
let resizeRaf = 0;
|
||||
const ro = new ResizeObserver(() => {
|
||||
if (!containerRef.current) return;
|
||||
const nextHeight = fillHeight
|
||||
? containerRef.current.clientHeight || height
|
||||
: height;
|
||||
chart.applyOptions({
|
||||
width: containerRef.current.clientWidth,
|
||||
height: nextHeight,
|
||||
// Debounce + skip viewport re-snap: sibling UI height flicker must not reflow the chart range.
|
||||
if (resizeRaf) cancelAnimationFrame(resizeRaf);
|
||||
resizeRaf = requestAnimationFrame(() => {
|
||||
if (!containerRef.current || !chartRef.current) return;
|
||||
const nextHeight = fillHeight
|
||||
? containerRef.current.clientHeight || height
|
||||
: height;
|
||||
chartRef.current.applyOptions({
|
||||
width: containerRef.current.clientWidth,
|
||||
height: nextHeight,
|
||||
});
|
||||
});
|
||||
applyFixedViewport(chart, series.data().length, followLatestRef.current);
|
||||
});
|
||||
ro.observe(containerRef.current);
|
||||
|
||||
return () => {
|
||||
if (resizeRaf) cancelAnimationFrame(resizeRaf);
|
||||
chart.timeScale().unsubscribeVisibleLogicalRangeChange(onRangeChange);
|
||||
ro.disconnect();
|
||||
chart.remove();
|
||||
|
||||
@ -9,6 +9,7 @@ import {
|
||||
CardContent,
|
||||
Chip,
|
||||
FormControlLabel,
|
||||
Pagination,
|
||||
Stack,
|
||||
Switch,
|
||||
Table,
|
||||
@ -19,9 +20,11 @@ import {
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import DownloadRoundedIcon from '@mui/icons-material/DownloadRounded';
|
||||
import VolunteerActivismRoundedIcon from '@mui/icons-material/VolunteerActivismRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link as RouterLink } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
@ -61,12 +64,59 @@ type GrantItem = {
|
||||
};
|
||||
|
||||
const USDT_DECIMALS = 6;
|
||||
const GRANTS_PAGE_SIZE = 25;
|
||||
|
||||
function GrantsPagination({
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
onPageChange,
|
||||
}: {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
onPageChange: (page: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
||||
const from = total === 0 ? 0 : page * pageSize + 1;
|
||||
const to = Math.min(total, (page + 1) * pageSize);
|
||||
if (total <= pageSize) {
|
||||
return total > 0 ? (
|
||||
<Typography variant="body2" sx={{ opacity: 0.7, mt: 1.5, px: 2, pb: 2 }}>
|
||||
{t('common.pagination', { from, to, total })}
|
||||
</Typography>
|
||||
) : null;
|
||||
}
|
||||
return (
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1}
|
||||
sx={{ alignItems: 'center', justifyContent: 'space-between', mt: 1.5, px: 2, pb: 2 }}
|
||||
>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
{t('common.pagination', { from, to, total })}
|
||||
</Typography>
|
||||
<Pagination
|
||||
count={pageCount}
|
||||
page={page + 1}
|
||||
onChange={(_, value) => onPageChange(value - 1)}
|
||||
color="primary"
|
||||
shape="rounded"
|
||||
size="medium"
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
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 [grantsPage, setGrantsPage] = useState(0);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [exportError, setExportError] = useState<string | null>(null);
|
||||
|
||||
const configQ = useQuery({
|
||||
queryKey: ['admin-solo-encouragement-config'],
|
||||
@ -88,11 +138,15 @@ export function SoloEncouragementAdminPage() {
|
||||
});
|
||||
|
||||
const grantsQ = useQuery({
|
||||
queryKey: ['admin-solo-encouragement-grants', grantFilter],
|
||||
queryKey: ['admin-solo-encouragement-grants', grantFilter, grantsPage],
|
||||
queryFn: async () => {
|
||||
const status = grantFilter === 'all' ? '' : `status=${grantFilter}&`;
|
||||
const params = new URLSearchParams({
|
||||
limit: String(GRANTS_PAGE_SIZE),
|
||||
offset: String(grantsPage * GRANTS_PAGE_SIZE),
|
||||
});
|
||||
if (grantFilter !== 'all') params.set('status', grantFilter);
|
||||
const res = await api.get<{ items: GrantItem[]; total: number }>(
|
||||
`/api/v1/admin/solo-encouragement/grants?${status}limit=50`
|
||||
`/api/v1/admin/solo-encouragement/grants?${params.toString()}`
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
@ -102,6 +156,10 @@ export function SoloEncouragementAdminPage() {
|
||||
if (configQ.data && !form) setForm(configQ.data);
|
||||
}, [configQ.data, form]);
|
||||
|
||||
useEffect(() => {
|
||||
setGrantsPage(0);
|
||||
}, [grantFilter]);
|
||||
|
||||
const saveMut = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!form) return;
|
||||
@ -141,6 +199,31 @@ export function SoloEncouragementAdminPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const downloadExcel = async () => {
|
||||
setExporting(true);
|
||||
setExportError(null);
|
||||
try {
|
||||
const params: Record<string, string> = {};
|
||||
if (grantFilter !== 'all') params.status = grantFilter;
|
||||
const res = await api.get('/api/v1/admin/solo-encouragement/grants/export', {
|
||||
params,
|
||||
responseType: 'blob',
|
||||
});
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
const suffix = grantFilter === 'all' ? '' : `-${grantFilter}`;
|
||||
const url = URL.createObjectURL(res.data);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `solo-encouragement-grants${suffix}-${stamp}.xlsx`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch {
|
||||
setExportError(t('admin.soloEncouragement.exportFailed'));
|
||||
} finally {
|
||||
setExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const savedEnabled = configQ.data?.enabled ?? false;
|
||||
const isDirty =
|
||||
!!form &&
|
||||
@ -155,6 +238,8 @@ export function SoloEncouragementAdminPage() {
|
||||
return <Typography sx={{ p: 2 }}>{t('admin.soloEncouragement.loading')}</Typography>;
|
||||
}
|
||||
|
||||
const grantsTotal = grantsQ.data?.total ?? 0;
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack spacing={0.75} sx={{ mb: 2.5 }}>
|
||||
@ -304,21 +389,51 @@ export function SoloEncouragementAdminPage() {
|
||||
</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}
|
||||
<Stack
|
||||
direction={{ xs: 'column', sm: 'row' }}
|
||||
spacing={1}
|
||||
sx={{ alignItems: { sm: 'center' }, justifyContent: 'space-between', mb: 1.5, flexWrap: 'wrap' }}
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', 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>
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap' }}>
|
||||
<Button
|
||||
size="small"
|
||||
label={t(`admin.soloEncouragement.filter.${f}`)}
|
||||
color={grantFilter === f ? 'primary' : 'default'}
|
||||
variant={grantFilter === f ? 'filled' : 'outlined'}
|
||||
onClick={() => setGrantFilter(f)}
|
||||
/>
|
||||
))}
|
||||
variant="outlined"
|
||||
startIcon={<DownloadRoundedIcon />}
|
||||
onClick={() => void downloadExcel()}
|
||||
disabled={exporting || grantsTotal === 0}
|
||||
>
|
||||
{exporting ? t('admin.soloEncouragement.exporting') : t('admin.soloEncouragement.exportExcel')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
component={RouterLink}
|
||||
to="/admin/reports/financial-encouragement-grants"
|
||||
variant="text"
|
||||
>
|
||||
{t('admin.soloEncouragement.openReport')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Stack>
|
||||
{exportError && (
|
||||
<Alert severity="error" sx={{ mb: 1.5 }} onClose={() => setExportError(null)}>
|
||||
{exportError}
|
||||
</Alert>
|
||||
)}
|
||||
<Card sx={{ borderRadius: 3 }}>
|
||||
<CardContent sx={{ p: 0, '&:last-child': { pb: 0 } }}>
|
||||
<ScrollableTable>
|
||||
@ -347,7 +462,17 @@ export function SoloEncouragementAdminPage() {
|
||||
{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'} />
|
||||
<Chip
|
||||
size="small"
|
||||
label={row.status}
|
||||
color={
|
||||
row.status === 'eligible'
|
||||
? 'warning'
|
||||
: row.status === 'granted'
|
||||
? 'success'
|
||||
: 'default'
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
{row.status === 'eligible' && (
|
||||
@ -391,6 +516,12 @@ export function SoloEncouragementAdminPage() {
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
<GrantsPagination
|
||||
page={grantsPage}
|
||||
pageSize={GRANTS_PAGE_SIZE}
|
||||
total={grantsTotal}
|
||||
onPageChange={setGrantsPage}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
|
||||
@ -100,6 +100,8 @@ export const en = {
|
||||
'Your account has been temporarily locked after several unsuccessful login attempts. You can try again in {{minutes}} minute(s).',
|
||||
captchaRequired: 'Complete the security check below and try again.',
|
||||
captchaInvalid: 'Security check failed. Please try again.',
|
||||
captchaMathLabel: 'Security check: {{prompt}}',
|
||||
captchaMathHelper: 'Enter the result to continue after several failed attempts.',
|
||||
resendFailed: 'Failed to resend verification email',
|
||||
registerSubtitle: "Join Prediqo — use a friend's referral link or sign up directly.",
|
||||
invitedWithCode: 'You were invited with referral code <strong>{{code}}</strong>.',
|
||||
@ -1639,7 +1641,8 @@ export const en = {
|
||||
lockoutMinutes: 'Lockout duration (minutes)',
|
||||
lockoutMinutesHint: '0 = disable temporary lockout (max 1440 = 24h)',
|
||||
captchaAfter: 'Show captcha after N failures',
|
||||
captchaAfterHint: 'Requires captcha to be configured on the server',
|
||||
captchaAfterHint:
|
||||
'0 = disable. Built-in math captcha is used by default; set TURNSTILE_SITE_KEY / TURNSTILE_SECRET_KEY for Cloudflare Turnstile.',
|
||||
},
|
||||
candlePredict: {
|
||||
title: 'Candle Predict engine',
|
||||
@ -1843,6 +1846,10 @@ export const en = {
|
||||
noGrants: 'No grants yet.',
|
||||
grant: 'Grant',
|
||||
reject: 'Reject',
|
||||
exportExcel: 'Export Excel',
|
||||
exporting: 'Exporting…',
|
||||
exportFailed: 'Excel export failed',
|
||||
openReport: 'Open in Reports',
|
||||
filter: {
|
||||
eligible: 'Eligible',
|
||||
granted: 'Granted',
|
||||
|
||||
@ -101,6 +101,8 @@ export const fr = {
|
||||
'Votre compte a été temporairement verrouillé après plusieurs tentatives de connexion infructueuses. Vous pourrez réessayer dans {{minutes}} minute(s).',
|
||||
captchaRequired: 'Complétez la vérification de sécurité ci-dessous et réessayez.',
|
||||
captchaInvalid: 'Échec de la vérification de sécurité. Veuillez réessayer.',
|
||||
captchaMathLabel: 'Vérification : {{prompt}}',
|
||||
captchaMathHelper: 'Saisissez le résultat pour continuer après plusieurs échecs.',
|
||||
resendFailed: 'Échec de l’envoi de l’e-mail de vérification',
|
||||
registerSubtitle:
|
||||
'Rejoignez Prediqo — utilisez le lien de parrainage d’un ami ou inscrivez-vous directement.',
|
||||
@ -1656,7 +1658,8 @@ export const fr = {
|
||||
lockoutMinutes: 'Durée du verrouillage (minutes)',
|
||||
lockoutMinutesHint: '0 = désactiver (max 1440 = 24 h)',
|
||||
captchaAfter: 'Afficher le captcha après N échecs',
|
||||
captchaAfterHint: 'Nécessite un captcha configuré sur le serveur',
|
||||
captchaAfterHint:
|
||||
'0 = désactivé. Captcha mathématique intégré par défaut ; définissez TURNSTILE_SITE_KEY / TURNSTILE_SECRET_KEY pour Cloudflare Turnstile.',
|
||||
},
|
||||
candlePredict: {
|
||||
title: 'Moteur Candle Predict',
|
||||
@ -1860,6 +1863,10 @@ export const fr = {
|
||||
noGrants: 'Aucun bonus pour l’instant.',
|
||||
grant: 'Accorder',
|
||||
reject: 'Refuser',
|
||||
exportExcel: 'Exporter Excel',
|
||||
exporting: 'Export…',
|
||||
exportFailed: 'Échec de l’export Excel',
|
||||
openReport: 'Ouvrir dans Rapports',
|
||||
filter: {
|
||||
eligible: 'Éligibles',
|
||||
granted: 'Accordés',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user