diff --git a/server.js b/server.js index a97e571..a38c984 100644 --- a/server.js +++ b/server.js @@ -1825,6 +1825,121 @@ app.post('/api/convos/:cid/ask', requireAuth, aiLimiter, async (req, res) => { } catch (e) { res.status(500).json({ error: e.message }); } }); + +// ---------- AI 匹配产品:按客户需求从产品库里挑合适 / 接近的型号 ---------- +// 两步:① 只把型号目录(型号、品类、功率等一行一个)给 AI,挑出候选;② 把候选的完整参数给 AI,逐项对比需求,给出匹配度和差距 +const MATCH_SKIP_KEY = /(^id$|Id$|image|img|photo|picture|video|file|pdf|html|detail|template|cost|price|note|supplier|createdAt|updatedAt|publish|slug|seo|web|gallery|sort|hidden|hideBrand|_)/i; +function productList() { + try { const raw = readData()['crm:products']; const list = typeof raw === 'string' ? JSON.parse(raw) : raw; return Array.isArray(list) ? list.filter((p) => p && p.name) : []; } catch (e) { return []; } +} +const pPower = (p) => [p.ratedPower ? `${p.ratedPower}${p.ratedPowerUnit || ''}` : '', p.powerOrCapacity, p.moduleCapacity ? `${p.moduleCapacity}Ah` : '', p.moduleMaxEnergy ? `${p.moduleMaxEnergy}kWh` : '', p.voltage || p.moduleVoltage || p.batteryVoltage].filter(Boolean).join(' / '); +const pIndexLine = (p) => [p.name, (p.extraNames || []).filter(Boolean).join('/'), p.brand, p.category, [p.type, ...(p.extraTypes || [])].filter(Boolean).join('/'), p.machineVariant, pPower(p)].map((x) => String(x || '').replace(/\s+/g, ' ').trim()).filter(Boolean).join(' | '); +function pFullSpec(p) { + const out = []; + for (const [k, v] of Object.entries(p)) { + if (MATCH_SKIP_KEY.test(k) && !/^sellingPoints$/.test(k)) continue; + let t; + if (typeof v === 'string' || typeof v === 'number') t = String(v).trim(); + else if (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string')) t = v.join(', '); + else if (Array.isArray(v) && v.length && v.every((x) => x && typeof x === 'object' && !Array.isArray(x))) t = v.map((x) => Object.values(x).filter((y) => typeof y === 'string' && y).join(' ')).join('; '); + else continue; + if (!t) continue; + out.push(`${k}: ${t.replace(/\s*\n\s*/g, ';').slice(0, 400)}`); + } + return out.join('\n').slice(0, 3500); +} +const MATCH_PICK_PROMPT = `${OUR_BUSINESS} +你是我们的售前工程师。下面是客户的需求,以及我们产品库的型号目录(每行:型号 | 别名 | 品牌 | 大类 | 细分品类 | 标机/长机 | 功率容量电压)。 +请挑出所有可能满足或接近客户需求的型号作为候选(每项需求最多 6 个,总共最多 24 个),宁多勿漏,相近功率段、同系列的也可以带上;完全不相关的不要。 +型号必须原样照抄目录里的,不能编造。严格只输出 JSON:{"candidates": ["型号1", "型号2"]}`; +const MATCH_PROMPT = `${OUR_BUSINESS} +你是我们的售前工程师。下面是客户的需求(来自沟通记录和 AI 分析),以及我们产品库里候选型号的完整参数(字段名是英文,值是我们录入的参数)。 +请逐项对照客户需求,从候选里为每一项需求选出最合适的 1~3 个型号,判断符合程度,并指出不满足或需要跟客户确认的地方。 +规则: +- 型号只能用候选里出现的,原样照抄,不能编造型号或参数。 +- 参数里没有写的不要假设"满足",要放进 gaps 里写"产品库未录入 xx,需确认"。 +- 后备时间、电池数量等需要配置的,在 config 里给出建议配置思路(如"外置电池包 ×2"),没有依据的数字不要编。 +- 候选里实在没有合适的,matches 为空数组,在 noMatch 说明原因和建议(比如需要定制、或推荐相近的品类)。 +用中文,严格只输出一个 JSON 对象: +{ + "summary": "2~4 句话:整体能不能满足、推荐方案的思路", + "groups": [ + {"need": "客户这一项需求(如 LOT 1:55 套带外置电池包的塔式在线式 UPS)", "qty": "数量", + "matches": [{"model": "型号", "fit": "符合 / 基本符合 / 接近", "reason": "为什么选它,对应了哪些要求", "gaps": ["不满足或需确认的地方"], "config": "建议配置,可空"}], + "noMatch": "没有合适型号时的说明,可空"} + ], + "questions": ["为了确定选型,还需要问客户的问题"] +}`; +function needsText(c, customer) { + const a = c.analysis && c.analysis.result; + const parts = []; + if (a) { + if (a.summary) parts.push(`【AI 分析摘要】${a.summary}`); + if (Array.isArray(a.needs) && a.needs.length) parts.push(`【客户需求】\n- ${a.needs.join('\n- ')}`); + if (Array.isArray(a.products) && a.products.length) parts.push(`【意向产品】\n${a.products.map((p) => `- ${p.model || ''} × ${p.qty || '?'}:${p.notes || ''}`).join('\n')}`); + } + const ctx = convoContext(customer, c.items, a ? 20000 : 40000, { customer: String(customer.contact || customer.company || '').replace(/\s*[((].*$/, '').trim(), me: 'Mike' }); + if (ctx.profile) parts.push(`【客户档案】\n${ctx.profile}`); + parts.push(`【沟通记录(${ctx.skipped ? '较早的部分省略了' : '全部'})】\n${ctx.text}`); + return parts.join('\n\n'); +} +app.post('/api/convos/:cid/match', 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 c = readConvos()[cid]; + if (!c || !c.items.length) return res.status(400).json({ error: '这个客户还没有沟通记录' }); + const products = productList(); + if (!products.length) return res.status(400).json({ error: '产品库是空的' }); + const customer = (() => { try { const raw = readData()['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 { id, fakeRes } = createAiJob(); + res.json({ jobId: id }); + (async () => { + try { + const need = needsText(c, customer); + const norm = (s) => String(s || '').toLowerCase().replace(/\s+/g, ''); + const byName = new Map(); + for (const p of products) for (const n of [p.name, ...(p.extraNames || [])]) if (n && !byName.has(norm(n))) byName.set(norm(n), p); + // ① 挑候选(产品少就直接全部给) + let cands = products; + if (products.length > 30) { + const idx = products.map(pIndexLine).join('\n'); + const r1 = await callDeepSeekWithRetry(cfg.apiKey, [ + { role: 'system', content: MATCH_PICK_PROMPT }, + { role: 'user', content: `${need}\n\n【产品库型号目录,共 ${products.length} 个】\n${idx}` }, + ], { maxTokens: 1500, temperature: 0.1, timeoutMs: 180000 }); + const { data } = extractJson(r1); + const names = data && Array.isArray(data.candidates) ? data.candidates : []; + const seen = new Set(); cands = []; + for (const n of names) { const p = byName.get(norm(n)); if (p && !seen.has(p.id)) { seen.add(p.id); cands.push(p); } } + if (!cands.length) throw new Error('产品库里没找到和需求相关的型号'); + cands = cands.slice(0, 24); + } + // ② 逐项对比 + const specs = cands.map((p) => `### ${p.name}\n${pFullSpec(p)}`).join('\n\n'); + const r2 = await callDeepSeekWithRetry(cfg.apiKey, [ + { role: 'system', content: MATCH_PROMPT }, + { role: 'user', content: `${need}\n\n【候选型号完整参数,共 ${cands.length} 个】\n\n${specs}` }, + ], { maxTokens: 5000, temperature: 0.2, timeoutMs: 240000 }); + const { data } = extractJson(r2); + if (!data || typeof data !== 'object' || !Array.isArray(data.groups)) throw new Error('AI 返回的格式不对,请重试'); + // 只保留产品库里真实存在的型号,并带上产品信息 + for (const g of data.groups) { + g.matches = (Array.isArray(g.matches) ? g.matches : []).map((m) => { + const p = byName.get(norm(m.model)); + return p ? { ...m, model: p.name, productId: p.id, category: p.category || '', type: p.type || '', power: pPower(p) } : null; + }).filter(Boolean); + } + const fresh = readConvos(); const fc = convoOf(fresh, cid); + fc.match = { at: Date.now(), count: c.items.length, candidates: cands.length, total: products.length, result: data }; + writeConvos(fresh); + fakeRes.json({ ok: true, match: fc.match }); + } catch (e) { + fakeRes.status(500).json({ error: e.message || 'AI 匹配失败' }); + } + })(); +}); + const publicApi = mountPublicApi(app, { dataFile: DATA_FILE, uploadsDir: UPLOADS_DIR, requireAuth, writeData, ai: { loadAiConfig, callDeepSeekWithRetry, extractJson } }); if (publicApi && publicApi.scheduleTemplateSync) onTemplatesChanged = publicApi.scheduleTemplateSync;