| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099 |
- /* POUCHLAB 后台管理:登录 / 仪表盘 / 订单管理(状态·支付·发货·CAD 导出)/ 用户管理 */
- (function () {
- const h = window.React.createElement;
- const A = window.PL.ui.antd;
- const UI = window.PL.ui;
- const dayjs = window.dayjs;
- const STATUS = [
- { value: 'pending_payment', label: '待支付', color: 'orange' },
- { value: 'producing', label: '生产中', color: 'processing' },
- { value: 'shipped', label: '已发货', color: 'geekblue' },
- { value: 'completed', label: '已完成', color: 'success' },
- { value: 'cancelled', label: '已取消', color: 'default' }
- ];
- const PAYS = [
- { value: 'unpaid', label: '未支付', color: 'orange' },
- { value: 'paid', label: '已支付', color: 'success' },
- { value: 'refunded', label: '已退款', color: 'purple' }
- ];
- const TYPE_LABEL = { bag: '包装袋', box: '纸盒' };
- const statusMeta = function (v) { return STATUS.find(function (s) { return s.value === v; }) || { label: v, color: 'default' }; };
- const payMeta = function (v) { return PAYS.find(function (s) { return s.value === v; }) || { label: v, color: 'default' }; };
- const fmtTime = function (ts) { return ts ? dayjs(ts * 1000).format('MM-DD HH:mm') : '-'; };
- const fmtMoney = function (n) { return '¥' + Number(n || 0).toFixed(2); };
- const state = {
- booted: false, admin: null,
- login: { username: '', password: '', busy: false },
- view: 'dashboard',
- stats: null, recent: [],
- orders: { items: [], total: 0, page: 1, pageSize: 10, loading: false,
- filter: { type: '', status: '', pay: '', query: '', userId: 0, userName: '' } },
- users: { items: [], total: 0, page: 1, pageSize: 10, loading: false, query: '' },
- factories: { items: [], loading: false },
- facModal: { open: false, id: 0, username: '', name: '', password: '', busy: false, isCreate: true },
- quotaModal: { open: false, user: null, quota: 0, busy: false },
- aiConfig: { loaded: false, baseUrl: '', model: '', apiKeyMasked: '', hasKey: false, configured: false, dbOverridden: {}, saving: false, testing: false, testResult: null },
- drawer: { open: false, no: null, data: null,
- form: { status: '', pay: '', adminNote: '', carrier: '', trackingNo: '' },
- saveBusy: false, shipBusy: false, replyText: '', replyBusy: false },
- cadModal: { open: false, no: null, url: null, loading: false },
- emailModal: { open: false, messageId: null, orderNo: null, to: '', subject: '', body: '', busy: false, tab: 'edit', previewHtml: '', previewBusy: false }
- };
- const isFactory = function () { return state.admin && state.admin.role === 'factory'; };
- const apiBase = function () { return isFactory() ? '/factory' : '/admin'; };
- const previewCache = new Map();
- const dxfBufferCache = new Map(); // orderNo -> ArrayBuffer(CAD 交互预览)
- /* 交互式 CAD 查看器(@mlightcad/cad-simple-viewer 单文件 ESM,与 QuotePilot/rag 同款) */
- let cadHost = null; // 复用的 canvas 容器
- let cadManagerPromise = null; // manager 单例
- function getCadManager(parent) {
- if (!cadHost) {
- cadHost = document.createElement('div');
- cadHost.className = 'cad-canvas-host';
- }
- if (!cadHost.isConnected) parent.appendChild(cadHost);
- if (!cadManagerPromise) {
- cadManagerPromise = import('../vendor/cad-viewer.esm.js?v=1.7.0').then(function (mod) {
- mod.AcApDocManager.createInstance({
- container: cadHost,
- busyIndicatorHost: cadHost,
- autoResize: true,
- useMainThreadDraw: true, // 无 worker 文件,主线程渲染(刀版图很小,足够)
- disableExport: true
- });
- return mod.AcApDocManager.instance;
- }).catch(function (err) {
- cadManagerPromise = null;
- throw err;
- });
- }
- return cadManagerPromise;
- }
- function fetchDxfBuffer(no) {
- if (dxfBufferCache.has(no)) return Promise.resolve(dxfBufferCache.get(no));
- return fetch('/api/admin/orders/' + no + '/dxf', {
- headers: { Authorization: 'Bearer ' + PL.api.token() }
- }).then(function (res) {
- if (!res.ok) return res.json().catch(function () { return {}; }).then(function (d) {
- throw new Error(d.detail || 'CAD 图纸获取失败');
- });
- return res.arrayBuffer();
- }).then(function (buf) {
- dxfBufferCache.set(no, buf);
- return buf;
- });
- }
- /* ---------------- 数据加载 ---------------- */
- function boot() {
- if (!PL.api.token()) { state.booted = true; render(); return; }
- PL.api.get('/auth/me').then(function (u) {
- if (u.role === 'admin' || u.role === 'factory') {
- state.admin = u;
- state.view = u.role === 'factory' ? 'orders' : 'dashboard';
- if (u.role === 'factory') loadOrders();
- else loadDashboard();
- } else {
- PL.api.setToken('');
- UI.message.warning('该账号无后台权限');
- }
- state.booted = true; render();
- }, function () { state.booted = true; render(); });
- }
- function doLogin() {
- if (!state.login.username || !state.login.password) {
- UI.message.warning('请输入用户名和密码');
- return;
- }
- state.login.busy = true; render();
- PL.api.post('/auth/admin/login', { username: state.login.username, password: state.login.password }).then(function (r) {
- PL.api.setToken(r.token);
- state.admin = r.user;
- state.login = { username: '', password: '', busy: false };
- if (r.user.role === 'factory') {
- state.view = 'orders';
- loadOrders();
- } else {
- loadDashboard();
- }
- render();
- }, function (err) {
- state.login.busy = false;
- UI.message.error(err.message || '登录失败');
- render();
- });
- }
- function logout() {
- PL.api.setToken('');
- state.admin = null;
- render();
- }
- function loadDashboard() {
- PL.api.get('/admin/stats').then(function (s) { state.stats = s; render(); });
- PL.api.get('/admin/orders?page=1&page_size=8').then(function (r) { state.recent = r.items || []; render(); });
- }
- function loadOrders() {
- const f = state.orders.filter;
- const q = apiBase() + '/orders?page=' + state.orders.page + '&page_size=' + state.orders.pageSize +
- (f.type ? '&type=' + f.type : '') +
- (f.status ? '&status=' + f.status : '') +
- (!isFactory() && f.pay ? '&pay_status=' + f.pay : '') +
- (!isFactory() && f.userId ? '&user_id=' + f.userId : '') +
- (f.query ? '&query=' + encodeURIComponent(f.query) : '');
- state.orders.loading = true; render();
- PL.api.get(q).then(function (r) {
- state.orders.items = r.items || [];
- state.orders.total = r.total || 0;
- state.orders.loading = false;
- render();
- }, function (err) {
- state.orders.loading = false;
- UI.message.error(err.message || '订单加载失败');
- render();
- });
- }
- function loadUsers() {
- state.users.loading = true; render();
- PL.api.get('/admin/users?page=' + state.users.page + '&page_size=' + state.users.pageSize +
- (state.users.query ? '&query=' + encodeURIComponent(state.users.query) : '')).then(function (r) {
- state.users.items = r.items || [];
- state.users.total = r.total || 0;
- state.users.loading = false;
- render();
- }, function (err) {
- state.users.loading = false;
- UI.message.error(err.message || '用户加载失败');
- render();
- });
- }
- function loadAiConfig() {
- PL.api.get('/admin/ai-config').then(function (r) {
- state.aiConfig = Object.assign({}, state.aiConfig, r, { loaded: true, saving: false, testing: false, testResult: null });
- render();
- }, function (err) {
- UI.message.error(err.message || '配置加载失败');
- render();
- });
- }
- function saveAiConfig() {
- const c = state.aiConfig;
- c.saving = true; c.testResult = null; render();
- PL.api.request('PUT', '/admin/ai-config', {
- base_url: c.baseUrl, model: c.model, api_key: c.newKey || ''
- }).then(function () {
- c.saving = false; c.newKey = '';
- UI.message.success('AI 配置已保存');
- loadAiConfig();
- }, function (err) {
- c.saving = false;
- UI.message.error(err.message || '保存失败');
- render();
- });
- }
- function testAiConfig() {
- const c = state.aiConfig;
- c.testing = true; c.testResult = null; render();
- PL.api.post('/admin/ai-config/test').then(function (r) {
- c.testing = false;
- c.testResult = r;
- render();
- }, function (err) {
- c.testing = false;
- c.testResult = { ok: false, error: err.message || '测试失败' };
- render();
- });
- }
- function AiConfigView() {
- const c = state.aiConfig;
- if (!c.loaded) {
- return h('div', { style: { padding: 80, textAlign: 'center' } }, h(A.Spin, null));
- }
- return h('div', null,
- h(A.Alert, {
- type: c.configured ? 'success' : 'warning', showIcon: true, style: { marginBottom: 16 },
- message: c.configured ? 'AI 排版已启用(模型 ' + c.model + ')' : 'AI 排版未启用:未配置 API Key',
- description: '配置存于数据库(后台即时生效,优先于部署环境变量)。支持任意 OpenAI 兼容接口:智谱 / ModelScope / DeepSeek / 自建 vLLM 等。'
- }),
- h('div', { className: 'pl-admin-card', style: { maxWidth: 640 } },
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, 'API 地址(Base URL,如 https://open.bigmodel.cn/api/paas/v4)'),
- h(A.Input, { value: c.baseUrl, placeholder: 'https://open.bigmodel.cn/api/paas/v4',
- onChange: function (e) { c.baseUrl = e.target.value; render(); } }),
- h('div', { style: { fontSize: 12, color: '#7d7466', margin: '12px 0 4px' } }, '模型名(如 glm-4-flash / glm-4.6 / deepseek-chat)'),
- h(A.Input, { value: c.model, placeholder: 'glm-4-flash',
- onChange: function (e) { c.model = e.target.value; render(); } }),
- h('div', { style: { fontSize: 12, color: '#7d7466', margin: '12px 0 4px' } },
- 'API Key' + (c.hasKey ? '(当前:' + c.apiKeyMasked + ',留空则不修改)' : '(未配置)')),
- h(A.Input.Password, { value: c.newKey || '', placeholder: c.hasKey ? '留空保持不变' : '粘贴 API Key',
- onChange: function (e) { c.newKey = e.target.value; render(); } }),
- h('div', { style: { display: 'flex', gap: 10, marginTop: 18 } },
- h(A.Button, { type: 'primary', loading: c.saving, onClick: saveAiConfig }, '保存配置'),
- h(A.Button, { loading: c.testing, onClick: testAiConfig, disabled: !c.hasKey && !c.newKey }, '测试连通')),
- c.testResult ? h(A.Alert, {
- type: c.testResult.ok ? 'success' : 'error', showIcon: true, style: { marginTop: 14 },
- message: c.testResult.ok ? ('连通成功 · ' + (c.testResult.model || '') + ' · 回复: ' + (c.testResult.reply || ''))
- : ('连通失败:' + (c.testResult.error || '未知错误'))
- }) : null),
- h('div', { className: 'pl-admin-card', style: { maxWidth: 640, marginTop: 14 } },
- h('b', { style: { fontSize: 13.5 } }, '用量说明'),
- h('p', { style: { fontSize: 12.5, color: '#7d7466', lineHeight: 1.8, margin: '8px 0 0' } },
- '· 每位用户默认 20 次,在「用户管理 → AI 额度」按人调整(设 0 禁用)', h('br'),
- '· 用户每次成功生成扣 1 次,失败不扣;仪表盘显示"今日 AI 排版"', h('br'),
- '· Key 仅存储在服务端数据库,界面只回显打码值'))
- );
- }
- function loadFactories() {
- state.factories.loading = true; render();
- PL.api.get('/admin/factory-accounts').then(function (r) {
- state.factories.items = r.items || [];
- state.factories.loading = false;
- render();
- }, function (err) {
- state.factories.loading = false;
- UI.message.error(err.message || '工厂账号加载失败');
- render();
- });
- }
- function saveFactoryAccount() {
- const m = state.facModal;
- if (m.isCreate) {
- if (!m.username || !m.password) { UI.message.warning('请填写用户名和密码'); return; }
- } else if (m.password && m.password.length < 6) {
- UI.message.warning('新密码至少 6 位'); return;
- }
- m.busy = true; render();
- const req = m.isCreate
- ? PL.api.post('/admin/factory-accounts', { username: m.username, password: m.password, name: m.name })
- : PL.api.patch('/admin/factory-accounts/' + m.id, {
- name: m.name || undefined,
- password: m.password || undefined
- });
- req.then(function () {
- m.busy = false; m.open = false;
- UI.message.success(m.isCreate ? '工厂账号已创建' : '已保存');
- loadFactories();
- }, function (err) {
- m.busy = false;
- UI.message.error(err.message || '保存失败');
- render();
- });
- }
- function openQuotaModal(u) {
- state.quotaModal = { open: true, user: u, quota: u.aiQuota == null ? 20 : u.aiQuota, busy: false };
- render();
- }
- function saveQuota(reset) {
- const m = state.quotaModal;
- m.busy = true; render();
- PL.api.patch('/admin/users/' + m.user.id, {
- ai_quota: m.quota,
- ai_used: reset ? 0 : undefined
- }).then(function () {
- m.busy = false; m.open = false;
- UI.message.success(reset ? '额度已保存且用量已清零' : '额度已保存');
- loadUsers();
- }, function (err) {
- m.busy = false;
- UI.message.error(err.message || '保存失败');
- render();
- });
- }
- function QuotaModal() {
- const m = state.quotaModal;
- if (!m.user) return null;
- return h(A.Modal, {
- open: m.open, width: 420, title: 'AI 排版额度 · ' + (m.user.name || m.user.phone),
- footer: null, onCancel: function () { m.open = false; render(); }
- },
- h('p', { style: { fontSize: 12.5, color: '#7d7466', margin: '0 0 10px' } },
- '已用 ' + (m.user.aiUsed || 0) + ' 次。设为 0 表示禁止该用户使用 AI 排版。'),
- h(A.InputNumber, { value: m.quota, min: 0, max: 100000, style: { width: '100%' },
- onChange: function (v) { m.quota = v || 0; render(); } }),
- h('div', { style: { display: 'flex', gap: 8, marginTop: 14, justifyContent: 'flex-end' } },
- h(A.Button, { onClick: function () { m.open = false; render(); } }, '取消'),
- h(A.Button, { onClick: function () { saveQuota(true); } }, '保存并清零用量'),
- h(A.Button, { type: 'primary', loading: m.busy, onClick: function () { saveQuota(false); } }, '保存'))
- );
- }
- function toggleFactoryAccount(u) {
- const next = u.status === 'active' ? 'disabled' : 'active';
- PL.api.patch('/admin/factory-accounts/' + u.id, { status: next }).then(function () {
- UI.message.success(next === 'active' ? '已启用' : '已禁用');
- loadFactories();
- }, function (err) { UI.message.error(err.message || '操作失败'); });
- }
- function adminPreview(no, key) {
- const k = no + ':' + key;
- if (previewCache.has(k)) return previewCache.get(k);
- fetch('/api/admin/orders/' + no + '/preview/' + key, {
- headers: { Authorization: 'Bearer ' + PL.api.token() }
- }).then(function (res) { return res.ok ? res.blob() : null; }).then(function (blob) {
- previewCache.set(k, blob ? URL.createObjectURL(blob) : null);
- render();
- }).catch(function () { previewCache.set(k, null); });
- return null;
- }
- function openOrder(no) {
- state.drawer = { open: true, no: no, data: null,
- form: { status: '', pay: '', adminNote: '', carrier: '', trackingNo: '' },
- saveBusy: false, shipBusy: false, replyText: '', replyBusy: false };
- render();
- PL.api.get(apiBase() + '/orders/' + no).then(function (d) {
- state.drawer.data = d;
- state.drawer.form = {
- status: d.status, pay: d.payStatus, adminNote: d.adminNote || '',
- carrier: d.carrier || '', trackingNo: d.trackingNo || '', assignedTo: d.assignedTo || 0
- };
- if (!isFactory() && !state.factories.items.length) loadFactories();
- render();
- (d.previews || []).forEach(function (key) { adminPreview(no, key); });
- }, function (err) {
- state.drawer.open = false;
- UI.message.error(err.message || '详情加载失败');
- render();
- });
- }
- /* ---------------- 工厂协作:反馈线程 / 邮件 ---------------- */
- function postReply() {
- const dw = state.drawer;
- const text = (dw.replyText || '').trim();
- if (!text) {
- UI.message.warning('请填写反馈/回复内容');
- return;
- }
- dw.replyBusy = true; render();
- PL.api.post(apiBase() + '/orders/' + dw.no + '/messages', { content: text }).then(function (r) {
- dw.replyBusy = false;
- dw.replyText = '';
- if (dw.data) dw.data.messages = r.messages || [];
- UI.message.success(isFactory() ? '反馈已提交,等待平台处理' : '回复已发送');
- render();
- }, function (err) {
- dw.replyBusy = false;
- UI.message.error(err.message || '提交失败');
- render();
- });
- }
- function emailTemplate(d, msg) {
- // 只写正文:订单号/金额/页头页脚/按钮由服务端品牌模板自动包装
- return {
- subject: '【Steady】订单 ' + d.orderNo + ' 设计问题确认',
- body: d.contactName + ',您好:\n\n' +
- '您的订单「' + (d.summary || d.orderNo) + '」在印前生产检查中,工厂反馈了以下问题:\n\n' +
- '—————— 工厂反馈 ——————\n' + (msg.content || '') + '\n——————————————\n\n' +
- '请您回复本邮件确认处理方式,或点击下方按钮登录「我的订单」查看进度。如需修改设计,可重新进入设计工作室调整后再次提交。'
- };
- }
- function openEmailComposer(d, msg) {
- if (!d.contactEmail) {
- UI.message.warning('该订单未留邮箱,可编辑存档内容供其他渠道使用');
- }
- const t = emailTemplate(d, msg);
- state.emailModal = { open: true, messageId: msg.id, orderNo: d.orderNo,
- to: d.contactEmail || '(未留邮箱)', subject: t.subject, body: t.body,
- busy: false, tab: 'edit', previewHtml: '', previewBusy: false };
- render();
- }
- function sendEmail() {
- const m = state.emailModal;
- if (!m.subject.trim() || !m.body.trim()) {
- UI.message.warning('请填写邮件主题与内容');
- return;
- }
- m.busy = true; render();
- PL.api.post('/admin/orders/' + m.orderNo + '/messages/' + m.messageId + '/email',
- { subject: m.subject, body: m.body }).then(function (r) {
- m.busy = false; m.open = false;
- if (state.drawer.data) state.drawer.data.messages = r.messages || [];
- if (r.emailStatus === 'sent') UI.message.success('邮件已发送给用户');
- else if (r.hasEmail === false) UI.message.warning('该订单未留邮箱,内容已存档到反馈线程');
- else UI.message.warning(r.smtpConfigured ? ('发送失败已存档:' + (r.error || '')) : 'SMTP 未配置,内容已存档(可复制到其他渠道发送)');
- render();
- }, function (err) {
- m.busy = false;
- UI.message.error(err.message || '发送失败');
- render();
- });
- }
- function loadEmailPreview() {
- const m = state.emailModal;
- if (m.previewHtml || m.previewBusy) return;
- m.previewBusy = true; render();
- let token = '';
- try { token = localStorage.getItem('pouchlab.token.v1') || ''; } catch (e) {}
- fetch('/api/admin/orders/' + m.orderNo + '/email/preview', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
- body: JSON.stringify({ subject: m.subject, body: m.body })
- }).then(function (res) {
- if (!res.ok) throw new Error('preview ' + res.status);
- return res.text();
- }).then(function (html) {
- m.previewBusy = false; m.previewHtml = html; render();
- }).catch(function () {
- m.previewBusy = false; render();
- UI.message.error('预览加载失败');
- });
- }
- function switchEmailTab(key) {
- const m = state.emailModal;
- m.tab = key;
- if (key === 'preview') { m.previewHtml = ''; loadEmailPreview(); }
- render();
- }
- function saveOrder() {
- const f = state.drawer.form;
- state.drawer.saveBusy = true; render();
- PL.api.patch('/admin/orders/' + state.drawer.no, {
- status: f.status, pay_status: f.pay, admin_note: f.adminNote,
- assigned_to: f.assignedTo || undefined,
- clear_assignment: f.assignedTo ? undefined : (state.drawer.data && state.drawer.data.assignedTo ? true : undefined)
- }).then(function (d) {
- state.drawer.saveBusy = false;
- state.drawer.data = d;
- UI.message.success('已保存');
- loadOrders();
- loadDashboard();
- }, function (err) {
- state.drawer.saveBusy = false;
- UI.message.error(err.message || '保存失败');
- render();
- });
- }
- function shipOrder() {
- const f = state.drawer.form;
- if (!f.carrier || !f.trackingNo) {
- UI.message.warning('请填写快递公司和运单号');
- return;
- }
- state.drawer.shipBusy = true; render();
- PL.api.post('/admin/orders/' + state.drawer.no + '/ship', {
- carrier: f.carrier, tracking_no: f.trackingNo
- }).then(function (d) {
- state.drawer.shipBusy = false;
- state.drawer.data = d;
- state.drawer.form.status = d.status;
- UI.message.success('已发货并通知用户');
- loadOrders(); loadDashboard();
- }, function (err) {
- state.drawer.shipBusy = false;
- UI.message.error(err.message || '发货失败');
- render();
- });
- }
- function toggleUser(u) {
- const next = u.status === 'active' ? 'disabled' : 'active';
- PL.api.patch('/admin/users/' + u.id, { status: next }).then(function () {
- UI.message.success(next === 'active' ? '已启用' : '已禁用');
- loadUsers();
- }, function (err) { UI.message.error(err.message || '操作失败'); });
- }
- function openCadPreview(no) {
- state.cadModal = { open: true, no: no, loading: true, error: null };
- render();
- setTimeout(function () { mountCadPreview(no); }, 60); // 等 Modal 挂载到 DOM
- }
- function mountCadPreview(no) {
- const hostWrap = document.getElementById('cadPreviewHost');
- if (!hostWrap) return;
- Promise.all([getCadManager(hostWrap), fetchDxfBuffer(no)]).then(function (results) {
- const manager = results[0];
- const buffer = results[1];
- return manager.openDocument(no + '-cad.dxf', buffer, { progressiveRendering: true }).then(function () {
- manager.curView.zoomToSmartExtents(5000);
- if (state.cadModal.no === no) {
- state.cadModal.loading = false;
- render();
- }
- });
- }).catch(function (err) {
- if (state.cadModal.no === no) {
- state.cadModal.open = false;
- state.cadModal.loading = false;
- render();
- }
- UI.message.error(err && err.message ? err.message : 'CAD 预览加载失败');
- });
- }
- function downloadDxf(no) {
- no = no || state.drawer.no || state.cadModal.no;
- UI.message.loading({ content: '正在生成 CAD 图纸…', key: 'dxf', duration: 0 });
- PL.api.download('/admin/orders/' + no + '/dxf', no + '-cad.dxf').then(function () {
- UI.message.success({ content: 'CAD 图纸已下载', key: 'dxf' });
- }, function (err) {
- UI.message.error({ content: err.message || '生成失败', key: 'dxf' });
- });
- }
- function downloadDesign(no) {
- no = no || state.drawer.no;
- PL.api.download('/admin/orders/' + no + '/design', no + '-design.json').then(function () {}, function (err) {
- UI.message.error(err.message || '下载失败');
- });
- }
- function downloadProductionPdf(no) {
- no = no || state.drawer.no;
- UI.message.loading({ content: '正在生成生产图纸…', key: 'ppdf', duration: 0 });
- PL.api.download('/admin/orders/' + no + '/pdf', no + '-生产图纸.pdf').then(function () {
- UI.message.success({ content: '生产图纸已下载', key: 'ppdf' });
- }, function (err) {
- UI.message.error({ content: err.message || '生成失败', key: 'ppdf' });
- });
- }
- function downloadVectorPdf(no) {
- no = no || state.drawer.no;
- PL.api.download('/admin/orders/' + no + '/vector-pdf', no + '-刀版1to1.pdf').then(function () {}, function (err) {
- UI.message.error(err.message || '生成失败');
- });
- }
- function downloadEps(no) {
- no = no || state.drawer.no;
- PL.api.download('/admin/orders/' + no + '/eps', no + '-刀版1to1.eps').then(function () {
- UI.message.success({ content: 'EPS 已下载:CorelDRAW 打开后「另存为 CDR」即得 .cdr 文件', duration: 5 });
- }, function (err) {
- UI.message.error(err.message || '生成失败');
- });
- }
- /* ---------------- 视图 ---------------- */
- function LoginView() {
- return h('div', { className: 'pl-admin-login' },
- h('div', { className: 'pl-admin-login-card' },
- h('div', { className: 'pl-admin-login-brand' },
- h('img', { className: 'pl-admin-login-logo', src: 'assets/img/brand/steady-logo-full.png', alt: 'Steady Packaging' }),
- h('div', null,
- h('div', { className: 'pl-admin-login-title' }, '后台管理'),
- h('small', { style: { color: '#a79d8d', letterSpacing: '0.12em', fontSize: 10 } }, 'ADMIN CONSOLE'))),
- h(A.Form, { layout: 'vertical', onFinish: doLogin },
- h(A.Form.Item, { label: '用户名', style: { marginBottom: 14 } },
- h(A.Input, {
- value: state.login.username, size: 'large', placeholder: '管理员账号',
- onChange: function (e) { state.login.username = e.target.value; render(); }
- })),
- h(A.Form.Item, { label: '密码', style: { marginBottom: 20 } },
- h(A.Input.Password, {
- value: state.login.password, size: 'large', placeholder: '密码',
- onChange: function (e) { state.login.password = e.target.value; render(); }
- })),
- h(A.Button, { type: 'primary', htmlType: 'submit', size: 'large', block: true,
- loading: state.login.busy }, '登 录')),
- h('p', { style: { fontSize: 11, color: '#c3baa9', textAlign: 'center', marginTop: 16 } },
- '默认账号 admin / admin123,登录后请尽快修改密码')
- )
- );
- }
- function StatusTag(v) { const m = statusMeta(v); return h(A.Tag, { color: m.color }, m.label); }
- function PayTag(v) { const m = payMeta(v); return h(A.Tag, { color: m.color }, m.label); }
- function DashboardView() {
- const s = state.stats || {};
- const cards = [
- { num: s.ordersTotal, lbl: '订单总数' },
- { num: s.ordersToday, lbl: '今日新增订单' },
- { num: s.pendingShip, lbl: '待发货' },
- { num: fmtMoney(s.revenue), lbl: '已支付金额' },
- { num: s.usersTotal, lbl: '注册用户' },
- { num: s.aiCallsToday != null ? s.aiCallsToday : '-', lbl: '今日 AI 排版' }
- ];
- const cols = [
- { title: '订单号', dataIndex: 'orderNo', render: function (v, r) { return h('a', { onClick: function () { openOrder(v); } }, v); } },
- { title: '类型', dataIndex: 'type', width: 80, render: function (v) { return TYPE_LABEL[v] || v; } },
- { title: '规格', dataIndex: 'summary', ellipsis: true },
- { title: '金额', dataIndex: 'total', width: 100, render: fmtMoney },
- { title: '支付', dataIndex: 'payStatus', width: 90, render: PayTag },
- { title: '状态', dataIndex: 'status', width: 90, render: StatusTag },
- { title: '下单时间', dataIndex: 'createdAt', width: 110, render: fmtTime }
- ];
- return h('div', null,
- h('div', { className: 'pl-admin-stat-grid' },
- cards.map(function (c, i) {
- return h('div', { className: 'pl-admin-card pl-admin-stat', key: i },
- h('span', { className: 'num' }, c.num == null ? '-' : c.num),
- h('span', { className: 'lbl' }, c.lbl));
- })),
- h('div', { className: 'pl-admin-card' },
- h('div', { style: { display: 'flex', alignItems: 'center', marginBottom: 12 } },
- h('b', { style: { fontSize: 15 } }, '最新订单'),
- h('span', { style: { flex: 1 } }),
- h(A.Button, { size: 'small', type: 'link', onClick: function () { state.view = 'orders'; loadOrders(); render(); } }, '全部订单 →')),
- h(A.Table, {
- columns: cols, dataSource: state.recent, rowKey: 'orderNo',
- size: 'small', pagination: false, loading: !state.stats && !state.recent.length
- }))
- );
- }
- function OrdersView() {
- const f = state.orders.filter;
- const cols = [
- { title: '订单号', dataIndex: 'orderNo', width: 150, render: function (v) { return h('a', { onClick: function () { openOrder(v); } }, v); } },
- { title: '类型', dataIndex: 'type', width: 76, render: function (v) { return TYPE_LABEL[v] || v; } },
- { title: '规格摘要', dataIndex: 'summary', ellipsis: true },
- { title: '数量', dataIndex: 'spec', width: 70, render: function (s) { return s && s.qty ? s.qty : '-'; } },
- { title: '金额', dataIndex: 'total', width: 96, render: function (v) { return h('b', null, fmtMoney(v)); } },
- { title: '支付', dataIndex: 'payStatus', width: 86, render: PayTag },
- { title: '状态', dataIndex: 'status', width: 86, render: StatusTag },
- { title: '联系人', dataIndex: 'contactName', width: 90, render: function (v, r) { return v + ' / ' + (r.contactPhone || '-'); } },
- { title: '下单', dataIndex: 'createdAt', width: 100, render: fmtTime },
- { title: '操作', key: 'act', width: 170, render: function (_, r) {
- return h(A.Space, { size: 4 },
- h(A.Button, { size: 'small', onClick: function () { openOrder(r.orderNo); } }, '详情'),
- h(A.Button, { size: 'small', onClick: function () { openCadPreview(r.orderNo); } }, 'CAD'));
- } }
- ];
- return h('div', null,
- h('div', { className: 'pl-admin-card', style: { marginBottom: 14, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' } },
- h(A.Select, { value: f.type, style: { width: 110 }, placeholder: '类型',
- allowClear: true, options: [{ value: 'bag', label: '包装袋' }, { value: 'box', label: '纸盒' }],
- onChange: function (v) { f.type = v || ''; state.orders.page = 1; loadOrders(); } }),
- h(A.Select, { value: f.status, style: { width: 110 }, placeholder: '订单状态',
- allowClear: true, options: STATUS.map(function (s) { return { value: s.value, label: s.label }; }),
- onChange: function (v) { f.status = v || ''; state.orders.page = 1; loadOrders(); } }),
- isFactory() ? null : h(A.Select, { value: f.pay, style: { width: 110 }, placeholder: '支付状态',
- allowClear: true, options: PAYS.map(function (s) { return { value: s.value, label: s.label }; }),
- onChange: function (v) { f.pay = v || ''; state.orders.page = 1; loadOrders(); } }),
- h(A.Input.Search, { value: f.query, style: { width: isFactory() ? 250 : 250 }, placeholder: isFactory() ? '搜索订单号' : '搜索订单号 / 联系人 / 手机号',
- allowClear: true,
- onChange: function (e) { f.query = e.target.value; render(); },
- onSearch: function () { state.orders.page = 1; loadOrders(); } }),
- !isFactory() && f.userId ? h(A.Tag, { closable: true, onClose: function () { f.userId = 0; f.userName = ''; state.orders.page = 1; loadOrders(); } },
- '用户:' + (f.userName || f.userId)) : null
- ),
- h('div', { className: 'pl-admin-card' },
- h(A.Table, {
- columns: cols, dataSource: state.orders.items, rowKey: 'orderNo',
- size: 'small', loading: state.orders.loading,
- pagination: {
- current: state.orders.page, total: state.orders.total, pageSize: state.orders.pageSize,
- showSizeChanger: false, showTotal: function (t) { return '共 ' + t + ' 单'; },
- onChange: function (p) { state.orders.page = p; loadOrders(); }
- }
- }))
- );
- }
- function UsersView() {
- const userCols = [
- { title: 'ID', dataIndex: 'id', width: 60 },
- { title: '邮箱', dataIndex: 'email', width: 180, render: function (v) { return v || '—'; } },
- { title: '手机号(旧)', dataIndex: 'phone', width: 120, render: function (v) { return v || '—'; } },
- { title: '昵称', dataIndex: 'name', width: 120 },
- { title: '订单数', dataIndex: 'orderCount', width: 80 },
- { title: '消费额', dataIndex: 'paidTotal', width: 100, render: fmtMoney },
- { title: 'AI 用量', dataIndex: 'aiUsed', width: 100, render: function (_, u) {
- return (u.aiUsed || 0) + ' / ' + (u.aiQuota == null ? 20 : u.aiQuota);
- } },
- { title: '状态', dataIndex: 'status', width: 90, render: function (v) {
- return h(A.Tag, { color: v === 'active' ? 'success' : 'error' }, v === 'active' ? '正常' : '已禁用');
- } },
- { title: '注册时间', dataIndex: 'createdAt', width: 120, render: fmtTime },
- { title: '操作', key: 'act', width: 250, render: function (_, u) {
- return h(A.Space, { size: 4 },
- h(A.Button, { size: 'small', onClick: function () { toggleUser(u); } }, u.status === 'active' ? '禁用' : '启用'),
- h(A.Button, { size: 'small', onClick: function () { openQuotaModal(u); } }, 'AI 额度'),
- h(A.Button, { size: 'small', type: 'link', onClick: function () {
- state.orders.filter.userId = u.id;
- state.orders.filter.userName = u.name || u.phone;
- state.orders.page = 1;
- state.view = 'orders';
- loadOrders();
- } }, '查看订单'));
- } }
- ];
- const facCols = [
- { title: 'ID', dataIndex: 'id', width: 60 },
- { title: '用户名', dataIndex: 'username', width: 130 },
- { title: '工厂名称', dataIndex: 'name', width: 160 },
- { title: '分配订单数', dataIndex: 'orderCount', width: 100 },
- { title: '状态', dataIndex: 'status', width: 90, render: function (v) {
- return h(A.Tag, { color: v === 'active' ? 'success' : 'error' }, v === 'active' ? '正常' : '已禁用');
- } },
- { title: '创建时间', dataIndex: 'createdAt', width: 120, render: fmtTime },
- { title: '操作', key: 'act', width: 260, render: function (_, u) {
- return h(A.Space, { size: 4 },
- h(A.Button, { size: 'small', onClick: function () { toggleFactoryAccount(u); } }, u.status === 'active' ? '禁用' : '启用'),
- h(A.Button, { size: 'small', onClick: function () {
- state.facModal = { open: true, id: u.id, username: u.username, name: u.name, password: '', busy: false, isCreate: false };
- render();
- } }, '改名/重置密码'));
- } }
- ];
- return h('div', { className: 'pl-admin-card' },
- h(A.Tabs, { items: [
- { key: 'users', label: '注册用户', children:
- h('div', null,
- h('div', { style: { display: 'flex', gap: 10, marginBottom: 14 } },
- h(A.Input.Search, { value: state.users.query, style: { width: 260 }, placeholder: '搜索手机号 / 邮箱 / 昵称',
- allowClear: true,
- onChange: function (e) { state.users.query = e.target.value; render(); },
- onSearch: function () { state.users.page = 1; loadUsers(); } })),
- h(A.Table, {
- columns: userCols, dataSource: state.users.items, rowKey: 'id',
- size: 'small', loading: state.users.loading,
- pagination: {
- current: state.users.page, total: state.users.total, pageSize: state.users.pageSize,
- showSizeChanger: false, showTotal: function (t) { return '共 ' + t + ' 位用户'; },
- onChange: function (p) { state.users.page = p; loadUsers(); }
- }
- })) },
- { key: 'factories', label: '工厂账号', children:
- h('div', null,
- h(A.Alert, { type: 'info', showIcon: true, style: { marginBottom: 14 },
- message: '一家协作工厂一个账号;订单在「订单详情 → 分配工厂」指定后,对应工厂才能看到该订单(用户隐私自动脱敏)' }),
- h('div', { style: { marginBottom: 14 } },
- h(A.Button, { type: 'primary', onClick: function () {
- state.facModal = { open: true, id: 0, username: '', name: '', password: '', busy: false, isCreate: true };
- render();
- } }, '+ 新建工厂账号')),
- h(A.Table, {
- columns: facCols, dataSource: state.factories.items, rowKey: 'id',
- size: 'small', loading: state.factories.loading, pagination: false
- })) }
- ], onChange: function (k) { if (k === 'factories' && !state.factories.items.length) loadFactories(); } })
- );
- }
- function FactoryAccountModal() {
- const m = state.facModal;
- return h(A.Modal, {
- open: m.open, width: 460,
- title: m.isCreate ? '新建工厂账号' : '修改工厂账号(' + m.username + ')',
- okText: m.isCreate ? '创建' : '保存', cancelText: '取消',
- confirmLoading: m.busy,
- onOk: saveFactoryAccount,
- onCancel: function () { m.open = false; render(); }
- },
- m.isCreate ? h('div', { style: { marginBottom: 12 } },
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '登录用户名(3-30 位字母/数字/下划线)'),
- h(A.Input, { value: m.username, placeholder: '如 hangzhou-box',
- onChange: function (e) { m.username = e.target.value; render(); } })) : null,
- h('div', { style: { marginBottom: 12 } },
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '工厂名称(对外显示)'),
- h(A.Input, { value: m.name, placeholder: '如 杭州彩印包装厂',
- onChange: function (e) { m.name = e.target.value; render(); } })),
- h('div', null,
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } },
- m.isCreate ? '初始密码(至少 6 位)' : '重置密码(留空则不修改)'),
- h(A.Input.Password, { value: m.password, placeholder: '至少 6 位',
- onChange: function (e) { m.password = e.target.value; render(); } })),
- h('p', { style: { fontSize: 11, color: '#a79d8d', marginTop: 12 } },
- '工厂用此账号在 admin.html 登录,仅见分配给它的订单')
- );
- }
- function specRows(d) {
- const s = d.spec || {};
- const rows = [
- ['类型', TYPE_LABEL[d.type] || d.type],
- ['数量', (s.qty || '-') + ' 件'],
- ['摘要', d.summary || '-']
- ];
- if (d.type === 'bag') {
- rows.push(['袋型', s.productName || '-']);
- rows.push(['尺寸', (s.sizeLabel || '-') + '(' + (s.w || '-') + '×' + (s.h || '-') + ' mm)']);
- rows.push(['材质', s.materialName || '-']);
- rows.push(['工艺', s.finishName || '-']);
- } else {
- rows.push(['盒型', (s.boxName || '-') + '(' + (s.boxNo || '-') + ')']);
- rows.push(['内尺寸', (s.w || '-') + ' × ' + (s.d || '-') + ' × ' + (s.h || '-') + ' mm']);
- rows.push(['材质', (s.materialName || '-') + (s.thickness ? ' · 厚 ' + s.thickness + 'mm' : '')]);
- rows.push(['印色', s.printName || '-']);
- rows.push(['印刷方式', s.printWay || '-']);
- }
- const q = d.quote || {};
- rows.push(['单价', fmtMoney(q.unit || d.unitPrice)]);
- rows.push(['总额', h('b', { style: { color: '#ff5c2b' } }, fmtMoney(d.total))]);
- return rows;
- }
- function OrderDrawer() {
- const dw = state.drawer;
- const d = dw.data;
- const f = dw.form;
- return h(A.Drawer, {
- open: dw.open, width: 640, title: dw.no ? '订单 ' + dw.no : '订单详情',
- onClose: function () { dw.open = false; render(); }
- },
- !d ? h('div', { style: { padding: 80, textAlign: 'center' } }, h(A.Spin, null)) : h('div', null,
- (d.previews || []).length ? h('div', { className: 'pl-preview-grid' },
- d.previews.map(function (key) {
- const url = previewCache.get(d.orderNo + ':' + key);
- return url ? h(A.Image, { key: key, src: url, height: 150, style: { borderRadius: 10, border: '1px solid #efe9dc' } }) : null;
- })) : null,
- h(A.Descriptions, { title: '规格与金额', column: 2, size: 'small', bordered: true, style: { marginTop: 14 } },
- specRows(d).map(function (r, i) {
- return h(A.Descriptions.Item, { key: i, label: r[0], span: i === 2 || (d.type === 'bag' && i === 3) || (d.type === 'box' && i >= 3 && i <= 6) ? 2 : 1 }, r[1]);
- })),
- h(A.Descriptions, { title: '下单与联系', column: 1, size: 'small', bordered: true, style: { marginTop: 16 } },
- h(A.Descriptions.Item, { label: '用户' }, (d.ownerName || '-') + ' · ' + (d.ownerPhone || '-')),
- h(A.Descriptions.Item, { label: '联系人' }, d.contactName + ' · ' + d.contactPhone + (d.contactEmail ? ' · ' + d.contactEmail : '')),
- h(A.Descriptions.Item, { label: '收货地址' }, d.address || '-'),
- d.note ? h(A.Descriptions.Item, { label: '用户备注' }, d.note) : null),
- isFactory() ? null : h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '订单操作'),
- isFactory() ? null : h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 } },
- h('div', null,
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '订单状态'),
- h(A.Select, { value: f.status, style: { width: '100%' },
- options: STATUS.map(function (s) { return { value: s.value, label: s.label }; }),
- onChange: function (v) { f.status = v; render(); } })),
- h('div', null,
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '支付状态'),
- h(A.Select, { value: f.pay, style: { width: '100%' },
- options: PAYS.map(function (s) { return { value: s.value, label: s.label }; }),
- onChange: function (v) { f.pay = v; render(); } }))),
- isFactory() ? null : h('div', { style: { marginTop: 10 } },
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '分配工厂(分配后该工厂才能看到此订单)'),
- h(A.Select, {
- value: f.assignedTo || 0, style: { width: '100%' },
- options: [{ value: 0, label: '未分配' }].concat(state.factories.items.map(function (u) {
- return { value: u.id, label: (u.name || u.username) + (u.status === 'active' ? '' : '(已禁用)') };
- })),
- onChange: function (v) { f.assignedTo = v; render(); }
- })),
- isFactory() ? null : h('div', { style: { marginTop: 10 } },
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '管理员备注'),
- h(A.Input.TextArea, { value: f.adminNote, rows: 2, placeholder: '内部备注(用户不可见)',
- onChange: function (e) { f.adminNote = e.target.value; render(); } })),
- h('div', { style: { marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' } },
- isFactory() ? null : h(A.Button, { type: 'primary', loading: dw.saveBusy, onClick: saveOrder }, '保存修改'),
- h(A.Button, { type: 'primary', ghost: !isFactory(), onClick: function () { downloadProductionPdf(d.orderNo); } }, '生产图纸 PDF'),
- h(A.Tooltip, { title: 'mm 实尺矢量刀版,CorelDRAW/Illustrator 可直接打开编辑(CDR 交付替代)' },
- h(A.Button, { onClick: function () { downloadVectorPdf(d.orderNo); } }, '矢量刀版 1:1')),
- h(A.Tooltip, { title: 'EPS 矢量(CorelDRAW 原生导入,另存为 CDR 即得 .cdr 文件)' },
- h(A.Button, { onClick: function () { downloadEps(d.orderNo); } }, 'EPS(.cdr)')),
- h(A.Button, { onClick: function () { openCadPreview(d.orderNo); } }, 'CAD 预览'),
- h(A.Button, { onClick: function () { downloadDxf(d.orderNo); } }, 'DXF'),
- !isFactory() && d.hasDesign ? h(A.Button, { onClick: function () { downloadDesign(d.orderNo); } }, '设计稿') : null),
- isFactory() ? null : h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '物流发货'),
- isFactory() ? null : h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1.4fr auto', gap: 10, alignItems: 'center' } },
- h(A.Input, { value: f.carrier, placeholder: '快递公司(如 顺丰速运)',
- onChange: function (e) { f.carrier = e.target.value; render(); } }),
- h(A.Input, { value: f.trackingNo, placeholder: '运单号',
- onChange: function (e) { f.trackingNo = e.target.value; render(); } }),
- h(A.Button, { type: 'primary', ghost: true, loading: dw.shipBusy, onClick: shipOrder,
- disabled: d.status === 'cancelled' }, '发货')),
- isFactory() || !d.trackingNo ? null : h('div', { style: { marginTop: 8, fontSize: 12, color: '#7d7466' } },
- '当前物流:' + d.carrier + ' · ' + d.trackingNo),
- /* 工厂协作:反馈线程(工厂提交 / 管理员回复 / 邮件通知用户) */
- h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } },
- isFactory() ? '设计问题反馈' : '工厂协作'),
- h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
- (d.messages || []).length ? (d.messages || []).map(function (m) {
- const isFac = m.senderRole === 'factory';
- return h('div', { key: m.id, style: {
- background: isFac ? '#fff7f0' : '#f4f8f2',
- border: '1px solid ' + (isFac ? '#ffd9c2' : '#dce8d4'),
- borderRadius: 10, padding: '8px 10px'
- } },
- h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } },
- h('b', { style: { color: isFac ? '#c2610f' : '#4f6b2f' } },
- isFac ? '🏭 ' + (m.senderName || '工厂') : '🛠 ' + (m.senderName || '管理员')),
- ' ' + fmtTime(m.createdAt)),
- h('div', { style: { whiteSpace: 'pre-wrap', fontSize: 13 } }, m.content),
- m.emailStatus ? h('div', { style: { marginTop: 6, padding: '6px 8px', background: '#fffdf8', borderRadius: 6, fontSize: 12 } },
- '📧 ',
- m.emailStatus === 'sent' ? '已发送邮件至 ' + m.emailTo
- : m.emailStatus === 'archived' ? '邮件内容已存档(' + (m.emailTo || '未留邮箱') + ')'
- : m.emailStatus,
- h('div', { style: { color: '#a79d8d', marginTop: 2 } }, '主题:' + m.emailSubject)) : null,
- !isFactory() && isFac && !m.emailStatus ? h('div', { style: { marginTop: 6 } },
- h(A.Button, { size: 'small', type: 'primary', ghost: true,
- onClick: function () { openEmailComposer(d, m); } }, '✉ 邮件通知用户(模板)')) : null);
- }) : h('div', { style: { color: '#a79d8d', fontSize: 12.5 } },
- isFactory() ? '如发现设计问题(出血不足、图文越界、工艺冲突等),请在下方提交,平台会转达用户。'
- : '工厂的反馈会显示在这里,可选择将问题整理成邮件通知用户。')),
- h('div', { style: { display: 'flex', gap: 8, marginTop: 4 } },
- h(A.Input.TextArea, {
- value: dw.replyText, rows: 2,
- placeholder: isFactory() ? '描述设计问题(如:正面文字超出安全区 2mm,建议内移…)' : '回复工厂…',
- onChange: function (e) { dw.replyText = e.target.value; render(); }
- }),
- h(A.Button, { type: 'primary', loading: dw.replyBusy, onClick: postReply,
- style: { alignSelf: 'flex-end' } }, isFactory() ? '提交反馈' : '回复')),
- h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '操作时间线'),
- h(A.Timeline, {
- items: (d.events || []).slice().reverse().map(function (e) {
- return {
- color: e.kind === 'logistics' ? 'geekblue' : 'green',
- children: h('div', null,
- h('div', { style: { fontWeight: 600 } }, e.title + ' ', h('span', { style: { fontWeight: 400, fontSize: 11, color: '#a79d8d' } }, fmtTime(e.createdAt))),
- e.detail ? h('div', { style: { fontSize: 12, color: '#7d7466' } }, e.detail) : null)
- };
- })
- })
- )
- );
- }
- function EmailComposerModal() {
- const m = state.emailModal;
- const hasTo = m.to && m.to !== '(未留邮箱)';
- return h(A.Modal, {
- open: m.open, width: 760, title: '邮件通知用户',
- okText: m.tab === 'preview' ? '确认发送' : '发送', cancelText: '取消',
- confirmLoading: m.busy,
- onOk: sendEmail,
- onCancel: function () { m.open = false; render(); }
- },
- h(A.Alert, {
- type: hasTo ? 'success' : 'warning', showIcon: true, style: { marginBottom: 12 },
- message: hasTo ? ('收件人:' + m.to + ' · 发件人:Steady <mail@steadypackaging.com>')
- : ('收件人:' + m.to + ' — 订单未留邮箱,发送后内容将存档到反馈线程,可复制到其他渠道')
- }),
- h(A.Tabs, {
- activeKey: m.tab,
- onChange: switchEmailTab,
- items: [
- { key: 'edit', label: '编辑内容', children: [
- h('div', { key: 'l1', style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '邮件主题'),
- h(A.Input, { key: 's', value: m.subject,
- onChange: function (e) { m.subject = e.target.value; render(); } }),
- h('div', { key: 'l2', style: { fontSize: 12, color: '#7d7466', margin: '12px 0 4px' } }, '邮件正文(页头、订单卡片、按钮、页脚由系统模板自动生成)'),
- h(A.Input.TextArea, { key: 'b', value: m.body, rows: 14,
- onChange: function (e) { m.body = e.target.value; render(); } })
- ]},
- { key: 'preview', label: '预览效果', children:
- h('div', { style: { height: 460, borderRadius: 10, border: '1px solid #e6ddcd', overflow: 'hidden', background: '#f6f2e9', position: 'relative' } },
- m.previewBusy
- ? h('div', { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' } }, h(A.Spin, { tip: '渲染中…' }))
- : h('iframe', {
- title: '邮件预览', srcDoc: m.previewHtml,
- style: { width: '100%', height: '100%', border: 'none', background: '#f6f2e9' }
- }))
- }
- ]
- })
- );
- }
- function CadPreviewModal() {
- const m = state.cadModal;
- return h(A.Modal, {
- open: m.open, width: 1000, title: '工厂 CAD 图纸 ' + (m.no || ''),
- onCancel: function () { m.open = false; render(); },
- footer: h('div', null,
- h('span', { style: { float: 'left', color: '#a79d8d', fontSize: 12, lineHeight: '32px' } }, '滚轮缩放 · 拖拽平移 · 可点选图元查看图层'),
- h(A.Button, { onClick: function () { m.open = false; render(); } }, '关闭'),
- h(A.Button, { type: 'primary', style: { marginLeft: 8 }, onClick: function () { downloadDxf(m.no); } }, '下载 DXF'))
- },
- h('div', { id: 'cadPreviewHost', style: { position: 'relative', height: '68vh', background: '#fff', borderRadius: 8, overflow: 'hidden' } },
- m.loading ? h('div', { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', zIndex: 1, background: '#fffdf8' } },
- h(A.Spin, null)) : null)
- );
- }
- function App() {
- if (!state.booted) {
- return h('div', { style: { minHeight: '100vh', display: 'grid', placeItems: 'center' } }, h(A.Spin, null));
- }
- if (!state.admin) return LoginView();
- const fac = isFactory();
- const views = fac
- ? { orders: OrdersView }
- : { dashboard: DashboardView, orders: OrdersView, users: UsersView, aisetting: AiConfigView };
- const titles = fac
- ? { orders: '生产订单' }
- : { dashboard: '仪表盘', orders: '订单管理', users: '用户管理', aisetting: 'AI 设置' };
- if (!views[state.view]) state.view = 'orders';
- return h(A.Layout, { style: { minHeight: '100vh' } },
- h(A.Layout.Sider, { width: 208, className: 'pl-admin-sider', breakpoint: 'lg', collapsedWidth: 0 },
- h('div', { className: 'pl-admin-brand' },
- h('img', { className: 'pl-admin-brand-logo', src: 'assets/img/brand/steady-wordmark-light.png', alt: 'Steady Packaging' }),
- h('small', null, fac ? '工厂协作端 · FACTORY PARTNER' : '后台管理 · ADMIN')),
- h(A.Menu, {
- className: 'pl-admin-menu', theme: 'dark', mode: 'inline',
- selectedKeys: [state.view],
- onClick: function (e) {
- state.view = e.key;
- if (e.key === 'dashboard' && !state.stats) loadDashboard();
- if (e.key === 'orders' && !state.orders.items.length) loadOrders();
- if (e.key === 'users' && !state.users.items.length) loadUsers();
- if (e.key === 'aisetting' && !state.aiConfig.loaded) loadAiConfig();
- render();
- },
- items: fac
- ? [{ key: 'orders', label: '📦 生产订单' }]
- : [
- { key: 'dashboard', label: '📊 仪表盘' },
- { key: 'orders', label: '📦 订单管理' },
- { key: 'users', label: '👥 用户管理' },
- { key: 'aisetting', label: '🤖 AI 设置' }
- ]
- })),
- h(A.Layout, null,
- h(A.Layout.Header, { className: 'pl-admin-header', style: { background: '#fffdf8' } },
- h('span', { className: 'title' }, titles[state.view]),
- h('div', null,
- h('span', { style: { color: '#7d7466', fontSize: 12.5, marginRight: 12 } },
- (state.admin.name || state.admin.username) + (fac ? '(协作工厂)' : '(管理员)')),
- h(A.Button, { size: 'small', onClick: logout }, '退出'))),
- h(A.Layout.Content, { style: { padding: 20, overflow: 'initial' } },
- (views[state.view])(),
- OrderDrawer(),
- CadPreviewModal(),
- EmailComposerModal(),
- FactoryAccountModal(),
- QuotaModal()))
- );
- }
- function render() {
- UI.render(document.getElementById('root'), App());
- }
- document.addEventListener('pl:auth-expired', function () {
- if (state.admin) UI.message.warning('登录已失效,请重新登录');
- state.admin = null;
- render();
- });
- boot();
- })();
|