admin.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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 }
  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. return {
  377. subject: '【袋研社】订单 ' + d.orderNo + ' 设计问题确认',
  378. body: d.contactName + ',您好:\n\n' +
  379. '您的订单「' + (d.summary || d.orderNo) + '」在印前生产检查中,工厂反馈了以下问题:\n\n' +
  380. '—————— 工厂反馈 ——————\n' + (msg.content || '') + '\n——————————————\n\n' +
  381. '请您回复本邮件确认处理方式,或登录「我的订单」查看订单进度。如需修改设计,可重新进入设计工作室调整后再次提交。\n\n' +
  382. '订单号:' + d.orderNo + '\n金额:¥' + Number(d.total || 0).toFixed(2) + '\n\n' +
  383. '袋研社 POUCHLAB\n' + new Date().toLocaleDateString('zh-CN')
  384. };
  385. }
  386. function openEmailComposer(d, msg) {
  387. if (!d.contactEmail) {
  388. UI.message.warning('该订单未留邮箱,可编辑存档内容供其他渠道使用');
  389. }
  390. const t = emailTemplate(d, msg);
  391. state.emailModal = { open: true, messageId: msg.id, orderNo: d.orderNo,
  392. to: d.contactEmail || '(未留邮箱)', subject: t.subject, body: t.body, busy: 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 saveOrder() {
  417. const f = state.drawer.form;
  418. state.drawer.saveBusy = true; render();
  419. PL.api.patch('/admin/orders/' + state.drawer.no, {
  420. status: f.status, pay_status: f.pay, admin_note: f.adminNote,
  421. assigned_to: f.assignedTo || undefined,
  422. clear_assignment: f.assignedTo ? undefined : (state.drawer.data && state.drawer.data.assignedTo ? true : undefined)
  423. }).then(function (d) {
  424. state.drawer.saveBusy = false;
  425. state.drawer.data = d;
  426. UI.message.success('已保存');
  427. loadOrders();
  428. loadDashboard();
  429. }, function (err) {
  430. state.drawer.saveBusy = false;
  431. UI.message.error(err.message || '保存失败');
  432. render();
  433. });
  434. }
  435. function shipOrder() {
  436. const f = state.drawer.form;
  437. if (!f.carrier || !f.trackingNo) {
  438. UI.message.warning('请填写快递公司和运单号');
  439. return;
  440. }
  441. state.drawer.shipBusy = true; render();
  442. PL.api.post('/admin/orders/' + state.drawer.no + '/ship', {
  443. carrier: f.carrier, tracking_no: f.trackingNo
  444. }).then(function (d) {
  445. state.drawer.shipBusy = false;
  446. state.drawer.data = d;
  447. state.drawer.form.status = d.status;
  448. UI.message.success('已发货并通知用户');
  449. loadOrders(); loadDashboard();
  450. }, function (err) {
  451. state.drawer.shipBusy = false;
  452. UI.message.error(err.message || '发货失败');
  453. render();
  454. });
  455. }
  456. function toggleUser(u) {
  457. const next = u.status === 'active' ? 'disabled' : 'active';
  458. PL.api.patch('/admin/users/' + u.id, { status: next }).then(function () {
  459. UI.message.success(next === 'active' ? '已启用' : '已禁用');
  460. loadUsers();
  461. }, function (err) { UI.message.error(err.message || '操作失败'); });
  462. }
  463. function openCadPreview(no) {
  464. state.cadModal = { open: true, no: no, loading: true, error: null };
  465. render();
  466. setTimeout(function () { mountCadPreview(no); }, 60); // 等 Modal 挂载到 DOM
  467. }
  468. function mountCadPreview(no) {
  469. const hostWrap = document.getElementById('cadPreviewHost');
  470. if (!hostWrap) return;
  471. Promise.all([getCadManager(hostWrap), fetchDxfBuffer(no)]).then(function (results) {
  472. const manager = results[0];
  473. const buffer = results[1];
  474. return manager.openDocument(no + '-cad.dxf', buffer, { progressiveRendering: true }).then(function () {
  475. manager.curView.zoomToSmartExtents(5000);
  476. if (state.cadModal.no === no) {
  477. state.cadModal.loading = false;
  478. render();
  479. }
  480. });
  481. }).catch(function (err) {
  482. if (state.cadModal.no === no) {
  483. state.cadModal.open = false;
  484. state.cadModal.loading = false;
  485. render();
  486. }
  487. UI.message.error(err && err.message ? err.message : 'CAD 预览加载失败');
  488. });
  489. }
  490. function downloadDxf(no) {
  491. no = no || state.drawer.no || state.cadModal.no;
  492. UI.message.loading({ content: '正在生成 CAD 图纸…', key: 'dxf', duration: 0 });
  493. PL.api.download('/admin/orders/' + no + '/dxf', no + '-cad.dxf').then(function () {
  494. UI.message.success({ content: 'CAD 图纸已下载', key: 'dxf' });
  495. }, function (err) {
  496. UI.message.error({ content: err.message || '生成失败', key: 'dxf' });
  497. });
  498. }
  499. function downloadDesign(no) {
  500. no = no || state.drawer.no;
  501. PL.api.download('/admin/orders/' + no + '/design', no + '-design.json').then(function () {}, function (err) {
  502. UI.message.error(err.message || '下载失败');
  503. });
  504. }
  505. function downloadProductionPdf(no) {
  506. no = no || state.drawer.no;
  507. UI.message.loading({ content: '正在生成生产图纸…', key: 'ppdf', duration: 0 });
  508. PL.api.download('/admin/orders/' + no + '/pdf', no + '-生产图纸.pdf').then(function () {
  509. UI.message.success({ content: '生产图纸已下载', key: 'ppdf' });
  510. }, function (err) {
  511. UI.message.error({ content: err.message || '生成失败', key: 'ppdf' });
  512. });
  513. }
  514. function downloadVectorPdf(no) {
  515. no = no || state.drawer.no;
  516. PL.api.download('/admin/orders/' + no + '/vector-pdf', no + '-刀版1to1.pdf').then(function () {}, function (err) {
  517. UI.message.error(err.message || '生成失败');
  518. });
  519. }
  520. function downloadEps(no) {
  521. no = no || state.drawer.no;
  522. PL.api.download('/admin/orders/' + no + '/eps', no + '-刀版1to1.eps').then(function () {
  523. UI.message.success({ content: 'EPS 已下载:CorelDRAW 打开后「另存为 CDR」即得 .cdr 文件', duration: 5 });
  524. }, function (err) {
  525. UI.message.error(err.message || '生成失败');
  526. });
  527. }
  528. /* ---------------- 视图 ---------------- */
  529. function LoginView() {
  530. return h('div', { className: 'pl-admin-login' },
  531. h('div', { className: 'pl-admin-login-card' },
  532. h('div', { className: 'pl-admin-login-brand' },
  533. h('span', { className: 'logo-mark' },
  534. h('svg', { viewBox: '0 0 24 24', fill: 'none', width: 30, height: 30 },
  535. 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' }),
  536. h('path', { d: 'M7.4 11.1h9.2', stroke: '#17140f', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  537. h('circle', { cx: 14.2, cy: 11.1, r: 1.15, fill: '#ff5c2b' }),
  538. h('path', { d: 'M9.5 14.4h4.9', stroke: '#ff5c2b', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  539. h('path', { d: 'M17.8 5.2v2.4M16.6 6.4h2.4', stroke: '#17140f', 'stroke-width': 1.2, 'stroke-linecap': 'round' }))),
  540. h('div', null,
  541. h('div', { className: 'pl-admin-login-title' }, '袋研社 · 后台管理'),
  542. h('small', { style: { color: '#a79d8d', letterSpacing: '0.12em', fontSize: 10 } }, 'POUCHLAB ADMIN'))),
  543. h(A.Form, { layout: 'vertical', onFinish: doLogin },
  544. h(A.Form.Item, { label: '用户名', style: { marginBottom: 14 } },
  545. h(A.Input, {
  546. value: state.login.username, size: 'large', placeholder: '管理员账号',
  547. onChange: function (e) { state.login.username = e.target.value; render(); }
  548. })),
  549. h(A.Form.Item, { label: '密码', style: { marginBottom: 20 } },
  550. h(A.Input.Password, {
  551. value: state.login.password, size: 'large', placeholder: '密码',
  552. onChange: function (e) { state.login.password = e.target.value; render(); }
  553. })),
  554. h(A.Button, { type: 'primary', htmlType: 'submit', size: 'large', block: true,
  555. loading: state.login.busy }, '登 录')),
  556. h('p', { style: { fontSize: 11, color: '#c3baa9', textAlign: 'center', marginTop: 16 } },
  557. '默认账号 admin / admin123,登录后请尽快修改密码')
  558. )
  559. );
  560. }
  561. function StatusTag(v) { const m = statusMeta(v); return h(A.Tag, { color: m.color }, m.label); }
  562. function PayTag(v) { const m = payMeta(v); return h(A.Tag, { color: m.color }, m.label); }
  563. function DashboardView() {
  564. const s = state.stats || {};
  565. const cards = [
  566. { num: s.ordersTotal, lbl: '订单总数' },
  567. { num: s.ordersToday, lbl: '今日新增订单' },
  568. { num: s.pendingShip, lbl: '待发货' },
  569. { num: fmtMoney(s.revenue), lbl: '已支付金额' },
  570. { num: s.usersTotal, lbl: '注册用户' },
  571. { num: s.aiCallsToday != null ? s.aiCallsToday : '-', lbl: '今日 AI 排版' }
  572. ];
  573. const cols = [
  574. { title: '订单号', dataIndex: 'orderNo', render: function (v, r) { return h('a', { onClick: function () { openOrder(v); } }, v); } },
  575. { title: '类型', dataIndex: 'type', width: 80, render: function (v) { return TYPE_LABEL[v] || v; } },
  576. { title: '规格', dataIndex: 'summary', ellipsis: true },
  577. { title: '金额', dataIndex: 'total', width: 100, render: fmtMoney },
  578. { title: '支付', dataIndex: 'payStatus', width: 90, render: PayTag },
  579. { title: '状态', dataIndex: 'status', width: 90, render: StatusTag },
  580. { title: '下单时间', dataIndex: 'createdAt', width: 110, render: fmtTime }
  581. ];
  582. return h('div', null,
  583. h('div', { className: 'pl-admin-stat-grid' },
  584. cards.map(function (c, i) {
  585. return h('div', { className: 'pl-admin-card pl-admin-stat', key: i },
  586. h('span', { className: 'num' }, c.num == null ? '-' : c.num),
  587. h('span', { className: 'lbl' }, c.lbl));
  588. })),
  589. h('div', { className: 'pl-admin-card' },
  590. h('div', { style: { display: 'flex', alignItems: 'center', marginBottom: 12 } },
  591. h('b', { style: { fontSize: 15 } }, '最新订单'),
  592. h('span', { style: { flex: 1 } }),
  593. h(A.Button, { size: 'small', type: 'link', onClick: function () { state.view = 'orders'; loadOrders(); render(); } }, '全部订单 →')),
  594. h(A.Table, {
  595. columns: cols, dataSource: state.recent, rowKey: 'orderNo',
  596. size: 'small', pagination: false, loading: !state.stats && !state.recent.length
  597. }))
  598. );
  599. }
  600. function OrdersView() {
  601. const f = state.orders.filter;
  602. const cols = [
  603. { title: '订单号', dataIndex: 'orderNo', width: 150, render: function (v) { return h('a', { onClick: function () { openOrder(v); } }, v); } },
  604. { title: '类型', dataIndex: 'type', width: 76, render: function (v) { return TYPE_LABEL[v] || v; } },
  605. { title: '规格摘要', dataIndex: 'summary', ellipsis: true },
  606. { title: '数量', dataIndex: 'spec', width: 70, render: function (s) { return s && s.qty ? s.qty : '-'; } },
  607. { title: '金额', dataIndex: 'total', width: 96, render: function (v) { return h('b', null, fmtMoney(v)); } },
  608. { title: '支付', dataIndex: 'payStatus', width: 86, render: PayTag },
  609. { title: '状态', dataIndex: 'status', width: 86, render: StatusTag },
  610. { title: '联系人', dataIndex: 'contactName', width: 90, render: function (v, r) { return v + ' / ' + (r.contactPhone || '-'); } },
  611. { title: '下单', dataIndex: 'createdAt', width: 100, render: fmtTime },
  612. { title: '操作', key: 'act', width: 170, render: function (_, r) {
  613. return h(A.Space, { size: 4 },
  614. h(A.Button, { size: 'small', onClick: function () { openOrder(r.orderNo); } }, '详情'),
  615. h(A.Button, { size: 'small', onClick: function () { openCadPreview(r.orderNo); } }, 'CAD'));
  616. } }
  617. ];
  618. return h('div', null,
  619. h('div', { className: 'pl-admin-card', style: { marginBottom: 14, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' } },
  620. h(A.Select, { value: f.type, style: { width: 110 }, placeholder: '类型',
  621. allowClear: true, options: [{ value: 'bag', label: '包装袋' }, { value: 'box', label: '纸盒' }],
  622. onChange: function (v) { f.type = v || ''; state.orders.page = 1; loadOrders(); } }),
  623. h(A.Select, { value: f.status, style: { width: 110 }, placeholder: '订单状态',
  624. allowClear: true, options: STATUS.map(function (s) { return { value: s.value, label: s.label }; }),
  625. onChange: function (v) { f.status = v || ''; state.orders.page = 1; loadOrders(); } }),
  626. isFactory() ? null : h(A.Select, { value: f.pay, style: { width: 110 }, placeholder: '支付状态',
  627. allowClear: true, options: PAYS.map(function (s) { return { value: s.value, label: s.label }; }),
  628. onChange: function (v) { f.pay = v || ''; state.orders.page = 1; loadOrders(); } }),
  629. h(A.Input.Search, { value: f.query, style: { width: isFactory() ? 250 : 250 }, placeholder: isFactory() ? '搜索订单号' : '搜索订单号 / 联系人 / 手机号',
  630. allowClear: true,
  631. onChange: function (e) { f.query = e.target.value; render(); },
  632. onSearch: function () { state.orders.page = 1; loadOrders(); } }),
  633. !isFactory() && f.userId ? h(A.Tag, { closable: true, onClose: function () { f.userId = 0; f.userName = ''; state.orders.page = 1; loadOrders(); } },
  634. '用户:' + (f.userName || f.userId)) : null
  635. ),
  636. h('div', { className: 'pl-admin-card' },
  637. h(A.Table, {
  638. columns: cols, dataSource: state.orders.items, rowKey: 'orderNo',
  639. size: 'small', loading: state.orders.loading,
  640. pagination: {
  641. current: state.orders.page, total: state.orders.total, pageSize: state.orders.pageSize,
  642. showSizeChanger: false, showTotal: function (t) { return '共 ' + t + ' 单'; },
  643. onChange: function (p) { state.orders.page = p; loadOrders(); }
  644. }
  645. }))
  646. );
  647. }
  648. function UsersView() {
  649. const userCols = [
  650. { title: 'ID', dataIndex: 'id', width: 60 },
  651. { title: '邮箱', dataIndex: 'email', width: 180, render: function (v) { return v || '—'; } },
  652. { title: '手机号(旧)', dataIndex: 'phone', width: 120, render: function (v) { return v || '—'; } },
  653. { title: '昵称', dataIndex: 'name', width: 120 },
  654. { title: '订单数', dataIndex: 'orderCount', width: 80 },
  655. { title: '消费额', dataIndex: 'paidTotal', width: 100, render: fmtMoney },
  656. { title: 'AI 用量', dataIndex: 'aiUsed', width: 100, render: function (_, u) {
  657. return (u.aiUsed || 0) + ' / ' + (u.aiQuota == null ? 20 : u.aiQuota);
  658. } },
  659. { title: '状态', dataIndex: 'status', width: 90, render: function (v) {
  660. return h(A.Tag, { color: v === 'active' ? 'success' : 'error' }, v === 'active' ? '正常' : '已禁用');
  661. } },
  662. { title: '注册时间', dataIndex: 'createdAt', width: 120, render: fmtTime },
  663. { title: '操作', key: 'act', width: 250, render: function (_, u) {
  664. return h(A.Space, { size: 4 },
  665. h(A.Button, { size: 'small', onClick: function () { toggleUser(u); } }, u.status === 'active' ? '禁用' : '启用'),
  666. h(A.Button, { size: 'small', onClick: function () { openQuotaModal(u); } }, 'AI 额度'),
  667. h(A.Button, { size: 'small', type: 'link', onClick: function () {
  668. state.orders.filter.userId = u.id;
  669. state.orders.filter.userName = u.name || u.phone;
  670. state.orders.page = 1;
  671. state.view = 'orders';
  672. loadOrders();
  673. } }, '查看订单'));
  674. } }
  675. ];
  676. const facCols = [
  677. { title: 'ID', dataIndex: 'id', width: 60 },
  678. { title: '用户名', dataIndex: 'username', width: 130 },
  679. { title: '工厂名称', dataIndex: 'name', width: 160 },
  680. { title: '分配订单数', dataIndex: 'orderCount', width: 100 },
  681. { title: '状态', dataIndex: 'status', width: 90, render: function (v) {
  682. return h(A.Tag, { color: v === 'active' ? 'success' : 'error' }, v === 'active' ? '正常' : '已禁用');
  683. } },
  684. { title: '创建时间', dataIndex: 'createdAt', width: 120, render: fmtTime },
  685. { title: '操作', key: 'act', width: 260, render: function (_, u) {
  686. return h(A.Space, { size: 4 },
  687. h(A.Button, { size: 'small', onClick: function () { toggleFactoryAccount(u); } }, u.status === 'active' ? '禁用' : '启用'),
  688. h(A.Button, { size: 'small', onClick: function () {
  689. state.facModal = { open: true, id: u.id, username: u.username, name: u.name, password: '', busy: false, isCreate: false };
  690. render();
  691. } }, '改名/重置密码'));
  692. } }
  693. ];
  694. return h('div', { className: 'pl-admin-card' },
  695. h(A.Tabs, { items: [
  696. { key: 'users', label: '注册用户', children:
  697. h('div', null,
  698. h('div', { style: { display: 'flex', gap: 10, marginBottom: 14 } },
  699. h(A.Input.Search, { value: state.users.query, style: { width: 260 }, placeholder: '搜索手机号 / 邮箱 / 昵称',
  700. allowClear: true,
  701. onChange: function (e) { state.users.query = e.target.value; render(); },
  702. onSearch: function () { state.users.page = 1; loadUsers(); } })),
  703. h(A.Table, {
  704. columns: userCols, dataSource: state.users.items, rowKey: 'id',
  705. size: 'small', loading: state.users.loading,
  706. pagination: {
  707. current: state.users.page, total: state.users.total, pageSize: state.users.pageSize,
  708. showSizeChanger: false, showTotal: function (t) { return '共 ' + t + ' 位用户'; },
  709. onChange: function (p) { state.users.page = p; loadUsers(); }
  710. }
  711. })) },
  712. { key: 'factories', label: '工厂账号', children:
  713. h('div', null,
  714. h(A.Alert, { type: 'info', showIcon: true, style: { marginBottom: 14 },
  715. message: '一家协作工厂一个账号;订单在「订单详情 → 分配工厂」指定后,对应工厂才能看到该订单(用户隐私自动脱敏)' }),
  716. h('div', { style: { marginBottom: 14 } },
  717. h(A.Button, { type: 'primary', onClick: function () {
  718. state.facModal = { open: true, id: 0, username: '', name: '', password: '', busy: false, isCreate: true };
  719. render();
  720. } }, '+ 新建工厂账号')),
  721. h(A.Table, {
  722. columns: facCols, dataSource: state.factories.items, rowKey: 'id',
  723. size: 'small', loading: state.factories.loading, pagination: false
  724. })) }
  725. ], onChange: function (k) { if (k === 'factories' && !state.factories.items.length) loadFactories(); } })
  726. );
  727. }
  728. function FactoryAccountModal() {
  729. const m = state.facModal;
  730. return h(A.Modal, {
  731. open: m.open, width: 460,
  732. title: m.isCreate ? '新建工厂账号' : '修改工厂账号(' + m.username + ')',
  733. okText: m.isCreate ? '创建' : '保存', cancelText: '取消',
  734. confirmLoading: m.busy,
  735. onOk: saveFactoryAccount,
  736. onCancel: function () { m.open = false; render(); }
  737. },
  738. m.isCreate ? h('div', { style: { marginBottom: 12 } },
  739. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '登录用户名(3-30 位字母/数字/下划线)'),
  740. h(A.Input, { value: m.username, placeholder: '如 hangzhou-box',
  741. onChange: function (e) { m.username = e.target.value; render(); } })) : null,
  742. h('div', { style: { marginBottom: 12 } },
  743. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '工厂名称(对外显示)'),
  744. h(A.Input, { value: m.name, placeholder: '如 杭州彩印包装厂',
  745. onChange: function (e) { m.name = e.target.value; render(); } })),
  746. h('div', null,
  747. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } },
  748. m.isCreate ? '初始密码(至少 6 位)' : '重置密码(留空则不修改)'),
  749. h(A.Input.Password, { value: m.password, placeholder: '至少 6 位',
  750. onChange: function (e) { m.password = e.target.value; render(); } })),
  751. h('p', { style: { fontSize: 11, color: '#a79d8d', marginTop: 12 } },
  752. '工厂用此账号在 admin.html 登录,仅见分配给它的订单')
  753. );
  754. }
  755. function specRows(d) {
  756. const s = d.spec || {};
  757. const rows = [
  758. ['类型', TYPE_LABEL[d.type] || d.type],
  759. ['数量', (s.qty || '-') + ' 件'],
  760. ['摘要', d.summary || '-']
  761. ];
  762. if (d.type === 'bag') {
  763. rows.push(['袋型', s.productName || '-']);
  764. rows.push(['尺寸', (s.sizeLabel || '-') + '(' + (s.w || '-') + '×' + (s.h || '-') + ' mm)']);
  765. rows.push(['材质', s.materialName || '-']);
  766. rows.push(['工艺', s.finishName || '-']);
  767. } else {
  768. rows.push(['盒型', (s.boxName || '-') + '(' + (s.boxNo || '-') + ')']);
  769. rows.push(['内尺寸', (s.w || '-') + ' × ' + (s.d || '-') + ' × ' + (s.h || '-') + ' mm']);
  770. rows.push(['材质', (s.materialName || '-') + (s.thickness ? ' · 厚 ' + s.thickness + 'mm' : '')]);
  771. rows.push(['印色', s.printName || '-']);
  772. rows.push(['印刷方式', s.printWay || '-']);
  773. }
  774. const q = d.quote || {};
  775. rows.push(['单价', fmtMoney(q.unit || d.unitPrice)]);
  776. rows.push(['总额', h('b', { style: { color: '#ff5c2b' } }, fmtMoney(d.total))]);
  777. return rows;
  778. }
  779. function OrderDrawer() {
  780. const dw = state.drawer;
  781. const d = dw.data;
  782. const f = dw.form;
  783. return h(A.Drawer, {
  784. open: dw.open, width: 640, title: dw.no ? '订单 ' + dw.no : '订单详情',
  785. onClose: function () { dw.open = false; render(); }
  786. },
  787. !d ? h('div', { style: { padding: 80, textAlign: 'center' } }, h(A.Spin, null)) : h('div', null,
  788. (d.previews || []).length ? h('div', { className: 'pl-preview-grid' },
  789. d.previews.map(function (key) {
  790. const url = previewCache.get(d.orderNo + ':' + key);
  791. return url ? h(A.Image, { key: key, src: url, height: 150, style: { borderRadius: 10, border: '1px solid #efe9dc' } }) : null;
  792. })) : null,
  793. h(A.Descriptions, { title: '规格与金额', column: 2, size: 'small', bordered: true, style: { marginTop: 14 } },
  794. specRows(d).map(function (r, i) {
  795. 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]);
  796. })),
  797. h(A.Descriptions, { title: '下单与联系', column: 1, size: 'small', bordered: true, style: { marginTop: 16 } },
  798. h(A.Descriptions.Item, { label: '用户' }, (d.ownerName || '-') + ' · ' + (d.ownerPhone || '-')),
  799. h(A.Descriptions.Item, { label: '联系人' }, d.contactName + ' · ' + d.contactPhone + (d.contactEmail ? ' · ' + d.contactEmail : '')),
  800. h(A.Descriptions.Item, { label: '收货地址' }, d.address || '-'),
  801. d.note ? h(A.Descriptions.Item, { label: '用户备注' }, d.note) : null),
  802. isFactory() ? null : h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '订单操作'),
  803. isFactory() ? null : h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 } },
  804. h('div', null,
  805. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '订单状态'),
  806. h(A.Select, { value: f.status, style: { width: '100%' },
  807. options: STATUS.map(function (s) { return { value: s.value, label: s.label }; }),
  808. onChange: function (v) { f.status = v; render(); } })),
  809. h('div', null,
  810. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '支付状态'),
  811. h(A.Select, { value: f.pay, style: { width: '100%' },
  812. options: PAYS.map(function (s) { return { value: s.value, label: s.label }; }),
  813. onChange: function (v) { f.pay = v; render(); } }))),
  814. isFactory() ? null : h('div', { style: { marginTop: 10 } },
  815. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '分配工厂(分配后该工厂才能看到此订单)'),
  816. h(A.Select, {
  817. value: f.assignedTo || 0, style: { width: '100%' },
  818. options: [{ value: 0, label: '未分配' }].concat(state.factories.items.map(function (u) {
  819. return { value: u.id, label: (u.name || u.username) + (u.status === 'active' ? '' : '(已禁用)') };
  820. })),
  821. onChange: function (v) { f.assignedTo = v; render(); }
  822. })),
  823. isFactory() ? null : h('div', { style: { marginTop: 10 } },
  824. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '管理员备注'),
  825. h(A.Input.TextArea, { value: f.adminNote, rows: 2, placeholder: '内部备注(用户不可见)',
  826. onChange: function (e) { f.adminNote = e.target.value; render(); } })),
  827. h('div', { style: { marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' } },
  828. isFactory() ? null : h(A.Button, { type: 'primary', loading: dw.saveBusy, onClick: saveOrder }, '保存修改'),
  829. h(A.Button, { type: 'primary', ghost: !isFactory(), onClick: function () { downloadProductionPdf(d.orderNo); } }, '生产图纸 PDF'),
  830. h(A.Tooltip, { title: 'mm 实尺矢量刀版,CorelDRAW/Illustrator 可直接打开编辑(CDR 交付替代)' },
  831. h(A.Button, { onClick: function () { downloadVectorPdf(d.orderNo); } }, '矢量刀版 1:1')),
  832. h(A.Tooltip, { title: 'EPS 矢量(CorelDRAW 原生导入,另存为 CDR 即得 .cdr 文件)' },
  833. h(A.Button, { onClick: function () { downloadEps(d.orderNo); } }, 'EPS(.cdr)')),
  834. h(A.Button, { onClick: function () { openCadPreview(d.orderNo); } }, 'CAD 预览'),
  835. h(A.Button, { onClick: function () { downloadDxf(d.orderNo); } }, 'DXF'),
  836. !isFactory() && d.hasDesign ? h(A.Button, { onClick: function () { downloadDesign(d.orderNo); } }, '设计稿') : null),
  837. isFactory() ? null : h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '物流发货'),
  838. isFactory() ? null : h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1.4fr auto', gap: 10, alignItems: 'center' } },
  839. h(A.Input, { value: f.carrier, placeholder: '快递公司(如 顺丰速运)',
  840. onChange: function (e) { f.carrier = e.target.value; render(); } }),
  841. h(A.Input, { value: f.trackingNo, placeholder: '运单号',
  842. onChange: function (e) { f.trackingNo = e.target.value; render(); } }),
  843. h(A.Button, { type: 'primary', ghost: true, loading: dw.shipBusy, onClick: shipOrder,
  844. disabled: d.status === 'cancelled' }, '发货')),
  845. isFactory() || !d.trackingNo ? null : h('div', { style: { marginTop: 8, fontSize: 12, color: '#7d7466' } },
  846. '当前物流:' + d.carrier + ' · ' + d.trackingNo),
  847. /* 工厂协作:反馈线程(工厂提交 / 管理员回复 / 邮件通知用户) */
  848. h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } },
  849. isFactory() ? '设计问题反馈' : '工厂协作'),
  850. h('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
  851. (d.messages || []).length ? (d.messages || []).map(function (m) {
  852. const isFac = m.senderRole === 'factory';
  853. return h('div', { key: m.id, style: {
  854. background: isFac ? '#fff7f0' : '#f4f8f2',
  855. border: '1px solid ' + (isFac ? '#ffd9c2' : '#dce8d4'),
  856. borderRadius: 10, padding: '8px 10px'
  857. } },
  858. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } },
  859. h('b', { style: { color: isFac ? '#c2610f' : '#4f6b2f' } },
  860. isFac ? '🏭 ' + (m.senderName || '工厂') : '🛠 ' + (m.senderName || '管理员')),
  861. ' ' + fmtTime(m.createdAt)),
  862. h('div', { style: { whiteSpace: 'pre-wrap', fontSize: 13 } }, m.content),
  863. m.emailStatus ? h('div', { style: { marginTop: 6, padding: '6px 8px', background: '#fffdf8', borderRadius: 6, fontSize: 12 } },
  864. '📧 ',
  865. m.emailStatus === 'sent' ? '已发送邮件至 ' + m.emailTo
  866. : m.emailStatus === 'archived' ? '邮件内容已存档(' + (m.emailTo || '未留邮箱') + ')'
  867. : m.emailStatus,
  868. h('div', { style: { color: '#a79d8d', marginTop: 2 } }, '主题:' + m.emailSubject)) : null,
  869. !isFactory() && isFac && !m.emailStatus ? h('div', { style: { marginTop: 6 } },
  870. h(A.Button, { size: 'small', type: 'primary', ghost: true,
  871. onClick: function () { openEmailComposer(d, m); } }, '✉ 邮件通知用户(模板)')) : null);
  872. }) : h('div', { style: { color: '#a79d8d', fontSize: 12.5 } },
  873. isFactory() ? '如发现设计问题(出血不足、图文越界、工艺冲突等),请在下方提交,平台会转达用户。'
  874. : '工厂的反馈会显示在这里,可选择将问题整理成邮件通知用户。')),
  875. h('div', { style: { display: 'flex', gap: 8, marginTop: 4 } },
  876. h(A.Input.TextArea, {
  877. value: dw.replyText, rows: 2,
  878. placeholder: isFactory() ? '描述设计问题(如:正面文字超出安全区 2mm,建议内移…)' : '回复工厂…',
  879. onChange: function (e) { dw.replyText = e.target.value; render(); }
  880. }),
  881. h(A.Button, { type: 'primary', loading: dw.replyBusy, onClick: postReply,
  882. style: { alignSelf: 'flex-end' } }, isFactory() ? '提交反馈' : '回复')),
  883. h('div', { style: { margin: '18px 0 8px', fontWeight: 700 } }, '操作时间线'),
  884. h(A.Timeline, {
  885. items: (d.events || []).slice().reverse().map(function (e) {
  886. return {
  887. color: e.kind === 'logistics' ? 'geekblue' : 'green',
  888. children: h('div', null,
  889. h('div', { style: { fontWeight: 600 } }, e.title + ' ', h('span', { style: { fontWeight: 400, fontSize: 11, color: '#a79d8d' } }, fmtTime(e.createdAt))),
  890. e.detail ? h('div', { style: { fontSize: 12, color: '#7d7466' } }, e.detail) : null)
  891. };
  892. })
  893. })
  894. )
  895. );
  896. }
  897. function EmailComposerModal() {
  898. const m = state.emailModal;
  899. return h(A.Modal, {
  900. open: m.open, width: 640, title: '邮件通知用户(模板已生成,可编辑)',
  901. okText: '发送', cancelText: '取消',
  902. confirmLoading: m.busy,
  903. onOk: sendEmail,
  904. onCancel: function () { m.open = false; render(); }
  905. },
  906. h(A.Alert, {
  907. type: m.to && m.to !== '(未留邮箱)' ? 'info' : 'warning', showIcon: true, style: { marginBottom: 12 },
  908. message: '收件人:' + m.to + (m.to && m.to !== '(未留邮箱)' ? '' : ' — 未配置 SMTP 或订单未留邮箱时,内容将存档到反馈线程,可复制到其他渠道')
  909. }),
  910. h('div', { style: { fontSize: 12, color: '#7d7466', marginBottom: 4 } }, '邮件主题'),
  911. h(A.Input, { value: m.subject,
  912. onChange: function (e) { m.subject = e.target.value; render(); } }),
  913. h('div', { style: { fontSize: 12, color: '#7d7466', margin: '10px 0 4px' } }, '邮件正文(模板已按工厂反馈自动生成)'),
  914. h(A.Input.TextArea, { value: m.body, rows: 12,
  915. onChange: function (e) { m.body = e.target.value; render(); } })
  916. );
  917. }
  918. function CadPreviewModal() {
  919. const m = state.cadModal;
  920. return h(A.Modal, {
  921. open: m.open, width: 1000, title: '工厂 CAD 图纸 ' + (m.no || ''),
  922. onCancel: function () { m.open = false; render(); },
  923. footer: h('div', null,
  924. h('span', { style: { float: 'left', color: '#a79d8d', fontSize: 12, lineHeight: '32px' } }, '滚轮缩放 · 拖拽平移 · 可点选图元查看图层'),
  925. h(A.Button, { onClick: function () { m.open = false; render(); } }, '关闭'),
  926. h(A.Button, { type: 'primary', style: { marginLeft: 8 }, onClick: function () { downloadDxf(m.no); } }, '下载 DXF'))
  927. },
  928. h('div', { id: 'cadPreviewHost', style: { position: 'relative', height: '68vh', background: '#fff', borderRadius: 8, overflow: 'hidden' } },
  929. m.loading ? h('div', { style: { position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', zIndex: 1, background: '#fffdf8' } },
  930. h(A.Spin, null)) : null)
  931. );
  932. }
  933. function App() {
  934. if (!state.booted) {
  935. return h('div', { style: { minHeight: '100vh', display: 'grid', placeItems: 'center' } }, h(A.Spin, null));
  936. }
  937. if (!state.admin) return LoginView();
  938. const fac = isFactory();
  939. const views = fac
  940. ? { orders: OrdersView }
  941. : { dashboard: DashboardView, orders: OrdersView, users: UsersView, aisetting: AiConfigView };
  942. const titles = fac
  943. ? { orders: '生产订单' }
  944. : { dashboard: '仪表盘', orders: '订单管理', users: '用户管理', aisetting: 'AI 设置' };
  945. if (!views[state.view]) state.view = 'orders';
  946. return h(A.Layout, { style: { minHeight: '100vh' } },
  947. h(A.Layout.Sider, { width: 208, className: 'pl-admin-sider', breakpoint: 'lg', collapsedWidth: 0 },
  948. h('div', { className: 'pl-admin-brand' },
  949. h('span', { style: { display: 'inline-flex', fontSize: 18 } },
  950. h('svg', { viewBox: '0 0 24 24', fill: 'none', width: 22, height: 22 },
  951. 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' }),
  952. h('path', { d: 'M7.4 11.1h9.2', stroke: '#17140f', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  953. h('circle', { cx: 14.2, cy: 11.1, r: 1.15, fill: '#ff5c2b' }),
  954. h('path', { d: 'M9.5 14.4h4.9', stroke: '#ff5c2b', 'stroke-width': 1.4, 'stroke-linecap': 'round' }))),
  955. h('span', null, fac ? '工厂协作端' : '袋研社后台',
  956. h('small', null, fac ? 'FACTORY PARTNER' : 'POUCHLAB ADMIN'))),
  957. h(A.Menu, {
  958. className: 'pl-admin-menu', theme: 'dark', mode: 'inline',
  959. selectedKeys: [state.view],
  960. onClick: function (e) {
  961. state.view = e.key;
  962. if (e.key === 'dashboard' && !state.stats) loadDashboard();
  963. if (e.key === 'orders' && !state.orders.items.length) loadOrders();
  964. if (e.key === 'users' && !state.users.items.length) loadUsers();
  965. if (e.key === 'aisetting' && !state.aiConfig.loaded) loadAiConfig();
  966. render();
  967. },
  968. items: fac
  969. ? [{ key: 'orders', label: '📦 生产订单' }]
  970. : [
  971. { key: 'dashboard', label: '📊 仪表盘' },
  972. { key: 'orders', label: '📦 订单管理' },
  973. { key: 'users', label: '👥 用户管理' },
  974. { key: 'aisetting', label: '🤖 AI 设置' }
  975. ]
  976. })),
  977. h(A.Layout, null,
  978. h(A.Layout.Header, { className: 'pl-admin-header', style: { background: '#fffdf8' } },
  979. h('span', { className: 'title' }, titles[state.view]),
  980. h('div', null,
  981. h('span', { style: { color: '#7d7466', fontSize: 12.5, marginRight: 12 } },
  982. (state.admin.name || state.admin.username) + (fac ? '(协作工厂)' : '(管理员)')),
  983. h(A.Button, { size: 'small', onClick: logout }, '退出'))),
  984. h(A.Layout.Content, { style: { padding: 20, overflow: 'initial' } },
  985. (views[state.view])(),
  986. OrderDrawer(),
  987. CadPreviewModal(),
  988. EmailComposerModal(),
  989. FactoryAccountModal(),
  990. QuotaModal()))
  991. );
  992. }
  993. function render() {
  994. UI.render(document.getElementById('root'), App());
  995. }
  996. document.addEventListener('pl:auth-expired', function () {
  997. if (state.admin) UI.message.warning('登录已失效,请重新登录');
  998. state.admin = null;
  999. render();
  1000. });
  1001. boot();
  1002. })();