9be58bd5ef
- tickets.js: one shared desk (platform iap now, linkspin later), dual-mode store (MySQL tables tickets + ticket_messages, else support.json); refs IAP-<1000+id> / LS-; private no-login link /support/t/<ref>.<HMAC> signed with DATA_DIR/support.key (or SUPPORT_SECRET); ingestEmail() ready for the support@ intake step (threads by Message-ID, then [ref] in the subject from the same sender) - Member Help pane (/my#help): list with status + unread badge, new ticket (category, subject, message, up to 2 screenshots via /api/my/upload), thread + reply (a reply reopens a closed ticket) - Public /support: name, email, category, subject, message behind the sign-up walls (honeypot, form age, per-IP limits with the icon check, global cap) plus a per-email cap; confirmation email with the ref and the private link - Chatbot: CANNED + systemPrompt know the help desk; answers that cannot help (or "talk to a human") offer "Send this to support", which files the last turns as a ticket (members: Help pane; signed out: email + the same guard) - Admin Support pane: open / waiting / closed / all, platform, category, search; open-count badge; ticket view with requester account info, internal notes, status/priority/category, saved replies (site setting supportTemplates); deep link /admin#support?t=<ref> - Notifications: new ticket / member reply -> Telegram to Marty's private chat only (supportTelegramChat, default 1289244227, site bot then Hermes fallback, never a group or the Discord relay) + email to ADMIN_EMAIL, max one per ticket per 10 min; Marty's reply -> email "[IAP-1042] subject" + a 'notice' inbox message for members, bursts batched - support* settings are kept out of /api/config; Support link in the site footer, home footer, member page foot, terms and privacy; "Contact support" errors point at /support - QA walk: member Help ticket flow, admin Support pane + deep link, internal-note leak check, public /support + private link + tampered token + form-age refusal - Cache tags: common.js 20261016a, chat.js 20261016a, my.js 20261016r, admin.js 20261016sp, support.js 20261016a Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
324 lines
24 KiB
JavaScript
324 lines
24 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 will land on
|
|
// this same desk later (platform 'linkspin'). Only Marty answers for now, from his admin login.
|
|
//
|
|
// 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 /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';
|
|
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 => 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 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) { return this.d().tickets.filter(t => t.email === email && t.memberUnread).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 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) { return Number((await db.q('SELECT COUNT(*) n FROM tickets WHERE email=? AND member_unread=1', [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 head = kind === 'new' ? '\u{1F3AB} <b>' + t.ref + '</b> new ticket' : '\u{1F4AC} <b>' + t.ref + '</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 + ' · ' + t.platform + ' · ' + escH(t.category) + '\n' + escH(who(t)) + '\n' + escH(t.subject) + '\n“' + escH(firstLine(last.body)) + '”\n' + adminLink(t) + extra;
|
|
if (deps.telegram) deps.telegram(text).catch(() => {});
|
|
if (deps.adminEmail && deps.mailer && deps.mailer.hasKey()) {
|
|
const body = items.map(i => i.body).join('\n\n---\n\n');
|
|
deps.mailer.send(deps.adminEmail, '[' + t.ref + '] ' + (kind === 'new' ? 'New ticket: ' : 'Reply: ') + t.subject,
|
|
(kind === 'new' ? 'New support ticket' : 'Member reply') + ' on ' + 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) {
|
|
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">InstantAdPay support. Reply on the page above, or email support@instantadpay.com and keep the ticket number in the subject.</p></div>';
|
|
}
|
|
function confirmRequester(t, m) {
|
|
if (!deps.mailer || !deps.mailer.hasKey()) return;
|
|
const link = linkFor(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\nInstantAdPay 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'), { transactional: true })
|
|
.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);
|
|
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 + '\n\nInstantAdPay 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'), { transactional: true })
|
|
.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
|
|
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 };
|
|
}
|
|
// 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);
|
|
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;
|
|
const now = Date.now();
|
|
const m = { ticketId: t.id, author, body, 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);
|
|
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 });
|
|
async function memberList(email) { return (await impl().list({ email: lc(email), limit: 100 })).map(pubTicket); }
|
|
async function memberUnread(email) { return impl().memberUnread(lc(email)); }
|
|
// 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 });
|
|
return { ticket: Object.assign(t, { adminUnread: false }), messages: await impl().messages(t.id, true), 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 }); }
|
|
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, CATEGORIES, STATUSES, PRIORITIES, PLATFORMS, SOURCES, DEFAULT_TEMPLATES, refOf, parseRef, tokenFor, linkFor,
|
|
create, addMessage, setFields, byRef, byToken, memberList, memberUnread, memberView, adminList, adminView, counts, ingestEmail };
|