After improving the performance of pages and start refonting the welcome page
This commit is contained in:
parent
78ce1e8997
commit
d02e0d281b
2
backend/dist/apps/ws.js
vendored
2
backend/dist/apps/ws.js
vendored
@ -31,7 +31,7 @@ async function main() {
|
||||
await securityHub_1.securityWsHub.start();
|
||||
const server = http_1.default.createServer((_req, res) => {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('Prediqo WebSocket gateway');
|
||||
res.end('Tloto WebSocket gateway');
|
||||
});
|
||||
const gameWss = new ws_1.WebSocketServer({ noServer: true });
|
||||
const supportWss = new ws_1.WebSocketServer({ noServer: true });
|
||||
|
||||
2
backend/dist/apps/ws.js.map
vendored
2
backend/dist/apps/ws.js.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"ws.js","sourceRoot":"","sources":["../../src/apps/ws.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;AAEH,gDAAwB;AACxB,2BAAqC;AAErC,sCAAmC;AACnC,4DAA0D;AAC1D,oDAAuE;AACvE,8CAA8E;AAC9E,4CAA+C;AAC/C,0DAAyD;AACzD,4DAA2D;AAE3D,KAAK,UAAU,IAAI;IACjB,IAAA,mBAAU,EAAC,IAAI,CAAC,CAAC;IAEjB,IAAI,CAAC,eAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC;QACvB,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC,CAAC;QACvD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAED,MAAM,IAAA,4BAAa,EAAC;QAClB,YAAY,EAAE,KAAK;QACnB,qBAAqB,EAAE,KAAK;QAC5B,gBAAgB,EAAE,KAAK;KACxB,CAAC,CAAC;IAEH,MAAM,eAAS,CAAC,KAAK,EAAE,CAAC;IACxB,MAAM,yBAAY,CAAC,KAAK,EAAE,CAAC;IAC3B,MAAM,2BAAa,CAAC,KAAK,EAAE,CAAC;IAE5B,MAAM,MAAM,GAAG,cAAI,CAAC,YAAY,CAAC,CAAC,IAA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AAC,GAAG,CAAC,qBAAqB,eAAM,CAAC,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;QAC1D,OAAO,CAAC,GAAG,CAAC,sBAAsB,eAAM,CAAC,EAAE,CAAC,YAAY,EAAE,CAAC,CAAC;QAC5D,OAAO,CAAC,GAAG,CAAC,cAAc,eAAM,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACpD,CAAC,CAAC,CAAC;AACL,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;IACjB,IAAA,yBAAgB,EAAC,CAAC,CAAC,CAAC;IACpB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
|
||||
@ -1,10 +1,15 @@
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
export declare function getOrCreateConversation(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function postCurrentMessage(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function userSendCurrentWithAttachment(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function listMyConversations(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getMessages(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function patchMessage(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function removeMessage(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function postMessage(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function postTyping(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function uploadCurrentAttachment(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function uploadAttachment(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getAttachment(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function adminListConversations(req: AuthRequest, res: Response): Promise<void>;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"support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wBAAsB,gBAAgB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAYrF;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAYrF;AAED,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOtF;AAED,wBAAsB,qBAAqB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAyB1F;AAED,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAmB5F;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB3F"}
|
||||
92
backend/dist/controllers/supportController.js
vendored
92
backend/dist/controllers/supportController.js
vendored
@ -37,10 +37,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getOrCreateConversation = getOrCreateConversation;
|
||||
exports.postCurrentMessage = postCurrentMessage;
|
||||
exports.userSendCurrentWithAttachment = userSendCurrentWithAttachment;
|
||||
exports.listMyConversations = listMyConversations;
|
||||
exports.getMessages = getMessages;
|
||||
exports.patchMessage = patchMessage;
|
||||
exports.removeMessage = removeMessage;
|
||||
exports.postMessage = postMessage;
|
||||
exports.postTyping = postTyping;
|
||||
exports.uploadCurrentAttachment = uploadCurrentAttachment;
|
||||
exports.uploadAttachment = uploadAttachment;
|
||||
exports.getAttachment = getAttachment;
|
||||
exports.adminListConversations = adminListConversations;
|
||||
@ -72,21 +77,55 @@ function handleError(res, e) {
|
||||
res.status(403).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
if (msg === 'Conversation not found' || msg === 'Not found') {
|
||||
if (msg === 'Conversation not found' || msg === 'Not found' || msg === 'Message not found') {
|
||||
res.status(404).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
if (msg === 'Edit window expired' ||
|
||||
msg === 'Delete window expired' ||
|
||||
msg === 'Message already deleted') {
|
||||
res.status(409).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({ error: msg });
|
||||
}
|
||||
async function getOrCreateConversation(req, res) {
|
||||
try {
|
||||
const conv = await supportService.getOrCreateConversation(buildCtx(req));
|
||||
const conv = await supportService.findCurrentConversation(buildCtx(req));
|
||||
res.json(conv);
|
||||
}
|
||||
catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function postCurrentMessage(req, res) {
|
||||
try {
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body : undefined;
|
||||
const msg = await supportService.sendToCurrentConversation(buildCtx(req), { body });
|
||||
res.status(201).json(msg);
|
||||
}
|
||||
catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function userSendCurrentWithAttachment(req, res) {
|
||||
try {
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body : undefined;
|
||||
const attachmentUrl = typeof req.body?.attachmentUrl === 'string' ? req.body.attachmentUrl : undefined;
|
||||
const attachmentName = typeof req.body?.attachmentName === 'string' ? req.body.attachmentName : undefined;
|
||||
const attachmentMime = typeof req.body?.attachmentMime === 'string' ? req.body.attachmentMime : undefined;
|
||||
const msg = await supportService.sendToCurrentConversation(buildCtx(req), {
|
||||
body,
|
||||
attachmentUrl,
|
||||
attachmentName,
|
||||
attachmentMime,
|
||||
});
|
||||
res.status(201).json(msg);
|
||||
}
|
||||
catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function listMyConversations(req, res) {
|
||||
try {
|
||||
const items = await supportService.listUserConversations(buildCtx(req));
|
||||
@ -106,6 +145,25 @@ async function getMessages(req, res) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function patchMessage(req, res) {
|
||||
try {
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body : '';
|
||||
const msg = await supportService.editMessage(req.params.id, req.params.messageId, buildCtx(req), body);
|
||||
res.json(msg);
|
||||
}
|
||||
catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function removeMessage(req, res) {
|
||||
try {
|
||||
const msg = await supportService.deleteMessage(req.params.id, req.params.messageId, buildCtx(req));
|
||||
res.json(msg);
|
||||
}
|
||||
catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function postMessage(req, res) {
|
||||
try {
|
||||
const body = typeof req.body?.body === 'string' ? req.body.body : undefined;
|
||||
@ -126,6 +184,34 @@ async function postTyping(req, res) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function uploadCurrentAttachment(req, res) {
|
||||
try {
|
||||
if (!req.file) {
|
||||
res.status(400).json({ error: 'No file uploaded' });
|
||||
return;
|
||||
}
|
||||
const filePath = supportService.resolveUploadPath(req.file.filename);
|
||||
try {
|
||||
await (0, uploadValidation_1.validateUploadedFile)(filePath, supportUpload_1.SUPPORT_ALLOWED_MIMES);
|
||||
}
|
||||
catch (e) {
|
||||
(0, fileMagic_1.removeUploadedFile)(filePath);
|
||||
const msg = e instanceof Error ? e.message : 'File validation failed';
|
||||
res.status(msg.includes('virus') ? 422 : 400).json({ error: msg });
|
||||
return;
|
||||
}
|
||||
const url = supportService.publicAttachmentUrl(req.file.filename);
|
||||
await (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.support, req.file.filename);
|
||||
res.status(201).json({
|
||||
attachmentUrl: url,
|
||||
attachmentName: req.file.originalname,
|
||||
attachmentMime: req.file.mimetype,
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
handleError(res, e);
|
||||
}
|
||||
}
|
||||
async function uploadAttachment(req, res) {
|
||||
try {
|
||||
if (!req.file) {
|
||||
@ -162,6 +248,8 @@ async function getAttachment(req, res) {
|
||||
res.status(404).json({ error: 'File not found' });
|
||||
return;
|
||||
}
|
||||
// Helmet defaults to CORP same-origin; the web app is on another port/origin.
|
||||
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
|
||||
res.sendFile(filePath);
|
||||
}
|
||||
catch (e) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
28
backend/dist/domain/candle-predict/index.d.ts
vendored
28
backend/dist/domain/candle-predict/index.d.ts
vendored
@ -25,6 +25,13 @@ declare function mapConfig(row: repo.CandlePredictConfigRow): {
|
||||
auto: boolean;
|
||||
multiCandle: boolean;
|
||||
};
|
||||
/** Display-only chart identity (synthetic; not an external market symbol). */
|
||||
instrument: {
|
||||
symbol: string;
|
||||
displayName: string;
|
||||
quoteCurrency: string;
|
||||
priceDigits: number;
|
||||
};
|
||||
updatedAt: string;
|
||||
};
|
||||
type PlayerConfigDto = Omit<ReturnType<typeof mapConfig>, 'poolWinnerRule' | 'poolMultiplier' | 'tieTolerancePercent' | 'tieToleranceMaxPercent' | 'tieToleranceMinEnabled' | 'tieToleranceMaxEnabled' | 'dailyRevenueTarget' | 'dailyRevenueOverflowStrategy'>;
|
||||
@ -88,6 +95,13 @@ export declare function getPublicConfig(): Promise<{
|
||||
auto: boolean;
|
||||
multiCandle: boolean;
|
||||
};
|
||||
/** Display-only chart identity (synthetic; not an external market symbol). */
|
||||
instrument: {
|
||||
symbol: string;
|
||||
displayName: string;
|
||||
quoteCurrency: string;
|
||||
priceDigits: number;
|
||||
};
|
||||
updatedAt: string;
|
||||
}>;
|
||||
export declare function updateAdminConfig(body: Record<string, unknown>): Promise<{
|
||||
@ -114,6 +128,13 @@ export declare function updateAdminConfig(body: Record<string, unknown>): Promis
|
||||
auto: boolean;
|
||||
multiCandle: boolean;
|
||||
};
|
||||
/** Display-only chart identity (synthetic; not an external market symbol). */
|
||||
instrument: {
|
||||
symbol: string;
|
||||
displayName: string;
|
||||
quoteCurrency: string;
|
||||
priceDigits: number;
|
||||
};
|
||||
updatedAt: string;
|
||||
}>;
|
||||
export declare function listAdminIntervals(): Promise<{
|
||||
@ -200,6 +221,13 @@ export declare function getGameState(userId?: string, intervalMinutes?: number,
|
||||
auto: boolean;
|
||||
multiCandle: boolean;
|
||||
};
|
||||
/** Display-only chart identity (synthetic; not an external market symbol). */
|
||||
instrument: {
|
||||
symbol: string;
|
||||
displayName: string;
|
||||
quoteCurrency: string;
|
||||
priceDigits: number;
|
||||
};
|
||||
updatedAt: string;
|
||||
};
|
||||
intervals: PlayerIntervalDto[];
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/domain/candle-predict/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,4CAA4C,CAAC;AACnE,OAAO,KAAK,gBAAgB,MAAM,qCAAqC,CAAC;AACxE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AA4BvE,OAAO,EAOL,KAAK,4BAA4B,EAClC,MAAM,2CAA2C,CAAC;AAsLnD,iBAAS,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;EA6BlD;AAED,KAAK,eAAe,GAAG,IAAI,CACzB,UAAU,CAAC,OAAO,SAAS,CAAC,EAC1B,gBAAgB,GAChB,gBAAgB,GAChB,qBAAqB,GACrB,wBAAwB,GACxB,wBAAwB,GACxB,wBAAwB,GACxB,oBAAoB,GACpB,8BAA8B,CACjC,CAAC;AAiBF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,eAAe,EAAE,MAAM,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,OAAO,CAAC;IACnB,QAAQ,EAAE,OAAO,CAAC;IAClB,uBAAuB,EAAE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AE,WAAW,CAAC;CAChC;;;;;;;;;;;;;;;;GA6HF;AAED,wBAAgB,wBAAwB,IAAI,IAAI,CAoB/C"}
|
||||
49
backend/dist/domain/candle-predict/index.js
vendored
49
backend/dist/domain/candle-predict/index.js
vendored
@ -229,6 +229,13 @@ function mapConfig(row) {
|
||||
auto: row.prediction_auto_enabled ?? true,
|
||||
multiCandle: row.prediction_multi_enabled ?? true,
|
||||
},
|
||||
/** Display-only chart identity (synthetic; not an external market symbol). */
|
||||
instrument: {
|
||||
symbol: row.instrument_symbol ?? 'FO',
|
||||
displayName: row.instrument_display_name ?? 'Full Option',
|
||||
quoteCurrency: row.instrument_quote_currency ?? 'USDT',
|
||||
priceDigits: Number(row.instrument_price_digits ?? 2),
|
||||
},
|
||||
updatedAt: row.updated_at.toISOString(),
|
||||
};
|
||||
}
|
||||
@ -479,6 +486,44 @@ async function updateAdminConfig(body) {
|
||||
}
|
||||
dailyRevenueOverflowStrategy = body.dailyRevenueOverflowStrategy;
|
||||
}
|
||||
const instrumentBody = typeof body.instrument === 'object' && body.instrument !== null
|
||||
? body.instrument
|
||||
: null;
|
||||
const instrumentSymbol = typeof instrumentBody?.symbol === 'string'
|
||||
? instrumentBody.symbol.trim()
|
||||
: typeof body.instrumentSymbol === 'string'
|
||||
? body.instrumentSymbol.trim()
|
||||
: undefined;
|
||||
const instrumentDisplayName = typeof instrumentBody?.displayName === 'string'
|
||||
? instrumentBody.displayName.trim()
|
||||
: typeof body.instrumentDisplayName === 'string'
|
||||
? body.instrumentDisplayName.trim()
|
||||
: undefined;
|
||||
const instrumentQuoteCurrency = typeof instrumentBody?.quoteCurrency === 'string'
|
||||
? instrumentBody.quoteCurrency.trim()
|
||||
: typeof body.instrumentQuoteCurrency === 'string'
|
||||
? body.instrumentQuoteCurrency.trim()
|
||||
: undefined;
|
||||
const instrumentPriceDigits = typeof instrumentBody?.priceDigits === 'number'
|
||||
? instrumentBody.priceDigits
|
||||
: typeof body.instrumentPriceDigits === 'number'
|
||||
? body.instrumentPriceDigits
|
||||
: undefined;
|
||||
if (instrumentSymbol !== undefined && !instrumentSymbol) {
|
||||
throw new Error('instrument.symbol must not be empty');
|
||||
}
|
||||
if (instrumentDisplayName !== undefined && !instrumentDisplayName) {
|
||||
throw new Error('instrument.displayName must not be empty');
|
||||
}
|
||||
if (instrumentQuoteCurrency !== undefined && !instrumentQuoteCurrency) {
|
||||
throw new Error('instrument.quoteCurrency must not be empty');
|
||||
}
|
||||
if (instrumentPriceDigits !== undefined &&
|
||||
(!Number.isInteger(instrumentPriceDigits) ||
|
||||
instrumentPriceDigits < 0 ||
|
||||
instrumentPriceDigits > 8)) {
|
||||
throw new Error('instrument.priceDigits must be an integer between 0 and 8');
|
||||
}
|
||||
const updated = await repo.updateConfig({
|
||||
stakeAmounts,
|
||||
minStakeAmount,
|
||||
@ -520,6 +565,10 @@ async function updateAdminConfig(body) {
|
||||
typeof body.predictionTypes.multiCandle === 'boolean'
|
||||
? body.predictionTypes.multiCandle
|
||||
: undefined,
|
||||
instrumentSymbol,
|
||||
instrumentDisplayName,
|
||||
instrumentQuoteCurrency,
|
||||
instrumentPriceDigits,
|
||||
});
|
||||
// Global enable toggles should win over stale per-interval "on/off" overrides.
|
||||
if (typeof body.tieToleranceMinEnabled === 'boolean' ||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -14,6 +14,8 @@ export type PlayerRoundDto = {
|
||||
secondsToBettingEnd: number;
|
||||
secondsToBettingStart: number;
|
||||
secondsToClose: number;
|
||||
bettingEndMs?: number;
|
||||
bettingStartMs?: number;
|
||||
shortPoolPercent?: number;
|
||||
longPoolPercent?: number;
|
||||
version?: number;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"publishRoundState.d.ts","sourceRoot":"","sources":["../../../../src/domain/candle-predict/realtime/publishRoundState.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,oEAAoE;AACpE,wBAAsB,iBAAiB,CAAC,KAAK,EAAE;IAC7C,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,cAAc,CAAC;IACtB,KAAK,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACxC,SAAS,CAAC,EAAE,eAAe,GAAG,eAAe,CAAC;CAC/C,GAAG,OAAO,CAAC,IAAI,CAAC,CAqDhB;AAED,wBAAsB,mBAAmB,CACvC,eAAe,EAAE,MAAM,EACvB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC9B,OAAO,CAAC,IAAI,CAAC,CAOf"}
|
||||
{"version":3,"file":"publishRoundState.d.ts","sourceRoot":"","sources":["../../../../src/domain/candle-predict/realtime/publishRoundState.ts"],"names":[],"mappings":"AAMA,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,MAAM,CAAC;I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round.secondsToBettingEnd,
|
||||
secondsToBettingStart: input.round.secondsToBettingStart,
|
||||
secondsToClose: input.round.secondsToClose,
|
||||
bettingEndMs: input.round.bettingEndMs ?? input.round.candleOpenMs,
|
||||
bettingStartMs: input.round.bettingStartMs,
|
||||
version: input.round.version ?? 1,
|
||||
};
|
||||
await (0, roundCache_1.setRoundCache)(input.intervalMinutes, input.openMs, cachePayload);
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"publishRoundState.js","sourceRoot":"","sources":["../../../../src/domain/candle-predict/realtime/publishRoundState.ts"],"names":[],"mappings":";;AA4BA,8CA2DC;AAED,kDAUC;AAnGD,4CAAyC;AACzC,mEAAwF;AACxF,iEAAiE;AACjE,2DAAmE;AACnE,yEAA6E;AAuB7E,oEAAoE;AAC7D,KAAK,UAAU,iBAAiB,CAAC,KAMvC;IACC,IAAI,CAAC,eAAM,CAAC,KAAK,CAAC,OAAO;QAAE,OAAO;IAElC,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,EAAE,KAAK,IAAI,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,CAAC;IACxC,MAAM,SAAS,GAAG,SAAS,GAAG,QAAQ,CAAC;IACvC,MAAM,gBAAgB,GACpB,KAAK,CAAC,KAAK,CAAC,gBAAgB;QAC5B,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACxE,MAAM,eAAe,GACnB,KAAK,CAAC,KAAK,CAAC,eAAe;QAC3B,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,QAAQ,GAAG,SAAS,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,C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,MAAM,IAAA,0BAAiB,EAAC,KAAK,CAAC,eAAe,EAAE;QAC7C,IAAI,EAAE,KAAK,CAAC,SAAS,IAAI,eAAe;QACxC,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,OAAO,EAAE;YACP,KAAK,EAAE,YAAY;YACnB,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,GAAG,CAAC,YAAY,IAAI,IAAI,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACvE;QACD,OAAO,EAAE,YAAY,CAAC,OAAO;KAC9B,CAAC,CAAC;AACL,CAAC;AAEM,KAAK,UAAU,mBAAmB,CACvC,eAAuB,EACvB,MAA+B;IAE/B,IAAI,CAAC,eAAM,CAAC,KAAK,CAAC,OAAO;QAAE,OAAO;IAClC,MAAM,IAAA,0BAAiB,EAAC,eAAe,EAAE;QACvC,IAAI,EAAE,eAAe;QACrB,eAAe;QACf,OAAO,EAAE,EAAE,MAAM,EAAE;KACpB,CAAC,CAAC;AACL,CAAC"}
|
||||
{"version":3,"file":"publishRoundState.js","sourceRoot":"","sources":["../../../../src/domain/candle-predict/realtime/publishRoundState.ts"],"names":[],"mappings":";;AA8BA,8CA6DC;AAED,kDAUC;AAvGD,4CAAyC;AACzC,mEAAwF;AACxF,iEAAiE;AACjE,2DAAmE;AACnE,yEAA6E;AAyB7E,oEAAoE;AAC7D,KAAK,UAAU,iBAAiB,CAAC,KAMvC;IACC,IAAI,CAAC,eAAM,CAAC,KAAK,CAAC,OAAO;QAAE,OAAO;IAElC,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,EAAE,KAAK,IAAI,CAAC,CAAC;IAC1C,MAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,EAAE,IAAI,IAAI,CAAC,CAAC;IACxC,MAAM,SAAS,GAAG,SAAS,GAAG,QAAQ,CAAC;IACvC,MAAM,gBAAgB,GACpB,KAAK,CAAC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
||||
4
backend/dist/models/settings.model.d.ts
vendored
4
backend/dist/models/settings.model.d.ts
vendored
@ -53,5 +53,9 @@ export interface SystemSettings {
|
||||
login_risk_auto_suspend_accounts: boolean;
|
||||
/** Minimum login risk score (0–100) to trigger auto-suspend when enabled. */
|
||||
login_risk_auto_suspend_threshold: number;
|
||||
/** Minutes after send during which the author may edit a support message (0 = disabled). */
|
||||
support_message_edit_window_minutes: number;
|
||||
/** Minutes after send during which the author may delete a support message (0 = disabled). */
|
||||
support_message_delete_window_minutes: number;
|
||||
}
|
||||
//# sourceMappingURL=settings.model.d.ts.map
|
||||
2
backend/dist/models/settings.model.d.ts.map
vendored
2
backend/dist/models/settings.model.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"settings.model.d.ts","sourceRoot":"","sources":["../../src/models/settings.model.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,8FAA8F;AAC9F,MAAM,WAAW,cAAc;IAC7B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,0BAA0B,EAAE,OAAO,CAAC;IACpC,0BAA0B,EAAE,OAAO,CAAC;IACpC,uBAAuB,EAAE,OAAO,CAAC;IACjC,wBAAwB,EAAE,OAAO,CAAC;IAClC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oCAAoC,EAAE,OAAO,CAAC;IAC9C,sDAAsD;IACtD,iBAAiB,EAAE,OAAO,CAAC;IAC3B,+DAA+D;IAC/D,kCAAkC,EAAE,OAAO,CAAC;IAC5C,mCAAmC,EAAE,OAAO,CAAC;IAC7C,kCAAkC,EAAE,OAAO,CAAC;IAC5C,mCAAmC,EAAE,OAAO,CAAC;IAC7C,4EAA4E;IAC5E,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oDAAoD;IACpD,cAAc,EAAE,MAAM,CAAC;IACvB,sDAAsD;IACtD,oBAAoB,EAAE,MAAM,CAAC;IAC7B,0BAA0B,EAAE,MAAM,CAAC;IACnC,8BA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kC,EAAE,OAAO,CAAC;IAC5C,mCAAmC,EAAE,OAAO,CAAC;IAC7C,4EAA4E;IAC5E,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oDAAoD;IACpD,cAAc,EAAE,MAAM,CAAC;IACvB,sDAAsD;IACtD,oBAAoB,EAAE,MAAM,CAAC;IAC7B,0BAA0B,EAAE,MAAM,CAAC;IACnC,8BAA8B,EAAE,MAAM,CAAC;IACvC,6BAA6B,EAAE,MAAM,CAAC;IACtC,oCAAoC,EAAE,MAAM,CAAC;IAC7C,mCAAmC,EAAE,MAAM,CAAC;IAC5C,gCAAgC,EAAE,MAAM,CAAC;IACzC,8FAA8F;IAC9F,+BAA+B,EAAE,MAAM,CAAC;IACxC,0FAA0F;IAC1F,iCAAiC,EAAE,MAAM,CAAC;IAC1C,sEAAsE;IACtE,iBAAiB,EAAE,OAAO,CAAC;IAC3B,uFAAuF;IACvF,sBAAsB,EAAE,OAAO,CAAC;IAChC,kEAAkE;IAClE,uBAAuB,EAAE,MAAM,CAAC;IAChC,6DAA6D;IAC7D,yBAAyB,EAAE,MAAM,CAAC;IAClC,6DAA6D;IAC7D,qBAAqB,EAAE,MAAM,CAAC;IAC9B,yGAAyG;IACzG,4BAA4B,EAAE,MAAM,CAAC;IACrC,2EAA2E;IAC3E,2BAA2B,EAAE,OAAO,CAAC;IACrC,yEAAyE;IACzE,gCAAgC,EAAE,OAAO,CAAC;IAC1C,6EAA6E;IAC7E,iCAAiC,EAAE,MAAM,CAAC;IAC1C,4FAA4F;IAC5F,mCAAmC,EAAE,MAAM,CAAC;IAC5C,8FAA8F;IAC9F,qCAAqC,EAAE,MAAM,CAAC;CAC/C"}
|
||||
2
backend/dist/models/support.model.d.ts
vendored
2
backend/dist/models/support.model.d.ts
vendored
@ -24,6 +24,8 @@ export type SupportMessageRow = {
|
||||
attachment_name: string | null;
|
||||
attachment_mime: string | null;
|
||||
read_at: Date | null;
|
||||
edited_at: Date | null;
|
||||
deleted_at: Date | null;
|
||||
created_at: Date;
|
||||
};
|
||||
//# sourceMappingURL=support.model.d.ts.map
|
||||
2
backend/dist/models/support.model.d.ts.map
vendored
2
backend/dist/models/support.model.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"support.model.d.ts","sourceRoot":"","sources":["../../src/models/support.model.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,yBAAyB,GAAG,MAAM,GAAG,SAAS,GAAG,UAAU,GAAG,QAAQ,CAAC;AAEnF,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC;AAE7D,MAAM,MAAM,sBAAsB,GAAG;IACnC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,yBAAyB,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,eAAe,EAAE,IAAI,GAAG,IAAI,CAAC;IAC7B,oBAAoB,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,iBAAiB,CAAC;IAC/B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,OAAO,EAAE,IAAI,GAAG,IAAI,CAAC;IACrB,U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AE,IAAI,CAAC;CAClB,CAAC"}
|
||||
2
backend/dist/realtime/redis/keys.d.ts
vendored
2
backend/dist/realtime/redis/keys.d.ts
vendored
@ -38,6 +38,8 @@ export type RoundCacheHash = {
|
||||
secondsToBettingEnd: string;
|
||||
secondsToBettingStart: string;
|
||||
secondsToClose: string;
|
||||
bettingEndMs: string;
|
||||
bettingStartMs: string;
|
||||
version: string;
|
||||
};
|
||||
export type PoolCacheHash = {
|
||||
|
||||
2
backend/dist/realtime/redis/keys.d.ts.map
vendored
2
backend/dist/realtime/redis/keys.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../../../src/realtime/redis/keys.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAE9D,eAAO,MAAM,YAAY,YAAY,CAAC;AAEtC,eAAO,MAAM,SAAS;;;sCAGK,MAAM,UAAU,MAAM;sCAEtB,MAAM,UAAU,MAAM;uCAErB,MAAM;iCACZ,MAAM,mBAAmB,MAAM,UAAU,MAAM;4CAEpC,MAAM;mCACf,MAAM;;;4CAGG,MAAM;kCAChB,MAAM;;IAE3B,6FAA6F;;8CAE5D,MAAM;uCACb,MAAM,mBAAmB,MAAM;wCAE9B,MAAM;CACzB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;I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,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd,CAAC"}
|
||||
4
backend/dist/realtime/redis/roundCache.d.ts
vendored
4
backend/dist/realtime/redis/roundCache.d.ts
vendored
@ -17,6 +17,10 @@ export type CachedRoundDto = {
|
||||
secondsToBettingEnd: number;
|
||||
secondsToBettingStart: number;
|
||||
secondsToClose: number;
|
||||
/** Absolute ms when the open (betting) window ends (= candleOpenMs). */
|
||||
bettingEndMs?: number;
|
||||
/** Absolute ms when the open window starts. */
|
||||
bettingStartMs?: number;
|
||||
version: number;
|
||||
};
|
||||
/** Serialize a player-visible round DTO into a Redis HASH. */
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"roundCache.d.ts","sourceRoot":"","sources":["../../../src/realtime/redis/roundCache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AAM7C,MAAM,MAAM,cAAc,GAAG;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,mBAAmB,EAAE,MAAM,CA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/realtime/redis/roundCache.js
vendored
4
backend/dist/realtime/redis/roundCache.js
vendored
@ -37,6 +37,8 @@ function serializeRoundToHash(round) {
|
||||
secondsToBettingEnd: String(round.secondsToBettingEnd),
|
||||
secondsToBettingStart: String(round.secondsToBettingStart),
|
||||
secondsToClose: String(round.secondsToClose),
|
||||
bettingEndMs: String(round.bettingEndMs ?? round.candleOpenMs),
|
||||
bettingStartMs: empty(round.bettingStartMs != null ? String(round.bettingStartMs) : ''),
|
||||
version: String(round.version ?? 1),
|
||||
};
|
||||
}
|
||||
@ -62,6 +64,8 @@ function parseRoundFromHash(hash) {
|
||||
secondsToBettingEnd: Number(hash.secondsToBettingEnd ?? 0),
|
||||
secondsToBettingStart: Number(hash.secondsToBettingStart ?? 0),
|
||||
secondsToClose: Number(hash.secondsToClose ?? 0),
|
||||
bettingEndMs: Number(hash.bettingEndMs ?? hash.candleOpenMs),
|
||||
bettingStartMs: parseOptionalNumber(hash.bettingStartMs) ?? undefined,
|
||||
version: Number(hash.version ?? 1),
|
||||
};
|
||||
}
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"roundCache.js","sourceRoot":"","sources":["../../../src/realtime/redis/roundCache.ts"],"names":[],"mappings":";;AAsCA,oDAuBC;AAGD,gDAsBC;AAED,sCAWC;AAED,sCAeC;AAED,sDAQC;AA7HD,iCAAmC;AACnC,qCAA0C;AAE1C,MAAM,iBAAiB,GAAG,KAAM,CAAC;AAuBjC,SAAS,KAAK,CAAC,KAAgC;IAC7C,OAAO,KAAK,IAAI,EAAE,CAAC;AACrB,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAyB;IACpD,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IACxC,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IACxB,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,C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AAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACpD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAClC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,CAAC,KAAK,CAAC,oCAAoC,EAAE,CAAC,CAAC,CAAC;QACvD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,qBAAqB,CACzC,eAAuB,EACvB,MAAc;IAEd,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,CAAC;IAC/B,IAAI,CAAC,KAAK;QAAE,OAAO,CAAC,CAAC;IACrB,MAAM,GAAG,GAAG,gBAAS,CAAC,KAAK,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC;IACrD,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;AAC1C,CAAC"}
|
||||
@ -24,6 +24,14 @@ export type CandlePredictConfigRow = {
|
||||
prediction_single_enabled: boolean;
|
||||
prediction_auto_enabled: boolean;
|
||||
prediction_multi_enabled: boolean;
|
||||
/** Short ticker shown on the chart, e.g. FO */
|
||||
instrument_symbol: string;
|
||||
/** Full instrument name, e.g. Full Option */
|
||||
instrument_display_name: string;
|
||||
/** Quote currency for the pair, e.g. USDT */
|
||||
instrument_quote_currency: string;
|
||||
/** Decimal places for chart price labels */
|
||||
instrument_price_digits: number;
|
||||
updated_at: Date;
|
||||
};
|
||||
export type CandlePredictMultiLevelRow = {
|
||||
@ -139,6 +147,10 @@ export type ConfigUpdate = Partial<{
|
||||
predictionSingleEnabled: boolean;
|
||||
predictionAutoEnabled: boolean;
|
||||
predictionMultiEnabled: boolean;
|
||||
instrumentSymbol: string;
|
||||
instrumentDisplayName: string;
|
||||
instrumentQuoteCurrency: string;
|
||||
instrumentPriceDigits: number;
|
||||
}>;
|
||||
export declare function updateConfig(update: ConfigUpdate): Promise<CandlePredictConfigRow>;
|
||||
/**
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -88,12 +88,16 @@ async function updateConfig(update) {
|
||||
wallet_type_code = $15,
|
||||
auto_modes = $16::jsonb,
|
||||
is_active = $17,
|
||||
prediction_single_enabled = $18,
|
||||
prediction_auto_enabled = $19,
|
||||
prediction_multi_enabled = $20,
|
||||
daily_revenue_target = $21,
|
||||
daily_revenue_overflow_strategy = $22,
|
||||
updated_at = NOW()
|
||||
prediction_single_enabled = $18,
|
||||
prediction_auto_enabled = $19,
|
||||
prediction_multi_enabled = $20,
|
||||
daily_revenue_target = $21,
|
||||
daily_revenue_overflow_strategy = $22,
|
||||
instrument_symbol = $23,
|
||||
instrument_display_name = $24,
|
||||
instrument_quote_currency = $25,
|
||||
instrument_price_digits = $26,
|
||||
updated_at = NOW()
|
||||
WHERE id = 1
|
||||
RETURNING *`, [
|
||||
update.intervalMinutes ?? current.interval_minutes,
|
||||
@ -120,6 +124,10 @@ async function updateConfig(update) {
|
||||
update.dailyRevenueOverflowStrategy ??
|
||||
current.daily_revenue_overflow_strategy ??
|
||||
'neutral',
|
||||
update.instrumentSymbol ?? current.instrument_symbol ?? 'FO',
|
||||
update.instrumentDisplayName ?? current.instrument_display_name ?? 'Full Option',
|
||||
update.instrumentQuoteCurrency ?? current.instrument_quote_currency ?? 'USDT',
|
||||
update.instrumentPriceDigits ?? current.instrument_price_digits ?? 2,
|
||||
]);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"settingsRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/settingsRepository.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAiM3C,gEAAgE;AAEhE,wBAAgB,uBAAuB,IAAI,IAAI,CAI9C;AAID;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CA4B3D;AA4ED;;;;;;;;;;GAUG;AAEH,wBAAsB,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBpF"}
|
||||
{"version":3,"file":"settingsRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/settingsRepository.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAyM3C,gEAAgE;AAEhE,wBAAgB,uBAAuB,IAAI,IAAI,CAI9C;AAID;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CA4B3D;AAgFD;;;;;;;;;;GAUG;AAEH,wBAAsB,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBpF"}
|
||||
@ -49,6 +49,8 @@ function buildDefaults() {
|
||||
sybil_auto_suspend_accounts: true,
|
||||
login_risk_auto_suspend_accounts: false,
|
||||
login_risk_auto_suspend_threshold: 70,
|
||||
support_message_edit_window_minutes: 15,
|
||||
support_message_delete_window_minutes: 15,
|
||||
};
|
||||
}
|
||||
const BOOLEAN_KEYS = new Set([
|
||||
@ -85,6 +87,8 @@ const INTEGER_KEYS = new Set([
|
||||
'login_captcha_after_failures',
|
||||
'max_concurrent_sessions',
|
||||
'login_risk_auto_suspend_threshold',
|
||||
'support_message_edit_window_minutes',
|
||||
'support_message_delete_window_minutes',
|
||||
]);
|
||||
/**
|
||||
|
||||
@ -161,6 +165,8 @@ const UPDATABLE_KEYS = [
|
||||
'login_risk_auto_suspend_accounts',
|
||||
'login_risk_auto_suspend_threshold',
|
||||
'max_concurrent_sessions',
|
||||
'support_message_edit_window_minutes',
|
||||
'support_message_delete_window_minutes',
|
||||
];
|
||||
/**
|
||||
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"settingsRepository.js","sourceRoot":"","sources":["../../src/repositories/settingsRepository.ts"],"names":[],"mappings":";;AAuMA,0DAIC;AAYD,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BAAmB;IAEnB,oCAAoC;IAEpC,qCAAqC;IAErC,oCAAoC;IAEpC,qCAAqC;IAErC,sBAAsB;IAEtB,gBAAgB;IAEhB,sBAAsB;IAEtB,4BAA4B;IAE5B,gCAAgC;IAEhC,+BAA+B;IAE/B,sCAAsC;IAEtC,qCAAqC;IAErC,kCAAkC;IAElC,iCAAiC;IAEjC,mCAAmC;IAEnC,mBAAmB;IAEnB,2BAA2B;IAE3B,uBAAuB;IAEvB,8BAA8B;IAE9B,wBAAwB;IAExB,6BAA6B;IAE7B,kCAAkC;IAElC,mCAAmC;IAEnC,yBAAyB;IAEzB,qCAAqC;IAErC,uCAAuC;CAE/B,CAAC;AAIX;;;;;;;;;;GAUG;AAEI,KAAK,UAAU,cAAc,CAAC,OAAgC;IAEnE,KAAK,MAAM,GAAG,IAAI,cAAc,EAAE,CAAC;QAEjC,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;QAE3B,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QAElC,MAAM,GAAG,GAAG,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAEpF,MAAM,IAAA,kBAAK,EAET;;sEAEgE,EAEhE,CAAC,GAAG,EAAE,GAAG,CAAC,CAEX,CAAC;IAEJ,CAAC;IAED,uBAAuB,EAAE,CAAC;AAE5B,CAAC"}
|
||||
@ -30,6 +30,11 @@ export declare function updateConversation(id: string, patch: Partial<{
|
||||
export declare function touchConversationLastMessage(id: string, preview: string, incrementUnreadUser: boolean, incrementUnreadStaff: boolean): Promise<void>;
|
||||
export declare function resetUnreadCounters(id: string, side: 'user' | 'staff'): Promise<void>;
|
||||
export declare function listMessages(conversationId: string, after?: string, limit?: number): Promise<SupportMessageRow[]>;
|
||||
export declare function findMessageById(id: string): Promise<SupportMessageRow | null>;
|
||||
export declare function findLatestVisibleMessage(conversationId: string): Promise<SupportMessageRow | null>;
|
||||
export declare function updateMessageBody(id: string, body: string): Promise<SupportMessageRow | null>;
|
||||
export declare function softDeleteMessage(id: string): Promise<SupportMessageRow | null>;
|
||||
export declare function updateConversationPreview(id: string, preview: string, lastMessageAt: Date | null): Promise<void>;
|
||||
export declare function createMessage(input: {
|
||||
conversationId: string;
|
||||
senderType: SupportSenderType;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"supportRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/supportRepository.ts"],"names":[],"mappings":"AACA,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,yBAAyB,CAAC;AAEjC,MAAM,MAAM,uBAAuB,GAAG;IACpC,MAAM,CAAC,EAAE,yBAAyB,CAAC;IACnC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,wBAAsB,oBAAoB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CAM7F;AAED,wBAAsB,6BAA6B,CACjD,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CASxC;AAED,wBAAsB,gCAAgC,CACpD,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CASxC;AAED,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,MAAM,EACd,KAAK,SAAK,GACT,OAAO,CAAC,sBAAsB,EAAE,CAAC,CAQnC;AAED,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC;IAAE,IAAI,EAAE,sBAAsB,EAAE,CAAC;IAAC,KAAK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AAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAkB7B;AAED,wBAAsB,gBAAgB,CACpC,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,GAAG,OAAO,GAC3B,OAAO,CAAC,MAAM,CAAC,CAYjB;AAED,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC,CAM7D;AAED,wBAAsB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACtE,EAAE,EAAE,MAAM,CAAC;IACX,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;IACxB,UAAU,EAAE,OAAO,CAAC;IACpB,UAAU,EAAE,IAAI,CAAC;CAClB,GAAG,IAAI,CAAC,CAqBR;AAED,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAShF;AAED,sFAAsF;AACtF,wBAAsB,kCAAkC,CACtD,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,MAAM,CAAC,CAkBjB"}
|
||||
{"version":3,"file":"supportRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/supportRepository.ts"],"names":[],"mappings":"AACA,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,yBAAyB,CAAC;AAEjC,M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AE,MAAM,CAAC;IACvB,UAAU,EAAE,iBAAiB,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAkB7B;AAED,wBAAsB,gBAAgB,CACpC,cAAc,EAAE,MAAM,EACtB,UAAU,EAAE,MAAM,GAAG,OAAO,GAC3B,OAAO,CAAC,MAAM,CAAC,CAYjB;AAED,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC,CAM7D;AAED,wBAAsB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACtE,EAAE,EAAE,MAAM,CAAC;IACX,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;IACxB,UAAU,EAAE,OAAO,CAAC;IACpB,UAAU,EAAE,IAAI,CAAC;CAClB,GAAG,IAAI,CAAC,CAqBR;AAED,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAShF;AAED,sFAAsF;AACtF,wBAAsB,kCAAkC,CACtD,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,MAAM,CAAC,CAkBjB"}
|
||||
38
backend/dist/repositories/supportRepository.js
vendored
38
backend/dist/repositories/supportRepository.js
vendored
@ -11,6 +11,11 @@ exports.updateConversation = updateConversation;
|
||||
exports.touchConversationLastMessage = touchConversationLastMessage;
|
||||
exports.resetUnreadCounters = resetUnreadCounters;
|
||||
exports.listMessages = listMessages;
|
||||
exports.findMessageById = findMessageById;
|
||||
exports.findLatestVisibleMessage = findLatestVisibleMessage;
|
||||
exports.updateMessageBody = updateMessageBody;
|
||||
exports.softDeleteMessage = softDeleteMessage;
|
||||
exports.updateConversationPreview = updateConversationPreview;
|
||||
exports.createMessage = createMessage;
|
||||
exports.markMessagesRead = markMessagesRead;
|
||||
exports.countUnreadStaffInbox = countUnreadStaffInbox;
|
||||
@ -83,6 +88,7 @@ async function listConversationsAdmin(filters) {
|
||||
params.push(term);
|
||||
i++;
|
||||
}
|
||||
conditions.push('c.last_message_at IS NOT NULL');
|
||||
const where = conditions.join(' AND ');
|
||||
const limit = Math.min(filters.limit ?? 50, 100);
|
||||
const offset = filters.offset ?? 0;
|
||||
@ -157,6 +163,38 @@ async function listMessages(conversationId, after, limit = 100) {
|
||||
ORDER BY created_at ASC
|
||||
LIMIT $2`, [conversationId, limit]);
|
||||
}
|
||||
async function findMessageById(id) {
|
||||
const rows = await (0, connection_1.query)('SELECT * FROM support_messages WHERE id = $1', [id]);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
async function findLatestVisibleMessage(conversationId) {
|
||||
const rows = await (0, connection_1.query)(`SELECT * FROM support_messages
|
||||
WHERE conversation_id = $1 AND deleted_at IS NULL
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1`, [conversationId]);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
async function updateMessageBody(id, body) {
|
||||
const rows = await (0, connection_1.query)(`UPDATE support_messages
|
||||
SET body = $2, edited_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
RETURNING *`, [id, body]);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
async function softDeleteMessage(id) {
|
||||
const rows = await (0, connection_1.query)(`UPDATE support_messages
|
||||
SET deleted_at = NOW()
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
RETURNING *`, [id]);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
async function updateConversationPreview(id, preview, lastMessageAt) {
|
||||
await (0, connection_1.query)(`UPDATE support_conversations SET
|
||||
last_message_preview = $2,
|
||||
last_message_at = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`, [id, preview.slice(0, 500), lastMessageAt]);
|
||||
}
|
||||
async function createMessage(input) {
|
||||
const rows = await (0, connection_1.query)(`INSERT INTO support_messages (
|
||||
conversation_id, sender_type, sender_user_id, body,
|
||||
|
||||
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;AA8HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AA0axB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA+HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAodxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
19
backend/dist/routes/index.js
vendored
19
backend/dist/routes/index.js
vendored
@ -59,6 +59,7 @@ const analyticsController = __importStar(require("../controllers/analyticsContro
|
||||
const reportsController = __importStar(require("../controllers/reportsController"));
|
||||
const gameController = __importStar(require("../controllers/gameController"));
|
||||
const advertisementController = __importStar(require("../controllers/advertisementController"));
|
||||
const marketingController = __importStar(require("../controllers/marketingController"));
|
||||
const candlePredictController = __importStar(require("../controllers/candlePredictController"));
|
||||
const gamePlayController = __importStar(require("../controllers/gamePlayController"));
|
||||
const securityController = __importStar(require("../controllers/securityController"));
|
||||
@ -108,17 +109,25 @@ router.get('/faq/entries/:id', faqController.getPublicFaq);
|
||||
router.post('/faq/entries/:id/view', faqController.recordView);
|
||||
router.post('/faq/entries/:id/helpful', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(adminSchemas_1.faqHelpfulBodySchema), faqController.recordHelpful);
|
||||
router.get('/faq/files/:filename', faqController.getFaqFile);
|
||||
/** Public marketing reads (landing / welcome) — catalogue only, no play/bets. */
|
||||
/** Public marketing reads (landing / welcome) — catalogue + social-proof feeds. */
|
||||
router.get('/games', gameController.listGames);
|
||||
router.get('/advertisements', advertisementController.listAdvertisements);
|
||||
router.get('/marketing/daily-stats', marketingController.getDailyStats);
|
||||
router.get('/marketing/activity-feed', marketingController.getActivityFeed);
|
||||
router.get('/marketing/withdrawal-feed', marketingController.getWithdrawalFeed);
|
||||
/** Public Share Card verification (HMAC token). */
|
||||
router.get('/share-cards/verify/:token', shareCardController.verifyShareCard);
|
||||
/** Support messaging — guests (visitor token) and optional authenticated users. */
|
||||
router.get('/support/files/:filename', supportController.getAttachment);
|
||||
router.post('/support/conversations/current', optionalAuth_1.optionalAuthMiddleware, supportController.getOrCreateConversation);
|
||||
router.post('/support/conversations/current/messages', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(adminSchemas_1.supportMessageBodySchema), supportController.postCurrentMessage);
|
||||
router.post('/support/conversations/current/messages/attachment', optionalAuth_1.optionalAuthMiddleware, supportController.userSendCurrentWithAttachment);
|
||||
router.post('/support/conversations/current/upload', optionalAuth_1.optionalAuthMiddleware, supportUpload_1.supportUpload.single('file'), supportController.uploadCurrentAttachment);
|
||||
router.get('/support/conversations', optionalAuth_1.optionalAuthMiddleware, supportController.listMyConversations);
|
||||
router.get('/support/conversations/:id/messages', optionalAuth_1.optionalAuthMiddleware, supportController.getMessages);
|
||||
router.post('/support/conversations/:id/messages', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(adminSchemas_1.supportMessageBodySchema), supportController.postMessage);
|
||||
router.patch('/support/conversations/:id/messages/:messageId', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(adminSchemas_1.supportMessageBodySchema), supportController.patchMessage);
|
||||
router.delete('/support/conversations/:id/messages/:messageId', optionalAuth_1.optionalAuthMiddleware, supportController.removeMessage);
|
||||
router.post('/support/conversations/:id/messages/attachment', optionalAuth_1.optionalAuthMiddleware, supportController.userSendWithAttachment);
|
||||
router.post('/support/conversations/:id/typing', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(adminSchemas_1.supportTypingBodySchema), supportController.postTyping);
|
||||
router.post('/support/conversations/:id/upload', optionalAuth_1.optionalAuthMiddleware, supportUpload_1.supportUpload.single('file'), supportController.uploadAttachment);
|
||||
@ -214,9 +223,9 @@ router.get('/admin/fund-requests/:id', (0, auth_1.requireRoles)('admin'), (0, au
|
||||
router.post('/admin/fund-requests/:id/approve', (0, auth_1.requirePermissions)('fund_operation.approve'), fundApprovalController.approveFundRequest);
|
||||
router.post('/admin/fund-requests/:id/reject', (0, auth_1.requirePermissions)('fund_operation.approve'), (0, validate_1.validateBody)(adminSchemas_1.fundRequestRejectBodySchema), fundApprovalController.rejectFundRequest);
|
||||
router.delete('/admin/fund-requests/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.request'), fundApprovalController.cancelFundRequest);
|
||||
router.get('/admin/approval-policies', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('approval_policy.view'), fundApprovalController.listApprovalPolicies);
|
||||
router.get('/admin/approval-policies/revisions', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('approval_policy.view'), fundApprovalController.listPolicyRevisions);
|
||||
router.post('/admin/approval-policies/draft-change', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('approval_policy.manage'), (0, validate_1.validateBody)(adminSchemas_1.approvalPolicyDraftBodySchema), fundApprovalController.draftPolicyChange);
|
||||
router.get('/admin/approval-policies', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.approve'), fundApprovalController.listApprovalPolicies);
|
||||
router.get('/admin/approval-policies/revisions', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.approve'), fundApprovalController.listPolicyRevisions);
|
||||
router.post('/admin/approval-policies/draft-change', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.approve'), (0, validate_1.validateBody)(adminSchemas_1.approvalPolicyDraftBodySchema), fundApprovalController.draftPolicyChange);
|
||||
router.post('/admin/users/:userId/verify-email', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('users.admin'), adminController.verifyUserEmail);
|
||||
router.patch('/admin/users/:userId/security', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('security.admin'), (0, validate_1.validateBody)(adminSchemas_1.adminUserSecurityBodySchema), securityController.updateUserSecurity);
|
||||
router.get('/admin/security/alerts', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('security.admin'), (0, validate_1.validateQuery)(querySchemas_1.securityAlertsQuerySchema), securityController.listAlerts);
|
||||
@ -299,6 +308,8 @@ router.get('/admin/support/conversations/:id', (0, auth_2.requireStaff)(), suppo
|
||||
router.patch('/admin/support/conversations/:id', (0, auth_2.requireStaff)(), (0, validate_1.validateBody)(adminResourceSchemas_1.supportConversationUpdateBodySchema), supportController.adminUpdateConversation);
|
||||
router.get('/admin/support/conversations/:id/messages', (0, auth_2.requireStaff)(), supportController.adminGetMessages);
|
||||
router.post('/admin/support/conversations/:id/messages', (0, auth_2.requireStaff)(), (0, validate_1.validateBody)(adminSchemas_1.supportMessageBodySchema), supportController.adminPostMessage);
|
||||
router.patch('/admin/support/conversations/:id/messages/:messageId', (0, auth_2.requireStaff)(), (0, validate_1.validateBody)(adminSchemas_1.supportMessageBodySchema), supportController.patchMessage);
|
||||
router.delete('/admin/support/conversations/:id/messages/:messageId', (0, auth_2.requireStaff)(), supportController.removeMessage);
|
||||
router.post('/admin/support/conversations/:id/messages/attachment', (0, auth_2.requireStaff)(), supportController.adminSendWithAttachment);
|
||||
router.post('/admin/support/conversations/:id/typing', (0, auth_2.requireStaff)(), supportController.postTyping);
|
||||
router.post('/admin/support/conversations/:id/upload', (0, auth_2.requireStaff)(), supportUpload_1.supportUpload.single('file'), supportController.adminUploadAttachment);
|
||||
|
||||
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/services/authService.d.ts.map
vendored
2
backend/dist/services/authService.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"authService.d.ts","sourceRoot":"","sources":["../../src/services/authService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2BH,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAmB,KAAK,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAmCtC,+DAA+D;AAC/D,wBAAsB,eAAe,CAAC,IAAI,EAAE;IAC1C,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,OAAO,CAAC,UAAU,CAAC,CAatB;AAED,wEAAwE;AACxE,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,UAAU,GAAG,UAAU,CAWnE;AAoBD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,IAAI,CAgB/E;AAED;;GAEG;AACH,wBAAsB,QAAQ,CAAC,KAAK,EAAE;IACpC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,kBAAkB,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAA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,KAAK,IAAI,CAQ5E"}
|
||||
3
backend/dist/services/authService.js
vendored
3
backend/dist/services/authService.js
vendored
@ -64,6 +64,7 @@ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
||||
const otplib_1 = require("otplib");
|
||||
const crypto_1 = require("crypto");
|
||||
const QRCode = __importStar(require("qrcode"));
|
||||
const platformName_1 = require("../brand/platformName");
|
||||
const config_1 = require("../config");
|
||||
const crypto_2 = require("../utils/crypto");
|
||||
const userRepository = __importStar(require("../repositories/userRepository"));
|
||||
@ -679,7 +680,7 @@ async function setupTotp(userId, opts) {
|
||||
}
|
||||
const secret = otplib_1.authenticator.generateSecret();
|
||||
const encrypted = (0, crypto_2.encrypt)(secret);
|
||||
const otpauth = otplib_1.authenticator.keyuri(user.email_hash, 'Prediqo', secret);
|
||||
const otpauth = otplib_1.authenticator.keyuri(user.email_hash, platformName_1.PLATFORM_NAME, secret);
|
||||
const qrCodeUrl = await QRCode.toDataURL(otpauth);
|
||||
await userRepository.updateTotp(userId, encrypted, false);
|
||||
await auditLogRepository.create({
|
||||
|
||||
2
backend/dist/services/authService.js.map
vendored
2
backend/dist/services/authService.js.map
vendored
File diff suppressed because one or more lines are too long
2
backend/dist/services/emailService.d.ts.map
vendored
2
backend/dist/services/emailService.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"emailService.d.ts","sourceRoot":"","sources":["../../src/services/emailService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,qEAAqE;AACrE,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD;AAOD;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,OAAO,CAEnD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAG1C;AAmCD,6DAA6D;AAC7D,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAG1D;AA8CD;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,EAAE,EAAE,MAAM,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E,oBAAoB,GACxB,OAAO,CAAC,IAAI,CAAC,CAoBf"}
|
||||
55
backend/dist/services/emailService.js
vendored
55
backend/dist/services/emailService.js
vendored
@ -22,6 +22,7 @@ exports.sendTotpDisabledEmail = sendTotpDisabledEmail;
|
||||
exports.sendRolesChangedEmail = sendRolesChangedEmail;
|
||||
exports.sendPermissionsChangedEmail = sendPermissionsChangedEmail;
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
const platformName_1 = require("../brand/platformName");
|
||||
const config_1 = require("../config");
|
||||
let transporter = null;
|
||||
/** Gmail app passwords are often copied with spaces — strip them. */
|
||||
@ -96,19 +97,19 @@ function resolveFromAddress() {
|
||||
const host = config_1.config.email.host.toLowerCase();
|
||||
const usesGmail = host.includes('gmail.com') || host.includes('googlemail.com');
|
||||
if (usesGmail && user.endsWith('@gmail.com') && !fromEmail.endsWith('@gmail.com')) {
|
||||
return `"Prediqo" <${user}>`;
|
||||
return `"${platformName_1.PLATFORM_NAME}" <${user}>`;
|
||||
}
|
||||
return from;
|
||||
}
|
||||
/** Shared Prediqo HTML shell (no external image — works in all mail clients). */
|
||||
/** Shared branded HTML shell (no external image — works in all mail clients). */
|
||||
function brandEmailHtml(title, bodyHtml) {
|
||||
return `
|
||||
<div style="font-family:system-ui,-apple-system,Segoe UI,sans-serif;max-width:520px;margin:0 auto;padding:24px;background:#0B0F1A;color:#F8FAFC;border-radius:12px;">
|
||||
<div style="font-weight:900;font-size:20px;letter-spacing:0.3px;color:#10B981;margin:0 0 16px;">Prediqo</div>
|
||||
<div style="font-weight:900;font-size:20px;letter-spacing:0.3px;color:#10B981;margin:0 0 16px;">${platformName_1.PLATFORM_WORDMARK}</div>
|
||||
<h2 style="color:#F8FAFC;margin:0 0 16px;font-size:22px;">${title}</h2>
|
||||
${bodyHtml}
|
||||
<p style="font-size:11px;color:#64748B;margin:28px 0 0;border-top:1px solid #1E2740;padding-top:14px;">
|
||||
Prediqo — premium prediction platform
|
||||
${platformName_1.PLATFORM_NAME} — premium prediction platform
|
||||
</p>
|
||||
</div>
|
||||
`;
|
||||
@ -119,9 +120,9 @@ const CTA_STYLE = 'background:#10B981;color:#0B0F1A;text-decoration:none;padding
|
||||
* @param verifyUrl - Full URL opened by the user to confirm ownership
|
||||
*/
|
||||
async function sendVerificationEmail(to, verifyUrl) {
|
||||
const subject = 'Verify your Prediqo email address';
|
||||
const subject = 'Verify your Tloto email address';
|
||||
const text = [
|
||||
'Welcome to Prediqo!',
|
||||
'Welcome to Tloto!',
|
||||
'',
|
||||
'Please verify your email address by opening this link:',
|
||||
verifyUrl,
|
||||
@ -130,7 +131,7 @@ async function sendVerificationEmail(to, verifyUrl) {
|
||||
'If you did not create an account, you can ignore this email.',
|
||||
].join('\n');
|
||||
const html = brandEmailHtml('Verify your email', `
|
||||
<p style="color:#94A3B8;line-height:1.5;">Thanks for joining <strong style="color:#F8FAFC;">Prediqo</strong>. Confirm your email address to secure your account.</p>
|
||||
<p style="color:#94A3B8;line-height:1.5;">Thanks for joining <strong style="color:#F8FAFC;">Tloto</strong>. Confirm your email address to secure your account.</p>
|
||||
<p style="margin:24px 0;">
|
||||
<a href="${verifyUrl}" style="${CTA_STYLE}">Verify email</a>
|
||||
</p>
|
||||
@ -162,9 +163,9 @@ async function sendVerificationEmail(to, verifyUrl) {
|
||||
* Sends a password reset message with a clickable link.
|
||||
*/
|
||||
async function sendPasswordResetEmail(to, resetUrl) {
|
||||
const subject = 'Reset your Prediqo password';
|
||||
const subject = 'Reset your Tloto password';
|
||||
const text = [
|
||||
'You requested a password reset for your Prediqo account.',
|
||||
'You requested a password reset for your Tloto account.',
|
||||
'',
|
||||
'Open this link to choose a new password:',
|
||||
resetUrl,
|
||||
@ -173,7 +174,7 @@ async function sendPasswordResetEmail(to, resetUrl) {
|
||||
'If you did not request this, you can ignore this email.',
|
||||
].join('\n');
|
||||
const html = brandEmailHtml('Reset your password', `
|
||||
<p style="color:#94A3B8;line-height:1.5;">We received a request to reset the password for your <strong style="color:#F8FAFC;">Prediqo</strong> account.</p>
|
||||
<p style="color:#94A3B8;line-height:1.5;">We received a request to reset the password for your <strong style="color:#F8FAFC;">Tloto</strong> account.</p>
|
||||
<p style="margin:24px 0;">
|
||||
<a href="${resetUrl}" style="${CTA_STYLE}">Reset password</a>
|
||||
</p>
|
||||
@ -205,9 +206,9 @@ async function sendPasswordResetEmail(to, resetUrl) {
|
||||
* Sends a security alert notification to an administrator email address.
|
||||
*/
|
||||
async function sendSecurityAlertEmail(to, alert) {
|
||||
const subject = `[Prediqo Security ${alert.severity.toUpperCase()}] ${alert.title}`;
|
||||
const subject = `[Tloto Security ${alert.severity.toUpperCase()}] ${alert.title}`;
|
||||
const text = [
|
||||
'A security alert was raised on the Prediqo platform.',
|
||||
'A security alert was raised on the Tloto platform.',
|
||||
'',
|
||||
`Alert ID: ${alert.alertId}`,
|
||||
`Severity: ${alert.severity}`,
|
||||
@ -298,8 +299,8 @@ async function sendUserSecurityEmail(to, subject, title, bodyLines, htmlBody) {
|
||||
}
|
||||
/** Notifies the user of a sign-in from a new IP or device. */
|
||||
async function sendNewLoginEmail(to, ctx) {
|
||||
await sendUserSecurityEmail(to, 'New sign-in to your Prediqo account', 'New sign-in detected', [
|
||||
'We detected a sign-in to your Prediqo account from a new IP address or device.',
|
||||
await sendUserSecurityEmail(to, 'New sign-in to your Tloto account', 'New sign-in detected', [
|
||||
'We detected a sign-in to your Tloto account from a new IP address or device.',
|
||||
'',
|
||||
formatSecurityContext(ctx),
|
||||
'',
|
||||
@ -313,8 +314,8 @@ async function sendNewLoginEmail(to, ctx) {
|
||||
/** Notifies the user of a sign-in from a new country. */
|
||||
async function sendNewCountryLoginEmail(to, ctx) {
|
||||
const country = ctx.countryCode?.trim() || 'unknown';
|
||||
await sendUserSecurityEmail(to, 'Sign-in from a new country on your Prediqo account', 'New country sign-in', [
|
||||
`We detected a sign-in to your Prediqo account from a new country (${country}).`,
|
||||
await sendUserSecurityEmail(to, 'Sign-in from a new country on your Tloto account', 'New country sign-in', [
|
||||
`We detected a sign-in to your Tloto account from a new country (${country}).`,
|
||||
'',
|
||||
formatSecurityContext(ctx),
|
||||
'',
|
||||
@ -327,20 +328,20 @@ async function sendNewCountryLoginEmail(to, ctx) {
|
||||
}
|
||||
/** Notifies the user that their password was changed. */
|
||||
async function sendPasswordChangedEmail(to, ctx) {
|
||||
await sendUserSecurityEmail(to, 'Your Prediqo password was changed', 'Password changed', [
|
||||
'The password for your Prediqo account was just changed.',
|
||||
await sendUserSecurityEmail(to, 'Your Tloto password was changed', 'Password changed', [
|
||||
'The password for your Tloto account was just changed.',
|
||||
'',
|
||||
formatSecurityContext(ctx),
|
||||
'',
|
||||
`Time: ${new Date().toISOString()}`,
|
||||
], `<p>The password for your Prediqo account was just changed.</p>
|
||||
], `<p>The password for your Tloto account was just changed.</p>
|
||||
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
|
||||
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
|
||||
}
|
||||
/** Notifies the user that two-factor authentication was enabled. */
|
||||
async function sendTotpEnabledEmail(to, ctx) {
|
||||
await sendUserSecurityEmail(to, 'Two-factor authentication enabled on Prediqo', '2FA enabled', [
|
||||
'Two-factor authentication was enabled on your Prediqo account.',
|
||||
await sendUserSecurityEmail(to, 'Two-factor authentication enabled on Tloto', '2FA enabled', [
|
||||
'Two-factor authentication was enabled on your Tloto account.',
|
||||
'',
|
||||
formatSecurityContext(ctx),
|
||||
'',
|
||||
@ -351,8 +352,8 @@ async function sendTotpEnabledEmail(to, ctx) {
|
||||
}
|
||||
/** Notifies the user that two-factor authentication was disabled. */
|
||||
async function sendTotpDisabledEmail(to, ctx) {
|
||||
await sendUserSecurityEmail(to, 'Two-factor authentication disabled on Prediqo', '2FA disabled', [
|
||||
'Two-factor authentication was disabled on your Prediqo account.',
|
||||
await sendUserSecurityEmail(to, 'Two-factor authentication disabled on Tloto', '2FA disabled', [
|
||||
'Two-factor authentication was disabled on your Tloto account.',
|
||||
'',
|
||||
formatSecurityContext(ctx),
|
||||
'',
|
||||
@ -364,8 +365,8 @@ async function sendTotpDisabledEmail(to, ctx) {
|
||||
/** Notifies the user that their platform roles were updated. */
|
||||
async function sendRolesChangedEmail(to, roles, ctx) {
|
||||
const roleList = roles.join(', ') || '(none)';
|
||||
await sendUserSecurityEmail(to, 'Your Prediqo account roles were updated', 'Account roles updated', [
|
||||
'An administrator updated the roles assigned to your Prediqo account.',
|
||||
await sendUserSecurityEmail(to, 'Your Tloto account roles were updated', 'Account roles updated', [
|
||||
'An administrator updated the roles assigned to your Tloto account.',
|
||||
'',
|
||||
`New roles: ${roleList}`,
|
||||
'',
|
||||
@ -380,8 +381,8 @@ async function sendRolesChangedEmail(to, roles, ctx) {
|
||||
/** Notifies the user that their effective permissions were updated. */
|
||||
async function sendPermissionsChangedEmail(to, permissions, ctx) {
|
||||
const permList = permissions.join(', ') || '(none)';
|
||||
await sendUserSecurityEmail(to, 'Your Prediqo account permissions were updated', 'Account permissions updated', [
|
||||
'An administrator updated the permissions assigned to your Prediqo account.',
|
||||
await sendUserSecurityEmail(to, 'Your Tloto account permissions were updated', 'Account permissions updated', [
|
||||
'An administrator updated the permissions assigned to your Tloto account.',
|
||||
'',
|
||||
`Effective permissions: ${permList}`,
|
||||
'',
|
||||
|
||||
2
backend/dist/services/emailService.js.map
vendored
2
backend/dist/services/emailService.js.map
vendored
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"settingsService.d.ts","sourceRoot":"","sources":["../../src/services/settingsService.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AA6K3C;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAI3D;AAID;;;;;;;;;;GAUG;AAEH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CA+K3F;AAID;;;;;;;;GAQG;AAEH,wBAAsB,cAAc,CAClC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,EAChC,KAAK,CAAC,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GACjE,OAAO,CAAC,cAAc,CAAC,CAkCzB"}
|
||||
{"version":3,"file":"settingsService.d.ts","sourceRoot":"","sources":["../../src/services/settingsService.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAyM3C;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAI3D;AAID;;;;;;;;;;GAUG;AAEH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CA2L3F;AAID;;;;;;;;GAQG;AAEH,wBAAsB,cAAc,CAClC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,EAChC,KAAK,CAAC,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GACjE,OAAO,CAAC,cAAc,CAAC,CAkCzB"}
|
||||
12
backend/dist/services/settingsService.js
vendored
12
backend/dist/services/settingsService.js
vendored
@ -98,6 +98,12 @@ function validateUpdates(updates) {
|
||||
if (updates.max_concurrent_sessions !== undefined) {
|
||||
updates.max_concurrent_sessions = clampInt(updates.max_concurrent_sessions, 0, 100);
|
||||
}
|
||||
if (updates.support_message_edit_window_minutes !== undefined) {
|
||||
updates.support_message_edit_window_minutes = clampInt(updates.support_message_edit_window_minutes, 0, 10080);
|
||||
}
|
||||
if (updates.support_message_delete_window_minutes !== undefined) {
|
||||
updates.support_message_delete_window_minutes = clampInt(updates.support_message_delete_window_minutes, 0, 10080);
|
||||
}
|
||||
}
|
||||
/**
|
||||
|
||||
@ -212,6 +218,12 @@ function parseSettingsUpdates(body) {
|
||||
if (typeof body.login_captcha_after_failures === 'number') {
|
||||
updates.login_captcha_after_failures = body.login_captcha_after_failures;
|
||||
}
|
||||
if (typeof body.support_message_edit_window_minutes === 'number') {
|
||||
updates.support_message_edit_window_minutes = body.support_message_edit_window_minutes;
|
||||
}
|
||||
if (typeof body.support_message_delete_window_minutes === 'number') {
|
||||
updates.support_message_delete_window_minutes = body.support_message_delete_window_minutes;
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
/**
|
||||
|
||||
2
backend/dist/services/settingsService.js.map
vendored
2
backend/dist/services/settingsService.js.map
vendored
File diff suppressed because one or more lines are too long
@ -6,6 +6,11 @@ export type SupportRealtimeEvent = {
|
||||
} | {
|
||||
type: 'message.read';
|
||||
conversationId: string;
|
||||
} | {
|
||||
type: 'message.updated' | 'message.deleted';
|
||||
conversationId: string;
|
||||
messageId: string;
|
||||
message?: Record<string, unknown>;
|
||||
} | {
|
||||
type: 'conversation.updated';
|
||||
conversationId: string;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"supportRealtimeService.d.ts","sourceRoot":"","sources":["../../src/services/supportRealtimeService.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,oBAAoB,GAC5B;IACE,IAAI,EAAE,aAAa,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,GACD;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GAChD;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GACxD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC;AAIzF,wBAAsB,mBAAmB,CACvC,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAQf;AAED,wBAAsB,kBAAkB,CACtC,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,MAAM,GAAG,OAAO,EACvB,MAAM,EAAE,OAAO,GACd,OAAO,CAAC,IAAI,CAAC,CAef;AAED,wBAAsB,mBAAmB,CACvC,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;IAAE,UAAU,EAAE,OAAO,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,CAAC,CAQxD"}
|
||||
{"version":3,"file":"supportRealtimeService.d.ts","sourceRoot":"","sources":["../../src/services/supportRealtimeService.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,oBAAoB,GAC5B;IACE,IAAI,EAAE,aAAa,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,GACD;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GAChD;IACE,IAAI,EAAE,iBAAiB,GAAG,iBAAiB,CAAC;IAC5C,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC,GACD;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,GACxD;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAAC;AAIzF,wBAAsB,mBAAmB,CACvC,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,oBAAoB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAQf;AAED,wBAAsB,kBAAkB,CACtC,cAAc,EAAE,MAAM,EACtB,KAAK,EAAE,MAAM,GAAG,OAAO,EACvB,MAAM,EAAE,OAAO,GACd,OAAO,CAAC,IAAI,CAAC,CAef;AAED,wBAAsB,mBAAmB,CACvC,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC;IAAE,UAAU,EAAE,OAAO,CAAC;IAAC,WAAW,EAAE,OAAO,CAAA;CAAE,CAAC,CAQxD"}
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"supportRealtimeService.js","sourceRoot":"","sources":["../../src/services/supportRealtimeService.ts"],"names":[],"mappings":";;AAgBA,kDAWC;AAED,gDAmBC;AAED,kDAUC;AA5DD,qDAA0D;AAC1D,+DAAiE;AAajE,MAAM,cAAc,GAAG,CAAC,CAAC;AAElB,KAAK,UAAU,mBAAmB,CACvC,cAAsB,EACtB,KAA2B;IAE3B,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,CAAC;IAC/B,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,MAAM,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,GAAG,KAAK,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAC7D,MAAM,KAAK,CAAC,OAAO,CAAC,8BAAgB,CAAC,kBAAkB,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC;IAClF,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,KAAK,CAAC,OAAO,CAAC,8BAAgB,CAAC,gBAAgB,EAAE,EAAE,OAAO,CAAC,CAAC;IACpE,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,kBAAkB,CACtC,cAAsB,EACtB,KAAuB,EACvB,MAAe;IAEf,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,CAAC;IAC/B,IAAI,CAAC,KAAK;QAAE,OAAO;IACnB,MAAM,GAAG,GAAG,8BAAgB,CAAC,MAAM,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IAC3D,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,cAAc,CAAC,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IACD,MAAM,mBAAmB,CAAC,cAAc,EAAE;QACxC,IAAI,EAAE,QAAQ;QACd,cAAc;QACd,KAAK;QACL,MAAM;KACP,CAAC,CAAC;AACL,CAAC;AAEM,KAAK,UAAU,mBAAmB,CACvC,cAAsB;IAEtB,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,CAAC;IAC/B,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;IAC7D,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACtC,KAAK,CAAC,GAAG,CAAC,8BAAgB,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAC1D,KAAK,CAAC,GAAG,CAAC,8BAAgB,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;KAC5D,CAAC,CAAC;IACH,OAAO,EAAE,UAAU,EAAE,IAAI,KAAK,GAAG,EAAE,WAAW,EAAE,KAAK,KAAK,GAAG,EAAE,CAAC;AAClE,CAAC"}
|
||||
{"version":3,"file":"supportRealtimeService.js","sourceRoot":"","sources":["../../src/services/supportRealtimeService.ts"],"names":[],"mappings":";;AAsBA,kDAWC;AAED,gDAmBC;AAED,kDAUC;AAlED,qDAA0D;AAC1D,+DA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AC;IAC/B,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;IAC7D,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACtC,KAAK,CAAC,GAAG,CAAC,8BAAgB,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,CAAC;QAC1D,KAAK,CAAC,GAAG,CAAC,8BAAgB,CAAC,MAAM,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;KAC5D,CAAC,CAAC;IACH,OAAO,EAAE,UAAU,EAAE,IAAI,KAAK,GAAG,EAAE,WAAW,EAAE,KAAK,KAAK,GAAG,EAAE,CAAC;AAClE,CAAC"}
|
||||
100
backend/dist/services/supportService.d.ts
vendored
100
backend/dist/services/supportService.d.ts
vendored
@ -6,7 +6,7 @@ export type SupportAccessContext = {
|
||||
visitorToken?: string | null;
|
||||
};
|
||||
export declare function assertConversationAccess(conversationId: string, ctx: SupportAccessContext): Promise<SupportConversationRow>;
|
||||
export declare function getOrCreateConversation(ctx: SupportAccessContext): Promise<{
|
||||
export declare function findCurrentConversation(ctx: SupportAccessContext): Promise<{
|
||||
id: string;
|
||||
userId: string | null;
|
||||
visitorToken: string | null;
|
||||
@ -20,6 +20,46 @@ export declare function getOrCreateConversation(ctx: SupportAccessContext): Prom
|
||||
unreadStaff: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
} | null>;
|
||||
export declare function ensureCurrentConversation(ctx: SupportAccessContext): Promise<{
|
||||
id: string;
|
||||
userId: string | null;
|
||||
visitorToken: string | null;
|
||||
isAnonymous: boolean;
|
||||
subject: string | null;
|
||||
status: import("../models/support.model").SupportConversationStatus;
|
||||
assignedTo: string | null;
|
||||
lastMessageAt: string | null;
|
||||
lastMessagePreview: string | null;
|
||||
unreadUser: number;
|
||||
unreadStaff: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}>;
|
||||
export declare function sendToCurrentConversation(ctx: SupportAccessContext, input: {
|
||||
body?: string;
|
||||
attachmentUrl?: string;
|
||||
attachmentName?: string;
|
||||
attachmentMime?: string;
|
||||
}): Promise<{
|
||||
id: string;
|
||||
conversationId: string;
|
||||
senderType: SupportSenderType;
|
||||
senderUserId: string | null;
|
||||
senderDisplayName: string | null;
|
||||
body: string | null;
|
||||
attachmentUrl: string | null;
|
||||
attachmentName: string | null;
|
||||
attachmentMime: string | null;
|
||||
readAt: string | null;
|
||||
editedAt: string | null;
|
||||
deletedAt: string | null;
|
||||
deleted: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
editAvailableUntil: string | null;
|
||||
deleteAvailableUntil: string | null;
|
||||
}>;
|
||||
export declare function listUserConversations(ctx: SupportAccessContext): Promise<{
|
||||
id: string;
|
||||
@ -48,12 +88,23 @@ export declare function getConversationMessages(conversationId: string, ctx: Sup
|
||||
attachmentName: string | null;
|
||||
attachmentMime: string | null;
|
||||
readAt: string | null;
|
||||
editedAt: string | null;
|
||||
deletedAt: string | null;
|
||||
deleted: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
editAvailableUntil: string | null;
|
||||
deleteAvailableUntil: string | null;
|
||||
}[];
|
||||
typing: {
|
||||
userTyping: boolean;
|
||||
staffTyping: boolean;
|
||||
};
|
||||
policy: {
|
||||
editWindowMinutes: number;
|
||||
deleteWindowMinutes: number;
|
||||
};
|
||||
}>;
|
||||
export declare function sendMessage(conversationId: string, ctx: SupportAccessContext, input: {
|
||||
body?: string;
|
||||
@ -71,7 +122,54 @@ export declare function sendMessage(conversationId: string, ctx: SupportAccessCo
|
||||
attachmentName: string | null;
|
||||
attachmentMime: string | null;
|
||||
readAt: string | null;
|
||||
editedAt: string | null;
|
||||
deletedAt: string | null;
|
||||
deleted: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
editAvailableUntil: string | null;
|
||||
deleteAvailableUntil: string | null;
|
||||
}>;
|
||||
export declare function editMessage(conversationId: string, messageId: string, ctx: SupportAccessContext, body: string): Promise<{
|
||||
id: string;
|
||||
conversationId: string;
|
||||
senderType: SupportSenderType;
|
||||
senderUserId: string | null;
|
||||
senderDisplayName: string | null;
|
||||
body: string | null;
|
||||
attachmentUrl: string | null;
|
||||
attachmentName: string | null;
|
||||
attachmentMime: string | null;
|
||||
readAt: string | null;
|
||||
editedAt: string | null;
|
||||
deletedAt: string | null;
|
||||
deleted: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
editAvailableUntil: string | null;
|
||||
deleteAvailableUntil: string | null;
|
||||
}>;
|
||||
export declare function deleteMessage(conversationId: string, messageId: string, ctx: SupportAccessContext): Promise<{
|
||||
id: string;
|
||||
conversationId: string;
|
||||
senderType: SupportSenderType;
|
||||
senderUserId: string | null;
|
||||
senderDisplayName: string | null;
|
||||
body: string | null;
|
||||
attachmentUrl: string | null;
|
||||
attachmentName: string | null;
|
||||
attachmentMime: string | null;
|
||||
readAt: string | null;
|
||||
editedAt: string | null;
|
||||
deletedAt: string | null;
|
||||
deleted: boolean;
|
||||
createdAt: string;
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
editAvailableUntil: string | null;
|
||||
deleteAvailableUntil: string | null;
|
||||
}>;
|
||||
export declare function setTyping(conversationId: string, ctx: SupportAccessContext, active: boolean): Promise<{
|
||||
ok: boolean;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"supportService.d.ts","sourceRoot":"","sources":["../../src/services/supportService.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,sBAAsB,EAEtB,iBAAiB,EAClB,MAAM,yBAAyB,CAAC;AASjC,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAE7D;AAuDD,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,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AAM,GAAG,IAAI,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;;;;;;;;;;;;;;;;;;;;GAiBA;AAED,wBAAsB,0BAA0B,CAAC,cAAc,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BtE;AAED,wBAAsB,uBAAuB,CAC3C,cAAc,EAAE,MAAM,EACtB,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE;IACL,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;;;;;;;;;;;;;;GAoBF;AAED,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,MAAM,CAAC,CAE3D;AAED,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAI5D;AAED,wBAAgB,eAAe,IAAI,MAAM,CAIxC;AAED,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE9D;AAED,yFAAyF;AACzF,wBAAsB,0BAA0B,CAC9C,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACtC,OAAO,CAAC,MAAM,CAAC,CAajB"}
|
||||
166
backend/dist/services/supportService.js
vendored
166
backend/dist/services/supportService.js
vendored
@ -38,10 +38,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isStaffRole = isStaffRole;
|
||||
exports.assertConversationAccess = assertConversationAccess;
|
||||
exports.getOrCreateConversation = getOrCreateConversation;
|
||||
exports.findCurrentConversation = findCurrentConversation;
|
||||
exports.ensureCurrentConversation = ensureCurrentConversation;
|
||||
exports.sendToCurrentConversation = sendToCurrentConversation;
|
||||
exports.listUserConversations = listUserConversations;
|
||||
exports.getConversationMessages = getConversationMessages;
|
||||
exports.sendMessage = sendMessage;
|
||||
exports.editMessage = editMessage;
|
||||
exports.deleteMessage = deleteMessage;
|
||||
exports.setTyping = setTyping;
|
||||
exports.listAdminConversations = listAdminConversations;
|
||||
exports.getAdminConversationDetail = getAdminConversationDetail;
|
||||
@ -56,6 +60,8 @@ const fs_1 = __importDefault(require("fs"));
|
||||
const crypto_1 = require("../utils/crypto");
|
||||
const repo = __importStar(require("../repositories/supportRepository"));
|
||||
const supportRealtimeService_1 = require("./supportRealtimeService");
|
||||
const settingsRepository = __importStar(require("../repositories/settingsRepository"));
|
||||
const supportMessagePolicy_1 = require("./supportMessagePolicy");
|
||||
const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']);
|
||||
function isStaffRole(role) {
|
||||
return !!role && STAFF_ROLES.has(role);
|
||||
@ -67,24 +73,65 @@ function previewForMessage(body, attachmentName) {
|
||||
return `📎 ${attachmentName}`;
|
||||
return 'Message';
|
||||
}
|
||||
function mapMessage(row, staffNames) {
|
||||
function mapMessage(row, staffNames, actions) {
|
||||
const staffName = row.sender_type === 'staff' && row.sender_user_id
|
||||
? staffNames?.get(row.sender_user_id) ?? null
|
||||
: null;
|
||||
const deleted = !!row.deleted_at;
|
||||
return {
|
||||
id: row.id,
|
||||
conversationId: row.conversation_id,
|
||||
senderType: row.sender_type,
|
||||
senderUserId: row.sender_user_id,
|
||||
senderDisplayName: staffName,
|
||||
body: row.body,
|
||||
attachmentUrl: row.attachment_url,
|
||||
attachmentName: row.attachment_name,
|
||||
attachmentMime: row.attachment_mime,
|
||||
body: deleted ? null : row.body,
|
||||
attachmentUrl: deleted ? null : row.attachment_url,
|
||||
attachmentName: deleted ? null : row.attachment_name,
|
||||
attachmentMime: deleted ? null : row.attachment_mime,
|
||||
readAt: row.read_at?.toISOString() ?? null,
|
||||
editedAt: row.edited_at?.toISOString() ?? null,
|
||||
deletedAt: row.deleted_at?.toISOString() ?? null,
|
||||
deleted,
|
||||
createdAt: row.created_at.toISOString(),
|
||||
canEdit: actions?.canEdit ?? false,
|
||||
canDelete: actions?.canDelete ?? false,
|
||||
editAvailableUntil: actions?.editAvailableUntil ?? null,
|
||||
deleteAvailableUntil: actions?.deleteAvailableUntil ?? null,
|
||||
};
|
||||
}
|
||||
async function loadActionWindows() {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
return {
|
||||
editWindowMinutes: settings.support_message_edit_window_minutes,
|
||||
deleteWindowMinutes: settings.support_message_delete_window_minutes,
|
||||
};
|
||||
}
|
||||
function ownerFlags(row, conv, ctx) {
|
||||
return (0, supportMessagePolicy_1.isSupportMessageOwner)({
|
||||
senderType: row.sender_type,
|
||||
senderUserId: row.sender_user_id,
|
||||
conversationVisitorToken: conv.visitor_token,
|
||||
actorUserId: ctx.userId,
|
||||
actorVisitorToken: ctx.visitorToken,
|
||||
});
|
||||
}
|
||||
function messageActions(row, conv, ctx, windows) {
|
||||
return (0, supportMessagePolicy_1.resolveSupportMessageActions)({
|
||||
createdAt: row.created_at,
|
||||
deleted: !!row.deleted_at,
|
||||
isOwner: ownerFlags(row, conv, ctx),
|
||||
editWindowMinutes: windows.editWindowMinutes,
|
||||
deleteWindowMinutes: windows.deleteWindowMinutes,
|
||||
});
|
||||
}
|
||||
async function refreshConversationPreview(conversationId) {
|
||||
const latest = await repo.findLatestVisibleMessage(conversationId);
|
||||
if (!latest) {
|
||||
await repo.updateConversationPreview(conversationId, '', null);
|
||||
return;
|
||||
}
|
||||
await repo.updateConversationPreview(conversationId, previewForMessage(latest.body, latest.attachment_name), latest.created_at);
|
||||
}
|
||||
function mapConversation(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
@ -127,7 +174,11 @@ async function assertConversationAccess(conversationId, ctx) {
|
||||
}
|
||||
throw new Error('Forbidden');
|
||||
}
|
||||
async function getOrCreateConversation(ctx) {
|
||||
async function findCurrentConversation(ctx) {
|
||||
const conv = await findActiveConversationRow(ctx);
|
||||
return conv ? mapConversation(conv) : null;
|
||||
}
|
||||
async function findActiveConversationRow(ctx) {
|
||||
if (ctx.userId) {
|
||||
let conv = await repo.findActiveConversationForUser(ctx.userId);
|
||||
if (!conv && ctx.visitorToken) {
|
||||
@ -136,19 +187,30 @@ async function getOrCreateConversation(ctx) {
|
||||
conv = await repo.attachVisitorConversationToUser(visitorConv.id, ctx.userId);
|
||||
}
|
||||
}
|
||||
if (!conv) {
|
||||
conv = await repo.createConversation({ userId: ctx.userId });
|
||||
}
|
||||
return mapConversation(conv);
|
||||
return conv;
|
||||
}
|
||||
if (!ctx.visitorToken)
|
||||
return null;
|
||||
return repo.findActiveConversationForVisitor(ctx.visitorToken);
|
||||
}
|
||||
async function ensureConversationRow(ctx) {
|
||||
const existing = await findActiveConversationRow(ctx);
|
||||
if (existing)
|
||||
return existing;
|
||||
if (ctx.userId) {
|
||||
return repo.createConversation({ userId: ctx.userId });
|
||||
}
|
||||
if (!ctx.visitorToken) {
|
||||
throw new Error('Visitor token is required for anonymous support');
|
||||
}
|
||||
let conv = await repo.findActiveConversationForVisitor(ctx.visitorToken);
|
||||
if (!conv) {
|
||||
conv = await repo.createConversation({ visitorToken: ctx.visitorToken });
|
||||
}
|
||||
return mapConversation(conv);
|
||||
return repo.createConversation({ visitorToken: ctx.visitorToken });
|
||||
}
|
||||
async function ensureCurrentConversation(ctx) {
|
||||
return mapConversation(await ensureConversationRow(ctx));
|
||||
}
|
||||
async function sendToCurrentConversation(ctx, input) {
|
||||
const conv = await ensureConversationRow(ctx);
|
||||
return sendMessage(conv.id, ctx, input);
|
||||
}
|
||||
async function listUserConversations(ctx) {
|
||||
if (!ctx.userId) {
|
||||
@ -161,7 +223,7 @@ async function listUserConversations(ctx) {
|
||||
return rows.map(mapConversation);
|
||||
}
|
||||
async function getConversationMessages(conversationId, ctx, after) {
|
||||
await assertConversationAccess(conversationId, ctx);
|
||||
const conv = await assertConversationAccess(conversationId, ctx);
|
||||
const rows = await repo.listMessages(conversationId, after);
|
||||
const staffIds = rows
|
||||
.filter((m) => m.sender_type === 'staff' && m.sender_user_id)
|
||||
@ -180,9 +242,11 @@ async function getConversationMessages(conversationId, ctx, after) {
|
||||
conversationId,
|
||||
});
|
||||
const typing = await (0, supportRealtimeService_1.getTypingIndicators)(conversationId);
|
||||
const windows = await loadActionWindows();
|
||||
return {
|
||||
messages: rows.map((r) => mapMessage(r, staffNames)),
|
||||
messages: rows.map((r) => mapMessage(r, staffNames, messageActions(r, conv, ctx, windows))),
|
||||
typing,
|
||||
policy: windows,
|
||||
};
|
||||
}
|
||||
async function sendMessage(conversationId, ctx, input) {
|
||||
@ -219,13 +283,75 @@ async function sendMessage(conversationId, ctx, input) {
|
||||
if (conv.status === 'resolved' || conv.status === 'closed') {
|
||||
await repo.updateConversation(conversationId, { status: 'open' });
|
||||
}
|
||||
const windows = await loadActionWindows();
|
||||
const mapped = mapMessage(msg, undefined, messageActions(msg, conv, ctx, windows));
|
||||
await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, {
|
||||
type: 'message.new',
|
||||
conversationId,
|
||||
messageId: msg.id,
|
||||
message: mapMessage(msg),
|
||||
message: mapped,
|
||||
});
|
||||
return mapMessage(msg);
|
||||
return mapped;
|
||||
}
|
||||
async function editMessage(conversationId, messageId, ctx, body) {
|
||||
const conv = await assertConversationAccess(conversationId, ctx);
|
||||
const row = await repo.findMessageById(messageId);
|
||||
if (!row || row.conversation_id !== conversationId) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
const windows = await loadActionWindows();
|
||||
(0, supportMessagePolicy_1.assertSupportMessageAction)('edit', {
|
||||
createdAt: row.created_at,
|
||||
deleted: !!row.deleted_at,
|
||||
isOwner: ownerFlags(row, conv, ctx),
|
||||
editWindowMinutes: windows.editWindowMinutes,
|
||||
deleteWindowMinutes: windows.deleteWindowMinutes,
|
||||
});
|
||||
const trimmed = body.trim();
|
||||
if (!trimmed && !row.attachment_url) {
|
||||
throw new Error('Message body or attachment is required');
|
||||
}
|
||||
const updated = await repo.updateMessageBody(messageId, trimmed);
|
||||
if (!updated) {
|
||||
throw new Error('Message already deleted');
|
||||
}
|
||||
await refreshConversationPreview(conversationId);
|
||||
const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows));
|
||||
await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, {
|
||||
type: 'message.updated',
|
||||
conversationId,
|
||||
messageId: updated.id,
|
||||
message: mapped,
|
||||
});
|
||||
return mapped;
|
||||
}
|
||||
async function deleteMessage(conversationId, messageId, ctx) {
|
||||
const conv = await assertConversationAccess(conversationId, ctx);
|
||||
const row = await repo.findMessageById(messageId);
|
||||
if (!row || row.conversation_id !== conversationId) {
|
||||
throw new Error('Message not found');
|
||||
}
|
||||
const windows = await loadActionWindows();
|
||||
(0, supportMessagePolicy_1.assertSupportMessageAction)('delete', {
|
||||
createdAt: row.created_at,
|
||||
deleted: !!row.deleted_at,
|
||||
isOwner: ownerFlags(row, conv, ctx),
|
||||
editWindowMinutes: windows.editWindowMinutes,
|
||||
deleteWindowMinutes: windows.deleteWindowMinutes,
|
||||
});
|
||||
const updated = await repo.softDeleteMessage(messageId);
|
||||
if (!updated) {
|
||||
throw new Error('Message already deleted');
|
||||
}
|
||||
await refreshConversationPreview(conversationId);
|
||||
const mapped = mapMessage(updated, undefined, messageActions(updated, conv, ctx, windows));
|
||||
await (0, supportRealtimeService_1.publishSupportEvent)(conversationId, {
|
||||
type: 'message.deleted',
|
||||
conversationId,
|
||||
messageId: updated.id,
|
||||
message: mapped,
|
||||
});
|
||||
return mapped;
|
||||
}
|
||||
async function setTyping(conversationId, ctx, active) {
|
||||
await assertConversationAccess(conversationId, ctx);
|
||||
|
||||
2
backend/dist/services/supportService.js.map
vendored
2
backend/dist/services/supportService.js.map
vendored
File diff suppressed because one or more lines are too long
33
backend/src/controllers/marketingController.ts
Normal file
33
backend/src/controllers/marketingController.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
import * as marketingService from '../services/marketingService';
|
||||
|
||||
export async function getDailyStats(_req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const stats = await marketingService.getDailyStats();
|
||||
res.json(stats);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Failed to load daily stats';
|
||||
res.status(500).json({ error: msg });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getActivityFeed(_req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const feed = await marketingService.getActivityFeed();
|
||||
res.json(feed);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Failed to load activity feed';
|
||||
res.status(500).json({ error: msg });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getWithdrawalFeed(_req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const feed = await marketingService.getWithdrawalFeed();
|
||||
res.json(feed);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Failed to load withdrawal feed';
|
||||
res.status(500).json({ error: msg });
|
||||
}
|
||||
}
|
||||
105
backend/src/repositories/marketingRepository.ts
Normal file
105
backend/src/repositories/marketingRepository.ts
Normal file
@ -0,0 +1,105 @@
|
||||
import { query } from '../db/connection';
|
||||
|
||||
/** Stake kinds counted in public daily unique players (includes test wallets). */
|
||||
export const MARKETING_STAKE_KINDS = ['main', 'bonus', 'test'] as const;
|
||||
|
||||
/** UTC calendar day bounds for "today". */
|
||||
export function utcDayBounds(now = new Date()): { dayStart: Date; dayEnd: Date; day: string } {
|
||||
const dayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
||||
const dayEnd = new Date(dayStart);
|
||||
dayEnd.setUTCDate(dayEnd.getUTCDate() + 1);
|
||||
const day = dayStart.toISOString().slice(0, 10);
|
||||
return { dayStart, dayEnd, day };
|
||||
}
|
||||
|
||||
export type DailyStatsRow = {
|
||||
unique_players: string;
|
||||
total_participations: string;
|
||||
};
|
||||
|
||||
/** Unique players + total bets for UTC day; includes main/bonus/test; excludes auto bets. */
|
||||
export async function getDailyPlayerStats(dayStart: Date, dayEnd: Date): Promise<DailyStatsRow> {
|
||||
const rows = await query<DailyStatsRow[]>(
|
||||
`SELECT
|
||||
COUNT(DISTINCT user_id)::text AS unique_players,
|
||||
COUNT(*)::text AS total_participations
|
||||
FROM candle_predict_bets
|
||||
WHERE created_at >= $1 AND created_at < $2
|
||||
AND COALESCE(is_auto, FALSE) = FALSE
|
||||
AND stake_account_kind IN ('${MARKETING_STAKE_KINDS.join("','")}')`,
|
||||
[dayStart.toISOString(), dayEnd.toISOString()]
|
||||
);
|
||||
return rows[0] ?? { unique_players: '0', total_participations: '0' };
|
||||
}
|
||||
|
||||
export type RealActivityRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
stake_display: string;
|
||||
status: string;
|
||||
direction: string;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
/** Recent non-auto bets (any status) — used for withdrawals-adjacent activity history. */
|
||||
export async function listRecentRealActivity(limit: number): Promise<RealActivityRow[]> {
|
||||
return query<RealActivityRow[]>(
|
||||
`SELECT id, user_id, stake_display::text AS stake_display, status, direction, created_at
|
||||
FROM candle_predict_bets
|
||||
WHERE COALESCE(is_auto, FALSE) = FALSE
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1`,
|
||||
[limit]
|
||||
);
|
||||
}
|
||||
|
||||
/** Latest open bets per user (pending / in_progress) for Live Activity "Playing". */
|
||||
export async function listRecentPlayingActivity(limit: number): Promise<RealActivityRow[]> {
|
||||
return query<RealActivityRow[]>(
|
||||
`SELECT id, user_id, stake_display, status, direction, created_at FROM (
|
||||
SELECT DISTINCT ON (user_id)
|
||||
id, user_id, stake_display::text AS stake_display, status, direction, created_at
|
||||
FROM candle_predict_bets
|
||||
WHERE COALESCE(is_auto, FALSE) = FALSE
|
||||
AND status IN ('pending', 'in_progress')
|
||||
AND stake_account_kind IN ('${MARKETING_STAKE_KINDS.join("','")}')
|
||||
ORDER BY user_id, created_at DESC
|
||||
) t
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1`,
|
||||
[limit]
|
||||
);
|
||||
}
|
||||
|
||||
/** Distinct players with a non-auto bet in the last [minutes] (all stake kinds). */
|
||||
export async function countRecentDistinctPlayers(minutes: number): Promise<number> {
|
||||
const rows = await query<{ c: string }[]>(
|
||||
`SELECT COUNT(DISTINCT user_id)::text AS c
|
||||
FROM candle_predict_bets
|
||||
WHERE COALESCE(is_auto, FALSE) = FALSE
|
||||
AND stake_account_kind IN ('${MARKETING_STAKE_KINDS.join("','")}')
|
||||
AND created_at >= NOW() - ($1::int * INTERVAL '1 minute')`,
|
||||
[minutes]
|
||||
);
|
||||
return Number(rows[0]?.c) || 0;
|
||||
}
|
||||
|
||||
export type RealWithdrawalRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
amount: string;
|
||||
status: string;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
/** Completed withdrawals only (confirmed payouts). */
|
||||
export async function listRecentRealWithdrawals(limit: number): Promise<RealWithdrawalRow[]> {
|
||||
return query<RealWithdrawalRow[]>(
|
||||
`SELECT id, user_id, amount::text AS amount, status, created_at
|
||||
FROM transactions
|
||||
WHERE type = 'withdrawal' AND status = 'completed'
|
||||
ORDER BY created_at DESC
|
||||
LIMIT $1`,
|
||||
[limit]
|
||||
);
|
||||
}
|
||||
@ -105,6 +105,7 @@ import * as analyticsController from '../controllers/analyticsController';
|
||||
import * as reportsController from '../controllers/reportsController';
|
||||
import * as gameController from '../controllers/gameController';
|
||||
import * as advertisementController from '../controllers/advertisementController';
|
||||
import * as marketingController from '../controllers/marketingController';
|
||||
import * as candlePredictController from '../controllers/candlePredictController';
|
||||
import * as gamePlayController from '../controllers/gamePlayController';
|
||||
import * as securityController from '../controllers/securityController';
|
||||
@ -165,9 +166,12 @@ router.post('/faq/entries/:id/view', faqController.recordView);
|
||||
router.post('/faq/entries/:id/helpful', optionalAuthMiddleware, validateBody(faqHelpfulBodySchema), faqController.recordHelpful);
|
||||
router.get('/faq/files/:filename', faqController.getFaqFile);
|
||||
|
||||
/** Public marketing reads (landing / welcome) — catalogue only, no play/bets. */
|
||||
/** Public marketing reads (landing / welcome) — catalogue + social-proof feeds. */
|
||||
router.get('/games', gameController.listGames);
|
||||
router.get('/advertisements', advertisementController.listAdvertisements);
|
||||
router.get('/marketing/daily-stats', marketingController.getDailyStats);
|
||||
router.get('/marketing/activity-feed', marketingController.getActivityFeed);
|
||||
router.get('/marketing/withdrawal-feed', marketingController.getWithdrawalFeed);
|
||||
|
||||
/** Public Share Card verification (HMAC token). */
|
||||
router.get('/share-cards/verify/:token', shareCardController.verifyShareCard);
|
||||
|
||||
241
backend/src/services/marketingService.ts
Normal file
241
backend/src/services/marketingService.ts
Normal file
@ -0,0 +1,241 @@
|
||||
import * as marketingRepository from '../repositories/marketingRepository';
|
||||
|
||||
const FEED_TARGET = 24;
|
||||
const REAL_FETCH = 16;
|
||||
const CACHE_TTL_MS = 12_000;
|
||||
const ACTIVE_WINDOW_MINUTES = 15;
|
||||
/** Marketing boost so early launch still looks lively. */
|
||||
const ACTIVE_SYNTHETIC_BASE = 180;
|
||||
const ACTIVE_SYNTHETIC_SPREAD = 90;
|
||||
|
||||
type CacheEntry<T> = { at: number; value: T };
|
||||
const cache = new Map<string, CacheEntry<unknown>>();
|
||||
|
||||
function cached<T>(key: string, factory: () => Promise<T>): Promise<T> {
|
||||
const hit = cache.get(key) as CacheEntry<T> | undefined;
|
||||
if (hit && Date.now() - hit.at < CACHE_TTL_MS) return Promise.resolve(hit.value);
|
||||
return factory().then((value) => {
|
||||
cache.set(key, { at: Date.now(), value });
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
/** Mask UUID/user id to short public handle (privacy). */
|
||||
export function maskPublicId(raw: string): string {
|
||||
const cleaned = raw.replace(/[^a-zA-Z0-9]/g, '');
|
||||
if (cleaned.length < 4) return `${cleaned}***`;
|
||||
return `${cleaned.slice(0, 2)}***${cleaned.slice(-2)}`;
|
||||
}
|
||||
|
||||
function formatStakeDisplay(raw: string | number): string {
|
||||
const n = typeof raw === 'number' ? raw : Number(raw);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
if (n >= 1000) return n.toFixed(0);
|
||||
if (n >= 1) return n.toFixed(2);
|
||||
return n.toFixed(4);
|
||||
}
|
||||
|
||||
/** Format wallet raw bigint (6 decimals USDT-like) for display. */
|
||||
export function formatAmountRaw(raw: string | number): string {
|
||||
const n = typeof raw === 'number' ? raw : Number(raw);
|
||||
if (!Number.isFinite(n)) return '0';
|
||||
return formatStakeDisplay(n / 1_000_000);
|
||||
}
|
||||
|
||||
export type MarketingActivityItem = {
|
||||
id: string;
|
||||
publicId: string;
|
||||
kind: 'bet';
|
||||
amountLabel: string;
|
||||
statusLabel: 'Playing';
|
||||
createdAt: string;
|
||||
synthetic: boolean;
|
||||
};
|
||||
|
||||
export type MarketingWithdrawalItem = {
|
||||
id: string;
|
||||
publicId: string;
|
||||
amountLabel: string;
|
||||
statusLabel: string;
|
||||
createdAt: string;
|
||||
synthetic: boolean;
|
||||
};
|
||||
|
||||
export type MarketingDailyStats = {
|
||||
uniquePlayersToday: number;
|
||||
totalParticipationsToday: number;
|
||||
day: string;
|
||||
timezone: 'UTC';
|
||||
};
|
||||
|
||||
export type MarketingActivityFeed = {
|
||||
items: MarketingActivityItem[];
|
||||
activePlayersCount: number;
|
||||
};
|
||||
|
||||
const SYNTHETIC_HANDLES = [
|
||||
'7a***k2',
|
||||
'9c***m1',
|
||||
'3f***p8',
|
||||
'b2***q4',
|
||||
'e8***t6',
|
||||
'1d***w9',
|
||||
'5h***n3',
|
||||
'c4***r7',
|
||||
'8j***v5',
|
||||
'2m***x0',
|
||||
'6p***y1',
|
||||
'0s***z8',
|
||||
'4n***a3',
|
||||
'd7***b5',
|
||||
'f1***c9',
|
||||
'a9***d2',
|
||||
'g3***e4',
|
||||
'h6***f7',
|
||||
'i2***g1',
|
||||
'j8***h6',
|
||||
];
|
||||
|
||||
const SYNTHETIC_WITHDRAWALS = [20, 35, 50, 80, 100, 120, 200, 250, 300, 450, 500, 800];
|
||||
|
||||
/** Faster slot so synthetic pool rotates ~every 10s server-side. */
|
||||
function slotIndex(now = Date.now()): number {
|
||||
return Math.floor(now / 10_000);
|
||||
}
|
||||
|
||||
/** Playing-only synthetic rows (no Won / no stake emphasis). */
|
||||
export function buildSyntheticActivity(count: number, now = Date.now()): MarketingActivityItem[] {
|
||||
const slot = slotIndex(now);
|
||||
const start = (slot * 3) % SYNTHETIC_HANDLES.length;
|
||||
const items: MarketingActivityItem[] = [];
|
||||
const n = Math.min(count, SYNTHETIC_HANDLES.length);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const handle = SYNTHETIC_HANDLES[(start + i) % SYNTHETIC_HANDLES.length];
|
||||
items.push({
|
||||
id: `syn-act-${slot}-${i}`,
|
||||
publicId: handle,
|
||||
kind: 'bet',
|
||||
amountLabel: '0',
|
||||
statusLabel: 'Playing',
|
||||
createdAt: new Date(now - i * 20_000).toISOString(),
|
||||
synthetic: true,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
export function buildSyntheticWithdrawals(count: number, now = Date.now()): MarketingWithdrawalItem[] {
|
||||
const slot = slotIndex(now);
|
||||
const items: MarketingWithdrawalItem[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const idx = (slot + i * 2) % SYNTHETIC_HANDLES.length;
|
||||
const amount = SYNTHETIC_WITHDRAWALS[(slot + i * 5) % SYNTHETIC_WITHDRAWALS.length];
|
||||
items.push({
|
||||
id: `syn-wd-${slot}-${i}`,
|
||||
publicId: SYNTHETIC_HANDLES[idx],
|
||||
amountLabel: String(amount),
|
||||
statusLabel: 'Completed',
|
||||
createdAt: new Date(now - i * 90_000).toISOString(),
|
||||
synthetic: true,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** Merge real first, pad with synthetic; de-dupe by publicId. */
|
||||
export function mergeFeedItems<T extends { id: string; publicId?: string }>(
|
||||
real: T[],
|
||||
synthetic: T[],
|
||||
target: number
|
||||
): T[] {
|
||||
const out: T[] = [];
|
||||
const seen = new Set<string>();
|
||||
const push = (item: T) => {
|
||||
const key = item.publicId ?? item.id;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
out.push(item);
|
||||
};
|
||||
for (const r of real) {
|
||||
if (out.length >= target) break;
|
||||
push(r);
|
||||
}
|
||||
for (const s of synthetic) {
|
||||
if (out.length >= target) break;
|
||||
push(s);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Marketing active count = recent real distinct + lively synthetic boost. */
|
||||
export function computeActivePlayersCount(realRecent: number, now = Date.now()): number {
|
||||
const slot = slotIndex(now);
|
||||
const boost = ACTIVE_SYNTHETIC_BASE + (slot % ACTIVE_SYNTHETIC_SPREAD);
|
||||
return Math.max(realRecent + boost, boost);
|
||||
}
|
||||
|
||||
function mapRealPlaying(row: marketingRepository.RealActivityRow): MarketingActivityItem {
|
||||
return {
|
||||
id: row.id,
|
||||
publicId: maskPublicId(row.user_id),
|
||||
kind: 'bet',
|
||||
amountLabel: '0',
|
||||
statusLabel: 'Playing',
|
||||
createdAt: row.created_at.toISOString(),
|
||||
synthetic: false,
|
||||
};
|
||||
}
|
||||
|
||||
function mapRealWithdrawal(row: marketingRepository.RealWithdrawalRow): MarketingWithdrawalItem {
|
||||
return {
|
||||
id: row.id,
|
||||
publicId: maskPublicId(row.user_id),
|
||||
amountLabel: formatAmountRaw(row.amount),
|
||||
statusLabel: 'Completed',
|
||||
createdAt: row.created_at.toISOString(),
|
||||
synthetic: false,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getDailyStats(): Promise<MarketingDailyStats> {
|
||||
return cached('daily-stats', async () => {
|
||||
const { dayStart, dayEnd, day } = marketingRepository.utcDayBounds();
|
||||
const row = await marketingRepository.getDailyPlayerStats(dayStart, dayEnd);
|
||||
return {
|
||||
uniquePlayersToday: Number(row.unique_players) || 0,
|
||||
totalParticipationsToday: Number(row.total_participations) || 0,
|
||||
day,
|
||||
timezone: 'UTC',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getActivityFeed(): Promise<MarketingActivityFeed> {
|
||||
return cached('activity-feed', async () => {
|
||||
const [rows, realActive] = await Promise.all([
|
||||
marketingRepository.listRecentPlayingActivity(REAL_FETCH),
|
||||
marketingRepository.countRecentDistinctPlayers(ACTIVE_WINDOW_MINUTES),
|
||||
]);
|
||||
const real = rows.map(mapRealPlaying);
|
||||
const synthetic = buildSyntheticActivity(FEED_TARGET);
|
||||
const items = mergeFeedItems(real, synthetic, FEED_TARGET);
|
||||
return {
|
||||
items,
|
||||
activePlayersCount: computeActivePlayersCount(realActive),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getWithdrawalFeed(): Promise<{ items: MarketingWithdrawalItem[] }> {
|
||||
return cached('withdrawal-feed', async () => {
|
||||
const rows = await marketingRepository.listRecentRealWithdrawals(8);
|
||||
const real = rows.map(mapRealWithdrawal);
|
||||
const synthetic = buildSyntheticWithdrawals(12);
|
||||
return { items: mergeFeedItems(real, synthetic, 12) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Test helper: clear in-memory cache. */
|
||||
export function clearMarketingCache(): void {
|
||||
cache.clear();
|
||||
}
|
||||
82
backend/src/tests/marketingService.test.ts
Normal file
82
backend/src/tests/marketingService.test.ts
Normal file
@ -0,0 +1,82 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
MARKETING_STAKE_KINDS,
|
||||
utcDayBounds,
|
||||
} from '../repositories/marketingRepository';
|
||||
import {
|
||||
buildSyntheticActivity,
|
||||
buildSyntheticWithdrawals,
|
||||
computeActivePlayersCount,
|
||||
formatAmountRaw,
|
||||
maskPublicId,
|
||||
mergeFeedItems,
|
||||
} from '../services/marketingService';
|
||||
|
||||
describe('marketingService helpers', () => {
|
||||
test('daily stats include main bonus and test stake kinds', () => {
|
||||
assert.deepEqual([...MARKETING_STAKE_KINDS], ['main', 'bonus', 'test']);
|
||||
});
|
||||
|
||||
test('utcDayBounds uses UTC midnight', () => {
|
||||
const { dayStart, dayEnd, day } = utcDayBounds(new Date('2026-10-17T15:30:00.000Z'));
|
||||
assert.equal(day, '2026-10-17');
|
||||
assert.equal(dayStart.toISOString(), '2026-10-17T00:00:00.000Z');
|
||||
assert.equal(dayEnd.toISOString(), '2026-10-18T00:00:00.000Z');
|
||||
});
|
||||
|
||||
test('maskPublicId anonymizes uuids', () => {
|
||||
const masked = maskPublicId('abcdef12-3456-7890-abcd-ef1234567890');
|
||||
assert.match(masked, /^[a-z0-9]{2}\*\*\*[a-z0-9]{2}$/i);
|
||||
assert.equal(maskPublicId('ab'), 'ab***');
|
||||
});
|
||||
|
||||
test('formatAmountRaw converts micro-units', () => {
|
||||
assert.equal(formatAmountRaw('1000000'), '1.00');
|
||||
assert.equal(formatAmountRaw('50000000'), '50.00');
|
||||
});
|
||||
|
||||
test('mergeFeedItems keeps real first then pads synthetic', () => {
|
||||
const real = [
|
||||
{ id: 'r1', publicId: 'aa***11' },
|
||||
{ id: 'r2', publicId: 'bb***22' },
|
||||
];
|
||||
const synthetic = [
|
||||
{ id: 's1', publicId: 'cc***33' },
|
||||
{ id: 's2', publicId: 'dd***44' },
|
||||
{ id: 's3', publicId: 'ee***55' },
|
||||
];
|
||||
const merged = mergeFeedItems(real, synthetic, 4);
|
||||
assert.deepEqual(
|
||||
merged.map((x) => x.id),
|
||||
['r1', 'r2', 's1', 's2']
|
||||
);
|
||||
});
|
||||
|
||||
test('synthetic activity is Playing-only with unique handles', () => {
|
||||
const items = buildSyntheticActivity(12, 1_700_000_000_000);
|
||||
assert.equal(items.length, 12);
|
||||
assert.ok(items.every((i) => i.synthetic));
|
||||
assert.ok(items.every((i) => i.statusLabel === 'Playing'));
|
||||
assert.ok(items.every((i) => i.kind === 'bet'));
|
||||
assert.equal(new Set(items.map((i) => i.publicId)).size, items.length);
|
||||
});
|
||||
|
||||
test('computeActivePlayersCount merges real + synthetic boost', () => {
|
||||
const count = computeActivePlayersCount(20, 1_700_000_000_000);
|
||||
assert.ok(count > 20);
|
||||
assert.ok(count >= 180);
|
||||
});
|
||||
|
||||
test('synthetic withdrawals pad feed', () => {
|
||||
const items = buildSyntheticWithdrawals(12, 1_700_000_000_000);
|
||||
assert.equal(items.length, 12);
|
||||
assert.ok(items.every((i) => i.statusLabel === 'Completed'));
|
||||
});
|
||||
|
||||
test('merge with empty real still fills from synthetic', () => {
|
||||
const synthetic = buildSyntheticActivity(12, 1_700_000_000_000);
|
||||
const merged = mergeFeedItems([], synthetic, 12);
|
||||
assert.equal(merged.length, 12);
|
||||
});
|
||||
});
|
||||
@ -14,10 +14,12 @@ import '../../domain/repositories/advertisement_repository.dart';
|
||||
import '../../domain/repositories/faq_repository.dart';
|
||||
import '../../domain/repositories/game_catalog_repository.dart';
|
||||
import '../../domain/repositories/health_repository.dart';
|
||||
import '../../domain/repositories/marketing_repository.dart';
|
||||
import '../../domain/repositories/notification_repository.dart';
|
||||
import '../../domain/repositories/prediction_repository.dart';
|
||||
import '../../domain/repositories/referral_repository.dart';
|
||||
import '../../domain/repositories/repositories.dart';
|
||||
import '../../data/repositories/marketing_repository_impl.dart';
|
||||
import '../../features/auth/bloc/auth_bloc.dart';
|
||||
import '../../features/prediction/bloc/prediction_bloc.dart';
|
||||
import '../../features/wallet/bloc/wallet_bloc.dart';
|
||||
@ -25,6 +27,7 @@ import '../../data/repositories/support_repository.dart';
|
||||
import '../../features/support/bloc/support_bloc.dart';
|
||||
import '../config/app_config.dart';
|
||||
import '../network/api_client.dart';
|
||||
import '../network/connectivity_controller.dart';
|
||||
import '../realtime/game_socket_service.dart';
|
||||
import '../realtime/support_socket_service.dart';
|
||||
import '../../l10n/locale_controller.dart';
|
||||
@ -37,6 +40,9 @@ Future<void> configureDependencies({AppConfig? config}) async {
|
||||
if (!sl.isRegistered<AppConfig>()) {
|
||||
sl.registerSingleton<AppConfig>(appConfig);
|
||||
}
|
||||
if (!sl.isRegistered<ConnectivityController>()) {
|
||||
sl.registerSingleton<ConnectivityController>(ConnectivityController());
|
||||
}
|
||||
if (!sl.isRegistered<LocaleController>()) {
|
||||
final localeController = LocaleController();
|
||||
await localeController.load();
|
||||
@ -98,6 +104,11 @@ Future<void> configureDependencies({AppConfig? config}) async {
|
||||
() => GameCatalogRepositoryImpl(sl()),
|
||||
);
|
||||
}
|
||||
if (!sl.isRegistered<MarketingRepository>()) {
|
||||
sl.registerLazySingleton<MarketingRepository>(
|
||||
() => MarketingRepositoryImpl(sl()),
|
||||
);
|
||||
}
|
||||
if (!sl.isRegistered<AuthBloc>()) {
|
||||
sl.registerFactory<AuthBloc>(() => AuthBloc(sl())..add(const AuthCheckRequested()));
|
||||
}
|
||||
|
||||
53
prediqo_mobile/lib/core/network/connectivity_controller.dart
Normal file
53
prediqo_mobile/lib/core/network/connectivity_controller.dart
Normal file
@ -0,0 +1,53 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:connectivity_plus/connectivity_plus.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// App-wide connectivity signal for offline banner + reconnect refresh.
|
||||
class ConnectivityController extends ChangeNotifier {
|
||||
ConnectivityController({Connectivity? connectivity})
|
||||
: _connectivity = connectivity ?? Connectivity() {
|
||||
_init();
|
||||
}
|
||||
|
||||
final Connectivity _connectivity;
|
||||
StreamSubscription<List<ConnectivityResult>>? _sub;
|
||||
bool _online = true;
|
||||
bool _started = false;
|
||||
|
||||
bool get isOnline => _online;
|
||||
bool get isOffline => !_online;
|
||||
|
||||
Future<void> _init() async {
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
try {
|
||||
final current = await _connectivity.checkConnectivity();
|
||||
_apply(current);
|
||||
} catch (_) {
|
||||
_online = true;
|
||||
}
|
||||
_sub = _connectivity.onConnectivityChanged.listen(_apply);
|
||||
}
|
||||
|
||||
void _apply(List<ConnectivityResult> results) {
|
||||
final next = results.any((r) => r != ConnectivityResult.none);
|
||||
if (next == _online) return;
|
||||
_online = next;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Force a one-shot re-check (e.g. after a failed Dio call).
|
||||
Future<void> refresh() async {
|
||||
try {
|
||||
final current = await _connectivity.checkConnectivity();
|
||||
_apply(current);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_sub?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@ -33,11 +33,22 @@ class GameSocketService {
|
||||
int _reconnectAttempt = 0;
|
||||
bool _connecting = false;
|
||||
GameSocketConnectionState _connectionState = GameSocketConnectionState.disconnected;
|
||||
DateTime? _lastActivityAt;
|
||||
|
||||
bool get isConnected => _channel != null;
|
||||
bool get isEnabled => _config.wsEnabled;
|
||||
GameSocketConnectionState get connectionState => _connectionState;
|
||||
|
||||
/// True when the socket looks freshly alive (avoids tearing it down for
|
||||
/// brief overlay lifecycle blips such as opening Support chat).
|
||||
bool get looksRecentlyAlive {
|
||||
if (_channel == null) return false;
|
||||
if (_connectionState != GameSocketConnectionState.connected) return false;
|
||||
final last = _lastActivityAt;
|
||||
if (last == null) return false;
|
||||
return DateTime.now().difference(last) < const Duration(seconds: 25);
|
||||
}
|
||||
|
||||
void addListener(GameSocketListener listener) => _listeners.add(listener);
|
||||
void removeListener(GameSocketListener listener) => _listeners.remove(listener);
|
||||
void addStatusListener(GameSocketStatusListener listener) => _statusListeners.add(listener);
|
||||
@ -72,6 +83,7 @@ class GameSocketService {
|
||||
cancelOnError: true,
|
||||
);
|
||||
_reconnectAttempt = 0;
|
||||
_lastActivityAt = DateTime.now();
|
||||
_setConnectionState(GameSocketConnectionState.connected);
|
||||
_heartbeat?.cancel();
|
||||
_heartbeat = Timer.periodic(const Duration(seconds: 30), (_) {
|
||||
@ -104,6 +116,13 @@ class GameSocketService {
|
||||
if (interval != null && isConnected) subscribe(interval);
|
||||
}
|
||||
|
||||
/// Like [forceReconnect], but skips the teardown when traffic was seen
|
||||
/// recently — used after short overlay lifecycle transitions.
|
||||
Future<void> reconnectAfterBackground() async {
|
||||
if (looksRecentlyAlive) return;
|
||||
await forceReconnect();
|
||||
}
|
||||
|
||||
void subscribe(int intervalMinutes) {
|
||||
_subscribedInterval = intervalMinutes;
|
||||
_send({'type': 'subscribe', 'intervalMinutes': intervalMinutes});
|
||||
@ -116,6 +135,7 @@ class GameSocketService {
|
||||
void _onMessage(dynamic raw) {
|
||||
try {
|
||||
final map = jsonDecode(raw as String) as Map<String, dynamic>;
|
||||
_lastActivityAt = DateTime.now();
|
||||
_armStaleTimer();
|
||||
if (_connectionState != GameSocketConnectionState.connected) {
|
||||
_setConnectionState(GameSocketConnectionState.connected);
|
||||
|
||||
112
prediqo_mobile/lib/data/models/marketing_models.dart
Normal file
112
prediqo_mobile/lib/data/models/marketing_models.dart
Normal file
@ -0,0 +1,112 @@
|
||||
/// Public marketing payloads for Welcome social-proof sections.
|
||||
library;
|
||||
|
||||
class MarketingDailyStats {
|
||||
const MarketingDailyStats({
|
||||
required this.uniquePlayersToday,
|
||||
required this.totalParticipationsToday,
|
||||
required this.day,
|
||||
this.timezone = 'UTC',
|
||||
});
|
||||
|
||||
final int uniquePlayersToday;
|
||||
final int totalParticipationsToday;
|
||||
final String day;
|
||||
final String timezone;
|
||||
|
||||
factory MarketingDailyStats.fromJson(Map<String, dynamic> json) {
|
||||
return MarketingDailyStats(
|
||||
uniquePlayersToday: (json['uniquePlayersToday'] as num?)?.toInt() ?? 0,
|
||||
totalParticipationsToday:
|
||||
(json['totalParticipationsToday'] as num?)?.toInt() ?? 0,
|
||||
day: (json['day'] ?? '').toString(),
|
||||
timezone: (json['timezone'] ?? 'UTC').toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MarketingActivityItem {
|
||||
const MarketingActivityItem({
|
||||
required this.id,
|
||||
required this.publicId,
|
||||
required this.kind,
|
||||
required this.amountLabel,
|
||||
required this.statusLabel,
|
||||
required this.createdAt,
|
||||
required this.synthetic,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String publicId;
|
||||
final String kind;
|
||||
final String amountLabel;
|
||||
final String statusLabel;
|
||||
final String createdAt;
|
||||
final bool synthetic;
|
||||
|
||||
factory MarketingActivityItem.fromJson(Map<String, dynamic> json) {
|
||||
return MarketingActivityItem(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
publicId: (json['publicId'] ?? '').toString(),
|
||||
kind: (json['kind'] ?? 'bet').toString(),
|
||||
amountLabel: (json['amountLabel'] ?? '0').toString(),
|
||||
statusLabel: (json['statusLabel'] ?? 'Playing').toString(),
|
||||
createdAt: (json['createdAt'] ?? '').toString(),
|
||||
synthetic: json['synthetic'] == true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MarketingActivityFeed {
|
||||
const MarketingActivityFeed({
|
||||
required this.items,
|
||||
required this.activePlayersCount,
|
||||
});
|
||||
|
||||
final List<MarketingActivityItem> items;
|
||||
final int activePlayersCount;
|
||||
|
||||
factory MarketingActivityFeed.fromJson(Map<String, dynamic> json) {
|
||||
final list = json['items'];
|
||||
final items = list is List
|
||||
? list
|
||||
.whereType<Map>()
|
||||
.map((e) => MarketingActivityItem.fromJson(Map<String, dynamic>.from(e)))
|
||||
.where((e) => e.statusLabel.toLowerCase() != 'won' && e.kind != 'win')
|
||||
.toList()
|
||||
: <MarketingActivityItem>[];
|
||||
return MarketingActivityFeed(
|
||||
items: items,
|
||||
activePlayersCount: (json['activePlayersCount'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MarketingWithdrawalItem {
|
||||
const MarketingWithdrawalItem({
|
||||
required this.id,
|
||||
required this.publicId,
|
||||
required this.amountLabel,
|
||||
required this.statusLabel,
|
||||
required this.createdAt,
|
||||
required this.synthetic,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String publicId;
|
||||
final String amountLabel;
|
||||
final String statusLabel;
|
||||
final String createdAt;
|
||||
final bool synthetic;
|
||||
|
||||
factory MarketingWithdrawalItem.fromJson(Map<String, dynamic> json) {
|
||||
return MarketingWithdrawalItem(
|
||||
id: (json['id'] ?? '').toString(),
|
||||
publicId: (json['publicId'] ?? '').toString(),
|
||||
amountLabel: (json['amountLabel'] ?? '0').toString(),
|
||||
statusLabel: (json['statusLabel'] ?? '').toString(),
|
||||
createdAt: (json['createdAt'] ?? '').toString(),
|
||||
synthetic: json['synthetic'] == true,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -54,8 +54,51 @@ class SupportMessageModel {
|
||||
this.canDelete = false,
|
||||
this.editAvailableUntil,
|
||||
this.deleteAvailableUntil,
|
||||
this.isPending = false,
|
||||
});
|
||||
|
||||
/// Optimistic local bubble waiting for network flush.
|
||||
factory SupportMessageModel.pendingLocal({
|
||||
required String localId,
|
||||
required String body,
|
||||
String conversationId = '',
|
||||
}) {
|
||||
return SupportMessageModel(
|
||||
id: localId,
|
||||
conversationId: conversationId,
|
||||
senderType: 'user',
|
||||
createdAt: DateTime.now().toUtc().toIso8601String(),
|
||||
body: body,
|
||||
isPending: true,
|
||||
);
|
||||
}
|
||||
|
||||
/// Optimistic local image bubble; [filePath] is a device path until flush.
|
||||
factory SupportMessageModel.pendingLocalImage({
|
||||
required String localId,
|
||||
required String filePath,
|
||||
String conversationId = '',
|
||||
}) {
|
||||
final name = filePath.replaceAll('\\', '/').split('/').last;
|
||||
final ext = name.contains('.') ? name.split('.').last.toLowerCase() : 'jpg';
|
||||
final mime = switch (ext) {
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
'webp' => 'image/webp',
|
||||
_ => 'image/jpeg',
|
||||
};
|
||||
return SupportMessageModel(
|
||||
id: localId,
|
||||
conversationId: conversationId,
|
||||
senderType: 'user',
|
||||
createdAt: DateTime.now().toUtc().toIso8601String(),
|
||||
attachmentUrl: filePath,
|
||||
attachmentName: name,
|
||||
attachmentMime: mime,
|
||||
isPending: true,
|
||||
);
|
||||
}
|
||||
|
||||
final String id;
|
||||
final String conversationId;
|
||||
final String senderType;
|
||||
@ -72,6 +115,8 @@ class SupportMessageModel {
|
||||
final bool canDelete;
|
||||
final String? editAvailableUntil;
|
||||
final String? deleteAvailableUntil;
|
||||
/// True for client-queued messages not yet acknowledged by the API.
|
||||
final bool isPending;
|
||||
|
||||
bool get isDeleted {
|
||||
if (deletedAt != null && deletedAt!.isNotEmpty) return true;
|
||||
@ -136,6 +181,7 @@ class SupportMessageModel {
|
||||
bool? canDelete,
|
||||
String? editAvailableUntil,
|
||||
String? deleteAvailableUntil,
|
||||
bool? isPending,
|
||||
bool clearAttachment = false,
|
||||
}) {
|
||||
return SupportMessageModel(
|
||||
@ -155,6 +201,7 @@ class SupportMessageModel {
|
||||
canDelete: canDelete ?? this.canDelete,
|
||||
editAvailableUntil: editAvailableUntil ?? this.editAvailableUntil,
|
||||
deleteAvailableUntil: deleteAvailableUntil ?? this.deleteAvailableUntil,
|
||||
isPending: isPending ?? this.isPending,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -3,10 +3,104 @@ import '../../core/errors/app_exception.dart';
|
||||
import '../../core/network/api_client.dart';
|
||||
import '../../domain/repositories/repositories.dart';
|
||||
|
||||
/// Short TTL + in-flight coalesce for `/me` profile reads.
|
||||
class AuthProfileStore {
|
||||
static const ttl = Duration(seconds: 30);
|
||||
|
||||
UserProfile? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<UserProfile>? _inFlight;
|
||||
int fetchStarts = 0;
|
||||
|
||||
UserProfile? peekLast() => _cached;
|
||||
|
||||
UserProfile? peekFresh() {
|
||||
if (_cached == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
}
|
||||
|
||||
Future<UserProfile> get(
|
||||
Future<UserProfile> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
}
|
||||
fetchStarts++;
|
||||
final future = fetch().then((value) {
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) _inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Long TTL for the static countries catalog.
|
||||
class AuthCountriesStore {
|
||||
static const ttl = Duration(minutes: 30);
|
||||
|
||||
List<CountryOption>? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<List<CountryOption>>? _inFlight;
|
||||
int fetchStarts = 0;
|
||||
|
||||
List<CountryOption>? peekLast() => _cached;
|
||||
|
||||
List<CountryOption>? peekFresh() {
|
||||
if (_cached == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
}
|
||||
|
||||
Future<List<CountryOption>> get(
|
||||
Future<List<CountryOption>> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
}
|
||||
fetchStarts++;
|
||||
final future = fetch().then((value) {
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) _inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AuthRepositoryImpl implements AuthRepository {
|
||||
AuthRepositoryImpl(this._api);
|
||||
|
||||
final ApiClient _api;
|
||||
final AuthProfileStore profileStore = AuthProfileStore();
|
||||
final AuthCountriesStore countriesStore = AuthCountriesStore();
|
||||
|
||||
@override
|
||||
Future<LoginResult> login(
|
||||
@ -80,22 +174,30 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<CountryOption>> getCountries() async {
|
||||
try {
|
||||
final res = await _api.dio.get<List<dynamic>>('/api/v1/countries');
|
||||
final raw = res.data ?? const [];
|
||||
return raw
|
||||
.whereType<Map>()
|
||||
.map((e) => CountryOption(
|
||||
code: (e['code'] ?? '').toString().toUpperCase(),
|
||||
name: (e['name'] ?? e['code'] ?? '').toString(),
|
||||
))
|
||||
.where((c) => c.code.length == 2)
|
||||
.toList()
|
||||
..sort((a, b) => a.name.compareTo(b.name));
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to load countries');
|
||||
}
|
||||
List<CountryOption>? peekLastCountries() => countriesStore.peekLast();
|
||||
|
||||
@override
|
||||
void invalidateCountries() => countriesStore.invalidate();
|
||||
|
||||
@override
|
||||
Future<List<CountryOption>> getCountries({bool force = false}) {
|
||||
return countriesStore.get(() async {
|
||||
try {
|
||||
final res = await _api.dio.get<List<dynamic>>('/api/v1/countries');
|
||||
final raw = res.data ?? const [];
|
||||
return raw
|
||||
.whereType<Map>()
|
||||
.map((e) => CountryOption(
|
||||
code: (e['code'] ?? '').toString().toUpperCase(),
|
||||
name: (e['name'] ?? e['code'] ?? '').toString(),
|
||||
))
|
||||
.where((c) => c.code.length == 2)
|
||||
.toList()
|
||||
..sort((a, b) => a.name.compareTo(b.name));
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to load countries');
|
||||
}
|
||||
}, force: force);
|
||||
}
|
||||
|
||||
@override
|
||||
@ -137,6 +239,7 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
} catch (_) {}
|
||||
}
|
||||
await _api.clearTokens();
|
||||
profileStore.invalidate();
|
||||
}
|
||||
|
||||
@override
|
||||
@ -173,6 +276,7 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
'/api/v1/2fa/enable',
|
||||
data: {'code': code},
|
||||
);
|
||||
profileStore.invalidate();
|
||||
final codes = res.data?['recoveryCodes'];
|
||||
if (codes is List) {
|
||||
return codes.map((e) => e.toString()).where((e) => e.isNotEmpty).toList();
|
||||
@ -190,6 +294,7 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
'password': password,
|
||||
'code': code,
|
||||
});
|
||||
profileStore.invalidate();
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to disable 2FA');
|
||||
}
|
||||
@ -213,25 +318,33 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<UserProfile> getProfile() async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>('/api/v1/me');
|
||||
final data = res.data ?? {};
|
||||
return UserProfile(
|
||||
firstName: data['firstName'] as String?,
|
||||
middleName: data['middleName'] as String?,
|
||||
lastName: data['lastName'] as String?,
|
||||
dateOfBirth: data['dateOfBirth'] as String?,
|
||||
email: data['email'] as String?,
|
||||
phone: data['phone'] as String?,
|
||||
countryOfResidence: (data['countryOfResidence'] as String?)?.toUpperCase(),
|
||||
nationality: (data['nationality'] as String?)?.toUpperCase(),
|
||||
gender: data['gender'] as String?,
|
||||
totpEnabled: data['totpEnabled'] == true,
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to load profile');
|
||||
}
|
||||
UserProfile? peekLastProfile() => profileStore.peekLast();
|
||||
|
||||
@override
|
||||
void invalidateProfile() => profileStore.invalidate();
|
||||
|
||||
@override
|
||||
Future<UserProfile> getProfile({bool force = false}) {
|
||||
return profileStore.get(() async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>('/api/v1/me');
|
||||
final data = res.data ?? {};
|
||||
return UserProfile(
|
||||
firstName: data['firstName'] as String?,
|
||||
middleName: data['middleName'] as String?,
|
||||
lastName: data['lastName'] as String?,
|
||||
dateOfBirth: data['dateOfBirth'] as String?,
|
||||
email: data['email'] as String?,
|
||||
phone: data['phone'] as String?,
|
||||
countryOfResidence: (data['countryOfResidence'] as String?)?.toUpperCase(),
|
||||
nationality: (data['nationality'] as String?)?.toUpperCase(),
|
||||
gender: data['gender'] as String?,
|
||||
totpEnabled: data['totpEnabled'] == true,
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to load profile');
|
||||
}
|
||||
}, force: force);
|
||||
}
|
||||
|
||||
@override
|
||||
@ -263,6 +376,7 @@ class AuthRepositoryImpl implements AuthRepository {
|
||||
'gender': gender,
|
||||
},
|
||||
);
|
||||
profileStore.invalidate();
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Profile update failed');
|
||||
}
|
||||
|
||||
@ -4,25 +4,102 @@ import '../../core/network/api_client.dart';
|
||||
import '../../data/models/faq_models.dart';
|
||||
import '../../domain/repositories/faq_repository.dart';
|
||||
|
||||
/// TTL cache keyed by category/search for FAQ browse + search.
|
||||
class FaqListStore {
|
||||
static const ttl = Duration(minutes: 2);
|
||||
|
||||
final Map<String, List<FaqEntryModel>> _cached = {};
|
||||
final Map<String, DateTime> _cachedAt = {};
|
||||
Future<List<FaqEntryModel>>? _inFlight;
|
||||
String? _inFlightKey;
|
||||
int fetchStarts = 0;
|
||||
|
||||
String keyFor({String? search, String? category}) =>
|
||||
'${category ?? ''}|${search ?? ''}';
|
||||
|
||||
List<FaqEntryModel>? peekLast({String? search, String? category}) =>
|
||||
_cached[keyFor(search: search, category: category)];
|
||||
|
||||
void invalidate() {
|
||||
_cached.clear();
|
||||
_cachedAt.clear();
|
||||
}
|
||||
|
||||
Future<List<FaqEntryModel>> get(
|
||||
Future<List<FaqEntryModel>> Function() fetch, {
|
||||
required String key,
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final cached = _cached[key];
|
||||
final at = _cachedAt[key];
|
||||
if (cached != null &&
|
||||
at != null &&
|
||||
DateTime.now().difference(at) < ttl) {
|
||||
return cached;
|
||||
}
|
||||
if (_inFlight != null && _inFlightKey == key) return _inFlight!;
|
||||
} else if (_inFlight != null && _inFlightKey == key) {
|
||||
return _inFlight!;
|
||||
}
|
||||
fetchStarts++;
|
||||
final future = fetch().then((value) {
|
||||
_cached[key] = value;
|
||||
_cachedAt[key] = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
_inFlightKey = key;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) {
|
||||
_inFlight = null;
|
||||
_inFlightKey = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class FaqRepositoryImpl implements FaqRepository {
|
||||
FaqRepositoryImpl(this._api);
|
||||
final ApiClient _api;
|
||||
|
||||
final FaqListStore store = FaqListStore();
|
||||
|
||||
@override
|
||||
Future<List<FaqEntryModel>> listEntries({String? search, String? category}) async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/faq/entries',
|
||||
queryParameters: {
|
||||
if (search != null && search.isNotEmpty) 'search': search,
|
||||
if (category != null && category.isNotEmpty) 'category': category,
|
||||
},
|
||||
);
|
||||
return (res.data?['items'] as List<dynamic>? ?? [])
|
||||
.map((e) => FaqEntryModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to load FAQ');
|
||||
}
|
||||
List<FaqEntryModel>? peekLast({String? search, String? category}) =>
|
||||
store.peekLast(search: search, category: category);
|
||||
|
||||
@override
|
||||
void invalidate() => store.invalidate();
|
||||
|
||||
@override
|
||||
Future<List<FaqEntryModel>> listEntries({
|
||||
String? search,
|
||||
String? category,
|
||||
bool force = false,
|
||||
}) {
|
||||
final key = store.keyFor(search: search, category: category);
|
||||
return store.get(
|
||||
() async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/faq/entries',
|
||||
queryParameters: {
|
||||
if (search != null && search.isNotEmpty) 'search': search,
|
||||
if (category != null && category.isNotEmpty) 'category': category,
|
||||
},
|
||||
);
|
||||
return (res.data?['items'] as List<dynamic>? ?? [])
|
||||
.map((e) => FaqEntryModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to load FAQ');
|
||||
}
|
||||
},
|
||||
key: key,
|
||||
force: force,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,125 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../core/network/api_client.dart';
|
||||
import '../../data/models/marketing_models.dart';
|
||||
import '../../domain/repositories/marketing_repository.dart';
|
||||
import '../../features/welcome/utils/marketing_fallback.dart';
|
||||
|
||||
class _Store<T> {
|
||||
static const ttl = Duration(seconds: 25);
|
||||
|
||||
T? cached;
|
||||
DateTime? cachedAt;
|
||||
Future<T>? inFlight;
|
||||
|
||||
T? peekLast() => cached;
|
||||
|
||||
T? peekFresh() {
|
||||
if (cached == null || cachedAt == null) return null;
|
||||
if (DateTime.now().difference(cachedAt!) >= ttl) return null;
|
||||
return cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
cached = null;
|
||||
cachedAt = null;
|
||||
}
|
||||
|
||||
Future<T> get(Future<T> Function() fetch, {bool force = false}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (inFlight != null) return inFlight!;
|
||||
}
|
||||
final future = fetch().then((value) {
|
||||
cached = value;
|
||||
cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(inFlight, future)) inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Public marketing reads. On failure, returns local synthetic content.
|
||||
class MarketingRepositoryImpl implements MarketingRepository {
|
||||
MarketingRepositoryImpl(this._api);
|
||||
|
||||
final ApiClient _api;
|
||||
final _stats = _Store<MarketingDailyStats>();
|
||||
final _activity = _Store<MarketingActivityFeed>();
|
||||
final _withdrawals = _Store<List<MarketingWithdrawalItem>>();
|
||||
|
||||
@override
|
||||
MarketingDailyStats? peekLastDailyStats() => _stats.peekLast();
|
||||
|
||||
@override
|
||||
MarketingActivityFeed? peekLastActivityFeed() => _activity.peekLast();
|
||||
|
||||
@override
|
||||
List<MarketingWithdrawalItem>? peekLastWithdrawals() => _withdrawals.peekLast();
|
||||
|
||||
@override
|
||||
void invalidate() {
|
||||
_stats.invalidate();
|
||||
_activity.invalidate();
|
||||
_withdrawals.invalidate();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MarketingDailyStats> getDailyStats({bool force = false}) {
|
||||
return _stats.get(_fetchDailyStats, force: force);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MarketingActivityFeed> getActivityFeed({bool force = false}) {
|
||||
return _activity.get(_fetchActivity, force: force);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<MarketingWithdrawalItem>> getWithdrawalFeed({bool force = false}) {
|
||||
return _withdrawals.get(_fetchWithdrawals, force: force);
|
||||
}
|
||||
|
||||
Future<MarketingDailyStats> _fetchDailyStats() async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>('/api/v1/marketing/daily-stats');
|
||||
return MarketingDailyStats.fromJson(res.data ?? {});
|
||||
} catch (_) {
|
||||
return marketingFallbackStats();
|
||||
}
|
||||
}
|
||||
|
||||
Future<MarketingActivityFeed> _fetchActivity() async {
|
||||
try {
|
||||
final res = await _api.dio.get('/api/v1/marketing/activity-feed');
|
||||
final data = res.data;
|
||||
if (data is! Map) return marketingFallbackActivityFeed();
|
||||
final feed = MarketingActivityFeed.fromJson(Map<String, dynamic>.from(data));
|
||||
if (feed.items.isEmpty) return marketingFallbackActivityFeed();
|
||||
return feed;
|
||||
} on DioException {
|
||||
return marketingFallbackActivityFeed();
|
||||
} catch (_) {
|
||||
return marketingFallbackActivityFeed();
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<MarketingWithdrawalItem>> _fetchWithdrawals() async {
|
||||
try {
|
||||
final res = await _api.dio.get('/api/v1/marketing/withdrawal-feed');
|
||||
final data = res.data;
|
||||
final list = data is Map ? data['items'] : null;
|
||||
if (list is! List || list.isEmpty) return marketingFallbackWithdrawals();
|
||||
return list
|
||||
.whereType<Map>()
|
||||
.map((e) => MarketingWithdrawalItem.fromJson(Map<String, dynamic>.from(e)))
|
||||
.toList();
|
||||
} catch (_) {
|
||||
return marketingFallbackWithdrawals();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -4,15 +4,92 @@ import '../../core/network/api_client.dart';
|
||||
import '../../data/models/notification_models.dart';
|
||||
import '../../domain/repositories/notification_repository.dart';
|
||||
|
||||
/// Short TTL + in-flight coalesce for the notifications inbox first page.
|
||||
class NotificationListStore {
|
||||
static const ttl = Duration(seconds: 30);
|
||||
|
||||
/// Only cache first-page fetches at this size or larger (Home uses limit:1).
|
||||
static const minCacheableLimit = 10;
|
||||
|
||||
SecurityNotificationsPage? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<SecurityNotificationsPage>? _inFlight;
|
||||
int fetchStarts = 0;
|
||||
|
||||
SecurityNotificationsPage? peekLast() => _cached;
|
||||
|
||||
SecurityNotificationsPage? peekFresh() {
|
||||
if (_cached == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
}
|
||||
|
||||
Future<SecurityNotificationsPage> get(
|
||||
Future<SecurityNotificationsPage> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
}
|
||||
fetchStarts++;
|
||||
final future = fetch().then((value) {
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) _inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class NotificationRepositoryImpl implements NotificationRepository {
|
||||
NotificationRepositoryImpl(this._api);
|
||||
final ApiClient _api;
|
||||
|
||||
final NotificationListStore store = NotificationListStore();
|
||||
|
||||
@override
|
||||
SecurityNotificationsPage? peekLast() => store.peekLast();
|
||||
|
||||
@override
|
||||
SecurityNotificationsPage? peekFresh() => store.peekFresh();
|
||||
|
||||
@override
|
||||
void invalidate() => store.invalidate();
|
||||
|
||||
@override
|
||||
Future<SecurityNotificationsPage> list({
|
||||
int limit = 30,
|
||||
int offset = 0,
|
||||
bool unreadOnly = false,
|
||||
bool force = false,
|
||||
}) async {
|
||||
final cacheable =
|
||||
offset == 0 && !unreadOnly && limit >= NotificationListStore.minCacheableLimit;
|
||||
if (cacheable) {
|
||||
return store.get(
|
||||
() => _fetch(limit: limit, offset: offset, unreadOnly: unreadOnly),
|
||||
force: force,
|
||||
);
|
||||
}
|
||||
return _fetch(limit: limit, offset: offset, unreadOnly: unreadOnly);
|
||||
}
|
||||
|
||||
Future<SecurityNotificationsPage> _fetch({
|
||||
required int limit,
|
||||
required int offset,
|
||||
required bool unreadOnly,
|
||||
}) async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
@ -33,6 +110,7 @@ class NotificationRepositoryImpl implements NotificationRepository {
|
||||
Future<void> markRead(String notificationId) async {
|
||||
try {
|
||||
await _api.dio.patch('/api/v1/me/security-notifications/$notificationId/read');
|
||||
invalidate();
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to mark notification as read');
|
||||
}
|
||||
@ -42,6 +120,7 @@ class NotificationRepositoryImpl implements NotificationRepository {
|
||||
Future<void> markAllRead() async {
|
||||
try {
|
||||
await _api.dio.patch('/api/v1/me/security-notifications/read-all');
|
||||
invalidate();
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Failed to mark all as read');
|
||||
}
|
||||
|
||||
@ -4,16 +4,153 @@ import '../../core/network/api_client.dart';
|
||||
import '../../data/models/referral_models.dart';
|
||||
import '../../domain/repositories/referral_repository.dart';
|
||||
|
||||
/// Short TTL + in-flight coalesce for referral dashboard, keyed by maxDepth.
|
||||
class ReferralDashboardStore {
|
||||
static const ttl = Duration(seconds: 45);
|
||||
|
||||
final Map<int, ReferralDashboardModel> _cached = {};
|
||||
final Map<int, DateTime> _cachedAt = {};
|
||||
final Map<int, Future<ReferralDashboardModel>> _inFlight = {};
|
||||
int fetchStarts = 0;
|
||||
|
||||
ReferralDashboardModel? peekLast(int maxDepth) => _cached[maxDepth];
|
||||
|
||||
ReferralDashboardModel? peekFresh(int maxDepth) {
|
||||
final page = _cached[maxDepth];
|
||||
final at = _cachedAt[maxDepth];
|
||||
if (page == null || at == null) return null;
|
||||
if (DateTime.now().difference(at) >= ttl) return null;
|
||||
return page;
|
||||
}
|
||||
|
||||
void invalidate([int? maxDepth]) {
|
||||
if (maxDepth == null) {
|
||||
_cached.clear();
|
||||
_cachedAt.clear();
|
||||
} else {
|
||||
_cached.remove(maxDepth);
|
||||
_cachedAt.remove(maxDepth);
|
||||
}
|
||||
}
|
||||
|
||||
Future<ReferralDashboardModel> get(
|
||||
int maxDepth,
|
||||
Future<ReferralDashboardModel> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh(maxDepth);
|
||||
if (hit != null) return hit;
|
||||
final pending = _inFlight[maxDepth];
|
||||
if (pending != null) return pending;
|
||||
}
|
||||
fetchStarts++;
|
||||
final future = fetch().then((value) {
|
||||
_cached[maxDepth] = value;
|
||||
_cachedAt[maxDepth] = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight[maxDepth] = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight[maxDepth], future)) {
|
||||
_inFlight.remove(maxDepth);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Short TTL for commissions first page (offset 0).
|
||||
class ReferralCommissionsStore {
|
||||
static const ttl = Duration(seconds: 45);
|
||||
static const minCacheableLimit = 10;
|
||||
|
||||
ReferralCommissionsPage? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<ReferralCommissionsPage>? _inFlight;
|
||||
int fetchStarts = 0;
|
||||
|
||||
ReferralCommissionsPage? peekLast() => _cached;
|
||||
|
||||
ReferralCommissionsPage? peekFresh() {
|
||||
if (_cached == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
}
|
||||
|
||||
Future<ReferralCommissionsPage> get(
|
||||
Future<ReferralCommissionsPage> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
}
|
||||
fetchStarts++;
|
||||
final future = fetch().then((value) {
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) _inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ReferralRepositoryImpl implements ReferralRepository {
|
||||
ReferralRepositoryImpl(this._api);
|
||||
final ApiClient _api;
|
||||
|
||||
final ReferralDashboardStore dashboardStore = ReferralDashboardStore();
|
||||
final ReferralCommissionsStore commissionsStore = ReferralCommissionsStore();
|
||||
|
||||
@override
|
||||
Future<ReferralDashboardModel> getDashboard({int maxDepth = 10}) async {
|
||||
ReferralDashboardModel? peekLastDashboard({int maxDepth = 1}) =>
|
||||
dashboardStore.peekLast(maxDepth.clamp(1, 10));
|
||||
|
||||
@override
|
||||
ReferralDashboardModel? peekFreshDashboard({int maxDepth = 1}) =>
|
||||
dashboardStore.peekFresh(maxDepth.clamp(1, 10));
|
||||
|
||||
@override
|
||||
ReferralCommissionsPage? peekLastCommissions() => commissionsStore.peekLast();
|
||||
|
||||
@override
|
||||
void invalidateDashboard({int? maxDepth}) =>
|
||||
dashboardStore.invalidate(maxDepth?.clamp(1, 10));
|
||||
|
||||
@override
|
||||
void invalidateCommissions() => commissionsStore.invalidate();
|
||||
|
||||
@override
|
||||
Future<ReferralDashboardModel> getDashboard({
|
||||
int maxDepth = 10,
|
||||
bool force = false,
|
||||
}) {
|
||||
final depth = maxDepth.clamp(1, 10);
|
||||
return dashboardStore.get(
|
||||
depth,
|
||||
() => _fetchDashboard(depth),
|
||||
force: force,
|
||||
);
|
||||
}
|
||||
|
||||
Future<ReferralDashboardModel> _fetchDashboard(int maxDepth) async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/referral/dashboard',
|
||||
queryParameters: {'maxDepth': maxDepth.clamp(1, 10)},
|
||||
queryParameters: {'maxDepth': maxDepth},
|
||||
);
|
||||
return ReferralDashboardModel.fromJson(res.data ?? {});
|
||||
} on DioException catch (e) {
|
||||
@ -22,7 +159,26 @@ class ReferralRepositoryImpl implements ReferralRepository {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ReferralCommissionsPage> getCommissions({int limit = 25, int offset = 0}) async {
|
||||
Future<ReferralCommissionsPage> getCommissions({
|
||||
int limit = 25,
|
||||
int offset = 0,
|
||||
bool force = false,
|
||||
}) async {
|
||||
final cacheable =
|
||||
offset == 0 && limit >= ReferralCommissionsStore.minCacheableLimit;
|
||||
if (cacheable) {
|
||||
return commissionsStore.get(
|
||||
() => _fetchCommissions(limit: limit, offset: offset),
|
||||
force: force,
|
||||
);
|
||||
}
|
||||
return _fetchCommissions(limit: limit, offset: offset);
|
||||
}
|
||||
|
||||
Future<ReferralCommissionsPage> _fetchCommissions({
|
||||
required int limit,
|
||||
required int offset,
|
||||
}) async {
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/referral/commissions',
|
||||
@ -52,7 +208,10 @@ class ReferralRepositoryImpl implements ReferralRepository {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> transferBonusToMain({required int walletTypeId, required String amountRaw}) async {
|
||||
Future<void> transferBonusToMain({
|
||||
required int walletTypeId,
|
||||
required String amountRaw,
|
||||
}) async {
|
||||
try {
|
||||
await _api.dio.post('/api/v1/bonus/transfer-to-main', data: {
|
||||
'walletTypeId': walletTypeId,
|
||||
|
||||
@ -1,5 +1,13 @@
|
||||
import '../../data/models/faq_models.dart';
|
||||
|
||||
abstract class FaqRepository {
|
||||
Future<List<FaqEntryModel>> listEntries({String? search, String? category});
|
||||
Future<List<FaqEntryModel>> listEntries({
|
||||
String? search,
|
||||
String? category,
|
||||
bool force = false,
|
||||
});
|
||||
|
||||
List<FaqEntryModel>? peekLast({String? search, String? category});
|
||||
|
||||
void invalidate();
|
||||
}
|
||||
|
||||
@ -0,0 +1,14 @@
|
||||
import '../../data/models/marketing_models.dart';
|
||||
|
||||
/// Public marketing reads for Welcome (stats + social-proof feeds).
|
||||
abstract class MarketingRepository {
|
||||
MarketingDailyStats? peekLastDailyStats();
|
||||
MarketingActivityFeed? peekLastActivityFeed();
|
||||
List<MarketingWithdrawalItem>? peekLastWithdrawals();
|
||||
|
||||
void invalidate();
|
||||
|
||||
Future<MarketingDailyStats> getDailyStats({bool force = false});
|
||||
Future<MarketingActivityFeed> getActivityFeed({bool force = false});
|
||||
Future<List<MarketingWithdrawalItem>> getWithdrawalFeed({bool force = false});
|
||||
}
|
||||
@ -1,10 +1,19 @@
|
||||
import '../../data/models/notification_models.dart';
|
||||
|
||||
abstract class NotificationRepository {
|
||||
/// Last first-page snapshot (may be stale) for immediate paint.
|
||||
SecurityNotificationsPage? peekLast();
|
||||
|
||||
/// Fresh first-page cache within TTL, else null.
|
||||
SecurityNotificationsPage? peekFresh();
|
||||
|
||||
void invalidate();
|
||||
|
||||
Future<SecurityNotificationsPage> list({
|
||||
int limit = 30,
|
||||
int offset = 0,
|
||||
bool unreadOnly = false,
|
||||
bool force = false,
|
||||
});
|
||||
|
||||
Future<void> markRead(String notificationId);
|
||||
|
||||
@ -1,8 +1,34 @@
|
||||
import '../../data/models/referral_models.dart';
|
||||
|
||||
abstract class ReferralRepository {
|
||||
Future<ReferralDashboardModel> getDashboard({int maxDepth = 10});
|
||||
Future<ReferralCommissionsPage> getCommissions({int limit = 25, int offset = 0});
|
||||
/// Last dashboard snapshot for [maxDepth] (may be stale) — immediate paint.
|
||||
ReferralDashboardModel? peekLastDashboard({int maxDepth = 1});
|
||||
|
||||
/// Fresh dashboard within TTL for [maxDepth], else null.
|
||||
ReferralDashboardModel? peekFreshDashboard({int maxDepth = 1});
|
||||
|
||||
/// Last commissions first page (may be stale).
|
||||
ReferralCommissionsPage? peekLastCommissions();
|
||||
|
||||
void invalidateDashboard({int? maxDepth});
|
||||
|
||||
void invalidateCommissions();
|
||||
|
||||
Future<ReferralDashboardModel> getDashboard({
|
||||
int maxDepth = 10,
|
||||
bool force = false,
|
||||
});
|
||||
|
||||
Future<ReferralCommissionsPage> getCommissions({
|
||||
int limit = 25,
|
||||
int offset = 0,
|
||||
bool force = false,
|
||||
});
|
||||
|
||||
Future<({List<BonusBalanceModel> balances, bool bonusWithdrawable})> getBonusBalances();
|
||||
Future<void> transferBonusToMain({required int walletTypeId, required String amountRaw});
|
||||
|
||||
Future<void> transferBonusToMain({
|
||||
required int walletTypeId,
|
||||
required String amountRaw,
|
||||
});
|
||||
}
|
||||
|
||||
@ -50,7 +50,9 @@ abstract class AuthRepository {
|
||||
String? captchaToken,
|
||||
});
|
||||
Future<RegisterResult> register(RegisterRequest request);
|
||||
Future<List<CountryOption>> getCountries();
|
||||
Future<List<CountryOption>> getCountries({bool force = false});
|
||||
List<CountryOption>? peekLastCountries();
|
||||
void invalidateCountries();
|
||||
Future<({bool valid, String? reason})> validateReferralCode(String code);
|
||||
Future<void> resendVerificationEmail(String email);
|
||||
Future<void> logout();
|
||||
@ -62,7 +64,9 @@ abstract class AuthRepository {
|
||||
Future<void> disable2FA({required String password, required String code});
|
||||
/// Issues new recovery codes (invalidates previous ones). Requires a valid TOTP code.
|
||||
Future<List<String>> regenerateRecoveryCodes(String totpCode);
|
||||
Future<UserProfile> getProfile();
|
||||
Future<UserProfile> getProfile({bool force = false});
|
||||
UserProfile? peekLastProfile();
|
||||
void invalidateProfile();
|
||||
Future<void> updateProfile({
|
||||
String? firstName,
|
||||
String? middleName,
|
||||
|
||||
@ -4,7 +4,8 @@ import '../../../core/theme/app_colors.dart';
|
||||
import '../../../domain/repositories/health_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
|
||||
class NetworkScreen extends StatefulWidget {
|
||||
const NetworkScreen({super.key});
|
||||
@ -16,6 +17,7 @@ class NetworkScreen extends StatefulWidget {
|
||||
class _NetworkScreenState extends State<NetworkScreen> {
|
||||
HealthStatus? _health;
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
@ -24,10 +26,12 @@ class _NetworkScreenState extends State<NetworkScreen> {
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keep = _health != null;
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_loading = !keep;
|
||||
_retrying = force && !keep;
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final health = await context.read<HealthRepository>().getHealth();
|
||||
@ -35,12 +39,17 @@ class _NetworkScreenState extends State<NetworkScreen> {
|
||||
setState(() {
|
||||
_health = health;
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_health == null) {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -49,16 +58,36 @@ class _NetworkScreenState extends State<NetworkScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('admin_network_screen'),
|
||||
appBar: AppBar(
|
||||
title: Text(s.networkStatus),
|
||||
actions: [
|
||||
IconButton(onPressed: _load, icon: const Icon(Icons.refresh_rounded)),
|
||||
IconButton(
|
||||
onPressed: _loading ? null : () => _load(),
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _loading
|
||||
? PredLoadingView(message: s.loading)
|
||||
: _error != null
|
||||
? PredErrorView(message: _error!, onRetry: _load)
|
||||
body: _error != null && _health == null
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _health == null
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
@ -126,10 +155,19 @@ class _InfoRow extends StatelessWidget {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(label, style: Theme.of(context).textTheme.bodyMedium),
|
||||
Text(value, style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Expanded(
|
||||
child: Text(label, style: Theme.of(context).textTheme.bodyMedium),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Flexible(
|
||||
child: Text(
|
||||
value,
|
||||
textAlign: TextAlign.end,
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -6,6 +6,8 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../data/repositories/admin_repository_impl.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
/// Admin-only screen to view and update password policy and JWT expiry settings.
|
||||
@ -22,6 +24,7 @@ class SettingsScreen extends StatefulWidget {
|
||||
class _SettingsScreenState extends State<SettingsScreen> {
|
||||
SystemSettings? _settings;
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
bool _saving = false;
|
||||
|
||||
@ -44,10 +47,12 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
}
|
||||
|
||||
/// Fetches current system settings and populates form controllers.
|
||||
Future<void> _load() async {
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keepForm = _settings != null;
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_loading = !keepForm;
|
||||
_retrying = force && !keepForm;
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final s = await widget.adminRepo.getSettings();
|
||||
@ -58,13 +63,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_accessExpiryController.text = s.accessTokenExpiry;
|
||||
_refreshExpiryController.text = s.refreshTokenExpiry;
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_settings == null) {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -118,198 +128,215 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isAdmin = context.read<AuthBloc>().state.isAdmin;
|
||||
if (!isAdmin) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
body: const Center(child: Text('Access denied. Admin only.')),
|
||||
Widget _settingsBody(BuildContext context) {
|
||||
if (_error != null && _settings == null) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Settings'),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () => context.pop(),
|
||||
),
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _error != null
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(_error!),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(onPressed: _load, child: const Text('Retry')),
|
||||
],
|
||||
if (_loading && _settings == null) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 120),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 120),
|
||||
SizedBox(height: 24),
|
||||
PredSkeletonCard(height: 48),
|
||||
],
|
||||
);
|
||||
}
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: Icon(Icons.password_rounded, color: AppColors.goldPrimary),
|
||||
title: Text(
|
||||
'Password policy',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.goldPrimary,
|
||||
),
|
||||
),
|
||||
subtitle: const Text('Minimum length and character requirements'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextField(
|
||||
controller: _minLengthController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Minimum length',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'Minimum password length (e.g. 8)',
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
),
|
||||
)
|
||||
: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: Icon(Icons.password_rounded, color: AppColors.goldPrimary),
|
||||
title: Text(
|
||||
'Password policy',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.goldPrimary,
|
||||
),
|
||||
),
|
||||
subtitle: const Text('Minimum length and character requirements'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextField(
|
||||
controller: _minLengthController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Minimum length',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'Minimum password length (e.g. 8)',
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require uppercase letter'),
|
||||
value: _settings!.passwordRequireUppercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: v ?? true,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require lowercase letter'),
|
||||
value: _settings!.passwordRequireLowercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: v ?? true,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require number'),
|
||||
value: _settings!.passwordRequireNumber,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: v ?? true,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require special character'),
|
||||
value: _settings!.passwordRequireSpecial,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: v ?? true,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: Icon(Icons.timer_outlined, color: AppColors.goldPrimary),
|
||||
title: Text(
|
||||
'Token expiration',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.goldPrimary,
|
||||
),
|
||||
),
|
||||
subtitle: const Text('Access and refresh token validity'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Use values like 15m, 1h, 7d (minutes, hours, days). New tokens will use these values.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _accessExpiryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Access token expiry',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'e.g. 15m, 1h',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _refreshExpiryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Refresh token expiry',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'e.g. 7d, 30d',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Save settings'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require uppercase letter'),
|
||||
value: _settings!.passwordRequireUppercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: v ?? true,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require lowercase letter'),
|
||||
value: _settings!.passwordRequireLowercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: v ?? true,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require number'),
|
||||
value: _settings!.passwordRequireNumber,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: v ?? true,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require special character'),
|
||||
value: _settings!.passwordRequireSpecial,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: v ?? true,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: Icon(Icons.timer_outlined, color: AppColors.goldPrimary),
|
||||
title: Text(
|
||||
'Token expiration',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.goldPrimary,
|
||||
),
|
||||
),
|
||||
subtitle: const Text('Access and refresh token validity'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Use values like 15m, 1h, 7d (minutes, hours, days). New tokens will use these values.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _accessExpiryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Access token expiry',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'e.g. 15m, 1h',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _refreshExpiryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Refresh token expiry',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'e.g. 7d, 30d',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Save settings'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<AuthBloc, AuthState>(
|
||||
buildWhen: (prev, next) => prev.isAdmin != next.isAdmin,
|
||||
builder: (context, authState) {
|
||||
if (!authState.isAdmin) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
body: const Center(child: Text('Access denied. Admin only.')),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
key: const Key('admin_settings_screen'),
|
||||
appBar: AppBar(
|
||||
title: const Text('Settings'),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () => context.pop(),
|
||||
),
|
||||
),
|
||||
body: _settingsBody(context),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,6 +6,8 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../data/repositories/admin_repository_impl.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
|
||||
/// Full user detail view for admins: profile, account flags, and balances.
|
||||
class UserDetailScreen extends StatefulWidget {
|
||||
@ -26,6 +28,7 @@ class UserDetailScreen extends StatefulWidget {
|
||||
class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
AdminUserDetails? _data;
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
@ -35,10 +38,12 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
}
|
||||
|
||||
/// Fetches profile, flags, and balances for [widget.userId].
|
||||
Future<void> _load() async {
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keepData = _data != null;
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_loading = !keepData;
|
||||
_retrying = force && !keepData;
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final data = await widget.adminRepo.getUserDetails(widget.userId);
|
||||
@ -46,13 +51,18 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
setState(() {
|
||||
_data = data;
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_data == null) {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -94,9 +104,23 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Widget _skeletonBody() {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 160),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 100),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
key: const Key('admin_user_detail_screen'),
|
||||
appBar: AppBar(
|
||||
title: const Text('User details'),
|
||||
flexibleSpace: Container(
|
||||
@ -107,27 +131,19 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
onPressed: () => context.pop(),
|
||||
),
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _error != null
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error_outline_rounded, size: 48, color: Theme.of(context).colorScheme.error),
|
||||
const SizedBox(height: 16),
|
||||
Text(_error!, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: () => context.pop(),
|
||||
child: const Text('Back'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
body: _error != null && _data == null
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _data == null
|
||||
? _skeletonBody()
|
||||
: _data == null
|
||||
? const Center(child: Text('User not found'))
|
||||
: SingleChildScrollView(
|
||||
|
||||
@ -6,6 +6,8 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../data/repositories/admin_repository_impl.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
|
||||
/// Lists registered users with search, pagination, and inline flag management.
|
||||
class UserManagementScreen extends StatefulWidget {
|
||||
@ -26,6 +28,7 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
List<AdminUserListItem> _users = [];
|
||||
int _total = 0;
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
int _offset = 0;
|
||||
static const _pageSize = 25;
|
||||
@ -43,11 +46,13 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
}
|
||||
|
||||
/// Loads a page of users from the API, optionally resetting pagination.
|
||||
Future<void> _load({bool resetOffset = true}) async {
|
||||
Future<void> _load({bool resetOffset = true, bool force = false}) async {
|
||||
if (resetOffset) _offset = 0;
|
||||
final keepList = _users.isNotEmpty;
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_loading = !keepList;
|
||||
_retrying = force && !keepList;
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final result = await widget.adminRepo.listUsers(
|
||||
@ -60,13 +65,18 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
_users = result.users;
|
||||
_total = result.total;
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_users.isEmpty) {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -124,6 +134,7 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
key: const Key('admin_users_screen'),
|
||||
appBar: AppBar(
|
||||
title: const Text('User Management'),
|
||||
flexibleSpace: Container(
|
||||
@ -158,50 +169,55 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Card(
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: Theme.of(context).colorScheme.onErrorContainer),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(_error!)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _users.isEmpty
|
||||
? const Center(child: Text('No users found'))
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
itemCount: _users.length,
|
||||
itemBuilder: (context, index) {
|
||||
final u = _users[index];
|
||||
return _UserExpansionTile(
|
||||
user: u,
|
||||
formatCreated: _formatCreated,
|
||||
onUpdateFlag: _updateFlag,
|
||||
onViewDetails: () => context.push('/admin/users/${u.id}'),
|
||||
);
|
||||
},
|
||||
child: _error != null && _users.isEmpty
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _users.isEmpty
|
||||
? ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _users.isEmpty
|
||||
? const Center(child: Text('No users found'))
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
itemCount: _users.length,
|
||||
itemBuilder: (context, index) {
|
||||
final u = _users[index];
|
||||
return _UserExpansionTile(
|
||||
user: u,
|
||||
formatCreated: _formatCreated,
|
||||
onUpdateFlag: _updateFlag,
|
||||
onViewDetails: () => context.push('/admin/users/${u.id}'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
if (_total > 0 && !_loading)
|
||||
if (_total > 0 && !(_loading && _users.isEmpty))
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: _offset <= 0
|
||||
onPressed: _offset <= 0 || _loading
|
||||
? null
|
||||
: () {
|
||||
setState(() => _offset = (_offset - _pageSize).clamp(0, _total));
|
||||
@ -211,7 +227,7 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
),
|
||||
Text('${_offset + 1}-${(_offset + _users.length).clamp(0, _total)} of $_total'),
|
||||
IconButton(
|
||||
onPressed: _offset + _users.length >= _total
|
||||
onPressed: _offset + _users.length >= _total || _loading
|
||||
? null
|
||||
: () {
|
||||
setState(() => _offset += _pageSize);
|
||||
|
||||
@ -45,7 +45,8 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
|
||||
/// Signs in with email, password, and optional TOTP; navigates via listener on success.
|
||||
Future<void> _onLogin(AuthLoginRequested event, Emitter<AuthState> emit) async {
|
||||
emit(const AuthState.loading());
|
||||
if (state.isSubmitting) return;
|
||||
emit(const AuthState.submitting());
|
||||
try {
|
||||
final result = await _authRepo.login(
|
||||
event.email,
|
||||
@ -61,7 +62,8 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
|
||||
/// Registers a new account; emits [AuthStatus.registered] on success.
|
||||
Future<void> _onRegister(AuthRegisterRequested event, Emitter<AuthState> emit) async {
|
||||
emit(const AuthState.loading());
|
||||
if (state.isSubmitting) return;
|
||||
emit(const AuthState.submitting());
|
||||
try {
|
||||
final result = await _authRepo.register(RegisterRequest(
|
||||
fullName: event.fullName,
|
||||
@ -86,7 +88,8 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
AuthResendVerificationRequested event,
|
||||
Emitter<AuthState> emit,
|
||||
) async {
|
||||
emit(const AuthState.loading());
|
||||
if (state.isSubmitting) return;
|
||||
emit(const AuthState.submitting());
|
||||
try {
|
||||
await _authRepo.resendVerificationEmail(event.email);
|
||||
emit(const AuthState.verificationResent(
|
||||
|
||||
@ -3,7 +3,10 @@ part of 'auth_bloc.dart';
|
||||
/// High-level authentication lifecycle status emitted by [AuthBloc].
|
||||
enum AuthStatus {
|
||||
initial,
|
||||
/// Session restore / bootstrap (splash, router).
|
||||
loading,
|
||||
/// Form submit in flight (login / register / resend) — keeps guest UI mounted.
|
||||
submitting,
|
||||
authenticated,
|
||||
unauthenticated,
|
||||
registered,
|
||||
@ -30,6 +33,7 @@ class AuthState extends Equatable {
|
||||
|
||||
const AuthState.initial() : this();
|
||||
const AuthState.loading() : this(status: AuthStatus.loading);
|
||||
const AuthState.submitting() : this(status: AuthStatus.submitting);
|
||||
const AuthState.authenticated({
|
||||
String? userId,
|
||||
String? role,
|
||||
@ -98,6 +102,9 @@ class AuthState extends Equatable {
|
||||
bool get isCaptchaChallenge =>
|
||||
errorCode == 'CAPTCHA_REQUIRED' || errorCode == 'CAPTCHA_INVALID';
|
||||
|
||||
/// True while a guest auth form submit is in flight.
|
||||
bool get isSubmitting => status == AuthStatus.submitting;
|
||||
|
||||
AuthState copyWith({
|
||||
AuthStatus? status,
|
||||
String? userId,
|
||||
|
||||
@ -32,8 +32,19 @@ class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_loading) return;
|
||||
final email = _emailController.text.trim();
|
||||
if (email.isEmpty) return;
|
||||
final s = context.strings;
|
||||
if (email.isEmpty) {
|
||||
setState(() => _error = s.emailCannotBeEmpty);
|
||||
_errorTimer = scheduleMessageClear(
|
||||
setState,
|
||||
() => _error = null,
|
||||
previous: _errorTimer,
|
||||
);
|
||||
showErrorSnackBar(context, s.emailCannotBeEmpty);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
@ -65,6 +76,7 @@ class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('forgot_password_screen'),
|
||||
appBar: AppBar(
|
||||
leading: welcomeBackButton(context),
|
||||
title: Text(s.forgotPassword),
|
||||
@ -81,6 +93,7 @@ class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
|
||||
Text(s.resetEmailSent, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('forgot_password_back_to_login'),
|
||||
label: s.signIn,
|
||||
onPressed: () => context.go('/login'),
|
||||
),
|
||||
@ -92,16 +105,26 @@ class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
|
||||
Text(s.forgotPasswordHint),
|
||||
const SizedBox(height: 20),
|
||||
PredTextField(
|
||||
key: const Key('forgot_password_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
enabled: !_loading,
|
||||
textInputAction: TextInputAction.done,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
onSubmitted: _loading ? null : (_) => _submit(),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
||||
Text(
|
||||
_error!,
|
||||
key: const Key('forgot_password_error'),
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('forgot_password_submit'),
|
||||
label: s.sendResetLink,
|
||||
loading: _loading,
|
||||
onPressed: _submit,
|
||||
|
||||
@ -87,13 +87,21 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
|
||||
void _submitLogin() {
|
||||
final bloc = context.read<AuthBloc>();
|
||||
if (bloc.state.isSubmitting) return;
|
||||
final email = _emailController.text.trim();
|
||||
final password = _passwordController.text;
|
||||
if (email.isEmpty || password.isEmpty) {
|
||||
showErrorSnackBar(context, context.strings.loginFieldsRequired);
|
||||
return;
|
||||
}
|
||||
setState(() => _verifyBanner = null);
|
||||
context.read<AuthBloc>().add(AuthLoginRequested(
|
||||
email: _emailController.text.trim(),
|
||||
password: _passwordController.text,
|
||||
totpCode: _totpController.text.isEmpty ? null : _totpController.text,
|
||||
captchaToken: _buildCaptchaToken(),
|
||||
));
|
||||
bloc.add(AuthLoginRequested(
|
||||
email: email,
|
||||
password: password,
|
||||
totpCode: _totpController.text.isEmpty ? null : _totpController.text,
|
||||
captchaToken: _buildCaptchaToken(),
|
||||
));
|
||||
}
|
||||
|
||||
@override
|
||||
@ -176,138 +184,158 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.status == AuthStatus.loading;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
gradient: AppColors.heroGradient(isDark),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
const PrediqoLogo(size: 64, showWordmark: false),
|
||||
const SizedBox(height: 12),
|
||||
Text(s.appName, style: Theme.of(context).textTheme.headlineMedium),
|
||||
const SizedBox(height: 6),
|
||||
Text(s.tagline, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
).animate().fadeIn(duration: 400.ms).slideY(begin: 0.05, end: 0),
|
||||
const SizedBox(height: 24),
|
||||
if (_showVerifyHint) ...[
|
||||
final loading = state.isSubmitting;
|
||||
return AutofillGroup(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.primary.withValues(alpha: 0.35)),
|
||||
gradient: AppColors.heroGradient(isDark),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Text(s.registerSuccessVerify),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
if (_verifyBanner != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.danger.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.danger.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
child: Column(
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: AppColors.danger, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_verifyBanner!,
|
||||
style: const TextStyle(color: AppColors.danger, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
const PrediqoLogo(size: 64, showWordmark: false),
|
||||
const SizedBox(height: 12),
|
||||
Text(s.appName, style: Theme.of(context).textTheme.headlineMedium),
|
||||
const SizedBox(height: 6),
|
||||
Text(s.tagline, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
).animate().fadeIn(duration: 400.ms).slideY(begin: 0.05, end: 0),
|
||||
const SizedBox(height: 24),
|
||||
if (_showVerifyHint) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.primary.withValues(alpha: 0.35)),
|
||||
),
|
||||
child: Text(s.registerSuccessVerify),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
if (_verifyBanner != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.danger.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.danger.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: AppColors.danger, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_verifyBanner!,
|
||||
style: const TextStyle(color: AppColors.danger, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(s.emailNotVerifiedHint, style: Theme.of(context).textTheme.bodySmall),
|
||||
TextButton(
|
||||
onPressed: loading
|
||||
? null
|
||||
: () {
|
||||
final email = _emailController.text.trim();
|
||||
if (email.isEmpty) {
|
||||
showErrorSnackBar(context, s.emailCannotBeEmpty);
|
||||
return;
|
||||
}
|
||||
context.read<AuthBloc>().add(AuthResendVerificationRequested(email));
|
||||
},
|
||||
child: Text(s.resendVerification),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
PredTextField(
|
||||
key: const Key('login_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
prefixIcon: Icons.email_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(s.emailNotVerifiedHint, style: Theme.of(context).textTheme.bodySmall),
|
||||
TextButton(
|
||||
onPressed: loading
|
||||
? null
|
||||
: () {
|
||||
final email = _emailController.text.trim();
|
||||
if (email.isEmpty) return;
|
||||
context.read<AuthBloc>().add(AuthResendVerificationRequested(email));
|
||||
},
|
||||
child: Text(s.resendVerification),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
PredTextField(
|
||||
key: const Key('login_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
prefixIcon: Icons.email_outlined,
|
||||
enabled: !loading,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
key: const Key('login_password'),
|
||||
controller: _passwordController,
|
||||
label: s.password,
|
||||
obscure: _obscurePassword,
|
||||
prefixIcon: Icons.lock_outline,
|
||||
enabled: !loading,
|
||||
suffix: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
controller: _totpController,
|
||||
label: s.totpCode,
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon: Icons.security_outlined,
|
||||
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,
|
||||
key: const Key('login_password'),
|
||||
controller: _passwordController,
|
||||
label: s.password,
|
||||
obscure: _obscurePassword,
|
||||
prefixIcon: Icons.lock_outline,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.password],
|
||||
suffix: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: loading
|
||||
? null
|
||||
: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
controller: _totpController,
|
||||
label: s.totpCode,
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon: Icons.security_outlined,
|
||||
maxLength: 6,
|
||||
enabled: !loading,
|
||||
textInputAction: _captchaRequired
|
||||
? TextInputAction.next
|
||||
: TextInputAction.done,
|
||||
onSubmitted: loading ? null : (_) => _submitLogin(),
|
||||
),
|
||||
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,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: loading ? null : (_) => _submitLogin(),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(s.captchaMathHelper, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
key: const Key('forgot_password_link'),
|
||||
onPressed: loading ? null : () => context.push('/forgot-password'),
|
||||
child: Text(s.forgotPassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
PredPrimaryButton(
|
||||
key: const Key('login_submit'),
|
||||
label: s.signIn,
|
||||
loading: loading,
|
||||
onPressed: _submitLogin,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: loading ? null : () => context.go('/register'),
|
||||
child: Text(s.signUp),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(s.captchaMathHelper, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
key: const Key('forgot_password_link'),
|
||||
onPressed: loading ? null : () => context.push('/forgot-password'),
|
||||
child: Text(s.forgotPassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
PredPrimaryButton(
|
||||
key: const Key('login_submit'),
|
||||
label: s.signIn,
|
||||
loading: loading,
|
||||
onPressed: _submitLogin,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(onPressed: () => context.go('/register'), child: Text(s.signUp)),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
@ -10,6 +10,7 @@ import '../../../domain/repositories/repositories.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_button.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/prediqo_logo.dart';
|
||||
import '../../welcome/utils/welcome_navigation.dart';
|
||||
@ -75,23 +76,36 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadCountries() async {
|
||||
setState(() {
|
||||
_loadingCountries = true;
|
||||
_countriesError = null;
|
||||
});
|
||||
Future<void> _loadCountries({bool force = false}) async {
|
||||
final repo = sl<AuthRepository>();
|
||||
final peek = repo.peekLastCountries();
|
||||
if (!force && peek != null && peek.isNotEmpty) {
|
||||
setState(() {
|
||||
_countries = peek;
|
||||
_loadingCountries = false;
|
||||
_countriesError = null;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_loadingCountries = true;
|
||||
_countriesError = null;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final list = await sl<AuthRepository>().getCountries();
|
||||
final list = await repo.getCountries(force: force);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_countries = list;
|
||||
_loadingCountries = false;
|
||||
_countriesError = null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loadingCountries = false;
|
||||
_countriesError = e.toString();
|
||||
if (_countries.isEmpty) {
|
||||
_countriesError = e.toString();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -216,6 +230,8 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
}
|
||||
|
||||
void _submit(AppStrings s) {
|
||||
final bloc = context.read<AuthBloc>();
|
||||
if (bloc.state.isSubmitting || _loadingCountries) return;
|
||||
final fullName = _fullNameController.text.trim();
|
||||
final email = _emailController.text.trim();
|
||||
final password = _passwordController.text;
|
||||
@ -243,7 +259,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
}
|
||||
|
||||
setState(() => _formError = null);
|
||||
context.read<AuthBloc>().add(AuthRegisterRequested(
|
||||
bloc.add(AuthRegisterRequested(
|
||||
fullName: fullName,
|
||||
email: email,
|
||||
password: password,
|
||||
@ -308,7 +324,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.status == AuthStatus.loading;
|
||||
final loading = state.isSubmitting;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
@ -342,7 +358,7 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
message: s.countriesLoadFailed,
|
||||
danger: false,
|
||||
actionLabel: s.retry,
|
||||
onAction: loading ? null : _loadCountries,
|
||||
onAction: loading ? null : () => _loadCountries(force: true),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
@ -352,6 +368,8 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
prefixIcon: Icons.person_outline,
|
||||
enabled: !loading,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.name],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
@ -360,6 +378,8 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
prefixIcon: Icons.email_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
@ -368,6 +388,8 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
keyboardType: TextInputType.phone,
|
||||
prefixIcon: Icons.phone_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.telephoneNumber],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
@ -376,9 +398,11 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
obscure: _obscure,
|
||||
prefixIcon: Icons.lock_outline,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.newPassword],
|
||||
suffix: IconButton(
|
||||
icon: Icon(_obscure ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: () => setState(() => _obscure = !_obscure),
|
||||
onPressed: loading ? null : () => setState(() => _obscure = !_obscure),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
@ -388,21 +412,27 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
obscure: _obscureConfirm,
|
||||
prefixIcon: Icons.lock_outline,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.newPassword],
|
||||
suffix: IconButton(
|
||||
icon: Icon(
|
||||
_obscureConfirm ? Icons.visibility_outlined : Icons.visibility_off_outlined,
|
||||
),
|
||||
onPressed: () => setState(() => _obscureConfirm = !_obscureConfirm),
|
||||
onPressed:
|
||||
loading ? null : () => setState(() => _obscureConfirm = !_obscureConfirm),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
_SelectField(
|
||||
label: s.countryOfResidence,
|
||||
value: _countryLabel(_countryCode),
|
||||
enabled: !loading && !_loadingCountries && _countries.isNotEmpty,
|
||||
onTap: () => _pickCountry(nationality: false),
|
||||
helper: s.countryHelper,
|
||||
),
|
||||
if (_loadingCountries && _countries.isEmpty)
|
||||
const PredSkeletonCard(height: 56)
|
||||
else
|
||||
_SelectField(
|
||||
label: s.countryOfResidence,
|
||||
value: _countryLabel(_countryCode),
|
||||
enabled: !loading && !_loadingCountries && _countries.isNotEmpty,
|
||||
onTap: () => _pickCountry(nationality: false),
|
||||
helper: s.countryHelper,
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Text(s.genderRequired, style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 8),
|
||||
@ -425,20 +455,25 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
_SelectField(
|
||||
label: s.nationalityOptional,
|
||||
value: _countryLabel(_nationalityCode),
|
||||
enabled: !loading && !_loadingCountries && _countries.isNotEmpty,
|
||||
onTap: () => _pickCountry(nationality: true),
|
||||
clearable: _nationalityCode != null,
|
||||
onClear: () => setState(() => _nationalityCode = null),
|
||||
),
|
||||
if (_loadingCountries && _countries.isEmpty)
|
||||
const PredSkeletonCard(height: 56)
|
||||
else
|
||||
_SelectField(
|
||||
label: s.nationalityOptional,
|
||||
value: _countryLabel(_nationalityCode),
|
||||
enabled: !loading && !_loadingCountries && _countries.isNotEmpty,
|
||||
onTap: () => _pickCountry(nationality: true),
|
||||
clearable: _nationalityCode != null,
|
||||
onClear: () => setState(() => _nationalityCode = null),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
controller: _referralController,
|
||||
label: s.referralCodeOptional,
|
||||
prefixIcon: Icons.card_giftcard_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: loading ? null : (_) => _submit(s),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9]')),
|
||||
LengthLimitingTextInputFormatter(32),
|
||||
@ -470,8 +505,9 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('register_submit'),
|
||||
label: s.signUp,
|
||||
loading: loading || _loadingCountries,
|
||||
loading: loading || (_loadingCountries && _countries.isEmpty),
|
||||
onPressed: () => _submit(s),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
@ -12,6 +12,8 @@ import '../../../domain/repositories/repositories.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
|
||||
/// Guides the user through 2FA setup, or manages disable when already enabled.
|
||||
@ -29,39 +31,65 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
final _regenCodeController = TextEditingController();
|
||||
|
||||
bool _loadingProfile = true;
|
||||
bool _profileRetrying = false;
|
||||
bool _totpEnabled = false;
|
||||
bool _profileKnown = false;
|
||||
String? _profileError;
|
||||
bool _startingSetup = false;
|
||||
bool _awaitingEnable = false;
|
||||
bool _awaitingDisable = false;
|
||||
bool _regenerating = false;
|
||||
List<String> _recoveryCodes = const [];
|
||||
Future<void>? _profileInFlight;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = sl<AuthRepository>().peekLastProfile();
|
||||
if (cached != null) {
|
||||
_totpEnabled = cached.totpEnabled;
|
||||
_profileKnown = true;
|
||||
_loadingProfile = false;
|
||||
}
|
||||
_loadProfile();
|
||||
}
|
||||
|
||||
Future<void> _loadProfile() async {
|
||||
setState(() {
|
||||
_loadingProfile = true;
|
||||
_profileError = null;
|
||||
});
|
||||
try {
|
||||
final profile = await sl<AuthRepository>().getProfile();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_totpEnabled = profile.totpEnabled;
|
||||
_loadingProfile = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_profileError = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
_loadingProfile = false;
|
||||
});
|
||||
}
|
||||
Future<void> _loadProfile({bool force = false}) {
|
||||
if (_profileInFlight != null) return _profileInFlight!;
|
||||
final keep = _profileKnown && !force;
|
||||
final future = () async {
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_loadingProfile = true;
|
||||
if (!force) _profileError = null;
|
||||
_profileRetrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final profile = await sl<AuthRepository>().getProfile(force: force);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_totpEnabled = profile.totpEnabled;
|
||||
_profileKnown = true;
|
||||
_loadingProfile = false;
|
||||
_profileError = null;
|
||||
_profileRetrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loadingProfile = false;
|
||||
_profileRetrying = false;
|
||||
if (!_profileKnown) {
|
||||
_profileError = e is AppException
|
||||
? e.message
|
||||
: AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_profileInFlight = future.whenComplete(() => _profileInFlight = null);
|
||||
return _profileInFlight!;
|
||||
}
|
||||
|
||||
@override
|
||||
@ -118,6 +146,7 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('totp_setup_screen'),
|
||||
appBar: AppBar(title: Text(s.twoFactor)),
|
||||
body: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
@ -133,6 +162,7 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
_recoveryCodes = List<String>.from(state.recoveryCodes);
|
||||
_codeController.clear();
|
||||
});
|
||||
sl<AuthRepository>().invalidateProfile();
|
||||
// Keep recovery codes visible — do not pop away.
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
@ -148,6 +178,7 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
_disableCodeController.clear();
|
||||
_regenCodeController.clear();
|
||||
});
|
||||
sl<AuthRepository>().invalidateProfile();
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
@ -166,22 +197,28 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
if (_loadingProfile) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (_profileError != null) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(_profileError!, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(onPressed: _loadProfile, child: Text(s.retry)),
|
||||
],
|
||||
if (_profileError != null && !_profileKnown) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _profileError!,
|
||||
retrying: _profileRetrying,
|
||||
onRetry: () => _loadProfile(force: true),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_loadingProfile && !_profileKnown) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 48),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 48),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_totpEnabled && state.totpData == null) {
|
||||
|
||||
@ -1,10 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/models/faq_models.dart';
|
||||
import '../../../domain/repositories/faq_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import '../../welcome/utils/welcome_navigation.dart';
|
||||
|
||||
class FaqScreen extends StatefulWidget {
|
||||
@ -22,11 +25,22 @@ class _FaqScreenState extends State<FaqScreen> {
|
||||
final _searchController = TextEditingController();
|
||||
List<FaqEntryModel> _entries = [];
|
||||
bool _loading = true;
|
||||
bool _searching = false;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
String? _activeSearch;
|
||||
int _loadGen = 0;
|
||||
Future<void>? _sameKeyInFlight;
|
||||
String? _sameKey;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = _repo.peekLast(category: widget.initialCategory);
|
||||
if (cached != null && cached.isNotEmpty) {
|
||||
_entries = cached;
|
||||
_loading = false;
|
||||
}
|
||||
_load(category: widget.initialCategory);
|
||||
}
|
||||
|
||||
@ -36,34 +50,76 @@ class _FaqScreenState extends State<FaqScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _load({String? search, String? category}) async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
Future<void> _load({
|
||||
String? search,
|
||||
String? category,
|
||||
bool force = false,
|
||||
}) {
|
||||
final cat = category ?? widget.initialCategory;
|
||||
final key = '${cat ?? ''}|${search ?? ''}';
|
||||
// Coalesce only identical in-flight queries (retry spam); new searches proceed.
|
||||
if (_sameKeyInFlight != null && _sameKey == key) return _sameKeyInFlight!;
|
||||
|
||||
final gen = ++_loadGen;
|
||||
final keepVisible = _entries.isNotEmpty;
|
||||
final future = () async {
|
||||
setState(() {
|
||||
_activeSearch = search;
|
||||
_retrying = force;
|
||||
if (keepVisible) {
|
||||
_searching = true;
|
||||
if (!force) _error = null;
|
||||
} else {
|
||||
_loading = true;
|
||||
if (!force) _error = null;
|
||||
}
|
||||
});
|
||||
try {
|
||||
final entries = await _repo.listEntries(
|
||||
search: search,
|
||||
category: cat,
|
||||
force: force,
|
||||
);
|
||||
if (!mounted || gen != _loadGen) return;
|
||||
setState(() {
|
||||
_entries = entries;
|
||||
_loading = false;
|
||||
_searching = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted || gen != _loadGen) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_searching = false;
|
||||
_retrying = false;
|
||||
if (_entries.isEmpty) {
|
||||
_error = AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_sameKey = key;
|
||||
_sameKeyInFlight = future.whenComplete(() {
|
||||
if (_sameKey == key) {
|
||||
_sameKeyInFlight = null;
|
||||
_sameKey = null;
|
||||
}
|
||||
});
|
||||
try {
|
||||
final entries = await _repo.listEntries(
|
||||
search: search,
|
||||
category: category ?? widget.initialCategory,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_entries = entries;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
return _sameKeyInFlight!;
|
||||
}
|
||||
|
||||
void _clearSearch() {
|
||||
_searchController.clear();
|
||||
_load(category: widget.initialCategory, force: true);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('faq_screen'),
|
||||
appBar: AppBar(
|
||||
leading: welcomeBackButton(context),
|
||||
title: Text(s.faqTitle),
|
||||
@ -73,58 +129,113 @@ class _FaqScreenState extends State<FaqScreen> {
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
|
||||
child: TextField(
|
||||
key: const Key('faq_search'),
|
||||
controller: _searchController,
|
||||
decoration: InputDecoration(
|
||||
hintText: s.searchFaq,
|
||||
prefixIcon: const Icon(Icons.search_rounded),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.clear_rounded),
|
||||
onPressed: () {
|
||||
_searchController.clear();
|
||||
_load(category: widget.initialCategory);
|
||||
},
|
||||
onPressed: _clearSearch,
|
||||
),
|
||||
),
|
||||
onSubmitted: (q) => _load(search: q, category: widget.initialCategory),
|
||||
onSubmitted: (q) => _load(
|
||||
search: q.trim().isEmpty ? null : q.trim(),
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_searching)
|
||||
const LinearProgressIndicator(
|
||||
minHeight: 2,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
Expanded(
|
||||
child: _loading
|
||||
? PredLoadingView(message: s.loading)
|
||||
: _error != null
|
||||
? PredErrorView(message: _error!, onRetry: () => _load())
|
||||
: _entries.isEmpty
|
||||
? Center(child: Text(s.noFaqResults))
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(20),
|
||||
itemCount: _entries.length,
|
||||
itemBuilder: (context, index) {
|
||||
final entry = _entries[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: PredCard(
|
||||
child: ExpansionTile(
|
||||
title: Text(
|
||||
entry.question,
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
subtitle: entry.category.isNotEmpty
|
||||
? Text(entry.category)
|
||||
: null,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(entry.answer),
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(
|
||||
search: _activeSearch,
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
child: _error != null && _entries.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(
|
||||
search: _activeSearch,
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _entries.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _entries.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 160,
|
||||
child: Center(child: Text(s.noFaqResults)),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.builder(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
itemCount: _entries.length,
|
||||
itemBuilder: (context, index) {
|
||||
final entry = _entries[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: PredCard(
|
||||
child: ExpansionTile(
|
||||
title: Text(
|
||||
entry.question,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
subtitle: entry.category.isNotEmpty
|
||||
? Text(entry.category)
|
||||
: null,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
16,
|
||||
0,
|
||||
16,
|
||||
16,
|
||||
),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(entry.answer),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
@ -19,7 +18,9 @@ import '../../../shared/utils/app_update.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/language_toggle_button.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/prediqo_logo.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import '../utils/home_navigation.dart';
|
||||
import '../../prediction/bloc/prediction_bloc.dart';
|
||||
import '../../wallet/bloc/wallet_bloc.dart';
|
||||
@ -34,14 +35,27 @@ class HomeScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> {
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
List<AdvertisementModel> _heroAds = [];
|
||||
List<GameCatalogItem> _games = [];
|
||||
ReferralDashboardModel? _referral;
|
||||
int _unreadNotifications = 0;
|
||||
bool _updateAvailable = false;
|
||||
bool _totpEnabled = true;
|
||||
bool _totpKnown = false;
|
||||
|
||||
bool _adsLoading = true;
|
||||
bool _gamesLoading = true;
|
||||
bool _referralLoading = false;
|
||||
bool _adsRetrying = false;
|
||||
bool _gamesRetrying = false;
|
||||
bool _referralRetrying = false;
|
||||
String? _adsError;
|
||||
String? _gamesError;
|
||||
String? _referralError;
|
||||
|
||||
Future<void>? _adsInFlight;
|
||||
Future<void>? _gamesInFlight;
|
||||
Future<void>? _referralInFlight;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -49,13 +63,12 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
final cachedGames = sl<GameCatalogRepository>().peekLast();
|
||||
if (cachedGames != null && cachedGames.isNotEmpty) {
|
||||
_games = cachedGames;
|
||||
_gamesLoading = false;
|
||||
}
|
||||
final cachedAds = sl<AdvertisementRepository>().peekLast(placement: 'home_hero');
|
||||
if (cachedAds != null && cachedAds.isNotEmpty) {
|
||||
_heroAds = cachedAds;
|
||||
}
|
||||
if (_heroAds.isNotEmpty || _games.isNotEmpty) {
|
||||
_loading = false;
|
||||
_adsLoading = false;
|
||||
}
|
||||
_load();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@ -89,67 +102,140 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
Future<void> _refreshTotp() async {
|
||||
final profile = await _soft(sl<AuthRepository>().getProfile());
|
||||
if (!mounted || profile == null) return;
|
||||
setState(() => _totpEnabled = profile.totpEnabled);
|
||||
setState(() {
|
||||
_totpEnabled = profile.totpEnabled;
|
||||
_totpKnown = true;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _loadAds({bool force = false}) {
|
||||
if (_adsInFlight != null) return _adsInFlight!;
|
||||
final keep = _heroAds.isNotEmpty && !force;
|
||||
final future = () async {
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_adsLoading = true;
|
||||
_adsError = null;
|
||||
_adsRetrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final ads = await sl<AdvertisementRepository>().list(
|
||||
placement: 'home_hero',
|
||||
force: force,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_heroAds = ads;
|
||||
_adsLoading = false;
|
||||
_adsError = null;
|
||||
_adsRetrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_adsLoading = false;
|
||||
_adsRetrying = false;
|
||||
if (_heroAds.isEmpty) {
|
||||
_adsError = AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_adsInFlight = future.whenComplete(() => _adsInFlight = null);
|
||||
return _adsInFlight!;
|
||||
}
|
||||
|
||||
Future<void> _loadGames({bool force = false}) {
|
||||
if (_gamesInFlight != null) return _gamesInFlight!;
|
||||
final keep = _games.isNotEmpty && !force;
|
||||
final future = () async {
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_gamesLoading = true;
|
||||
_gamesError = null;
|
||||
_gamesRetrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final games = await sl<GameCatalogRepository>().list(force: force);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_games = games;
|
||||
_gamesLoading = false;
|
||||
_gamesError = null;
|
||||
_gamesRetrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_gamesLoading = false;
|
||||
_gamesRetrying = false;
|
||||
if (_games.isEmpty) {
|
||||
_gamesError = AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_gamesInFlight = future.whenComplete(() => _gamesInFlight = null);
|
||||
return _gamesInFlight!;
|
||||
}
|
||||
|
||||
Future<void> _loadReferral({bool force = false}) {
|
||||
if (_referralInFlight != null) return _referralInFlight!;
|
||||
final future = () async {
|
||||
setState(() {
|
||||
if (_referral == null) _referralLoading = true;
|
||||
_referralError = null;
|
||||
_referralRetrying = force || _referral == null;
|
||||
});
|
||||
try {
|
||||
final referral = await sl<ReferralRepository>().getDashboard(maxDepth: 1);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_referral = referral;
|
||||
_referralLoading = false;
|
||||
_referralError = null;
|
||||
_referralRetrying = false;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_referralLoading = false;
|
||||
_referralRetrying = false;
|
||||
if (_referral == null) {
|
||||
_referralError = AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_referralInFlight = future.whenComplete(() => _referralInFlight = null);
|
||||
return _referralInFlight!;
|
||||
}
|
||||
|
||||
Future<void> _loadExtras() async {
|
||||
final notifFuture = _soft(sl<NotificationRepository>().list(limit: 1));
|
||||
final profileFuture = _soft(sl<AuthRepository>().getProfile());
|
||||
final referralFuture = _loadReferral();
|
||||
final notifPage = await notifFuture;
|
||||
final profile = await profileFuture;
|
||||
await referralFuture;
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (notifPage != null) _unreadNotifications = notifPage.unreadCount;
|
||||
if (profile != null) {
|
||||
_totpEnabled = profile.totpEnabled;
|
||||
_totpKnown = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keep = (_heroAds.isNotEmpty || _games.isNotEmpty) && !force;
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final adsFuture = _soft(
|
||||
sl<AdvertisementRepository>().list(placement: 'home_hero', force: force),
|
||||
);
|
||||
final gamesFuture = _soft(sl<GameCatalogRepository>().list(force: force));
|
||||
final extrasFuture = () async {
|
||||
final referral = await _soft(sl<ReferralRepository>().getDashboard(maxDepth: 1));
|
||||
final notifPage = await _soft(sl<NotificationRepository>().list(limit: 1));
|
||||
final profile = await _soft(sl<AuthRepository>().getProfile());
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (referral != null) _referral = referral;
|
||||
if (notifPage != null) _unreadNotifications = notifPage.unreadCount;
|
||||
if (profile != null) _totpEnabled = profile.totpEnabled;
|
||||
});
|
||||
}();
|
||||
|
||||
adsFuture.then((ads) {
|
||||
if (!mounted || ads == null) return;
|
||||
setState(() {
|
||||
_heroAds = ads;
|
||||
_loading = false;
|
||||
_error = null;
|
||||
});
|
||||
});
|
||||
gamesFuture.then((games) {
|
||||
if (!mounted || games == null) return;
|
||||
setState(() {
|
||||
_games = games;
|
||||
_loading = false;
|
||||
});
|
||||
});
|
||||
|
||||
final ads = await adsFuture;
|
||||
final games = await gamesFuture;
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
if (ads == null && games == null && _heroAds.isEmpty && _games.isEmpty) {
|
||||
_error = AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
await extrasFuture;
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
await Future.wait([
|
||||
_loadAds(force: force),
|
||||
_loadGames(force: force),
|
||||
_loadExtras(),
|
||||
]);
|
||||
}
|
||||
|
||||
Future<void> _onUpdateTap() => handleAppUpdateTap(
|
||||
@ -226,54 +312,44 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
),
|
||||
if (_error != null && !_loading)
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(_error!, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton(onPressed: _load, child: Text(s.retry)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
_heroAds.isEmpty
|
||||
? HomeAdCarousel(
|
||||
ads: _heroAds,
|
||||
loading: _loading && _heroAds.isEmpty,
|
||||
)
|
||||
.animate()
|
||||
.fadeIn(duration: 350.ms)
|
||||
.slideY(begin: 0.04, end: 0)
|
||||
: HomeAdCarousel(
|
||||
ads: _heroAds,
|
||||
loading: false,
|
||||
),
|
||||
if (_adsError != null && _heroAds.isEmpty)
|
||||
SectionError(
|
||||
message: _adsError!,
|
||||
retrying: _adsRetrying,
|
||||
onRetry: () => _loadAds(force: true),
|
||||
)
|
||||
else
|
||||
HomeAdCarousel(
|
||||
ads: _heroAds,
|
||||
loading: _adsLoading && _heroAds.isEmpty,
|
||||
),
|
||||
const SizedBox(height: 22),
|
||||
_SectionTitle(title: s.playNow, subtitle: s.playNowSubtitle),
|
||||
const SizedBox(height: 12),
|
||||
if (_games.isNotEmpty)
|
||||
if (_gamesError != null && _games.isEmpty)
|
||||
SectionError(
|
||||
message: _gamesError!,
|
||||
retrying: _gamesRetrying,
|
||||
onRetry: () => _loadGames(force: true),
|
||||
)
|
||||
else if (_games.isNotEmpty)
|
||||
..._games.take(4).map(
|
||||
(g) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: _GameCard(game: g, onTap: () => _openGame(g)),
|
||||
),
|
||||
)
|
||||
else if (_loading)
|
||||
const SizedBox(
|
||||
height: 110,
|
||||
child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
|
||||
else if (_gamesLoading)
|
||||
const Column(
|
||||
children: [
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
],
|
||||
)
|
||||
else
|
||||
_FeaturedPredictCard(onTap: () => context.go('/predict')),
|
||||
@ -308,7 +384,7 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
),
|
||||
],
|
||||
),
|
||||
if (!_loading && !_totpEnabled) ...[
|
||||
if (_totpKnown && !_totpEnabled) ...[
|
||||
const SizedBox(height: 22),
|
||||
_SectionTitle(title: s.homeSecurity, subtitle: s.homeTwoFaTitle),
|
||||
const SizedBox(height: 12),
|
||||
@ -319,7 +395,28 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
},
|
||||
),
|
||||
],
|
||||
if (_referral != null) ...[
|
||||
if (_referralError != null && _referral == null) ...[
|
||||
const SizedBox(height: 22),
|
||||
_SectionTitle(
|
||||
title: s.yourNetwork,
|
||||
subtitle: s.yourNetworkSubtitle,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SectionError(
|
||||
message: _referralError!,
|
||||
compact: true,
|
||||
retrying: _referralRetrying,
|
||||
onRetry: () => _loadReferral(force: true),
|
||||
),
|
||||
] else if (_referralLoading && _referral == null) ...[
|
||||
const SizedBox(height: 22),
|
||||
_SectionTitle(
|
||||
title: s.yourNetwork,
|
||||
subtitle: s.yourNetworkSubtitle,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 96),
|
||||
] else if (_referral != null) ...[
|
||||
const SizedBox(height: 22),
|
||||
_SectionTitle(
|
||||
title: s.yourNetwork,
|
||||
|
||||
@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
import '../../../../data/models/advertisement_models.dart';
|
||||
import '../../../../l10n/app_strings.dart';
|
||||
import '../../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../utils/home_navigation.dart';
|
||||
|
||||
/// Auto-rotating hero carousel for dynamic home promotions.
|
||||
@ -71,14 +72,7 @@ class _HomeAdCarouselState extends State<HomeAdCarousel> {
|
||||
return _buildCarousel();
|
||||
}
|
||||
if (widget.loading) {
|
||||
return Container(
|
||||
height: 200,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceCard,
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
),
|
||||
child: const Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
|
||||
);
|
||||
return const PredSkeletonCarousel(height: 200);
|
||||
}
|
||||
|
||||
return Container(
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/models/notification_models.dart';
|
||||
import '../../../domain/repositories/notification_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
|
||||
class NotificationsScreen extends StatefulWidget {
|
||||
const NotificationsScreen({super.key});
|
||||
@ -21,65 +23,108 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
final _repo = sl<NotificationRepository>();
|
||||
bool _loading = true;
|
||||
bool _loadingMore = false;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
List<SecurityNotificationModel> _items = [];
|
||||
int _unreadCount = 0;
|
||||
int _total = 0;
|
||||
Future<void>? _listInFlight;
|
||||
|
||||
bool get _hasMore => _items.length < _total;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = _repo.peekLast();
|
||||
if (cached != null) {
|
||||
_items = cached.items;
|
||||
_total = cached.total;
|
||||
_unreadCount = cached.unreadCount;
|
||||
_loading = false;
|
||||
}
|
||||
_load(reset: true);
|
||||
}
|
||||
|
||||
Future<void> _load({required bool reset}) async {
|
||||
if (reset) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
} else {
|
||||
if (_loadingMore || !_hasMore) return;
|
||||
setState(() => _loadingMore = true);
|
||||
Future<void> _load({required bool reset, bool force = false}) {
|
||||
if (!reset) {
|
||||
return _loadMore();
|
||||
}
|
||||
if (_listInFlight != null) return _listInFlight!;
|
||||
|
||||
final keep = _items.isNotEmpty && !force;
|
||||
final future = () async {
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
final page = await _repo.list(
|
||||
limit: _pageSize,
|
||||
offset: 0,
|
||||
force: force || !keep,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_items = page.items;
|
||||
_total = page.total;
|
||||
_unreadCount = page.unreadCount;
|
||||
_loading = false;
|
||||
_error = null;
|
||||
_retrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_items.isEmpty) {
|
||||
_error = e is AppException
|
||||
? e.message
|
||||
: e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
|
||||
_listInFlight = future.whenComplete(() => _listInFlight = null);
|
||||
return _listInFlight!;
|
||||
}
|
||||
|
||||
Future<void> _loadMore() async {
|
||||
if (_loadingMore || !_hasMore) return;
|
||||
setState(() => _loadingMore = true);
|
||||
try {
|
||||
final offset = reset ? 0 : _items.length;
|
||||
final page = await _repo.list(limit: _pageSize, offset: offset);
|
||||
final page = await _repo.list(limit: _pageSize, offset: _items.length);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (reset) {
|
||||
_items = page.items;
|
||||
} else {
|
||||
final existingIds = _items.map((e) => e.id).toSet();
|
||||
_items = [
|
||||
..._items,
|
||||
...page.items.where((e) => !existingIds.contains(e.id)),
|
||||
];
|
||||
}
|
||||
final existingIds = _items.map((e) => e.id).toSet();
|
||||
_items = [
|
||||
..._items,
|
||||
...page.items.where((e) => !existingIds.contains(e.id)),
|
||||
];
|
||||
_total = page.total;
|
||||
_unreadCount = page.unreadCount;
|
||||
_loading = false;
|
||||
_loadingMore = false;
|
||||
});
|
||||
} catch (e) {
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (reset) {
|
||||
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
}
|
||||
_loading = false;
|
||||
_loadingMore = false;
|
||||
});
|
||||
setState(() => _loadingMore = false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _markAll() async {
|
||||
try {
|
||||
await _repo.markAllRead();
|
||||
await _load(reset: true);
|
||||
await _load(reset: true, force: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
@ -177,113 +222,138 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _loading
|
||||
? PredLoadingView(message: s.loading)
|
||||
: _error != null
|
||||
? PredErrorView(message: _error!, onRetry: () => _load(reset: true))
|
||||
: RefreshIndicator(
|
||||
onRefresh: () => _load(reset: true),
|
||||
child: _items.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(40),
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.notifications_none_rounded,
|
||||
size: 48,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noNotifications,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
itemCount: _items.length + (_hasMore ? 1 : 0),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= _items.length) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Center(
|
||||
child: _loadingMore
|
||||
? const SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
)
|
||||
: OutlinedButton(
|
||||
onPressed: () => _load(reset: false),
|
||||
child: Text(s.loadMore),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final item = _items[index];
|
||||
return PredCard(
|
||||
onTap: () => _openItem(item),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
margin: const EdgeInsets.only(top: 5),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: item.isUnread
|
||||
? AppColors.primary
|
||||
: AppColors.border,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.title,
|
||||
style: TextStyle(
|
||||
fontWeight: item.isUnread
|
||||
? FontWeight.w800
|
||||
: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
item.body,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall
|
||||
?.copyWith(color: AppColors.textSecondary),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_formatDate(item.createdAt),
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.labelSmall
|
||||
?.copyWith(color: AppColors.textMuted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => _load(reset: true, force: true),
|
||||
child: _buildBody(s),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody(AppStrings s) {
|
||||
if (_loading && _items.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_error != null && _items.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(reset: true, force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_items.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(40),
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.notifications_none_rounded,
|
||||
size: 48,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noNotifications,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
itemCount: _items.length + (_hasMore ? 1 : 0),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= _items.length) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Center(
|
||||
child: _loadingMore
|
||||
? const PredSkeletonLine(width: 120, height: 36)
|
||||
: OutlinedButton(
|
||||
onPressed: () => _load(reset: false),
|
||||
child: Text(s.loadMore),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final item = _items[index];
|
||||
return PredCard(
|
||||
onTap: () => _openItem(item),
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
margin: const EdgeInsets.only(top: 5),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: item.isUnread ? AppColors.primary : AppColors.border,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.title,
|
||||
style: TextStyle(
|
||||
fontWeight:
|
||||
item.isUnread ? FontWeight.w800 : FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
item.body,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall
|
||||
?.copyWith(color: AppColors.textSecondary),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_formatDate(item.createdAt),
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.labelSmall
|
||||
?.copyWith(color: AppColors.textMuted),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,12 +2,15 @@ import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/realtime/game_socket_service.dart';
|
||||
import '../../../core/utils/amount_utils.dart';
|
||||
import '../../../data/models/prediction_models.dart';
|
||||
import '../../../data/repositories/prediction_repository_impl.dart';
|
||||
import '../../../data/repositories/wallet_repository_impl.dart';
|
||||
import '../../../domain/repositories/prediction_repository.dart';
|
||||
import '../../support/utils/support_ui_gate.dart';
|
||||
import '../utils/candle_interval_cache.dart';
|
||||
import '../utils/prediction_history_filter_store.dart';
|
||||
import '../utils/server_adjusted_countdown.dart';
|
||||
|
||||
@ -41,8 +44,9 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
on<PredictionWsMessageReceived>(_onWsMessage);
|
||||
on<PredictionSocketStatusChanged>(_onSocketStatusChanged);
|
||||
on<PredictionHistoryPageRequested>(_onHistoryPage, transformer: _sequential());
|
||||
on<PredictionHistoryFilterChanged>(_onHistoryFilterChanged, transformer: _sequential());
|
||||
on<PredictionHistoryFilterChanged>(_onHistoryFilterChanged);
|
||||
on<PredictionCandlesOlderRequested>(_onOlderCandles);
|
||||
on<PredictionCandlesReloadRequested>(_onCandlesReload, transformer: _sequential());
|
||||
on<PredictionPaused>(_onPaused);
|
||||
on<PredictionResumed>(_onResumed);
|
||||
on<PredictionAppResumed>(_onAppResumed, transformer: _sequential());
|
||||
@ -68,6 +72,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
static const _pollJitterRatio = 0.12;
|
||||
|
||||
final historyFilterStore = PredictionHistoryFilterStore();
|
||||
final candleIntervalCache = CandleIntervalCache();
|
||||
|
||||
String _historyKey({
|
||||
int? intervalMinutes,
|
||||
@ -111,6 +116,32 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
);
|
||||
}
|
||||
|
||||
int _chartPageSizeForMinutes(int intervalMinutes) {
|
||||
IntervalModel? meta;
|
||||
for (final i in state.gameState?.intervals ?? const <IntervalModel>[]) {
|
||||
if (i.intervalMinutes == intervalMinutes) {
|
||||
meta = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
final limit = meta?.chartCandleLimit ??
|
||||
state.gameState?.interval.chartCandleLimit ??
|
||||
80;
|
||||
return limit.clamp(20, 200);
|
||||
}
|
||||
|
||||
void _rememberCandles(
|
||||
int intervalMinutes,
|
||||
List<OhlcCandleModel> items,
|
||||
bool hasMore,
|
||||
) {
|
||||
if (items.isEmpty) return;
|
||||
candleIntervalCache.put(
|
||||
intervalMinutes,
|
||||
CandleIntervalPage(items: items, hasMore: hasMore),
|
||||
);
|
||||
}
|
||||
|
||||
List<PredictionModel> _applyLiveHistoryOverlays(List<PredictionModel> items) {
|
||||
final liveMulti = state.gameState?.userMultiBet;
|
||||
final liveBet = state.gameState?.userBet;
|
||||
@ -149,7 +180,9 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
final wallet = state.historyWalletFilter;
|
||||
final status = state.historyStatusFilter;
|
||||
if (append || (showSpinnerIfEmpty && state.history.isEmpty)) {
|
||||
emit(state.copyWith(isLoadingHistory: true));
|
||||
emit(state.copyWith(isLoadingHistory: true, clearHistoryError: true));
|
||||
} else {
|
||||
emit(state.copyWith(clearHistoryError: true));
|
||||
}
|
||||
try {
|
||||
final result = await _fetchHistoryPage(
|
||||
@ -188,14 +221,18 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
historyPage: nextPage,
|
||||
historyTotalPages: nextTotal,
|
||||
isLoadingHistory: false,
|
||||
clearHistoryError: true,
|
||||
));
|
||||
} catch (_) {
|
||||
} catch (e) {
|
||||
if (_isCurrentHistoryContext(
|
||||
intervalMinutes: interval,
|
||||
wallet: wallet,
|
||||
status: status,
|
||||
)) {
|
||||
emit(state.copyWith(isLoadingHistory: false));
|
||||
emit(state.copyWith(
|
||||
isLoadingHistory: false,
|
||||
historyError: e.toString().replaceFirst('Exception: ', ''),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -271,6 +308,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
|
||||
void _onPaused(PredictionPaused event, Emitter<PredictionState> emit) {
|
||||
_screenActive = false;
|
||||
SupportUiGate.predictionScreenActive = false;
|
||||
_stopPolling();
|
||||
_healthyPollSkips = 0;
|
||||
}
|
||||
@ -279,6 +317,13 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
PredictionSocketStatusChanged event,
|
||||
Emitter<PredictionState> emit,
|
||||
) {
|
||||
// Support sheet open: ignore transient game-WS drops so the Live badge
|
||||
// does not flash "Reconnecting…" over a healthy Predict session.
|
||||
if (SupportUiGate.holdsGameRealtime &&
|
||||
event.status != GameSocketConnectionState.connected &&
|
||||
state.isRealtimeHealthy) {
|
||||
return;
|
||||
}
|
||||
final nextRealtime = switch (event.status) {
|
||||
GameSocketConnectionState.connected => PredictionRealtimeStatus.live,
|
||||
GameSocketConnectionState.connecting => PredictionRealtimeStatus.syncing,
|
||||
@ -304,9 +349,22 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
|
||||
Future<void> _onResumed(PredictionResumed event, Emitter<PredictionState> emit) async {
|
||||
_screenActive = true;
|
||||
SupportUiGate.predictionScreenActive = true;
|
||||
add(const PredictionLoadRequested(ifStale: true));
|
||||
}
|
||||
|
||||
/// Live badge status — holds "live" while Support is open on this screen.
|
||||
PredictionRealtimeStatus _realtimeStatus({
|
||||
required PredictionRealtimeStatus whenDisconnected,
|
||||
}) {
|
||||
if (SupportUiGate.holdsGameRealtime &&
|
||||
state.realtimeStatus == PredictionRealtimeStatus.live) {
|
||||
return PredictionRealtimeStatus.live;
|
||||
}
|
||||
if (_socket.isConnected) return PredictionRealtimeStatus.live;
|
||||
return whenDisconnected;
|
||||
}
|
||||
|
||||
static const _freshSyncMs = 5000;
|
||||
|
||||
void _ensureRealtime([int? intervalMinutes]) {
|
||||
@ -339,8 +397,16 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
Emitter<PredictionState> emit,
|
||||
) async {
|
||||
if (!_screenActive) return;
|
||||
if (SupportUiGate.holdsGameRealtime) {
|
||||
// Support sheet / IME lifecycle — refresh via poll, do not tear WS down.
|
||||
_startPolling();
|
||||
add(const PredictionRefreshTick(forceGameState: true));
|
||||
return;
|
||||
}
|
||||
if (_socket.isEnabled) {
|
||||
await _socket.forceReconnect();
|
||||
// Prefer a soft check: opening Support / IME can fake a resume and a
|
||||
// hard forceReconnect briefly shows "Reconnecting…" despite a healthy WS.
|
||||
await _socket.reconnectAfterBackground();
|
||||
}
|
||||
// Old recursive Timer chain may have been suspended mid-flight; restart
|
||||
// it fresh instead of trusting whatever was already scheduled.
|
||||
@ -477,7 +543,17 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
final interval = state.selectedIntervalMinutes;
|
||||
final historyWallet = state.historyWalletFilter;
|
||||
final historyStatus = state.historyStatusFilter;
|
||||
final pageSize = _chartPageSizeForMinutes(interval);
|
||||
final stateFuture = _repo.getState(intervalMinutes: interval);
|
||||
final candlesOutcome = _repo
|
||||
.getCandlesPage(
|
||||
intervalMinutes: interval,
|
||||
limit: pageSize,
|
||||
)
|
||||
.then<({CandlesPageModel? page, Object? error})>(
|
||||
(page) => (page: page, error: null),
|
||||
onError: (Object e, StackTrace _) => (page: null, error: e),
|
||||
);
|
||||
final historyFuture = _soft(_fetchHistoryPage(
|
||||
1,
|
||||
intervalMinutes: interval,
|
||||
@ -509,27 +585,38 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
gameState: applied,
|
||||
selectedIntervalMinutes: applied.selectedIntervalMinutes,
|
||||
wsConnected: _socket.isConnected,
|
||||
realtimeStatus: _socket.isConnected
|
||||
? PredictionRealtimeStatus.live
|
||||
: (_socket.isEnabled
|
||||
? PredictionRealtimeStatus.syncing
|
||||
: PredictionRealtimeStatus.polling),
|
||||
realtimeStatus: _realtimeStatus(
|
||||
whenDisconnected: _socket.isEnabled
|
||||
? PredictionRealtimeStatus.syncing
|
||||
: PredictionRealtimeStatus.polling,
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
final pageSize = gameState.interval.chartCandleLimit.clamp(20, 200);
|
||||
final candlesFuture = _repo.getCandlesPage(
|
||||
intervalMinutes: gameState.selectedIntervalMinutes,
|
||||
limit: pageSize,
|
||||
);
|
||||
|
||||
final candlesPage = await candlesFuture;
|
||||
emit(state.copyWith(
|
||||
status: PredictionStatus.ready,
|
||||
candles: candlesPage.items,
|
||||
hasMoreOlderCandles: candlesPage.hasMore,
|
||||
isLoadingOlderCandles: false,
|
||||
));
|
||||
final candles = await candlesOutcome;
|
||||
if (state.selectedIntervalMinutes != gameState.selectedIntervalMinutes) {
|
||||
return;
|
||||
}
|
||||
if (candles.error == null && candles.page != null) {
|
||||
_rememberCandles(
|
||||
gameState.selectedIntervalMinutes,
|
||||
candles.page!.items,
|
||||
candles.page!.hasMore,
|
||||
);
|
||||
emit(state.copyWith(
|
||||
status: PredictionStatus.ready,
|
||||
candles: candles.page!.items,
|
||||
hasMoreOlderCandles: candles.page!.hasMore,
|
||||
isLoadingOlderCandles: false,
|
||||
clearCandlesError: true,
|
||||
));
|
||||
} else if (candles.error != null) {
|
||||
emit(state.copyWith(
|
||||
status: PredictionStatus.ready,
|
||||
isLoadingOlderCandles: false,
|
||||
candlesError: candles.error.toString().replaceFirst('Exception: ', ''),
|
||||
));
|
||||
}
|
||||
|
||||
final history = await historyFuture;
|
||||
final labels = await balancesFuture;
|
||||
@ -552,6 +639,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
history: historyItems,
|
||||
historyPage: history.page,
|
||||
historyTotalPages: history.totalPages,
|
||||
clearHistoryError: true,
|
||||
mainBalanceLabel: labels?.mainLabel,
|
||||
bonusBalanceLabel: labels?.bonusLabel,
|
||||
testBalanceLabel: labels?.testLabel,
|
||||
@ -559,15 +647,34 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
bonusAvailable: labels?.bonus,
|
||||
testAvailable: labels?.test,
|
||||
));
|
||||
} else if (labels != null) {
|
||||
emit(state.copyWith(
|
||||
mainBalanceLabel: labels.mainLabel,
|
||||
bonusBalanceLabel: labels.bonusLabel,
|
||||
testBalanceLabel: labels.testLabel,
|
||||
mainAvailable: labels.main,
|
||||
bonusAvailable: labels.bonus,
|
||||
testAvailable: labels.test,
|
||||
));
|
||||
} else {
|
||||
if (_isCurrentHistoryContext(
|
||||
intervalMinutes: interval,
|
||||
wallet: historyWallet,
|
||||
status: historyStatus,
|
||||
) &&
|
||||
history == null &&
|
||||
state.history.isEmpty) {
|
||||
emit(state.copyWith(
|
||||
isLoadingHistory: false,
|
||||
historyError: AppException.connectionFailedMessage,
|
||||
mainBalanceLabel: labels?.mainLabel,
|
||||
bonusBalanceLabel: labels?.bonusLabel,
|
||||
testBalanceLabel: labels?.testLabel,
|
||||
mainAvailable: labels?.main,
|
||||
bonusAvailable: labels?.bonus,
|
||||
testAvailable: labels?.test,
|
||||
));
|
||||
} else if (labels != null) {
|
||||
emit(state.copyWith(
|
||||
mainBalanceLabel: labels.mainLabel,
|
||||
bonusBalanceLabel: labels.bonusLabel,
|
||||
testBalanceLabel: labels.testLabel,
|
||||
mainAvailable: labels.main,
|
||||
bonusAvailable: labels.bonus,
|
||||
testAvailable: labels.test,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
_lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch;
|
||||
@ -578,9 +685,11 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
status: keepExistingUi ? PredictionStatus.ready : PredictionStatus.error,
|
||||
errorMessage: keepExistingUi ? state.errorMessage : e.toString(),
|
||||
wsConnected: _socket.isConnected,
|
||||
realtimeStatus: _socket.isEnabled
|
||||
? PredictionRealtimeStatus.polling
|
||||
: PredictionRealtimeStatus.syncing,
|
||||
realtimeStatus: _realtimeStatus(
|
||||
whenDisconnected: _socket.isEnabled
|
||||
? PredictionRealtimeStatus.polling
|
||||
: PredictionRealtimeStatus.syncing,
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -643,44 +752,114 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
bonusAvailable: labels?.bonus,
|
||||
testAvailable: labels?.test,
|
||||
wsConnected: _socket.isConnected,
|
||||
realtimeStatus: _socket.isConnected
|
||||
? PredictionRealtimeStatus.live
|
||||
: (_socket.isEnabled ? PredictionRealtimeStatus.syncing : PredictionRealtimeStatus.polling),
|
||||
realtimeStatus: _realtimeStatus(
|
||||
whenDisconnected: _socket.isEnabled
|
||||
? PredictionRealtimeStatus.syncing
|
||||
: PredictionRealtimeStatus.polling,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onIntervalChanged(PredictionIntervalChanged event, Emitter<PredictionState> emit) async {
|
||||
final prevInterval = state.selectedIntervalMinutes;
|
||||
final minutes = event.minutes;
|
||||
final gs = state.gameState;
|
||||
final cached = historyFilterStore.peek(
|
||||
final cachedHistory = historyFilterStore.peek(
|
||||
_historyKey(
|
||||
intervalMinutes: event.minutes,
|
||||
intervalMinutes: minutes,
|
||||
wallet: state.historyWalletFilter,
|
||||
status: state.historyStatusFilter,
|
||||
),
|
||||
);
|
||||
final cachedCandles = candleIntervalCache.peek(minutes);
|
||||
emit(state.copyWith(
|
||||
selectedIntervalMinutes: event.minutes,
|
||||
candles: const [],
|
||||
hasMoreOlderCandles: true,
|
||||
isLoadingOlderCandles: true,
|
||||
history: cached?.items ?? const [],
|
||||
historyPage: cached?.page ?? 1,
|
||||
historyTotalPages: cached?.totalPages ?? 1,
|
||||
isLoadingHistory: cached == null,
|
||||
selectedIntervalMinutes: minutes,
|
||||
candles: cachedCandles?.items ?? const [],
|
||||
hasMoreOlderCandles: cachedCandles?.hasMore ?? true,
|
||||
isLoadingOlderCandles: cachedCandles == null,
|
||||
clearCandlesError: true,
|
||||
history: cachedHistory?.items ?? const [],
|
||||
historyPage: cachedHistory?.page ?? 1,
|
||||
historyTotalPages: cachedHistory?.totalPages ?? 1,
|
||||
isLoadingHistory: cachedHistory == null,
|
||||
clearHistoryError: cachedHistory != null,
|
||||
gameState: gs?.copyWith(
|
||||
selectedIntervalMinutes: event.minutes,
|
||||
selectedIntervalMinutes: minutes,
|
||||
clearRound: true,
|
||||
clearUserBet: true,
|
||||
),
|
||||
));
|
||||
if (_socket.isEnabled && _socket.isConnected) {
|
||||
if (prevInterval != event.minutes) {
|
||||
if (prevInterval != minutes) {
|
||||
_socket.unsubscribe(prevInterval);
|
||||
}
|
||||
_socket.subscribe(event.minutes);
|
||||
_socket.subscribe(minutes);
|
||||
}
|
||||
|
||||
try {
|
||||
final pageSize = _chartPageSizeForMinutes(minutes);
|
||||
final stateFuture = _repo.getState(intervalMinutes: minutes);
|
||||
final candlesOutcome = _repo
|
||||
.getCandlesPage(
|
||||
intervalMinutes: minutes,
|
||||
limit: pageSize,
|
||||
)
|
||||
.then<({CandlesPageModel? page, Object? error})>(
|
||||
(page) => (page: page, error: null),
|
||||
onError: (Object e, StackTrace _) => (page: null, error: e),
|
||||
);
|
||||
|
||||
final gameState = await stateFuture;
|
||||
if (state.selectedIntervalMinutes != minutes) return;
|
||||
|
||||
final applied = _stabilizeGameStateRound(
|
||||
previous: state.gameState,
|
||||
incoming: gameState,
|
||||
);
|
||||
emit(state.copyWith(
|
||||
status: PredictionStatus.ready,
|
||||
gameState: applied,
|
||||
selectedIntervalMinutes: applied.selectedIntervalMinutes,
|
||||
wsConnected: _socket.isConnected,
|
||||
realtimeStatus: _realtimeStatus(
|
||||
whenDisconnected: _socket.isEnabled
|
||||
? PredictionRealtimeStatus.syncing
|
||||
: PredictionRealtimeStatus.polling,
|
||||
),
|
||||
));
|
||||
|
||||
final candles = await candlesOutcome;
|
||||
if (state.selectedIntervalMinutes != minutes) return;
|
||||
if (candles.error == null && candles.page != null) {
|
||||
_rememberCandles(minutes, candles.page!.items, candles.page!.hasMore);
|
||||
emit(state.copyWith(
|
||||
candles: candles.page!.items,
|
||||
hasMoreOlderCandles: candles.page!.hasMore,
|
||||
isLoadingOlderCandles: false,
|
||||
clearCandlesError: true,
|
||||
));
|
||||
} else if (candles.error != null) {
|
||||
emit(state.copyWith(
|
||||
isLoadingOlderCandles: false,
|
||||
candlesError: candles.error.toString().replaceFirst('Exception: ', ''),
|
||||
));
|
||||
}
|
||||
|
||||
_lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch;
|
||||
_healthyPollSkips = 0;
|
||||
_startPolling();
|
||||
|
||||
await _refreshHistoryFromServer(
|
||||
emit,
|
||||
page: 1,
|
||||
showSpinnerIfEmpty: cachedHistory == null,
|
||||
);
|
||||
} catch (e) {
|
||||
if (state.selectedIntervalMinutes != minutes) return;
|
||||
emit(state.copyWith(
|
||||
errorMessage: e.toString().replaceFirst('Exception: ', ''),
|
||||
));
|
||||
}
|
||||
add(const PredictionLoadRequested());
|
||||
}
|
||||
|
||||
void _onStakeSelected(PredictionStakeSelected event, Emitter<PredictionState> emit) {
|
||||
@ -822,6 +1001,10 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
final prevUserBetId = state.gameState?.userBet?.id;
|
||||
final prevLastAuto = state.gameState?.autoSettings?.lastAutoBetAt;
|
||||
final nowMs = DateTime.now().millisecondsSinceEpoch;
|
||||
// Phase boundary (0s / ≤1s): never skip `/state` — healthy-WS skips were
|
||||
// leaving the UI stuck at 0s for ~8–20s then jumping mid next window.
|
||||
final phaseBoundary =
|
||||
countdownNeedsStateResync(state.gameState?.round, clientNowMs: nowMs);
|
||||
final shouldDoSafetyStateSync =
|
||||
!event.forceGameState &&
|
||||
wsOk &&
|
||||
@ -835,6 +1018,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
!hasActiveMulti &&
|
||||
!autoOn &&
|
||||
!event.forceGameState &&
|
||||
!phaseBoundary &&
|
||||
!shouldDoSafetyStateSync) {
|
||||
_healthyPollSkips++;
|
||||
final labels = await _loadBalances(state.gameState?.config.walletTypeCode);
|
||||
@ -887,10 +1071,13 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
mainAvailable: labels.main,
|
||||
bonusAvailable: labels.bonus,
|
||||
testAvailable: labels.test,
|
||||
wsConnected: _socket.isConnected,
|
||||
realtimeStatus: _socket.isConnected
|
||||
? PredictionRealtimeStatus.live
|
||||
: (_socket.isEnabled ? PredictionRealtimeStatus.reconnecting : PredictionRealtimeStatus.polling),
|
||||
wsConnected: _socket.isConnected ||
|
||||
(SupportUiGate.holdsGameRealtime && state.isRealtimeHealthy),
|
||||
realtimeStatus: _realtimeStatus(
|
||||
whenDisconnected: _socket.isEnabled
|
||||
? PredictionRealtimeStatus.reconnecting
|
||||
: PredictionRealtimeStatus.polling,
|
||||
),
|
||||
history: history,
|
||||
stakeAccountKind: multi != null
|
||||
? _parseStakeKind(multi.stakeAccountKind)
|
||||
@ -1013,9 +1200,12 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
}
|
||||
if (type == 'round.settled') {
|
||||
// Candle + next window arrive via candle.append / round.updated.
|
||||
// A full Load would re-apply a stale HTTP snapshot mid-countdown.
|
||||
// A full Load would re-apply a stale HTTP snapshot mid-countdown,
|
||||
// but a forced `/state` tick is required when those WS events lag —
|
||||
// otherwise the UI stays at 0s until the healthy poll catches up.
|
||||
add(const PredictionBalancesRefreshRequested());
|
||||
add(const PredictionHistoryPageRequested(1));
|
||||
add(const PredictionRefreshTick(forceGameState: true));
|
||||
}
|
||||
break;
|
||||
case 'multi.updated':
|
||||
@ -1209,7 +1399,7 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
!state.hasMoreOlderCandles) {
|
||||
return;
|
||||
}
|
||||
emit(state.copyWith(isLoadingOlderCandles: true));
|
||||
emit(state.copyWith(isLoadingOlderCandles: true, clearCandlesError: true));
|
||||
try {
|
||||
final oldest = state.candles.first;
|
||||
final pageSize = (state.gameState?.interval.chartCandleLimit ?? 80).clamp(20, 200);
|
||||
@ -1218,13 +1408,57 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
beforeOpenMs: oldest.openMs,
|
||||
limit: pageSize,
|
||||
);
|
||||
final merged = _mergeCandles(page.items, state.candles);
|
||||
_rememberCandles(
|
||||
state.selectedIntervalMinutes,
|
||||
merged,
|
||||
page.hasMore,
|
||||
);
|
||||
emit(state.copyWith(
|
||||
candles: _mergeCandles(page.items, state.candles),
|
||||
candles: merged,
|
||||
hasMoreOlderCandles: page.hasMore,
|
||||
isLoadingOlderCandles: false,
|
||||
clearCandlesError: true,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
isLoadingOlderCandles: false,
|
||||
candlesError: e.toString().replaceFirst('Exception: ', ''),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onCandlesReload(
|
||||
PredictionCandlesReloadRequested event,
|
||||
Emitter<PredictionState> emit,
|
||||
) async {
|
||||
emit(state.copyWith(
|
||||
isLoadingOlderCandles: state.candles.isEmpty,
|
||||
clearCandlesError: true,
|
||||
));
|
||||
try {
|
||||
final pageSize =
|
||||
(state.gameState?.interval.chartCandleLimit ?? 80).clamp(20, 200);
|
||||
final page = await _repo.getCandlesPage(
|
||||
intervalMinutes: state.selectedIntervalMinutes,
|
||||
limit: pageSize,
|
||||
);
|
||||
_rememberCandles(
|
||||
state.selectedIntervalMinutes,
|
||||
page.items,
|
||||
page.hasMore,
|
||||
);
|
||||
emit(state.copyWith(
|
||||
candles: page.items,
|
||||
hasMoreOlderCandles: page.hasMore,
|
||||
isLoadingOlderCandles: false,
|
||||
clearCandlesError: true,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
isLoadingOlderCandles: false,
|
||||
candlesError: e.toString().replaceFirst('Exception: ', ''),
|
||||
));
|
||||
} catch (_) {
|
||||
emit(state.copyWith(isLoadingOlderCandles: false));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -135,6 +135,11 @@ class PredictionCandlesOlderRequested extends PredictionEvent {
|
||||
const PredictionCandlesOlderRequested();
|
||||
}
|
||||
|
||||
/// Reloads the visible candle window (section retry).
|
||||
class PredictionCandlesReloadRequested extends PredictionEvent {
|
||||
const PredictionCandlesReloadRequested();
|
||||
}
|
||||
|
||||
/// Pause HTTP polling when leaving the prediction screen (bloc is app-scoped).
|
||||
class PredictionPaused extends PredictionEvent {
|
||||
const PredictionPaused();
|
||||
|
||||
@ -25,6 +25,8 @@ class PredictionState extends Equatable {
|
||||
this.isSavingAuto = false,
|
||||
this.isLoadingOlderCandles = false,
|
||||
this.hasMoreOlderCandles = true,
|
||||
this.candlesError,
|
||||
this.historyError,
|
||||
this.betPlaced = false,
|
||||
this.errorMessage,
|
||||
this.mainBalanceLabel = '—',
|
||||
@ -59,6 +61,8 @@ class PredictionState extends Equatable {
|
||||
final bool isSavingAuto;
|
||||
final bool isLoadingOlderCandles;
|
||||
final bool hasMoreOlderCandles;
|
||||
final String? candlesError;
|
||||
final String? historyError;
|
||||
final bool betPlaced;
|
||||
final String? errorMessage;
|
||||
final String mainBalanceLabel;
|
||||
@ -141,6 +145,10 @@ class PredictionState extends Equatable {
|
||||
bool? isSavingAuto,
|
||||
bool? isLoadingOlderCandles,
|
||||
bool? hasMoreOlderCandles,
|
||||
String? candlesError,
|
||||
String? historyError,
|
||||
bool clearCandlesError = false,
|
||||
bool clearHistoryError = false,
|
||||
bool? betPlaced,
|
||||
String? errorMessage,
|
||||
bool clearError = false,
|
||||
@ -178,6 +186,10 @@ class PredictionState extends Equatable {
|
||||
isSavingAuto: isSavingAuto ?? this.isSavingAuto,
|
||||
isLoadingOlderCandles: isLoadingOlderCandles ?? this.isLoadingOlderCandles,
|
||||
hasMoreOlderCandles: hasMoreOlderCandles ?? this.hasMoreOlderCandles,
|
||||
candlesError:
|
||||
clearCandlesError ? null : (candlesError ?? this.candlesError),
|
||||
historyError:
|
||||
clearHistoryError ? null : (historyError ?? this.historyError),
|
||||
betPlaced: betPlaced ?? false,
|
||||
errorMessage: clearError ? null : (errorMessage ?? this.errorMessage),
|
||||
mainBalanceLabel: mainBalanceLabel ?? this.mainBalanceLabel,
|
||||
@ -213,6 +225,8 @@ class PredictionState extends Equatable {
|
||||
isSavingAuto,
|
||||
isLoadingOlderCandles,
|
||||
hasMoreOlderCandles,
|
||||
candlesError,
|
||||
historyError,
|
||||
betPlaced,
|
||||
errorMessage,
|
||||
mainBalanceLabel,
|
||||
|
||||
@ -3,12 +3,15 @@ import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/models/game_catalog_models.dart';
|
||||
import '../../../domain/repositories/game_catalog_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import '../../home/utils/home_navigation.dart';
|
||||
import '../bloc/prediction_bloc.dart';
|
||||
import '../utils/game_catalog_ui.dart';
|
||||
@ -23,9 +26,11 @@ class PredictionGamesScreen extends StatefulWidget {
|
||||
|
||||
class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
List<GameCatalogItem> _games = [];
|
||||
bool _predictionPrefetchScheduled = false;
|
||||
Future<void>? _inFlight;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@ -48,30 +53,42 @@ class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _load({bool force = false}) async {
|
||||
Future<void> _load({bool force = false}) {
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
final keepList = _games.isNotEmpty && !force;
|
||||
if (!keepList) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final games = await sl<GameCatalogRepository>().list(force: force);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_games = games;
|
||||
_loading = false;
|
||||
_error = null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = keepList ? _error : e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
_schedulePredictionPrefetch();
|
||||
final future = () async {
|
||||
if (!keepList) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
} else if (force) {
|
||||
setState(() => _retrying = true);
|
||||
}
|
||||
try {
|
||||
final games = await sl<GameCatalogRepository>().list(force: force);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_games = games;
|
||||
_loading = false;
|
||||
_error = null;
|
||||
_retrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (!keepList) {
|
||||
_error = AppException.connectionFailedMessage;
|
||||
}
|
||||
});
|
||||
}
|
||||
_schedulePredictionPrefetch();
|
||||
}();
|
||||
_inFlight = future.whenComplete(() => _inFlight = null);
|
||||
return _inFlight!;
|
||||
}
|
||||
|
||||
void _openGame(GameCatalogItem game) {
|
||||
@ -114,59 +131,52 @@ class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_error != null && !_loading)
|
||||
SliverFillRemaining(
|
||||
hasScrollBody: false,
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
if (_error != null && _games.isEmpty)
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
)
|
||||
else if (_loading && _games.isEmpty)
|
||||
const Column(
|
||||
children: [
|
||||
Text(_error!, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton(onPressed: () => _load(force: true), child: Text(s.retry)),
|
||||
PredSkeletonCard(height: 96),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 96),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 96),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
if (_loading)
|
||||
const SizedBox(
|
||||
height: 160,
|
||||
child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)),
|
||||
)
|
||||
else if (_games.isEmpty)
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Text(
|
||||
s.predictionGamesEmpty,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
..._games.map(
|
||||
(g) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: _PredictionGameCard(
|
||||
game: g,
|
||||
onTap: () => _openGame(g),
|
||||
)
|
||||
.animate()
|
||||
.fadeIn(duration: 280.ms)
|
||||
.slideY(begin: 0.03, end: 0),
|
||||
),
|
||||
)
|
||||
else if (_games.isEmpty)
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Text(
|
||||
s.predictionGamesEmpty,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
)
|
||||
else
|
||||
..._games.map(
|
||||
(g) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: _PredictionGameCard(
|
||||
game: g,
|
||||
onTap: () => _openGame(g),
|
||||
)
|
||||
.animate()
|
||||
.fadeIn(duration: 280.ms)
|
||||
.slideY(begin: 0.03, end: 0),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@ -7,9 +7,12 @@ import '../../../../data/models/prediction_models.dart';
|
||||
import '../../../../data/models/candle_predict_instrument.dart';
|
||||
import '../../../../l10n/app_strings.dart';
|
||||
import '../../../../shared/widgets/pred_card.dart';
|
||||
import '../../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../../shared/widgets/section_error.dart';
|
||||
import '../../../../shared/widgets/adaptive_space_between_row.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
import '../../support/utils/support_ui_gate.dart';
|
||||
import '../bloc/prediction_bloc.dart';
|
||||
import '../utils/server_adjusted_countdown.dart';
|
||||
import 'widgets/candle_chart_widget.dart';
|
||||
@ -17,6 +20,24 @@ import 'widgets/multi_sequence_progress.dart';
|
||||
import 'widgets/prediction_bet_panel.dart';
|
||||
import '../../share_cards/presentation/share_result_widgets.dart';
|
||||
|
||||
/// Whether a real background stay was observed (not sheet/IME overlays).
|
||||
///
|
||||
/// Android 12+ often emits `hidden` for bottom sheets — that must NOT count.
|
||||
/// Resume sequences also pass through `inactive`, so callers should latch
|
||||
/// [paused]/[detached] rather than inspecting only the previous state.
|
||||
@visibleForTesting
|
||||
bool predictionIsRealBackgroundLifecycle(AppLifecycleState state) {
|
||||
return state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached;
|
||||
}
|
||||
|
||||
/// True when a background stay was long enough to warrant a game-WS check.
|
||||
@visibleForTesting
|
||||
bool predictionBackgroundDwellAllowsReconnect(Duration? dwell) {
|
||||
if (dwell == null) return false;
|
||||
return dwell >= const Duration(milliseconds: 1200);
|
||||
}
|
||||
|
||||
class PredictionScreen extends StatefulWidget {
|
||||
const PredictionScreen({super.key});
|
||||
|
||||
@ -27,15 +48,33 @@ class PredictionScreen extends StatefulWidget {
|
||||
class _PredictionScreenState extends State<PredictionScreen> with WidgetsBindingObserver {
|
||||
late final PredictionBloc _bloc;
|
||||
Timer? _uiClock;
|
||||
/// Debounce forced `/state` while the local countdown is stuck at 0s.
|
||||
int? _lastZeroResyncMs;
|
||||
/// Latched when the app truly backgrounds (`paused` / `detached`).
|
||||
/// Cleared on handled `resumed`. Sheet overlays often emit `hidden` /
|
||||
/// `inactive` only — those must not trigger a game-socket reconnect.
|
||||
bool _sawRealBackground = false;
|
||||
DateTime? _backgroundedAt;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_bloc = context.read<PredictionBloc>();
|
||||
_bloc.add(const PredictionResumed());
|
||||
// Rebuild bet gating as the open window expires (canBet uses DateTime.now).
|
||||
// Phase-boundary resync only — countdown / bet-gate ticks live in
|
||||
// RepaintBoundary children so the 1s clock does not rebuild chart/history.
|
||||
_uiClock = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (mounted) setState(() {});
|
||||
if (!mounted) return;
|
||||
final round = _bloc.state.gameState?.round;
|
||||
if (countdownStuckAtZero(round)) {
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
if (_lastZeroResyncMs == null || now - _lastZeroResyncMs! >= 2000) {
|
||||
_lastZeroResyncMs = now;
|
||||
_bloc.add(const PredictionRefreshTick(forceGameState: true));
|
||||
}
|
||||
} else {
|
||||
_lastZeroResyncMs = null;
|
||||
}
|
||||
});
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
}
|
||||
@ -51,13 +90,31 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
/// Screen navigation (`initState`/`dispose`) is NOT the only way this page's
|
||||
/// timers/socket can go stale — the OS backgrounding the whole app (screen
|
||||
/// lock, app switcher, phone call) while the user stays on this route is
|
||||
/// far more common, especially over "several minutes". Force a verified
|
||||
/// reconnect + full resync every time the app comes back to the foreground.
|
||||
/// far more common, especially over "several minutes". Reconnect only after
|
||||
/// a real background dwell — never for Support sheet / IME overlays.
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
_bloc.add(const PredictionAppResumed());
|
||||
if (predictionIsRealBackgroundLifecycle(state)) {
|
||||
_sawRealBackground = true;
|
||||
_backgroundedAt ??= DateTime.now();
|
||||
return;
|
||||
}
|
||||
if (state != AppLifecycleState.resumed) return;
|
||||
|
||||
final sawBackground = _sawRealBackground;
|
||||
final bgAt = _backgroundedAt;
|
||||
_sawRealBackground = false;
|
||||
_backgroundedAt = null;
|
||||
if (!sawBackground) return;
|
||||
if (!predictionBackgroundDwellAllowsReconnect(
|
||||
bgAt == null ? null : DateTime.now().difference(bgAt),
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
// Support sheet can race lifecycle events; never tear the game WS down
|
||||
// while chat is opening/open.
|
||||
if (SupportUiGate.holdsGameRealtime) return;
|
||||
_bloc.add(const PredictionAppResumed());
|
||||
}
|
||||
|
||||
void _setHistoryFilters({String? wallet, String? status}) {
|
||||
@ -109,18 +166,12 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
if (state.status == PredictionStatus.loading && state.gameState == null) {
|
||||
return PredLoadingView(message: s.loading);
|
||||
}
|
||||
if (state.status == PredictionStatus.error && state.gameState == null) {
|
||||
return PredErrorView(
|
||||
message: state.errorMessage ?? s.error,
|
||||
onRetry: () => context.read<PredictionBloc>().add(const PredictionLoadRequested()),
|
||||
);
|
||||
}
|
||||
|
||||
final gs = state.gameState;
|
||||
final round = gs?.round;
|
||||
final bootstrapping =
|
||||
state.status == PredictionStatus.loading && gs == null;
|
||||
final bootError =
|
||||
state.status == PredictionStatus.error && gs == null;
|
||||
|
||||
return KeyedSubtree(
|
||||
key: const Key('prediction_screen'),
|
||||
@ -142,7 +193,16 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
const SizedBox(height: 4),
|
||||
Text(s.tagline, style: Theme.of(context).textTheme.bodySmall),
|
||||
const SizedBox(height: 20),
|
||||
if (!state.isRealtimeHealthy) ...[
|
||||
if (bootError) ...[
|
||||
SectionError(
|
||||
message: state.errorMessage ?? s.error,
|
||||
onRetry: () => context
|
||||
.read<PredictionBloc>()
|
||||
.add(const PredictionLoadRequested()),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
if (!bootstrapping && !state.isRealtimeHealthy) ...[
|
||||
PredCard(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@ -167,45 +227,79 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_RoundPhaseHeader(
|
||||
round: round,
|
||||
openLabel: s.timeLeft,
|
||||
waitLabel: s.waitingRound,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
CandleChartWidget(
|
||||
candles: state.candles,
|
||||
isLoadingOlder: state.isLoadingOlderCandles,
|
||||
hasMoreOlder: state.hasMoreOlderCandles,
|
||||
instrument: gs?.config.instrument ?? defaultCandlePredictInstrument,
|
||||
),
|
||||
if (context.watch<AuthBloc>().state.isAdmin &&
|
||||
round != null &&
|
||||
round.longPoolPercent != null &&
|
||||
round.shortPoolPercent != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
PoolBarWidget(
|
||||
longPercent: round.longPoolPercent!,
|
||||
shortPercent: round.shortPoolPercent!,
|
||||
if (bootstrapping) ...[
|
||||
const PredSkeletonLine(width: 120, height: 14),
|
||||
const SizedBox(height: 8),
|
||||
const Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: PredSkeletonLine(width: 64, height: 28),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
PredSkeleton(
|
||||
width: double.infinity,
|
||||
height: CandleChartWidget.chartHeight,
|
||||
borderRadius: 12,
|
||||
),
|
||||
] else ...[
|
||||
RepaintBoundary(
|
||||
child: _RoundPhaseHeader(
|
||||
round: round,
|
||||
openLabel: s.timeLeft,
|
||||
waitLabel: s.waitingRound,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (state.candlesError != null && state.candles.isEmpty)
|
||||
SectionError(
|
||||
message: state.candlesError!,
|
||||
retrying: state.isLoadingOlderCandles,
|
||||
onRetry: () => context
|
||||
.read<PredictionBloc>()
|
||||
.add(const PredictionCandlesReloadRequested()),
|
||||
)
|
||||
else
|
||||
RepaintBoundary(
|
||||
child: CandleChartWidget(
|
||||
candles: state.candles,
|
||||
isLoadingOlder: state.isLoadingOlderCandles,
|
||||
hasMoreOlder: state.hasMoreOlderCandles,
|
||||
instrument: gs?.config.instrument ??
|
||||
defaultCandlePredictInstrument,
|
||||
),
|
||||
),
|
||||
if (context.watch<AuthBloc>().state.isAdmin &&
|
||||
round != null &&
|
||||
round.longPoolPercent != null &&
|
||||
round.shortPoolPercent != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
PoolBarWidget(
|
||||
longPercent: round.longPoolPercent!,
|
||||
shortPercent: round.shortPoolPercent!,
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (gs != null && gs.intervals.isNotEmpty)
|
||||
AdaptiveSpaceBetweenRow(
|
||||
height: 42,
|
||||
children: [
|
||||
for (final item in gs.intervals.where((i) => i.isActive))
|
||||
ChoiceChip(
|
||||
label: Text(item.label),
|
||||
selected: item.intervalMinutes == state.selectedIntervalMinutes,
|
||||
onSelected: (_) => context.read<PredictionBloc>().add(
|
||||
PredictionIntervalChanged(item.intervalMinutes),
|
||||
),
|
||||
),
|
||||
],
|
||||
BlocSelector<PredictionBloc, PredictionState, int>(
|
||||
selector: (s) => s.selectedIntervalMinutes,
|
||||
builder: (context, selectedMinutes) {
|
||||
return AdaptiveSpaceBetweenRow(
|
||||
height: 42,
|
||||
children: [
|
||||
for (final item in gs.intervals.where((i) => i.isActive))
|
||||
ChoiceChip(
|
||||
label: Text(item.label),
|
||||
selected: item.intervalMinutes == selectedMinutes,
|
||||
onSelected: (_) => context.read<PredictionBloc>().add(
|
||||
PredictionIntervalChanged(item.intervalMinutes),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (gs?.autoSettings?.enabled == true) ...[
|
||||
@ -218,116 +312,134 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
PredictionBetPanel(state: state),
|
||||
if (bootstrapping)
|
||||
const PredSkeletonCard(height: 220)
|
||||
else
|
||||
RepaintBoundary(child: _TickingBetPanel(state: state)),
|
||||
const SizedBox(height: 20),
|
||||
Text(s.recentPredictions, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 10),
|
||||
_HistoryFilterBar(
|
||||
walletFilter: state.historyWalletFilter,
|
||||
statusFilter: state.historyStatusFilter,
|
||||
onAll: () => _setHistoryFilters(),
|
||||
onWallet: (kind) => _setHistoryFilters(
|
||||
wallet: state.historyWalletFilter == kind ? null : kind,
|
||||
status: state.historyStatusFilter,
|
||||
),
|
||||
onStatus: (status) => _setHistoryFilters(
|
||||
wallet: state.historyWalletFilter,
|
||||
status: state.historyStatusFilter == status ? null : status,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final filtered = state.history;
|
||||
final canLoadMore = state.historyPage < state.historyTotalPages;
|
||||
final hasFilters = state.historyWalletFilter != null ||
|
||||
state.historyStatusFilter != null;
|
||||
final showEndLabel = !canLoadMore &&
|
||||
state.historyTotalPages > 1 &&
|
||||
filtered.isNotEmpty;
|
||||
final showLoadMore = canLoadMore;
|
||||
|
||||
if (state.isLoadingHistory && state.history.isEmpty) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 24),
|
||||
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.history.isEmpty) {
|
||||
return PredCard(
|
||||
child: Text(
|
||||
s.noPredictionsYet,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
if (!bootstrapping)
|
||||
BlocSelector<PredictionBloc, PredictionState, (String?, String?)>(
|
||||
selector: (s) => (s.historyWalletFilter, s.historyStatusFilter),
|
||||
builder: (context, filters) {
|
||||
final (walletFilter, statusFilter) = filters;
|
||||
return _HistoryFilterBar(
|
||||
walletFilter: walletFilter,
|
||||
statusFilter: statusFilter,
|
||||
onAll: () => _setHistoryFilters(),
|
||||
onWallet: (kind) => _setHistoryFilters(
|
||||
wallet: walletFilter == kind ? null : kind,
|
||||
status: statusFilter,
|
||||
),
|
||||
onStatus: (status) => _setHistoryFilters(
|
||||
wallet: walletFilter,
|
||||
status: statusFilter == status ? null : status,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (bootstrapping ||
|
||||
(state.isLoadingHistory && state.history.isEmpty)) ...[
|
||||
const PredSkeletonCard(height: 72),
|
||||
const SizedBox(height: 8),
|
||||
const PredSkeletonCard(height: 72),
|
||||
const SizedBox(height: 8),
|
||||
const PredSkeletonCard(height: 72),
|
||||
] else if (state.historyError != null && state.history.isEmpty) ...[
|
||||
SectionError(
|
||||
message: state.historyError!,
|
||||
retrying: state.isLoadingHistory,
|
||||
onRetry: () => context
|
||||
.read<PredictionBloc>()
|
||||
.add(const PredictionHistoryPageRequested(1)),
|
||||
),
|
||||
] else
|
||||
Builder(
|
||||
builder: (context) {
|
||||
final filtered = state.history;
|
||||
final canLoadMore = state.historyPage < state.historyTotalPages;
|
||||
final hasFilters = state.historyWalletFilter != null ||
|
||||
state.historyStatusFilter != null;
|
||||
final showEndLabel = !canLoadMore &&
|
||||
state.historyTotalPages > 1 &&
|
||||
filtered.isNotEmpty;
|
||||
final showLoadMore = canLoadMore;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (filtered.isEmpty)
|
||||
PredCard(
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
hasFilters ? s.noFilteredPredictions : s.noPredictionsYet,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (hasFilters && canLoadMore && state.isLoadingHistory) ...[
|
||||
const SizedBox(height: 12),
|
||||
const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
...filtered.map(
|
||||
(p) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: _PredictionHistoryCard(prediction: p),
|
||||
),
|
||||
),
|
||||
if (showLoadMore) ...[
|
||||
const SizedBox(height: 4),
|
||||
TextButton(
|
||||
onPressed: state.isLoadingHistory
|
||||
? null
|
||||
: () => context.read<PredictionBloc>().add(
|
||||
PredictionHistoryPageRequested(
|
||||
state.historyPage + 1,
|
||||
append: true,
|
||||
),
|
||||
),
|
||||
child: state.isLoadingHistory
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(s.loadMore),
|
||||
),
|
||||
] else if (showEndLabel) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
s.historyEndReached,
|
||||
if (state.history.isEmpty) {
|
||||
return PredCard(
|
||||
child: Text(
|
||||
s.noPredictionsYet,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textMuted,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (filtered.isEmpty)
|
||||
PredCard(
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
hasFilters
|
||||
? s.noFilteredPredictions
|
||||
: s.noPredictionsYet,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (hasFilters &&
|
||||
canLoadMore &&
|
||||
state.isLoadingHistory) ...[
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonLine(
|
||||
width: 120,
|
||||
height: 18,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
...filtered.map(
|
||||
(p) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: _PredictionHistoryCard(prediction: p),
|
||||
),
|
||||
),
|
||||
if (showLoadMore) ...[
|
||||
const SizedBox(height: 4),
|
||||
TextButton(
|
||||
onPressed: state.isLoadingHistory
|
||||
? null
|
||||
: () => context.read<PredictionBloc>().add(
|
||||
PredictionHistoryPageRequested(
|
||||
state.historyPage + 1,
|
||||
append: true,
|
||||
),
|
||||
),
|
||||
child: state.isLoadingHistory
|
||||
? const PredSkeletonLine(width: 80, height: 18)
|
||||
: Text(s.loadMore),
|
||||
),
|
||||
] else if (showEndLabel) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
s.historyEndReached,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textMuted,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@ -337,6 +449,40 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
}
|
||||
}
|
||||
|
||||
/// Local 1s rebuild so [PredictionState.isBettingWindowOpen] updates without
|
||||
/// repainting chart / history.
|
||||
class _TickingBetPanel extends StatefulWidget {
|
||||
const _TickingBetPanel({required this.state});
|
||||
|
||||
final PredictionState state;
|
||||
|
||||
@override
|
||||
State<_TickingBetPanel> createState() => _TickingBetPanelState();
|
||||
}
|
||||
|
||||
class _TickingBetPanelState extends State<_TickingBetPanel> {
|
||||
Timer? _tick;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (mounted) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tick?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return PredictionBetPanel(state: widget.state);
|
||||
}
|
||||
}
|
||||
|
||||
class _HistoryFilterBar extends StatelessWidget {
|
||||
const _HistoryFilterBar({
|
||||
required this.walletFilter,
|
||||
@ -367,7 +513,7 @@ class _HistoryFilterBar extends StatelessWidget {
|
||||
_HistoryFilterChip(
|
||||
label: s.walletMain,
|
||||
selected: walletFilter == 'main',
|
||||
color: AppColors.textMuted,
|
||||
color: AppColors.walletMain,
|
||||
onTap: () => onWallet('main'),
|
||||
),
|
||||
_HistoryFilterChip(
|
||||
@ -746,9 +892,9 @@ class _StatusChip extends StatelessWidget {
|
||||
}
|
||||
|
||||
/// Chip + seconds from the same snapshot, same formula as web
|
||||
/// `useServerAdjustedCountdown`. Ticks come from the screen's 1s [_uiClock]
|
||||
/// — no extra timer and no network per second.
|
||||
class _RoundPhaseHeader extends StatelessWidget {
|
||||
/// `useServerAdjustedCountdown`. Owns a 1s ticker so only this header
|
||||
/// (and the bet panel) rebuild — not the chart or history list.
|
||||
class _RoundPhaseHeader extends StatefulWidget {
|
||||
const _RoundPhaseHeader({
|
||||
required this.round,
|
||||
required this.openLabel,
|
||||
@ -759,9 +905,30 @@ class _RoundPhaseHeader extends StatelessWidget {
|
||||
final String openLabel;
|
||||
final String waitLabel;
|
||||
|
||||
@override
|
||||
State<_RoundPhaseHeader> createState() => _RoundPhaseHeaderState();
|
||||
}
|
||||
|
||||
class _RoundPhaseHeaderState extends State<_RoundPhaseHeader> {
|
||||
Timer? _tick;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (mounted) setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tick?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final current = round;
|
||||
final current = widget.round;
|
||||
if (current == null) {
|
||||
return const Row(
|
||||
children: [
|
||||
@ -784,7 +951,7 @@ class _RoundPhaseHeader extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
isOpen ? openLabel : waitLabel,
|
||||
isOpen ? widget.openLabel : widget.waitLabel,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
Text(
|
||||
|
||||
@ -3,6 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
import '../../../../data/models/prediction_models.dart';
|
||||
import '../../../../l10n/app_strings.dart';
|
||||
import '../../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../bloc/prediction_bloc.dart';
|
||||
import '../../../../data/models/candle_predict_instrument.dart';
|
||||
|
||||
@ -158,15 +159,13 @@ class _CandleChartWidgetState extends State<CandleChartWidget> {
|
||||
if (candles.isEmpty) {
|
||||
return SizedBox(
|
||||
height: CandleChartWidget.chartHeight,
|
||||
child: Center(
|
||||
child: widget.isLoadingOlder
|
||||
? const SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(s.chartNoData),
|
||||
),
|
||||
child: widget.isLoadingOlder
|
||||
? const PredSkeleton(
|
||||
width: double.infinity,
|
||||
height: CandleChartWidget.chartHeight,
|
||||
borderRadius: 12,
|
||||
)
|
||||
: Center(child: Text(s.chartNoData)),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,22 @@
|
||||
import '../../../data/models/prediction_models.dart';
|
||||
|
||||
/// Last candle page per interval — paint instantly when revisiting a chip.
|
||||
class CandleIntervalCache {
|
||||
final Map<int, CandleIntervalPage> _pages = {};
|
||||
|
||||
CandleIntervalPage? peek(int intervalMinutes) => _pages[intervalMinutes];
|
||||
|
||||
void put(int intervalMinutes, CandleIntervalPage page) {
|
||||
_pages[intervalMinutes] = page;
|
||||
}
|
||||
}
|
||||
|
||||
class CandleIntervalPage {
|
||||
const CandleIntervalPage({
|
||||
required this.items,
|
||||
required this.hasMore,
|
||||
});
|
||||
|
||||
final List<OhlcCandleModel> items;
|
||||
final bool hasMore;
|
||||
}
|
||||
@ -64,6 +64,28 @@ ServerAdjustedCountdown serverAdjustedCountdown(
|
||||
);
|
||||
}
|
||||
|
||||
/// True when the local adjusted clock is at (or about to hit) a phase boundary.
|
||||
///
|
||||
/// After open/wait reaches `0s`, the UI stays frozen until WS/HTTP delivers the
|
||||
/// next snapshot. Healthy-WS poll skips can delay that by ~8–20s — the user
|
||||
/// then sees `0s` then jumps mid-window (~49s). Callers must force a state
|
||||
/// resync instead of skipping `/state`.
|
||||
bool countdownNeedsStateResync(RoundModel? round, {int? clientNowMs}) {
|
||||
if (round == null) return false;
|
||||
final adj = serverAdjustedCountdown(round, clientNowMs: clientNowMs);
|
||||
if (adj.bettingOpen) return adj.secondsToBettingEnd <= 1;
|
||||
return adj.secondsToBettingStart <= 1;
|
||||
}
|
||||
|
||||
/// True when the displayed countdown is stuck at `0s` (open expired or wait
|
||||
/// exhausted) and needs a fresher round snapshot to resume.
|
||||
bool countdownStuckAtZero(RoundModel? round, {int? clientNowMs}) {
|
||||
if (round == null) return false;
|
||||
final adj = serverAdjustedCountdown(round, clientNowMs: clientNowMs);
|
||||
if (adj.bettingOpen) return false;
|
||||
return adj.secondsToBettingEnd <= 0 && adj.secondsToBettingStart <= 0;
|
||||
}
|
||||
|
||||
/// True when UI-relevant round fields changed (ignore ticking countdown fields).
|
||||
bool roundUiChanged(RoundModel? prev, RoundModel? next) {
|
||||
if (identical(prev, next)) return false;
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/models/referral_models.dart';
|
||||
import '../../../domain/repositories/referral_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import 'widgets/referral_member_card.dart';
|
||||
|
||||
const _pageSize = 15;
|
||||
@ -20,6 +22,7 @@ class ReferralDirectsScreen extends StatefulWidget {
|
||||
class _ReferralDirectsScreenState extends State<ReferralDirectsScreen> {
|
||||
final _repo = sl<ReferralRepository>();
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
List<ReferralNetworkMember> _members = [];
|
||||
int _visibleCount = _pageSize;
|
||||
@ -27,27 +30,48 @@ class _ReferralDirectsScreenState extends State<ReferralDirectsScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = _repo.peekLastDashboard(maxDepth: 1);
|
||||
if (cached != null) {
|
||||
_members = cached.directMembers;
|
||||
_loading = false;
|
||||
}
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keep = _members.isNotEmpty && !force;
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final dashboard = await _repo.getDashboard(maxDepth: 1);
|
||||
final dashboard = await _repo.getDashboard(maxDepth: 1, force: force || !keep);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_members = dashboard.directMembers;
|
||||
_visibleCount = _pageSize;
|
||||
_loading = false;
|
||||
_error = null;
|
||||
_retrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_members.isEmpty) {
|
||||
_error = e is AppException
|
||||
? e.message
|
||||
: e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -60,53 +84,88 @@ class _ReferralDirectsScreenState extends State<ReferralDirectsScreen> {
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(s.directReferrals)),
|
||||
body: _loading
|
||||
? PredLoadingView(message: s.loading)
|
||||
: _error != null
|
||||
? PredErrorView(message: _error!, onRetry: _load)
|
||||
: RefreshIndicator(
|
||||
onRefresh: _load,
|
||||
child: _members.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.all(40),
|
||||
children: [
|
||||
const Icon(Icons.groups_outlined, size: 48, color: AppColors.textMuted),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noDirectReferrals,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 28),
|
||||
itemCount: visible.length + (remaining > 0 ? 1 : 0),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= visible.length) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_visibleCount = (_visibleCount + _pageSize)
|
||||
.clamp(0, _members.length);
|
||||
});
|
||||
},
|
||||
child: Text(s.loadMoreRemaining(remaining)),
|
||||
);
|
||||
}
|
||||
return ReferralMemberCard(member: visible[index]);
|
||||
},
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
child: _buildBody(s, visible, remaining),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody(
|
||||
AppStrings s,
|
||||
List<ReferralNetworkMember> visible,
|
||||
int remaining,
|
||||
) {
|
||||
if (_loading && _members.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 28),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_error != null && _members.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 28),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_members.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.all(40),
|
||||
children: [
|
||||
const Icon(Icons.groups_outlined, size: 48, color: AppColors.textMuted),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noDirectReferrals,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 28),
|
||||
itemCount: visible.length + (remaining > 0 ? 1 : 0),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= visible.length) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_visibleCount =
|
||||
(_visibleCount + _pageSize).clamp(0, _members.length);
|
||||
});
|
||||
},
|
||||
child: Text(s.loadMoreRemaining(remaining)),
|
||||
);
|
||||
}
|
||||
return ReferralMemberCard(member: visible[index]);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/network/api_client.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/models/referral_models.dart';
|
||||
import '../../../domain/repositories/referral_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import 'widgets/referral_network_tree.dart';
|
||||
|
||||
/// Expandable tree of commission-eligible referral levels.
|
||||
@ -19,6 +21,7 @@ class ReferralNetworkScreen extends StatefulWidget {
|
||||
class _ReferralNetworkScreenState extends State<ReferralNetworkScreen> {
|
||||
final _repo = sl<ReferralRepository>();
|
||||
bool _loading = true;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
ReferralDashboardModel? _dashboard;
|
||||
String? _rootUserId;
|
||||
@ -26,17 +29,31 @@ class _ReferralNetworkScreenState extends State<ReferralNetworkScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = _repo.peekLastDashboard(maxDepth: 10);
|
||||
if (cached != null) {
|
||||
_dashboard = cached;
|
||||
_loading = false;
|
||||
}
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keep = _dashboard != null && !force;
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_error = null;
|
||||
_retrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final results = await Future.wait([
|
||||
_repo.getDashboard(maxDepth: 10),
|
||||
_repo.getDashboard(maxDepth: 10, force: force || !keep),
|
||||
sl<ApiClient>().getStoredUserId(),
|
||||
]);
|
||||
if (!mounted) return;
|
||||
@ -44,12 +61,19 @@ class _ReferralNetworkScreenState extends State<ReferralNetworkScreen> {
|
||||
_dashboard = results[0] as ReferralDashboardModel;
|
||||
_rootUserId = results[1] as String?;
|
||||
_loading = false;
|
||||
_error = null;
|
||||
_retrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_dashboard == null) {
|
||||
_error = e is AppException
|
||||
? e.message
|
||||
: e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -85,45 +109,77 @@ class _ReferralNetworkScreenState extends State<ReferralNetworkScreen> {
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _loading
|
||||
? PredLoadingView(message: s.loading)
|
||||
: _error != null
|
||||
? PredErrorView(message: _error!, onRetry: _load)
|
||||
: RefreshIndicator(
|
||||
onRefresh: _load,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
children: [
|
||||
Text(
|
||||
s.tapToExpand,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (_dashboard != null)
|
||||
ReferralNetworkTree(
|
||||
members: _dashboard!.network,
|
||||
rootUserId: _resolvedRootUserId(_dashboard!),
|
||||
referrer: _dashboard!.referrer,
|
||||
)
|
||||
else
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 40),
|
||||
child: Text(
|
||||
s.noNetworkMembers,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
child: _buildBody(s),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody(AppStrings s) {
|
||||
if (_loading && _dashboard == null) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
children: const [
|
||||
PredSkeletonLine(width: 180, height: 14),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 120),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_error != null && _dashboard == null) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 28),
|
||||
children: [
|
||||
Text(
|
||||
s.tapToExpand,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (_dashboard != null)
|
||||
ReferralNetworkTree(
|
||||
members: _dashboard!.network,
|
||||
rootUserId: _resolvedRootUserId(_dashboard!),
|
||||
referrer: _dashboard!.referrer,
|
||||
)
|
||||
else
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 40),
|
||||
child: Text(
|
||||
s.noNetworkMembers,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../core/utils/amount_utils.dart';
|
||||
import '../../../data/models/referral_models.dart';
|
||||
@ -9,7 +10,8 @@ import '../../../domain/repositories/referral_repository.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
|
||||
class ReferralScreen extends StatefulWidget {
|
||||
const ReferralScreen({super.key});
|
||||
@ -20,41 +22,138 @@ class ReferralScreen extends StatefulWidget {
|
||||
|
||||
class _ReferralScreenState extends State<ReferralScreen> {
|
||||
final _repo = sl<ReferralRepository>();
|
||||
|
||||
/// Hub only needs counts / code / earnings — shallow tree (depth 1).
|
||||
static const _hubDepth = 1;
|
||||
static const _commissionsPageSize = 10;
|
||||
|
||||
ReferralDashboardModel? _dashboard;
|
||||
List<ReferralCommissionModel> _commissions = [];
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
static const _commissionsPageSize = 10;
|
||||
int _visibleCommissions = _commissionsPageSize;
|
||||
|
||||
bool _dashboardLoading = true;
|
||||
bool _commissionsLoading = true;
|
||||
bool _dashboardRetrying = false;
|
||||
bool _commissionsRetrying = false;
|
||||
String? _dashboardError;
|
||||
String? _commissionsError;
|
||||
|
||||
Future<void>? _dashboardInFlight;
|
||||
Future<void>? _commissionsInFlight;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
final cachedDash = _repo.peekLastDashboard(maxDepth: _hubDepth);
|
||||
if (cachedDash != null) {
|
||||
_dashboard = cachedDash;
|
||||
_dashboardLoading = false;
|
||||
}
|
||||
final cachedCommissions = _repo.peekLastCommissions();
|
||||
if (cachedCommissions != null) {
|
||||
_commissions = cachedCommissions.items;
|
||||
_commissionsLoading = false;
|
||||
}
|
||||
_loadDashboard();
|
||||
_loadCommissions();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final dashboard = await _repo.getDashboard(maxDepth: 10);
|
||||
final commissions = await _repo.getCommissions();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_dashboard = dashboard;
|
||||
_commissions = commissions.items;
|
||||
_visibleCommissions = _commissionsPageSize;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
Future<void> _loadDashboard({bool force = false}) {
|
||||
if (_dashboardInFlight != null) return _dashboardInFlight!;
|
||||
final keep = _dashboard != null && !force;
|
||||
final future = () async {
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_dashboardLoading = true;
|
||||
_dashboardError = null;
|
||||
_dashboardRetrying = force;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_dashboardError = null;
|
||||
_dashboardRetrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final dashboard = await _repo.getDashboard(
|
||||
maxDepth: _hubDepth,
|
||||
force: force || !keep,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_dashboard = dashboard;
|
||||
_dashboardLoading = false;
|
||||
_dashboardError = null;
|
||||
_dashboardRetrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_dashboardLoading = false;
|
||||
_dashboardRetrying = false;
|
||||
if (_dashboard == null) {
|
||||
_dashboardError = e is AppException
|
||||
? e.message
|
||||
: e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_dashboardInFlight = future.whenComplete(() => _dashboardInFlight = null);
|
||||
return _dashboardInFlight!;
|
||||
}
|
||||
|
||||
Future<void> _loadCommissions({bool force = false}) {
|
||||
if (_commissionsInFlight != null) return _commissionsInFlight!;
|
||||
final keep = _commissions.isNotEmpty && !force;
|
||||
final future = () async {
|
||||
if (!keep) {
|
||||
setState(() {
|
||||
_commissionsLoading = true;
|
||||
_commissionsError = null;
|
||||
_commissionsRetrying = force;
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
_commissionsError = null;
|
||||
_commissionsRetrying = force;
|
||||
});
|
||||
}
|
||||
try {
|
||||
final page = await _repo.getCommissions(
|
||||
force: force || !keep,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_commissions = page.items;
|
||||
_visibleCommissions = _commissionsPageSize;
|
||||
_commissionsLoading = false;
|
||||
_commissionsError = null;
|
||||
_commissionsRetrying = false;
|
||||
});
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_commissionsLoading = false;
|
||||
_commissionsRetrying = false;
|
||||
if (_commissions.isEmpty) {
|
||||
_commissionsError = e is AppException
|
||||
? e.message
|
||||
: e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}();
|
||||
_commissionsInFlight =
|
||||
future.whenComplete(() => _commissionsInFlight = null);
|
||||
return _commissionsInFlight!;
|
||||
}
|
||||
|
||||
Future<void> _refreshAll() async {
|
||||
await Future.wait([
|
||||
_loadDashboard(force: true),
|
||||
_loadCommissions(force: true),
|
||||
]);
|
||||
}
|
||||
|
||||
/// Navigate after the current pointer/scroll gesture settles to avoid
|
||||
@ -71,249 +170,289 @@ class _ReferralScreenState extends State<ReferralScreen> {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(s.referralTitle)),
|
||||
body: _loading
|
||||
? PredLoadingView(message: s.loading)
|
||||
: _error != null
|
||||
? PredErrorView(message: _error!, onRetry: _load)
|
||||
: RefreshIndicator(
|
||||
onRefresh: _load,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
if (_dashboard != null) ...[
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(s.yourReferralCode,
|
||||
style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SelectableText(
|
||||
_dashboard!.referralCode ?? '—',
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
color: AppColors.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
if ((_dashboard!.referralCode ?? '').isNotEmpty)
|
||||
IconButton(
|
||||
tooltip: s.copy,
|
||||
onPressed: () {
|
||||
Clipboard.setData(
|
||||
ClipboardData(text: _dashboard!.referralCode!),
|
||||
);
|
||||
showSuccessSnackBar(context, s.copied);
|
||||
},
|
||||
icon: const Icon(Icons.copy_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (_dashboard!.referralLink.isNotEmpty) ...[
|
||||
Text(s.inviteLink, style: Theme.of(context).textTheme.bodySmall),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
_dashboard!.referralLink,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: s.copy,
|
||||
onPressed: () {
|
||||
Clipboard.setData(
|
||||
ClipboardData(text: _dashboard!.referralLink),
|
||||
);
|
||||
showSuccessSnackBar(context, s.copied);
|
||||
},
|
||||
icon: const Icon(Icons.copy_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: _refreshAll,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
..._dashboardSection(s),
|
||||
const SizedBox(height: 20),
|
||||
Text(s.recentCommissions, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
..._commissionsSection(s),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _dashboardSection(AppStrings s) {
|
||||
if (_dashboardLoading && _dashboard == null) {
|
||||
return const [
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 100),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 120),
|
||||
];
|
||||
}
|
||||
if (_dashboardError != null && _dashboard == null) {
|
||||
return [
|
||||
SectionError(
|
||||
message: _dashboardError!,
|
||||
retrying: _dashboardRetrying,
|
||||
onRetry: () => _loadDashboard(force: true),
|
||||
),
|
||||
];
|
||||
}
|
||||
final d = _dashboard;
|
||||
if (d == null) return const [];
|
||||
|
||||
return [
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(s.yourReferralCode, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: SelectableText(
|
||||
d.referralCode ?? '—',
|
||||
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
|
||||
color: AppColors.primary,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _StatCard(
|
||||
label: s.directReferrals,
|
||||
value: '${_dashboard!.directReferrals}',
|
||||
icon: Icons.person_add_alt_1_rounded,
|
||||
onTap: () => _openRoute('/referral/directs'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _StatCard(
|
||||
label: s.networkSize,
|
||||
value: '${_dashboard!.networkSize}',
|
||||
icon: Icons.account_tree_rounded,
|
||||
onTap: () => _openRoute('/referral/network'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
onTap: () => _openRoute('/referral/directs'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.groups_rounded, color: AppColors.primary),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.viewDirectReferrals,
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
PredCard(
|
||||
onTap: () => _openRoute('/referral/network'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.lan_rounded, color: AppColors.accentGold),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.viewNetworkTree,
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_dashboard!.referrer != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
s.yourReferrer,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_dashboard!.referrer!.displayName,
|
||||
style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 16),
|
||||
),
|
||||
Text(
|
||||
'${s.memberSince} ${_formatDate(_dashboard!.referrer!.memberSince)}',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(s.earnings, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 12),
|
||||
_EarningRow(
|
||||
label: s.totalEarned,
|
||||
raw: _dashboard!.totalEarnedRaw,
|
||||
),
|
||||
_EarningRow(label: s.paid, raw: _dashboard!.paidRaw),
|
||||
_EarningRow(label: s.pending, raw: _dashboard!.pendingRaw),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_dashboard!.levels.isNotEmpty) ...[
|
||||
const SizedBox(height: 20),
|
||||
Text(s.commissionLevels,
|
||||
style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
..._dashboard!.levels.map(
|
||||
(l) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Text(
|
||||
'${s.level} ${l.levelNumber}: ${l.commissionPercent.toStringAsFixed(1)}%',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
if (_commissions.isNotEmpty) ...[
|
||||
const SizedBox(height: 20),
|
||||
Text(s.recentCommissions,
|
||||
style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
..._commissions.take(_visibleCommissions).map(
|
||||
(c) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
[
|
||||
if (c.referredDisplayName != null)
|
||||
c.referredDisplayName!,
|
||||
'${s.level} ${c.levelNumber}',
|
||||
c.status,
|
||||
].where((e) => e.isNotEmpty).join(' · '),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${rawAmountToHuman(c.amountRaw, 6)} USDT',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_commissions.length > _visibleCommissions)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_visibleCommissions =
|
||||
(_visibleCommissions + _commissionsPageSize)
|
||||
.clamp(0, _commissions.length);
|
||||
});
|
||||
},
|
||||
child: Text(
|
||||
s.loadMoreRemaining(
|
||||
_commissions.length - _visibleCommissions,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
if ((d.referralCode ?? '').isNotEmpty)
|
||||
IconButton(
|
||||
tooltip: s.copy,
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: d.referralCode!));
|
||||
showSuccessSnackBar(context, s.copied);
|
||||
},
|
||||
icon: const Icon(Icons.copy_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (d.referralLink.isNotEmpty) ...[
|
||||
Text(s.inviteLink, style: Theme.of(context).textTheme.bodySmall),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
d.referralLink,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: s.copy,
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: d.referralLink));
|
||||
showSuccessSnackBar(context, s.copied);
|
||||
},
|
||||
icon: const Icon(Icons.copy_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _StatCard(
|
||||
label: s.directReferrals,
|
||||
value: '${d.directReferrals}',
|
||||
icon: Icons.person_add_alt_1_rounded,
|
||||
onTap: () => _openRoute('/referral/directs'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _StatCard(
|
||||
label: s.networkSize,
|
||||
value: '${d.networkSize}',
|
||||
icon: Icons.account_tree_rounded,
|
||||
onTap: () => _openRoute('/referral/network'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
onTap: () => _openRoute('/referral/directs'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.groups_rounded, color: AppColors.primary),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.viewDirectReferrals,
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
PredCard(
|
||||
onTap: () => _openRoute('/referral/network'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.lan_rounded, color: AppColors.accentGold),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.viewNetworkTree,
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
const Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (d.referrer != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(s.yourReferrer, style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
d.referrer!.displayName,
|
||||
style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 16),
|
||||
),
|
||||
Text(
|
||||
'${s.memberSince} ${_formatDate(d.referrer!.memberSince)}',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(s.earnings, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 12),
|
||||
_EarningRow(label: s.totalEarned, raw: d.totalEarnedRaw),
|
||||
_EarningRow(label: s.paid, raw: d.paidRaw),
|
||||
_EarningRow(label: s.pending, raw: d.pendingRaw),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (d.levels.isNotEmpty) ...[
|
||||
const SizedBox(height: 20),
|
||||
Text(s.commissionLevels, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 8),
|
||||
...d.levels.map(
|
||||
(l) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Text(
|
||||
'${s.level} ${l.levelNumber}: ${l.commissionPercent.toStringAsFixed(1)}%',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
List<Widget> _commissionsSection(AppStrings s) {
|
||||
if (_commissionsLoading && _commissions.isEmpty) {
|
||||
return const [
|
||||
PredSkeletonCard(height: 64),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 64),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 64),
|
||||
];
|
||||
}
|
||||
if (_commissionsError != null && _commissions.isEmpty) {
|
||||
return [
|
||||
SectionError(
|
||||
message: _commissionsError!,
|
||||
retrying: _commissionsRetrying,
|
||||
onRetry: () => _loadCommissions(force: true),
|
||||
),
|
||||
];
|
||||
}
|
||||
if (_commissions.isEmpty) {
|
||||
return [
|
||||
PredCard(
|
||||
child: Text(
|
||||
s.noCommissionsYet,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
return [
|
||||
..._commissions.take(_visibleCommissions).map(
|
||||
(c) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
[
|
||||
if (c.referredDisplayName != null) c.referredDisplayName!,
|
||||
'${s.level} ${c.levelNumber}',
|
||||
c.status,
|
||||
].where((e) => e.isNotEmpty).join(' · '),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${rawAmountToHuman(c.amountRaw, 6)} USDT',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_commissions.length > _visibleCommissions)
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_visibleCommissions =
|
||||
(_visibleCommissions + _commissionsPageSize)
|
||||
.clamp(0, _commissions.length);
|
||||
});
|
||||
},
|
||||
child: Text(
|
||||
s.loadMoreRemaining(_commissions.length - _visibleCommissions),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
String _formatDate(String iso) {
|
||||
@ -374,8 +513,10 @@ class _EarningRow extends StatelessWidget {
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(label),
|
||||
Text('${rawAmountToHuman(raw, 6)} USDT',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Text(
|
||||
'${rawAmountToHuman(raw, 6)} USDT',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -10,7 +10,33 @@ import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/prediqo_logo.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
/// Minimum branding dwell before leaving splash (real session still required).
|
||||
const Duration kSplashMinBrandingDelay = Duration(milliseconds: 1200);
|
||||
|
||||
/// Semver-ish compare: true when [latest] is strictly newer than [current].
|
||||
bool splashIsNewerVersion(String latest, String current) {
|
||||
List<int> parts(String v) =>
|
||||
v.split('.').map((e) => int.tryParse(e.replaceAll(RegExp(r'[^0-9]'), '')) ?? 0).toList();
|
||||
final a = parts(latest);
|
||||
final b = parts(current);
|
||||
final len = a.length > b.length ? a.length : b.length;
|
||||
for (var i = 0; i < len; i++) {
|
||||
final x = i < a.length ? a[i] : 0;
|
||||
final y = i < b.length ? b[i] : 0;
|
||||
if (x > y) return true;
|
||||
if (x < y) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// True while splash must still wait for a real session check result.
|
||||
bool splashShouldWaitForAuth(AuthStatus status) =>
|
||||
status == AuthStatus.loading || status == AuthStatus.initial;
|
||||
|
||||
/// Branded splash while session and light bootstrap checks run.
|
||||
///
|
||||
/// Never navigates on a guessed/fake session — only after auth leaves
|
||||
/// [AuthStatus.initial]/[AuthStatus.loading], and not before [kSplashMinBrandingDelay].
|
||||
class SplashScreen extends StatefulWidget {
|
||||
const SplashScreen({super.key});
|
||||
|
||||
@ -29,21 +55,26 @@ class _SplashScreenState extends State<SplashScreen> {
|
||||
}
|
||||
|
||||
Future<void> _bootstrap() async {
|
||||
final minDelay = Future<void>.delayed(const Duration(milliseconds: 1200));
|
||||
final minDelay = Future<void>.delayed(kSplashMinBrandingDelay);
|
||||
final versionCheck = _checkAppUpdate();
|
||||
|
||||
final authBloc = context.read<AuthBloc>();
|
||||
// Belt-and-suspenders: factory usually fires AuthCheckRequested; ensure it runs.
|
||||
if (authBloc.state.status == AuthStatus.initial) {
|
||||
authBloc.add(const AuthCheckRequested());
|
||||
}
|
||||
|
||||
Future<void> waitAuth() async {
|
||||
if (authBloc.state.status == AuthStatus.loading ||
|
||||
authBloc.state.status == AuthStatus.initial) {
|
||||
if (splashShouldWaitForAuth(authBloc.state.status)) {
|
||||
await authBloc.stream.firstWhere(
|
||||
(s) => s.status != AuthStatus.loading && s.status != AuthStatus.initial,
|
||||
(s) => !splashShouldWaitForAuth(s.status),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await Future.wait([minDelay, versionCheck, waitAuth()]);
|
||||
if (!mounted || _navigated) return;
|
||||
// Route only from the real post-check auth state (never invent a session).
|
||||
_navigated = true;
|
||||
final signedIn = authBloc.state.isSignedIn;
|
||||
context.go(signedIn ? '/home' : '/welcome');
|
||||
@ -56,25 +87,10 @@ class _SplashScreenState extends State<SplashScreen> {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
if (!mounted) return;
|
||||
setState(() => _updateAvailable = _isNewerVersion(latest, info.version));
|
||||
setState(() => _updateAvailable = splashIsNewerVersion(latest, info.version));
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
bool _isNewerVersion(String latest, String current) {
|
||||
List<int> parts(String v) =>
|
||||
v.split('.').map((e) => int.tryParse(e.replaceAll(RegExp(r'[^0-9]'), '')) ?? 0).toList();
|
||||
final a = parts(latest);
|
||||
final b = parts(current);
|
||||
final len = a.length > b.length ? a.length : b.length;
|
||||
for (var i = 0; i < len; i++) {
|
||||
final x = i < a.length ? a[i] : 0;
|
||||
final y = i < b.length ? b[i] : 0;
|
||||
if (x > y) return true;
|
||||
if (x < y) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user