Update App.jsx via upload script - 2026-11-07 00:20:35

This commit is contained in:
mike 2026-11-07 00:20:48 +08:00
parent 3b2878f08d
commit c3d78f7a1e
1 changed files with 412 additions and 2 deletions

414
App.jsx
View File

@ -5,7 +5,7 @@ import {
Building2, Globe, Phone, Save, RefreshCw, LayoutDashboard, Users, Building2, Globe, Phone, Save, RefreshCw, LayoutDashboard, Users,
Package, Layers, Zap, Tag, Inbox, Paperclip, Package, Layers, Zap, Tag, Inbox, Paperclip,
Menu, LogOut, GripVertical, BookOpen, FileText, FolderTree, Lock, Sparkles, Printer, Image as ImageIcon, Menu, LogOut, GripVertical, BookOpen, FileText, FolderTree, Lock, Sparkles, Printer, Image as ImageIcon,
ShieldCheck, Settings2, Boxes, Download, Wifi, Radio, QrCode, Folder, FolderPlus, Factory, UploadCloud, ClipboardList ShieldCheck, Settings2, Boxes, Download, Wifi, Radio, QrCode, Folder, FolderPlus, Factory, UploadCloud, ClipboardList, MessageCircle
} from 'lucide-react'; } from 'lucide-react';
import { MicUploadPage } from './mic-upload/MicUploadPage'; import { MicUploadPage } from './mic-upload/MicUploadPage';
import { ImageToolPage } from './mic-upload/ImageToolPage'; import { ImageToolPage } from './mic-upload/ImageToolPage';
@ -2374,6 +2374,7 @@ const NAV_GROUPS = [
{ id: 'monitor', label: '客户档案', icon: LayoutDashboard }, { id: 'monitor', label: '客户档案', icon: LayoutDashboard },
{ id: 'manage', label: '客户管理', icon: Users }, { id: 'manage', label: '客户管理', icon: Users },
{ id: 'orders', label: '订单管理', icon: ClipboardList }, { id: 'orders', label: '订单管理', icon: ClipboardList },
{ id: 'chat', label: '在线客服', icon: MessageCircle },
{ id: 'jms', label: 'Just My Socks', icon: Wifi }, { id: 'jms', label: 'Just My Socks', icon: Wifi },
] }, ] },
{ label: '产品', items: [ { label: '产品', items: [
@ -2502,7 +2503,9 @@ function MainApp({ username, onLogout }) {
}, []); }, []);
const [customers, setCustomers] = useState([]); const [customers, setCustomers] = useState([]);
const [products, setProducts] = useState([]); const [products, setProducts] = useState([]);
const [view, setView] = useState('monitor'); // 推送消息里的链接 /?chat=对话id → 直接打开在线客服的这个对话
const chatLinkSid = useMemo(() => { try { return new URLSearchParams(window.location.search).get('chat') || null; } catch (e) { return null; } }, []);
const [view, setView] = useState(chatLinkSid ? 'chat' : 'monitor');
const [mobileMenuOpen, setMobileMenuOpen] = useState(false); const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
const [selectedId, setSelectedId] = useState(null); const [selectedId, setSelectedId] = useState(null);
@ -4201,6 +4204,18 @@ function MainApp({ username, onLogout }) {
<TemplateCenter templates={webDetailTemplates} setTemplates={setWebDetailTemplates} <TemplateCenter templates={webDetailTemplates} setTemplates={setWebDetailTemplates}
products={products} setProducts={setProducts} onNotify={notify} savedTick={tplSavedTick} /> products={products} setProducts={setProducts} onNotify={notify} savedTick={tplSavedTick} />
)} )}
{view === 'chat' && (
<ChatCenter onNotify={notify} initialSid={chatLinkSid}
onSaveCustomer={(conv) => {
const l = conv.lead || {};
const c = { ...blankCustomer(), company: l.company || '', contact: l.name || '', country: l.country || conv.ipCountry || '', email: l.email || '', phone: l.whatsapp || '',
intendedModel: (l.products || []).join(', '), intendedQty: l.quantity || '', source: '网站在线客服', notes: [l.summary_zh, `对话:${conv.sid}`].filter(Boolean).join('\n') };
setCustomers(prev => [...prev, c]);
setView('manage'); setDraft(null); setSelectedId(c.id);
notify('已存为客户档案,可以继续补充');
}} />
)}
{view === 'website' && ( {view === 'website' && (
<WebsiteManager <WebsiteManager
assets={webAssets} setAssets={setWebAssets} assets={webAssets} setAssets={setWebAssets}
@ -9728,3 +9743,398 @@ function Info({ icon, label, value }) {
</div> </div>
); );
} }
/* ------------------------------- 在线客服 ------------------------------- */
// 网站聊天窗口的后台:实时看 AI 和客户的对话、接管 / 交还 AI、悄悄话、中文自动翻译、客户分级;
// 知识库、待解答问题、规则、范例;设置(企业微信推送等)。数据在服务器 chat-data.json(public-api.js 里的 mountChat)。
const CH_TIER = { project: ['工程项目', '#7c3aed'], importer: ['进口商/批发商', '#2F8F5B'], reseller: ['小经销商', '#3D6E99'], personal: ['个人买家', '#C9842E'], unknown: ['待判断', '#8a96a8'], spam: ['垃圾消息', '#b9c0cc'] };
const chApi = async (method, url, body) => {
const r = await fetch(url, { method, headers: body ? { 'Content-Type': 'application/json' } : undefined, body: body ? JSON.stringify(body) : undefined, credentials: 'same-origin' });
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`);
return j;
};
const chTime = (t) => { const d = new Date(t), now = new Date(); const hm = d.toTimeString().slice(0, 5); return d.toDateString() === now.toDateString() ? hm : `${d.getMonth() + 1}/${d.getDate()} ${hm}`; };
const chFlag = (cc) => (cc && /^[A-Z]{2}$/.test(cc) ? String.fromCodePoint(...[...cc].map((ch) => 127397 + ch.charCodeAt(0))) : '🌐');
const chLink = (s) => String(s).split(/(https?:\/\/[^\s]+)/g).map((p, i) => (/^https?:\/\//.test(p) ? <a key={i} href={p} target="_blank" rel="noreferrer">{p}</a> : p));
function ChatCenter({ onNotify, onSaveCustomer, initialSid }) {
const [tab, setTab] = useState('convs');
const [list, setList] = useState([]);
const [sel, setSel] = useState(initialSid || null);
const [conv, setConv] = useState(null);
const [filter, setFilter] = useState('important');
const [know, setKnow] = useState(null);
const verRef = useRef(0), selRef = useRef(sel);
selRef.current = sel;
const loadList = async () => { try { const j = await chApi('GET', '/api/chat/admin/convs'); setList(j.list); } catch (e) {} };
const loadConv = async (sid) => { if (!sid) { setConv(null); return; } try { const j = await chApi('GET', `/api/chat/admin/conv/${sid}`); if (selRef.current === sid) setConv(j.conv); } catch (e) { setConv(null); } };
const loadKnow = async () => { try { setKnow(await chApi('GET', '/api/chat/admin/knowledge')); } catch (e) {} };
// 长轮询:服务器有任何变化就刷新列表和当前对话
useEffect(() => {
let alive = true;
(async () => {
await loadList();
while (alive) {
try {
const j = await chApi('GET', `/api/chat/admin/wait?ver=${verRef.current}`);
if (!alive) break;
if (j.ver !== verRef.current) { verRef.current = j.ver; await loadList(); if (selRef.current) await loadConv(selRef.current); }
} catch (e) { await new Promise((r) => setTimeout(r, 5000)); }
}
})();
return () => { alive = false; };
}, []);
useEffect(() => { loadConv(sel); }, [sel]);
useEffect(() => { if (tab !== 'convs' && tab !== 'settings') loadKnow(); }, [tab]);
const shown = list.filter((c) => filter === 'all' || (filter === 'important' ? (c.lead && (c.lead.score >= 50 || c.lead.needsHuman)) || c.mode === 'human' : filter === 'live' ? Date.now() - c.updated < 30 * 60e3 && c.status !== 'closed' : (c.lead && c.lead.tier) === filter));
const counts = { important: list.filter((c) => (c.lead && (c.lead.score >= 50 || c.lead.needsHuman)) || c.mode === 'human').length, live: list.filter((c) => Date.now() - c.updated < 30 * 60e3 && c.status !== 'closed').length, all: list.length };
return (
<div className="chc">
<style>{CHC_CSS}</style>
<div className="chc-tabs">
{[['convs', '对话'], ['unanswered', `待解答${know ? ` ${know.unanswered.filter((u) => u.status === 'open').length}` : ''}`], ['kb', '知识库'], ['rules', '规则与范例'], ['settings', '设置']].map(([k, l]) => (
<button key={k} className={tab === k ? 'on' : ''} onClick={() => setTab(k)}>{l}</button>
))}
</div>
{tab === 'convs' && (
<div className={`chc-main ${sel ? 'has-sel' : ''}`}>
<div className="chc-list">
<div className="chc-filters">
{[['important', '重要'], ['live', '进行中'], ['all', '全部'], ['spam', '垃圾']].map(([k, l]) => (
<button key={k} className={filter === k ? 'on' : ''} onClick={() => setFilter(k)}>{l}{counts[k] !== undefined ? ` ${counts[k]}` : ''}</button>
))}
</div>
{!shown.length && <div className="chc-empty">{filter === 'important' ? '还没有重要客户。AI 正在接待的所有对话在"全部"里。' : '没有对话'}</div>}
{shown.map((c) => {
const t = CH_TIER[(c.lead && c.lead.tier) || 'unknown'] || CH_TIER.unknown;
const live = Date.now() - c.updated < 5 * 60e3 && c.status !== 'closed';
return (
<div key={c.sid} className={`chc-item ${sel === c.sid ? 'on' : ''}`} onClick={() => setSel(c.sid)}>
<div className="chc-item-top">
<span className="chc-flag">{chFlag(c.ipCountry)}</span>
<b>{(c.lead && (c.lead.company || c.lead.name)) || (c.lead && c.lead.country) || c.ipCountry || '访客'}</b>
{live && <i className="chc-live" title="进行中" />}
{c.unread > 0 && <span className="chc-unread">{c.unread}</span>}
<small>{chTime(c.updated)}</small>
</div>
<div className="chc-item-mid">
<span className="chc-tier" style={{ background: t[1] }}>{t[0]}</span>
{c.lead && c.lead.score > 0 && <span className="chc-score">{c.lead.score}</span>}
{c.mode === 'human' ? <span className="chc-mode human">你在接待</span> : <span className="chc-mode">AI</span>}
{c.lead && c.lead.needsHuman && c.mode !== 'human' && <span className="chc-mode need">需要人工</span>}
</div>
<div className="chc-item-last">{c.lead && c.lead.summary_zh ? c.lead.summary_zh : c.last ? c.last.text : ''}</div>
</div>
);
})}
</div>
{sel && conv ? <ChatConversation conv={conv} onBack={() => setSel(null)} onNotify={onNotify} onSaveCustomer={onSaveCustomer} onReload={() => loadConv(sel)} onDeleted={() => { setSel(null); loadList(); }} /> : <div className="chc-pane chc-placeholder">{sel ? '加载中…' : '选择左边的一个对话'}</div>}
</div>
)}
{tab === 'unanswered' && know && <ChatUnanswered know={know} setKnow={setKnow} onNotify={onNotify} onOpen={(sid) => { setTab('convs'); setFilter('all'); setSel(sid); }} />}
{tab === 'kb' && know && <ChatKnowledge know={know} setKnow={setKnow} onNotify={onNotify} />}
{tab === 'rules' && know && <ChatRules know={know} setKnow={setKnow} onNotify={onNotify} />}
{tab === 'settings' && <ChatSettings onNotify={onNotify} />}
</div>
);
}
function ChatConversation({ conv, onBack, onNotify, onSaveCustomer, onReload, onDeleted }) {
const [text, setText] = useState('');
const [note, setNote] = useState('');
const [translate, setTranslate] = useState(true);
const [preview, setPreview] = useState('');
const [busy, setBusy] = useState(false);
const [showOrig, setShowOrig] = useState(false);
const [leadOpen, setLeadOpen] = useState(false);
const bodyRef = useRef(null);
const lastId = conv.msgs.length ? conv.msgs[conv.msgs.length - 1].id : 0;
useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [lastId, conv.typing, conv.sid]);
useEffect(() => { setText(''); setNote(''); setPreview(''); }, [conv.sid]);
const act = async (p, body, ok) => { try { await chApi('POST', `/api/chat/admin/${conv.sid}/${p}`, body); if (ok) onNotify(ok); onReload(); } catch (e) { onNotify('失败:' + e.message); } };
const send = async () => {
const v = text.trim(); if (!v) return;
setBusy(true);
try { await chApi('POST', `/api/chat/admin/${conv.sid}/send`, { text: v, translate }); setText(''); setPreview(''); onReload(); }
catch (e) { onNotify('发送失败:' + e.message); }
setBusy(false);
};
const doPreview = async () => {
if (!text.trim()) return;
setBusy(true);
try { const j = await chApi('POST', `/api/chat/admin/${conv.sid}/translate`, { text }); setPreview(j.text); } catch (e) { onNotify('翻译失败:' + e.message); }
setBusy(false);
};
const saveExample = async (m) => {
const prev = [...conv.msgs].filter((x) => x.id < m.id && x.from === 'user').pop();
try {
const k = await chApi('GET', '/api/chat/admin/knowledge');
await chApi('PUT', '/api/chat/admin/knowledge', { examples: [{ id: 'ex_' + Date.now(), q: prev ? prev.text : '', a: m.text, at: Date.now() }, ...k.examples] });
onNotify('已存为范例,AI 以后会参考这种回答');
} catch (e) { onNotify('保存失败:' + e.message); }
};
const l = conv.lead || {};
const t = CH_TIER[l.tier || 'unknown'] || CH_TIER.unknown;
const human = conv.mode === 'human';
return (
<div className="chc-pane">
<div className="chc-head">
<button className="btn btn-sm chc-back" onClick={onBack}>← 返回</button>
<div className="chc-head-who">
<b>{chFlag(conv.ipCountry)} {l.company || l.name || l.country || '访客'}</b>
<small>{conv.page ? conv.page.replace(/^https?:\/\/[^/]+/, '') : ''} · {chTime(conv.created)} 开始</small>
</div>
<div className="chc-head-act">
{human ? <button className="btn btn-sm" onClick={() => act('release', null, '已交还 AI')}>交还 AI</button> : <button className="btn btn-sm btn-primary" onClick={() => act('takeover', null, '已接管,客户会看到 Mike 加入了对话')}>接管对话</button>}
<button className="btn btn-sm" onClick={() => setLeadOpen((v) => !v)}>客户信息</button>
<button className="btn btn-sm" onClick={() => setShowOrig((v) => !v)}>{showOrig ? '看中文' : '看原文'}</button>
</div>
</div>
<div className="chc-status">
{human ? <span className="human">● 你在接待,AI 已暂停</span> : <span>● AI 正在接待{conv.typing ? '(正在输入…)' : ''}</span>}
{l.needsHuman && !human && <span className="need">AI 建议人工介入{l.handoff ? `:${l.handoff}` : ''}</span>}
</div>
<div className="chc-split">
<div className="chc-body" ref={bodyRef}>
{conv.msgs.map((m) => (
m.from === 'sys' ? <div key={m.id} className="chc-sys">{m.text}</div> : (
<div key={m.id} className={`chc-m ${m.from}`}>
<small>{m.from === 'user' ? '客户' : m.from === 'ai' ? 'AI' : m.from === 'note' ? '悄悄话(客户看不到)' : 'Mike(你)'} · {chTime(m.at)}</small>
<p>{chLink(!showOrig && m.zh && m.from !== 'human' ? m.zh : m.text)}</p>
{m.from === 'human' && m.zh && <em>你写的:{m.zh}</em>}
{!showOrig && m.zh && m.from !== 'human' && <em className="orig">{m.text}</em>}
{m.from === 'human' && <button className="chc-star" onClick={() => saveExample(m)}>⭐ 存为范例</button>}
</div>
)
))}
{conv.typing && <div className="chc-m ai typing"><p>正在输入…</p></div>}
</div>
{leadOpen && (
<div className="chc-lead">
<div className="chc-lead-top"><span className="chc-tier" style={{ background: t[1] }}>{t[0]}</span><b>{l.score || 0}</b><small>分</small></div>
<div className="chc-bar"><i style={{ width: `${l.score || 0}%` }} /></div>
{l.summary_zh && <p className="chc-sum">{l.summary_zh}</p>}
{[['姓名', 'name'], ['公司', 'company'], ['国家', 'country'], ['邮箱', 'email'], ['WhatsApp', 'whatsapp'], ['数量', 'quantity']].map(([lab, k]) => l[k] ? <div key={k} className="chc-kv"><span>{lab}</span><b>{l[k]}</b></div> : null)}
{l.products && l.products.length > 0 && <div className="chc-kv"><span>产品</span><b>{l.products.join('、')}</b></div>}
<div className="chc-kv"><span>IP 国家</span><b>{conv.ipCountry || '-'}</b></div>
<div className="chc-kv"><span>语言</span><b>{conv.custLang || conv.lang}</b></div>
{conv.pages && conv.pages.length > 0 && <div className="chc-pages"><span>看过的页面</span>{conv.pages.slice(-6).map((p, i) => <a key={i} href={p.page} target="_blank" rel="noreferrer">{p.page.replace(/^https?:\/\/[^/]+/, '')}</a>)}</div>}
<div className="chc-lead-act">
<button className="btn btn-sm btn-primary" onClick={() => onSaveCustomer(conv)}>存为客户档案</button>
{['importer', 'project', 'reseller', 'personal', 'spam'].map((k) => l.tier !== k && <button key={k} className="btn btn-sm" onClick={() => act('lead', { tier: k }, '已改为' + CH_TIER[k][0])}>标为{CH_TIER[k][0]}</button>)}
<button className="btn btn-sm" onClick={() => act('close', null, '已结束')}>结束对话</button>
<button className="btn btn-sm" style={{ color: 'var(--led-red)' }} onClick={async () => { if (!window.confirm('删除这个对话?')) return; await chApi('POST', `/api/chat/admin/${conv.sid}/delete`); onDeleted(); }}>删除</button>
</div>
</div>
)}
</div>
<div className="chc-compose">
<textarea value={text} onChange={(e) => { setText(e.target.value); setPreview(''); }} placeholder={human ? '直接用中文写,发出去会自动翻译成客户的语言' : '在这里回复就会接管对话(AI 暂停);用中文写会自动翻译'} rows={2}
onKeyDown={(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) send(); }} />
{preview && <div className="chc-preview"><small>客户会看到:</small>{preview}</div>}
<div className="chc-compose-row">
<label><input type="checkbox" checked={translate} onChange={(e) => setTranslate(e.target.checked)} /> 中文自动翻译</label>
{translate && /[一-鿿]/.test(text) && <button className="btn btn-sm" disabled={busy} onClick={doPreview}>先看翻译</button>}
<button className="btn btn-sm btn-primary" disabled={busy || !text.trim()} onClick={send}>{busy ? '…' : '发送(Ctrl+Enter)'}</button>
</div>
<div className="chc-note-row">
<input value={note} onChange={(e) => setNote(e.target.value)} placeholder="悄悄话给 AI(客户看不到),例如:这个客户可以给 5% 折扣,引导他先下样品单" onKeyDown={(e) => { if (e.key === 'Enter' && note.trim()) { act('note', { text: note.trim() }, '已告诉 AI'); setNote(''); } }} />
<button className="btn btn-sm" disabled={!note.trim()} onClick={() => { act('note', { text: note.trim() }, '已告诉 AI'); setNote(''); }}>告诉 AI</button>
<button className="btn btn-sm" onClick={() => act('nudge', null, 'AI 正在按你的意思回复')} title="AI 马上按悄悄话再回复客户一条(会交还给 AI)">让 AI 回复</button>
</div>
</div>
</div>
);
}
function ChatUnanswered({ know, setKnow, onNotify, onOpen }) {
const [ans, setAns] = useState({});
const open = know.unanswered.filter((u) => u.status === 'open');
const save = async (next) => { try { await chApi('PUT', '/api/chat/admin/knowledge', next); setKnow({ ...know, ...next }); } catch (e) { onNotify('保存失败:' + e.message); } };
return (
<div className="chc-box">
<p className="chc-tip">AI 答不上来或不确定的问题会出现在这里。写上答案(中文也可以)就会进入知识库,以后 AI 就会回答了。</p>
{!open.length && <div className="chc-empty">暂时没有待解答的问题 👍</div>}
{open.map((u) => (
<div key={u.id} className="chc-card">
<div className="chc-card-q"><b>{u.q}</b><small>{chTime(u.at)} · <a onClick={() => onOpen(u.sid)}>看对话</a></small></div>
<textarea rows={2} value={ans[u.id] || ''} onChange={(e) => setAns({ ...ans, [u.id]: e.target.value })} placeholder="写答案,例如:C10K 支持最多 3 台并机" />
<div className="chc-card-act">
<button className="btn btn-sm btn-primary" disabled={!(ans[u.id] || '').trim()} onClick={() => { save({ kb: [{ id: 'kb_' + Date.now(), q: u.q, a: ans[u.id].trim(), at: Date.now() }, ...know.kb], unanswered: know.unanswered.map((x) => (x.id === u.id ? { ...x, status: 'done' } : x)) }); onNotify('已加入知识库'); }}>加入知识库</button>
<button className="btn btn-sm" onClick={() => save({ unanswered: know.unanswered.map((x) => (x.id === u.id ? { ...x, status: 'ignored' } : x)) })}>忽略</button>
</div>
</div>
))}
</div>
);
}
function ChatKnowledge({ know, setKnow, onNotify }) {
const [items, setItems] = useState(know.kb);
const [q, setQ] = useState('');
const [dirty, setDirty] = useState(false);
useEffect(() => { setItems(know.kb); setDirty(false); }, [know.kb]);
const upd = (id, k, v) => { setItems(items.map((x) => (x.id === id ? { ...x, [k]: v } : x))); setDirty(true); };
const save = async () => { try { await chApi('PUT', '/api/chat/admin/knowledge', { kb: items }); setKnow({ ...know, kb: items }); setDirty(false); onNotify('知识库已保存,AI 马上生效'); } catch (e) { onNotify('保存失败:' + e.message); } };
const shown = items.filter((x) => !q || (x.q + x.a).toLowerCase().includes(q.toLowerCase()));
return (
<div className="chc-box">
<p className="chc-tip">AI 回答客户时会参考这里的内容:起订量、付款方式、交期、质保、认证、运输……写得越具体,AI 越专业。产品参数不用写,AI 会直接读产品管理里已发布的产品。中英文都可以。</p>
<div className="chc-bar-row">
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="搜索知识库" />
<button className="btn btn-sm" onClick={() => { setItems([{ id: 'kb_' + Date.now(), q: '', a: '', at: Date.now() }, ...items]); setDirty(true); }}>+ 新增一条</button>
<button className="btn btn-sm btn-primary" disabled={!dirty} onClick={save}>保存</button>
</div>
{shown.map((x) => (
<div key={x.id} className="chc-card">
<input className="chc-q" value={x.q} onChange={(e) => upd(x.id, 'q', e.target.value)} placeholder="问题 / 主题,例如:付款方式" />
<textarea rows={3} value={x.a} onChange={(e) => upd(x.id, 'a', e.target.value)} placeholder="答案,例如:T/T 30% 定金,70% 发货前付清;也接受 L/C" />
<div className="chc-card-act"><button className="btn btn-sm" style={{ color: 'var(--led-red)' }} onClick={() => { setItems(items.filter((y) => y.id !== x.id)); setDirty(true); }}>删除</button></div>
</div>
))}
</div>
);
}
function ChatRules({ know, setKnow, onNotify }) {
const [rules, setRules] = useState(know.rules);
const [ex, setEx] = useState(know.examples);
const [dirty, setDirty] = useState(false);
const save = async () => { try { await chApi('PUT', '/api/chat/admin/knowledge', { rules, examples: ex }); setKnow({ ...know, rules, examples: ex }); setDirty(false); onNotify('已保存,AI 马上生效'); } catch (e) { onNotify('保存失败:' + e.message); } };
return (
<div className="chc-box">
<div className="chc-bar-row"><h3>规则</h3><button className="btn btn-sm" onClick={() => { setRules([...rules, { id: 'r_' + Date.now(), text: '' }]); setDirty(true); }}>+ 新增规则</button><button className="btn btn-sm btn-primary" disabled={!dirty} onClick={save}>保存</button></div>
<p className="chc-tip">AI 每次对话都会遵守。发现 AI 哪里做得不对,就写一条,例如:不要主动推荐工频机给家庭用户;客户问 Mini UPS 小批量时,引导他看网站上的拼单。</p>
{rules.map((r) => (
<div key={r.id} className="chc-rule">
<input value={r.text} onChange={(e) => { setRules(rules.map((x) => (x.id === r.id ? { ...x, text: e.target.value } : x))); setDirty(true); }} placeholder="写一条规则" />
<button className="btn btn-sm" onClick={() => { setRules(rules.filter((x) => x.id !== r.id)); setDirty(true); }}>删除</button>
</div>
))}
<div className="chc-bar-row" style={{ marginTop: 24 }}><h3>范例(你的好回答)</h3></div>
<p className="chc-tip">在对话里点你自己回复下面的"⭐ 存为范例"就会出现在这里。AI 会学这些回答的说法和谈判方式。</p>
{!ex.length && <div className="chc-empty">还没有范例</div>}
{ex.map((x) => (
<div key={x.id} className="chc-card">
<small>客户问:</small><textarea rows={2} value={x.q} onChange={(e) => { setEx(ex.map((y) => (y.id === x.id ? { ...y, q: e.target.value } : y))); setDirty(true); }} />
<small>好的回答:</small><textarea rows={3} value={x.a} onChange={(e) => { setEx(ex.map((y) => (y.id === x.id ? { ...y, a: e.target.value } : y))); setDirty(true); }} />
<div className="chc-card-act"><button className="btn btn-sm" style={{ color: 'var(--led-red)' }} onClick={() => { setEx(ex.filter((y) => y.id !== x.id)); setDirty(true); }}>删除</button></div>
</div>
))}
</div>
);
}
function ChatSettings({ onNotify }) {
const [s, setS] = useState(null);
const [usage, setUsage] = useState([]);
useEffect(() => { chApi('GET', '/api/chat/admin/settings').then((j) => { setS(j.settings); setUsage(j.usage); }).catch((e) => onNotify('读取失败:' + e.message)); }, []);
if (!s) return <div className="chc-box">加载中…</div>;
const set = (k, v) => setS({ ...s, [k]: v });
const save = async () => { try { const j = await chApi('PUT', '/api/chat/admin/settings', s); setS(j.settings); onNotify('设置已保存'); } catch (e) { onNotify('保存失败:' + e.message); } };
return (
<div className="chc-box chc-set">
<label className="chc-switch"><input type="checkbox" checked={s.enabled} onChange={(e) => set('enabled', e.target.checked)} /> 网站在线客服开启(关闭后网站窗口只显示 WhatsApp / 邮箱)</label>
<div className="chc-f"><span>企业微信群机器人 Webhook</span><input value={s.wecomWebhook} onChange={(e) => set('wecomWebhook', e.target.value)} placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=..." /><small>企业微信 → 建一个只有你的群 → 群设置 → 群机器人 → 添加 → 复制 Webhook 地址粘贴到这里</small></div>
<div className="chc-f"><span>重要客户评分门槛(0–100)</span><input type="number" value={s.notifyScore} onChange={(e) => set('notifyScore', e.target.value)} /><small>评分达到这个分数才推送到手机。参考:个人买家 10–35,小经销商 40–60,进口商 60–85,工程项目 75–100。客户要求人工或 AI 答不了时也会推送。</small></div>
<div className="chc-f2">
<div className="chc-f"><span>窗口名称</span><input value={s.agentName} onChange={(e) => set('agentName', e.target.value)} /></div>
<div className="chc-f"><span>你的英文名</span><input value={s.managerName} onChange={(e) => set('managerName', e.target.value)} /></div>
<div className="chc-f"><span>你的职位</span><input value={s.managerTitle} onChange={(e) => set('managerTitle', e.target.value)} /></div>
</div>
<div className="chc-f2">
<div className="chc-f"><span>AI 最快多久回复(毫秒)</span><input type="number" value={s.minReplyMs} onChange={(e) => set('minReplyMs', e.target.value)} /><small>默认 5000 = 5 秒,看起来不像秒回</small></div>
<div className="chc-f"><span>每天 AI 调用上限</span><input type="number" value={s.dailyCap} onChange={(e) => set('dailyCap', e.target.value)} /><small>防止被人恶意刷,超过后转人工</small></div>
</div>
<div className="chc-bar-row">
<button className="btn btn-sm btn-primary" onClick={save}>保存设置</button>
<button className="btn btn-sm" onClick={async () => { try { await chApi('POST', '/api/chat/admin/test-push'); onNotify('已发送测试消息,看看企业微信收到没有'); } catch (e) { onNotify('推送失败:' + e.message); } }}>发一条测试推送</button>
</div>
<h3 style={{ marginTop: 24 }}>最近 14 天 AI 用量</h3>
<table className="chc-usage"><thead><tr><th>日期</th><th>总调用</th><th>回复客户</th><th>分级 / 翻译</th></tr></thead>
<tbody>{usage.slice().reverse().map(([d, u]) => <tr key={d}><td>{d}</td><td>{u.calls}</td><td>{u.reply || 0}</td><td>{(u.classify || 0) + (u.translate || 0)}</td></tr>)}</tbody></table>
</div>
);
}
const CHC_CSS = `
.chc { display: flex; flex-direction: column; gap: 12px; min-height: calc(100vh - 120px); }
.chc-tabs { display: flex; gap: 6px; flex-wrap: wrap; }
.chc-tabs button, .chc-filters button { padding: 7px 14px; border-radius: 999px; border: 1px solid var(--line); background: var(--panel); color: var(--ink); font: 500 13.5px inherit; cursor: pointer; }
.chc-tabs button.on, .chc-filters button.on { background: var(--ink); color: #fff; border-color: var(--ink); }
.chc-main { display: grid; grid-template-columns: 320px minmax(0, 1fr); gap: 12px; height: calc(100vh - 170px); min-height: 520px; }
.chc-list { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; overflow-y: auto; }
.chc-filters { display: flex; gap: 6px; padding: 10px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel); z-index: 1; flex-wrap: wrap; }
.chc-filters button { padding: 5px 11px; font-size: 12.5px; }
.chc-item { padding: 11px 12px; border-bottom: 1px solid var(--line); cursor: pointer; display: grid; gap: 5px; }
.chc-item:hover { background: #f5f8fb; } .chc-item.on { background: var(--led-blue-bg); }
.chc-item-top { display: flex; align-items: center; gap: 6px; } .chc-item-top b { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; } .chc-item-top small { color: var(--ink-soft); font-size: 11.5px; }
.chc-flag { font-size: 16px; }
.chc-live { width: 8px; height: 8px; border-radius: 50%; background: var(--led-green); box-shadow: 0 0 0 3px var(--led-green-bg); }
.chc-unread { min-width: 18px; height: 18px; border-radius: 9px; background: var(--led-red); color: #fff; font-size: 11px; font-weight: 700; text-align: center; line-height: 18px; padding: 0 5px; }
.chc-item-mid { display: flex; gap: 5px; align-items: center; flex-wrap: wrap; }
.chc-tier { padding: 2px 8px; border-radius: 999px; color: #fff; font-size: 11.5px; font-weight: 600; }
.chc-score { font: 600 12px 'IBM Plex Mono', monospace; color: var(--ink); }
.chc-mode { padding: 1px 7px; border-radius: 5px; background: #eef2f6; color: var(--ink-soft); font-size: 11px; font-weight: 600; } .chc-mode.human { background: var(--led-green-bg); color: var(--led-green); } .chc-mode.need { background: var(--led-amber-bg); color: var(--led-amber); }
.chc-item-last { font-size: 12.5px; color: var(--ink-soft); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.chc-empty { padding: 24px 16px; color: var(--ink-soft); font-size: 13.5px; text-align: center; }
.chc-pane { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
.chc-placeholder { align-items: center; justify-content: center; color: var(--ink-soft); }
.chc-head { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
.chc-back { display: none; }
.chc-head-who { flex: 1; min-width: 160px; display: grid; } .chc-head-who b { font-size: 15px; } .chc-head-who small { color: var(--ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chc-head-act { display: flex; gap: 6px; flex-wrap: wrap; }
.chc-status { display: flex; gap: 10px; flex-wrap: wrap; padding: 6px 12px; font-size: 12.5px; color: var(--blue); background: #f5f8fb; border-bottom: 1px solid var(--line); }
.chc-status .human { color: var(--led-green); font-weight: 600; } .chc-status .need { color: var(--led-amber); font-weight: 600; }
.chc-split { flex: 1; min-height: 0; display: flex; }
.chc-body { flex: 1; overflow-y: auto; padding: 14px; display: flex; flex-direction: column; gap: 10px; background: #f7f9fb; }
.chc-m { max-width: 78%; display: grid; gap: 3px; }
.chc-m small { font-size: 11px; color: var(--ink-soft); }
.chc-m p { margin: 0; padding: 9px 12px; border-radius: 12px; font-size: 14px; line-height: 1.5; white-space: pre-wrap; word-wrap: break-word; background: #fff; border: 1px solid var(--line); }
.chc-m p a { color: var(--blue); word-break: break-all; }
.chc-m em { font-style: normal; font-size: 12px; color: var(--ink-soft); padding: 0 4px; } .chc-m em.orig { color: #9aa5b5; }
.chc-m.user { align-self: flex-start; }
.chc-m.ai, .chc-m.human, .chc-m.note { align-self: flex-end; text-align: left; } .chc-m.ai small, .chc-m.human small, .chc-m.note small { text-align: right; }
.chc-m.ai p { background: #e8f1ff; border-color: #cfe0f8; } .chc-m.human p { background: var(--led-green-bg); border-color: #bfe3cd; } .chc-m.note p { background: #fff7db; border-color: #f0dc9a; border-style: dashed; }
.chc-m.typing p { color: var(--ink-soft); font-style: italic; }
.chc-star { justify-self: end; border: 0; background: none; color: var(--ink-soft); font-size: 11.5px; cursor: pointer; }
.chc-sys { align-self: center; font-size: 12px; color: var(--led-green); background: var(--led-green-bg); padding: 3px 12px; border-radius: 999px; }
.chc-lead { width: 280px; flex: none; border-left: 1px solid var(--line); padding: 14px; overflow-y: auto; display: grid; gap: 8px; align-content: start; }
.chc-lead-top { display: flex; align-items: baseline; gap: 6px; } .chc-lead-top b { font-size: 24px; margin-left: auto; } .chc-lead-top small { color: var(--ink-soft); }
.chc-bar { height: 6px; border-radius: 3px; background: #eef2f6; overflow: hidden; } .chc-bar i { display: block; height: 100%; background: linear-gradient(90deg, var(--led-amber), var(--led-green)); }
.chc-sum { margin: 0; font-size: 13.5px; line-height: 1.5; background: #f5f8fb; padding: 8px 10px; border-radius: 8px; }
.chc-kv { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 6px; font-size: 13px; } .chc-kv span { color: var(--ink-soft); } .chc-kv b { font-weight: 500; overflow-wrap: anywhere; }
.chc-pages { display: grid; gap: 3px; font-size: 12px; } .chc-pages span { color: var(--ink-soft); } .chc-pages a { color: var(--blue); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chc-lead-act { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
.chc-compose { border-top: 1px solid var(--line); padding: 10px 12px; display: grid; gap: 8px; }
.chc-compose textarea, .chc-box textarea, .chc-box input:not([type=checkbox]), .chc-note-row input { width: 100%; box-sizing: border-box; border: 1px solid var(--line); border-radius: 8px; padding: 8px 10px; font: 14px inherit; color: var(--ink); background: #fff; resize: vertical; }
.chc-preview { font-size: 13px; background: #f5f8fb; border-radius: 8px; padding: 8px 10px; white-space: pre-wrap; } .chc-preview small { display: block; color: var(--ink-soft); }
.chc-compose-row, .chc-note-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } .chc-compose-row label { font-size: 13px; color: var(--ink-soft); margin-right: auto; display: flex; gap: 5px; align-items: center; }
.chc-note-row input { flex: 1; min-width: 200px; background: #fffbea; }
.chc-box { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px; display: grid; gap: 10px; align-content: start; }
.chc-box h3 { margin: 0; font-size: 16px; }
.chc-tip { margin: 0; font-size: 13px; color: var(--ink-soft); line-height: 1.55; }
.chc-bar-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } .chc-bar-row input { flex: 1; min-width: 180px; } .chc-bar-row h3 { margin-right: auto; }
.chc-card { border: 1px solid var(--line); border-radius: 10px; padding: 10px; display: grid; gap: 6px; } .chc-card small { color: var(--ink-soft); font-size: 12px; }
.chc-card-q { display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; } .chc-card-q a { color: var(--blue); cursor: pointer; }
.chc-card-act { display: flex; gap: 6px; justify-content: flex-end; }
.chc-q { font-weight: 600; }
.chc-rule { display: flex; gap: 6px; }
.chc-set { max-width: 820px; }
.chc-switch { display: flex; gap: 8px; align-items: center; font-weight: 600; font-size: 14px; }
.chc-f { display: grid; gap: 4px; } .chc-f span { font-size: 13px; font-weight: 600; } .chc-f small { font-size: 12px; color: var(--ink-soft); line-height: 1.5; }
.chc-f2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; }
.chc-usage { border-collapse: collapse; font-size: 13px; } .chc-usage th, .chc-usage td { border-bottom: 1px solid var(--line); padding: 6px 12px; text-align: left; }
@media (max-width: 900px) {
.chc-main { grid-template-columns: minmax(0, 1fr); height: auto; min-height: 0; }
.chc-main.has-sel .chc-list { display: none; } .chc-main:not(.has-sel) .chc-pane { display: none; }
.chc-main.has-sel .chc-pane { height: calc(100vh - 130px); height: calc(100dvh - 130px); }
.chc-back { display: inline-flex; }
.chc-split { position: relative; } .chc-lead { position: absolute; inset: 0; width: auto; background: var(--panel); z-index: 2; border: 0; }
.chc-m { max-width: 90%; }
}
`;