admin.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. /* POUCHLAB 后台管理:登录 / 仪表盘 / 订单管理(状态·支付·发货·CAD 导出)/ 用户管理 */
  2. (function () {
  3. const h = window.React.createElement;
  4. const A = window.PL.ui.antd;
  5. const UI = window.PL.ui;
  6. const dayjs = window.dayjs;
  7. const STATUS = [
  8. { value: 'pending_payment', label: '待支付', color: 'orange' },
  9. { value: 'producing', label: '生产中', color: 'processing' },
  10. { value: 'shipped', label: '已发货', color: 'geekblue' },
  11. { value: 'completed', label: '已完成', color: 'success' },
  12. { value: 'cancelled', label: '已取消', color: 'default' }
  13. ];
  14. const PAYS = [
  15. { value: 'unpaid', label: '未支付', color: 'orange' },
  16. { value: 'paid', label: '已支付', color: 'success' },
  17. { value: 'refunded', label: '已退款', color: 'purple' }
  18. ];
  19. const TYPE_LABEL = { bag: '包装袋', box: '纸盒' };
  20. const statusMeta = function (v) { return STATUS.find(function (s) { return s.value === v; }) || { label: v, color: 'default' }; };
  21. const payMeta = function (v) { return PAYS.find(function (s) { return s.value === v; }) || { label: v, color: 'default' }; };
  22. const fmtTime = function (ts) { return ts ? dayjs(ts * 1000).format('MM-DD HH:mm') : '-'; };
  23. const fmtMoney = function (n) { return '¥' + Number(n || 0).toFixed(2); };
  24. const state = {
  25. booted: false, admin: null,
  26. login: { username: '', password: '', busy: false },
  27. view: 'dashboard',
  28. stats: null, recent: [],
  29. orders: { items: [], total: 0, page: 1, pageSize: 10, loading: false,
  30. filter: { type: '', status: '', pay: '', query: '', userId: 0, userName: '' } },
  31. users: { items: [], total: 0, page: 1, pageSize: 10, loading: false, query: '' },
  32. factories: { items: [], loading: false },
  33. facModal: { open: false, id: 0, username: '', name: '', password: '', busy: false, isCreate: true },
  34. quotaModal: { open: false, user: null, quota: 0, busy: false },
  35. aiConfig: { loaded: false, baseUrl: '', model: '', apiKeyMasked: '', hasKey: false, configured: false, dbOverridden: {}, saving: false, testing: false, testResult: null },
  36. drawer: { open: false, no: null, data: null,
  37. form: { status: '', pay: '', adminNote: '', carrier: '', trackingNo: '' },
  38. saveBusy: false, shipBusy: false, replyText: '', replyBusy: false },
  39. cadModal: { open: false, no: null, url: null, loading: false },
  40. emailModal: { open: false, messageId: null, orderNo: null, to: '', subject: '', body: '', busy: false, tab: 'edit', previewHtml: '', previewBusy: false }
  41. };
  42. const isFactory = function () { return state.admin && state.admin.role === 'factory'; };
  43. const apiBase = function () { return isFactory() ? '/factory' : '/admin'; };
  44. const previewCache = new Map();
  45. const dxfBufferCache = new Map(); // orderNo -> ArrayBuffer(CAD 交互预览)
  46. /* 交互式 CAD 查看器(@mlightcad/cad-simple-viewer 单文件 ESM,与 QuotePilot/rag 同款) */
  47. let cadHost = null; // 复用的 canvas 容器
  48. let cadManagerPromise = null; // manager 单例
  49. function getCadManager(parent) {
  50. if (!cadHost) {
  51. cadHost = document.createElement('div');
  52. cadHost.className = 'cad-canvas-host';
  53. }
  54. if (!cadHost.isConnected) parent.appendChild(cadHost);
  55. if (!cadManagerPromise) {
  56. cadManagerPromise = import('../vendor/cad-viewer.esm.js?v=1.7.0').then(function (mod) {
  57. mod.AcApDocManager.createInstance({
  58. container: cadHost,
  59. busyIndicatorHost: cadHost,
  60. autoResize: true,
  61. useMainThreadDraw: true, // 无 worker 文件,主线程渲染(刀版图很小,足够)
  62. disableExport: true
  63. });
  64. return mod.AcApDocManager.instance;
  65. }).catch(function (err) {
  66. cadManagerPromise = null;
  67. throw err;
  68. });
  69. }
  70. return cadManagerPromise;
  71. }
  72. function fetchDxfBuffer(no) {
  73. if (dxfBufferCache.has(no)) return Promise.resolve(dxfBufferCache.get(no));
  74. return fetch('/api/admin/orders/' + no + '/dxf', {
  75. headers: { Authorization: 'Bearer ' + PL.api.token() }
  76. }).then(function (res) {
  77. if (!res.ok) return res.json().catch(function () { return {}; }).then(function (d) {
  78. throw new Error(d.detail || 'CAD 图纸获取失败');
  79. });
  80. return res.arrayBuffer();
  81. }).then(function (buf) {
  82. dxfBufferCache.set(no, buf);
  83. return buf;
  84. });
  85. }
  86. /* ---------------- 数据加载 ---------------- */
  87. function boot() {
  88. if (!PL.api.token()) { state.booted = true; render(); return; }
  89. PL.api.get('/auth/me').then(function (u) {
  90. if (u.role === 'admin' || u.role === 'factory') {
  91. state.admin = u;
  92. state.view = u.role === 'factory' ? 'orders' : 'dashboard';
  93. if (u.role === 'factory') loadOrders();
  94. else loadDashboard();
  95. } else {
  96. PL.api.setToken('');
  97. UI.message.warning('该账号无后台权限');
  98. }
  99. state.booted = true; render();
  100. }, function () { state.booted = true; render(); });
  101. }
  102. function doLogin() {
  103. if (!state.login.username || !state.login.password) {
  104. UI.message.warning('请输入用户名和密码');
  105. return;
  106. }
  107. state.login.busy = true; render();
  108. PL.api.post('/auth/admin/login', { username: state.login.username, password: state.login.password }).then(function (r) {
  109. PL.api.setToken(r.token);
  110. state.admin = r.user;
  111. state.login = { username: '', password: '', busy: false };
  112. if (r.user.role === 'factory') {
  113. state.view = 'orders';
  114. loadOrders();
  115. } else {
  116. loadDashboard();
  117. }
  118. render();
  119. }, function (err) {
  120. state.login.busy = false;
  121. UI.message.error(err.message || '登录失败');
  122. render();
  123. });
  124. }
  125. function logout() {
  126. PL.api.setToken('');
  127. state.admin = null;
  128. render();
  129. }
  130. function loadDashboard() {
  131. PL.api.get('/admin/stats').then(function (s) { state.stats = s; render(); });
  132. PL.api.get('/admin/orders?page=1&page_size=8').then(function (r) { state.recent = r.items || []; render(); });
  133. }
  134. function loadOrders() {
  135. const f = state.orders.filter;
  136. const q = apiBase() + '/orders?page=' + state.orders.page + '&page_size=' + state.orders.pageSize +
  137. (f.type ? '&type=' + f.type : '') +
  138. (f.status ? '&status=' + f.status : '') +
  139. (!isFactory() && f.pay ? '&pay_status=' + f.pay : '') +
  140. (!isFactory() && f.userId ? '&user_id=' + f.userId : '') +
  141. (f.query ? '&query=' + encodeURIComponent(f.query) : '');
  142. state.orders.loading = true; render();
  143. PL.api.get(q).then(function (r) {
  144. state.orders.items = r.items || [];
  145. state.orders.total = r.total || 0;
  146. state.orders.loading = false;
  147. render();
  148. }, function (err) {
  149. state.orders.loading = false;
  150. UI.message.error(err.message || '订单加载失败');
  151. render();
  152. });
  153. }
  154. function loadUsers() {
  155. state.users.loading = true; render();
  156. PL.api.get('/admin/users?page=' + state.users.page + '&page_size=' + state.users.pageSize +
  157. (state.users.query ? '&query=' + encodeURIComponent(state.users.query) : '')).then(function (r) {
  158. state.users.items = r.items || [];
  159. state.users.total = r.total || 0;
  160. state.users.loading = false;
  161. render();
  162. }, function (err) {
  163. state.users.loading = false;
  164. UI.message.error(err.message || '用户加载失败');
  165. render();
  166. });
  167. }
  168. function loadAiConfig() {
  169. PL.api.get('/admin/ai-config').then(function (r) {
  170. state.aiConfig = Object.assign({}, state.aiConfig, r, { loaded: true, saving: false, testing: false, testResult: null });
  171. render();
  172. }, function (err) {
  173. UI.message.error(err.message || '配置加载失败');
  174. render();
  175. });
  176. }
  177. function saveAiConfig() {
  178. const c = state.aiConfig;
  179. c.saving = true; c.testResult = null; render();
  180. PL.api.request('PUT', '/admin/ai-config', {
  181. base_url: c.baseUrl, model: c.model, api_key: c.newKey || ''
  182. }).then(function () {
  183. c.saving = false; c.newKey = '';
  184. UI.message.success('AI 配置已保存');
  185. loadAiConfig();
  186. }, function (err) {
  187. c.saving = false;
  188. UI.message.error(err.message || '保存失败');
  189. render();
  190. });
  191. }
  192. function testAiConfig() {
  193. const c = state.aiConfig;
  194. c.testing = true; c.testResult = null; render();
  195. PL.api.post('/admin/ai-config/test').then(function (r) {
  196. c.testing = false;
  197. c.testResult = r;
  198. render();
  199. }, function (err) {
  200. c.testing = false;
  201. c.testResult = { ok: false, error: err.message || '测试失败' };
  202. render();
  203. });
  204. }
  205. function AiConfigView() {
  206. const c = state.aiConfig;
  207. if (!c.loaded) {
  208. return h('div', { style: { padding: 80, textAlign: 'center' } }, h(A.Spin, null));
  209. }
  210. return h('div', null,
  211. h(A.Alert, {
  212. type: c.configured ? 'success' : 'warning', showIcon: true, style: { marginBottom: 16 },
  213. message: c.configured ? 'AI 排版已启用(模型 ' + c.model + ')' : 'AI 排版未启用:未配置 API Key',
  214. description: '配置存于数据库(后台即时生效,优先于部署环境变量)。支持任意 OpenAI 兼容接口:智谱 / ModelScope / DeepSeek / 自建 vLLM 等。'
  215. }),
  216. h('div', { className: 'pl-admin-card', style: { maxWidth: 640 } },
  217. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, 'API 地址(Base URL,如 https://open.bigmodel.cn/api/paas/v4)'),
  218. h(A.Input, { value: c.baseUrl, placeholder: 'https://open.bigmodel.cn/api/paas/v4',
  219. onChange: function (e) { c.baseUrl = e.target.value; render(); } }),
  220. h('div', { style: { fontSize: 12, color: '#7d7466', margin: '12px 0 4px' } }, '模型名(如 glm-4-flash / glm-4.6 / deepseek-chat)'),
  221. h(A.Input, { value: c.model, placeholder: 'glm-4-flash',
  222. onChange: function (e) { c.model = e.target.value; render(); } }),
  223. h('div', { style: { fontSize: 12, color: '#7d7466', margin: '12px 0 4px' } },
  224. 'API Key' + (c.hasKey ? '(当前:' + c.apiKeyMasked + ',留空则不修改)' : '(未配置)')),
  225. h(A.Input.Password, { value: c.newKey || '', placeholder: c.hasKey ? '留空保持不变' : '粘贴 API Key',
  226. onChange: function (e) { c.newKey = e.target.value; render(); } }),
  227. h('div', { style: { display: 'flex', gap: 10, marginTop: 18 } },
  228. h(A.Button, { type: 'primary', loading: c.saving, onClick: saveAiConfig }, '保存配置'),
  229. h(A.Button, { loading: c.testing, onClick: testAiConfig, disabled: !c.hasKey && !c.newKey }, '测试连通')),
  230. c.testResult ? h(A.Alert, {
  231. type: c.testResult.ok ? 'success' : 'error', showIcon: true, style: { marginTop: 14 },
  232. message: c.testResult.ok ? ('连通成功 · ' + (c.testResult.model || '') + ' · 回复: ' + (c.testResult.reply || ''))
  233. : ('连通失败:' + (c.testResult.error || '未知错误'))
  234. }) : null),
  235. h('div', { className: 'pl-admin-card', style: { maxWidth: 640, marginTop: 14 } },
  236. h('b', { style: { fontSize: 13.5 } }, '用量说明'),
  237. h('p', { style: { fontSize: 12.5, color: '#7d7466', lineHeight: 1.8, margin: '8px 0 0' } },
  238. '· 每位用户默认 20 次,在「用户管理 → AI 额度」按人调整(设 0 禁用)', h('br'),
  239. '· 用户每次成功生成扣 1 次,失败不扣;仪表盘显示"今日 AI 排版"', h('br'),
  240. '· Key 仅存储在服务端数据库,界面只回显打码值'))
  241. );
  242. }
  243. function loadFactories() {
  244. state.factories.loading = true; render();
  245. PL.api.get('/admin/factory-accounts').then(function (r) {
  246. state.factories.items = r.items || [];
  247. state.factories.loading = false;
  248. render();
  249. }, function (err) {
  250. state.factories.loading = false;
  251. UI.message.error(err.message || '工厂账号加载失败');
  252. render();
  253. });
  254. }
  255. function saveFactoryAccount() {
  256. const m = state.facModal;
  257. if (m.isCreate) {
  258. if (!m.username || !m.password) { UI.message.warning('请填写用户名和密码'); return; }
  259. } else if (m.password && m.password.length < 6) {
  260. UI.message.warning('新密码至少 6 位'); return;
  261. }
  262. m.busy = true; render();
  263. const req = m.isCreate
  264. ? PL.api.post('/admin/factory-accounts', { username: m.username, password: m.password, name: m.name })
  265. : PL.api.patch('/admin/factory-accounts/' + m.id, {
  266. name: m.name || undefined,
  267. password: m.password || undefined
  268. });
  269. req.then(function () {
  270. m.busy = false; m.open = false;
  271. UI.message.success(m.isCreate ? '工厂账号已创建' : '已保存');
  272. loadFactories();
  273. }, function (err) {
  274. m.busy = false;
  275. UI.message.error(err.message || '保存失败');
  276. render();
  277. });
  278. }
  279. function openQuotaModal(u) {
  280. state.quotaModal = { open: true, user: u, quota: u.aiQuota == null ? 20 : u.aiQuota, busy: false };
  281. render();
  282. }
  283. function saveQuota(reset) {
  284. const m = state.quotaModal;
  285. m.busy = true; render();
  286. PL.api.patch('/admin/users/' + m.user.id, {
  287. ai_quota: m.quota,
  288. ai_used: reset ? 0 : undefined
  289. }).then(function () {
  290. m.busy = false; m.open = false;
  291. UI.message.success(reset ? '额度已保存且用量已清零' : '额度已保存');
  292. loadUsers();
  293. }, function (err) {
  294. m.busy = false;
  295. UI.message.error(err.message || '保存失败');
  296. render();
  297. });
  298. }
  299. function QuotaModal() {
  300. const m = state.quotaModal;
  301. if (!m.user) return null;
  302. return h(A.Modal, {
  303. open: m.open, width: 420, title: 'AI 排版额度 · ' + (m.user.name || m.user.phone),
  304. footer: null, onCancel: function () { m.open = false; render(); }
  305. },
  306. h('p', { style: { fontSize: 12.5, color: '#7d7466', margin: '0 0 10px' } },
  307. '已用 ' + (m.user.aiUsed || 0) + ' 次。设为 0 表示禁止该用户使用 AI 排版。'),
  308. h(A.InputNumber, { value: m.quota, min: 0, max: 100000, style: { width: '100%' },
  309. onChange: function (v) { m.quota = v || 0; render(); } }),
  310. h('div', { style: { display: 'flex', gap: 8, marginTop: 14, justifyContent: 'flex-end' } },
  311. h(A.Button, { onClick: function () { m.open = false; render(); } }, '取消'),
  312. h(A.Button, { onClick: function () { saveQuota(true); } }, '保存并清零用量'),
  313. h(A.Button, { type: 'primary', loading: m.busy, onClick: function () { saveQuota(false); } }, '保存'))
  314. );
  315. }
  316. function toggleFactoryAccount(u) {
  317. const next = u.status === 'active' ? 'disabled' : 'active';
  318. PL.api.patch('/admin/factory-accounts/' + u.id, { status: next }).then(function () {
  319. UI.message.success(next === 'active' ? '已启用' : '已禁用');
  320. loadFactories();
  321. }, function (err) { UI.message.error(err.message || '操作失败'); });
  322. }
  323. function adminPreview(no, key) {
  324. const k = no + ':' + key;
  325. if (previewCache.has(k)) return previewCache.get(k);
  326. fetch('/api/admin/orders/' + no + '/preview/' + key, {
  327. headers: { Authorization: 'Bearer ' + PL.api.token() }
  328. }).then(function (res) { return res.ok ? res.blob() : null; }).then(function (blob) {
  329. previewCache.set(k, blob ? URL.createObjectURL(blob) : null);
  330. render();
  331. }).catch(function () { previewCache.set(k, null); });
  332. return null;
  333. }
  334. function openOrder(no) {
  335. state.drawer = { open: true, no: no, data: null,
  336. form: { status: '', pay: '', adminNote: '', carrier: '', trackingNo: '' },
  337. saveBusy: false, shipBusy: false, replyText: '', replyBusy: false };
  338. render();
  339. PL.api.get(apiBase() + '/orders/' + no).then(function (d) {
  340. state.drawer.data = d;
  341. state.drawer.form = {
  342. status: d.status, pay: d.payStatus, adminNote: d.adminNote || '',
  343. carrier: d.carrier || '', trackingNo: d.trackingNo || '', assignedTo: d.assignedTo || 0
  344. };
  345. if (!isFactory() && !state.factories.items.length) loadFactories();
  346. render();
  347. (d.previews || []).forEach(function (key) { adminPreview(no, key); });
  348. }, function (err) {
  349. state.drawer.open = false;
  350. UI.message.error(err.message || '详情加载失败');
  351. render();
  352. });
  353. }
  354. /* ---------------- 工厂协作:反馈线程 / 邮件 ---------------- */
  355. function postReply() {
  356. const dw = state.drawer;
  357. const text = (dw.replyText || '').trim();
  358. if (!text) {
  359. UI.message.warning('请填写反馈/回复内容');
  360. return;
  361. }
  362. dw.replyBusy = true; render();
  363. PL.api.post(apiBase() + '/orders/' + dw.no + '/messages', { content: text }).then(function (r) {
  364. dw.replyBusy = false;
  365. dw.replyText = '';
  366. if (dw.data) dw.data.messages = r.messages || [];
  367. UI.message.success(isFactory() ? '反馈已提交,等待平台处理' : '回复已发送');
  368. render();
  369. }, function (err) {
  370. dw.replyBusy = false;
  371. UI.message.error(err.message || '提交失败');
  372. render();
  373. });
  374. }
  375. function emailTemplate(d, msg) {
  376. // 只写正文:订单号/金额/页头页脚/按钮由服务端品牌模板自动包装
  377. return {
  378. subject: '【Steady】订单 ' + d.orderNo + ' 设计问题确认',
  379. body: d.contactName + ',您好:\n\n' +
  380. '您的订单「' + (d.summary || d.orderNo) + '」在印前生产检查中,工厂反馈了以下问题:\n\n' +
  381. '—————— 工厂反馈 ——————\n' + (msg.content || '') + '\n——————————————\n\n' +
  382. '请您回复本邮件确认处理方式,或点击下方按钮登录「我的订单」查看进度。如需修改设计,可重新进入设计工作室调整后再次提交。'
  383. };
  384. }
  385. function openEmailComposer(d, msg) {
  386. if (!d.contactEmail) {
  387. UI.message.warning('该订单未留邮箱,可编辑存档内容供其他渠道使用');
  388. }
  389. const t = emailTemplate(d, msg);
  390. state.emailModal = { open: true, messageId: msg.id, orderNo: d.orderNo,
  391. to: d.contactEmail || '(未留邮箱)', subject: t.subject, body: t.body,
  392. busy: false, tab: 'edit', previewHtml: '', previewBusy: false };
  393. render();
  394. }
  395. function sendEmail() {
  396. const m = state.emailModal;
  397. if (!m.subject.trim() || !m.body.trim()) {
  398. UI.message.warning('请填写邮件主题与内容');
  399. return;
  400. }
  401. m.busy = true; render();
  402. PL.api.post('/admin/orders/' + m.orderNo + '/messages/' + m.messageId + '/email',
  403. { subject: m.subject, body: m.body }).then(function (r) {
  404. m.busy = false; m.open = false;
  405. if (state.drawer.data) state.drawer.data.messages = r.messages || [];
  406. if (r.emailStatus === 'sent') UI.message.success('邮件已发送给用户');
  407. else if (r.hasEmail === false) UI.message.warning('该订单未留邮箱,内容已存档到反馈线程');
  408. else UI.message.warning(r.smtpConfigured ? ('发送失败已存档:' + (r.error || '')) : 'SMTP 未配置,内容已存档(可复制到其他渠道发送)');
  409. render();
  410. }, function (err) {
  411. m.busy = false;
  412. UI.message.error(err.message || '发送失败');
  413. render();
  414. });
  415. }
  416. function loadEmailPreview() {
  417. const m = state.emailModal;
  418. if (m.previewHtml || m.previewBusy) return;
  419. m.previewBusy = true; render();
  420. let token = '';
  421. try { token = localStorage.getItem('pouchlab.token.v1') || ''; } catch (e) {}
  422. fetch('/api/admin/orders/' + m.orderNo + '/email/preview', {
  423. method: 'POST',
  424. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  425. body: JSON.stringify({ subject: m.subject, body: m.body })
  426. }).then(function (res) {
  427. if (!res.ok) throw new Error('preview ' + res.status);
  428. return res.text();
  429. }).then(function (html) {
  430. m.previewBusy = false; m.previewHtml = html; render();
  431. }).catch(function () {
  432. m.previewBusy = false; render();
  433. UI.message.error('预览加载失败');
  434. });
  435. }
  436. function switchEmailTab(key) {
  437. const m = state.emailModal;
  438. m.tab = key;
  439. if (key === 'preview') { m.previewHtml = ''; loadEmailPreview(); }
  440. render();
  441. }
  442. function saveOrder() {
  443. const f = state.drawer.form;
  444. state.drawer.saveBusy = true; render();
  445. PL.api.patch('/admin/orders/' + state.drawer.no, {
  446. status: f.status, pay_status: f.pay, admin_note: f.adminNote,
  447. assigned_to: f.assignedTo || undefined,
  448. clear_assignment: f.assignedTo ? undefined : (state.drawer.data && state.drawer.data.assignedTo ? true : undefined)
  449. }).then(function (d) {
  450. state.drawer.saveBusy = false;
  451. state.drawer.data = d;
  452. UI.message.success('已保存');
  453. loadOrders();
  454. loadDashboard();
  455. }, function (err) {
  456. state.drawer.saveBusy = false;
  457. UI.message.error(err.message || '保存失败');
  458. render();
  459. });
  460. }
  461. function shipOrder() {
  462. const f = state.drawer.form;
  463. if (!f.carrier || !f.trackingNo) {
  464. UI.message.warning('请填写快递公司和运单号');
  465. return;
  466. }
  467. state.drawer.shipBusy = true; render();
  468. PL.api.post('/admin/orders/' + state.drawer.no + '/ship', {
  469. carrier: f.carrier, tracking_no: f.trackingNo
  470. }).then(function (d) {
  471. state.drawer.shipBusy = false;
  472. state.drawer.data = d;
  473. state.drawer.form.status = d.status;
  474. UI.message.success('已发货并通知用户');
  475. loadOrders(); loadDashboard();
  476. }, function (err) {
  477. state.drawer.shipBusy = false;
  478. UI.message.error(err.message || '发货失败');
  479. render();
  480. });
  481. }
  482. function toggleUser(u) {
  483. const next = u.status === 'active' ? 'disabled' : 'active';
  484. PL.api.patch('/admin/users/' + u.id, { status: next }).then(function () {
  485. UI.message.success(next === 'active' ? '已启用' : '已禁用');
  486. loadUsers();
  487. }, function (err) { UI.message.error(err.message || '操作失败'); });
  488. }
  489. function openCadPreview(no) {
  490. state.cadModal = { open: true, no: no, loading: true, error: null };
  491. render();
  492. setTimeout(function () { mountCadPreview(no); }, 60); // 等 Modal 挂载到 DOM
  493. }
  494. function mountCadPreview(no) {
  495. const hostWrap = document.getElementById('cadPreviewHost');
  496. if (!hostWrap) return;
  497. Promise.all([getCadManager(hostWrap), fetchDxfBuffer(no)]).then(function (results) {
  498. const manager = results[0];
  499. const buffer = results[1];
  500. return manager.openDocument(no + '-cad.dxf', buffer, { progressiveRendering: true }).then(function () {
  501. manager.curView.zoomToSmartExtents(5000);
  502. if (state.cadModal.no === no) {
  503. state.cadModal.loading = false;
  504. render();
  505. }
  506. });
  507. }).catch(function (err) {
  508. if (state.cadModal.no === no) {
  509. state.cadModal.open = false;
  510. state.cadModal.loading = false;
  511. render();
  512. }
  513. UI.message.error(err && err.message ? err.message : 'CAD 预览加载失败');
  514. });
  515. }
  516. function downloadDxf(no) {
  517. no = no || state.drawer.no || state.cadModal.no;
  518. UI.message.loading({ content: '正在生成 CAD 图纸…', key: 'dxf', duration: 0 });
  519. PL.api.download('/admin/orders/' + no + '/dxf', no + '-cad.dxf').then(function () {
  520. UI.message.success({ content: 'CAD 图纸已下载', key: 'dxf' });
  521. }, function (err) {
  522. UI.message.error({ content: err.message || '生成失败', key: 'dxf' });
  523. });
  524. }
  525. function downloadDesign(no) {
  526. no = no || state.drawer.no;
  527. PL.api.download('/admin/orders/' + no + '/design', no + '-design.json').then(function () {}, function (err) {
  528. UI.message.error(err.message || '下载失败');
  529. });
  530. }
  531. function downloadProductionPdf(no) {
  532. no = no || state.drawer.no;
  533. UI.message.loading({ content: '正在生成生产图纸…', key: 'ppdf', duration: 0 });
  534. PL.api.download('/admin/orders/' + no + '/pdf', no + '-生产图纸.pdf').then(function () {
  535. UI.message.success({ content: '生产图纸已下载', key: 'ppdf' });
  536. }, function (err) {
  537. UI.message.error({ content: err.message || '生成失败', key: 'ppdf' });
  538. });
  539. }
  540. function downloadVectorPdf(no) {
  541. no = no || state.drawer.no;
  542. PL.api.download('/admin/orders/' + no + '/vector-pdf', no + '-刀版1to1.pdf').then(function () {}, function (err) {
  543. UI.message.error(err.message || '生成失败');
  544. });
  545. }
  546. function downloadEps(no) {
  547. no = no || state.drawer.no;
  548. PL.api.download('/admin/orders/' + no + '/eps', no + '-刀版1to1.eps').then(function () {
  549. UI.message.success({ content: 'EPS 已下载:CorelDRAW 打开后「另存为 CDR」即得 .cdr 文件', duration: 5 });
  550. }, function (err) {
  551. UI.message.error(err.message || '生成失败');
  552. });
  553. }
  554. /* ---------------- 视图 ---------------- */
  555. function LoginView() {
  556. return h('div', { className: 'pl-admin-login' },
  557. h('div', { className: 'pl-admin-login-card' },
  558. h('div', { className: 'pl-admin-login-brand' },
  559. h('span', { className: 'logo-mark' },
  560. h('svg', { viewBox: '0 0 24 24', fill: 'none', width: 30, height: 30 },
  561. h('path', { d: 'M7 8.2h10l1 10.1a2.8 2.8 0 0 1-2.8 3H8.8A2.8 2.8 0 0 1 6 18.3L7 8.2Z', fill: '#fffdf8' }),
  562. h('path', { d: 'M7.4 11.1h9.2', stroke: '#17140f', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  563. h('circle', { cx: 14.2, cy: 11.1, r: 1.15, fill: '#ff5c2b' }),
  564. h('path', { d: 'M9.5 14.4h4.9', stroke: '#ff5c2b', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  565. h('path', { d: 'M17.8 5.2v2.4M16.6 6.4h2.4', stroke: '#17140f', 'stroke-width': 1.2, 'stroke-linecap': 'round' }))),
  566. h('div', null,
  567. h('div', { className: 'pl-admin-login-title' }, '袋研社 · 后台管理'),
  568. h('small', { style: { color: '#a79d8d', letterSpacing: '0.12em', fontSize: 10 } }, 'POUCHLAB ADMIN'))),
  569. h(A.Form, { layout: 'vertical', onFinish: doLogin },
  570. h(A.Form.Item, { label: '用户名', style: { marginBottom: 14 } },
  571. h(A.Input, {
  572. value: state.login.username, size: 'large', placeholder: '管理员账号',
  573. onChange: function (e) { state.login.username = e.target.value; render(); }
  574. })),
  575. h(A.Form.Item, { label: '密码', style: { marginBottom: 20 } },
  576. h(A.Input.Password, {
  577. value: state.login.password, size: 'large', placeholder: '密码',
  578. onChange: function (e) { state.login.password = e.target.value; render(); }
  579. })),
  580. h(A.Button, { type: 'primary', htmlType: 'submit', size: 'large', block: true,
  581. loading: state.login.busy }, '登 录')),
  582. h('p', { style: { fontSize: 11, color: '#c3baa9', textAlign: 'center', marginTop: 16 } },
  583. '默认账号 admin / admin123,登录后请尽快修改密码')
  584. )
  585. );
  586. }
  587. function StatusTag(v) { const m = statusMeta(v); return h(A.Tag, { color: m.color }, m.label); }
  588. function PayTag(v) { const m = payMeta(v); return h(A.Tag, { color: m.color }, m.label); }
  589. function DashboardView() {
  590. const s = state.stats || {};
  591. const cards = [
  592. { num: s.ordersTotal, lbl: '订单总数' },
  593. { num: s.ordersToday, lbl: '今日新增订单' },
  594. { num: s.pendingShip, lbl: '待发货' },
  595. { num: fmtMoney(s.revenue), lbl: '已支付金额' },
  596. { num: s.usersTotal, lbl: '注册用户' },
  597. { num: s.aiCallsToday != null ? s.aiCallsToday : '-', lbl: '今日 AI 排版' }
  598. ];
  599. const cols = [
  600. { title: '订单号', dataIndex: 'orderNo', render: function (v, r) { return h('a', { onClick: function () { openOrder(v); } }, v); } },
  601. { title: '类型', dataIndex: 'type', width: 80, render: function (v) { return TYPE_LABEL[v] || v; } },
  602. { title: '规格', dataIndex: 'summary', ellipsis: true },
  603. { title: '金额', dataIndex: 'total', width: 100, render: fmtMoney },
  604. { title: '支付', dataIndex: 'payStatus', width: 90, render: PayTag },
  605. { title: '状态', dataIndex: 'status', width: 90, render: StatusTag },
  606. { title: '下单时间', dataIndex: 'createdAt', width: 110, render: fmtTime }
  607. ];
  608. return h('div', null,
  609. h('div', { className: 'pl-admin-stat-grid' },
  610. cards.map(function (c, i) {
  611. return h('div', { className: 'pl-admin-card pl-admin-stat', key: i },
  612. h('span', { className: 'num' }, c.num == null ? '-' : c.num),
  613. h('span', { className: 'lbl' }, c.lbl));
  614. })),
  615. h('div', { className: 'pl-admin-card' },
  616. h('div', { style: { display: 'flex', alignItems: 'center', marginBottom: 12 } },
  617. h('b', { style: { fontSize: 15 } }, '最新订单'),
  618. h('span', { style: { flex: 1 } }),
  619. h(A.Button, { size: 'small', type: 'link', onClick: function () { state.view = 'orders'; loadOrders(); render(); } }, '全部订单 →')),
  620. h(A.Table, {
  621. columns: cols, dataSource: state.recent, rowKey: 'orderNo',
  622. size: 'small', pagination: false, loading: !state.stats && !state.recent.length
  623. }))
  624. );
  625. }
  626. function OrdersView() {
  627. const f = state.orders.filter;
  628. const cols = [
  629. { title: '订单号', dataIndex: 'orderNo', width: 150, render: function (v) { return h('a', { onClick: function () { openOrder(v); } }, v); } },
  630. { title: '类型', dataIndex: 'type', width: 76, render: function (v) { return TYPE_LABEL[v] || v; } },
  631. { title: '规格摘要', dataIndex: 'summary', ellipsis: true },
  632. { title: '数量', dataIndex: 'spec', width: 70, render: function (s) { return s && s.qty ? s.qty : '-'; } },
  633. { title: '金额', dataIndex: 'total', width: 96, render: function (v) { return h('b', null, fmtMoney(v)); } },
  634. { title: '支付', dataIndex: 'payStatus', width: 86, render: PayTag },
  635. { title: '状态', dataIndex: 'status', width: 86, render: StatusTag },
  636. { title: '联系人', dataIndex: 'contactName', width: 90, render: function (v, r) { return v + ' / ' + (r.contactPhone || '-'); } },
  637. { title: '下单', dataIndex: 'createdAt', width: 100, render: fmtTime },
  638. { title: '操作', key: 'act', width: 170, render: function (_, r) {
  639. return h(A.Space, { size: 4 },
  640. h(A.Button, { size: 'small', onClick: function () { openOrder(r.orderNo); } }, '详情'),
  641. h(A.Button, { size: 'small', onClick: function () { openCadPreview(r.orderNo); } }, 'CAD'));
  642. } }
  643. ];
  644. return h('div', null,
  645. h('div', { className: 'pl-admin-card', style: { marginBottom: 14, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' } },
  646. h(A.Select, { value: f.type, style: { width: 110 }, placeholder: '类型',
  647. allowClear: true, options: [{ value: 'bag', label: '包装袋' }, { value: 'box', label: '纸盒' }],
  648. onChange: function (v) { f.type = v || ''; state.orders.page = 1; loadOrders(); } }),
  649. h(A.Select, { value: f.status, style: { width: 110 }, placeholder: '订单状态',
  650. allowClear: true, options: STATUS.map(function (s) { return { value: s.value, label: s.label }; }),
  651. onChange: function (v) { f.status = v || ''; state.orders.page = 1; loadOrders(); } }),
  652. isFactory() ? null : h(A.Select, { value: f.pay, style: { width: 110 }, placeholder: '支付状态',
  653. allowClear: true, options: PAYS.map(function (s) { return { value: s.value, label: s.label }; }),
  654. onChange: function (v) { f.pay = v || ''; state.orders.page = 1; loadOrders(); } }),
  655. h(A.Input.Search, { value: f.query, style: { width: isFactory() ? 250 : 250 }, placeholder: isFactory() ? '搜索订单号' : '搜索订单号 / 联系人 / 手机号',
  656. allowClear: true,
  657. onChange: function (e) { f.query = e.target.value; render(); },
  658. onSearch: function () { state.orders.page = 1; loadOrders(); } }),
  659. !isFactory() && f.userId ? h(A.Tag, { closable: true, onClose: function () { f.userId = 0; f.userName = ''; state.orders.page = 1; loadOrders(); } },
  660. '用户:' + (f.userName || f.userId)) : null
  661. ),
  662. h('div', { className: 'pl-admin-card' },
  663. h(A.Table, {
  664. columns: cols, dataSource: state.orders.items, rowKey: 'orderNo',
  665. size: 'small', loading: state.orders.loading,
  666. pagination: {
  667. current: state.orders.page, total: state.orders.total, pageSize: state.orders.pageSize,
  668. showSizeChanger: false, showTotal: function (t) { return '共 ' + t + ' 单'; },
  669. onChange: function (p) { state.orders.page = p; loadOrders(); }
  670. }
  671. }))
  672. );
  673. }
  674. function UsersView() {
  675. const userCols = [
  676. { title: 'ID', dataIndex: 'id', width: 60 },
  677. { title: '邮箱', dataIndex: 'email', width: 180, render: function (v) { return v || '—'; } },
  678. { title: '手机号(旧)', dataIndex: 'phone', width: 120, render: function (v) { return v || '—'; } },
  679. { title: '昵称', dataIndex: 'name', width: 120 },
  680. { title: '订单数', dataIndex: 'orderCount', width: 80 },
  681. { title: '消费额', dataIndex: 'paidTotal', width: 100, render: fmtMoney },
  682. { title: 'AI 用量', dataIndex: 'aiUsed', width: 100, render: function (_, u) {
  683. return (u.aiUsed || 0) + ' / ' + (u.aiQuota == null ? 20 : u.aiQuota);
  684. } },
  685. { title: '状态', dataIndex: 'status', width: 90, render: function (v) {
  686. return h(A.Tag, { color: v === 'active' ? 'success' : 'error' }, v === 'active' ? '正常' : '已禁用');
  687. } },
  688. { title: '注册时间', dataIndex: 'createdAt', width: 120, render: fmtTime },
  689. { title: '操作', key: 'act', width: 250, render: function (_, u) {
  690. return h(A.Space, { size: 4 },
  691. h(A.Button, { size: 'small', onClick: function () { toggleUser(u); } }, u.status === 'active' ? '禁用' : '启用'),
  692. h(A.Button, { size: 'small', onClick: function () { openQuotaModal(u); } }, 'AI 额度'),
  693. h(A.Button, { size: 'small', type: 'link', onClick: function () {
  694. state.orders.filter.userId = u.id;
  695. state.orders.filter.userName = u.name || u.phone;
  696. state.orders.page = 1;
  697. state.view = 'orders';
  698. loadOrders();
  699. } }, '查看订单'));
  700. } }
  701. ];
  702. const facCols = [
  703. { title: 'ID', dataIndex: 'id', width: 60 },
  704. { title: '用户名', dataIndex: 'username', width: 130 },
  705. { title: '工厂名称', dataIndex: 'name', width: 160 },
  706. { title: '分配订单数', dataIndex: 'orderCount', width: 100 },
  707. { title: '状态', dataIndex: 'status', width: 90, render: function (v) {
  708. return h(A.Tag, { color: v === 'active' ? 'success' : 'error' }, v === 'active' ? '正常' : '已禁用');
  709. } },
  710. { title: '创建时间', dataIndex: 'createdAt', width: 120, render: fmtTime },
  711. { title: '操作', key: 'act', width: 260, render: function (_, u) {
  712. return h(A.Space, { size: 4 },
  713. h(A.Button, { size: 'small', onClick: function () { toggleFactoryAccount(u); } }, u.status === 'active' ? '禁用' : '启用'),
  714. h(A.Button, { size: 'small', onClick: function () {
  715. state.facModal = { open: true, id: u.id, username: u.username, name: u.name, password: '', busy: false, isCreate: false };
  716. render();
  717. } }, '改名/重置密码'));
  718. } }
  719. ];
  720. return h('div', { className: 'pl-admin-card' },
  721. h(A.Tabs, { items: [
  722. { key: 'users', label: '注册用户', children:
  723. h('div', null,
  724. h('div', { style: { display: 'flex', gap: 10, marginBottom: 14 } },
  725. h(A.Input.Search, { value: state.users.query, style: { width: 260 }, placeholder: '搜索手机号 / 邮箱 / 昵称',
  726. allowClear: true,
  727. onChange: function (e) { state.users.query = e.target.value; render(); },
  728. onSearch: function () { state.users.page = 1; loadUsers(); } })),
  729. h(A.Table, {
  730. columns: userCols, dataSource: state.users.items, rowKey: 'id',
  731. size: 'small', loading: state.users.loading,
  732. pagination: {
  733. current: state.users.page, total: state.users.total, pageSize: state.users.pageSize,
  734. showSizeChanger: false, showTotal: function (t) { return '共 ' + t + ' 位用户'; },
  735. onChange: function (p) { state.users.page = p; loadUsers(); }
  736. }
  737. })) },
  738. { key: 'factories', label: '工厂账号', children:
  739. h('div', null,
  740. h(A.Alert, { type: 'info', showIcon: true, style: { marginBottom: 14 },
  741. message: '一家协作工厂一个账号;订单在「订单详情 → 分配工厂」指定后,对应工厂才能看到该订单(用户隐私自动脱敏)' }),
  742. h('div', { style: { marginBottom: 14 } },
  743. h(A.Button, { type: 'primary', onClick: function () {
  744. state.facModal = { open: true, id: 0, username: '', name: '', password: '', busy: false, isCreate: true };
  745. render();
  746. } }, '+ 新建工厂账号')),
  747. h(A.Table, {
  748. columns: facCols, dataSource: state.factories.items, rowKey: 'id',
  749. size: 'small', loading: state.factories.loading, pagination: false
  750. })) }
  751. ], onChange: function (k) { if (k === 'factories' && !state.factories.items.length) loadFactories(); } })
  752. );
  753. }
  754. function FactoryAccountModal() {
  755. const m = state.facModal;
  756. return h(A.Modal, {
  757. open: m.open, width: 460,
  758. title: m.isCreate ? '新建工厂账号' : '修改工厂账号(' + m.username + ')',
  759. okText: m.isCreate ? '创建' : '保存', cancelText: '取消',
  760. confirmLoading: m.busy,
  761. onOk: saveFactoryAccount,
  762. onCancel: function () { m.open = false; render(); }
  763. },
  764. m.isCreate ? h('div', { style: { marginBottom: 12 } },
  765. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '登录用户名(3-30 位字母/数字/下划线)'),
  766. h(A.Input, { value: m.username, placeholder: '如 hangzhou-box',
  767. onChange: function (e) { m.username = e.target.value; render(); } })) : null,
  768. h('div', { style: { marginBottom: 12 } },
  769. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '工厂名称(对外显示)'),
  770. h(A.Input, { value: m.name, placeholder: '如 杭州彩印包装厂',
  771. onChange: function (e) { m.name = e.target.value; render(); } })),
  772. h('div', null,
  773. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } },
  774. m.isCreate ? '初始密码(至少 6 位)' : '重置密码(留空则不修改)'),
  775. h(A.Input.Password, { value: m.password, placeholder: '至少 6 位',
  776. onChange: function (e) { m.password = e.target.value; render(); } })),
  777. h('p', { style: { fontSize: 11, color: '#a79d8d', marginTop: 12 } },
  778. '工厂用此账号在 admin.html 登录,仅见分配给它的订单')
  779. );
  780. }
  781. function specRows(d) {
  782. const s = d.spec || {};
  783. const rows = [
  784. ['类型', TYPE_LABEL[d.type] || d.type],
  785. ['数量', (s.qty || '-') + ' 件'],
  786. ['摘要', d.summary || '-']
  787. ];
  788. if (d.type === 'bag') {
  789. rows.push(['袋型', s.productName || '-']);
  790. rows.push(['尺寸', (s.sizeLabel || '-') + '(' + (s.w || '-') + '×' + (s.h || '-') + ' mm)']);
  791. rows.push(['材质', s.materialName || '-']);
  792. rows.push(['工艺', s.finishName || '-']);
  793. } else {
  794. rows.push(['盒型', (s.boxName || '-') + '(' + (s.boxNo || '-') + ')']);
  795. rows.push(['内尺寸', (s.w || '-') + ' × ' + (s.d || '-') + ' × ' + (s.h || '-') + ' mm']);
  796. rows.push(['材质', (s.materialName || '-') + (s.thickness ? ' · 厚 ' + s.thickness + 'mm' : '')]);
  797. rows.push(['印色', s.printName || '-']);
  798. rows.push(['印刷方式', s.printWay || '-']);
  799. }
  800. const q = d.quote || {};
  801. rows.push(['单价', fmtMoney(q.unit || d.unitPrice)]);
  802. rows.push(['总额', h('b', { style: { color: '#ff5c2b' } }, fmtMoney(d.total))]);
  803. return rows;
  804. }
  805. function OrderDrawer() {
  806. const dw = state.drawer;
  807. const d = dw.data;
  808. const f = dw.form;
  809. return h(A.Drawer, {
  810. open: dw.open, width: 640, title: dw.no ? '订单 ' + dw.no : '订单详情',
  811. onClose: function () { dw.open = false; render(); }
  812. },
  813. !d ? h('div', { style: { padding: 80, textAlign: 'center' } }, h(A.Spin, null)) : h('div', null,
  814. (d.previews || []).length ? h('div', { className: 'pl-preview-grid' },
  815. d.previews.map(function (key) {
  816. const url = previewCache.get(d.orderNo + ':' + key);
  817. return url ? h(A.Image, { key: key, src: url, height: 150, style: { borderRadius: 10, border: '1px solid #efe9dc' } }) : null;
  818. })) : null,
  819. h(A.Descriptions, { title: '规格与金额', column: 2, size: 'small', bordered: true, style: { marginTop: 14 } },
  820. specRows(d).map(function (r, i) {
  821. 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]);
  822. })),
  823. h(A.Descriptions, { title: '下单与联系', column: 1, size: 'small', bordered: true, style: { marginTop: 16 } },
  824. h(A.Descriptions.Item, { label: '用户' }, (d.ownerName || '-') + ' · ' + (d.ownerPhone || '-')),
  825. h(A.Descriptions.Item, { label: '联系人' }, d.contactName + ' · ' + d.contactPhone + (d.contactEmail ? ' · ' + d.contactEmail : '')),
  826. h(A.Descriptions.Item, { label: '收货地址' }, d.address || '-'),
  827. d.note ? h(A.Descriptions.Item, { label: '用户备注' }, d.note) : null),
  828. isFactory() ? null : h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '订单操作'),
  829. isFactory() ? null : h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 } },
  830. h('div', null,
  831. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '订单状态'),
  832. h(A.Select, { value: f.status, style: { width: '100%' },
  833. options: STATUS.map(function (s) { return { value: s.value, label: s.label }; }),
  834. onChange: function (v) { f.status = v; render(); } })),
  835. h('div', null,
  836. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '支付状态'),
  837. h(A.Select, { value: f.pay, style: { width: '100%' },
  838. options: PAYS.map(function (s) { return { value: s.value, label: s.label }; }),
  839. onChange: function (v) { f.pay = v; render(); } }))),
  840. isFactory() ? null : h('div', { style: { marginTop: 10 } },
  841. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '分配工厂(分配后该工厂才能看到此订单)'),
  842. h(A.Select, {
  843. value: f.assignedTo || 0, style: { width: '100%' },
  844. options: [{ value: 0, label: '未分配' }].concat(state.factories.items.map(function (u) {
  845. return { value: u.id, label: (u.name || u.username) + (u.status === 'active' ? '' : '(已禁用)') };
  846. })),
  847. onChange: function (v) { f.assignedTo = v; render(); }
  848. })),
  849. isFactory() ? null : h('div', { style: { marginTop: 10 } },
  850. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '管理员备注'),
  851. h(A.Input.TextArea, { value: f.adminNote, rows: 2, placeholder: '内部备注(用户不可见)',
  852. onChange: function (e) { f.adminNote = e.target.value; render(); } })),
  853. h('div', { style: { marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' } },
  854. isFactory() ? null : h(A.Button, { type: 'primary', loading: dw.saveBusy, onClick: saveOrder }, '保存修改'),
  855. h(A.Button, { type: 'primary', ghost: !isFactory(), onClick: function () { downloadProductionPdf(d.orderNo); } }, '生产图纸 PDF'),
  856. h(A.Tooltip, { title: 'mm 实尺矢量刀版,CorelDRAW/Illustrator 可直接打开编辑(CDR 交付替代)' },
  857. h(A.Button, { onClick: function () { downloadVectorPdf(d.orderNo); } }, '矢量刀版 1:1')),
  858. h(A.Tooltip, { title: 'EPS 矢量(CorelDRAW 原生导入,另存为 CDR 即得 .cdr 文件)' },
  859. h(A.Button, { onClick: function () { downloadEps(d.orderNo); } }, 'EPS(.cdr)')),
  860. h(A.Button, { onClick: function () { openCadPreview(d.orderNo); } }, 'CAD 预览'),
  861. h(A.Button, { onClick: function () { downloadDxf(d.orderNo); } }, 'DXF'),
  862. !isFactory() && d.hasDesign ? h(A.Button, { onClick: function () { downloadDesign(d.orderNo); } }, '设计稿') : null),
  863. isFactory() ? null : h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '物流发货'),
  864. isFactory() ? null : h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1.4fr auto', gap: 10, alignItems: 'center' } },
  865. h(A.Input, { value: f.carrier, placeholder: '快递公司(如 顺丰速运)',
  866. onChange: function (e) { f.carrier = e.target.value; render(); } }),
  867. h(A.Input, { value: f.trackingNo, placeholder: '运单号',
  868. onChange: function (e) { f.trackingNo = e.target.value; render(); } }),
  869. h(A.Button, { type: 'primary', ghost: true, loading: dw.shipBusy, onClick: shipOrder,
  870. disabled: d.status === 'cancelled' }, '发货')),
  871. isFactory() || !d.trackingNo ? null : h('div', { style: { marginTop: 8, fontSize: 12, color: '#7d7466' } },
  872. '当前物流:' + d.carrier + ' · ' + d.trackingNo),
  873. /* 工厂协作:反馈线程(工厂提交 / 管理员回复 / 邮件通知用户) */
  874. h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } },
  875. isFactory() ? '设计问题反馈' : '工厂协作'),
  876. h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
  877. (d.messages || []).length ? (d.messages || []).map(function (m) {
  878. const isFac = m.senderRole === 'factory';
  879. return h('div', { key: m.id, style: {
  880. background: isFac ? '#fff7f0' : '#f4f8f2',
  881. border: '1px solid ' + (isFac ? '#ffd9c2' : '#dce8d4'),
  882. borderRadius: 10, padding: '8px 10px'
  883. } },
  884. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } },
  885. h('b', { style: { color: isFac ? '#c2610f' : '#4f6b2f' } },
  886. isFac ? '🏭 ' + (m.senderName || '工厂') : '🛠 ' + (m.senderName || '管理员')),
  887. ' ' + fmtTime(m.createdAt)),
  888. h('div', { style: { whiteSpace: 'pre-wrap', fontSize: 13 } }, m.content),
  889. m.emailStatus ? h('div', { style: { marginTop: 6, padding: '6px 8px', background: '#fffdf8', borderRadius: 6, fontSize: 12 } },
  890. '📧 ',
  891. m.emailStatus === 'sent' ? '已发送邮件至 ' + m.emailTo
  892. : m.emailStatus === 'archived' ? '邮件内容已存档(' + (m.emailTo || '未留邮箱') + ')'
  893. : m.emailStatus,
  894. h('div', { style: { color: '#a79d8d', marginTop: 2 } }, '主题:' + m.emailSubject)) : null,
  895. !isFactory() && isFac && !m.emailStatus ? h('div', { style: { marginTop: 6 } },
  896. h(A.Button, { size: 'small', type: 'primary', ghost: true,
  897. onClick: function () { openEmailComposer(d, m); } }, '✉ 邮件通知用户(模板)')) : null);
  898. }) : h('div', { style: { color: '#a79d8d', fontSize: 12.5 } },
  899. isFactory() ? '如发现设计问题(出血不足、图文越界、工艺冲突等),请在下方提交,平台会转达用户。'
  900. : '工厂的反馈会显示在这里,可选择将问题整理成邮件通知用户。')),
  901. h('div', { style: { display: 'flex', gap: 8, marginTop: 4 } },
  902. h(A.Input.TextArea, {
  903. value: dw.replyText, rows: 2,
  904. placeholder: isFactory() ? '描述设计问题(如:正面文字超出安全区 2mm,建议内移…)' : '回复工厂…',
  905. onChange: function (e) { dw.replyText = e.target.value; render(); }
  906. }),
  907. h(A.Button, { type: 'primary', loading: dw.replyBusy, onClick: postReply,
  908. style: { alignSelf: 'flex-end' } }, isFactory() ? '提交反馈' : '回复')),
  909. h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '操作时间线'),
  910. h(A.Timeline, {
  911. items: (d.events || []).slice().reverse().map(function (e) {
  912. return {
  913. color: e.kind === 'logistics' ? 'geekblue' : 'green',
  914. children: h('div', null,
  915. h('div', { style: { fontWeight: 600 } }, e.title + ' ', h('span', { style: { fontWeight: 400, fontSize: 11, color: '#a79d8d' } }, fmtTime(e.createdAt))),
  916. e.detail ? h('div', { style: { fontSize: 12, color: '#7d7466' } }, e.detail) : null)
  917. };
  918. })
  919. })
  920. )
  921. );
  922. }
  923. function EmailComposerModal() {
  924. const m = state.emailModal;
  925. const hasTo = m.to && m.to !== '(未留邮箱)';
  926. return h(A.Modal, {
  927. open: m.open, width: 760, title: '邮件通知用户',
  928. okText: m.tab === 'preview' ? '确认发送' : '发送', cancelText: '取消',
  929. confirmLoading: m.busy,
  930. onOk: sendEmail,
  931. onCancel: function () { m.open = false; render(); }
  932. },
  933. h(A.Alert, {
  934. type: hasTo ? 'success' : 'warning', showIcon: true, style: { marginBottom: 12 },
  935. message: hasTo ? ('收件人:' + m.to + ' · 发件人:Steady <mail@steadypackaging.com>')
  936. : ('收件人:' + m.to + ' — 订单未留邮箱,发送后内容将存档到反馈线程,可复制到其他渠道')
  937. }),
  938. h(A.Tabs, {
  939. activeKey: m.tab,
  940. onChange: switchEmailTab,
  941. items: [
  942. { key: 'edit', label: '编辑内容', children: [
  943. h('div', { key: 'l1', style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '邮件主题'),
  944. h(A.Input, { key: 's', value: m.subject,
  945. onChange: function (e) { m.subject = e.target.value; render(); } }),
  946. h('div', { key: 'l2', style: { fontSize: 12, color: '#7d7466', margin: '12px 0 4px' } }, '邮件正文(页头、订单卡片、按钮、页脚由系统模板自动生成)'),
  947. h(A.Input.TextArea, { key: 'b', value: m.body, rows: 14,
  948. onChange: function (e) { m.body = e.target.value; render(); } })
  949. ]},
  950. { key: 'preview', label: '预览效果', children:
  951. h('div', { style: { height: 460, borderRadius: 10, border: '1px solid #e6ddcd', overflow: 'hidden', background: '#f6f2e9', position: 'relative' } },
  952. m.previewBusy
  953. ? h('div', { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' } }, h(A.Spin, { tip: '渲染中…' }))
  954. : h('iframe', {
  955. title: '邮件预览', srcDoc: m.previewHtml,
  956. style: { width: '100%', height: '100%', border: 'none', background: '#f6f2e9' }
  957. }))
  958. }
  959. ]
  960. })
  961. );
  962. }
  963. function CadPreviewModal() {
  964. const m = state.cadModal;
  965. return h(A.Modal, {
  966. open: m.open, width: 1000, title: '工厂 CAD 图纸 ' + (m.no || ''),
  967. onCancel: function () { m.open = false; render(); },
  968. footer: h('div', null,
  969. h('span', { style: { float: 'left', color: '#a79d8d', fontSize: 12, lineHeight: '32px' } }, '滚轮缩放 · 拖拽平移 · 可点选图元查看图层'),
  970. h(A.Button, { onClick: function () { m.open = false; render(); } }, '关闭'),
  971. h(A.Button, { type: 'primary', style: { marginLeft: 8 }, onClick: function () { downloadDxf(m.no); } }, '下载 DXF'))
  972. },
  973. h('div', { id: 'cadPreviewHost', style: { position: 'relative', height: '68vh', background: '#fff', borderRadius: 8, overflow: 'hidden' } },
  974. m.loading ? h('div', { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', zIndex: 1, background: '#fffdf8' } },
  975. h(A.Spin, null)) : null)
  976. );
  977. }
  978. function App() {
  979. if (!state.booted) {
  980. return h('div', { style: { minHeight: '100vh', display: 'grid', placeItems: 'center' } }, h(A.Spin, null));
  981. }
  982. if (!state.admin) return LoginView();
  983. const fac = isFactory();
  984. const views = fac
  985. ? { orders: OrdersView }
  986. : { dashboard: DashboardView, orders: OrdersView, users: UsersView, aisetting: AiConfigView };
  987. const titles = fac
  988. ? { orders: '生产订单' }
  989. : { dashboard: '仪表盘', orders: '订单管理', users: '用户管理', aisetting: 'AI 设置' };
  990. if (!views[state.view]) state.view = 'orders';
  991. return h(A.Layout, { style: { minHeight: '100vh' } },
  992. h(A.Layout.Sider, { width: 208, className: 'pl-admin-sider', breakpoint: 'lg', collapsedWidth: 0 },
  993. h('div', { className: 'pl-admin-brand' },
  994. h('span', { style: { display: 'inline-flex', fontSize: 18 } },
  995. h('svg', { viewBox: '0 0 24 24', fill: 'none', width: 22, height: 22 },
  996. h('path', { d: 'M7 8.2h10l1 10.1a2.8 2.8 0 0 1-2.8 3H8.8A2.8 2.8 0 0 1 6 18.3L7 8.2Z', fill: '#fffdf8' }),
  997. h('path', { d: 'M7.4 11.1h9.2', stroke: '#17140f', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  998. h('circle', { cx: 14.2, cy: 11.1, r: 1.15, fill: '#ff5c2b' }),
  999. h('path', { d: 'M9.5 14.4h4.9', stroke: '#ff5c2b', 'stroke-width': 1.4, 'stroke-linecap': 'round' }))),
  1000. h('span', null, fac ? '工厂协作端' : '袋研社后台',
  1001. h('small', null, fac ? 'FACTORY PARTNER' : 'POUCHLAB ADMIN'))),
  1002. h(A.Menu, {
  1003. className: 'pl-admin-menu', theme: 'dark', mode: 'inline',
  1004. selectedKeys: [state.view],
  1005. onClick: function (e) {
  1006. state.view = e.key;
  1007. if (e.key === 'dashboard' && !state.stats) loadDashboard();
  1008. if (e.key === 'orders' && !state.orders.items.length) loadOrders();
  1009. if (e.key === 'users' && !state.users.items.length) loadUsers();
  1010. if (e.key === 'aisetting' && !state.aiConfig.loaded) loadAiConfig();
  1011. render();
  1012. },
  1013. items: fac
  1014. ? [{ key: 'orders', label: '📦 生产订单' }]
  1015. : [
  1016. { key: 'dashboard', label: '📊 仪表盘' },
  1017. { key: 'orders', label: '📦 订单管理' },
  1018. { key: 'users', label: '👥 用户管理' },
  1019. { key: 'aisetting', label: '🤖 AI 设置' }
  1020. ]
  1021. })),
  1022. h(A.Layout, null,
  1023. h(A.Layout.Header, { className: 'pl-admin-header', style: { background: '#fffdf8' } },
  1024. h('span', { className: 'title' }, titles[state.view]),
  1025. h('div', null,
  1026. h('span', { style: { color: '#7d7466', fontSize: 12.5, marginRight: 12 } },
  1027. (state.admin.name || state.admin.username) + (fac ? '(协作工厂)' : '(管理员)')),
  1028. h(A.Button, { size: 'small', onClick: logout }, '退出'))),
  1029. h(A.Layout.Content, { style: { padding: 20, overflow: 'initial' } },
  1030. (views[state.view])(),
  1031. OrderDrawer(),
  1032. CadPreviewModal(),
  1033. EmailComposerModal(),
  1034. FactoryAccountModal(),
  1035. QuotaModal()))
  1036. );
  1037. }
  1038. function render() {
  1039. UI.render(document.getElementById('root'), App());
  1040. }
  1041. document.addEventListener('pl:auth-expired', function () {
  1042. if (state.admin) UI.message.warning('登录已失效,请重新登录');
  1043. state.admin = null;
  1044. render();
  1045. });
  1046. boot();
  1047. })();