962cdf08b5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
372 lines
29 KiB
JavaScript
372 lines
29 KiB
JavaScript
// Help desk (Marty, 2026-10-16): one shared support desk in the IAP admin portal. A member emailed
|
|
// support@instantadpay.com when it did not exist, so nobody had a way to ask for help. Tickets come in
|
|
// from the member Help pane ('form'), the public /support page ('public'), the chatbot hand-off
|
|
// ('chatbot') and, in a later step, inbound mail to support@ ('email'). LinkSpin tickets land on this
|
|
// same desk through the signed partner API (server.js /api/partner/support/*, LS_SYNC_SECRET), as
|
|
// platform 'linkspin': their links, emails and copy point at LinkSpin (LS_URL), and a LinkSpin ticket
|
|
// never sends an InstantAdPay in-app notice (LinkSpin shows its own unread badge). Only Marty answers,
|
|
// from his admin login or Telegram.
|
|
//
|
|
// Refs: IAP-<1000 + id> (LS-<1000 + id> for LinkSpin), one id sequence for the whole desk, so a ref
|
|
// always names one ticket. The private no-login link is <site>/support/t/<ref>.<32-char HMAC>, signed over
|
|
// the ticket id and requester email (DATA_DIR/support.key, or SUPPORT_SECRET), nothing stored.
|
|
//
|
|
// Email intake (next step) plugs in through ingestEmail({ from, name, subject, text, messageId,
|
|
// inReplyTo, references }): it threads by stored Message-ID first, then by the [IAP-1042] ref in the
|
|
// subject (only when the sender matches the ticket's email), else opens a new ticket (source 'email').
|
|
//
|
|
// Dual-mode store like the other modules (MySQL when DATABASE_URL is set, JSON on the volume).
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const db = require('./db');
|
|
|
|
let DATA_DIR = null, deps = {};
|
|
const SITE = 'https://instantadpay.com';
|
|
// per-platform face of the desk: where the requester's links point and whose name signs the mail
|
|
const BRAND = {
|
|
iap: { site: () => SITE, name: 'InstantAdPay', help: ref => SITE + '/my#help?t=' + ref, footer: 'Reply on the page above, or email support@instantadpay.com and keep the ticket number in the subject.' },
|
|
linkspin: { site: () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''), name: 'LinkSpin', help: ref => BRAND.linkspin.site() + '/help#t=' + ref, footer: 'Reply on the page above, or from Help in your LinkSpin Control Room.' }
|
|
};
|
|
const brandOf = t => BRAND[t && t.platform] || BRAND.iap;
|
|
const PLATFORM_NAME = { iap: 'InstantAdPay', linkspin: 'LinkSpin' };
|
|
const CATEGORIES = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
|
|
const STATUSES = ['open', 'waiting_on_member', 'closed'];
|
|
const PRIORITIES = ['normal', 'high'];
|
|
const PLATFORMS = ['iap', 'linkspin'];
|
|
const SOURCES = ['form', 'public', 'chatbot', 'email'];
|
|
const PREFIX = { iap: 'IAP', linkspin: 'LS' };
|
|
const REF_BASE = 1000;
|
|
const DEFAULT_TEMPLATES = [
|
|
{ name: 'Thanks, looking into it', body: 'Thanks for writing in. I am looking into this now and will reply here as soon as I have an answer.\n\nMarty' },
|
|
{ name: 'Sign-in code help', body: 'Sign-in codes come from no-reply@instantadpay.com and work for 15 minutes. If one does not arrive, check your spam or promotions folder, then request a fresh code at https://instantadpay.com/my. Each code replaces the one before it, so use the newest.\n\nMarty' },
|
|
{ name: 'Payouts are on-chain', body: 'Every payout is paid by the contract in the same transaction as the purchase, straight to the wallet on your account, and you can check each one on the live ledger: https://instantadpay.com/ledger. If a payout passed you by, it is usually because payouts were not switched on yet or a level was not open. Your Earnings tab shows the trace for each purchase.\n\nMarty' },
|
|
{ name: 'Solved, closing', body: 'Glad that is sorted. I will close this ticket now. If anything else comes up, reply here and it opens again.\n\nMarty' }
|
|
];
|
|
|
|
const refOf = (id, platform) => (PREFIX[platform] || 'IAP') + '-' + (REF_BASE + Number(id));
|
|
function parseRef(s) {
|
|
const m = /\b(IAP|LS)-(\d{4,9})\b/i.exec(String(s || ''));
|
|
if (!m) return null;
|
|
const id = Number(m[2]) - REF_BASE;
|
|
return id > 0 ? { ref: m[1].toUpperCase() + '-' + m[2], id } : null;
|
|
}
|
|
const clean = (s, n) => String(s == null ? '' : s).replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').trim().slice(0, n);
|
|
const oneLine = (s, n) => clean(s, 2000).replace(/\s+/g, ' ').slice(0, n);
|
|
const ATT_RE = /^\/uploads\/[a-z0-9]{24}\.(?:png|jpg|webp|gif)$/;
|
|
const atts = a => (Array.isArray(a) ? a : []).map(String).filter(x => ATT_RE.test(x)).slice(0, 2);
|
|
const lc = e => String(e || '').trim().toLowerCase();
|
|
|
|
// ---- signed private link ----
|
|
let SECRET = '';
|
|
function secret() {
|
|
if (process.env.SUPPORT_SECRET && process.env.SUPPORT_SECRET.length >= 32) return process.env.SUPPORT_SECRET;
|
|
if (SECRET) return SECRET;
|
|
const f = path.join(DATA_DIR, 'support.key');
|
|
try { SECRET = fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
|
|
if (SECRET.length < 32) {
|
|
const s = crypto.randomBytes(32).toString('hex');
|
|
try { fs.writeFileSync(f, s, { flag: 'wx', mode: 0o600 }); SECRET = s; } // wx: the other copy during a deploy overlap may have written it first
|
|
catch (e) { try { SECRET = fs.readFileSync(f, 'utf8').trim(); } catch (e2) { SECRET = s; } }
|
|
}
|
|
return SECRET;
|
|
}
|
|
const sig = t => crypto.createHmac('sha256', secret()).update('support:' + t.id + ':' + lc(t.email)).digest('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, 32);
|
|
const tokenFor = t => t.ref + '.' + sig(t);
|
|
const linkFor = t => brandOf(t).site() + '/support/t/' + tokenFor(t);
|
|
const TOKEN_RE = /^((?:IAP|LS)-\d{4,9})\.([A-Za-z0-9_-]{32})$/;
|
|
|
|
// ---- stores ----
|
|
const J = {
|
|
db: null,
|
|
FILE: () => path.join(DATA_DIR, 'support.json'),
|
|
load() { try { this.db = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.db = { nextId: 1, nextMsg: 1, tickets: [], messages: [] }; } },
|
|
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
|
|
d() { if (!this.db) this.load(); return this.db; },
|
|
async insertTicket(t) { const d = this.d(); const id = d.nextId++; d.tickets.push(Object.assign({}, t, { id, ref: refOf(id, t.platform) })); this.save(); return id; },
|
|
async updateTicket(id, f) { const t = this.d().tickets.find(x => x.id === Number(id)); if (t) { Object.assign(t, f); this.save(); } },
|
|
async getTicket(id) { const t = this.d().tickets.find(x => x.id === Number(id)); return t ? Object.assign({}, t) : null; },
|
|
async list(f) {
|
|
let rows = this.d().tickets.slice();
|
|
if (f.email) rows = rows.filter(t => t.email === f.email);
|
|
if (f.status) rows = rows.filter(t => t.status === f.status);
|
|
if (f.platform) rows = rows.filter(t => t.platform === f.platform);
|
|
if (f.category) rows = rows.filter(t => t.category === f.category);
|
|
if (f.q) { const q = f.q.toLowerCase(); rows = rows.filter(t => [t.ref, t.email, t.name, t.username, t.subject].some(v => String(v || '').toLowerCase().includes(q))); }
|
|
return rows.sort((a, b) => b.updated - a.updated).slice(0, f.limit || 200).map(t => Object.assign({}, t));
|
|
},
|
|
async insertMessage(m) { const d = this.d(); const id = d.nextMsg++; d.messages.push(Object.assign({}, m, { id })); this.save(); return id; },
|
|
async saveTr(msgId, ticketId, lang, en) { const d = this.d(); d.tr = d.tr || {}; d.tr[msgId] = { ticketId: Number(ticketId), lang, en }; this.save(); },
|
|
async trFor(ticketId) { const d = this.d(), out = {}; for (const [k, v] of Object.entries(d.tr || {})) if (v.ticketId === Number(ticketId)) out[k] = { lang: v.lang, en: v.en }; return out; },
|
|
async messages(ticketId, internal) { return this.d().messages.filter(m => m.ticketId === Number(ticketId) && (internal || !m.internal)).sort((a, b) => a.id - b.id).map(m => Object.assign({}, m)); },
|
|
async byMessageId(mids) { const s = new Set(mids); const m = this.d().messages.find(x => x.emailMessageId && s.has(x.emailMessageId)); return m ? m.ticketId : 0; },
|
|
async counts() { const out = { open: 0, waiting_on_member: 0, closed: 0, unread: 0 }; for (const t of this.d().tickets) { out[t.status] = (out[t.status] || 0) + 1; if (t.adminUnread) out.unread++; } return out; },
|
|
async memberUnread(email, platform) { return this.d().tickets.filter(t => t.email === email && t.memberUnread && (!platform || t.platform === platform)).length; }
|
|
};
|
|
const tRow = r => r ? ({ id: r.id, ref: r.ref, platform: r.platform, source: r.source, email: r.email, name: r.name || '', username: r.username || '',
|
|
subject: r.subject, category: r.category, status: r.status, priority: r.priority, created: Number(r.created), updated: Number(r.updated),
|
|
lastMemberAt: Number(r.last_member_at || 0), lastAdminAt: Number(r.last_admin_at || 0), adminUnread: !!r.admin_unread, memberUnread: !!r.member_unread }) : null;
|
|
const mRow = r => ({ id: r.id, ticketId: r.ticket_id, author: r.author, body: r.body || '', internal: !!r.internal, attachments: (() => { try { return JSON.parse(r.attachments || '[]'); } catch (e) { return []; } })(),
|
|
created: Number(r.created), emailMessageId: r.email_message_id || null, via: r.via || 'web' });
|
|
const COLS = { platform: 'platform', source: 'source', email: 'email', name: 'name', username: 'username', subject: 'subject', category: 'category', status: 'status', priority: 'priority',
|
|
created: 'created', updated: 'updated', lastMemberAt: 'last_member_at', lastAdminAt: 'last_admin_at', adminUnread: 'admin_unread', memberUnread: 'member_unread' };
|
|
const D = {
|
|
async insertTicket(t) {
|
|
const r = await db.q('INSERT INTO tickets (ref,platform,source,email,name,username,subject,category,status,priority,created,updated,last_member_at,last_admin_at,admin_unread,member_unread) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
|
['pending-' + crypto.randomBytes(5).toString('hex'), t.platform, t.source, t.email, t.name || null, t.username || null, t.subject, t.category, t.status, t.priority, t.created, t.updated, t.lastMemberAt || null, t.lastAdminAt || null, t.adminUnread ? 1 : 0, t.memberUnread ? 1 : 0]);
|
|
await db.q('UPDATE tickets SET ref=? WHERE id=?', [refOf(r.insertId, t.platform), r.insertId]);
|
|
return r.insertId;
|
|
},
|
|
async updateTicket(id, f) {
|
|
const sets = [], vals = [];
|
|
for (const [k, v] of Object.entries(f)) if (COLS[k]) { sets.push(COLS[k] + '=?'); vals.push(typeof v === 'boolean' ? (v ? 1 : 0) : v); }
|
|
if (sets.length) await db.q('UPDATE tickets SET ' + sets.join(',') + ' WHERE id=?', vals.concat([Number(id)]));
|
|
},
|
|
async getTicket(id) { return tRow((await db.q('SELECT * FROM tickets WHERE id=?', [Number(id)]))[0]); },
|
|
async list(f) {
|
|
const w = [], v = [];
|
|
if (f.email) { w.push('email=?'); v.push(f.email); }
|
|
if (f.status) { w.push('status=?'); v.push(f.status); }
|
|
if (f.platform) { w.push('platform=?'); v.push(f.platform); }
|
|
if (f.category) { w.push('category=?'); v.push(f.category); }
|
|
if (f.q) { w.push('(ref LIKE ? OR email LIKE ? OR name LIKE ? OR username LIKE ? OR subject LIKE ?)'); const l = '%' + f.q + '%'; v.push(l, l, l, l, l); }
|
|
return (await db.q('SELECT * FROM tickets' + (w.length ? ' WHERE ' + w.join(' AND ') : '') + ' ORDER BY updated DESC LIMIT ?', v.concat([f.limit || 200]))).map(tRow);
|
|
},
|
|
async insertMessage(m) {
|
|
const r = await db.q('INSERT INTO ticket_messages (ticket_id,author,body,internal,attachments,created,email_message_id,via) VALUES (?,?,?,?,?,?,?,?)',
|
|
[m.ticketId, m.author, m.body, m.internal ? 1 : 0, m.attachments && m.attachments.length ? JSON.stringify(m.attachments) : null, m.created, m.emailMessageId || null, m.via || 'web']);
|
|
return r.insertId;
|
|
},
|
|
async saveTr(msgId, ticketId, lang, en) { await db.q('INSERT INTO ticket_translations (message_id,ticket_id,lang,body_en) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE lang=VALUES(lang), body_en=VALUES(body_en)', [msgId, ticketId, lang, en]); },
|
|
async trFor(ticketId) { const out = {}; for (const r of await db.q('SELECT message_id, lang, body_en FROM ticket_translations WHERE ticket_id=?', [Number(ticketId)])) out[r.message_id] = { lang: r.lang, en: r.body_en }; return out; },
|
|
async messages(ticketId, internal) { return (await db.q('SELECT * FROM ticket_messages WHERE ticket_id=?' + (internal ? '' : ' AND internal=0') + ' ORDER BY id ASC', [Number(ticketId)])).map(mRow); },
|
|
async byMessageId(mids) { if (!mids.length) return 0; const r = await db.q('SELECT ticket_id FROM ticket_messages WHERE email_message_id IN (?) LIMIT 1', [mids]); return r.length ? r[0].ticket_id : 0; },
|
|
async counts() {
|
|
const out = { open: 0, waiting_on_member: 0, closed: 0, unread: 0 };
|
|
for (const r of await db.q('SELECT status, COUNT(*) n, SUM(admin_unread) u FROM tickets GROUP BY status')) { out[r.status] = Number(r.n); out.unread += Number(r.u || 0); }
|
|
return out;
|
|
},
|
|
async memberUnread(email, platform) { return Number((await db.q('SELECT COUNT(*) n FROM tickets WHERE email=? AND member_unread=1' + (platform ? ' AND platform=?' : ''), platform ? [email, platform] : [email]))[0].n); }
|
|
};
|
|
const impl = () => db.enabled() ? D : J;
|
|
|
|
// deps: { mailer, messages, accounts, telegram(text) -> Promise, adminEmail }
|
|
function init(opts) { DATA_DIR = opts.dataDir; deps = opts; }
|
|
|
|
// ---- notifications, throttled: the first event in a window goes out at once, the rest of the
|
|
// window's events are batched into one send at its end, so a burst of replies is one ping ----
|
|
const windows = new Map();
|
|
function throttled(key, ms, item, flush) {
|
|
const now = Date.now(); let w = windows.get(key);
|
|
if (!w || (now >= w.until && !w.timer)) {
|
|
windows.set(key, { until: now + ms, pending: [], timer: null });
|
|
if (windows.size > 2000) for (const [k, v] of windows) if (v.until < now && !v.timer) windows.delete(k);
|
|
return void Promise.resolve().then(() => flush([item])).catch(e => console.error('support notify', e.message));
|
|
}
|
|
w.pending.push(item);
|
|
if (!w.timer) {
|
|
w.timer = setTimeout(() => {
|
|
const items = w.pending.splice(0); w.timer = null; w.until = Date.now() + ms;
|
|
if (items.length) Promise.resolve().then(() => flush(items)).catch(e => console.error('support notify', e.message));
|
|
}, Math.max(0, w.until - now));
|
|
if (w.timer.unref) w.timer.unref();
|
|
}
|
|
}
|
|
const newPings = { hour: 0, n: 0, skipped: 0 }; // new-ticket pings: at most 20 an hour, the rest summed into the next one
|
|
const escH = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
const who = t => (t.name ? t.name + ' ' : '') + '<' + t.email + '>' + (t.username ? ' @' + t.username : '');
|
|
const adminLink = t => SITE + '/admin#support?t=' + t.ref;
|
|
const firstLine = s => oneLine(String(s || '').split('\n').find(l => l.trim()) || '', 140);
|
|
|
|
function pingAdmin(kind, t, m) {
|
|
const send = items => {
|
|
const last = items[items.length - 1];
|
|
const ls = t.platform === 'linkspin'; // LinkSpin tickets say so up front, so Marty knows which site the person is on
|
|
const head = (kind === 'new' ? '\u{1F3AB} <b>' + t.ref + '</b> new ' + (ls ? '\u{1F517} <b>LinkSpin</b> ' : '') + 'ticket' : '\u{1F4AC} <b>' + t.ref + '</b> ' + (ls ? '\u{1F517} <b>LinkSpin</b> ' : '') + (items.length > 1 ? items.length + ' member replies' : 'member reply'));
|
|
let extra = '';
|
|
if (kind === 'new') {
|
|
const h = Math.floor(Date.now() / 3600000);
|
|
if (newPings.hour !== h) { newPings.hour = h; newPings.n = 0; }
|
|
if (++newPings.n > 20) { newPings.skipped++; return; }
|
|
if (newPings.skipped) { extra = '\n(+' + newPings.skipped + ' more new tickets earlier were not pinged)'; newPings.skipped = 0; }
|
|
}
|
|
const text = head + ' · ' + (ls ? '' : (PLATFORM_NAME[t.platform] || t.platform) + ' · ') + escH(t.category) + '\n' + escH(who(t)) + '\n' + escH(t.subject) + (last.bodyEn ? '\n🌐 ' + escH(deps.translate.langName(last.lang)) + ', in English:' : '') + '\n“' + escH(firstLine(last.bodyEn || last.body)) + '”\n' + adminLink(t) + extra;
|
|
if (deps.telegram) deps.telegram(text, t.ref).catch(() => {});
|
|
if (deps.adminEmail && deps.mailer && deps.mailer.hasKey()) {
|
|
const body = items.map(i => i.bodyEn ? i.body + '\n\n[' + deps.translate.langName(i.lang) + ', in English]\n' + i.bodyEn : i.body).join('\n\n---\n\n');
|
|
deps.mailer.send(deps.adminEmail, '[' + t.ref + '] ' + (kind === 'new' ? 'New ' + (t.platform === 'linkspin' ? 'LinkSpin ' : '') + 'ticket: ' : 'Reply: ') + t.subject,
|
|
(kind === 'new' ? 'New support ticket' : 'Member reply') + ' on ' + (PLATFORM_NAME[t.platform] || t.platform) + ' (' + t.category + ')\nFrom: ' + who(t) + '\nSource: ' + t.source + '\n\n' + body + '\n\nAnswer it in the desk: ' + adminLink(t), null, { transactional: true }).catch(e => console.error('support admin mail', e.message));
|
|
}
|
|
};
|
|
if (kind === 'new') return send([m]);
|
|
throttled('admin:' + t.id, 10 * 60 * 1000, m, send);
|
|
}
|
|
function htmlMail(intro, blocks, link, linkLabel, brand) {
|
|
const b = brand || BRAND.iap;
|
|
return '<div style="font-family:Arial,sans-serif;font-size:15px;line-height:1.5;color:#1d2420;max-width:560px">'
|
|
+ '<p>' + escH(intro) + '</p>' + blocks.map(b => '<div style="border-left:3px solid #43e8c3;padding:6px 12px;margin:12px 0;white-space:pre-wrap">' + escH(b) + '</div>').join('')
|
|
+ '<p><a href="' + link + '" style="display:inline-block;background:#043b2f;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none">' + escH(linkLabel) + '</a></p>'
|
|
+ '<p style="font-size:12px;color:#777">' + escH(b.name) + ' support. ' + escH(b.footer) + '</p></div>';
|
|
}
|
|
// email intake (2026-10-16): the requester's replies come back through SendGrid Inbound Parse. The reply-to carries the ticket
|
|
// ref (reply+iap-1042@help.instantadpay.com, reply+ls-1003@linkspin.app); Auto-Submitted keeps other robots from answering.
|
|
const replyTo = t => 'reply+' + String(t.ref).toLowerCase() + (t.platform === 'linkspin' ? '@linkspin.app' : '@help.instantadpay.com');
|
|
const mailOpts = t => ({ transactional: true, replyTo: replyTo(t), headers: { 'Auto-Submitted': 'auto-replied' } });
|
|
function confirmRequester(t, m) {
|
|
if (!deps.mailer || !deps.mailer.hasKey()) return;
|
|
const link = linkFor(t), b = brandOf(t);
|
|
const text = 'Hi' + (t.name ? ' ' + t.name : '') + ',\n\nWe got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.\n\n'
|
|
+ 'Subject: ' + t.subject + '\n\n' + m.body + '\n\nView the ticket or add more detail here (no sign-in needed):\n' + link + '\n\n' + b.name + ' support';
|
|
deps.mailer.send(t.email, '[' + t.ref + '] ' + t.subject, text, htmlMail('We got your message and opened ticket ' + t.ref + '. Marty reads every one and will reply as soon as he can.', [m.body], link, 'View your ticket', b), mailOpts(t))
|
|
.catch(e => console.error('support confirm mail', e.message));
|
|
}
|
|
function notifyRequester(t, m) {
|
|
throttled('member:' + t.id, 2 * 60 * 1000, m, async items => {
|
|
const cur = (await impl().getTicket(t.id)) || t;
|
|
const link = linkFor(cur), b = brandOf(cur);
|
|
const bodies = items.map(i => i.body);
|
|
if (deps.mailer && deps.mailer.hasKey()) {
|
|
const text = 'Hi' + (cur.name ? ' ' + cur.name : '') + ',\n\nMarty replied to your support ticket ' + cur.ref + ':\n\n' + bodies.join('\n\n---\n\n')
|
|
+ '\n\nRead the whole thread and reply here:\n' + link + (cur.platform === 'linkspin' ? '\n\nOr open Help in your LinkSpin Control Room: ' + b.help(cur.ref) : '') + '\n\n' + b.name + ' support';
|
|
deps.mailer.send(cur.email, '[' + cur.ref + '] ' + cur.subject, text, htmlMail('Marty replied to your support ticket ' + cur.ref + ':', bodies, link, 'Read and reply', b), mailOpts(cur))
|
|
.catch(e => console.error('support reply mail', e.message));
|
|
}
|
|
// members also get it in their on-site inbox, as a notice: it never pops the sign-in modal. InstantAdPay tickets only:
|
|
// a LinkSpin ticket is followed on LinkSpin (its Help badge), and its requester may have no real account here at all
|
|
if (cur.platform !== 'iap') return;
|
|
try {
|
|
const acct = deps.accounts && await deps.accounts.byEmail(cur.email);
|
|
if (acct && deps.messages) await deps.messages.deliver(1, deps.adminEmail || 'house@instantadpay.com', [cur.email], 'Support replied: [' + cur.ref + '] ' + cur.subject.slice(0, 110),
|
|
'<p>Marty replied to your support ticket <b>' + escH(cur.ref) + '</b>.</p><p style="white-space:pre-wrap">' + escH(bodies[bodies.length - 1].slice(0, 600)) + '</p><p><a href="/my#help?t=' + escH(cur.ref) + '">Open it in Help</a></p>', 'notice');
|
|
} catch (e) { console.error('support notice', e.message); }
|
|
});
|
|
}
|
|
|
|
// ---- the desk ----
|
|
function validate(o) {
|
|
const subject = oneLine(o.subject, 140), body = clean(o.body, 5000);
|
|
if (subject.length < 3) return { error: 'Add a short subject.' };
|
|
if (body.length < 5) return { error: 'Tell us a little more in the message.' };
|
|
return { subject, body };
|
|
}
|
|
// translation (2026-10-16): a member message in another language gets its English stored beside it (m.lang, m.bodyEn), and
|
|
// the ticket's language is the language of the member's latest message (null = English or unknown)
|
|
async function annotate(m) {
|
|
if (!deps.translate) return m;
|
|
try {
|
|
const r = await deps.translate.detect(m.body);
|
|
if (r && r.lang && r.lang !== 'en' && r.english) { m.lang = r.lang; m.bodyEn = r.english; await impl().saveTr(m.id, m.ticketId, r.lang, r.english); }
|
|
} catch (e) { console.error('support translate in', e.message); }
|
|
return m;
|
|
}
|
|
async function memberLang(ticketId) {
|
|
const msgs = (await impl().messages(ticketId, false)).filter(x => x.author === 'member'); const last = msgs[msgs.length - 1]; if (!last) return null;
|
|
const tr = await impl().trFor(ticketId); return tr[last.id] ? tr[last.id].lang : null;
|
|
}
|
|
// create a ticket and its first message. o: { platform, source, email, name, username, subject, category, body,
|
|
// attachments, priority, emailMessageId, via, confirm (default true except source 'email'), notify (default true) }
|
|
async function create(o) {
|
|
const email = lc(o.email);
|
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email) || email.length > 190) return { error: 'That email address does not look right.' };
|
|
const v = validate(o); if (v.error) return v;
|
|
const now = Date.now();
|
|
const t = { platform: PLATFORMS.includes(o.platform) ? o.platform : 'iap', source: SOURCES.includes(o.source) ? o.source : 'form', email,
|
|
name: oneLine(o.name, 80), username: oneLine(o.username, 30), subject: v.subject, category: CATEGORIES.includes(o.category) ? o.category : 'Other',
|
|
status: 'open', priority: PRIORITIES.includes(o.priority) ? o.priority : 'normal', created: now, updated: now, lastMemberAt: now, lastAdminAt: 0, adminUnread: true, memberUnread: false };
|
|
const id = await impl().insertTicket(t);
|
|
const m = { ticketId: id, author: 'member', body: v.body, internal: false, attachments: atts(o.attachments), created: now, emailMessageId: o.emailMessageId ? String(o.emailMessageId).slice(0, 250) : null, via: o.via || (t.source === 'email' ? 'email' : 'web') };
|
|
m.id = await impl().insertMessage(m);
|
|
await annotate(m);
|
|
const ticket = await impl().getTicket(id);
|
|
if (o.notify !== false) pingAdmin('new', ticket, m);
|
|
if (o.confirm !== undefined ? o.confirm : t.source !== 'email') confirmRequester(ticket, m);
|
|
return { ok: true, ticket, message: m, token: tokenFor(ticket), link: linkFor(ticket) };
|
|
}
|
|
// add a message. o: { author 'member'|'admin'|'system', body, internal, attachments, status (admin: status after sending),
|
|
// emailMessageId, via }. A member reply reopens a closed or waiting ticket; an admin reply defaults to waiting_on_member.
|
|
async function addMessage(ticketId, o) {
|
|
const t = await impl().getTicket(ticketId);
|
|
if (!t) return { error: 'Ticket not found.' };
|
|
const author = ['member', 'admin', 'system'].includes(o.author) ? o.author : 'member';
|
|
const body = clean(o.body, 5000);
|
|
if (body.length < 1) return { error: 'Write a message first.' };
|
|
const internal = author === 'admin' && !!o.internal;
|
|
// Marty writes English; a member who wrote in another language gets the reply in it, with his English underneath
|
|
let sendBody = body;
|
|
if (author === 'admin' && !internal && deps.translate && o.translate !== false) {
|
|
const lang = await memberLang(t.id).catch(() => null);
|
|
if (lang) { const tr = await deps.translate.to(body, lang).catch(() => null); if (tr) sendBody = clean(tr + '\n\n---\n(English) ' + body, 5000); }
|
|
}
|
|
const now = Date.now();
|
|
const m = { ticketId: t.id, author, body: sendBody, internal, attachments: atts(o.attachments), created: now, emailMessageId: o.emailMessageId ? String(o.emailMessageId).slice(0, 250) : null, via: o.via || 'web' };
|
|
m.id = await impl().insertMessage(m);
|
|
if (author === 'member') await annotate(m);
|
|
const f = { updated: now };
|
|
if (author === 'member') Object.assign(f, { lastMemberAt: now, adminUnread: true, status: 'open' });
|
|
if (author === 'admin' && !internal) Object.assign(f, { lastAdminAt: now, memberUnread: true, status: STATUSES.includes(o.status) ? o.status : 'waiting_on_member' });
|
|
if (author === 'admin' && internal && STATUSES.includes(o.status)) f.status = o.status;
|
|
await impl().updateTicket(t.id, f);
|
|
const cur = await impl().getTicket(t.id);
|
|
if (author === 'member' && o.notify !== false) pingAdmin('reply', cur, m);
|
|
if (author === 'admin' && !internal && o.notify !== false) notifyRequester(cur, m);
|
|
return { ok: true, ticket: cur, message: m };
|
|
}
|
|
async function setFields(ticketId, f) {
|
|
const t = await impl().getTicket(ticketId); if (!t) return { error: 'Ticket not found.' };
|
|
const up = {};
|
|
if (STATUSES.includes(f.status)) up.status = f.status;
|
|
if (PRIORITIES.includes(f.priority)) up.priority = f.priority;
|
|
if (CATEGORIES.includes(f.category)) up.category = f.category;
|
|
if (PLATFORMS.includes(f.platform)) up.platform = f.platform;
|
|
if (!Object.keys(up).length) return { error: 'Nothing to change.' };
|
|
up.updated = Date.now();
|
|
await impl().updateTicket(t.id, up);
|
|
return { ok: true, ticket: await impl().getTicket(t.id) };
|
|
}
|
|
const byRef = async ref => { const r = parseRef(ref); if (!r) return null; const t = await impl().getTicket(r.id); return t && t.ref === r.ref ? t : null; };
|
|
async function byToken(tok) {
|
|
const m = TOKEN_RE.exec(String(tok || '')); if (!m) return null;
|
|
const t = await byRef(m[1]); if (!t) return null;
|
|
const want = sig(t);
|
|
return want.length === m[2].length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(m[2])) ? t : null;
|
|
}
|
|
const pubMsg = m => ({ id: m.id, author: m.author, body: m.body, attachments: m.attachments, created: m.created });
|
|
const pubTicket = t => ({ ref: t.ref, platform: t.platform, subject: t.subject, category: t.category, status: t.status, created: t.created, updated: t.updated, unread: t.memberUnread });
|
|
// platform: only that site's tickets (each site's Help pane shows its own); omitted = all of them
|
|
async function memberList(email, platform) { return (await impl().list({ email: lc(email), platform: PLATFORMS.includes(platform) ? platform : '', limit: 100 })).map(pubTicket); }
|
|
async function memberUnread(email, platform) { return impl().memberUnread(lc(email), PLATFORMS.includes(platform) ? platform : ''); }
|
|
// the requester's view of one ticket (no internal notes); opening it clears their unread flag
|
|
async function memberView(t) {
|
|
if (t.memberUnread) await impl().updateTicket(t.id, { memberUnread: false });
|
|
return { ticket: Object.assign(pubTicket(t), { unread: false, name: t.name }), messages: (await impl().messages(t.id, false)).map(pubMsg) };
|
|
}
|
|
async function adminList(f) {
|
|
const q = { status: STATUSES.includes(f.status) ? f.status : '', platform: PLATFORMS.includes(f.platform) ? f.platform : '', category: CATEGORIES.includes(f.category) ? f.category : '', q: oneLine(f.q, 80), limit: 300 };
|
|
return { tickets: await impl().list(q), counts: await impl().counts() };
|
|
}
|
|
async function adminView(id) {
|
|
const t = await impl().getTicket(id); if (!t) return null;
|
|
if (t.adminUnread) await impl().updateTicket(t.id, { adminUnread: false });
|
|
const tr = await impl().trFor(t.id);
|
|
const messages = (await impl().messages(t.id, true)).map(m => tr[m.id] ? Object.assign(m, { lang: tr[m.id].lang, langName: deps.translate ? deps.translate.langName(tr[m.id].lang) : tr[m.id].lang, bodyEn: tr[m.id].en }) : m);
|
|
return { ticket: Object.assign(t, { adminUnread: false }), messages, link: linkFor(t) };
|
|
}
|
|
const counts = () => impl().counts();
|
|
|
|
// inbound mail (next step): thread a reply or open a ticket. Returns { ok, ticket, message, created }.
|
|
async function ingestEmail(e) {
|
|
const from = lc(e.from);
|
|
const mid = e.messageId ? String(e.messageId).trim().slice(0, 250) : null;
|
|
const refs = [e.inReplyTo].concat(String(e.references || '').split(/\s+/)).map(x => String(x || '').trim()).filter(Boolean);
|
|
let ticketId = refs.length ? await impl().byMessageId(refs) : 0;
|
|
if (!ticketId) { const r = parseRef(e.subject); if (r) { const t = await byRef(r.ref); if (t && t.email === from) ticketId = t.id; } }
|
|
const body = clean(e.text, 5000);
|
|
if (ticketId) { const r = await addMessage(ticketId, { author: 'member', body, emailMessageId: mid, via: 'email' }); return Object.assign(r, { created: false }); }
|
|
if (e.canOpen && !(await e.canOpen(from))) return { error: 'not a member (new tickets need a platform account)', created: false }; // replies above still land
|
|
const r = await create({ platform: e.platform || 'iap', source: 'email', email: from, name: e.name, subject: oneLine(e.subject, 140) || '(no subject)', category: 'Other', body, emailMessageId: mid, via: 'email', confirm: !!e.confirm });
|
|
return Object.assign(r, { created: true });
|
|
}
|
|
|
|
module.exports = { init, PLATFORM_NAME, CATEGORIES, STATUSES, PRIORITIES, PLATFORMS, SOURCES, DEFAULT_TEMPLATES, refOf, parseRef, tokenFor, linkFor,
|
|
create, addMessage, setFields, byRef, byToken, memberList, memberUnread, memberView, adminList, adminView, counts, ingestEmail };
|