After adding the idea of the real market

This commit is contained in:
Your Name 2026-11-09 18:14:42 +02:00
parent f2cad66cd2
commit ebf64f40d7
65 changed files with 1800 additions and 296 deletions

View File

@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAoEH,kFAAkF;AAClF,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;YAoBb,kIAAkI;;;;;;;YAOlI,iFAAiF;;;;;YAKjF;;;;eAIG;;YAKH,mFAAmF;;;;YAInF;;;eAGG;;YAKH,8EAA8E;;YAK9E;;;;eAIG;;YAEH,uEAAuE;;YAEvE;;;eAGG;;YAEH,4DAA4D;;;;;;;;;;;;QAgB9D,kFAAkF;;QAElF,4FAA4F;;;;;QAQ5F,6FAA6F;;QAE7F,8EAA8E;;;;QAI9E,kEAAkE;;QAElE;;;WAGG;;QAEH;;;WAGG;;QAEH;;;WAGG;;;QAMH,gDAAgD;;QAEhD,0DAA0D;;QAE1D;;;WAGG;;QAEH,2DAA2D;;;;QAI3D,iFAAiF;;;;QAIjF,yDAAyD;;;;QAOzD,6FAA6F;;;;QAI7F,gEAAgE;;;;;;;;;;QAUhE,+DAA+D;;;;;;;QAO/D,4EAA4E;;QAE5E,qEAAqE;;;;;;;;QAQrE,iEAAiE;;QAEjE,8DAA8D;;QAE9D,4DAA4D;;;;;QAK5D,oEAAoE;;QAIpE,6DAA6D;;QAE7D,2EAA2E;;;;;;;;;;IAU7E,mFAAmF;;;QAGjF;;;WAGG;;;;;;;;;;;;;;;;;;QAuBH,yGAAyG;;;;QAIzG,8EAA8E;;;;IAOhF,sFAAsF;;;;;;IAMtF,qEAAqE;;;;;;;;;;;;;;;CAetE,CAAC"}
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAoEH,kFAAkF;AAClF,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;YAoBb,kIAAkI;;;;;;;YAOlI,iFAAiF;;;;;YAKjF;;;;eAIG;;YAKH,mFAAmF;;;;YAInF;;;eAGG;;YAKH,8EAA8E;;YAK9E;;;;eAIG;;YAEH,uEAAuE;;YAEvE;;;eAGG;;YAEH,4DAA4D;;;;;;;;;;;;QAgB9D,kFAAkF;;QAElF,4FAA4F;;;;;QAQ5F,6FAA6F;;QAE7F,8EAA8E;;;;QAI9E,kEAAkE;;QAElE;;;WAGG;;QAEH;;;WAGG;;QAEH;;;WAGG;;;QAMH,gDAAgD;;QAEhD,0DAA0D;;QAE1D;;;WAGG;;QAEH,2DAA2D;;;;QAI3D,iFAAiF;;;;QAIjF,yDAAyD;;;;QAOzD,6FAA6F;;;;QAI7F,gEAAgE;;;;;;;;;;QAUhE,+DAA+D;;;;;;;QAO/D,4EAA4E;;QAE5E,qEAAqE;;;;;;;;QAQrE,iEAAiE;;QAEjE,8DAA8D;;QAE9D,4DAA4D;;;;;QAK5D,oEAAoE;;QAIpE,6DAA6D;;QAE7D,2EAA2E;;;;;;;;;;IAU7E,mFAAmF;;;QAGjF;;;WAGG;;;;;;;;;;;;;;;;;;QA6BH,yGAAyG;;;;QAIzG,8EAA8E;;;;IAOhF,sFAAsF;;;;;;IAMtF,qEAAqE;;;;;;;;;;;;;;;CAetE,CAAC"}

View File

@ -278,7 +278,15 @@ exports.config = {
tracesSampleRate: Math.min(1, Math.max(0, parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE || '0.1'))),
},
clamav: {
enabled: process.env.CLAMAV_ENABLED === 'true',
// Production: on by default. Explicit CLAMAV_ENABLED=false disables; =true forces on in any env.
enabled: (() => {
const raw = (process.env.CLAMAV_ENABLED || '').trim().toLowerCase();
if (raw === 'true' || raw === '1' || raw === 'yes')
return true;
if (raw === 'false' || raw === '0' || raw === 'no')
return false;
return (process.env.NODE_ENV || 'development') === 'production';
})(),
host: process.env.CLAMAV_HOST || '127.0.0.1',
port: parseInt(process.env.CLAMAV_PORT || '3310', 10),
timeoutMs: readEnvInt('CLAMAV_TIMEOUT_MS', 30000, 5000, 120000),

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"file":"faqController.d.ts","sourceRoot":"","sources":["../../src/controllers/faqController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAgBjD,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAMtF;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAW/E;AAED,wBAAsB,eAAe,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOhF;AAED,wBAAsB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAM7E;AAED,wBAAsB,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAM3E;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CASlF;AAED,wBAAsB,UAAU,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAY3E;AAED,kEAAkE;AAClE,wBAAsB,wBAAwB,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBzF;AAED,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IA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,CAWxF;AAED,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAWxF;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAclF;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAUnF;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAWnF;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAMnF;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BrF;AAED,wBAAsB,2BAA2B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA6BhG;AAED,wBAAsB,2BAA2B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAYhG"}

View File

@ -32,9 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.listPublicCategories = listPublicCategories;
exports.listPublicFaqs = listPublicFaqs;
@ -55,11 +52,8 @@ exports.adminDeleteFaq = adminDeleteFaq;
exports.adminUploadMedia = adminUploadMedia;
exports.adminUploadCategoryDocument = adminUploadCategoryDocument;
exports.adminDeleteCategoryDocument = adminDeleteCategoryDocument;
const path_1 = __importDefault(require("path"));
const faqUpload_1 = require("../middleware/faqUpload");
const fileIntegrityService_1 = require("../services/fileIntegrityService");
const fileMagic_1 = require("../utils/fileMagic");
const uploadValidation_1 = require("../utils/uploadValidation");
const faqService = __importStar(require("../services/faqService"));
function handleError(res, e) {
const msg = e instanceof Error ? e.message : 'Request failed';
@ -128,13 +122,16 @@ async function recordHelpful(req, res) {
}
async function getFaqFile(req, res) {
try {
const filePath = faqService.readFaqFile(req.params.filename);
if (!filePath) {
const resolved = await faqService.resolvePublicFaqFile(req.params.filename);
if (!resolved) {
res.status(404).json({ error: 'File not found' });
return;
}
res.setHeader('Content-Type', resolved.mime);
res.setHeader('Content-Disposition', faqService.faqFileContentDisposition(resolved.downloadName, resolved.mime));
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.sendFile(filePath);
res.sendFile(resolved.filePath);
}
catch (e) {
handleError(res, e);
@ -150,7 +147,8 @@ async function downloadCategoryDocument(req, res) {
return;
}
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="${resolved.downloadName.replace(/"/g, '')}"`);
res.setHeader('Content-Disposition', faqService.faqFileContentDisposition(resolved.downloadName, 'application/pdf'));
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.sendFile(resolved.filePath);
}
@ -248,24 +246,26 @@ async function adminUploadMedia(req, res) {
res.status(400).json({ error: 'No file uploaded' });
return;
}
const filePath = path_1.default.join((0, faqUpload_1.ensureFaqUploadDir)(), req.file.filename);
try {
await (0, uploadValidation_1.validateUploadedFile)(filePath, faqUpload_1.FAQ_ALLOWED_MIMES);
const saved = await faqService.finalizeFaqUpload({
tempFilename: req.file.filename,
originalName: req.file.originalname,
kind: 'media',
uploadedByUserId: req.user?.userId ?? null,
allowedMimes: faqUpload_1.FAQ_ALLOWED_MIMES,
});
res.status(201).json({
url: saved.url,
filename: saved.filename,
mimeType: saved.mime,
originalName: saved.originalName,
});
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(filePath);
(0, fileMagic_1.removeUploadedFile)(faqService.resolveFaqFilePath(req.file.filename));
const msg = e instanceof Error ? e.message : 'File validation failed';
res.status(msg.includes('virus') ? 422 : 400).json({ error: msg });
return;
res.status(msg.toLowerCase().includes('virus') ? 422 : 400).json({ error: msg });
}
const url = faqService.publicFaqFileUrl(req.file.filename);
await (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.faq, req.file.filename);
res.status(201).json({
url,
filename: req.file.filename,
mimeType: req.file.mimetype,
originalName: req.file.originalname,
});
}
catch (e) {
handleError(res, e);
@ -286,15 +286,16 @@ async function adminUploadCategoryDocument(req, res) {
const item = await faqService.uploadCategoryDocument({
categoryId: id,
lang,
storedFilename: req.file.filename,
tempFilename: req.file.filename,
originalName: req.file.originalname,
byteSize: req.file.size,
uploadedByUserId: req.user?.userId ?? null,
});
res.status(201).json(item);
}
catch (e) {
const msg = e instanceof Error ? e.message : 'Upload failed';
if (msg.includes('virus')) {
if (msg.toLowerCase().includes('virus')) {
res.status(422).json({ error: msg });
return;
}

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"file":"supportController.d.ts","sourceRoot":"","sources":["../../src/controllers/supportController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAGnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAqCjD,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAO5F;AAED,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAQvF;AAED,wBAAsB,6BAA6B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GA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AAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB5F;AAED,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,CA2B1F;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"}

View File

@ -32,9 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrCreateConversation = getOrCreateConversation;
exports.postCurrentMessage = postCurrentMessage;
@ -57,13 +54,10 @@ exports.adminUnreadCount = adminUnreadCount;
exports.adminUploadAttachment = adminUploadAttachment;
exports.adminSendWithAttachment = adminSendWithAttachment;
exports.userSendWithAttachment = userSendWithAttachment;
const fs_1 = __importDefault(require("fs"));
const optionalAuth_1 = require("../middleware/optionalAuth");
const supportUpload_1 = require("../middleware/supportUpload");
const fileMagic_1 = require("../utils/fileMagic");
const uploadValidation_1 = require("../utils/uploadValidation");
const authService_1 = require("../services/authService");
const supportService = __importStar(require("../services/supportService"));
const fileIntegrityService_1 = require("../services/fileIntegrityService");
function buildCtx(req) {
return {
userId: req.user?.userId,
@ -190,23 +184,24 @@ async function uploadCurrentAttachment(req, res) {
res.status(400).json({ error: 'No file uploaded' });
return;
}
const filePath = supportService.resolveUploadPath(req.file.filename);
const ctx = buildCtx(req);
try {
await (0, uploadValidation_1.validateUploadedFile)(filePath, supportUpload_1.SUPPORT_ALLOWED_MIMES);
const saved = await supportService.finalizeSupportUpload({
tempFilename: req.file.filename,
originalName: req.file.originalname,
ctx,
});
res.status(201).json({
attachmentUrl: saved.url,
attachmentName: saved.originalName,
attachmentMime: saved.mime,
});
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(filePath);
(0, fileMagic_1.removeUploadedFile)(supportService.resolveUploadPath(req.file.filename));
const msg = e instanceof Error ? e.message : 'File validation failed';
res.status(msg.includes('virus') ? 422 : 400).json({ error: msg });
return;
res.status(msg.toLowerCase().includes('virus') ? 422 : 400).json({ error: msg });
}
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);
@ -218,24 +213,30 @@ async function uploadAttachment(req, res) {
res.status(400).json({ error: 'No file uploaded' });
return;
}
const filePath = supportService.resolveUploadPath(req.file.filename);
const ctx = buildCtx(req);
try {
await (0, uploadValidation_1.validateUploadedFile)(filePath, supportUpload_1.SUPPORT_ALLOWED_MIMES);
await supportService.assertConversationAccess(req.params.id, ctx);
const saved = await supportService.finalizeSupportUpload({
tempFilename: req.file.filename,
originalName: req.file.originalname,
conversationId: req.params.id,
ctx,
});
res.status(201).json({
attachmentUrl: saved.url,
attachmentName: saved.originalName,
attachmentMime: saved.mime,
});
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(filePath);
(0, fileMagic_1.removeUploadedFile)(supportService.resolveUploadPath(req.file.filename));
const msg = e instanceof Error ? e.message : 'File validation failed';
res.status(msg.includes('virus') ? 422 : 400).json({ error: msg });
if (msg === 'Forbidden' || msg === 'Conversation not found') {
handleError(res, e);
return;
}
await supportService.assertConversationAccess(req.params.id, buildCtx(req));
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,
});
res.status(msg.toLowerCase().includes('virus') ? 422 : 400).json({ error: msg });
}
}
catch (e) {
handleError(res, e);
@ -243,14 +244,32 @@ async function uploadAttachment(req, res) {
}
async function getAttachment(req, res) {
try {
const filePath = supportService.resolveUploadPath(req.params.filename);
if (!fs_1.default.existsSync(filePath)) {
res.status(404).json({ error: 'File not found' });
// <img src> cannot send Authorization — accept accessToken query as fallback.
if (!req.user) {
const q = req.query.accessToken;
if (typeof q === 'string' && q.trim()) {
try {
req.user = await (0, authService_1.verifyToken)(q.trim());
}
catch {
res.status(401).json({ error: 'Invalid or expired token' });
return;
}
}
}
const ctx = buildCtx(req);
if (!ctx.userId && !ctx.visitorToken && !supportService.isStaffRole(ctx.role)) {
res.status(401).json({ error: 'Authentication required' });
return;
}
const access = await supportService.assertSupportFileDownloadAccess(req.params.filename, ctx);
const downloadName = access.originalName || req.params.filename;
res.setHeader('Content-Type', access.mime);
res.setHeader('Content-Disposition', supportService.attachmentContentDisposition(downloadName));
res.setHeader('X-Content-Type-Options', 'nosniff');
// 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);
res.sendFile(access.filePath);
}
catch (e) {
handleError(res, e);
@ -338,23 +357,25 @@ async function adminUploadAttachment(req, res) {
res.status(400).json({ error: 'No file uploaded' });
return;
}
const filePath = supportService.resolveUploadPath(req.file.filename);
const ctx = buildCtx(req);
try {
await (0, uploadValidation_1.validateUploadedFile)(filePath, supportUpload_1.SUPPORT_ALLOWED_MIMES);
const saved = await supportService.finalizeSupportUpload({
tempFilename: req.file.filename,
originalName: req.file.originalname,
conversationId: req.params.id,
ctx,
});
res.status(201).json({
attachmentUrl: saved.url,
attachmentName: saved.originalName,
attachmentMime: saved.mime,
});
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(filePath);
(0, fileMagic_1.removeUploadedFile)(supportService.resolveUploadPath(req.file.filename));
const msg = e instanceof Error ? e.message : 'File validation failed';
res.status(msg.includes('virus') ? 422 : 400).json({ error: msg });
return;
res.status(msg.toLowerCase().includes('virus') ? 422 : 400).json({ error: msg });
}
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);

File diff suppressed because one or more lines are too long

View File

@ -6,8 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.faqUpload = exports.FAQ_ALLOWED_MIMES = void 0;
exports.ensureFaqUploadDir = ensureFaqUploadDir;
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid");
const MAX_BYTES = 10 * 1024 * 1024;
exports.FAQ_ALLOWED_MIMES = new Set([
@ -27,9 +27,9 @@ const storage = multer_1.default.diskStorage({
destination(_req, _file, cb) {
cb(null, ensureFaqUploadDir());
},
filename(_req, file, cb) {
const ext = path_1.default.extname(file.originalname).slice(0, 20);
cb(null, `${(0, uuid_1.v4)()}${ext}`);
filename(_req, _file, cb) {
// Temporary name — controller renames to uuid + extension from detected MIME.
cb(null, `${(0, uuid_1.v4)()}.upload`);
},
});
exports.faqUpload = (0, multer_1.default)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O;IACP,MAAM,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE;IACzC,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QACvB,IAAI,yBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YACzC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,EAAE,CAAC,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;CACF,CAAC,CAAC"}

View File

@ -1 +1 @@
{"version":3,"file":"supportUpload.d.ts","sourceRoot":"","sources":["../../src/middleware/supportUpload.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAM5B,eAAO,MAAM,qBAAqB,aAShC,CAAC;AAYH,eAAO,MAAM,aAAa,eAUxB,CAAC"}
{"version":3,"file":"supportUpload.d.ts","sourceRoot":"","sources":["../../src/middleware/supportUpload.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,QAAQ,CAAC;AAK5B,eAAO,MAAM,qBAAqB,aAShC,CAAC;AAYH,eAAO,MAAM,aAAa,eAUxB,CAAC"}

View File

@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.supportUpload = exports.SUPPORT_ALLOWED_MIMES = void 0;
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid");
const supportService_1 = require("../services/supportService");
const MAX_BYTES = 8 * 1024 * 1024;
@ -23,9 +22,9 @@ const storage = multer_1.default.diskStorage({
destination(_req, _file, cb) {
cb(null, (0, supportService_1.ensureUploadDir)());
},
filename(_req, file, cb) {
const ext = path_1.default.extname(file.originalname).slice(0, 20);
cb(null, `${(0, uuid_1.v4)()}${ext}`);
filename(_req, _file, cb) {
// Temporary name only — controller renames to uuid + extension from detected MIME.
cb(null, `${(0, uuid_1.v4)()}.upload`);
},
});
exports.supportUpload = (0, multer_1.default)({

View File

@ -1 +1 @@
{"version":3,"file":"supportUpload.js","sourceRoot":"","sources":["../../src/middleware/supportUpload.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA4B;AAC5B,gDAAwB;AACxB,+BAAoC;AACpC,+DAA6D;AAE7D,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACrB,QAAA,qBAAqB,GAAG,IAAI,GAAG,CAAC;IAC3C,YAAY;IACZ,WAAW;IACX,WAAW;IACX,YAAY;IACZ,iBAAiB;IACjB,YAAY;IACZ,oBAAoB;IACpB,yEAAyE;CAC1E,CAAC,CAAC;AAEH,MAAM,OAAO,GAAG,gBAAM,CAAC,WAAW,CAAC;IACjC,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACzB,EAAE,CAAC,IAAI,EAAE,IAAA,gCAAe,GAAE,CAAC,CAAC;IAC9B,CAAC;IACD,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QACrB,MAAM,GAAG,GAAG,cAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QACzD,EAAE,CAAC,IAAI,EAAE,GAAG,IAAA,SAAM,GAAE,GAAG,GAAG,EAAE,CAAC,CAAC;IAChC,CAAC;CACF,CAAC,CAAC;AAEU,QAAA,aAAa,GAAG,IAAA,gBAAM,EAAC;IAClC,OAAO;IACP,MAAM,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE;IACzC,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QACvB,IAAI,6BAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7C,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,EAAE,CAAC,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF,CAAC,CAAC"}
{"version":3,"file":"supportUpload.js","sourceRoot":"","sources":["../../src/middleware/supportUpload.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA4B;AAC5B,+BAAoC;AACpC,+DAA6D;AAE7D,MAAM,SAAS,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACrB,QAAA,qBAAqB,GAAG,IAAI,GAAG,CAAC;IAC3C,YAAY;IACZ,WAAW;IACX,WAAW;IACX,YAAY;IACZ,iBAAiB;IACjB,YAAY;IACZ,oBAAoB;IACpB,yEAAyE;CAC1E,CAAC,CAAC;AAEH,MAAM,OAAO,GAAG,gBAAM,CAAC,WAAW,CAAC;IACjC,WAAW,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACzB,EAAE,CAAC,IAAI,EAAE,IAAA,gCAAe,GAAE,CAAC,CAAC;IAC9B,CAAC;IACD,QAAQ,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QACtB,mFAAmF;QACnF,EAAE,CAAC,IAAI,EAAE,GAAG,IAAA,SAAM,GAAE,SAAS,CAAC,CAAC;IACjC,CAAC;CACF,CAAC,CAAC;AAEU,QAAA,aAAa,GAAG,IAAA,gBAAM,EAAC;IAClC,OAAO;IACP,MAAM,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,EAAE;IACzC,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QACvB,IAAI,6BAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC7C,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,EAAE,CAAC,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC,CAAC;QACzC,CAAC;IACH,CAAC;CACF,CAAC,CAAC"}

View File

@ -67,4 +67,27 @@ export declare function updateEntry(id: string, patch: Partial<{
}>): Promise<FaqEntryRow | null>;
export declare function deleteEntry(id: string): Promise<boolean>;
export declare function countEntriesInCategory(categoryId: number): Promise<number>;
export type FaqUploadedFileRow = {
filename: string;
mime: string;
original_name: string | null;
kind: 'media' | 'category_pdf';
category_id: number | null;
uploaded_by_user_id: string | null;
created_at: Date;
};
export declare function insertUploadedFile(input: {
filename: string;
mime: string;
originalName?: string | null;
kind: 'media' | 'category_pdf';
categoryId?: number | null;
uploadedByUserId?: string | null;
}): Promise<FaqUploadedFileRow>;
export declare function findUploadedFile(filename: string): Promise<FaqUploadedFileRow | null>;
export declare function deleteUploadedFile(filename: string): Promise<void>;
/** True if filename is still referenced as a category PDF pointer. */
export declare function isCategoryPdfFilename(filename: string): Promise<boolean>;
/** Legacy media: referenced from an FAQ answer HTML body. */
export declare function isReferencedInFaqAnswerHtml(filename: string): Promise<boolean>;
//# sourceMappingURL=faqRepository.d.ts.map

View File

@ -1 +1 @@
{"version":3,"file":"faqRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/faqRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElE,MAAM,MAAM,oBAAoB,GAAG,WAAW,GAAG;IAC/C,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,oBAAoB,GAAG;IACpD,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,CAAC;AAEF,wBAAsB,cAAc,CAAC,UAAU,UAAQ,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CASlF;AAED,wBAAsB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAGhF;AAED,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,MAAM,G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AI,CAAC;IAC7B,IAAI,EAAE,OAAO,GAAG,cAAc,CAAC;IAC/B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,UAAU,EAAE,IAAI,CAAC;CAClB,CAAC;AAEF,wBAAsB,kBAAkB,CAAC,KAAK,EAAE;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,IAAI,EAAE,OAAO,GAAG,cAAc,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAsB9B;AAED,wBAAsB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAM3F;AAED,wBAAsB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAExE;AAED,sEAAsE;AACtE,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ9E;AAED,6DAA6D;AAC7D,wBAAsB,2BAA2B,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CASpF"}

View File

@ -18,6 +18,11 @@ exports.createEntry = createEntry;
exports.updateEntry = updateEntry;
exports.deleteEntry = deleteEntry;
exports.countEntriesInCategory = countEntriesInCategory;
exports.insertUploadedFile = insertUploadedFile;
exports.findUploadedFile = findUploadedFile;
exports.deleteUploadedFile = deleteUploadedFile;
exports.isCategoryPdfFilename = isCategoryPdfFilename;
exports.isReferencedInFaqAnswerHtml = isReferencedInFaqAnswerHtml;
const connection_1 = require("../db/connection");
async function listCategories(activeOnly = false) {
if (activeOnly) {
@ -241,4 +246,46 @@ async function countEntriesInCategory(categoryId) {
const rows = await (0, connection_1.query)(`SELECT COUNT(*)::text AS count FROM faq_entries WHERE category_id = $1`, [categoryId]);
return Number(rows[0]?.count ?? 0);
}
async function insertUploadedFile(input) {
const rows = await (0, connection_1.query)(`INSERT INTO faq_uploaded_files (
filename, mime, original_name, kind, category_id, uploaded_by_user_id
) VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (filename) DO UPDATE SET
mime = EXCLUDED.mime,
original_name = EXCLUDED.original_name,
kind = EXCLUDED.kind,
category_id = EXCLUDED.category_id,
uploaded_by_user_id = COALESCE(EXCLUDED.uploaded_by_user_id, faq_uploaded_files.uploaded_by_user_id)
RETURNING *`, [
input.filename,
input.mime,
input.originalName ?? null,
input.kind,
input.categoryId ?? null,
input.uploadedByUserId ?? null,
]);
return rows[0];
}
async function findUploadedFile(filename) {
const rows = await (0, connection_1.query)(`SELECT * FROM faq_uploaded_files WHERE filename = $1`, [filename]);
return rows[0] ?? null;
}
async function deleteUploadedFile(filename) {
await (0, connection_1.query)(`DELETE FROM faq_uploaded_files WHERE filename = $1`, [filename]);
}
/** True if filename is still referenced as a category PDF pointer. */
async function isCategoryPdfFilename(filename) {
const rows = await (0, connection_1.query)(`SELECT 1 AS ok FROM faq_categories
WHERE pdf_fr_filename = $1 OR pdf_en_filename = $1
LIMIT 1`, [filename]);
return rows.length > 0;
}
/** Legacy media: referenced from an FAQ answer HTML body. */
async function isReferencedInFaqAnswerHtml(filename) {
const needle = `%/faq/files/${filename}%`;
const rows = await (0, connection_1.query)(`SELECT 1 AS ok FROM faq_entries
WHERE answer_html ILIKE $1
LIMIT 1`, [needle]);
return rows.length > 0;
}
//# sourceMappingURL=faqRepository.js.map

File diff suppressed because one or more lines are too long

View File

@ -59,4 +59,26 @@ export declare function getUserContextForSupport(userId: string): Promise<{
export declare function getStaffDisplayName(userId: string): Promise<string | null>;
/** Attach every open visitor conversation to the user and rewrite visitor senders. */
export declare function mergeAllVisitorConversationsToUser(visitorToken: string, userId: string): Promise<number>;
export type SupportUploadedFileRow = {
filename: string;
mime: string;
original_name: string | null;
conversation_id: string | null;
uploaded_by_user_id: string | null;
visitor_token: string | null;
created_at: Date;
};
export declare function insertUploadedFile(input: {
filename: string;
mime: string;
originalName?: string | null;
conversationId?: string | null;
uploadedByUserId?: string | null;
visitorToken?: string | null;
}): Promise<SupportUploadedFileRow>;
export declare function findUploadedFile(filename: string): Promise<SupportUploadedFileRow | null>;
export declare function bindUploadedFileConversation(filename: string, conversationId: string): Promise<void>;
export declare function findMessageByAttachmentFilename(filename: string): Promise<{
conversation_id: string;
} | null>;
//# sourceMappingURL=supportRepository.d.ts.map

View File

@ -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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X,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,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,EA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QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CAM/F;AAED,wBAAsB,4BAA4B,CAChD,QAAQ,EAAE,MAAM,EAChB,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,IAAI,CAAC,CAOf;AAED,wBAAsB,+BAA+B,CACnD,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC;IAAE,eAAe,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAc7C"}

View File

@ -22,6 +22,10 @@ exports.countUnreadStaffInbox = countUnreadStaffInbox;
exports.getUserContextForSupport = getUserContextForSupport;
exports.getStaffDisplayName = getStaffDisplayName;
exports.mergeAllVisitorConversationsToUser = mergeAllVisitorConversationsToUser;
exports.insertUploadedFile = insertUploadedFile;
exports.findUploadedFile = findUploadedFile;
exports.bindUploadedFileConversation = bindUploadedFileConversation;
exports.findMessageByAttachmentFilename = findMessageByAttachmentFilename;
const connection_1 = require("../db/connection");
async function findConversationById(id) {
const rows = await (0, connection_1.query)('SELECT * FROM support_conversations WHERE id = $1', [id]);
@ -255,4 +259,39 @@ async function mergeAllVisitorConversationsToUser(visitorToken, userId) {
WHERE conversation_id = ANY($1::uuid[]) AND sender_type = 'visitor'`, [ids, userId]);
return rows.length;
}
async function insertUploadedFile(input) {
const rows = await (0, connection_1.query)(`INSERT INTO support_uploaded_files (
filename, mime, original_name, conversation_id, uploaded_by_user_id, visitor_token
) VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *`, [
input.filename,
input.mime,
input.originalName ?? null,
input.conversationId ?? null,
input.uploadedByUserId ?? null,
input.visitorToken ?? null,
]);
return rows[0];
}
async function findUploadedFile(filename) {
const rows = await (0, connection_1.query)(`SELECT * FROM support_uploaded_files WHERE filename = $1`, [filename]);
return rows[0] ?? null;
}
async function bindUploadedFileConversation(filename, conversationId) {
await (0, connection_1.query)(`UPDATE support_uploaded_files
SET conversation_id = COALESCE(conversation_id, $2)
WHERE filename = $1`, [filename, conversationId]);
}
async function findMessageByAttachmentFilename(filename) {
const suffix = `%/support/files/${filename}`;
const rows = await (0, connection_1.query)(`SELECT conversation_id FROM support_messages
WHERE attachment_url IS NOT NULL
AND (
attachment_url = $1
OR attachment_url LIKE $2
)
ORDER BY created_at DESC
LIMIT 1`, [`/api/v1/support/files/${filename}`, suffix]);
return rows[0] ?? null;
}
//# sourceMappingURL=supportRepository.js.map

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAwJH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAqsBxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAwJH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAysBxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}

View File

@ -131,7 +131,7 @@ router.get('/app-updates/android', (0, validate_1.validateQuery)(mobileReleaseSc
router.get('/app-updates/android/download/:id', (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.downloadAndroid);
router.post('/app-updates/android/events', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(mobileReleaseSchemas_1.mobileUpdateEventBodySchema), mobileAppReleaseController.postEvent);
/** Support messaging — guests (visitor token) and optional authenticated users. */
router.get('/support/files/:filename', supportController.getAttachment);
router.get('/support/files/:filename', optionalAuth_1.optionalAuthMiddleware, 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);

File diff suppressed because one or more lines are too long

View File

@ -62,5 +62,27 @@ export declare function sendTotpDisabledEmail(to: string, ctx: SecurityEmailCont
export declare function sendRolesChangedEmail(to: string, roles: string[], ctx: SecurityEmailContext): Promise<void>;
/** Notifies the user that their effective permissions were updated. */
export declare function sendPermissionsChangedEmail(to: string, permissions: string[], ctx: SecurityEmailContext): Promise<void>;
type WalletEmailPayload = {
amountUsdt: string;
feeUsdt?: string;
totalUsdt?: string;
toAddressMasked?: string | null;
network?: string;
pendingApproval?: boolean;
statusNote?: string;
blockchainTxId?: string | null;
reason?: string;
counterpartyEmailMasked?: string;
};
/** Withdrawal request received (pending review or processing). */
export declare function sendWithdrawalSubmittedEmail(to: string, p: WalletEmailPayload): Promise<void>;
/** Withdrawal completed on-chain. */
export declare function sendWithdrawalCompletedEmail(to: string, p: WalletEmailPayload): Promise<void>;
/** Withdrawal failed or cancelled; funds returned. */
export declare function sendWithdrawalFailedEmail(to: string, p: WalletEmailPayload): Promise<void>;
/** Peer transfer sent confirmation. */
export declare function sendTransferSentEmail(to: string, p: WalletEmailPayload): Promise<void>;
/** Peer transfer received notification. */
export declare function sendTransferReceivedEmail(to: string, p: WalletEmailPayload): Promise<void>;
export {};
//# sourceMappingURL=emailService.d.ts.map

View File

@ -1 +1 @@
{"version":3,"file":"emailService.d.ts","sourceRoot":"","sources":["../../src/services/emailService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AASH,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;AAaD;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,MAAM,CAK3C;AAED,oEAAoE;AACpE,wBAAgB,qBAA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AAM,EACV,CAAC,EAAE,kBAAkB,GACpB,OAAO,CAAC,IAAI,CAAC,CAcf"}

View File

@ -23,6 +23,11 @@ exports.sendTotpEnabledEmail = sendTotpEnabledEmail;
exports.sendTotpDisabledEmail = sendTotpDisabledEmail;
exports.sendRolesChangedEmail = sendRolesChangedEmail;
exports.sendPermissionsChangedEmail = sendPermissionsChangedEmail;
exports.sendWithdrawalSubmittedEmail = sendWithdrawalSubmittedEmail;
exports.sendWithdrawalCompletedEmail = sendWithdrawalCompletedEmail;
exports.sendWithdrawalFailedEmail = sendWithdrawalFailedEmail;
exports.sendTransferSentEmail = sendTransferSentEmail;
exports.sendTransferReceivedEmail = sendTransferReceivedEmail;
const nodemailer_1 = __importDefault(require("nodemailer"));
const platformName_1 = require("../brand/platformName");
const config_1 = require("../config");
@ -407,4 +412,136 @@ async function sendPermissionsChangedEmail(to, permissions, ctx) {
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
}
async function sendUserWalletEmail(to, subject, title, bodyLines, htmlBody) {
const text = bodyLines.join('\n');
if (config_1.config.email.transport === 'console') {
console.log('[email] User wallet message (console transport)');
console.log(` To: ${to}`);
console.log(` Subject: ${subject}`);
console.log(text);
return;
}
const html = `
<div style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px;">
<h2 style="color:#D6B25E;margin:0 0 16px;">${title}</h2>
${htmlBody}
<p style="font-size:12px;color:#888;margin-top:24px;">
If you did not initiate this action, contact support immediately and secure your account.
</p>
</div>
`;
try {
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
html,
});
}
catch (e) {
throw formatEmailSendError('wallet notification', e);
}
}
function walletAmountLines(p) {
const lines = [`Amount: ${p.amountUsdt} USDT`];
if (p.feeUsdt)
lines.push(`Network fee: ${p.feeUsdt} USDT`);
if (p.totalUsdt)
lines.push(`Total debited: ${p.totalUsdt} USDT`);
if (p.toAddressMasked)
lines.push(`Destination: ${p.toAddressMasked}`);
if (p.network)
lines.push(`Network: ${p.network}`);
if (p.blockchainTxId)
lines.push(`On-chain TX: ${p.blockchainTxId}`);
return lines;
}
function walletAmountHtml(p) {
const items = [`<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>`];
if (p.feeUsdt)
items.push(`<li><strong>Network fee:</strong> ${p.feeUsdt} USDT</li>`);
if (p.totalUsdt)
items.push(`<li><strong>Total debited:</strong> ${p.totalUsdt} USDT</li>`);
if (p.toAddressMasked)
items.push(`<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`);
if (p.network)
items.push(`<li><strong>Network:</strong> ${p.network}</li>`);
if (p.blockchainTxId)
items.push(`<li><strong>On-chain TX:</strong> ${p.blockchainTxId}</li>`);
return `<ul style="font-size:14px;line-height:1.6;">${items.join('')}</ul>`;
}
/** Withdrawal request received (pending review or processing). */
async function sendWithdrawalSubmittedEmail(to, p) {
const note = p.statusNote ||
(p.pendingApproval
? 'Your withdrawal is pending review before it is sent on-chain.'
: 'Your withdrawal request was received and is being processed.');
await sendUserWalletEmail(to, 'Your Tloto withdrawal was submitted', 'Withdrawal submitted', [
note,
'',
...walletAmountLines(p),
'',
`Time: ${new Date().toISOString()}`,
], `<p>${note}</p>${walletAmountHtml(p)}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
}
/** Withdrawal completed on-chain. */
async function sendWithdrawalCompletedEmail(to, p) {
await sendUserWalletEmail(to, 'Your Tloto withdrawal was completed', 'Withdrawal completed', [
'Your withdrawal was sent successfully.',
'',
...walletAmountLines(p),
'',
`Time: ${new Date().toISOString()}`,
], `<p>Your withdrawal was sent successfully.</p>${walletAmountHtml(p)}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
}
/** Withdrawal failed or cancelled; funds returned. */
async function sendWithdrawalFailedEmail(to, p) {
const reason = p.reason?.trim();
const lines = [
'Your withdrawal could not be completed. The reserved amount was returned to your available balance.',
'',
`Amount: ${p.amountUsdt} USDT`,
];
if (p.toAddressMasked)
lines.push(`Destination: ${p.toAddressMasked}`);
if (reason)
lines.push(`Reason: ${reason}`);
lines.push('', `Time: ${new Date().toISOString()}`);
const reasonHtml = reason ? `<p><strong>Reason:</strong> ${reason}</p>` : '';
const destHtml = p.toAddressMasked
? `<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`
: '';
await sendUserWalletEmail(to, 'Your Tloto withdrawal could not be completed', 'Withdrawal failed', lines, `<p>Your withdrawal could not be completed. Funds were returned to your available balance.</p>
<ul style="font-size:14px;line-height:1.6;">
<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>
${destHtml}
</ul>
${reasonHtml}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
}
/** Peer transfer sent confirmation. */
async function sendTransferSentEmail(to, p) {
const counterparty = p.counterpartyEmailMasked || 'another user';
await sendUserWalletEmail(to, 'You sent a Tloto transfer', 'Transfer sent', [
`You sent ${p.amountUsdt} USDT to ${counterparty}.`,
'',
`Time: ${new Date().toISOString()}`,
], `<p>You sent <strong>${p.amountUsdt} USDT</strong> to <strong>${counterparty}</strong>.</p>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
}
/** Peer transfer received notification. */
async function sendTransferReceivedEmail(to, p) {
const counterparty = p.counterpartyEmailMasked || 'another Tloto user';
await sendUserWalletEmail(to, 'You received a Tloto transfer', 'Transfer received', [
`You received ${p.amountUsdt} USDT from ${counterparty}.`,
'',
`Time: ${new Date().toISOString()}`,
], `<p>You received <strong>${p.amountUsdt} USDT</strong> from <strong>${counterparty}</strong>.</p>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
}
//# sourceMappingURL=emailService.js.map

File diff suppressed because one or more lines are too long

View File

@ -30,6 +30,33 @@ declare function mapCategory(row: FaqCategoryRow): {
export declare function buildVoterKey(req: Request, userId?: string): string;
export declare function publicFaqFileUrl(filename: string): string;
export declare function resolveFaqFilePath(filename: string): string;
/**
* Validate magic/ClamAV, rename to uuid+safeExt, register legitimacy row.
*/
export declare function finalizeFaqUpload(input: {
tempFilename: string;
originalName?: string;
kind: 'media' | 'category_pdf';
categoryId?: number | null;
uploadedByUserId?: string | null;
allowedMimes: Set<string>;
}): Promise<{
filename: string;
mime: string;
originalName: string;
url: string;
}>;
/** Content-Disposition for FAQ downloads (attachment for PDF, inline for media). */
export declare function faqFileContentDisposition(downloadName: string, mime: string): string;
/**
* Resolve a legitimate FAQ file for public download.
* Registry first; legacy fallback for category PDFs / answer HTML references.
*/
export declare function resolvePublicFaqFile(filename: string): Promise<{
filePath: string;
mime: string;
downloadName: string;
} | null>;
export declare function getFaqPdfMaxBytes(): Promise<number>;
export declare function listPublicCategories(): Promise<{
id: number;
@ -225,9 +252,10 @@ export declare function readFaqFile(filename: string): string | null;
export declare function uploadCategoryDocument(input: {
categoryId: number;
lang: FaqDocumentLang;
storedFilename: string;
tempFilename: string;
originalName: string;
byteSize: number;
uploadedByUserId?: string | null;
}): Promise<ReturnType<typeof mapCategory>>;
export declare function deleteCategoryDocument(categoryId: number, lang: FaqDocumentLang): Promise<{
id: number;

View File

@ -1 +1 @@
{"version":3,"file":"faqService.d.ts","sourceRoot":"","sources":["../../src/services/faqService.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAuBtE,sDAAsD;AACtD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,CAGjE;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAc,GAAG,MAAM,CAIrF;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,eAAe,GACpB,MAAM,CAIR;AAgBD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AE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;GAuBjF;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;GAc7F;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM;;GAI9C;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI3D;AAED;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE;IAClD,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,eAAe,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC,CA6C1C;AAED,wBAAsB,sBAAsB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe;;;;;;;;;;;;;;;;;GAQrF;AAED,iEAAiE;AACjE,wBAAsB,6BAA6B,CACjD,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAY5D"}

View File

@ -42,6 +42,9 @@ exports.buildFaqCategoryGuideFilename = buildFaqCategoryGuideFilename;
exports.buildVoterKey = buildVoterKey;
exports.publicFaqFileUrl = publicFaqFileUrl;
exports.resolveFaqFilePath = resolveFaqFilePath;
exports.finalizeFaqUpload = finalizeFaqUpload;
exports.faqFileContentDisposition = faqFileContentDisposition;
exports.resolvePublicFaqFile = resolvePublicFaqFile;
exports.getFaqPdfMaxBytes = getFaqPdfMaxBytes;
exports.listPublicCategories = listPublicCategories;
exports.listPublicFaqs = listPublicFaqs;
@ -64,6 +67,7 @@ exports.resolvePublicCategoryDocument = resolvePublicCategoryDocument;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const crypto_1 = __importDefault(require("crypto"));
const uuid_1 = require("uuid");
const repo = __importStar(require("../repositories/faqRepository"));
const faqUpload_1 = require("../middleware/faqUpload");
const faqPdfUpload_1 = require("../middleware/faqPdfUpload");
@ -167,6 +171,105 @@ function publicFaqFileUrl(filename) {
function resolveFaqFilePath(filename) {
return path_1.default.join((0, faqUpload_1.ensureFaqUploadDir)(), path_1.default.basename(filename));
}
function safeFaqDisplayName(originalName, mime) {
const ext = (0, fileMagic_1.extensionForMime)(mime);
const base = path_1.default
.basename(originalName || 'file')
.replace(/[^\w.\-()+ ]+/g, '_')
.slice(0, 180);
const withoutExt = base.replace(/\.[^.]+$/, '') || 'file';
return `${withoutExt}${ext}`;
}
/**
* Validate magic/ClamAV, rename to uuid+safeExt, register legitimacy row.
*/
async function finalizeFaqUpload(input) {
const tempPath = resolveFaqFilePath(input.tempFilename);
let detected;
try {
detected = await (0, uploadValidation_1.validateUploadedFile)(tempPath, input.allowedMimes);
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(tempPath);
throw e;
}
const ext = (0, fileMagic_1.extensionForMime)(detected);
const finalName = `${(0, uuid_1.v4)()}${ext}`;
const finalPath = resolveFaqFilePath(finalName);
fs_1.default.renameSync(tempPath, finalPath);
const originalName = safeFaqDisplayName(input.originalName, detected);
await repo.insertUploadedFile({
filename: finalName,
mime: detected,
originalName,
kind: input.kind,
categoryId: input.categoryId ?? null,
uploadedByUserId: input.uploadedByUserId ?? null,
});
await (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.faq, finalName);
return {
filename: finalName,
mime: detected,
originalName,
url: publicFaqFileUrl(finalName),
};
}
/** Content-Disposition for FAQ downloads (attachment for PDF, inline for media). */
function faqFileContentDisposition(downloadName, mime) {
const ascii = downloadName.replace(/[^\x20-\x7E]/g, '_').replace(/"/g, '');
const encoded = encodeURIComponent(downloadName);
const disposition = mime === 'application/pdf' ? 'attachment' : 'inline';
return `${disposition}; filename="${ascii}"; filename*=UTF-8''${encoded}`;
}
/**
* Resolve a legitimate FAQ file for public download.
* Registry first; legacy fallback for category PDFs / answer HTML references.
*/
async function resolvePublicFaqFile(filename) {
const safe = path_1.default.basename(filename);
if (!safe || safe === '.' || safe === '..')
return null;
const filePath = resolveFaqFilePath(safe);
if (!fs_1.default.existsSync(filePath))
return null;
const registered = await repo.findUploadedFile(safe);
if (registered) {
return {
filePath,
mime: registered.mime,
downloadName: registered.original_name || safe,
};
}
if (await repo.isCategoryPdfFilename(safe)) {
return {
filePath,
mime: 'application/pdf',
downloadName: safe.toLowerCase().endsWith('.pdf') ? safe : `${safe}.pdf`,
};
}
if (await repo.isReferencedInFaqAnswerHtml(safe)) {
const ext = path_1.default.extname(safe).toLowerCase();
const mime = ext === '.jpg' || ext === '.jpeg'
? 'image/jpeg'
: ext === '.png'
? 'image/png'
: ext === '.gif'
? 'image/gif'
: ext === '.webp'
? 'image/webp'
: ext === '.mp4'
? 'video/mp4'
: ext === '.webm'
? 'video/webm'
: ext === '.pdf'
? 'application/pdf'
: null;
if (!mime)
return null;
return { filePath, mime, downloadName: safe };
}
return null;
}
async function getFaqPdfMaxBytes() {
const rows = await (0, connection_1.query)(`SELECT value FROM system_settings WHERE key = $1 LIMIT 1`, ['faq_pdf_max_bytes']);
const n = Number(rows[0]?.value);
@ -341,33 +444,34 @@ function readFaqFile(filename) {
async function uploadCategoryDocument(input) {
const cat = await repo.getCategoryById(input.categoryId);
if (!cat) {
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(input.storedFilename));
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(input.tempFilename));
throw new Error('Category not found');
}
const filePath = resolveFaqFilePath(input.storedFilename);
const maxBytes = await getFaqPdfMaxBytes();
if (input.byteSize > maxBytes) {
(0, fileMagic_1.removeUploadedFile)(filePath);
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(input.tempFilename));
throw new Error(`PDF exceeds maximum size of ${maxBytes} bytes`);
}
try {
await (0, uploadValidation_1.validateUploadedFile)(filePath, faqPdfUpload_1.FAQ_PDF_ALLOWED_MIMES);
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(filePath);
throw e;
}
const saved = await finalizeFaqUpload({
tempFilename: input.tempFilename,
originalName: input.originalName,
kind: 'category_pdf',
categoryId: input.categoryId,
uploadedByUserId: input.uploadedByUserId ?? null,
allowedMimes: faqPdfUpload_1.FAQ_PDF_ALLOWED_MIMES,
});
const previous = input.lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
// Prefer a clear guide name over the uploader's original filename.
const originalName = buildFaqCategoryGuideFilename(cat.slug || cat.name, input.lang);
const updated = await repo.setCategoryDocument(input.categoryId, input.lang, path_1.default.basename(input.storedFilename), originalName);
const updated = await repo.setCategoryDocument(input.categoryId, input.lang, saved.filename, originalName);
if (!updated) {
(0, fileMagic_1.removeUploadedFile)(filePath);
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(saved.filename));
await repo.deleteUploadedFile(saved.filename);
throw new Error('Category not found');
}
await (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.faq, path_1.default.basename(input.storedFilename));
if (previous && previous !== input.storedFilename) {
if (previous && previous !== saved.filename) {
unlinkFaqFileQuiet(previous);
await repo.deleteUploadedFile(previous).catch(() => undefined);
}
return mapCategory(updated);
}
@ -375,7 +479,10 @@ async function deleteCategoryDocument(categoryId, lang) {
const result = await repo.clearCategoryDocument(categoryId, lang);
if (!result)
throw new Error('Category not found');
if (result.removedFilename) {
unlinkFaqFileQuiet(result.removedFilename);
await repo.deleteUploadedFile(result.removedFilename).catch(() => undefined);
}
return mapCategory(result.row);
}
/** Resolve a public download for an active category document. */

File diff suppressed because one or more lines are too long

View File

@ -252,6 +252,30 @@ export declare function getStaffUnreadCount(): Promise<number>;
export declare function resolveUploadPath(storedName: string): string;
export declare function ensureUploadDir(): string;
export declare function publicAttachmentUrl(storedName: string): string;
/** Extract basename from a support attachment URL (relative or absolute). */
export declare function parseSupportAttachmentFilename(url: string): string | null;
/**
* Validate magic/ClamAV, rename to uuid+safeExt, register ACL row.
*/
export declare function finalizeSupportUpload(input: {
tempFilename: string;
originalName?: string;
conversationId?: string | null;
ctx: SupportAccessContext;
}): Promise<{
filename: string;
mime: string;
originalName: string;
url: string;
}>;
/** Authorize download of a stored support file. */
export declare function assertSupportFileDownloadAccess(filename: string, ctx: SupportAccessContext): Promise<{
mime: string;
originalName: string | null;
filePath: string;
}>;
/** Content-Disposition filename* / filename header value. */
export declare function attachmentContentDisposition(downloadName: string): string;
/** Links all anonymous visitor conversations to a newly registered or logged-in user. */
export declare function mergeVisitorSupportForUser(userId: string, visitorToken: string | null | undefined): Promise<number>;
//# sourceMappingURL=supportService.d.ts.map

View File

@ -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;AAgBjC,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAE7D;AAqHD,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B,CAAC;AAEF,wBAAsB,wBAAwB,CAC5C,cAAc,EAAE,MAAM,EACtB,GAAG,EAAE,oBAAoB,GACxB,OAAO,CAAC,sBAAsB,CAAC,CAiBjC;AAED,wBAAsB,uBAAuB,CAAC,GAAG,EAAE,oBAA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AC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,GAAG,EAAE,oBAAoB,CAAC;CAC3B,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAAC,CAgCjF;AAiBD,mDAAmD;AACnD,wBAAsB,+BAA+B,CACnD,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,oBAAoB,GACxB,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAwC1E;AA2BD,6DAA6D;AAC7D,wBAAgB,4BAA4B,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAIzE;AAED,yFAAyF;AACzF,wBAAsB,0BAA0B,CAC9C,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACtC,OAAO,CAAC,MAAM,CAAC,CAajB"}

View File

@ -54,14 +54,23 @@ exports.getStaffUnreadCount = getStaffUnreadCount;
exports.resolveUploadPath = resolveUploadPath;
exports.ensureUploadDir = ensureUploadDir;
exports.publicAttachmentUrl = publicAttachmentUrl;
exports.parseSupportAttachmentFilename = parseSupportAttachmentFilename;
exports.finalizeSupportUpload = finalizeSupportUpload;
exports.assertSupportFileDownloadAccess = assertSupportFileDownloadAccess;
exports.attachmentContentDisposition = attachmentContentDisposition;
exports.mergeVisitorSupportForUser = mergeVisitorSupportForUser;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const uuid_1 = require("uuid");
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 fileMagic_1 = require("../utils/fileMagic");
const uploadValidation_1 = require("../utils/uploadValidation");
const supportUpload_1 = require("../middleware/supportUpload");
const fileIntegrityService_1 = require("./fileIntegrityService");
const STAFF_ROLES = new Set(['admin', 'moderator', 'super_admin']);
function isStaffRole(role) {
return !!role && STAFF_ROLES.has(role);
@ -255,6 +264,16 @@ async function sendMessage(conversationId, ctx, input) {
if (!body && !input.attachmentUrl) {
throw new Error('Message body or attachment is required');
}
let attachmentUrl = input.attachmentUrl ?? null;
let attachmentName = input.attachmentName ?? null;
let attachmentMime = input.attachmentMime ?? null;
if (attachmentUrl) {
const meta = await assertOwnedSupportAttachment(attachmentUrl, ctx);
attachmentUrl = publicAttachmentUrl(meta.filename);
attachmentName = attachmentName || meta.original_name || meta.filename;
attachmentMime = meta.mime;
await repo.bindUploadedFileConversation(meta.filename, conversationId);
}
let senderType;
let senderUserId = null;
if (isStaffRole(ctx.role)) {
@ -273,11 +292,11 @@ async function sendMessage(conversationId, ctx, input) {
senderType,
senderUserId,
body,
attachmentUrl: input.attachmentUrl ?? null,
attachmentName: input.attachmentName ?? null,
attachmentMime: input.attachmentMime ?? null,
attachmentUrl,
attachmentName,
attachmentMime,
});
const preview = previewForMessage(body, input.attachmentName ?? null);
const preview = previewForMessage(body, attachmentName);
const staffSent = senderType === 'staff';
await repo.touchConversationLastMessage(conversationId, preview, staffSent, !staffSent);
if (conv.status === 'resolved' || conv.status === 'closed') {
@ -436,6 +455,151 @@ function ensureUploadDir() {
function publicAttachmentUrl(storedName) {
return `/api/v1/support/files/${encodeURIComponent(storedName)}`;
}
const SUPPORT_FILE_RE = /^\/api\/v1\/support\/files\/([^/?#]+)$/i;
/** Extract basename from a support attachment URL (relative or absolute). */
function parseSupportAttachmentFilename(url) {
try {
const pathOnly = url.startsWith('http') ? new URL(url).pathname : url.split('?')[0] ?? url;
const m = pathOnly.match(SUPPORT_FILE_RE);
if (!m?.[1])
return null;
const name = path_1.default.basename(decodeURIComponent(m[1]));
if (!name || name === '.' || name === '..')
return null;
return name;
}
catch {
return null;
}
}
function safeDisplayName(originalName, mime) {
const base = path_1.default.basename(originalName || 'attachment').replace(/[^\w.\-()+ ]+/g, '_').slice(0, 180);
const ext = (0, fileMagic_1.extensionForMime)(mime);
const withoutExt = base.replace(/\.[^.]+$/, '') || 'attachment';
return `${withoutExt}${ext}`;
}
/**
* Validate magic/ClamAV, rename to uuid+safeExt, register ACL row.
*/
async function finalizeSupportUpload(input) {
const tempPath = resolveUploadPath(input.tempFilename);
let detected;
try {
detected = await (0, uploadValidation_1.validateUploadedFile)(tempPath, supportUpload_1.SUPPORT_ALLOWED_MIMES);
}
catch (e) {
(0, fileMagic_1.removeUploadedFile)(tempPath);
throw e;
}
const ext = (0, fileMagic_1.extensionForMime)(detected);
const finalName = `${(0, uuid_1.v4)()}${ext}`;
const finalPath = resolveUploadPath(finalName);
fs_1.default.renameSync(tempPath, finalPath);
const originalName = safeDisplayName(input.originalName, detected);
await repo.insertUploadedFile({
filename: finalName,
mime: detected,
originalName,
conversationId: input.conversationId ?? null,
uploadedByUserId: input.ctx.userId ?? null,
visitorToken: input.ctx.visitorToken ?? null,
});
await (0, fileIntegrityService_1.recordUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.support, finalName);
return {
filename: finalName,
mime: detected,
originalName,
url: publicAttachmentUrl(finalName),
};
}
async function assertOwnedSupportAttachment(url, ctx) {
const filename = parseSupportAttachmentFilename(url);
if (!filename)
throw new Error('Invalid attachment URL');
const row = await repo.findUploadedFile(filename);
if (!row)
throw new Error('Attachment not found');
if (isStaffRole(ctx.role))
return row;
if (ctx.userId && row.uploaded_by_user_id === ctx.userId)
return row;
if (ctx.visitorToken && row.visitor_token === ctx.visitorToken)
return row;
if (row.conversation_id) {
await assertConversationAccess(row.conversation_id, ctx);
return row;
}
throw new Error('Forbidden');
}
/** Authorize download of a stored support file. */
async function assertSupportFileDownloadAccess(filename, ctx) {
const safe = path_1.default.basename(filename);
const filePath = resolveUploadPath(safe);
if (!fs_1.default.existsSync(filePath))
throw new Error('Not found');
if (isStaffRole(ctx.role)) {
const row = await repo.findUploadedFile(safe);
return {
mime: row?.mime || mimeFromFilename(safe),
originalName: row?.original_name ?? null,
filePath,
};
}
const row = await repo.findUploadedFile(safe);
if (row) {
if (ctx.userId && row.uploaded_by_user_id === ctx.userId) {
return { mime: row.mime, originalName: row.original_name, filePath };
}
if (ctx.visitorToken && row.visitor_token === ctx.visitorToken) {
return { mime: row.mime, originalName: row.original_name, filePath };
}
if (row.conversation_id) {
await assertConversationAccess(row.conversation_id, ctx);
return { mime: row.mime, originalName: row.original_name, filePath };
}
}
// Legacy files uploaded before ACL registry: allow if referenced by an accessible message.
const msg = await repo.findMessageByAttachmentFilename(safe);
if (msg) {
await assertConversationAccess(msg.conversation_id, ctx);
return {
mime: mimeFromFilename(safe),
originalName: null,
filePath,
};
}
throw new Error('Forbidden');
}
function mimeFromFilename(filename) {
const ext = path_1.default.extname(filename).toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
return 'image/jpeg';
case '.png':
return 'image/png';
case '.gif':
return 'image/gif';
case '.webp':
return 'image/webp';
case '.pdf':
return 'application/pdf';
case '.txt':
return 'text/plain';
case '.doc':
return 'application/msword';
case '.docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
default:
return 'application/octet-stream';
}
}
/** Content-Disposition filename* / filename header value. */
function attachmentContentDisposition(downloadName) {
const ascii = downloadName.replace(/[^\x20-\x7E]/g, '_').replace(/"/g, '');
const encoded = encodeURIComponent(downloadName);
return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`;
}
/** Links all anonymous visitor conversations to a newly registered or logged-in user. */
async function mergeVisitorSupportForUser(userId, visitorToken) {
if (!visitorToken || visitorToken.length < 16)

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
{"version":3,"file":"transferService.d.ts","sourceRoot":"","sources":["../../src/services/transferService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAkBH;;;;;;;;;;;GAWG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC;IAAE,aAAa,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAkFpD"}
{"version":3,"file":"transferService.d.ts","sourceRoot":"","sources":["../../src/services/transferService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmBH;;;;;;;;;;;GAWG;AACH,wBAAsB,eAAe,CACnC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC;IAAE,aAAa,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CA8FpD"}

View File

@ -50,6 +50,7 @@ const auditLogRepository = __importStar(require("../repositories/auditLogReposit
const walletCapabilities_1 = require("./walletCapabilities");
const withdrawalFee_1 = require("../utils/withdrawalFee");
const userAdminStatsService_1 = require("./userAdminStatsService");
const walletNotificationService = __importStar(require("./walletNotificationService"));
/**
* Transfers balance from one user to another identified by email.
* Peer transfers always debit/credit the unified main ledger (USDT_TRC20).
@ -127,6 +128,17 @@ async function requestTransfer(userId, toEmail, walletTypeCode, amountRaw, totpC
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(recipient.id);
const recipientEmail = toEmail.trim().toLowerCase();
void walletNotificationService.notifyTransferSent(userId, {
amountRaw,
toEmail: recipientEmail,
transactionId: senderTx.id,
});
void walletNotificationService.notifyTransferReceived(recipient.id, {
amountRaw,
fromUserId: userId,
transactionId: receiverTx.id,
});
return { transactionId: senderTx.id, status: 'completed' };
}
//# sourceMappingURL=transferService.js.map

View File

@ -1 +1 @@
{"version":3,"file":"transferService.js","sourceRoot":"","sources":["../../src/services/transferService.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BH,0CAwFC;AApHD,mCAAoC;AACpC,4CAA+C;AAC/C,2DAA6C;AAC7C,mFAAqE;AACrE,uFAAyE;AACzE,6FAA+E;AAC/E,+EAAiE;AACjE,mFAAqE;AACrE,uFAAyE;AACzE,6DAAuD;AACvD,0DAGgC;AAChC,mEAAqE;AAErE;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,eAAe,CACnC,MAAc,EACd,OAAe,EACf,cAAsB,EACtB,SAAiB,EACjB,QAAiB;IAEjB,IAAI,cAAc,KAAK,oCAAe,EAAE,CAAC;QACvC,MAAM,GAAG,GAAG,IAAI,KAAK,CACnB,+EAA+E,CACnD,CAAC;QAC/B,GAAG,CAAC,IAAI,GAAG,sBAAsB,CAAC;QAClC,MAAM,GAAG,CAAC;IACZ,CAAC;IAED,MAAM,UAAU,GAAG,MAAM,gBAAgB,CAAC,mBAAmB,CAAC,oCAAe,CAAC,CAAC;IAC/E,IAAI,CAAC,UAAU;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACxD,IAAI,SAAS,IAAI,EAAE;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEvD,MAAM,WAAW,CAAC,4BAA4B,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAEjE,MAAM,WAAW,GAAG,IAAA,qBAAY,EAAC,OAAO,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;IAC/D,MAAM,SAAS,GAAG,MAAM,cAAc,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;IACpE,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACvD,IAAI,SAAS,CAAC,EAA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BAAkB,CAAC,MAAM,EAAE;QACxD,SAAS;QACT,OAAO,EAAE,cAAc;QACvB,aAAa,EAAE,QAAQ,CAAC,EAAE;KAC3B,CAAC,CAAC;IACH,KAAK,yBAAyB,CAAC,sBAAsB,CAAC,SAAS,CAAC,EAAE,EAAE;QAClE,SAAS;QACT,UAAU,EAAE,MAAM;QAClB,aAAa,EAAE,UAAU,CAAC,EAAE;KAC7B,CAAC,CAAC;IAEH,OAAO,EAAE,aAAa,EAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;AAC7D,CAAC"}

View File

@ -1 +1 @@
{"version":3,"file":"withdrawalService.d.ts","sourceRoot":"","sources":["../../src/services/withdrawalService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA0GH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,gBAAgB,CAAC,CA0J3B;AAED,+EAA+E;AAC/E,wBAAsB,2BAA2B,CAC/C,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CA8ClC;AAsID,wFAAwF;AACxF,wBAAsB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAuBnG"}
{"version":3,"file":"withdrawalService.d.ts","sourceRoot":"","sources":["../../src/services/withdrawalService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA2GH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,gBAAgB,CAAC,CAoK3B;AAED,+EAA+E;AAC/E,wBAAsB,2BAA2B,CAC/C,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CA8ClC;AAsJD,wFAAwF;AACxF,wBAAsB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA8BnG"}

View File

@ -63,6 +63,7 @@ const withdrawalLimits_1 = require("../utils/withdrawalLimits");
const walletCapabilities_1 = require("./walletCapabilities");
const usdtUnits_1 = require("../utils/usdtUnits");
const hotLiquidityService_1 = require("./hotLiquidityService");
const walletNotificationService = __importStar(require("./walletNotificationService"));
function assertPayoutAddress(network, toAddress) {
const a = toAddress.trim();
if (network === 'BSC') {
@ -236,6 +237,16 @@ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, t
requestedBy: userId,
skipRequestPermission: true,
});
if (!fundReq.autoExecuted) {
void walletNotificationService.notifyWithdrawalSubmitted(userId, {
amountRaw,
feeRaw,
toAddress,
network,
transactionId: tx.id,
pendingApproval: true,
});
}
return {
transactionId: tx.id,
status: fundReq.autoExecuted ? 'completed' : 'pending_approval',
@ -370,6 +381,14 @@ async function broadcastWithdrawalTx(input) {
},
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
void walletNotificationService.notifyWithdrawalCompleted(userId, {
amountRaw,
feeRaw,
toAddress,
network,
transactionId: txId,
blockchainTxId,
});
try {
await referralService.processWithdrawalReferralCommissions({
userId,
@ -403,6 +422,13 @@ async function broadcastWithdrawalTx(input) {
metadata: { error: String(err) },
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
void walletNotificationService.notifyWithdrawalFailed(userId, {
amountRaw,
feeRaw,
toAddress,
transactionId: txId,
reason: err instanceof Error ? err.message : String(err),
});
}
if (err instanceof securityService_1.SecurityBlockedError)
throw err;
@ -434,5 +460,12 @@ async function abandonPendingWithdrawal(transactionId, reason) {
metadata: { reason },
});
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(tx.user_id);
void walletNotificationService.notifyWithdrawalFailed(tx.user_id, {
amountRaw,
feeRaw,
toAddress: tx.to_address || undefined,
transactionId: tx.id,
reason,
});
}
//# sourceMappingURL=withdrawalService.js.map

File diff suppressed because one or more lines are too long

View File

@ -506,3 +506,200 @@ export async function sendPermissionsChangedEmail(
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
type WalletEmailPayload = {
amountUsdt: string;
feeUsdt?: string;
totalUsdt?: string;
toAddressMasked?: string | null;
network?: string;
pendingApproval?: boolean;
statusNote?: string;
blockchainTxId?: string | null;
reason?: string;
counterpartyEmailMasked?: string;
};
async function sendUserWalletEmail(
to: string,
subject: string,
title: string,
bodyLines: string[],
htmlBody: string
): Promise<void> {
const text = bodyLines.join('\n');
if (config.email.transport === 'console') {
console.log('[email] User wallet message (console transport)');
console.log(` To: ${to}`);
console.log(` Subject: ${subject}`);
console.log(text);
return;
}
const html = `
<div style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px;">
<h2 style="color:#D6B25E;margin:0 0 16px;">${title}</h2>
${htmlBody}
<p style="font-size:12px;color:#888;margin-top:24px;">
If you did not initiate this action, contact support immediately and secure your account.
</p>
</div>
`;
try {
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
html,
});
} catch (e) {
throw formatEmailSendError('wallet notification', e);
}
}
function walletAmountLines(p: WalletEmailPayload): string[] {
const lines = [`Amount: ${p.amountUsdt} USDT`];
if (p.feeUsdt) lines.push(`Network fee: ${p.feeUsdt} USDT`);
if (p.totalUsdt) lines.push(`Total debited: ${p.totalUsdt} USDT`);
if (p.toAddressMasked) lines.push(`Destination: ${p.toAddressMasked}`);
if (p.network) lines.push(`Network: ${p.network}`);
if (p.blockchainTxId) lines.push(`On-chain TX: ${p.blockchainTxId}`);
return lines;
}
function walletAmountHtml(p: WalletEmailPayload): string {
const items = [`<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>`];
if (p.feeUsdt) items.push(`<li><strong>Network fee:</strong> ${p.feeUsdt} USDT</li>`);
if (p.totalUsdt) items.push(`<li><strong>Total debited:</strong> ${p.totalUsdt} USDT</li>`);
if (p.toAddressMasked) items.push(`<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`);
if (p.network) items.push(`<li><strong>Network:</strong> ${p.network}</li>`);
if (p.blockchainTxId) items.push(`<li><strong>On-chain TX:</strong> ${p.blockchainTxId}</li>`);
return `<ul style="font-size:14px;line-height:1.6;">${items.join('')}</ul>`;
}
/** Withdrawal request received (pending review or processing). */
export async function sendWithdrawalSubmittedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
const note =
p.statusNote ||
(p.pendingApproval
? 'Your withdrawal is pending review before it is sent on-chain.'
: 'Your withdrawal request was received and is being processed.');
await sendUserWalletEmail(
to,
'Your Tloto withdrawal was submitted',
'Withdrawal submitted',
[
note,
'',
...walletAmountLines(p),
'',
`Time: ${new Date().toISOString()}`,
],
`<p>${note}</p>${walletAmountHtml(p)}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Withdrawal completed on-chain. */
export async function sendWithdrawalCompletedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
await sendUserWalletEmail(
to,
'Your Tloto withdrawal was completed',
'Withdrawal completed',
[
'Your withdrawal was sent successfully.',
'',
...walletAmountLines(p),
'',
`Time: ${new Date().toISOString()}`,
],
`<p>Your withdrawal was sent successfully.</p>${walletAmountHtml(p)}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Withdrawal failed or cancelled; funds returned. */
export async function sendWithdrawalFailedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
const reason = p.reason?.trim();
const lines = [
'Your withdrawal could not be completed. The reserved amount was returned to your available balance.',
'',
`Amount: ${p.amountUsdt} USDT`,
];
if (p.toAddressMasked) lines.push(`Destination: ${p.toAddressMasked}`);
if (reason) lines.push(`Reason: ${reason}`);
lines.push('', `Time: ${new Date().toISOString()}`);
const reasonHtml = reason ? `<p><strong>Reason:</strong> ${reason}</p>` : '';
const destHtml = p.toAddressMasked
? `<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`
: '';
await sendUserWalletEmail(
to,
'Your Tloto withdrawal could not be completed',
'Withdrawal failed',
lines,
`<p>Your withdrawal could not be completed. Funds were returned to your available balance.</p>
<ul style="font-size:14px;line-height:1.6;">
<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>
${destHtml}
</ul>
${reasonHtml}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Peer transfer sent confirmation. */
export async function sendTransferSentEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
const counterparty = p.counterpartyEmailMasked || 'another user';
await sendUserWalletEmail(
to,
'You sent a Tloto transfer',
'Transfer sent',
[
`You sent ${p.amountUsdt} USDT to ${counterparty}.`,
'',
`Time: ${new Date().toISOString()}`,
],
`<p>You sent <strong>${p.amountUsdt} USDT</strong> to <strong>${counterparty}</strong>.</p>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Peer transfer received notification. */
export async function sendTransferReceivedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
const counterparty = p.counterpartyEmailMasked || 'another Tloto user';
await sendUserWalletEmail(
to,
'You received a Tloto transfer',
'Transfer received',
[
`You received ${p.amountUsdt} USDT from ${counterparty}.`,
'',
`Time: ${new Date().toISOString()}`,
],
`<p>You received <strong>${p.amountUsdt} USDT</strong> from <strong>${counterparty}</strong>.</p>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}

View File

@ -13,7 +13,11 @@ import {
import { sanitizeFaqHtml } from '../utils/sanitizeHtml';
import { validateUploadedFile } from '../utils/uploadValidation';
import { extensionForMime, removeUploadedFile } from '../utils/fileMagic';
import { recordUploadedFile, FILE_INTEGRITY_ROOTS } from './fileIntegrityService';
import {
recordUploadedFile,
forgetUploadedFile,
FILE_INTEGRITY_ROOTS,
} from './fileIntegrityService';
import { query } from '../db/connection';
function slugify(text: string): string {
@ -342,9 +346,11 @@ export async function updateAdminCategory(id: number, body: Record<string, unkno
return mapCategory(updated);
}
function unlinkFaqFileQuiet(filename: string | null | undefined): void {
/** Removes a FAQ PDF from disk and clears its FIM baseline (intentional delete). */
async function unlinkFaqFileQuiet(filename: string | null | undefined): Promise<void> {
if (!filename) return;
removeUploadedFile(resolveFaqFilePath(filename));
await forgetUploadedFile(FILE_INTEGRITY_ROOTS.faq, filename);
}
export async function deleteAdminCategory(id: number) {
@ -356,8 +362,8 @@ export async function deleteAdminCategory(id: number) {
if (!existing) throw new Error('Category not found');
const ok = await repo.deleteCategory(id);
if (!ok) throw new Error('Category not found');
unlinkFaqFileQuiet(existing.pdf_fr_filename);
unlinkFaqFileQuiet(existing.pdf_en_filename);
await unlinkFaqFileQuiet(existing.pdf_fr_filename);
await unlinkFaqFileQuiet(existing.pdf_en_filename);
return { ok: true };
}
@ -468,13 +474,13 @@ export async function uploadCategoryDocument(input: {
originalName
);
if (!updated) {
removeUploadedFile(resolveFaqFilePath(saved.filename));
await unlinkFaqFileQuiet(saved.filename);
await repo.deleteUploadedFile(saved.filename);
throw new Error('Category not found');
}
if (previous && previous !== saved.filename) {
unlinkFaqFileQuiet(previous);
await unlinkFaqFileQuiet(previous);
await repo.deleteUploadedFile(previous).catch(() => undefined);
}
@ -485,7 +491,7 @@ export async function deleteCategoryDocument(categoryId: number, lang: FaqDocume
const result = await repo.clearCategoryDocument(categoryId, lang);
if (!result) throw new Error('Category not found');
if (result.removedFilename) {
unlinkFaqFileQuiet(result.removedFilename);
await unlinkFaqFileQuiet(result.removedFilename);
await repo.deleteUploadedFile(result.removedFilename).catch(() => undefined);
}
return mapCategory(result.row);

View File

@ -82,6 +82,23 @@ export async function recordUploadedFile(
});
}
/**
* Drops the FIM baseline after an intentional file removal (replace/delete).
* Prevents false "deleted" integrity alerts on the next monitor pass.
*/
export async function forgetUploadedFile(
rootKey: FileIntegrityRootKey,
filename: string
): Promise<void> {
const safeName = path.basename(filename);
if (!safeName) return;
try {
await fileIntegrityRepository.deleteSnapshot(rootKey, safeName);
} catch (e) {
console.warn(`[file-integrity] forgetUploadedFile skipped (${rootKey}/${safeName}):`, e);
}
}
/** Scans one upload root and returns integrity issues vs stored baselines. */
export async function scanRoot(rootKey: FileIntegrityRootKey): Promise<FileIntegrityIssue[]> {
const rootDir = resolveRootDir(rootKey);

View File

@ -18,6 +18,7 @@ import {
getTransferMinRemainingRaw,
} from '../utils/withdrawalFee';
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
import * as walletNotificationService from './walletNotificationService';
/**
* Transfers balance from one user to another identified by email.
@ -118,5 +119,17 @@ export async function requestTransfer(
queueUserAdminStatsRefresh(userId);
queueUserAdminStatsRefresh(recipient.id);
const recipientEmail = toEmail.trim().toLowerCase();
void walletNotificationService.notifyTransferSent(userId, {
amountRaw,
toEmail: recipientEmail,
transactionId: senderTx.id,
});
void walletNotificationService.notifyTransferReceived(recipient.id, {
amountRaw,
fromUserId: userId,
transactionId: receiverTx.id,
});
return { transactionId: senderTx.id, status: 'completed' };
}

View File

@ -0,0 +1,265 @@
/**
* User-facing email + in-app notifications for wallet actions (withdrawals, transfers).
* Failures are logged but never block the primary action.
*/
import { decrypt } from '../utils/crypto';
import { formatUsdtRawHuman } from '../utils/withdrawalFee';
import * as userRepository from '../repositories/userRepository';
import * as userSecurityNotificationRepository from '../repositories/userSecurityNotificationRepository';
import * as emailService from './emailService';
async function resolveUserEmail(userId: string): Promise<string | null> {
const profile = await userRepository.getProfileForUser(userId);
if (!profile?.email_encrypted) return null;
try {
return decrypt(profile.email_encrypted);
} catch {
return null;
}
}
function logNotifyError(context: string, e: unknown): void {
const detail = e instanceof Error ? e.message : String(e);
console.error(`[wallet-notify] ${context}:`, detail);
}
async function recordInAppNotification(data: {
userId: string;
eventType: string;
title: string;
body?: string;
metadata?: Record<string, unknown>;
}): Promise<void> {
try {
await userSecurityNotificationRepository.createUserSecurityNotification(data);
} catch (e) {
logNotifyError('in-app notification', e);
}
}
function maskAddress(address: string): string {
const a = address.trim();
if (a.length <= 12) return a;
return `${a.slice(0, 6)}…${a.slice(-4)}`;
}
function maskEmail(email: string): string {
const e = email.trim();
const at = e.indexOf('@');
if (at <= 1) return '***';
const user = e.slice(0, at);
const domain = e.slice(at + 1);
const visible = user.slice(0, Math.min(2, user.length));
return `${visible}***@${domain}`;
}
function amountLabel(amountRaw: bigint | string, feeRaw?: bigint | string): {
amount: string;
fee?: string;
total?: string;
} {
const amount = formatUsdtRawHuman(BigInt(amountRaw));
if (feeRaw === undefined) return { amount };
const fee = formatUsdtRawHuman(BigInt(feeRaw));
const total = formatUsdtRawHuman(BigInt(amountRaw) + BigInt(feeRaw));
return { amount, fee, total };
}
/** Withdrawal submitted (awaiting approval / processing). */
export async function notifyWithdrawalSubmitted(
userId: string,
data: {
amountRaw: bigint | string;
feeRaw: bigint | string;
toAddress: string;
network?: string;
transactionId: string;
pendingApproval?: boolean;
}
): Promise<void> {
const { amount, fee, total } = amountLabel(data.amountRaw, data.feeRaw);
const dest = maskAddress(data.toAddress);
const statusNote = data.pendingApproval
? 'Your withdrawal is pending review before it is sent on-chain.'
: 'Your withdrawal request was received and is being processed.';
void recordInAppNotification({
userId,
eventType: 'withdrawal_submitted',
title: 'Withdrawal submitted',
body: `${amount} USDT to ${dest}${data.pendingApproval ? ' (pending review)' : ''}.`,
metadata: {
transactionId: data.transactionId,
amount,
fee,
total,
network: data.network,
pendingApproval: !!data.pendingApproval,
},
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendWithdrawalSubmittedEmail(email, {
amountUsdt: amount,
feeUsdt: fee!,
totalUsdt: total!,
toAddressMasked: dest,
network: data.network,
pendingApproval: !!data.pendingApproval,
statusNote,
});
} catch (e) {
logNotifyError('withdrawal submitted email', e);
}
}
/** Withdrawal completed on-chain. */
export async function notifyWithdrawalCompleted(
userId: string,
data: {
amountRaw: bigint | string;
feeRaw: bigint | string;
toAddress: string;
network?: string;
transactionId: string;
blockchainTxId?: string | null;
}
): Promise<void> {
const { amount, fee, total } = amountLabel(data.amountRaw, data.feeRaw);
const dest = maskAddress(data.toAddress);
void recordInAppNotification({
userId,
eventType: 'withdrawal_completed',
title: 'Withdrawal completed',
body: `${amount} USDT was sent to ${dest}.`,
metadata: {
transactionId: data.transactionId,
amount,
fee,
total,
network: data.network,
blockchainTxId: data.blockchainTxId ?? null,
},
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendWithdrawalCompletedEmail(email, {
amountUsdt: amount,
feeUsdt: fee!,
totalUsdt: total!,
toAddressMasked: dest,
network: data.network,
blockchainTxId: data.blockchainTxId ?? null,
});
} catch (e) {
logNotifyError('withdrawal completed email', e);
}
}
/** Withdrawal failed / cancelled (funds unlocked). */
export async function notifyWithdrawalFailed(
userId: string,
data: {
amountRaw: bigint | string;
feeRaw?: bigint | string;
toAddress?: string;
transactionId: string;
reason?: string;
}
): Promise<void> {
const { amount } = amountLabel(data.amountRaw, data.feeRaw);
const dest = data.toAddress ? maskAddress(data.toAddress) : null;
void recordInAppNotification({
userId,
eventType: 'withdrawal_failed',
title: 'Withdrawal failed',
body: dest
? `Your withdrawal of ${amount} USDT to ${dest} could not be completed. Funds were returned to your balance.`
: `Your withdrawal of ${amount} USDT could not be completed. Funds were returned to your balance.`,
metadata: {
transactionId: data.transactionId,
amount,
reason: data.reason ?? null,
},
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendWithdrawalFailedEmail(email, {
amountUsdt: amount,
toAddressMasked: dest,
reason: data.reason,
});
} catch (e) {
logNotifyError('withdrawal failed email', e);
}
}
/** Peer transfer sent (sender). */
export async function notifyTransferSent(
userId: string,
data: {
amountRaw: bigint | string;
toEmail: string;
transactionId: string;
}
): Promise<void> {
const { amount } = amountLabel(data.amountRaw);
const toMasked = maskEmail(data.toEmail);
void recordInAppNotification({
userId,
eventType: 'transfer_sent',
title: 'Transfer sent',
body: `You sent ${amount} USDT to ${toMasked}.`,
metadata: { transactionId: data.transactionId, amount, toEmailMasked: toMasked },
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendTransferSentEmail(email, {
amountUsdt: amount,
counterpartyEmailMasked: toMasked,
});
} catch (e) {
logNotifyError('transfer sent email', e);
}
}
/** Peer transfer received (recipient). */
export async function notifyTransferReceived(
userId: string,
data: {
amountRaw: bigint | string;
fromUserId: string;
transactionId: string;
}
): Promise<void> {
const { amount } = amountLabel(data.amountRaw);
let fromMasked = 'another Tloto user';
const fromEmail = await resolveUserEmail(data.fromUserId);
if (fromEmail) fromMasked = maskEmail(fromEmail);
void recordInAppNotification({
userId,
eventType: 'transfer_received',
title: 'Transfer received',
body: `You received ${amount} USDT from ${fromMasked}.`,
metadata: {
transactionId: data.transactionId,
amount,
fromEmailMasked: fromMasked,
},
});
const email = await resolveUserEmail(userId);
if (!email) return;
try {
await emailService.sendTransferReceivedEmail(email, {
amountUsdt: amount,
counterpartyEmailMasked: fromMasked,
});
} catch (e) {
logNotifyError('transfer received email', e);
}
}

View File

@ -41,6 +41,7 @@ import {
scaleLedgerToChain,
} from '../utils/usdtUnits';
import { assertHotWalletCanPay } from './hotLiquidityService';
import * as walletNotificationService from './walletNotificationService';
function assertPayoutAddress(network: 'TRON' | 'BSC', toAddress: string): void {
const a = toAddress.trim();
@ -260,6 +261,16 @@ export async function requestWithdrawal(
requestedBy: userId,
skipRequestPermission: true,
});
if (!fundReq.autoExecuted) {
void walletNotificationService.notifyWithdrawalSubmitted(userId, {
amountRaw,
feeRaw,
toAddress,
network,
transactionId: tx.id,
pendingApproval: true,
});
}
return {
transactionId: tx.id,
status: fundReq.autoExecuted ? 'completed' : 'pending_approval',
@ -432,6 +443,15 @@ async function broadcastWithdrawalTx(input: {
});
queueUserAdminStatsRefresh(userId);
void walletNotificationService.notifyWithdrawalCompleted(userId, {
amountRaw,
feeRaw,
toAddress,
network,
transactionId: txId,
blockchainTxId,
});
try {
await referralService.processWithdrawalReferralCommissions({
userId,
@ -464,6 +484,13 @@ async function broadcastWithdrawalTx(input: {
metadata: { error: String(err) },
});
queueUserAdminStatsRefresh(userId);
void walletNotificationService.notifyWithdrawalFailed(userId, {
amountRaw,
feeRaw,
toAddress,
transactionId: txId,
reason: err instanceof Error ? err.message : String(err),
});
}
if (err instanceof SecurityBlockedError) throw err;
throw err;
@ -494,4 +521,11 @@ export async function abandonPendingWithdrawal(transactionId: string, reason: st
metadata: { reason },
});
queueUserAdminStatsRefresh(tx.user_id);
void walletNotificationService.notifyWithdrawalFailed(tx.user_id, {
amountRaw,
feeRaw,
toAddress: tx.to_address || undefined,
transactionId: tx.id,
reason,
});
}

View File

@ -0,0 +1,274 @@
/**
* Verifies wallet email + in-app notifications for withdrawals and transfers.
* Stubs repositories / emailService so no DB or SMTP is required.
*/
import { afterEach, before, describe, test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
process.env.ENCRYPTION_KEY =
process.env.ENCRYPTION_KEY ||
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
process.env.EMAIL_TRANSPORT = 'console';
type InAppCall = {
userId: string;
eventType: string;
title: string;
body?: string;
metadata?: Record<string, unknown>;
};
type EmailCall = { fn: string; to: string; payload: Record<string, unknown> };
describe('walletNotificationService', () => {
let encrypt: (plaintext: string) => string;
let userRepository: typeof import('../repositories/userRepository');
let notifRepo: typeof import('../repositories/userSecurityNotificationRepository');
let emailService: typeof import('../services/emailService');
let walletNotify: typeof import('../services/walletNotificationService');
let inAppCalls: InAppCall[];
let emailCalls: EmailCall[];
let originalGetProfile: typeof userRepository.getProfileForUser;
let originalCreateNotif: typeof notifRepo.createUserSecurityNotification;
const originalEmailFns: Record<string, unknown> = {};
const emailFnNames = [
'sendWithdrawalSubmittedEmail',
'sendWithdrawalCompletedEmail',
'sendWithdrawalFailedEmail',
'sendTransferSentEmail',
'sendTransferReceivedEmail',
] as const;
before(async () => {
({ encrypt } = await import('../utils/crypto'));
userRepository = await import('../repositories/userRepository');
notifRepo = await import('../repositories/userSecurityNotificationRepository');
emailService = await import('../services/emailService');
walletNotify = await import('../services/walletNotificationService');
originalGetProfile = userRepository.getProfileForUser;
originalCreateNotif = notifRepo.createUserSecurityNotification;
for (const name of emailFnNames) {
originalEmailFns[name] = (emailService as Record<string, unknown>)[name];
}
});
afterEach(() => {
(userRepository as { getProfileForUser: typeof originalGetProfile }).getProfileForUser =
originalGetProfile;
(
notifRepo as {
createUserSecurityNotification: typeof originalCreateNotif;
}
).createUserSecurityNotification = originalCreateNotif;
for (const name of emailFnNames) {
(emailService as Record<string, unknown>)[name] = originalEmailFns[name];
}
});
function installStubs(opts?: { email?: string | null; inAppThrows?: boolean }) {
inAppCalls = [];
emailCalls = [];
const email = opts?.email === undefined ? 'alice@example.com' : opts.email;
(
userRepository as {
getProfileForUser: typeof userRepository.getProfileForUser;
}
).getProfileForUser = async (userId: string) => {
if (!email) return { email_encrypted: null } as never;
if (userId === 'user-no-email') return null;
return {
email_encrypted: encrypt(email),
} as never;
};
(
notifRepo as {
createUserSecurityNotification: typeof notifRepo.createUserSecurityNotification;
}
).createUserSecurityNotification = async (data) => {
if (opts?.inAppThrows) throw new Error('db down');
inAppCalls.push(data as InAppCall);
};
for (const name of emailFnNames) {
(emailService as Record<string, unknown>)[name] = async (
to: string,
payload: Record<string, unknown>
) => {
emailCalls.push({ fn: name, to, payload });
};
}
}
test('withdrawal submitted: in-app + email with masked address and pending note', async () => {
installStubs();
await walletNotify.notifyWithdrawalSubmitted('user-1', {
amountRaw: 5_000_000n,
feeRaw: 500_000n,
toAddress: 'TXYZabcdefghijklmnop1234567890ABCD',
network: 'TRON',
transactionId: 'tx-sub-1',
pendingApproval: true,
});
assert.equal(inAppCalls.length, 1);
assert.equal(inAppCalls[0].eventType, 'withdrawal_submitted');
assert.match(inAppCalls[0].body || '', /pending review/i);
assert.match(inAppCalls[0].body || '', /TXYZab…ABCD|TXYZab…/);
assert.equal(inAppCalls[0].metadata?.amount, '5');
assert.equal(inAppCalls[0].metadata?.fee, '0.5');
assert.equal(emailCalls.length, 1);
assert.equal(emailCalls[0].fn, 'sendWithdrawalSubmittedEmail');
assert.equal(emailCalls[0].to, 'alice@example.com');
assert.equal(emailCalls[0].payload.pendingApproval, true);
assert.equal(emailCalls[0].payload.amountUsdt, '5');
});
test('withdrawal completed: includes blockchain tx id', async () => {
installStubs();
await walletNotify.notifyWithdrawalCompleted('user-1', {
amountRaw: 10_000_000n,
feeRaw: 1_000_000n,
toAddress: '0x1234567890abcdef1234567890abcdef12345678',
network: 'BSC',
transactionId: 'tx-ok-1',
blockchainTxId: '0xdeadbeef',
});
assert.equal(inAppCalls[0].eventType, 'withdrawal_completed');
assert.equal(inAppCalls[0].metadata?.blockchainTxId, '0xdeadbeef');
assert.equal(emailCalls[0].fn, 'sendWithdrawalCompletedEmail');
assert.equal(emailCalls[0].payload.blockchainTxId, '0xdeadbeef');
assert.match(String(emailCalls[0].payload.toAddressMasked), /^0x1234…5678$/);
});
test('withdrawal failed: still notifies and does not throw when in-app fails', async () => {
installStubs({ inAppThrows: true });
await assert.doesNotReject(() =>
walletNotify.notifyWithdrawalFailed('user-1', {
amountRaw: 2_000_000n,
feeRaw: 500_000n,
toAddress: 'TShortAddrOnly',
transactionId: 'tx-fail-1',
reason: 'hot wallet empty',
})
);
assert.equal(inAppCalls.length, 0);
assert.equal(emailCalls.length, 1);
assert.equal(emailCalls[0].fn, 'sendWithdrawalFailedEmail');
assert.equal(emailCalls[0].payload.reason, 'hot wallet empty');
});
test('transfer sent + received: masks emails and notifies both sides', async () => {
installStubs({ email: 'bob@tloto.app' });
await walletNotify.notifyTransferSent('sender-1', {
amountRaw: 3_500_000n,
toEmail: 'carol@example.com',
transactionId: 'tx-out-1',
});
assert.equal(inAppCalls[0].eventType, 'transfer_sent');
assert.match(inAppCalls[0].body || '', /3\.5 USDT/);
assert.match(inAppCalls[0].body || '', /ca\*\*\*@example\.com/);
assert.equal(emailCalls[0].fn, 'sendTransferSentEmail');
assert.equal(emailCalls[0].payload.counterpartyEmailMasked, 'ca***@example.com');
inAppCalls = [];
emailCalls = [];
// Recipient resolve uses same stub email; fromUserId email is also resolved via stub.
await walletNotify.notifyTransferReceived('recipient-1', {
amountRaw: 3_500_000n,
fromUserId: 'sender-1',
transactionId: 'tx-in-1',
});
assert.equal(inAppCalls[0].eventType, 'transfer_received');
assert.equal(emailCalls[0].fn, 'sendTransferReceivedEmail');
assert.match(String(emailCalls[0].payload.counterpartyEmailMasked), /bo\*\*\*@tloto\.app/);
});
test('skips email when user has no resolvable address, still writes in-app', async () => {
installStubs({ email: null });
await walletNotify.notifyTransferSent('user-no-email', {
amountRaw: 1_000_000n,
toEmail: 'x@y.com',
transactionId: 'tx-out-2',
});
assert.equal(inAppCalls.length, 1);
assert.equal(emailCalls.length, 0);
});
test('email templates export and run under console transport', async () => {
// Restore real email fns for this case.
for (const name of emailFnNames) {
(emailService as Record<string, unknown>)[name] = originalEmailFns[name];
}
await assert.doesNotReject(() =>
emailService.sendWithdrawalSubmittedEmail('test@example.com', {
amountUsdt: '1',
feeUsdt: '0.5',
totalUsdt: '1.5',
toAddressMasked: 'TXYZab…ABCD',
network: 'TRON',
pendingApproval: true,
})
);
await assert.doesNotReject(() =>
emailService.sendWithdrawalCompletedEmail('test@example.com', {
amountUsdt: '1',
feeUsdt: '0.5',
totalUsdt: '1.5',
toAddressMasked: '0x1234…5678',
network: 'BSC',
blockchainTxId: '0xabc',
})
);
await assert.doesNotReject(() =>
emailService.sendWithdrawalFailedEmail('test@example.com', {
amountUsdt: '1',
toAddressMasked: 'TXYZab…ABCD',
reason: 'rejected',
})
);
await assert.doesNotReject(() =>
emailService.sendTransferSentEmail('test@example.com', {
amountUsdt: '2',
counterpartyEmailMasked: 'ab***@x.com',
})
);
await assert.doesNotReject(() =>
emailService.sendTransferReceivedEmail('test@example.com', {
amountUsdt: '2',
counterpartyEmailMasked: 'cd***@y.com',
})
);
});
});
describe('wallet notify wiring', () => {
const servicesDir = path.join(__dirname, '../services');
test('withdrawalService hooks submitted / completed / failed', () => {
const src = fs.readFileSync(path.join(servicesDir, 'withdrawalService.js'), 'utf8');
assert.match(src, /walletNotificationService/);
assert.match(src, /notifyWithdrawalSubmitted/);
assert.match(src, /notifyWithdrawalCompleted/);
assert.match(src, /notifyWithdrawalFailed/);
assert.match(src, /pendingApproval:\s*true/);
});
test('transferService hooks sent + received for both users', () => {
const src = fs.readFileSync(path.join(servicesDir, 'transferService.js'), 'utf8');
assert.match(src, /walletNotificationService/);
assert.match(src, /notifyTransferSent/);
assert.match(src, /notifyTransferReceived/);
});
});

View File

@ -1,6 +1,6 @@
# Bonuses Guide — Tloto
This guide explains what the **Bonus** wallet is, how to receive bonus credits, how to use them on Candle Predict, and what you can (or cannot) do with them.
This guide explains what the **Bonus** wallet is, how to receive bonus credits, how to use them on **Candle Predict** (FO / USDT positions), and what you can (or cannot) do with them.
<!--
For https://markdowntoword.io/tools/markdown-to-pdf :
@ -12,20 +12,20 @@ This guide explains what the **Bonus** wallet is, how to receive bonus credits,
<h2>1. What is the Bonus wallet?</h2>
<p>On Tloto, you can have several wallets. Here is the simple difference:</p>
<ul>
<li><strong>Main</strong>: your real USDT balance (deposits, play, withdrawals, transfers).</li>
<li><strong>Bonus</strong>: USDT credits to play <strong>Candle Predict</strong>.</li>
<li><strong>Main</strong>: your real USDT balance (deposits, market positions, withdrawals, transfers).</li>
<li><strong>Bonus</strong>: USDT credits to take positions on <strong>Candle Predict</strong> (FO / USDT).</li>
<li><strong>Test</strong>: a practice balance. It cannot be withdrawn and cannot move to Main.</li>
</ul>
<p>Bonus is mainly for <strong>making predictions</strong>. It is not the same balance as your deposits.</p>
<p>Bonus is mainly for <strong>Candle Predict positions</strong>. It is not the same balance as your deposits.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>2. How do I receive Bonus credits?</h2>
<p>You can receive Bonus in several ways, depending on what is active on the platform:</p>
<ul>
<li><strong>Referrals</strong>: commissions credited to your Bonus when your network plays in an eligible way.</li>
<li><strong>Referrals</strong>: commissions credited to your Bonus when your network places eligible Candle Predict positions.</li>
<li><strong>Offers / Campaigns</strong>: promotions shown on the home screen. Follow the offer instructions.</li>
<li><strong>Play eligibility</strong>: depending on your activity, the platform may make you eligible for an extra Bonus.</li>
<li><strong>Activity eligibility</strong>: depending on your market activity, the platform may make you eligible for an extra Bonus.</li>
<li><strong>Platform credit</strong>: sometimes a bonus appears in wallet activity after a support or platform action.</li>
</ul>
<p>Exact amounts and conditions are the ones <strong>shown in the app</strong>.</p>
@ -35,7 +35,7 @@ This guide explains what the **Bonus** wallet is, how to receive bonus credits,
<h2>3. How do I use Bonus?</h2>
<ol>
<li>Open <strong>Candle Predict</strong>.</li>
<li>Choose the <strong>Bonus</strong> wallet for your prediction.</li>
<li>Choose the <strong>Bonus</strong> wallet for your position.</li>
<li>Enter the amount (within the limits shown and your Bonus balance).</li>
<li>Confirm while participation is still <strong>open</strong>.</li>
</ol>
@ -43,22 +43,22 @@ This guide explains what the **Bonus** wallet is, how to receive bonus credits,
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>4. Where do winnings go when I play with Bonus?</h2>
<h2>4. Where do winnings go when I use Bonus?</h2>
<ul>
<li><strong>Won</strong>: the win usually arrives in the <strong>Main</strong> wallet.</li>
<li><strong>Lost</strong>: the Bonus amount you used is lost.</li>
<li><strong>Neutral / refunded</strong>: the amount returns to the <strong>Bonus</strong> wallet.</li>
</ul>
<p>Example: you play 5 USDT from Bonus and win. The win is credited to <strong>Main</strong>. You can then withdraw it under the withdrawal rules, if your Main balance allows it.</p>
<p>Example: you place 5 USDT from Bonus and win. The win is credited to <strong>Main</strong>. You can then withdraw it under the withdrawal rules, if your Main balance allows it.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>5. Can I withdraw or move my Bonus?</h2>
<p>By default, Bonus is for <strong>playing</strong>, not for cashing out directly.</p>
<p>By default, Bonus is for <strong>Candle Predict positions</strong>, not for cashing out directly.</p>
<ul>
<li>Check your <strong>Wallet</strong> screen.</li>
<li>If a button like <strong>Move all to main wallet</strong> is shown, Bonus → Main transfer is allowed.</li>
<li>If not, Bonus stays for predictions only.</li>
<li>If not, Bonus stays available for Candle Predict only.</li>
</ul>
<p>Even when transfer is possible, on-chain withdrawal still happens from <strong>Main</strong> afterward (see the Withdrawals guide).</p>
</div>
@ -77,8 +77,8 @@ This guide explains what the **Bonus** wallet is, how to receive bonus credits,
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>7. Common problems</h2>
<ul>
<li><strong>Bonus balance too low</strong>: lower the amount, or play with Main.</li>
<li><strong>No transfer to Main</strong>: the platform does not allow it right now. Play with Bonus, or use gains already on Main.</li>
<li><strong>Bonus balance too low</strong>: lower the amount, or use Main.</li>
<li><strong>No transfer to Main</strong>: the platform does not allow it right now. Use Bonus on Candle Predict, or use gains already on Main.</li>
<li><strong>Missing referral commission</strong>: check the Referrals guide (eligible activity, not Test wallet, not a neutral result).</li>
<li><strong>Offer seen but no Bonus</strong>: the carousel advertises the offer; the credit depends on the conditions you complete.</li>
</ul>
@ -89,9 +89,9 @@ This guide explains what the **Bonus** wallet is, how to receive bonus credits,
<p>Contact Tloto <strong>support</strong> if:</p>
<ol>
<li>An expected Bonus does not appear.</li>
<li>A win played with Bonus does not arrive on Main.</li>
<li>A win funded with Bonus does not arrive on Main.</li>
<li>A Bonus → Main transfer shown on screen does not work.</li>
</ol>
<p>Share the time, the amount, and the type of activity (prediction, referral, offer).</p>
<p>Share the time, the amount, and the type of activity (Candle Predict position, referral, offer).</p>
<p>See also the <strong>Predictions</strong>, <strong>Referrals</strong>, and <strong>Withdrawals</strong> guides.</p>
</div>

View File

@ -1,6 +1,6 @@
# Guide Bonus — Tloto
Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des crédits bonus, comment les utiliser sur Candle Predict, et ce que vous pouvez (ou ne pouvez pas) en faire.
Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des crédits bonus, comment les utiliser sur **Candle Predict** (positions FO / USDT), et ce que vous pouvez (ou ne pouvez pas) en faire.
<!--
Pour https://markdowntoword.io/tools/markdown-to-pdf :
@ -12,20 +12,20 @@ Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des cré
<h2>1. Qu'est-ce que le portefeuille Bonus ?</h2>
<p>Sur Tloto, vous pouvez avoir plusieurs portefeuilles. Voici la différence simple :</p>
<ul>
<li><strong>Principal</strong> : votre solde USDT réel (dépôts, jeux, retraits, transferts).</li>
<li><strong>Bonus</strong> : des crédits USDT pour jouer à <strong>Candle Predict</strong>.</li>
<li><strong>Principal</strong> : votre solde USDT réel (dépôts, positions de marché, retraits, transferts).</li>
<li><strong>Bonus</strong> : des crédits USDT pour prendre des positions sur <strong>Candle Predict</strong> (FO / USDT).</li>
<li><strong>Test</strong> : un solde d'entraînement. Il ne se retire pas et ne passe pas vers le Principal.</li>
</ul>
<p>Le Bonus sert surtout à <strong>participer aux prédictions</strong>. Ce n'est pas le même solde que vos dépôts.</p>
<p>Le Bonus sert surtout aux <strong>positions Candle Predict</strong>. Ce n'est pas le même solde que vos dépôts.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>2. Comment recevoir des crédits Bonus ?</h2>
<p>Vous pouvez recevoir du Bonus de plusieurs façons, selon ce qui est actif sur la plateforme :</p>
<ul>
<li><strong>Parrainage</strong> : commissions créditées sur votre Bonus quand votre réseau joue de façon éligible.</li>
<li><strong>Parrainage</strong> : commissions créditées sur votre Bonus quand votre réseau place des positions Candle Predict éligibles.</li>
<li><strong>Offres / Campagnes</strong> : promotions affichées sur l'accueil. Suivez les instructions de l'offre.</li>
<li><strong>Éligibilité de jeu</strong> : selon votre activité, la plateforme peut vous rendre éligible à un Bonus supplémentaire.</li>
<li><strong>Éligibilité d'activité</strong> : selon votre activité de marché, la plateforme peut vous rendre éligible à un Bonus supplémentaire.</li>
<li><strong>Crédit plateforme</strong> : parfois un bonus apparaît dans l'activité du portefeuille après une action du support ou de la plateforme.</li>
</ul>
<p>Les montants et conditions exactes sont ceux <strong>affichés dans l'application</strong>.</p>
@ -35,7 +35,7 @@ Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des cré
<h2>3. Comment utiliser le Bonus ?</h2>
<ol>
<li>Ouvrez <strong>Candle Predict</strong>.</li>
<li>Choisissez le portefeuille <strong>Bonus</strong> pour votre prédiction.</li>
<li>Choisissez le portefeuille <strong>Bonus</strong> pour votre position.</li>
<li>Indiquez le montant (dans les limites affichées et selon votre solde Bonus).</li>
<li>Confirmez pendant que la participation est <strong>ouverte</strong>.</li>
</ol>
@ -43,22 +43,22 @@ Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des cré
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>4. Où vont les gains joués avec le Bonus ?</h2>
<h2>4. Où vont les gains financés avec le Bonus ?</h2>
<ul>
<li><strong>Gagné</strong> : le gain arrive en général sur le portefeuille <strong>Principal</strong>.</li>
<li><strong>Perdu</strong> : le montant Bonus utilisé est perdu.</li>
<li><strong>Neutre / remboursé</strong> : le montant revient sur le portefeuille <strong>Bonus</strong>.</li>
</ul>
<p>Exemple : vous jouez 5 USDT en Bonus et gagnez. Le gain est crédité sur le <strong>Principal</strong>. Vous pourrez ensuite le retirer selon les règles de retrait, si le solde Principal le permet.</p>
<p>Exemple : vous placez 5 USDT en Bonus et gagnez. Le gain est crédité sur le <strong>Principal</strong>. Vous pourrez ensuite le retirer selon les règles de retrait, si le solde Principal le permet.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>5. Puis-je retirer ou transférer mon Bonus ?</h2>
<p>Par défaut, le Bonus sert à <strong>jouer</strong>, pas à sortir les fonds directement.</p>
<p>Par défaut, le Bonus sert aux <strong>positions Candle Predict</strong>, pas à sortir les fonds directement.</p>
<ul>
<li>Regardez votre écran <strong>Portefeuille</strong>.</li>
<li>Si un bouton comme <strong>Tout transférer vers le principal</strong> est proposé, le transfert Bonus → Principal est autorisé.</li>
<li>Sinon, le Bonus reste réservé aux prédictions.</li>
<li>Sinon, le Bonus reste réservé à Candle Predict.</li>
</ul>
<p>Même quand le transfert est possible, le retrait on-chain se fait ensuite depuis le <strong>Principal</strong> (voir le guide Retraits).</p>
</div>
@ -77,8 +77,8 @@ Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des cré
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>7. Problèmes fréquents</h2>
<ul>
<li><strong>Solde Bonus trop bas</strong> : baissez le montant, ou jouez avec le Principal.</li>
<li><strong>Pas de transfert vers le Principal</strong> : la plateforme ne l'autorise pas pour le moment. Jouez avec le Bonus, ou utilisez les gains déjà sur le Principal.</li>
<li><strong>Solde Bonus trop bas</strong> : baissez le montant, ou utilisez le Principal.</li>
<li><strong>Pas de transfert vers le Principal</strong> : la plateforme ne l'autorise pas pour le moment. Utilisez le Bonus sur Candle Predict, ou utilisez les gains déjà sur le Principal.</li>
<li><strong>Commission de parrainage absente</strong> : vérifiez le guide Parrainage (activité éligible, pas de portefeuille Test, pas de résultat neutre).</li>
<li><strong>Offre vue mais pas de Bonus</strong> : le carrousel annonce l'offre ; le crédit dépend des conditions remplies.</li>
</ul>
@ -89,9 +89,9 @@ Ce guide explique ce qu'est le portefeuille **Bonus**, comment recevoir des cré
<p>Contactez le <strong>support</strong> Tloto si :</p>
<ol>
<li>Un Bonus attendu n'apparaît pas.</li>
<li>Un gain joué en Bonus n'arrive pas sur le Principal.</li>
<li>Un gain financé en Bonus n'arrive pas sur le Principal.</li>
<li>Un transfert Bonus → Principal affiché ne fonctionne pas.</li>
</ol>
<p>Indiquez l'heure, le montant et le type d'activité (prédiction, parrainage, offre).</p>
<p>Indiquez l'heure, le montant et le type d'activité (position Candle Predict, parrainage, offre).</p>
<p>Voir aussi les guides <strong>Prédictions</strong>, <strong>Parrainage</strong> et <strong>Retraits</strong>.</p>
</div>

View File

@ -15,7 +15,7 @@ This guide explains how to **credit your USDT balance** on Tloto, which networks
<ul>
<li>Deposits are in <strong>USDT</strong></li>
<li>Two networks may be offered: <strong>TRON (TRC20)</strong> and <strong>BSC (BEP20)</strong></li>
<li>Credited funds go into a <strong>single USDT balance</strong> used for playing (Candle Predict)</li>
<li>Credited funds go into a <strong>single USDT balance</strong> used for market activity on Candle Predict (FO / USDT) and other wallet actions</li>
<li>Credit appears only after the required <strong>blockchain confirmations</strong></li>
</ul>
</div>
@ -89,7 +89,7 @@ Sending USDT on the <strong>wrong network</strong> may cause <strong>permanent l
<p>Once funds are credited:</p>
<ul>
<li>Your main USDT balance increases</li>
<li>You can play <strong>Candle Predict</strong></li>
<li>You can take positions on <strong>Candle Predict</strong> (FO / USDT)</li>
<li>You can later withdraw or transfer according to platform rules</li>
<li>A real-funds deposit may also be required for some features (for example referrals)</li>
</ul>

View File

@ -15,7 +15,7 @@ Ce guide explique comment **créditer votre solde USDT** sur Tloto, quels résea
<ul>
<li>Les dépôts se font en <strong>USDT</strong></li>
<li>Deux réseaux peuvent être proposés : <strong>TRON (TRC20)</strong> et <strong>BSC (BEP20)</strong></li>
<li>Les fonds crédités rejoignent un <strong>solde USDT unique</strong> utilisable pour jouer (Candle Predict)</li>
<li>Les fonds crédités rejoignent un <strong>solde USDT unique</strong> utilisable pour l'activité de marché sur Candle Predict (FO / USDT) et les autres actions portefeuille</li>
<li>Le crédit n'est visible qu'après les <strong>confirmations blockchain</strong> requises</li>
</ul>
</div>
@ -89,7 +89,7 @@ Envoyer des USDT sur le <strong>mauvais réseau</strong> peut entraîner une <st
<p>Une fois les fonds crédités :</p>
<ul>
<li>Votre solde principal USDT augmente</li>
<li>Vous pouvez jouer à <strong>Candle Predict</strong></li>
<li>Vous pouvez prendre des positions sur <strong>Candle Predict</strong> (FO / USDT)</li>
<li>Vous pourrez plus tard retirer ou transférer selon les règles de la plateforme</li>
<li>Un dépôt en fonds réels peut aussi être requis pour certaines fonctionnalités (par exemple le parrainage)</li>
</ul>

View File

@ -1,6 +1,6 @@
# Predictions Guide — Tloto
This guide explains how to play **Candle Predict**: predict whether the next candle goes up or down, play with an amount, and understand wins and refunds.
This guide explains how **Candle Predict** works on Tloto: how to take a directional position on **FO (Full Option) / USDT**, how sessions run, and how settlements and refunds are applied.
<!--
For https://markdowntoword.io/tools/markdown-to-pdf :
@ -10,38 +10,48 @@ This guide explains how to play **Candle Predict**: predict whether the next can
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>1. What is Candle Predict?</h2>
<p>Candle Predict is Tloto's prediction game.</p>
<p>You choose whether the <strong>next candle</strong> on the <strong>FO/USDT</strong> instrument will go:</p>
<p><strong>Candle Predict</strong> is Tloto's market product for directional positions on <strong>FO (Full Option) / USDT</strong>.</p>
<p><strong>FO (Full Option)</strong> is the platform instrument that tracks the aggregate movement of the world's <strong>liquid public financial markets</strong> — the publicly traded, readily priced asset stock — quoted against <strong>USDT</strong>. On the chart it appears as <strong>FO (Full Option) / USDT</strong>, with price levels in <strong>trillions (T)</strong>.</p>
<p>That liquid public market stock covers, in particular:</p>
<ul>
<li><strong>Listed equities</strong> — shares of publicly traded companies on major exchanges</li>
<li><strong>Public bonds / debt securities</strong> — sovereign and other liquid listed fixed-income instruments</li>
<li><strong>Liquid cryptocurrencies</strong> — major crypto assets with deep, continuous public pricing</li>
<li><strong>Major FX pairs</strong> — highly liquid foreign-exchange markets</li>
<li><strong>Listed futures and options</strong> — exchange-traded derivatives on indices, rates, currencies, and commodities</li>
<li><strong>Other liquid public instruments</strong> — for example listed ETFs and other exchange-traded products with reliable market prices</li>
</ul>
<p>In short, Full Option stands for the combined variation of these public markets, not a single isolated asset.</p>
<p>On each candle, you take a position on the next move:</p>
<ul>
<li><strong>Short</strong> (down ↓)</li>
<li><strong>Long</strong> (up ↑)</li>
</ul>
<p>Candles move in a random way, following the variations of <strong>FO/USDT</strong>.</p>
<p>To play: open the <strong>Games</strong> catalog → <strong>Candle Predict</strong>.</p>
<p>To open a session: platform catalog → <strong>Candle Predict</strong>.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>2. Before you play</h2>
<h2>2. Before you start</h2>
<ol>
<li>Sign in to your Tloto account.</li>
<li>Check that you have enough balance on the wallet you choose (<strong>Main</strong>, <strong>Bonus</strong>, or <strong>Test</strong> if it is offered).</li>
<li>Confirm that the wallet you intend to use has enough balance (<strong>Main</strong>, <strong>Bonus</strong>, or <strong>Test</strong> when available).</li>
<li>Open <strong>Candle Predict</strong>.</li>
<li>Choose a <strong>period</strong> from those shown (for example 1, 3, or 5 minutes).</li>
<li>Select a <strong>period</strong> among those displayed (for example 1, 3, or 5 minutes).</li>
</ol>
<p>You can play only when the status is <strong>open</strong>, before the candle starts.</p>
<p>Positions can be placed only while the session status is <strong>open</strong>, before the candle starts.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>3. Make a prediction</h2>
<h2>3. Place a position</h2>
<ol>
<li>Choose the <strong>wallet</strong> (Main, Bonus, or Test).</li>
<li>Choose a mode from those shown: <strong>Single</strong>, <strong>Multi</strong>, or <strong>Auto</strong>.</li>
<li>Choose <strong>Short</strong> or <strong>Long</strong> (in Multi: several directions in a row).</li>
<li>Enter the <strong>amount</strong> (between the minimum and maximum shown).</li>
<li>Look at the <strong>possible gain</strong> on screen (for example Payout ×…).</li>
<li>Select the <strong>wallet</strong> (Main, Bonus, or Test).</li>
<li>Choose a mode among those shown: <strong>Single</strong>, <strong>Multi</strong>, or <strong>Auto</strong>.</li>
<li>Choose <strong>Short</strong> or <strong>Long</strong> (in Multi: a sequence of directions).</li>
<li>Enter the <strong>amount</strong> (within the minimum and maximum shown).</li>
<li>Review the <strong>potential payout</strong> on screen (for example Payout ×…).</li>
<li>Confirm while participation is still <strong>open</strong>.</li>
</ol>
<p>In general, you can make only <strong>one prediction</strong> per round and per account. Single and Multi cannot be used at the same time on the same round.</p>
<p>In general, only <strong>one active position</strong> is allowed per round and per account. Single and Multi cannot be used together on the same round.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
@ -51,59 +61,59 @@ This guide explains how to play **Candle Predict**: predict whether the next can
<tr><th>Mode</th><th>How it works</th></tr>
</thead>
<tbody>
<tr><td><strong>Single</strong></td><td>You predict Short or Long for the next candle.</td></tr>
<tr><td><strong>Multi</strong></td><td>You predict several candles in a row, in a precise order. One wrong candle stops the sequence.</td></tr>
<tr><td><strong>Auto</strong></td><td>The game places an automatic prediction each round, on the period you chose.</td></tr>
<tr><td><strong>Single</strong></td><td>One Short or Long position on the next candle of FO / USDT.</td></tr>
<tr><td><strong>Multi</strong></td><td>A defined sequence of candle directions. One incorrect candle ends the sequence.</td></tr>
<tr><td><strong>Auto</strong></td><td>An automatic position is submitted each round on the period you selected.</td></tr>
</tbody>
</table>
<p>You only see the modes shown on screen. If a mode does not appear, it is not available right now.</p>
<p>Only modes shown on screen are available. If a mode is missing, it is currently disabled.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>5. How a round works</h2>
<h2>5. How a session works</h2>
<ul>
<li><strong>Open</strong>: you can make your prediction during the countdown.</li>
<li><strong>Locked</strong>: the candle is running. You cannot predict for this round anymore.</li>
<li><strong>Waiting</strong>: the game is waiting for the next opening.</li>
<li><strong>Finished</strong>: the result is known — Short, Long, or <strong>neutral</strong>.</li>
<li><strong>Open</strong>: you may place your position during the countdown.</li>
<li><strong>Locked</strong>: the candle is in progress. No further positions for this round.</li>
<li><strong>Waiting</strong>: the market is waiting for the next opening window.</li>
<li><strong>Finished</strong>: the outcome is known — Short, Long, or <strong>neutral</strong>.</li>
</ul>
<p>When the candle ends, the result appears. You can also see the details in your history (in progress, won, lost, refunded).</p>
<p>When the candle closes, the result is displayed. You can also review status in your history (in progress, won, lost, refunded).</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>6. Wins, losses, and neutral result</h2>
<h2>6. Settlement: wins, losses, and neutral</h2>
<ul>
<li><strong>Won</strong>: your prediction is correct. You receive about <strong>amount × shown gain</strong> from the confirmation screen.</li>
<li><strong>Lost</strong>: your prediction is wrong. You lose that amount.</li>
<li><strong>Neutral</strong>: the result is not clearly Short or clearly Long. Your amount is <strong>refunded</strong>.</li>
<li><strong>Won</strong>: your direction matches the candle result. You receive about <strong>amount × shown payout</strong> from the confirmation screen.</li>
<li><strong>Lost</strong>: your direction does not match. The amount for that position is lost.</li>
<li><strong>Neutral</strong>: the candle is neither clearly Short nor clearly Long. Your amount is <strong>refunded</strong>.</li>
</ul>
<p>Useful examples:</p>
<ul>
<li>If you play with 10 USDT and the shown gain is ×1.9, a correct result gives you about 19 USDT.</li>
<li>A win played with the <strong>Bonus</strong> wallet usually arrives on the <strong>Main</strong> balance.</li>
<li>The <strong>Test</strong> wallet is for practice. Funds stay in Test and cannot be withdrawn.</li>
<li>With 10 USDT and a shown payout of ×1.9, a correct result returns about 19 USDT.</li>
<li>A win funded from the <strong>Bonus</strong> wallet is usually credited to the <strong>Main</strong> balance.</li>
<li>The <strong>Test</strong> wallet is for practice only. Funds stay in Test and cannot be withdrawn.</li>
</ul>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>7. Common mistakes to avoid</h2>
<ul>
<li>Trying to predict when the round is already <strong>locked</strong></li>
<li>Choosing the wrong <strong>period</strong> (especially with Auto mode)</li>
<li>Using an amount higher than the balance of the <strong>chosen wallet</strong></li>
<li>In Multi: one wrong candle fails the whole sequence</li>
<li>Thinking a <strong>neutral</strong> result is a loss (it is a refund)</li>
<li>Trying to place a position when the round is already <strong>locked</strong></li>
<li>Selecting the wrong <strong>period</strong> (especially with Auto)</li>
<li>Using an amount higher than the balance of the <strong>selected wallet</strong></li>
<li>In Multi: one incorrect candle fails the entire sequence</li>
<li>Treating a <strong>neutral</strong> result as a loss (it is a refund)</li>
</ul>
<p>If you are new, start in <strong>Single</strong> mode with a small amount, or use the <strong>Test</strong> wallet if it is offered.</p>
<p>If you are new to FO (Full Option), start in <strong>Single</strong> with a small amount, or use the <strong>Test</strong> wallet when available.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>8. Need help?</h2>
<p>If a prediction stays stuck, a win does not appear, or the status looks wrong:</p>
<p>If a position stays pending, a settlement does not appear, or a status looks incorrect:</p>
<ol>
<li>Refresh the game screen and check your history.</li>
<li>Check the wallet you used and the balance (Main / Bonus / Test).</li>
<li>Contact Tloto <strong>support</strong> with the time, the period, and the expected result.</li>
<li>Refresh the Candle Predict screen and check your history.</li>
<li>Verify the wallet used and the balance (Main / Bonus / Test).</li>
<li>Contact Tloto <strong>support</strong> with the time, the period, and the expected outcome.</li>
</ol>
<p>To add funds to Main, see the <strong>Deposits</strong> guide. To take funds out, see the <strong>Withdrawals</strong> guide.</p>
<p>To fund Main, see the <strong>Deposits</strong> guide. To withdraw, see the <strong>Withdrawals</strong> guide.</p>
</div>

View File

@ -1,6 +1,6 @@
# Guide Prédictions — Tloto
Ce guide explique comment jouer à **Candle Predict** : prédire si la prochaine bougie monte ou descend, participer avec un montant, et comprendre les gains et les remboursements.
Ce guide explique le fonctionnement de **Candle Predict** sur Tloto : comment prendre une position directionnelle sur **FO (Full Option) / USDT**, comment se déroulent les sessions, et comment sont appliqués les règlements et remboursements.
<!--
Pour https://markdowntoword.io/tools/markdown-to-pdf :
@ -10,100 +10,110 @@ Ce guide explique comment jouer à **Candle Predict** : prédire si la prochaine
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>1. Qu'est-ce que Candle Predict ?</h2>
<p>Candle Predict est le jeu de prédiction de Tloto.</p>
<p>Vous choisissez si la <strong>prochaine bougie</strong> de l'instrument <strong>FO/USDT</strong> ira :</p>
<p><strong>Candle Predict</strong> est le produit de marché de Tloto permettant de prendre des positions directionnelles sur <strong>FO (Full Option) / USDT</strong>.</p>
<p><strong>FO (Full Option)</strong> est l'instrument de la plateforme qui suit la variation agrégée des <strong>marchés financiers publics liquides</strong> — le stock d'actifs cotés, négociables et disposant d'un prix de marché fiable — coté contre <strong>USDT</strong>. Sur le graphique, il apparaît sous la forme <strong>FO (Full Option) / USDT</strong>, avec des niveaux de prix exprimés en <strong>trillions (T)</strong>.</p>
<p>Ce stock d'actifs des marchés publics liquides couvre notamment :</p>
<ul>
<li><strong>Actions cotées</strong> — titres des sociétés listées sur les grandes bourses</li>
<li><strong>Obligations / titres de dette publics</strong> — instruments de taux souverains et autres titres de dette liquides cotés</li>
<li><strong>Crypto liquides</strong> — principaux actifs crypto disposant d'une cotation publique continue et profonde</li>
<li><strong>Devises majeures (FX)</strong> — paires de change très liquides</li>
<li><strong>Futures et options listés</strong> — dérivés négociés en bourse sur indices, taux, devises et matières premières</li>
<li><strong>Autres instruments publics liquides</strong> — par exemple ETF et autres produits cotés disposant d'un prix de marché fiable</li>
</ul>
<p>En résumé, Full Option symbolise la variation combinée de ces marchés publics, et non un actif isolé.</p>
<p>Sur chaque bougie, vous prenez une position sur le prochain mouvement :</p>
<ul>
<li><strong>Short</strong> (en baisse ↓)</li>
<li><strong>Long</strong> (en hausse ↑)</li>
</ul>
<p>Les bougies évoluent de façon aléatoire, selon les variations de <strong>FO/USDT</strong>.</p>
<p>Pour jouer : ouvrez le catalogue <strong>Jeux</strong> → <strong>Candle Predict</strong>.</p>
<p>Pour ouvrir une session : catalogue de la plateforme → <strong>Candle Predict</strong>.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>2. Avant de jouer</h2>
<h2>2. Avant de commencer</h2>
<ol>
<li>Connectez-vous à votre compte Tloto.</li>
<li>Vérifiez que vous avez assez de solde sur le portefeuille choisi (<strong>Principal</strong>, <strong>Bonus</strong> ou <strong>Test</strong> s'il est proposé).</li>
<li>Vérifiez que le portefeuille que vous souhaitez utiliser dispose d'un solde suffisant (<strong>Principal</strong>, <strong>Bonus</strong> ou <strong>Test</strong> s'il est proposé).</li>
<li>Ouvrez <strong>Candle Predict</strong>.</li>
<li>Choisissez une <strong>période</strong> parmi celles affichées (par exemple 1, 3 ou 5 minutes).</li>
<li>Sélectionnez une <strong>période</strong> parmi celles affichées (par exemple 1, 3 ou 5 minutes).</li>
</ol>
<p>Vous pouvez participer seulement quand le statut est <strong>ouvert</strong>, avant le début de la bougie.</p>
<p>Les positions ne peuvent être placées que lorsque le statut de session est <strong>ouvert</strong>, avant le début de la bougie.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>3. Faire une prédiction</h2>
<h2>3. Placer une position</h2>
<ol>
<li>Choisissez le <strong>portefeuille</strong> (Principal, Bonus ou Test).</li>
<li>Sélectionnez le <strong>portefeuille</strong> (Principal, Bonus ou Test).</li>
<li>Choisissez un mode parmi ceux affichés : <strong>Simple</strong>, <strong>Multi</strong> ou <strong>Auto</strong>.</li>
<li>Choisissez <strong>Short</strong> ou <strong>Long</strong> (en Multi : plusieurs directions à la suite).</li>
<li>Choisissez <strong>Short</strong> ou <strong>Long</strong> (en Multi : une séquence de directions).</li>
<li>Indiquez le <strong>montant</strong> (entre le minimum et le maximum affichés).</li>
<li>Regardez le <strong>gain possible</strong> montré à l'écran (par exemple Payout ×…).</li>
<li>Vérifiez le <strong>gain potentiel</strong> affiché à l'écran (par exemple Payout ×…).</li>
<li>Confirmez tant que la participation est encore <strong>ouverte</strong>.</li>
</ol>
<p>En général, vous ne pouvez faire qu'<strong>une prédiction</strong> par manche et par compte. Simple et Multi ne peuvent pas être utilisés en même temps sur la même manche.</p>
<p>En général, une seule <strong>position active</strong> est autorisée par manche et par compte. Simple et Multi ne peuvent pas être utilisés ensemble sur la même manche.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>4. Modes Simple, Multi et Auto</h2>
<table>
<thead>
<tr><th>Mode</th><th>Comment ça marche</th></tr>
<tr><th>Mode</th><th>Fonctionnement</th></tr>
</thead>
<tbody>
<tr><td><strong>Simple</strong></td><td>Vous prédisez Short ou Long pour la prochaine bougie.</td></tr>
<tr><td><strong>Multi</strong></td><td>Vous prédisez plusieurs bougies à la suite, dans un ordre précis. Une seule erreur arrête la séquence.</td></tr>
<tr><td><strong>Auto</strong></td><td>Le jeu place une prédiction automatique à chaque manche, sur la période choisie.</td></tr>
<tr><td><strong>Simple</strong></td><td>Une position Short ou Long sur la prochaine bougie de FO / USDT.</td></tr>
<tr><td><strong>Multi</strong></td><td>Une séquence définie de directions de bougies. Une seule bougie incorrecte met fin à la séquence.</td></tr>
<tr><td><strong>Auto</strong></td><td>Une position automatique est soumise à chaque manche sur la période sélectionnée.</td></tr>
</tbody>
</table>
<p>Vous ne voyez que les modes proposés à l'écran. Si un mode n'apparaît pas, il n'est pas disponible pour le moment.</p>
<p>Seuls les modes affichés à l'écran sont disponibles. Si un mode n'apparaît pas, il est temporairement désactivé.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>5. Déroulement d'une manche</h2>
<h2>5. Déroulement d'une session</h2>
<ul>
<li><strong>Ouvert</strong> : vous pouvez faire votre prédiction pendant le compte à rebours.</li>
<li><strong>Verrouillé</strong> : la bougie est en cours. Vous ne pouvez plus prédire pour cette manche.</li>
<li><strong>En attente</strong> : le jeu attend la prochaine ouverture.</li>
<li><strong>Ouvert</strong> : vous pouvez placer votre position pendant le compte à rebours.</li>
<li><strong>Verrouillé</strong> : la bougie est en cours. Aucune nouvelle position pour cette manche.</li>
<li><strong>En attente</strong> : le marché attend la prochaine fenêtre d'ouverture.</li>
<li><strong>Terminé</strong> : le résultat est connu — Short, Long, ou <strong>neutre</strong>.</li>
</ul>
<p>Quand la bougie se termine, le résultat s'affiche. Vous pouvez aussi voir le détail dans l'historique (en cours, gagné, perdu, remboursé).</p>
<p>À la clôture de la bougie, le résultat s'affiche. Vous pouvez aussi consulter le détail dans l'historique (en cours, gagné, perdu, remboursé).</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>6. Gains, pertes et résultat neutre</h2>
<h2>6. Règlement : gains, pertes et neutre</h2>
<ul>
<li><strong>Gagné</strong> : votre prédiction est bonne. Vous recevez environ <strong>montant × gain affiché</strong> au moment de la confirmation.</li>
<li><strong>Perdu</strong> : votre prédiction est mauvaise. Vous perdez ce montant.</li>
<li><strong>Neutre</strong> : le résultat n'est ni clairement Short ni clairement Long. Votre montant vous est <strong>remboursé</strong>.</li>
<li><strong>Gagné</strong> : votre direction correspond au résultat de la bougie. Vous recevez environ <strong>montant × gain affiché</strong> au moment de la confirmation.</li>
<li><strong>Perdu</strong> : votre direction ne correspond pas. Le montant de la position est perdu.</li>
<li><strong>Neutre</strong> : la bougie n'est ni clairement Short ni clairement Long. Votre montant vous est <strong>remboursé</strong>.</li>
</ul>
<p>Exemples utiles :</p>
<ul>
<li>Si vous participez avec 10 USDT et que le gain affiché est ×1,9, un bon résultat vous rapporte environ 19 USDT.</li>
<li>Un gain joué avec le portefeuille <strong>Bonus</strong> arrive en général sur le solde <strong>Principal</strong>.</li>
<li>Le portefeuille <strong>Test</strong> sert à s'entraîner. Les fonds restent dans le Test et ne se retirent pas.</li>
<li>Avec 10 USDT et un gain affiché de ×1,9, un résultat correct rapporte environ 19 USDT.</li>
<li>Un gain financé via le portefeuille <strong>Bonus</strong> est en général crédité sur le solde <strong>Principal</strong>.</li>
<li>Le portefeuille <strong>Test</strong> sert uniquement à l'entraînement. Les fonds restent dans le Test et ne se retirent pas.</li>
</ul>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>7. Erreurs fréquentes à éviter</h2>
<ul>
<li>Essayer de prédire quand la manche est déjà <strong>verrouillée</strong></li>
<li>Choisir la mauvaise <strong>période</strong> (surtout avec le mode Auto)</li>
<li>Utiliser un montant plus élevé que le solde du <strong>portefeuille choisi</strong></li>
<li>En Multi : une seule mauvaise bougie fait échouer toute la séquence</li>
<li>Croire qu'un résultat <strong>neutre</strong> est une perte (c'est un remboursement)</li>
<li>Essayer de placer une position alors que la manche est déjà <strong>verrouillée</strong></li>
<li>Sélectionner la mauvaise <strong>période</strong> (surtout avec Auto)</li>
<li>Utiliser un montant supérieur au solde du <strong>portefeuille choisi</strong></li>
<li>En Multi : une seule bougie incorrecte fait échouer toute la séquence</li>
<li>Considérer un résultat <strong>neutre</strong> comme une perte (c'est un remboursement)</li>
</ul>
<p>Si vous débutez, commencez en mode <strong>Simple</strong> avec un petit montant, ou utilisez le portefeuille <strong>Test</strong> s'il est proposé.</p>
<p>Si vous débutez sur FO (Full Option), commencez en mode <strong>Simple</strong> avec un petit montant, ou utilisez le portefeuille <strong>Test</strong> s'il est proposé.</p>
</div>
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>8. Besoin d'aide ?</h2>
<p>Si une prédiction reste bloquée, si un gain n'apparaît pas, ou si le statut semble incorrect :</p>
<p>Si une position reste en attente, si un règlement n'apparaît pas, ou si un statut semble incorrect :</p>
<ol>
<li>Rafraîchissez l'écran du jeu et regardez l'historique.</li>
<li>Rafraîchissez l'écran Candle Predict et consultez l'historique.</li>
<li>Vérifiez le portefeuille utilisé et le solde (Principal / Bonus / Test).</li>
<li>Contactez le <strong>support</strong> Tloto avec l'heure, la période et le résultat attendu.</li>
</ol>
<p>Pour ajouter des fonds sur le Principal, voir le guide <strong>Dépôts</strong>. Pour sortir des fonds, voir le guide <strong>Retraits</strong>.</p>
<p>Pour alimenter le Principal, voir le guide <strong>Dépôts</strong>. Pour un retrait, voir le guide <strong>Retraits</strong>.</p>
</div>

View File

@ -11,7 +11,7 @@ This guide explains how to **invite friends** to Tloto, share your code or link,
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>1. What is the referral program?</h2>
<p>The referral program lets you <strong>invite people</strong> to sign up on Tloto with your code or your link.</p>
<p>When people in your network play in an eligible way, you can receive <strong>commissions</strong>. These commissions arrive in your <strong>Bonus</strong> wallet.</p>
<p>When people in your network place eligible <strong>Candle Predict</strong> positions, you can receive <strong>commissions</strong>. These commissions arrive in your <strong>Bonus</strong> wallet.</p>
<p>Rates and levels are shown in the app. They can change depending on the program settings.</p>
</div>
@ -58,9 +58,9 @@ This guide explains how to **invite friends** to Tloto, share your code or link,
<p>The program can reward several types of activity. What is active is shown on the <strong>Referrals</strong> screen.</p>
<p>The most common case:</p>
<ul>
<li>Someone in your network plays <strong>Candle Predict</strong></li>
<li>Their prediction ends as <strong>won</strong> or <strong>lost</strong> (not neutral / refund)</li>
<li>They play with the <strong>Main</strong> or <strong>Bonus</strong> wallet (not <strong>Test</strong>)</li>
<li>Someone in your network places a position on <strong>Candle Predict</strong> (FO / USDT)</li>
<li>Their position settles as <strong>won</strong> or <strong>lost</strong> (not neutral / refund)</li>
<li>They use the <strong>Main</strong> or <strong>Bonus</strong> wallet (not <strong>Test</strong>)</li>
<li>A commission may then be credited to your <strong>Bonus</strong> wallet</li>
</ul>
<p>The percentages per level (level 1, level 2, and so on) are the ones <strong>shown in the app</strong>.</p>

View File

@ -11,7 +11,7 @@ Ce guide explique comment **inviter des amis** sur Tloto, partager votre code ou
<div style="page-break-inside: avoid; break-inside: avoid;">
<h2>1. Qu'est-ce que le parrainage ?</h2>
<p>Le programme de parrainage vous permet d'<strong>inviter des personnes</strong> à s'inscrire sur Tloto avec votre code ou votre lien.</p>
<p>Quand les personnes de votre réseau jouent de façon éligible, vous pouvez recevoir des <strong>commissions</strong>. Ces commissions arrivent sur votre portefeuille <strong>Bonus</strong>.</p>
<p>Quand les personnes de votre réseau placent des positions <strong>Candle Predict</strong> éligibles, vous pouvez recevoir des <strong>commissions</strong>. Ces commissions arrivent sur votre portefeuille <strong>Bonus</strong>.</p>
<p>Les taux et les niveaux sont affichés dans l'application. Ils peuvent changer selon la configuration du programme.</p>
</div>
@ -58,9 +58,9 @@ Ce guide explique comment **inviter des amis** sur Tloto, partager votre code ou
<p>Le programme peut récompenser plusieurs types d'activité. Ce qui est actif est indiqué dans l'écran <strong>Parrainage</strong>.</p>
<p>Le cas le plus courant :</p>
<ul>
<li>Une personne de votre réseau joue à <strong>Candle Predict</strong></li>
<li>Sa prédiction se termine en <strong>gagné</strong> ou <strong>perdu</strong> (pas en neutre / remboursement)</li>
<li>La participation vient du portefeuille <strong>Principal</strong> ou <strong>Bonus</strong> (pas du <strong>Test</strong>)</li>
<li>Une personne de votre réseau place une position sur <strong>Candle Predict</strong> (FO / USDT)</li>
<li>Sa position se termine en <strong>gagné</strong> ou <strong>perdu</strong> (pas en neutre / remboursement)</li>
<li>Elle utilise le portefeuille <strong>Principal</strong> ou <strong>Bonus</strong> (pas le <strong>Test</strong>)</li>
<li>Une commission peut alors être créditée sur votre portefeuille <strong>Bonus</strong></li>
</ul>
<p>Les pourcentages par niveau (niveau 1, niveau 2, etc.) sont ceux <strong>affichés dans l'application</strong>.</p>

View File

@ -29,15 +29,18 @@ class CandlePredictInstrument {
/// Decimal places for price labels on the chart.
final int priceDigits;
/// Pair ticker, e.g. FO/USDT.
String get pairSymbol => '$symbol/$quoteCurrency';
/// Short pair ticker, e.g. FO / USDT.
String get shortPairSymbol => '$symbol / $quoteCurrency';
/// Header line, e.g. FO/USDT — Full Option.
String get chartTitle => '$pairSymbol — $displayName';
/// Pair ticker shown as chart title, e.g. FO (Full Option) / USDT.
String get pairSymbol => '$symbol ($displayName) / $quoteCurrency';
/// Price subtitle, e.g. FO/USDT — 105.50.
/// Header / semantics label for the chart instrument.
String get chartTitle => pairSymbol;
/// Price subtitle with trillion unit, e.g. FO / USDT — 105.50T.
String priceLabel(double price) =>
'$pairSymbol — ${price.toStringAsFixed(priceDigits)}';
'$shortPairSymbol — ${price.toStringAsFixed(priceDigits)}T';
factory CandlePredictInstrument.fromJson(Map<String, dynamic>? json) {
if (json == null) return defaultCandlePredictInstrument;

View File

@ -292,15 +292,6 @@ class _CandleChartWidgetState extends State<CandleChartWidget> {
],
),
),
Text(
widget.instrument.displayName,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white.withValues(alpha: 0.72),
shadows: const [
Shadow(blurRadius: 6, color: Colors.black54),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(

View File

@ -1,7 +1,7 @@
name: prediqo_mobile
description: "Tloto mobile app - prediction games and crypto wallet."
publish_to: 'none'
version: 2.0.2+13
version: 2.0.2+14
environment:
sdk: ^3.9.2

View File

@ -290,17 +290,6 @@ export const CandlestickChart = memo(function CandlestickChart({
>
{pairSymbol}
</Typography>
<Typography
variant="caption"
sx={{
opacity: 0.72,
lineHeight: 1.2,
color: 'rgba(255,255,255,0.78)',
textShadow: '0 1px 6px rgba(0,0,0,0.5)',
}}
>
{instrument.displayName}
</Typography>
{lastClose != null && (
<Typography
variant="caption"

View File

@ -71,24 +71,31 @@ export function getActiveInstrument(): SyntheticInstrumentConfig {
return DEFAULT_CANDLE_PREDICT_INSTRUMENT;
}
/** Pair ticker shown on the chart, e.g. FO/USDT */
/** Short pair ticker, e.g. FO / USDT */
export function instrumentShortPairSymbol(
instrument: SyntheticInstrumentConfig = DEFAULT_CANDLE_PREDICT_INSTRUMENT
): string {
return `${instrument.symbol} / ${instrument.quoteCurrency}`;
}
/** Pair ticker shown as chart title, e.g. FO (Full Option) / USDT */
export function instrumentPairSymbol(
instrument: SyntheticInstrumentConfig = DEFAULT_CANDLE_PREDICT_INSTRUMENT
): string {
return `${instrument.symbol}/${instrument.quoteCurrency}`;
return `${instrument.symbol} (${instrument.displayName}) / ${instrument.quoteCurrency}`;
}
/** Header line, e.g. FO/USDT — Full Option */
/** Header / aria label for the chart instrument. */
export function instrumentChartTitle(
instrument: SyntheticInstrumentConfig = DEFAULT_CANDLE_PREDICT_INSTRUMENT
): string {
return `${instrumentPairSymbol(instrument)} — ${instrument.displayName}`;
return instrumentPairSymbol(instrument);
}
/** Price subtitle, e.g. FO/USDT — 105.50 */
/** Price subtitle with trillion unit, e.g. FO / USDT — 105.50T */
export function instrumentPriceLabel(
price: number,
instrument: SyntheticInstrumentConfig = DEFAULT_CANDLE_PREDICT_INSTRUMENT
): string {
return `${instrumentPairSymbol(instrument)} — ${price.toFixed(instrument.priceDigits)}`;
return `${instrumentShortPairSymbol(instrument)} — ${price.toFixed(instrument.priceDigits)}T`;
}

View File

@ -666,7 +666,8 @@ export const en = {
'You can still set up 2FA below. If email fields stay empty, ENCRYPTION_KEY may have changed — set ENCRYPTION_KEY_PREVIOUS to the old key, or update your email after 2FA is enabled.',
securityNotifications: {
title: 'Security activity',
subtitle: 'Recent security events on your account (new sign-ins, password changes, 2FA updates).',
subtitle:
'Recent account activity: sign-ins, password/2FA changes, withdrawals, and transfers.',
markAllRead: 'Mark all read',
markRead: 'Mark read',
loadError: 'Failed to load security notifications.',

View File

@ -677,7 +677,7 @@ export const fr = {
securityNotifications: {
title: 'Activité de sécurité',
subtitle:
'Événements de sécurité récents sur votre compte (nouvelles connexions, changements de mot de passe, 2FA).',
'Activité récente du compte : connexions, mot de passe/2FA, retraits et transferts.',
markAllRead: 'Tout marquer comme lu',
markRead: 'Marquer lu',
loadError: 'Impossible de charger les notifications de sécurité.',