diff --git a/server.js b/server.js
index 69cbdc4..95168d0 100644
--- a/server.js
+++ b/server.js
@@ -1218,6 +1218,378 @@ app.delete('/api/uploads/:customerId/:fileName', requireAuth, (req, res) => {
});
const mountPublicApi = require('./public-api');
+/* ------------------------- 客户沟通记录 + AI 分析 ------------------------- */
+// 每个客户可以记录和我们的沟通:邮件、WhatsApp、微信、电话、会议……
+// 录入方式:直接粘贴文字,或者上传文件——WhatsApp 导出的聊天(.txt / .zip)、邮件(.eml)、截图(OCR 识别文字)、
+// PDF、Word(.docx)、网页(.html)、纯文本。文件原件存在 uploads/<客户id>/ 下(conv_ 开头),识别出的文字存进记录。
+// 记录单独存在 conversations.json(不放进客户列表,免得每次保存客户都带上大段聊天),有自动备份。
+// AI 分析:把这个客户的全部沟通(新的优先,总长度有上限)交给 AI,输出总结、阶段、意向、需求、顾虑、下一步、跟进消息草稿。
+const zlib = require('zlib');
+const CONVO_FILE = path.join(__dirname, 'conversations.json');
+const CONVO_CHANNELS = ['email', 'whatsapp', 'wechat', 'phone', 'meeting', 'other'];
+const CONVO_TEXT_MAX = 300000; // 每条记录最多保存的文字
+const CONVO_AI_BUDGET = 48000; // 交给 AI 的沟通文字总长度上限(新的优先)
+let convoCache = null, convoBackupAt = 0;
+
+function readConvos() {
+ if (convoCache) return convoCache;
+ try { convoCache = JSON.parse(fs.readFileSync(CONVO_FILE, 'utf8')) || {}; } catch (e) { convoCache = {}; }
+ return convoCache;
+}
+function writeConvos(all) {
+ convoCache = all;
+ try {
+ if (fs.existsSync(CONVO_FILE) && Date.now() - convoBackupAt > 3600 * 1000) {
+ fs.mkdirSync(BACKUP_DIR, { recursive: true });
+ const ts = new Date().toISOString().replace(/[:T]/g, '-').slice(0, 19);
+ fs.copyFileSync(CONVO_FILE, path.join(BACKUP_DIR, `conversations-${ts}.json`));
+ convoBackupAt = Date.now();
+ const files = fs.readdirSync(BACKUP_DIR).filter((f) => /^conversations-.*\.json$/.test(f)).sort();
+ for (const f of files.slice(0, Math.max(0, files.length - 72))) fs.unlinkSync(path.join(BACKUP_DIR, f));
+ }
+ } catch (e) { console.warn('[沟通记录] 备份失败:', e.message); }
+ const tmp = CONVO_FILE + '.tmp';
+ fs.writeFileSync(tmp, JSON.stringify(all), 'utf8');
+ fs.renameSync(tmp, CONVO_FILE);
+}
+const convoOf = (all, cid) => all[cid] || (all[cid] = { items: [], analysis: null });
+
+// ---------- 文件解析 ----------
+// 不依赖额外的 npm 包:ZIP(WhatsApp 导出、.docx)用 Node 自带的 zlib 解压
+function unzipEntries(buf) {
+ const out = [];
+ let eocd = -1;
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 70000); i--) if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
+ if (eocd < 0) throw new Error('不是有效的 ZIP 文件');
+ const count = buf.readUInt16LE(eocd + 10);
+ let p = buf.readUInt32LE(eocd + 16);
+ for (let n = 0; n < count && p + 46 <= buf.length; n++) {
+ if (buf.readUInt32LE(p) !== 0x02014b50) break;
+ const method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), nlen = buf.readUInt16LE(p + 28);
+ const elen = buf.readUInt16LE(p + 30), clen = buf.readUInt16LE(p + 32), lho = buf.readUInt32LE(p + 42);
+ const name = buf.slice(p + 46, p + 46 + nlen).toString('utf8');
+ p += 46 + nlen + elen + clen;
+ out.push({ name, read: () => {
+ const ln = buf.readUInt16LE(lho + 26), le = buf.readUInt16LE(lho + 28);
+ const data = buf.slice(lho + 30 + ln + le, lho + 30 + ln + le + csize);
+ return method === 0 ? data : method === 8 ? zlib.inflateRawSync(data) : null;
+ } });
+ }
+ return out;
+}
+const decodeText = (buf, charset) => {
+ const cs = String(charset || 'utf-8').toLowerCase().replace(/^(x-)?(gb2312|gb_2312.*)$/, 'gbk');
+ try { return new TextDecoder(cs).decode(buf); } catch (e) { return buf.toString('utf8'); }
+};
+const stripHtml = (h) => String(h || '')
+ .replace(/<(script|style|head)[\s\S]*?<\/\1>/gi, ' ')
+ .replace(/
|<\/(p|div|tr|li|h\d)>/gi, '\n')
+ .replace(/<[^>]+>/g, ' ')
+ .replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'")
+ .replace(/[ \t]+/g, ' ').replace(/\n\s*\n\s*\n+/g, '\n\n').trim();
+
+// WhatsApp 导出:每条消息一行开头是日期时间 + 发送人,如
+// [12/03/2026, 14:05:33] Ahmed: Hello (iPhone)
+// 12/03/2026, 14:05 - Ahmed: Hello (安卓)
+const WA_LINE = /^?\[?(\d{1,4}[./-]\d{1,2}[./-]\d{2,4}),?\s+(\d{1,2}:\d{2}(?::\d{2})?(?:\s?[APap]\.?\s?[Mm]\.?)?)\]?\s*(?:-\s*)?([^:\n]{1,60}):\s/;
+function parseWhatsApp(text) {
+ const t = String(text || '').replace(/[-]/g, '').replace(/\r\n/g, '\n');
+ const lines = t.split('\n');
+ let msgs = 0, first = '', last = '';
+ const people = new Map();
+ for (const l of lines) {
+ const m = l.match(WA_LINE);
+ if (!m) continue;
+ msgs++; if (!first) first = m[1]; last = m[1];
+ const who = m[3].trim(); people.set(who, (people.get(who) || 0) + 1);
+ }
+ if (msgs < 2) return null;
+ return { text: t.trim(), stats: { messages: msgs, people: [...people.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6).map(([n, c]) => ({ n, c })), from: first, to: last } };
+}
+
+// 邮件 .eml:解析头(发件人、收件人、日期、主题)+ 正文(优先纯文本,没有就用 HTML 去标签),支持 base64 / quoted-printable / GBK
+function decodeWords(s) {
+ return String(s || '').replace(/=\?([^?]+)\?([bqBQ])\?([^?]*)\?=/g, (m, cs, enc, data) => {
+ try {
+ const buf = /b/i.test(enc) ? Buffer.from(data, 'base64') : Buffer.from(data.replace(/_/g, ' ').replace(/=([0-9A-F]{2})/gi, (x, h) => String.fromCharCode(parseInt(h, 16))), 'latin1');
+ return decodeText(buf, cs);
+ } catch (e) { return m; }
+ }).replace(/\?=\s+=\?/g, '?==?');
+}
+function splitMime(raw) {
+ const i = raw.search(/\r?\n\r?\n/);
+ const head = i < 0 ? raw : raw.slice(0, i), body = i < 0 ? '' : raw.slice(i).replace(/^\r?\n\r?\n/, '');
+ const headers = {};
+ for (const line of head.replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) {
+ const k = line.indexOf(':'); if (k > 0) headers[line.slice(0, k).trim().toLowerCase()] = line.slice(k + 1).trim();
+ }
+ return { headers, body };
+}
+function mimeBody(part) {
+ const ct = part.headers['content-type'] || 'text/plain';
+ const cte = (part.headers['content-transfer-encoding'] || '').toLowerCase();
+ const cs = (ct.match(/charset="?([^";\s]+)/i) || [])[1];
+ if (/^multipart\//i.test(ct)) {
+ const b = (ct.match(/boundary="?([^";]+)"?/i) || [])[1];
+ if (!b) return { plain: '', html: '' };
+ const parts = part.body.split('--' + b).slice(1).filter((x) => !/^--/.test(x)).map((x) => splitMime(x.replace(/^\r?\n/, '')));
+ let plain = '', html = '';
+ for (const p of parts) { const r = mimeBody(p); if (!plain && r.plain) plain = r.plain; if (!html && r.html) html = r.html; }
+ return { plain, html };
+ }
+ if (/attachment/i.test(part.headers['content-disposition'] || '')) return { plain: '', html: '' };
+ let buf;
+ if (cte === 'base64') buf = Buffer.from(part.body.replace(/\s+/g, ''), 'base64');
+ else if (cte === 'quoted-printable') buf = Buffer.from(part.body.replace(/=\r?\n/g, '').replace(/=([0-9A-F]{2})/gi, (x, h) => String.fromCharCode(parseInt(h, 16))), 'latin1');
+ else buf = Buffer.from(part.body, 'latin1');
+ const txt = decodeText(buf, cs);
+ if (/text\/html/i.test(ct)) return { plain: '', html: txt };
+ if (/text\/plain/i.test(ct)) return { plain: txt, html: '' };
+ return { plain: '', html: '' };
+}
+function parseEml(buf) {
+ const msg = splitMime(buf.toString('latin1'));
+ const h = (k) => decodeWords(msg.headers[k] || '');
+ const { plain, html } = mimeBody(msg);
+ const body = (plain || stripHtml(html)).replace(/\r\n/g, '\n').trim();
+ const head = [['From', h('from')], ['To', h('to')], ['Cc', h('cc')], ['Date', h('date')], ['Subject', h('subject')]].filter((x) => x[1]).map(([k, v]) => `${k}: ${v}`).join('\n');
+ const d = Date.parse(h('date'));
+ return { text: `${head}\n\n${body}`.trim(), subject: h('subject'), date: isNaN(d) ? '' : new Date(d).toISOString().slice(0, 10) };
+}
+
+async function extractConvoFile(f) {
+ const name = f.originalname || 'file', ext = path.extname(name).toLowerCase();
+ if (ext === '.eml') { const r = parseEml(f.buffer); return { kind: 'email', ...r }; }
+ 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(`${name}:压缩包里没有找到聊天记录 .txt`);
+ const t = decodeText(txt.read());
+ const wa = parseWhatsApp(t);
+ const media = entries.filter((e) => /\.(jpe?g|png|webp|mp4|opus|pdf|docx?)$/i.test(e.name)).length;
+ return wa ? { kind: 'whatsapp', text: wa.text, stats: { ...wa.stats, media } } : { kind: 'text', text: t };
+ }
+ if (ext === '.docx') {
+ const doc = unzipEntries(f.buffer).find((e) => e.name === 'word/document.xml');
+ if (!doc) throw new Error(`${name}:读不到 Word 内容`);
+ return { kind: 'text', text: stripHtml(doc.read().toString('utf8').replace(/<\/w:p>/g, '\n').replace(//g, '\t')) };
+ }
+ if (ext === '.html' || ext === '.htm') return { kind: 'text', text: stripHtml(decodeText(f.buffer)) };
+ if (ext === '.pdf') {
+ fs.mkdirSync(OCR_TMP_ROOT, { recursive: true });
+ const tmp = fs.mkdtempSync(path.join(OCR_TMP_ROOT, 'conv-'));
+ try {
+ let t = await pdfTextLayer(f.buffer, tmp);
+ if (!t) t = await ocrImages((await renderPdfToImages(f.buffer, tmp)).slice(0, 15));
+ return { kind: 'text', text: t, ocr: !t };
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
+ }
+ if (/^image\//.test(f.mimetype) || /\.(jpe?g|png|webp|bmp|gif)$/i.test(ext)) {
+ fs.mkdirSync(OCR_TMP_ROOT, { recursive: true });
+ const tmp = fs.mkdtempSync(path.join(OCR_TMP_ROOT, 'conv-'));
+ try {
+ const p = path.join(tmp, 'img' + (ext || '.png'));
+ fs.writeFileSync(p, f.buffer);
+ return { kind: 'image', text: await ocrImages([p]), ocr: true };
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
+ }
+ if (/^text\//.test(f.mimetype) || /\.(txt|csv|md|json|log)$/i.test(ext)) {
+ const t = decodeText(f.buffer);
+ const wa = parseWhatsApp(t);
+ return wa ? { kind: 'whatsapp', text: wa.text, stats: wa.stats } : { kind: 'text', text: t };
+ }
+ throw new Error(`${name}:不支持这种文件(支持 WhatsApp 导出 .txt/.zip、邮件 .eml、截图、PDF、Word .docx、网页、文本)`);
+}
+
+const convoUpload = multer({ storage: multer.memoryStorage(), limits: { files: 10, fileSize: 30 * 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('�') ? n : u; };
+const clipTxt = (v, n) => String(v == null ? '' : v).replace(/\r\n/g, '\n').slice(0, n);
+
+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);
+});
+
+// 新增一条:粘贴的文字 + 上传的文件(每个文件识别出的文字依次拼在后面)
+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: '请粘贴沟通内容或上传文件' });
+ 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 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 });
+ }
+ });
+});
+
+app.put('/api/convos/:cid/:id', requireAuth, (req, res) => {
+ const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
+ const all = readConvos(); const c = all[cid];
+ 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;
+ it.updatedAt = Date.now();
+ writeConvos(all);
+ res.json({ ok: true, item: it });
+});
+
+app.delete('/api/convos/:cid/:id', requireAuth, (req, res) => {
+ const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
+ const all = readConvos(); const c = all[cid];
+ const it = c && c.items.find((x) => x.id === req.params.id);
+ if (!it) return res.status(404).json({ error: 'not found' });
+ c.items = c.items.filter((x) => x !== it);
+ for (const f of it.files || []) fs.unlink(path.join(UPLOADS_DIR, cid, path.basename(f.stored)), () => {});
+ writeConvos(all);
+ res.json({ ok: true });
+});
+
+// 删除客户时一起删
+app.delete('/api/convos/:cid', requireAuth, (req, res) => {
+ const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
+ const all = readConvos(); const c = all[cid];
+ if (c) { for (const it of c.items) for (const f of it.files || []) fs.unlink(path.join(UPLOADS_DIR, cid, path.basename(f.stored)), () => {}); delete all[cid]; writeConvos(all); }
+ res.json({ ok: true });
+});
+
+// ---------- 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);
+ 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;
+ }
+ const c = customer || {};
+ const profile = [
+ c.company && `公司:${c.company}`, c.contact && `联系人:${c.contact}`, c.country && `国家:${c.country}`,
+ 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 };
+}
+const OUR_BUSINESS = '我们是 SKE Power(山克),中国东莞的 UPS 工厂:生产 Mini DC UPS、后备式 / 在线式 / 机架式 / 模块化 / 工频 UPS,还有光伏逆变器、储能电池(锂电、铅酸)、电池柜、精密空调、微模块数据中心等,主要做出口(非洲、中东、独联体、东南亚、欧洲、拉美)。';
+const CONVO_ANALYZE_PROMPT = `${OUR_BUSINESS}
+你是我们的外贸销售助理。下面是我们和一个客户的全部沟通记录(邮件、WhatsApp 等,按时间先后),以及客户档案。
+请认真读完,站在销售的角度分析,只根据记录里真实出现的内容,不要编造;记录里没有的信息就写空字符串或空数组。
+用中文输出(跟进消息草稿除外),严格只输出一个 JSON 对象,不要任何解释:
+{
+ "summary": "3~6 句话总结:客户是谁、要什么、谈到哪一步、现在卡在哪里",
+ "stage": "从这些里选一个:初次询盘 / 需求沟通 / 报价中 / 样品或测试 / 谈判中 / 已下单 / 售后 / 停滞",
+ "intent": "高 / 中 / 低",
+ "intentReason": "一句话说明为什么这么判断",
+ "needs": ["客户的具体需求,每条一句:用途、负载、后备时间、电压、认证、包装、交期等"],
+ "products": [{"model": "型号或产品类型", "qty": "数量", "notes": "规格 / 配置 / 价格等补充"}],
+ "price": "报价、目标价、付款方式、贸易术语等(原样写数字和币种)",
+ "timeline": "客户的时间要求:什么时候要货、项目时间",
+ "decision": "决策人、采购流程、终端用户等",
+ "competitors": "提到的竞争对手或对比品牌",
+ "concerns": ["客户的顾虑 / 异议 / 不满意的地方"],
+ "promises": ["我们答应了但记录里还看不到完成的事(比如答应发报价、样品、资料)"],
+ "risks": ["丢单风险或需要注意的地方"],
+ "nextActions": [{"action": "具体要做的下一步", "priority": "高 / 中 / 低", "when": "建议什么时候做"}],
+ "customerLanguage": "客户沟通用的语言,如 English / Español / Русский / العربية / 中文",
+ "followUp": {"channel": "email 或 whatsapp(按客户最常用的)", "subject": "邮件主题(WhatsApp 就留空)", "message": "用客户的语言写一条跟进消息,口吻专业友好,结合上面最重要的下一步;不要编造价格、交期等具体数字,需要数字的地方用 [ ] 留空让我填"},
+ "tags": ["2~5 个简短标签,如 模块化UPS、价格敏感、项目单、经销商"]
+}`;
+
+app.post('/api/convos/:cid/analyze', requireAuth, aiLimiter, (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 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 { id, fakeRes } = createAiJob();
+ res.json({ jobId: id });
+ (async () => {
+ try {
+ const content = await callDeepSeekWithRetry(cfg.apiKey, [
+ { role: 'system', content: CONVO_ANALYZE_PROMPT },
+ { role: 'user', content: `【客户档案】\n${ctx.profile || '(空)'}\n\n【沟通记录,共 ${ctx.count} 条${ctx.skipped ? `,最早的 ${ctx.skipped} 条因为太长没有放进来` : ''}】\n\n${ctx.text}` },
+ ], { maxTokens: 4000, temperature: 0.3, timeoutMs: 240000 });
+ const { data } = extractJson(content);
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('AI 返回的格式不对,请重试');
+ const fresh = readConvos(); const fc = convoOf(fresh, cid);
+ fc.analysis = { at: Date.now(), count: c.items.length, skipped: ctx.skipped, result: data };
+ writeConvos(fresh);
+ fakeRes.json({ ok: true, analysis: fc.analysis });
+ } catch (e) {
+ fakeRes.status(500).json({ error: e.message || 'AI 分析失败' });
+ }
+ })();
+});
+
+// 针对这个客户的沟通随便问一句(比如"他上次要的是多少台?""我们报过什么价?")
+app.post('/api/convos/:cid/ask', requireAuth, aiLimiter, async (req, res) => {
+ const cid = safeId(req.params.cid); if (!cid) return res.status(400).json({ error: 'bad id' });
+ const q = clipTxt((req.body || {}).question, 1000).trim();
+ if (!q) return res.status(400).json({ error: '请输入问题' });
+ const cfg = loadAiConfig();
+ 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);
+ try {
+ const answer = await callDeepSeekWithRetry(cfg.apiKey, [
+ { role: 'system', content: `${OUR_BUSINESS}\n下面是我们和一个客户的沟通记录。只根据记录回答问题,用中文,简洁;记录里找不到就直接说"记录里没有提到"。引用具体内容时注明日期。` },
+ { role: 'user', content: `【沟通记录】\n${ctx.text}\n\n【问题】${q}` },
+ ], { maxTokens: 1200, temperature: 0.2, timeoutMs: 120000 });
+ res.json({ answer: String(answer || '').trim() });
+ } catch (e) { res.status(500).json({ error: e.message }); }
+});
+
const publicApi = mountPublicApi(app, { dataFile: DATA_FILE, uploadsDir: UPLOADS_DIR, requireAuth, writeData, ai: { loadAiConfig, callDeepSeekWithRetry, extractJson } });
if (publicApi && publicApi.scheduleTemplateSync) onTemplatesChanged = publicApi.scheduleTemplateSync;