Update server.js via upload script - 2026-11-16 22:46:41
This commit is contained in:
parent
4fc3350952
commit
4f0723fc95
277
server.js
277
server.js
|
|
@ -1402,62 +1402,188 @@ async function extractConvoFile(f) {
|
|||
}
|
||||
|
||||
const convoUpload = multer({ storage: multer.memoryStorage(), limits: { files: 10, fileSize: 30 * 1024 * 1024 } });
|
||||
const importUpload = multer({ storage: multer.memoryStorage(), limits: { files: 5, fileSize: 200 * 1024 * 1024 } });
|
||||
const fixUploadName = (n) => { n = String(n || ''); if (/[^\u0000-ÿ]/.test(n)) return n; const u = Buffer.from(n, 'latin1').toString('utf8'); return u.includes('<27>') ? n : u; };
|
||||
const clipTxt = (v, n) => String(v == null ? '' : v).replace(/\r\n/g, '\n').slice(0, n);
|
||||
|
||||
// ---------- 聊天式沟通记录 ----------
|
||||
// 每条消息:{ id, from: 'customer' | 'me', channel, at: 'YYYY-MM-DD HH:mm', text, zh, files: [{ name, stored, size, mime }], fileText, createdAt }
|
||||
// zh:中文对照(原文已是中文时为 '',还没翻译时没有这个字段)
|
||||
// 旧版的整段记录(没有 from)当作 from: 'note' 显示
|
||||
const MSG_CHANNELS = ['whatsapp', 'wechat', 'email', 'phone', 'meeting', 'other'];
|
||||
const AT_RE = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
|
||||
const nowAt = () => { const d = new Date(Date.now() + 8 * 3600 * 1000); return d.toISOString().slice(0, 16).replace('T', ' '); }; // 北京时间
|
||||
const newMsgId = () => 'm_' + Date.now() + '_' + crypto.randomBytes(3).toString('hex');
|
||||
const isMostlyChinese = (t) => { const s = String(t || ''); const han = (s.match(/\p{Script=Han}/gu) || []).length; const lat = (s.match(/[A-Za-zА-Яа-яЁё\u0600-\u06FF]/g) || []).length; return han > 0 && han * 2 >= lat; };
|
||||
function normMsg(m) {
|
||||
if (m.from) return m;
|
||||
return { ...m, from: 'note', at: m.at || `${m.date || '2000-01-01'} 00:00` };
|
||||
}
|
||||
function storeFile(cid, f, prefix = 'conv') {
|
||||
const dir = path.join(UPLOADS_DIR, cid); fs.mkdirSync(dir, { recursive: true });
|
||||
const ext = path.extname(f.originalname || '').toLowerCase().replace(/[^.a-z0-9]/g, '');
|
||||
const stored = `${prefix}_${Date.now()}_${crypto.randomBytes(3).toString('hex')}${ext}`;
|
||||
fs.writeFileSync(path.join(dir, stored), f.buffer);
|
||||
return { name: f.originalname, stored, size: f.size || f.buffer.length, mime: f.mimetype || '' };
|
||||
}
|
||||
const MIME_BY_EXT = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif', '.pdf': 'application/pdf', '.mp4': 'video/mp4', '.opus': 'audio/ogg', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' };
|
||||
|
||||
// 附件里的文字(给 AI 看,不显示):PDF 文字层、Word、邮件、文本;图片不做 OCR(太慢)
|
||||
async function fileTextFor(f) {
|
||||
const ext = path.extname(f.originalname || '').toLowerCase();
|
||||
if (!['.pdf', '.docx', '.eml', '.txt', '.csv', '.md', '.html', '.htm'].includes(ext)) return '';
|
||||
try {
|
||||
if (ext === '.pdf') {
|
||||
fs.mkdirSync(OCR_TMP_ROOT, { recursive: true });
|
||||
const tmp = fs.mkdtempSync(path.join(OCR_TMP_ROOT, 'conv-'));
|
||||
try { return clipTxt(await pdfTextLayer(f.buffer, tmp), 20000); } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
|
||||
}
|
||||
const r = await extractConvoFile(f);
|
||||
return clipTxt(r.text, 20000);
|
||||
} catch (e) { return ''; }
|
||||
}
|
||||
|
||||
// WhatsApp 导出 → 一条条消息。日期格式各手机不一样(日/月/年、月/日/年、年-月-日),整份文件统一判断
|
||||
function waDateOrder(rows) {
|
||||
let dayFirst = 0, monthFirst = 0;
|
||||
for (const r of rows) {
|
||||
const p = r.d.split(/[./-]/).map(Number);
|
||||
if (p[0] > 31) continue;
|
||||
if (p[0] > 12) dayFirst++; else if (p[1] > 12) monthFirst++;
|
||||
}
|
||||
return monthFirst > dayFirst ? 'mdy' : 'dmy';
|
||||
}
|
||||
function waToAt(d, t, order) {
|
||||
const p = d.split(/[./-]/).map(Number);
|
||||
let y, m, day;
|
||||
if (p[0] > 31) [y, m, day] = p; else if (order === 'mdy') [m, day, y] = p; else [day, m, y] = p;
|
||||
if (y < 100) y += 2000;
|
||||
const tm = t.match(/(\d{1,2}):(\d{2})/); let h = +tm[1];
|
||||
if (/p/i.test(t) && h < 12) h += 12; if (/a/i.test(t) && h === 12) h = 0;
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${y}-${pad(m)}-${pad(day)} ${pad(h)}:${tm[2]}`;
|
||||
}
|
||||
const WA_ATTACH = [/<attached:\s*([^>]+)>/i, /^(.+?\.\w{2,5})\s*\((?:file attached|文件已附上|archivo adjunto|файл прикреплен)\)/i, /^?([\w-]+\.\w{2,5})\s*$/];
|
||||
function parseWaMessages(text) {
|
||||
const t = String(text || '').replace(/[-]/g, '').replace(/\r\n/g, '\n');
|
||||
const rows = []; let cur = null;
|
||||
for (const l of t.split('\n')) {
|
||||
const m = l.match(WA_LINE);
|
||||
if (m) { cur = { d: m[1], t: m[2], who: m[3].trim(), text: l.slice(m[0].length) }; rows.push(cur); }
|
||||
else if (cur) cur.text += '\n' + l;
|
||||
}
|
||||
const order = waDateOrder(rows);
|
||||
return rows.map((r) => ({ at: waToAt(r.d, r.t, order), who: r.who, text: r.text.trim() }));
|
||||
}
|
||||
const sameName = (a, b) => { a = String(a || '').toLowerCase().trim(); b = String(b || '').toLowerCase().trim(); return !!a && !!b && (a === b || a.split(/\s+/)[0] === b.split(/\s+/)[0]); };
|
||||
|
||||
app.get('/api/convos/:cid', requireAuth, (req, res) => {
|
||||
const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
|
||||
const c = readConvos()[cid] || { items: [], analysis: null };
|
||||
res.json(c);
|
||||
res.json({ ...c, items: c.items.map(normMsg) });
|
||||
});
|
||||
|
||||
// 新增一条:粘贴的文字 + 上传的文件(每个文件识别出的文字依次拼在后面)
|
||||
// 发一条消息(客户说的 / 我回复的),可带附件
|
||||
app.post('/api/convos/:cid', requireAuth, (req, res) => {
|
||||
const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
|
||||
convoUpload.array('files', 10)(req, res, async (err) => {
|
||||
if (err) return res.status(400).json({ error: err.code === 'LIMIT_FILE_SIZE' ? '单个文件不能超过 30 MB' : err.message });
|
||||
const b = req.body || {};
|
||||
const files = (req.files || []).map((f) => ({ ...f, originalname: fixUploadName(f.originalname) }));
|
||||
const pasted = clipTxt(b.text, CONVO_TEXT_MAX).trim();
|
||||
if (!pasted && !files.length) return res.status(400).json({ error: '请粘贴沟通内容或上传文件' });
|
||||
const text = clipTxt(b.text, CONVO_TEXT_MAX).trim();
|
||||
if (!text && !files.length) return res.status(400).json({ error: '请输入内容或添加附件' });
|
||||
try {
|
||||
const parts = [], saved = [], notes = [];
|
||||
let channel = CONVO_CHANNELS.includes(b.channel) ? b.channel : '', title = clipTxt(b.title, 200).trim(), date = /^\d{4}-\d{2}-\d{2}$/.test(b.date || '') ? b.date : '';
|
||||
let stats = null;
|
||||
if (pasted) {
|
||||
const wa = parseWhatsApp(pasted);
|
||||
if (wa) { stats = wa.stats; if (!channel) channel = 'whatsapp'; }
|
||||
parts.push(pasted);
|
||||
}
|
||||
const dir = path.join(UPLOADS_DIR, cid); fs.mkdirSync(dir, { recursive: true });
|
||||
for (const f of files) {
|
||||
const r = await extractConvoFile(f);
|
||||
if (r.kind === 'email' && !channel) channel = 'email';
|
||||
if (r.kind === 'whatsapp' && !channel) channel = 'whatsapp';
|
||||
if (r.kind === 'email' && !title && r.subject) title = r.subject;
|
||||
if (r.date && !date) date = r.date;
|
||||
if (r.stats) stats = stats ? { ...stats, messages: (stats.messages || 0) + (r.stats.messages || 0) } : r.stats;
|
||||
if (r.ocr) notes.push(`${f.originalname}:截图 / 扫描件文字是 OCR 识别的,可能有错字`);
|
||||
if (r.text && r.text.trim()) parts.push(files.length > 1 || pasted ? `===== ${f.originalname} =====\n${r.text.trim()}` : r.text.trim());
|
||||
const stored = `conv_${Date.now()}_${crypto.randomBytes(3).toString('hex')}${path.extname(f.originalname).toLowerCase().replace(/[^.a-z0-9]/g, '') || ''}`;
|
||||
fs.writeFileSync(path.join(dir, stored), f.buffer);
|
||||
saved.push({ name: f.originalname, stored, size: f.size, mime: f.mimetype });
|
||||
}
|
||||
const text = clipTxt(parts.join('\n\n'), CONVO_TEXT_MAX);
|
||||
if (!text.trim() && !saved.length) return res.status(400).json({ error: '没有识别出文字内容' });
|
||||
const item = {
|
||||
id: 'cv_' + Date.now() + '_' + crypto.randomBytes(3).toString('hex'),
|
||||
channel: channel || 'other', title, date: date || new Date().toISOString().slice(0, 10),
|
||||
direction: ['in', 'out', 'both'].includes(b.direction) ? b.direction : 'both',
|
||||
text, files: saved, stats, notes, createdAt: Date.now(),
|
||||
const saved = [], ft = [];
|
||||
for (const f of files) { saved.push(storeFile(cid, f)); const x = await fileTextFor(f); if (x) ft.push(`【${f.originalname}】\n${x}`); }
|
||||
const msg = {
|
||||
id: newMsgId(), from: b.from === 'me' ? 'me' : 'customer',
|
||||
channel: MSG_CHANNELS.includes(b.channel) ? b.channel : 'whatsapp',
|
||||
at: AT_RE.test(b.at || '') ? b.at : nowAt(), text, files: saved, createdAt: Date.now(),
|
||||
};
|
||||
const all = readConvos(); const c = convoOf(all, cid);
|
||||
c.items.push(item); writeConvos(all);
|
||||
res.json({ ok: true, item });
|
||||
} catch (e) {
|
||||
console.warn('[沟通记录] 添加失败:', e.message);
|
||||
res.status(400).json({ error: e.message });
|
||||
if (ft.length) msg.fileText = clipTxt(ft.join('\n\n'), 40000);
|
||||
if (!text || isMostlyChinese(text)) msg.zh = '';
|
||||
const all = readConvos(); convoOf(all, cid).items.push(msg); writeConvos(all);
|
||||
res.json({ ok: true, item: msg });
|
||||
} catch (e) { res.status(400).json({ error: e.message }); }
|
||||
});
|
||||
});
|
||||
|
||||
// 导入整段聊天:WhatsApp 导出(.txt / .zip,含图片)、邮件 .eml、或直接粘贴的 WhatsApp 文字 → 拆成一条条消息
|
||||
// me:聊天记录里"我"的名字(默认 Mike),其他人都算客户
|
||||
app.post('/api/convos/:cid/import', requireAuth, (req, res) => {
|
||||
const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
|
||||
importUpload.array('files', 5)(req, res, async (err) => {
|
||||
if (err) return res.status(400).json({ error: err.code === 'LIMIT_FILE_SIZE' ? '文件太大(最多 200 MB)' : err.message });
|
||||
const b = req.body || {};
|
||||
const meNames = String(b.me || 'Mike').split(/[,,]/).map((s) => s.trim()).filter(Boolean);
|
||||
const channel = MSG_CHANNELS.includes(b.channel) ? b.channel : '';
|
||||
const files = (req.files || []).map((f) => ({ ...f, originalname: fixUploadName(f.originalname) }));
|
||||
const out = [];
|
||||
const isMe = (who) => meNames.some((n) => sameName(n, who) || String(who || '').toLowerCase().includes(n.toLowerCase()));
|
||||
const addWa = (rows, media, ch) => {
|
||||
for (const r of rows) {
|
||||
let text = r.text; const fl = [];
|
||||
for (const re of WA_ATTACH) {
|
||||
const m = text.match(re);
|
||||
if (m && media) {
|
||||
const name = m[1].trim(); const e = media.get(name.toLowerCase());
|
||||
if (e) {
|
||||
const buf = e.read();
|
||||
if (buf) { fl.push(storeFile(cid, { originalname: name, buffer: buf, size: buf.length, mimetype: MIME_BY_EXT[path.extname(name).toLowerCase()] || '' }, 'wa')); text = text.replace(m[0], '').trim(); }
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (/^<(Media omitted|媒体文件已省略|Multimedia omitido)>$/i.test(text)) text = '[图片 / 文件未导出]';
|
||||
if (!text && !fl.length) continue;
|
||||
const msg = { id: newMsgId(), from: isMe(r.who) ? 'me' : 'customer', who: r.who, channel: ch || channel || 'whatsapp', at: r.at, text, files: fl, createdAt: Date.now() };
|
||||
if (!text || isMostlyChinese(text)) msg.zh = '';
|
||||
out.push(msg);
|
||||
}
|
||||
};
|
||||
try {
|
||||
const pasted = clipTxt(b.text, CONVO_TEXT_MAX).trim();
|
||||
if (pasted) {
|
||||
const rows = parseWaMessages(pasted);
|
||||
if (rows.length < 1) return res.status(400).json({ error: '没认出聊天格式。每行要像 "12/11/2026, 14:05 - Anton: 内容" 这样;单条消息请直接在下面的输入框里发。' });
|
||||
addWa(rows, null, channel);
|
||||
}
|
||||
for (const f of files) {
|
||||
const ext = path.extname(f.originalname).toLowerCase();
|
||||
if (ext === '.zip') {
|
||||
const entries = unzipEntries(f.buffer);
|
||||
const txt = entries.find((e) => /(^|\/)(_chat|WhatsApp[^/]*)\.txt$/i.test(e.name)) || entries.find((e) => /\.txt$/i.test(e.name));
|
||||
if (!txt) throw new Error(`${f.originalname}:压缩包里没有找到聊天记录 .txt`);
|
||||
const media = new Map(entries.filter((e) => e !== txt).map((e) => [path.basename(e.name).toLowerCase(), e]));
|
||||
addWa(parseWaMessages(decodeText(txt.read())), media, 'whatsapp');
|
||||
} else if (ext === '.eml') {
|
||||
const raw = f.buffer.toString('latin1'); const head = splitMime(raw).headers;
|
||||
const r = parseEml(f.buffer);
|
||||
const fromH = decodeWords(head.from || '');
|
||||
const mine = /ups-china\.com|skepower|ske-?power/i.test(fromH) || isMe(fromH.replace(/<.*>/, '').replace(/"/g, ''));
|
||||
const body = r.text.split(/\n\n/).slice(1).join('\n\n').trim();
|
||||
const d = Date.parse(decodeWords(head.date || ''));
|
||||
const at = isNaN(d) ? nowAt() : new Date(d + 8 * 3600 * 1000).toISOString().slice(0, 16).replace('T', ' ');
|
||||
const text = `${r.subject ? `主题:${r.subject}\n\n` : ''}${body}`;
|
||||
const msg = { id: newMsgId(), from: mine ? 'me' : 'customer', channel: 'email', at, text: clipTxt(text, CONVO_TEXT_MAX), files: [storeFile(cid, f)], createdAt: Date.now() };
|
||||
if (isMostlyChinese(body)) msg.zh = '';
|
||||
out.push(msg);
|
||||
} else if (/^text\//.test(f.mimetype) || ext === '.txt') {
|
||||
const rows = parseWaMessages(decodeText(f.buffer));
|
||||
if (!rows.length) throw new Error(`${f.originalname}:没认出 WhatsApp 聊天格式`);
|
||||
addWa(rows, null, channel);
|
||||
} else throw new Error(`${f.originalname}:导入只支持 WhatsApp 导出(.txt / .zip)和邮件(.eml)。图片、PDF 请在聊天输入框里作为附件发送`);
|
||||
}
|
||||
if (!out.length) return res.status(400).json({ error: '没有读到消息' });
|
||||
// 和已有消息重复的(同时间、同发送方、同内容)跳过,方便重复导入同一个聊天的新导出
|
||||
const all = readConvos(); const c = convoOf(all, cid);
|
||||
const key = (m) => `${m.at}|${m.from}|${String(m.text || '').slice(0, 200)}`;
|
||||
const have = new Set(c.items.map(key));
|
||||
const fresh = out.filter((m) => !have.has(key(m)));
|
||||
c.items.push(...fresh); writeConvos(all);
|
||||
const people = [...new Set(out.map((m) => m.who).filter(Boolean))];
|
||||
res.json({ ok: true, items: fresh, skipped: out.length - fresh.length, people, meFound: out.some((m) => m.from === 'me') });
|
||||
} catch (e) { console.warn('[沟通记录] 导入失败:', e.message); res.status(400).json({ error: e.message }); }
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1467,14 +1593,14 @@ app.put('/api/convos/:cid/:id', requireAuth, (req, res) => {
|
|||
const it = c && c.items.find((x) => x.id === req.params.id);
|
||||
if (!it) return res.status(404).json({ error: 'not found' });
|
||||
const b = req.body || {};
|
||||
if (CONVO_CHANNELS.includes(b.channel)) it.channel = b.channel;
|
||||
if (typeof b.title === 'string') it.title = clipTxt(b.title, 200);
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(b.date || '')) it.date = b.date;
|
||||
if (typeof b.text === 'string') it.text = clipTxt(b.text, CONVO_TEXT_MAX);
|
||||
if (['in', 'out', 'both'].includes(b.direction)) it.direction = b.direction;
|
||||
if (MSG_CHANNELS.includes(b.channel)) it.channel = b.channel;
|
||||
if (b.from === 'me' || b.from === 'customer') { if (it.from) it.from = b.from; }
|
||||
if (AT_RE.test(b.at || '')) { it.at = b.at; if (it.date) it.date = b.at.slice(0, 10); }
|
||||
if (typeof b.text === 'string' && b.text !== it.text) { it.text = clipTxt(b.text, CONVO_TEXT_MAX); if (it.from) { delete it.zh; if (!it.text.trim() || isMostlyChinese(it.text)) it.zh = ''; } }
|
||||
if (typeof b.zh === 'string') it.zh = clipTxt(b.zh, CONVO_TEXT_MAX);
|
||||
it.updatedAt = Date.now();
|
||||
writeConvos(all);
|
||||
res.json({ ok: true, item: it });
|
||||
res.json({ ok: true, item: normMsg(it) });
|
||||
});
|
||||
|
||||
app.delete('/api/convos/:cid/:id', requireAuth, (req, res) => {
|
||||
|
|
@ -1496,19 +1622,54 @@ app.delete('/api/convos/:cid', requireAuth, (req, res) => {
|
|||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// 翻译成中文对照:一次最多处理 30 条还没翻译的消息,返回 { done: [{id, zh}], remaining }
|
||||
app.post('/api/convos/:cid/translate', requireAuth, async (req, res) => {
|
||||
const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
|
||||
const cfg = loadAiConfig();
|
||||
if (!cfg.apiKey && !cfg.backup.apiKey) return res.status(400).json({ error: '还没有配置 AI(设置 → AI 接口)' });
|
||||
const want = Array.isArray((req.body || {}).ids) ? new Set(req.body.ids) : null;
|
||||
const pending = () => { const c = readConvos()[cid]; return c ? c.items.filter((m) => m.from && m.zh === undefined && (!want || want.has(m.id))) : []; };
|
||||
let batch = [], size = 0;
|
||||
for (const m of pending()) { const l = String(m.text).length; if (batch.length && (batch.length >= 30 || size + l > 12000)) break; batch.push(m); size += l; }
|
||||
if (!batch.length) return res.json({ done: [], remaining: 0 });
|
||||
try {
|
||||
const input = {}; batch.forEach((m, i) => { input[String(i + 1)] = clipTxt(m.text, 6000); });
|
||||
const content = await callDeepSeekWithRetry(cfg.apiKey, [
|
||||
{ role: 'system', content: `${OUR_BUSINESS}\n你是翻译。把用户给的每条聊天消息翻译成简体中文,口语自然,准确保留型号、数字、单位、价格、人名、公司名。原文本身已经是中文的,译文写空字符串。只输出一个 JSON 对象,键和输入的编号一样,值是译文,不要任何解释。` },
|
||||
{ role: 'user', content: JSON.stringify(input) },
|
||||
], { maxTokens: 6000, temperature: 0.1, timeoutMs: 120000 });
|
||||
const { data } = extractJson(content);
|
||||
if (!data || typeof data !== 'object') throw new Error('翻译返回的格式不对');
|
||||
const all = readConvos(); const c = convoOf(all, cid); const done = [];
|
||||
batch.forEach((m, i) => {
|
||||
const v = data[String(i + 1)]; if (typeof v !== 'string') return;
|
||||
const it = c.items.find((x) => x.id === m.id); if (!it || it.text !== m.text) return;
|
||||
it.zh = v.trim(); done.push({ id: it.id, zh: it.zh });
|
||||
});
|
||||
writeConvos(all);
|
||||
res.json({ done, remaining: pending().length });
|
||||
} catch (e) { res.status(500).json({ error: e.message || '翻译失败' }); }
|
||||
});
|
||||
|
||||
// ---------- AI ----------
|
||||
const CONVO_CH_ZH = { email: '邮件', whatsapp: 'WhatsApp', wechat: '微信', phone: '电话', meeting: '会议 / 面谈', other: '其他' };
|
||||
function convoContext(customer, items, budget) {
|
||||
const sorted = [...items].sort((a, b) => String(a.date).localeCompare(String(b.date)) || a.createdAt - b.createdAt);
|
||||
function convoContext(customer, items, budget, names = {}) {
|
||||
const sorted = items.map(normMsg).sort((a, b) => String(a.at).localeCompare(String(b.at)) || a.createdAt - b.createdAt);
|
||||
const cust = names.customer || '客户', me = names.me || '我们';
|
||||
const fmt = (m) => {
|
||||
if (m.from === 'note') return `### [${CONVO_CH_ZH[m.channel] || m.channel}] ${m.date || m.at.slice(0, 10)}${m.title ? ` · ${m.title}` : ''}\n${m.text || ''}`;
|
||||
const who = m.from === 'me' ? `${me}(我们)` : `${m.who && !sameName(m.who, cust) ? m.who : cust}(客户)`;
|
||||
const att = (m.files || []).length ? `\n[附件:${m.files.map((f) => f.name).join('、')}]` : '';
|
||||
const ft = m.fileText ? `\n[附件内容摘录]\n${String(m.fileText).slice(0, 4000)}` : '';
|
||||
return `[${m.at} ${CONVO_CH_ZH[m.channel] || m.channel}] ${who}:${m.text || ''}${att}${ft}`;
|
||||
};
|
||||
const picked = []; let used = 0, skipped = 0;
|
||||
for (let i = sorted.length - 1; i >= 0; i--) {
|
||||
const it = sorted[i];
|
||||
const head = `### [${CONVO_CH_ZH[it.channel] || it.channel}] ${it.date}${it.title ? ` · ${it.title}` : ''}`;
|
||||
let body = String(it.text || '');
|
||||
const room = budget - used - head.length - 10;
|
||||
if (room < 400) { skipped = i + 1; break; }
|
||||
if (body.length > room) body = '……(前面省略)\n' + body.slice(body.length - room);
|
||||
picked.unshift(`${head}\n${body}`); used += head.length + body.length + 2;
|
||||
let s = fmt(sorted[i]);
|
||||
const room = budget - used - 4;
|
||||
if (room < 300) { skipped = i + 1; break; }
|
||||
if (s.length > room) s = s.slice(0, room) + '……';
|
||||
picked.unshift(s); used += s.length + 1;
|
||||
}
|
||||
const c = customer || {};
|
||||
const profile = [
|
||||
|
|
@ -1516,11 +1677,11 @@ function convoContext(customer, items, budget) {
|
|||
c.website && `网站:${c.website}`, c.intendedModel && `意向型号:${c.intendedModel}`, c.intendedQty && `意向数量:${c.intendedQty}`,
|
||||
c.hasOrdered ? '已经下过单' : '', c.isVip ? 'VIP 客户' : '', c.source && `来源:${c.source}`, c.notes && `备注:${String(c.notes).slice(0, 800)}`,
|
||||
].filter(Boolean).join('\n');
|
||||
return { text: picked.join('\n\n'), skipped, profile, count: items.length };
|
||||
return { text: picked.join('\n'), skipped, profile, count: items.length };
|
||||
}
|
||||
const OUR_BUSINESS = '我们是 SKE Power(山克),中国东莞的 UPS 工厂:生产 Mini DC UPS、后备式 / 在线式 / 机架式 / 模块化 / 工频 UPS,还有光伏逆变器、储能电池(锂电、铅酸)、电池柜、精密空调、微模块数据中心等,主要做出口(非洲、中东、独联体、东南亚、欧洲、拉美)。';
|
||||
const CONVO_ANALYZE_PROMPT = `${OUR_BUSINESS}
|
||||
你是我们的外贸销售助理。下面是我们和一个客户的全部沟通记录(邮件、WhatsApp 等,按时间先后),以及客户档案。
|
||||
你是我们的外贸销售助理。下面是我们和一个客户的全部沟通记录(WhatsApp、微信、邮件等,按时间先后,每行是一条消息,标明了是客户说的还是我们说的),以及客户档案。
|
||||
请认真读完,站在销售的角度分析,只根据记录里真实出现的内容,不要编造;记录里没有的信息就写空字符串或空数组。
|
||||
用中文输出(跟进消息草稿除外),严格只输出一个 JSON 对象,不要任何解释:
|
||||
{
|
||||
|
|
@ -1550,7 +1711,7 @@ app.post('/api/convos/:cid/analyze', requireAuth, aiLimiter, (req, res) => {
|
|||
const all = readConvos(); const c = all[cid];
|
||||
if (!c || !c.items.length) return res.status(400).json({ error: '这个客户还没有沟通记录' });
|
||||
const customer = (() => { try { const d = readData(); const raw = d['crm:customers']; const list = typeof raw === 'string' ? JSON.parse(raw) : raw; return (Array.isArray(list) ? list : []).find((x) => x.id === cid) || {}; } catch (e) { return {}; } })();
|
||||
const ctx = convoContext(customer, c.items, CONVO_AI_BUDGET);
|
||||
const ctx = convoContext(customer, c.items, CONVO_AI_BUDGET, { customer: String(customer.contact || customer.company || '').replace(/\s*[((].*$/, '').trim(), me: 'Mike' });
|
||||
const { id, fakeRes } = createAiJob();
|
||||
res.json({ jobId: id });
|
||||
(async () => {
|
||||
|
|
@ -1580,7 +1741,7 @@ app.post('/api/convos/:cid/ask', requireAuth, aiLimiter, async (req, res) => {
|
|||
if (!cfg.apiKey && !cfg.backup.apiKey) return res.status(400).json({ error: '还没有配置 AI(设置 → AI 接口)' });
|
||||
const c = readConvos()[cid];
|
||||
if (!c || !c.items.length) return res.status(400).json({ error: '这个客户还没有沟通记录' });
|
||||
const ctx = convoContext({}, c.items, CONVO_AI_BUDGET);
|
||||
const ctx = convoContext({}, c.items, CONVO_AI_BUDGET, { me: 'Mike' });
|
||||
try {
|
||||
const answer = await callDeepSeekWithRetry(cfg.apiKey, [
|
||||
{ role: 'system', content: `${OUR_BUSINESS}\n下面是我们和一个客户的沟通记录。只根据记录回答问题,用中文,简洁;记录里找不到就直接说"记录里没有提到"。引用具体内容时注明日期。` },
|
||||
|
|
|
|||
Loading…
Reference in New Issue