Update public-api.js via upload script - 2026-11-07 15:18:32
This commit is contained in:
parent
feca316c31
commit
e9d3d48a76
156
public-api.js
156
public-api.js
|
|
@ -17,6 +17,7 @@
|
|||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const dns = require('dns');
|
||||
|
||||
const PRODUCTS_KEY = 'crm:products';
|
||||
|
||||
|
|
@ -883,6 +884,7 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
origins: ['https://ups-china.com', 'https://www.ups-china.com'],
|
||||
dailyCap: 3000, // 每天 AI 调用上限(防刷,超过后只转人工)
|
||||
minReplyMs: 5000, // AI 回复最少等多久(从客户发消息算起)
|
||||
waNumber: '8615201273157', // 重要客户"转到 WhatsApp"按钮用的号码(国家码+号码,不要 +)
|
||||
};
|
||||
const SEED_KB = [
|
||||
{ q: 'Who is SKE / is it a factory?', a: 'SKE Power is a UPS and energy-storage factory in Dongguan, Guangdong (SKE Industrial Park, No. 185 Keji Road, Dongkeng Town), with a sales and service office in Beijing. ISO 9001, ISO 14001 and ISO 45001 certified. Products are exported to 120+ countries through 100+ agents.' },
|
||||
|
|
@ -1000,6 +1002,86 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
return items.map((x) => ({ x, s: words(f(x)).reduce((n, t) => n + (w.has(t) ? 1 : 0), 0) })).sort((a, b) => b.s - a.s).slice(0, k).map((y) => y.x);
|
||||
}
|
||||
|
||||
/* ---------------- 联系方式检查(第一层:格式 + 拼写 + 域名能否收信) ---------------- */
|
||||
// 电话号码由网站用 Google 号码库检查后随消息带过来(checks);邮箱在这里检查
|
||||
const MAIL_DOMAINS = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'live.com', 'icloud.com', 'aol.com', 'mail.ru', 'yandex.ru', 'yandex.com', 'gmx.com', 'gmx.de', 'protonmail.com', 'proton.me', 'qq.com', '163.com', '126.com', 'yahoo.fr', 'hotmail.fr', 'yahoo.co.uk', 'rambler.ru', 'bk.ru', 'inbox.ru', 'list.ru', 'zoho.com'];
|
||||
const DISPOSABLE = ['mailinator.com', 'guerrillamail.com', '10minutemail.com', 'tempmail.com', 'temp-mail.org', 'yopmail.com', 'trashmail.com', 'sharklasers.com', 'getnada.com', 'dispostable.com', 'maildrop.cc', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'emailondeck.com', 'mohmal.com', 'tempail.com', 'moakt.com'];
|
||||
const TLD_FIX = { con: 'com', cmo: 'com', comm: 'com', cpm: 'com', vom: 'com', xom: 'com', ocm: 'com', ner: 'net', nte: 'net', ogr: 'org', rul: 'ru' };
|
||||
function lev(a, b) {
|
||||
const m = a.length, n = b.length, d = Array.from({ length: m + 1 }, (_, i) => [i]);
|
||||
for (let j = 1; j <= n; j++) d[0][j] = j;
|
||||
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
||||
return d[m][n];
|
||||
}
|
||||
const withTimeout = (p, ms) => Promise.race([p, new Promise((_, r) => setTimeout(() => r(new Error('timeout')), ms))]);
|
||||
// 服务器自己的 DNS 能不能用(查 gmail.com 试一下,10 分钟查一次);不能用就不判断"域名不存在",免得误报
|
||||
let dnsOk = { at: 0, ok: false };
|
||||
async function dnsWorks() {
|
||||
if (Date.now() - dnsOk.at < 600e3) return dnsOk.ok;
|
||||
let ok = false; try { const r = await withTimeout(dns.promises.resolveMx('gmail.com'), 3000); ok = !!(r && r.length); } catch (e) { ok = false; }
|
||||
dnsOk = { at: Date.now(), ok }; return ok;
|
||||
}
|
||||
async function checkEmail(addr) {
|
||||
const email = addr.toLowerCase();
|
||||
if (!/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(email)) return { status: 'bad', note: 'invalid format' };
|
||||
let [user, domain] = email.split('@');
|
||||
const tld = domain.split('.').pop();
|
||||
let suggest = '';
|
||||
if (TLD_FIX[tld]) suggest = `${user}@${domain.replace(/\.[^.]+$/, '.' + TLD_FIX[tld])}`;
|
||||
if (!MAIL_DOMAINS.includes(domain)) {
|
||||
const near = MAIL_DOMAINS.map((d) => [d, lev(domain, d)]).filter(([, k]) => k > 0 && k <= 2).sort((a, b) => a[1] - b[1])[0];
|
||||
if (near) suggest = `${user}@${near[0]}`;
|
||||
}
|
||||
if (DISPOSABLE.includes(domain)) return { status: 'warn', note: 'disposable email address' };
|
||||
if (MAIL_DOMAINS.includes(domain)) return { status: 'ok', note: 'domain accepts email' };
|
||||
if (!(await dnsWorks())) return suggest ? { status: 'warn', note: 'possible typo', suggest } : { status: 'ok', note: '' };
|
||||
let mx = 'unknown';
|
||||
try {
|
||||
const recs = await withTimeout(dns.promises.resolveMx(domain), 3000);
|
||||
mx = recs && recs.length ? 'ok' : 'none';
|
||||
} catch (e) {
|
||||
if (e.code === 'ENOTFOUND' || e.code === 'ENODATA' || e.code === 'NXDOMAIN') {
|
||||
try { await withTimeout(dns.promises.resolve4(domain), 2000); mx = 'none'; } catch (e2) { mx = (e2.code === 'ENOTFOUND' || e2.code === 'ENODATA') ? 'nodomain' : 'unknown'; }
|
||||
}
|
||||
}
|
||||
if (mx === 'nodomain') return { status: 'bad', note: `domain ${domain} does not exist`, suggest };
|
||||
if (mx === 'none') return { status: suggest ? 'bad' : 'warn', note: `domain ${domain} cannot receive email`, suggest };
|
||||
if (suggest) return { status: 'warn', note: 'possible typo', suggest };
|
||||
return { status: 'ok', note: mx === 'ok' ? 'domain accepts email' : '' };
|
||||
}
|
||||
async function runChecks(conv, text, phoneChecks) {
|
||||
conv.contacts = conv.contacts || { emails: {}, phones: {} };
|
||||
const C = conv.contacts;
|
||||
for (const p of (Array.isArray(phoneChecks) ? phoneChecks : []).slice(0, 3)) {
|
||||
const raw = String(p.raw || '').slice(0, 40); if (!raw) continue;
|
||||
const key = String(p.e164 || raw).slice(0, 24);
|
||||
C.phones[key] = { raw, e164: p.e164 ? String(p.e164).slice(0, 24) : '', country: String(p.country || '').slice(0, 4), status: p.ok ? 'ok' : 'bad', note: String(p.reason || '').slice(0, 80), at: Date.now(), asked: false };
|
||||
}
|
||||
const emails = [...new Set((String(text).match(/[^\s<>()[\]"',;:]+@[^\s<>()[\]"',;:]+\.[a-z]{2,}/gi) || []).map((e) => e.replace(/[.]+$/, '').toLowerCase()))].slice(0, 3);
|
||||
// 客户发了新的号码 / 邮箱:之前有问题的旧号码 / 旧邮箱算是被更正了,不再追问
|
||||
const newPhone = (Array.isArray(phoneChecks) ? phoneChecks : []).some((p) => p.ok);
|
||||
if (newPhone) for (const v of Object.values(C.phones)) if (v.status !== 'ok' && v.at < Date.now() - 500) v.superseded = true;
|
||||
if (emails.length) for (const [k, v] of Object.entries(C.emails)) if (!emails.includes(k)) v.superseded = true;
|
||||
await Promise.all(emails.map(async (e) => {
|
||||
try { C.emails[e] = { ...(await checkEmail(e)), at: Date.now(), asked: false }; } catch (err) { /* 检查失败就不标 */ }
|
||||
}));
|
||||
bump(conv);
|
||||
}
|
||||
function contactProblems(conv) {
|
||||
const C = conv.contacts || { emails: {}, phones: {} }, out = [];
|
||||
for (const [k, v] of Object.entries(C.phones)) if (v.status !== 'ok' && !v.asked && !v.superseded) out.push({ ref: v, line: `- phone/WhatsApp "${v.raw}" looks wrong (${v.note || 'invalid'}). Politely ask the customer to double-check it, including the country code.` });
|
||||
for (const [k, v] of Object.entries(C.emails)) if (v.status !== 'ok' && !v.asked && !v.superseded) out.push({ ref: v, line: `- email "${k}": ${v.note}${v.suggest ? `; did they mean "${v.suggest}"?` : ''}. Politely ask the customer to confirm it.` });
|
||||
return out;
|
||||
}
|
||||
const contactLine = (conv) => {
|
||||
norm(conv);
|
||||
const C = conv.contacts || { emails: {}, phones: {} }, icon = { ok: '✅', warn: '⚠️', bad: '❌' };
|
||||
const parts = [...Object.values(C.phones).filter((v) => !v.superseded).map((v) => `电话 ${icon[v.status] || ''} ${v.e164 || v.raw}`), ...Object.entries(C.emails).filter(([, v]) => !v.superseded).map(([k, v]) => `邮箱 ${icon[v.status] || ''} ${k}`)];
|
||||
if (conv.wa && conv.wa.verified) parts.unshift('WhatsApp ✔ 已验证');
|
||||
else if (conv.wa && conv.wa.clicked) parts.unshift(`WhatsApp 待确认 #${conv.code}`);
|
||||
return parts.join(',');
|
||||
};
|
||||
|
||||
/* ---------------- 对话 ---------------- */
|
||||
const LANG_NAME = { en: 'English', es: 'Spanish', ru: 'Russian', zh: 'Chinese', fr: 'French', pt: 'Portuguese', ar: 'Arabic' };
|
||||
const GREET = {
|
||||
|
|
@ -1010,7 +1092,7 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
const JOINED = { en: (n, t) => `${n} (${t}) joined the chat`, es: (n, t) => `${n} (${t}) se unió al chat`, ru: (n, t) => `${n} (${t}) присоединился к чату` };
|
||||
function pubMsg(conv, m) {
|
||||
const st = S();
|
||||
return { id: m.id, at: m.at, from: m.from === 'user' ? 'user' : m.from === 'sys' ? 'sys' : 'agent', name: m.from === 'human' ? st.managerName : m.from === 'ai' ? st.agentName : undefined, text: m.text };
|
||||
return { id: m.id, at: m.at, from: m.from === 'user' ? 'user' : m.from === 'sys' ? 'sys' : 'agent', name: m.from === 'human' ? st.managerName : m.from === 'ai' ? st.agentName : undefined, text: m.text, wa: m.wa || undefined };
|
||||
}
|
||||
const visible = (m) => m.from !== 'note';
|
||||
function addMsg(conv, m) {
|
||||
|
|
@ -1020,11 +1102,13 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
bump(conv);
|
||||
return msg;
|
||||
}
|
||||
// 旧对话(这个功能上线前开始的)补上新字段
|
||||
function norm(c) { if (c) { c.wa = c.wa || {}; c.contacts = c.contacts || { emails: {}, phones: {} }; c.code = c.code || String(1000 + crypto.randomInt(9000)); } return c; }
|
||||
function getConv(req) {
|
||||
const b = { ...(req.query || {}), ...(req.body || {}) };
|
||||
const c = store.convs[String(b.sid || '')];
|
||||
if (!c || !b.token || c.token !== String(b.token)) return null;
|
||||
return c;
|
||||
return norm(c);
|
||||
}
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
|
|
@ -1043,12 +1127,13 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
ip: ipHash(ip), ipCountry: String(req.headers['cf-ipcountry'] || '').slice(0, 4),
|
||||
page: String(b.page || '').slice(0, 300), title: String(b.title || '').slice(0, 200), ua: String(req.headers['user-agent'] || '').slice(0, 200),
|
||||
pages: [], msgs: [], mode: 'ai', typing: false, status: 'open', unread: 0, lead: { tier: 'unknown', score: 0 }, notified: 0, joined: false,
|
||||
code: String(1000 + crypto.randomInt(9000)), contacts: { emails: {}, phones: {} }, wa: {},
|
||||
};
|
||||
bump(conv);
|
||||
// 问候语:先"正在输入"一会儿再出来(不调 AI,省费用)
|
||||
setTimeout(() => { conv.typing = true; bump(conv); }, 900);
|
||||
setTimeout(() => { conv.typing = false; if (!conv.msgs.some((m) => m.from !== 'sys')) addMsg(conv, { from: 'ai', text: GREET[lang] }); else bump(conv); }, 2600);
|
||||
res.json({ sid, token });
|
||||
res.json({ sid, token, cc: conv.ipCountry });
|
||||
});
|
||||
|
||||
app.post('/api/chat/send', (req, res) => {
|
||||
|
|
@ -1064,10 +1149,23 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
if (conv.status === 'closed') conv.status = 'open';
|
||||
const m = addMsg(conv, { from: 'user', text, page: page || undefined });
|
||||
res.json({ ok: true, id: m.id });
|
||||
conv._chk = runChecks(conv, text, (req.body || {}).checks).catch((e) => console.warn('[chat] 检查联系方式失败:', e.message));
|
||||
scheduleAi(conv);
|
||||
scheduleClassify(conv);
|
||||
});
|
||||
|
||||
app.post('/api/chat/event', (req, res) => {
|
||||
const conv = getConv(req);
|
||||
if (!conv) return res.status(404).json({ error: 'no session' });
|
||||
if ((req.body || {}).type === 'wa_click' && !conv.wa.clicked) {
|
||||
conv.wa.clicked = Date.now();
|
||||
bump(conv);
|
||||
conv.notifiedAt = 0; // 这条一定要推
|
||||
notifyLead(conv, `客户点了"转到 WhatsApp",留意带 #${conv.code} 的 WhatsApp 消息`);
|
||||
}
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/chat/poll', async (req, res) => {
|
||||
const conv = getConv(req);
|
||||
if (!conv) return res.status(404).json({ error: 'no session' });
|
||||
|
|
@ -1085,6 +1183,21 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
req.on('close', () => { clearTimeout(t); set.delete(fn); });
|
||||
});
|
||||
|
||||
/* ---------------- 第二层:重要客户转到 WhatsApp ---------------- */
|
||||
const WA_LABEL = { en: (n) => `Chat with ${n} on WhatsApp`, es: (n) => `Hablar con ${n} por WhatsApp`, ru: (n) => `Написать ${n} в WhatsApp` };
|
||||
const WA_TEXT = {
|
||||
en: (n, who, code) => `Hi ${n}, ${who ? `this is ${who}` : 'I was chatting on your website'} (SKE chat #${code}).`,
|
||||
es: (n, who, code) => `Hola ${n}, ${who ? `soy ${who}` : 'estuve conversando en su sitio web'} (chat SKE #${code}).`,
|
||||
ru: (n, who, code) => `Здравствуйте, ${n}! ${who ? `Это ${who}` : 'Я писал(а) вам на сайте'} (чат SKE #${code}).`,
|
||||
};
|
||||
function waButton(conv) {
|
||||
const st = S(); if (!st.waNumber) return null;
|
||||
const l = conv.lead || {}, lang = WA_TEXT[conv.custLang] ? conv.custLang : (WA_TEXT[conv.lang] ? conv.lang : 'en');
|
||||
const who = [l.name, l.company && `${lang === 'es' ? 'de' : lang === 'ru' ? 'из' : 'from'} ${l.company}`].filter(Boolean).join(' ');
|
||||
return { url: `https://wa.me/${st.waNumber}?text=${encodeURIComponent(WA_TEXT[lang](st.managerName, who, conv.code))}`, label: WA_LABEL[lang](st.managerName) };
|
||||
}
|
||||
const important = (conv) => (conv.lead && (conv.lead.score || 0) >= S().notifyScore);
|
||||
|
||||
/* ---------------- AI 回复 ---------------- */
|
||||
const pending = new Map(); // sid → timer
|
||||
function scheduleAi(conv) {
|
||||
|
|
@ -1119,9 +1232,12 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
`PRODUCT CATALOG (model | type | rating | key specs | price ladder | page):\n${cat.map((o) => catLine(o, lang)).join('\n').slice(0, 40000)}`,
|
||||
mentioned.length ? `PRODUCT DETAILS:\n${mentioned.map((o) => productDetail(o, lang)).join('\n\n')}` : '',
|
||||
conv.page ? `The customer is currently on this page: ${conv.page}${conv.title ? ` ("${conv.title}")` : ''}` : '',
|
||||
conv._problems && conv._problems.length ? `CONTACT CHECK (automatic and reliable — mention it naturally in this reply, briefly, before anything else):\n${conv._problems.map((p) => p.line).join('\n')}` : '',
|
||||
important(conv) && !conv.wa.offered && st.waNumber ? `WHATSAPP: this is an important customer. In this reply, offer that ${st.managerName}, our ${st.managerTitle.toLowerCase()}, can continue with them directly on WhatsApp for the quotation, and add the tag [[WHATSAPP]] at the very end (a WhatsApp button will be shown under your message). Do not write a phone number or link yourself.` : '',
|
||||
].filter(Boolean).join('\n\n');
|
||||
}
|
||||
async function aiReply(conv) {
|
||||
norm(conv);
|
||||
if (conv.mode !== 'ai') return;
|
||||
const lastUser = [...conv.msgs].reverse().find((m) => m.from === 'user');
|
||||
if (!lastUser) return;
|
||||
|
|
@ -1131,6 +1247,8 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
if (conv.mode !== 'ai') return;
|
||||
conv.typing = true; bump(conv);
|
||||
const history = conv.msgs.filter((m) => m.from === 'user' || m.from === 'ai' || m.from === 'human').slice(-24);
|
||||
try { if (conv._chk) await withTimeout(conv._chk, 7000); } catch (e) { /* 检查超时就先回复 */ }
|
||||
conv._problems = contactProblems(conv);
|
||||
let text = '';
|
||||
try {
|
||||
if (!useAi('reply')) throw new Error('daily cap');
|
||||
|
|
@ -1146,7 +1264,8 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
// 提取标记
|
||||
const unsure = [...text.matchAll(/\[\[UNSURE:\s*([\s\S]*?)\]\]/gi)].map((x) => x[1].trim());
|
||||
const handoff = [...text.matchAll(/\[\[HANDOFF:\s*([\s\S]*?)\]\]/gi)].map((x) => x[1].trim());
|
||||
text = text.replace(/\[\[(UNSURE|HANDOFF):[\s\S]*?\]\]/gi, '').trim();
|
||||
const wantWa = /\[\[WHATSAPP\]\]/i.test(text);
|
||||
text = text.replace(/\[\[(UNSURE|HANDOFF):[\s\S]*?\]\]/gi, '').replace(/\[\[WHATSAPP\]\]/gi, '').trim();
|
||||
for (const q of unsure) if (q && !(store.unanswered || []).some((u) => u.q === q && u.status === 'open')) { store.unanswered = store.unanswered || []; store.unanswered.unshift({ id: uid('u'), q, sid: conv.sid, at: Date.now(), status: 'open' }); store.unanswered = store.unanswered.slice(0, 500); }
|
||||
if (handoff.length) { conv.lead.needsHuman = true; conv.lead.handoff = handoff[handoff.length - 1]; }
|
||||
// 按长度停顿,看起来像在打字;整体至少 minReplyMs
|
||||
|
|
@ -1155,7 +1274,11 @@ function mountChat(app, { dataFile, requireAuth, ai }) {
|
|||
await sleep(wait);
|
||||
conv.typing = false;
|
||||
if (conv.mode !== 'ai' || !text) { bump(conv); return; }
|
||||
addMsg(conv, { from: 'ai', text });
|
||||
for (const p of conv._problems || []) p.ref.asked = true;
|
||||
conv._problems = [];
|
||||
const wa = wantWa && !conv.wa.offered ? waButton(conv) : null;
|
||||
if (wa) conv.wa.offered = Date.now();
|
||||
addMsg(conv, { from: 'ai', text, wa: wa || undefined });
|
||||
if (handoff.length) notifyLead(conv, '客户需要人工:' + handoff[handoff.length - 1]);
|
||||
scheduleClassify(conv, true);
|
||||
}
|
||||
|
|
@ -1214,6 +1337,7 @@ ${dialog}`;
|
|||
`> ${[l.country || conv.ipCountry, TIER_ZH[l.tier] || '', l.score ? `评分 ${l.score}` : ''].filter(Boolean).join(' · ')}`,
|
||||
l.summary_zh ? `> ${l.summary_zh}` : '',
|
||||
[l.name, l.company].filter(Boolean).length ? `> ${[l.name, l.company].filter(Boolean).join(' / ')}` : '',
|
||||
contactLine(conv) ? `> ${contactLine(conv)}` : '',
|
||||
`> 状态:${conv.mode === 'human' ? '你在接待' : 'AI 正在接待'}`,
|
||||
panel ? `[打开对话](${panel}/?chat=${conv.sid}&k=${linkKey(conv.sid)})` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
|
|
@ -1227,7 +1351,7 @@ ${dialog}`;
|
|||
const A = '/api/chat/admin';
|
||||
const summary = (c) => {
|
||||
const last = [...c.msgs].reverse().find((m) => m.from === 'user' || m.from === 'ai' || m.from === 'human');
|
||||
return { sid: c.sid, created: c.created, updated: c.updated, lang: c.lang, ipCountry: c.ipCountry, page: c.page, mode: c.mode, status: c.status, typing: c.typing, unread: c.unread || 0, lead: c.lead, n: c.msgs.filter((m) => m.from === 'user').length, last: last ? { from: last.from, text: (last.zh || last.text).slice(0, 120), at: last.at } : null };
|
||||
return { contact: contactLine(c), code: c.code, sid: c.sid, created: c.created, updated: c.updated, lang: c.lang, ipCountry: c.ipCountry, page: c.page, mode: c.mode, status: c.status, typing: c.typing, unread: c.unread || 0, lead: c.lead, n: c.msgs.filter((m) => m.from === 'user').length, last: last ? { from: last.from, text: (last.zh || last.text).slice(0, 120), at: last.at } : null };
|
||||
};
|
||||
app.get(`${A}/wait`, requireAuth, (req, res) => {
|
||||
const since = Number(req.query.ver) || 0;
|
||||
|
|
@ -1268,7 +1392,7 @@ ${dialog}`;
|
|||
set.add(fn);
|
||||
req.on('close', () => { clearTimeout(t); set.delete(fn); });
|
||||
});
|
||||
const convOr404 = (req, res) => { const c = store.convs[req.params.sid]; if (!c) res.status(404).json({ error: 'not found' }); return c; };
|
||||
const convOr404 = (req, res) => { const c = norm(store.convs[req.params.sid]); if (!c) res.status(404).json({ error: 'not found' }); return c; };
|
||||
function join(c) {
|
||||
if (c.mode !== 'human') { c.mode = 'human'; c.typing = false; if (pending.has(c.sid)) { clearTimeout(pending.get(c.sid)); pending.delete(c.sid); } }
|
||||
if (!c.joined) { c.joined = true; const st = S(); addMsg(c, { from: 'sys', text: (JOINED[c.lang] || JOINED.en)(st.managerName, st.managerTitle) }); }
|
||||
|
|
@ -1313,6 +1437,22 @@ ${dialog}`;
|
|||
addMsg(c, { from: 'note', text });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
// 手动给客户发"转到 WhatsApp"按钮(以 Mike 的名义)
|
||||
const WA_MSG = { en: (n) => `You can also reach me directly on WhatsApp — just tap the button below.`, es: (n) => `También puede escribirme directamente por WhatsApp; toque el botón de abajo.`, ru: (n) => `Можно написать мне напрямую в WhatsApp — нажмите кнопку ниже.` };
|
||||
app.post(`${A}/:sid/wa-offer`, authConv, (req, res) => {
|
||||
const c = convOr404(req, res); if (!c) return;
|
||||
const wa = waButton(c); if (!wa) return res.status(400).json({ error: '设置里没填 WhatsApp 号码' });
|
||||
const lang = WA_MSG[c.custLang] ? c.custLang : (WA_MSG[c.lang] ? c.lang : 'en');
|
||||
join(c); c.wa.offered = Date.now();
|
||||
addMsg(c, { from: 'human', text: WA_MSG[lang](S().managerName), wa, zh: '(发了"转到 WhatsApp"按钮)' });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
app.post(`${A}/:sid/wa-verified`, authConv, (req, res) => {
|
||||
const c = convOr404(req, res); if (!c) return;
|
||||
c.wa.verified = (req.body || {}).off ? 0 : Date.now();
|
||||
if (c.wa.verified && (c.lead.score || 0) < 70) c.lead.score = 70;
|
||||
bump(c); res.json({ ok: true });
|
||||
});
|
||||
// 让 AI 按悄悄话马上再回一条
|
||||
app.post(`${A}/:sid/nudge`, authConv, (req, res) => { const c = convOr404(req, res); if (!c) return; c.mode = 'ai'; bump(c); aiReply(c).catch(() => {}); res.json({ ok: true }); });
|
||||
|
||||
|
|
@ -1334,7 +1474,7 @@ ${dialog}`;
|
|||
});
|
||||
app.put(`${A}/settings`, requireAuth, (req, res) => {
|
||||
const b = req.body || {}, cur = S(), next = { ...cur };
|
||||
for (const k of ['agentName', 'managerName', 'managerTitle', 'wecomWebhook', 'siteUrl', 'panelUrl']) if (typeof b[k] === 'string') next[k] = b[k].trim().slice(0, 500);
|
||||
for (const k of ['agentName', 'managerName', 'managerTitle', 'wecomWebhook', 'siteUrl', 'panelUrl', 'waNumber']) if (typeof b[k] === 'string') next[k] = b[k].trim().slice(0, 500);
|
||||
for (const k of ['notifyScore', 'dailyCap', 'minReplyMs']) if (b[k] !== undefined && !isNaN(+b[k])) next[k] = Math.max(0, +b[k]);
|
||||
if (typeof b.enabled === 'boolean') next.enabled = b.enabled;
|
||||
if (Array.isArray(b.origins)) next.origins = b.origins.map(String).filter((o) => /^https?:\/\/[^/]+$/.test(o)).slice(0, 20);
|
||||
|
|
|
|||
Loading…
Reference in New Issue