// MIC产品上传 — 前端页面 // // 接入方式(对照 App.jsx 里"后板图模板"菜单项的现成写法): // // 1. import { MicUploadPage } from './mic-upload/MicUploadPage'; // (或者把这个文件内容直接并入 App.jsx,看你想不想保持单文件习惯) // // 2. NAV_GROUPS 里"产品"分组,在 backpanel 那一项下面加一行(App.jsx 约2121行): // { id: 'mic-upload', label: 'MIC产品上传', icon: UploadCloud }, // UploadCloud 需要从 lucide-react 多 import 一个图标。 // // 3. 渲染switch里(App.jsx约3722-3724行 backpanel那块下面)加: // {view === 'mic-upload' && } // products / productCategories 都是 App.jsx 里已有的那两个state(约2225/2274行)。 // // 本组件是单模式(一次只处理一个产品),批量队列以后再加。 import React, { useState, useRef, useCallback, useEffect } from 'react'; const VIEWPORT = { width: 1280, height: 800 }; function useMicSession() { const [sessionId, setSessionId] = useState(null); const [wsToken, setWsToken] = useState(null); const [connected, setConnected] = useState(false); const [logs, setLogs] = useState([]); const wsRef = useRef(null); const frameCallbackRef = useRef(null); const appendLog = useCallback((entry) => { setLogs((prev) => [...prev.slice(-300), entry]); }, []); const openWs = useCallback((id, token, onFrame) => { frameCallbackRef.current = onFrame; const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; const ws = new WebSocket(`${proto}://${window.location.host}/ws/mic-upload?sessionId=${id}&token=${token}`); ws.onopen = () => setConnected(true); ws.onclose = () => setConnected(false); ws.onerror = () => setConnected(false); ws.onmessage = (ev) => { let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; } if (msg.type === 'frame') { // 收到画面帧本身就是"确实连着"的铁证——直接在这里也置一次true, // 不完全依赖onopen这一个事件(万一它在某些代理环境下没如期触发) setConnected(true); frameCallbackRef.current && frameCallbackRef.current(msg.data); } else if (msg.type === 'log') { appendLog(msg); } }; wsRef.current = ws; }, [appendLog]); // 单例会话:POST这个接口既是"新建"也是"接上已经在跑的那个",后端会自己判断 // 要不要真的启动新浏览器。所以组件挂载时(首次进这个页面/刷新/从别的菜单 // 切回来)都直接调它就够了,不需要额外猜"之前的会话还在不在"。 const connect = useCallback(async (onFrame) => { setLogs([]); const res = await fetch('/api/mic-upload/sessions', { method: 'POST' }); const data = await res.json(); if (!res.ok) throw new Error(data.error || '启动会话失败'); setSessionId(data.sessionId); setWsToken(data.wsToken); openWs(data.sessionId, data.wsToken, onFrame); return data; // { sessionId, wsToken, phase, reused } }, [openWs]); const stop = useCallback(async () => { if (wsRef.current) { try { wsRef.current.close(); } catch (e) {} wsRef.current = null; } if (sessionId) { try { await fetch(`/api/mic-upload/sessions/${sessionId}`, { method: 'DELETE' }); } catch (e) {} } setSessionId(null); setWsToken(null); setConnected(false); }, [sessionId]); const sendInput = useCallback((msg) => { if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { wsRef.current.send(JSON.stringify(msg)); } }, []); // 组件卸载(切到别的菜单)时只关WebSocket连接,后端的浏览器会话继续留着—— // 是单例的,切回来时挂载effect会重新POST /sessions,自动接上同一个。 useEffect(() => () => { if (wsRef.current) wsRef.current.close(); }, []); return { sessionId, wsToken, connected, logs, connect, stop, sendInput }; } // canvas <-> 远程浏览器坐标换算:canvas按容器宽度等比缩放显示,鼠标事件按缩放比换算回1280x800 function useRemoteCanvas(sendInput) { const canvasRef = useRef(null); const scaleRef = useRef(1); const drawFrame = useCallback((base64Jpeg) => { const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = () => { canvas.width = VIEWPORT.width; canvas.height = VIEWPORT.height; ctx.drawImage(img, 0, 0, VIEWPORT.width, VIEWPORT.height); }; img.src = `data:image/jpeg;base64,${base64Jpeg}`; }, []); const toRemoteCoords = useCallback((e) => { const canvas = canvasRef.current; const rect = canvas.getBoundingClientRect(); scaleRef.current = VIEWPORT.width / rect.width; const x = Math.round((e.clientX - rect.left) * scaleRef.current); const y = Math.round((e.clientY - rect.top) * scaleRef.current); return { x, y }; }, []); const handlers = { onMouseMove: (e) => { const { x, y } = toRemoteCoords(e); sendInput({ type: 'mousemove', x, y }); }, onMouseDown: (e) => { const { x, y } = toRemoteCoords(e); sendInput({ type: 'mousedown', x, y, button: 'left' }); }, onMouseUp: (e) => { const { x, y } = toRemoteCoords(e); sendInput({ type: 'mouseup', x, y, button: 'left' }); }, onWheel: (e) => { sendInput({ type: 'wheel', dx: e.deltaX, dy: e.deltaY }); e.preventDefault(); }, }; return { canvasRef, drawFrame, handlers }; } // 捕获键盘输入的隐藏input——登录表单里的账号密码靠这个转发过去 function KeyCaptureInput({ sendInput }) { const [value, setValue] = useState(''); return ( { const next = e.target.value; if (next.length > value.length) { sendInput({ type: 'text', text: next.slice(value.length) }); } else if (next.length < value.length) { for (let i = 0; i < value.length - next.length; i++) sendInput({ type: 'keydown', key: 'Backspace' }); } setValue(next); }} onKeyDown={(e) => { if (e.key === 'Enter') { sendInput({ type: 'keydown', key: 'Enter' }); setValue(''); } if (e.key === 'Tab') { sendInput({ type: 'keydown', key: 'Tab' }); e.preventDefault(); } }} style={{ width: '100%', padding: '8px 10px', fontSize: 13, border: '1px solid var(--line, #ddd)', borderRadius: 6 }} /> ); } // 已保存的MIC账号/密码——只存是否已保存(hasEmail/hasPassword)在前端state, // 密码明文从不出现在前端:保存时直接PUT给后端加密存储;使用时点"填入"按钮, // 后端解密后直接当键盘输入发给远程浏览器,不经过任何前端网络请求。 function SavedCredentialsPanel({ sessionId, sendAutofill }) { const [hasEmail, setHasEmail] = useState(false); const [hasPassword, setHasPassword] = useState(false); const [emailInput, setEmailInput] = useState(''); const [passwordInput, setPasswordInput] = useState(''); const [saving, setSaving] = useState(false); const [msg, setMsg] = useState(''); useEffect(() => { fetch('/api/mic-upload/credentials') .then((r) => r.json()) .then((d) => { setHasEmail(!!d.hasEmail); setHasPassword(!!d.hasPassword); }) .catch(() => {}); }, []); async function handleSave() { if (!emailInput && !passwordInput) return; setSaving(true); setMsg(''); try { const res = await fetch('/api/mic-upload/credentials', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: emailInput || undefined, password: passwordInput || undefined }), }); const data = await res.json(); if (!res.ok) throw new Error(data.error || '保存失败'); setHasEmail(data.hasEmail); setHasPassword(data.hasPassword); setEmailInput(''); setPasswordInput(''); setMsg('已保存'); } catch (e) { setMsg(e.message); } finally { setSaving(false); } } return (
已保存:账号{hasEmail ? '✓' : '未保存'} / 密码{hasPassword ? '✓' : '未保存'}
setEmailInput(e.target.value)} style={{ padding: '6px 8px', fontSize: 13 }} /> setPasswordInput(e.target.value)} style={{ padding: '6px 8px', fontSize: 13 }} /> {msg &&
{msg}
} {sessionId && (
)}
用法:先点一下右侧画面里要填的那个输入框(让它获得焦点),再点这里的"填入"按钮。
); } // 品类 -> MIC仿造发布模板URL 配置面板。列表来自CRM"产品分组"里的品类树, // 每个细分品类(type)一行,读写走 /api/mic-upload/templates。 function TemplateConfigPanel({ productCategories, onClose }) { const [rawText, setRawText] = useState(''); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [msg, setMsg] = useState(''); useEffect(() => { fetch('/api/mic-upload/templates', { cache: 'no-store' }) .then((r) => r.json()) .then((d) => setRawText(JSON.stringify(d.value || {}, null, 2))) .catch((e) => setMsg(`读取失败: ${e.message}`)) .finally(() => setLoading(false)); }, []); async function handleSave() { setMsg(''); let parsed; try { parsed = JSON.parse(rawText); } catch (e) { setMsg(`不是合法的JSON,改一下格式再保存: ${e.message}`); return; } if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { setMsg('格式不对,最外层必须是 { "品类名": "URL", ... } 这样的对象'); return; } setSaving(true); try { const res = await fetch('/api/mic-upload/templates', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: parsed }), }); const data = await res.json(); if (!res.ok) throw new Error(data.error || '保存失败'); setMsg('已保存'); } catch (e) { setMsg(e.message); } finally { setSaving(false); } } const allTypeNames = (productCategories || []).flatMap((cat) => cat.types || []); return (
品类发布模板配置
直接编辑这段JSON——key是品类的细分类型名,value是"仿造发布"模板产品的完整URL(形如 https://membercenter.made-in-china.com/productmanage.do?xcase=addSimilar&prodId=xxxx)。 不需要的品类可以留在JSON里但值填空字符串,或者干脆删掉那一行。
{loading ? (
加载中...
) : ( <>