From c3d78f7a1e908ca440b6e8e08cea5f101a31fac1 Mon Sep 17 00:00:00 2001 From: mike Date: Sat, 7 Nov 2026 00:20:48 +0800 Subject: [PATCH] Update App.jsx via upload script - 2026-11-07 00:20:35 --- App.jsx | 414 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 412 insertions(+), 2 deletions(-) diff --git a/App.jsx b/App.jsx index 5ed294d..f21b657 100644 --- a/App.jsx +++ b/App.jsx @@ -5,7 +5,7 @@ import { Building2, Globe, Phone, Save, RefreshCw, LayoutDashboard, Users, Package, Layers, Zap, Tag, Inbox, Paperclip, 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'; import { MicUploadPage } from './mic-upload/MicUploadPage'; import { ImageToolPage } from './mic-upload/ImageToolPage'; @@ -2374,6 +2374,7 @@ const NAV_GROUPS = [ { id: 'monitor', label: '客户档案', icon: LayoutDashboard }, { id: 'manage', label: '客户管理', icon: Users }, { id: 'orders', label: '订单管理', icon: ClipboardList }, + { id: 'chat', label: '在线客服', icon: MessageCircle }, { id: 'jms', label: 'Just My Socks', icon: Wifi }, ] }, { label: '产品', items: [ @@ -2502,7 +2503,9 @@ function MainApp({ username, onLogout }) { }, []); const [customers, setCustomers] = 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 [selectedId, setSelectedId] = useState(null); @@ -4201,6 +4204,18 @@ function MainApp({ username, onLogout }) { )} + {view === 'chat' && ( + { + 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' && ( ); } + +/* ------------------------------- 在线客服 ------------------------------- */ +// 网站聊天窗口的后台:实时看 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) ? {p} : 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 ( +
+ +
+ {[['convs', '对话'], ['unanswered', `待解答${know ? ` ${know.unanswered.filter((u) => u.status === 'open').length}` : ''}`], ['kb', '知识库'], ['rules', '规则与范例'], ['settings', '设置']].map(([k, l]) => ( + + ))} +
+ {tab === 'convs' && ( +
+
+
+ {[['important', '重要'], ['live', '进行中'], ['all', '全部'], ['spam', '垃圾']].map(([k, l]) => ( + + ))} +
+ {!shown.length &&
{filter === 'important' ? '还没有重要客户。AI 正在接待的所有对话在"全部"里。' : '没有对话'}
} + {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 ( +
setSel(c.sid)}> +
+ {chFlag(c.ipCountry)} + {(c.lead && (c.lead.company || c.lead.name)) || (c.lead && c.lead.country) || c.ipCountry || '访客'} + {live && } + {c.unread > 0 && {c.unread}} + {chTime(c.updated)} +
+
+ {t[0]} + {c.lead && c.lead.score > 0 && {c.lead.score}} + {c.mode === 'human' ? 你在接待 : AI} + {c.lead && c.lead.needsHuman && c.mode !== 'human' && 需要人工} +
+
{c.lead && c.lead.summary_zh ? c.lead.summary_zh : c.last ? c.last.text : ''}
+
+ ); + })} +
+ {sel && conv ? setSel(null)} onNotify={onNotify} onSaveCustomer={onSaveCustomer} onReload={() => loadConv(sel)} onDeleted={() => { setSel(null); loadList(); }} /> :
{sel ? '加载中…' : '选择左边的一个对话'}
} +
+ )} + {tab === 'unanswered' && know && { setTab('convs'); setFilter('all'); setSel(sid); }} />} + {tab === 'kb' && know && } + {tab === 'rules' && know && } + {tab === 'settings' && } +
+ ); +} + +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 ( +
+
+ +
+ {chFlag(conv.ipCountry)} {l.company || l.name || l.country || '访客'} + {conv.page ? conv.page.replace(/^https?:\/\/[^/]+/, '') : ''} · {chTime(conv.created)} 开始 +
+
+ {human ? : } + + +
+
+
+ {human ? ● 你在接待,AI 已暂停 : ● AI 正在接待{conv.typing ? '(正在输入…)' : ''}} + {l.needsHuman && !human && AI 建议人工介入{l.handoff ? `:${l.handoff}` : ''}} +
+
+
+ {conv.msgs.map((m) => ( + m.from === 'sys' ?
{m.text}
: ( +
+ {m.from === 'user' ? '客户' : m.from === 'ai' ? 'AI' : m.from === 'note' ? '悄悄话(客户看不到)' : 'Mike(你)'} · {chTime(m.at)} +

{chLink(!showOrig && m.zh && m.from !== 'human' ? m.zh : m.text)}

+ {m.from === 'human' && m.zh && 你写的:{m.zh}} + {!showOrig && m.zh && m.from !== 'human' && {m.text}} + {m.from === 'human' && } +
+ ) + ))} + {conv.typing &&

正在输入…

} +
+ {leadOpen && ( +
+
{t[0]}{l.score || 0}分
+
+ {l.summary_zh &&

{l.summary_zh}

} + {[['姓名', 'name'], ['公司', 'company'], ['国家', 'country'], ['邮箱', 'email'], ['WhatsApp', 'whatsapp'], ['数量', 'quantity']].map(([lab, k]) => l[k] ?
{lab}{l[k]}
: null)} + {l.products && l.products.length > 0 &&
产品{l.products.join('、')}
} +
IP 国家{conv.ipCountry || '-'}
+
语言{conv.custLang || conv.lang}
+ {conv.pages && conv.pages.length > 0 &&
看过的页面{conv.pages.slice(-6).map((p, i) => {p.page.replace(/^https?:\/\/[^/]+/, '')})}
} +
+ + {['importer', 'project', 'reseller', 'personal', 'spam'].map((k) => l.tier !== k && )} + + +
+
+ )} +
+
+