Help desk translation: member messages in other languages get an English translation (Telegram, admin email, admin view, bot thread); Marty's replies go back in the member's language with his English underneath (OpenRouter, reasoning off; failures fall back to untranslated)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -365,6 +365,14 @@ async function bootstrap() {
|
||||
via VARCHAR(12) NOT NULL DEFAULT 'web',
|
||||
INDEX (ticket_id), INDEX (email_message_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
// help desk translations (2026-10-16): the English of a member message written in another language
|
||||
await q(`CREATE TABLE IF NOT EXISTS ticket_translations (
|
||||
message_id INT PRIMARY KEY,
|
||||
ticket_id INT NOT NULL,
|
||||
lang VARCHAR(8) NOT NULL,
|
||||
body_en TEXT NOT NULL,
|
||||
INDEX (ticket_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
}
|
||||
|
||||
// one-time import: only when the tables are empty and JSON files exist
|
||||
|
||||
+1
-1
@@ -565,6 +565,6 @@
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/admin.js?v=20261016sp"></script>
|
||||
<script src="/assets/admin.js?v=20261016tr"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -886,6 +886,7 @@
|
||||
+ v.messages.map(m => '<div style="border:1px solid ' + (m.internal ? 'rgba(242,201,76,.55)' : m.author === 'admin' ? 'rgba(67,232,195,.45)' : 'var(--line)') + ';background:' + (m.internal ? 'rgba(242,201,76,.07)' : m.author === 'admin' ? 'rgba(67,232,195,.05)' : 'transparent') + ';border-radius:12px;padding:10px 14px;margin:8px 0">'
|
||||
+ '<div class="small muted" style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap"><b>' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '</b><span>' + esc(ctWhen(m.created)) + '</span></div>'
|
||||
+ '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:6px">' + spLink(m.body) + '</div>'
|
||||
+ (m.bodyEn ? '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:8px;padding:8px 10px;border-left:3px solid var(--accent,#43e8c3);background:rgba(67,232,195,.07);border-radius:6px"><span class="small muted">🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)</span>\n' + spLink(m.bodyEn) + '</div>' : '')
|
||||
+ ((m.attachments || []).length ? '<div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment" style="max-width:180px;max-height:140px;border-radius:8px;border:1px solid var(--line)"></a>').join('') + '</div>' : '') + '</div>').join('')
|
||||
+ '</div>'
|
||||
+ '<div class="card"><div class="card-head"><h3>Reply</h3><span class="sub">emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + '</span></div>'
|
||||
|
||||
@@ -59,6 +59,7 @@ const fridaybank = require('./fridaybank'); // Friday Bonus Hunts: days banked S
|
||||
const refill = require('./refill');
|
||||
const pdsync = require('./pdsync'); // PassiveDrip PTC bridge: our visit campaigns on their paid-to-click page (2026-09-30) // campaign running-low / ran-out notices, and what came of them // Five Dollar Friday: +20% credits on Friday packs, the wave, the badge (Marty, 2026-09-20)
|
||||
const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15)
|
||||
const translate = require('./translate'); // help desk: member messages in other languages, replies back in theirs (2026-10-16)
|
||||
const inbound = require('./inbound'); // help desk email intake: SendGrid Inbound Parse -> tickets (2026-10-16)
|
||||
const supportbot = require('./supportbot'); // @CTBTickets_bot: ticket pings with buttons + answering from Telegram (2026-10-16)
|
||||
const tickets = require('./tickets'); // help desk: member Help pane, public /support, chatbot hand-off, admin Support pane (Marty, 2026-10-16)
|
||||
@@ -533,7 +534,8 @@ async function boot() {
|
||||
// follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot)
|
||||
coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig });
|
||||
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
|
||||
tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram });
|
||||
translate.init({ dataDir: DATA_DIR });
|
||||
tickets.init({ dataDir: DATA_DIR, mailer, messages, accounts, adminEmail: ADMIN_EMAIL, telegram: supportTelegram, translate });
|
||||
inbound.init({ tickets });
|
||||
supportbot.init({ tickets, chatId: () => String(siteConfig().supportTelegramChat || '1289244227').trim(), site: 'https://instantadpay.com' });
|
||||
badge.init({ publicDir: PUBLIC_DIR });
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ async function sendList(which) {
|
||||
async function showThread(ref) {
|
||||
const t = await deps.tickets.byRef(ref); if (!t) return say('No ticket ' + escH(ref) + '.');
|
||||
const v = await deps.tickets.adminView(t.id);
|
||||
const msgs = (v.messages || []).slice(-6).map(m => (m.internal ? '📝 note' : m.author === 'admin' ? '↩️ you' : '👤 ' + escH(t.name || t.email)) + ': ' + escH(String(m.body).slice(0, 500)));
|
||||
const msgs = (v.messages || []).slice(-6).map(m => (m.internal ? '📝 note' : m.author === 'admin' ? '↩️ you' : '👤 ' + escH(t.name || t.email)) + ': ' + escH(String(m.body).slice(0, 500)) + (m.bodyEn ? '\n🌐 in English: ' + escH(String(m.bodyEn).slice(0, 500)) : ''));
|
||||
return say('<b>' + t.ref + '</b> · ' + STATUS_WORD[t.status] + ' · ' + (t.platform === 'linkspin' ? '🔗 <b>LinkSpin</b>' : escH((deps.tickets.PLATFORM_NAME || {})[t.platform] || t.platform)) + ' · ' + escH(t.category) + '\n' + escH(t.email) + '\n<b>' + escH(t.subject) + '</b>\n\n' + msgs.join('\n\n'), { reply_markup: keyboard(t.ref) });
|
||||
}
|
||||
|
||||
|
||||
+32
-4
@@ -96,6 +96,8 @@ const J = {
|
||||
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; },
|
||||
@@ -135,6 +137,8 @@ const D = {
|
||||
[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() {
|
||||
@@ -186,10 +190,10 @@ function pingAdmin(kind, t, m) {
|
||||
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) + '\n“' + escH(firstLine(last.body)) + '”\n' + adminLink(t) + extra;
|
||||
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.body).join('\n\n---\n\n');
|
||||
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));
|
||||
}
|
||||
@@ -245,6 +249,20 @@ function validate(o) {
|
||||
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) {
|
||||
@@ -258,6 +276,7 @@ async function create(o) {
|
||||
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);
|
||||
@@ -272,9 +291,16 @@ async function addMessage(ticketId, o) {
|
||||
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, internal, attachments: atts(o.attachments), created: now, emailMessageId: o.emailMessageId ? String(o.emailMessageId).slice(0, 250) : null, via: o.via || 'web' };
|
||||
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' });
|
||||
@@ -321,7 +347,9 @@ async function adminList(f) {
|
||||
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 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();
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Help desk translation (Marty, 2026-10-16: the first real ticket came in Italian). Member messages are checked for language
|
||||
// and get an English translation for Marty; his English replies go back in the member's language with his English underneath.
|
||||
// Same OpenRouter key and model as the chatbot (DATA_DIR/openrouter.key, reasoning off). Any failure returns null and the
|
||||
// desk carries on untranslated: translation never blocks a ticket or a reply.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const https = require('https');
|
||||
|
||||
let DATA_DIR = null;
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
function init(o) { DATA_DIR = o.dataDir; }
|
||||
const orKey = () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } };
|
||||
|
||||
function ask(system, user, maxTokens) {
|
||||
return new Promise(resolve => {
|
||||
const k = orKey(); if (!k) return resolve(null);
|
||||
const body = JSON.stringify({ model: MODEL, reasoning: { enabled: false }, max_tokens: maxTokens || 1200, temperature: 0,
|
||||
messages: [{ role: 'system', content: system }, { role: 'user', content: user }] });
|
||||
const rq = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST', timeout: 20000,
|
||||
headers: { Authorization: 'Bearer ' + k, 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
|
||||
res => { let d = ''; res.on('data', c => { d += c; }); res.on('end', () => {
|
||||
// OpenRouter can lead with keepalive whitespace; parse from the first brace
|
||||
const i = d.indexOf('{'); if (i < 0) return resolve(null);
|
||||
try { const j = JSON.parse(d.slice(i)); resolve(String(j.choices && j.choices[0] && j.choices[0].message && j.choices[0].message.content || '').trim() || null); } catch (e) { resolve(null); }
|
||||
}); });
|
||||
rq.on('error', () => resolve(null));
|
||||
rq.on('timeout', () => { rq.destroy(); resolve(null); });
|
||||
rq.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
// { lang: 'it', english: '...' } for a non-English text, { lang: 'en' } for English, null when it could not tell
|
||||
async function detect(text) {
|
||||
const t = String(text || '').trim(); if (t.length < 2) return null;
|
||||
const out = await ask('You identify the language of a customer support message and translate it to English. Answer with JSON only: '
|
||||
+ '{"lang":"<ISO 639-1 code>","english":"<the full message in natural English, or an empty string if it is already English>"}. '
|
||||
+ 'Keep names, numbers, wallet addresses, links and ticket references exactly as written.', t.slice(0, 4000), 1500);
|
||||
if (!out) return null;
|
||||
try {
|
||||
const j = JSON.parse(out.slice(out.indexOf('{'), out.lastIndexOf('}') + 1));
|
||||
const lang = String(j.lang || '').toLowerCase().slice(0, 5);
|
||||
if (!/^[a-z]{2}(-[a-z]{2})?$/.test(lang)) return null;
|
||||
if (lang === 'en' || lang.startsWith('en-')) return { lang: 'en' };
|
||||
const english = String(j.english || '').trim();
|
||||
return english ? { lang, english: english.slice(0, 5000) } : null;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
// Marty's English reply in the member's language; null on failure
|
||||
async function to(text, lang) {
|
||||
if (!lang || lang === 'en') return null;
|
||||
const out = await ask('Translate this customer support reply from English into the language with ISO 639-1 code "' + lang + '". '
|
||||
+ 'Keep the tone warm and plain. Keep names, numbers, POL amounts, wallet addresses, links, button names in quotes and ticket references exactly as written. '
|
||||
+ 'Answer with the translation only, no notes.', String(text).slice(0, 4000), 1800);
|
||||
return out ? out.slice(0, 5000) : null;
|
||||
}
|
||||
const NAMES = { it: 'Italian', es: 'Spanish', fr: 'French', de: 'German', pt: 'Portuguese', nl: 'Dutch', pl: 'Polish', tr: 'Turkish', ru: 'Russian', uk: 'Ukrainian',
|
||||
ro: 'Romanian', id: 'Indonesian', tl: 'Filipino', vi: 'Vietnamese', th: 'Thai', ar: 'Arabic', hi: 'Hindi', bn: 'Bengali', ur: 'Urdu', zh: 'Chinese', ja: 'Japanese',
|
||||
ko: 'Korean', sw: 'Swahili', yo: 'Yoruba', ha: 'Hausa', el: 'Greek', cs: 'Czech', hu: 'Hungarian', sv: 'Swedish', no: 'Norwegian', da: 'Danish', fi: 'Finnish', he: 'Hebrew', fa: 'Persian' };
|
||||
const langName = l => NAMES[String(l || '').slice(0, 2)] || String(l || '').toUpperCase();
|
||||
module.exports = { init, detect, to, langName };
|
||||
Reference in New Issue
Block a user