orders.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /* 我的订单:登录门禁 + 订单列表 + 详情(支付状态 / 生产进度 / 物流) */
  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 state = {
  8. items: [], total: 0, local: [], page: 1, pageSize: 8, loading: false,
  9. drawer: null, // 选中的订单(详情)
  10. detail: null, // 详情数据(含 events)
  11. detailBusy: false
  12. };
  13. const previewCache = new Map(); // "orderNo:key" -> objectURL
  14. const localPreview = new Map(); // "orderNo:key" -> dataURL(本地订单)
  15. const STATUS_OPTS = {
  16. pending_payment: { label: '待支付', color: 'orange' },
  17. producing: { label: '生产中', color: 'processing' },
  18. shipped: { label: '已发货', color: 'geekblue' },
  19. completed: { label: '已完成', color: 'success' },
  20. cancelled: { label: '已取消', color: 'default' }
  21. };
  22. const PAY_OPTS = {
  23. unpaid: { label: '未支付', color: 'orange' },
  24. paid: { label: '已支付', color: 'success' },
  25. refunded: { label: '已退款', color: 'purple' }
  26. };
  27. const TYPE_LABEL = { bag: '包装袋', box: '纸盒' };
  28. function fmtTime(ts) { return ts ? dayjs(ts * 1000).format('YYYY-MM-DD HH:mm') : '-'; }
  29. function statusTag(s) {
  30. const o = STATUS_OPTS[s] || { label: s, color: 'default' };
  31. return h(A.Tag, { color: o.color }, o.label);
  32. }
  33. function payTag(p) {
  34. const o = PAY_OPTS[p] || { label: p, color: 'default' };
  35. return h(A.Tag, { color: o.color }, o.label);
  36. }
  37. function loadPreview(orderNo, key) {
  38. const k = orderNo + ':' + key;
  39. if (previewCache.has(k)) return Promise.resolve(previewCache.get(k));
  40. return fetch('/api/orders/mine/' + orderNo + '/preview/' + key, {
  41. headers: PL.api.token() ? { Authorization: 'Bearer ' + PL.api.token() } : {}
  42. }).then(function (res) {
  43. if (!res.ok) throw new Error('preview');
  44. return res.blob();
  45. }).then(function (blob) {
  46. const url = URL.createObjectURL(blob);
  47. previewCache.set(k, url);
  48. return url;
  49. }).catch(function () {
  50. previewCache.set(k, null);
  51. return null;
  52. });
  53. }
  54. function previewSrc(orderNo, key) {
  55. if (!key) return null;
  56. return localPreview.get(orderNo + ':' + key) || previewCache.get(orderNo + ':' + key) || null;
  57. }
  58. /* ---------------- 本地订单(离线下单 / 本机保存) ---------------- */
  59. function bagPreview(no, design, side) {
  60. const k = no + ':' + side;
  61. if (localPreview.has(k)) return localPreview.get(k);
  62. let url = null;
  63. try {
  64. const R = window.PL.render;
  65. const D = window.PL.data;
  66. if (R && D) {
  67. const prod = D.productById(design.productId) || D.products[0];
  68. const s = design.sizeId === 'custom' && design.customSize
  69. ? { id: 'custom', label: '自定义', w: design.customSize.w, h: design.customSize.h }
  70. : D.sizeOf(prod, design.sizeId);
  71. const paint = design.bagColor ? Object.assign({}, prod, { mockColor: design.bagColor }) : prod;
  72. const sd = (design.sides && design.sides[side]) || { bg: null, elements: [] };
  73. const svg = R.bagSVG(paint, side, sd, { size: s, card: true, material: design.material, finish: design.finish });
  74. url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
  75. }
  76. } catch (e) { url = null; }
  77. localPreview.set(k, url);
  78. return url;
  79. }
  80. function bagSummary(design) {
  81. if (!design) return '包装袋';
  82. const D = window.PL.data;
  83. if (!D) return '包装袋';
  84. try {
  85. const p = D.productById(design.productId);
  86. const s = design.sizeId === 'custom' && design.customSize
  87. ? design.customSize
  88. : D.sizeOf(p, design.sizeId);
  89. return [p ? p.name : '包装袋', s ? (s.w + '×' + s.h + 'mm') : '', design.qty ? design.qty + ' 只' : '']
  90. .filter(Boolean).join(' · ');
  91. } catch (e) {
  92. return '包装袋';
  93. }
  94. }
  95. function bagLocalOrder(raw, key) {
  96. let design = raw.design;
  97. if (typeof design === 'string') {
  98. try { design = JSON.parse(design); } catch (e) { design = null; }
  99. }
  100. const no = raw.order || key.replace('pouchlab.order.', '');
  101. const qty = (raw.spec && raw.spec.qty) || raw.qty || (design && design.qty) || 0;
  102. const total = Number(raw.total || 0);
  103. const previews = [];
  104. if (design) {
  105. ['front', 'back'].forEach(function (side) {
  106. if (bagPreview(no, design, side)) previews.push(side);
  107. });
  108. } else if (raw.previews) {
  109. Object.keys(raw.previews).forEach(function (k) {
  110. const v = raw.previews[k];
  111. if (!v) return;
  112. localPreview.set(no + ':' + k, /^data:/.test(v) ? v : 'data:image/png;base64,' + v);
  113. previews.push(k);
  114. });
  115. }
  116. return {
  117. orderNo: no, type: 'bag', local: true,
  118. summary: raw.summary || bagSummary(design),
  119. spec: { qty: qty },
  120. total: total, unitPrice: qty ? total / qty : 0,
  121. contactName: raw.name || '-', contactPhone: raw.phone || '-', contactEmail: raw.email || '',
  122. address: raw.address || '(本机订单未记录地址)', note: raw.note || '',
  123. payStatus: 'unpaid', status: 'pending_payment',
  124. createdAt: Math.floor((raw.at || Date.now()) / 1000),
  125. previews: previews
  126. };
  127. }
  128. function boxLocalOrder(raw) {
  129. const no = raw.no || ('PLX' + (raw.time || Date.now()));
  130. const previews = [];
  131. Object.keys(raw.previews || {}).forEach(function (k) {
  132. const v = raw.previews[k];
  133. if (!v) return;
  134. localPreview.set(no + ':' + k, /^data:/.test(v) ? v : 'data:image/png;base64,' + v);
  135. previews.push(k);
  136. });
  137. // 列表缩略图优先展示 3D 效果
  138. const shot = previews.indexOf('box3d');
  139. if (shot > 0) previews.unshift(previews.splice(shot, 1)[0]);
  140. const qty = Number(raw.qty || 0);
  141. const total = Number(raw.total || 0);
  142. return {
  143. orderNo: no, type: 'box', local: true,
  144. summary: raw.summary || ('纸盒 ' + (raw.boxNo || '') + ' · ' + qty + ' 个'),
  145. spec: { qty: qty },
  146. total: total, unitPrice: qty ? total / qty : 0,
  147. contactName: raw.name || '-', contactPhone: '', contactEmail: '',
  148. address: '(本机订单未记录地址)', note: '',
  149. payStatus: 'unpaid', status: 'pending_payment',
  150. createdAt: Math.floor((raw.time || Date.now()) / 1000),
  151. previews: previews
  152. };
  153. }
  154. function buildLocalOrders() {
  155. const list = [];
  156. try {
  157. for (let i = 0; i < localStorage.length; i += 1) {
  158. const key = localStorage.key(i);
  159. if (!key || key.indexOf('pouchlab.order.') !== 0) continue;
  160. try {
  161. const raw = JSON.parse(localStorage.getItem(key) || 'null');
  162. if (raw) list.push(bagLocalOrder(raw, key));
  163. } catch (e) {}
  164. }
  165. } catch (e) {}
  166. try {
  167. const boxOrders = JSON.parse(localStorage.getItem('pouchlab.box.orders') || '[]');
  168. if (Array.isArray(boxOrders)) boxOrders.forEach(function (raw) { if (raw && raw.no) list.push(boxLocalOrder(raw)); });
  169. } catch (e) {}
  170. return list.sort(function (a, b) { return b.createdAt - a.createdAt; });
  171. }
  172. function loadList() {
  173. state.loading = true;
  174. render();
  175. PL.api.get('/orders/mine?page=' + state.page + '&page_size=' + state.pageSize).then(function (r) {
  176. state.items = r.items || [];
  177. // 本地订单(离线保存 / 盒子本机订单)与服务端订单按单号去重
  178. if (state.page === 1) {
  179. state.local = buildLocalOrders().filter(function (o) {
  180. return !state.items.some(function (item) { return item.orderNo === o.orderNo; });
  181. });
  182. }
  183. state.total = (r.total || 0) + state.local.length;
  184. state.loading = false;
  185. render();
  186. // 预取每行首图
  187. state.items.forEach(function (o) {
  188. if (o.previews && o.previews.length) loadPreview(o.orderNo, o.previews[0]).then(function () { render(); });
  189. });
  190. }, function (err) {
  191. state.items = [];
  192. if (state.page === 1) state.local = buildLocalOrders();
  193. state.total = state.local.length;
  194. state.loading = false;
  195. if (!err.network) UI.message.error(err.message || '订单加载失败');
  196. render();
  197. });
  198. }
  199. function openDetail(order) {
  200. state.drawer = order;
  201. state.detail = null;
  202. render();
  203. if (order.local) {
  204. state.detail = Object.assign({}, order, {
  205. events: [{
  206. kind: 'status', title: '订单保存在本机',
  207. detail: '服务器未收到该订单,联网后请在设计页重新提交',
  208. createdAt: order.createdAt
  209. }]
  210. });
  211. render();
  212. return;
  213. }
  214. PL.api.get('/orders/mine/' + order.orderNo).then(function (d) {
  215. state.detail = d;
  216. render();
  217. (d.previews || []).forEach(function (key) {
  218. loadPreview(d.orderNo, key).then(function () { render(); });
  219. });
  220. }, function (err) {
  221. UI.message.error(err.message || '详情加载失败');
  222. state.drawer = null;
  223. render();
  224. });
  225. }
  226. function refreshDetail(order) {
  227. PL.api.get('/orders/mine/' + order.orderNo).then(function (full) {
  228. if (state.drawer && state.drawer.orderNo === order.orderNo) {
  229. state.detail = full;
  230. render();
  231. }
  232. }, function () {});
  233. }
  234. function doPay(order) {
  235. state.detailBusy = true;
  236. render();
  237. PL.api.post('/orders/mine/' + order.orderNo + '/pay').then(function (d) {
  238. state.detailBusy = false;
  239. state.detail = d;
  240. UI.message.success('支付成功(模拟),订单已进入生产');
  241. loadList();
  242. refreshDetail(order);
  243. }, function (err) {
  244. state.detailBusy = false;
  245. UI.message.error(err.message || '支付失败');
  246. render();
  247. });
  248. }
  249. function doCancel(order) {
  250. state.detailBusy = true;
  251. render();
  252. PL.api.post('/orders/mine/' + order.orderNo + '/cancel').then(function (d) {
  253. state.detailBusy = false;
  254. state.detail = d;
  255. UI.message.success('订单已取消');
  256. loadList();
  257. refreshDetail(order);
  258. }, function (err) {
  259. state.detailBusy = false;
  260. UI.message.error(err.message || '取消失败');
  261. render();
  262. });
  263. }
  264. function copyTracking(no) {
  265. if (navigator.clipboard && navigator.clipboard.writeText) {
  266. navigator.clipboard.writeText(no).then(function () { UI.message.success('运单号已复制'); });
  267. }
  268. }
  269. /* ---------------- 视图 ---------------- */
  270. function Header(user) {
  271. return h('div', { className: 'pl-orders-header' },
  272. h('div', { className: 'pl-orders-wrap' },
  273. h('a', { className: 'logo', href: 'index.html' },
  274. h('span', { className: 'logo-mark' },
  275. h('svg', { viewBox: '0 0 24 24', fill: 'none' },
  276. 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' }),
  277. h('path', { d: 'M7.4 11.1h9.2', stroke: '#17140f', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  278. h('circle', { cx: 14.2, cy: 11.1, r: 1.15, fill: '#ff5c2b' }),
  279. h('path', { d: 'M9.5 14.4h4.9', stroke: '#ff5c2b', 'stroke-width': 1.4, 'stroke-linecap': 'round' }),
  280. h('path', { d: 'M17.8 5.2v2.4M16.6 6.4h2.4', stroke: '#17140f', 'stroke-width': 1.2, 'stroke-linecap': 'round' }))),
  281. h('span', { className: 'logo-type' }, h('b', null, '袋研社'), h('span', null, 'POUCHLAB'))),
  282. h('span', { className: 'spacer' }),
  283. h('a', { className: 'pl-nav', href: 'studio.html' }, '包装袋设计'),
  284. h('a', { className: 'pl-nav', href: 'box.html' }, '纸盒设计'),
  285. user
  286. ? h(A.Button, { size: 'small', onClick: function () { window.PL.auth.logout(); } }, '退出登录')
  287. : h(A.Button, { size: 'small', onClick: function () { window.PL.auth.open(); } }, '登录')
  288. )
  289. );
  290. }
  291. function LoginGate() {
  292. return h('div', { style: { padding: '90px 0', background: '#fffdf8', borderRadius: 16, border: '1px solid #e2dacb' } },
  293. h(A.Empty, {
  294. description: '登录后可查看订单的支付状态、生产进度与物流信息',
  295. image: A.Empty.PRESENTED_IMAGE_SIMPLE
  296. }),
  297. h('div', { style: { textAlign: 'center', marginTop: 18 } },
  298. h(A.Button, { type: 'primary', size: 'large', onClick: function () { window.PL.auth.open(); } }, '手机号登录')
  299. )
  300. );
  301. }
  302. function OrderCard(order) {
  303. const key = order.previews && order.previews.length ? order.previews[0] : null;
  304. const thumb = previewSrc(order.orderNo, key);
  305. return h('div', { className: 'pl-orders-card', key: order.orderNo, onClick: function () { openDetail(order); } },
  306. h('div', { className: 'pl-orders-thumb' }, thumb ? h('img', { src: thumb }) : null),
  307. h('div', { className: 'pl-orders-info' },
  308. h('div', { className: 'pl-orders-no' }, order.orderNo,
  309. h(A.Tag, { style: { marginLeft: 10 } }, TYPE_LABEL[order.type] || order.type),
  310. order.local ? h(A.Tag, { color: 'orange', style: { marginLeft: 6 } }, '本机保存') : null),
  311. h('div', { className: 'pl-orders-summary' }, order.summary || '-'),
  312. h('div', { className: 'pl-orders-time' }, '下单时间 ' + fmtTime(order.createdAt))
  313. ),
  314. h('div', { className: 'pl-orders-side' },
  315. h('div', { className: 'pl-orders-amount' }, '¥' + Number(order.total).toFixed(2),
  316. h('small', null, ' / ' + ((order.spec && order.spec.qty) || '-') + ' 件')),
  317. h('div', { className: 'pl-orders-tags' },
  318. payTag(order.payStatus),
  319. statusTag(order.status))
  320. )
  321. );
  322. }
  323. function DetailDrawer() {
  324. const order = state.detail || state.drawer || {};
  325. const d = state.detail;
  326. const spec = order.spec || {};
  327. const canPay = !order.local && order.payStatus === 'unpaid' && (order.status === 'pending_payment');
  328. const canCancel = !order.local && order.payStatus === 'unpaid' && ['pending_payment', 'producing'].indexOf(order.status) >= 0;
  329. const events = d ? d.events || [] : [];
  330. const shipped = d && d.carrier;
  331. return h(A.Drawer, {
  332. open: !!state.drawer, width: 560, title: '订单详情 ' + (order.orderNo || ''),
  333. onClose: function () { state.drawer = null; state.detail = null; render(); },
  334. footer: null
  335. },
  336. d ? h('div', null,
  337. order.local ? h(A.Alert, {
  338. type: 'warning', showIcon: true,
  339. message: '该订单保存在本机,尚未同步到服务器',
  340. description: '联网后可在设计页重新提交;设计稿与预览图已随订单保存在本机。',
  341. style: { marginBottom: 14 }
  342. }) : null,
  343. (d.previews || []).length ? h('div', { className: 'pl-preview-grid' },
  344. d.previews.map(function (key) {
  345. const url = previewSrc(d.orderNo, key);
  346. return url ? h('img', { key: key, src: url, title: key }) : null;
  347. })
  348. ) : null,
  349. h(A.Descriptions, { title: '规格与金额', column: 2, size: 'small', bordered: true, style: { marginTop: 14 } },
  350. h(A.Descriptions.Item, { label: '类型', span: 1 }, TYPE_LABEL[d.type] || d.type),
  351. h(A.Descriptions.Item, { label: '数量', span: 1 }, (spec.qty || '-') + ' 件'),
  352. h(A.Descriptions.Item, { label: '规格', span: 2 }, d.summary || '-'),
  353. h(A.Descriptions.Item, { label: '单价', span: 1 }, '¥' + Number(d.unitPrice || 0).toFixed(2)),
  354. h(A.Descriptions.Item, { label: '总额', span: 1 }, h('b', { style: { color: '#ff5c2b' } }, '¥' + Number(d.total || 0).toFixed(2))),
  355. h(A.Descriptions.Item, { label: '支付状态', span: 1 }, payTag(d.payStatus)),
  356. h(A.Descriptions.Item, { label: '订单状态', span: 1 }, statusTag(d.status))
  357. ),
  358. h(A.Descriptions, { title: '收货信息', column: 1, size: 'small', bordered: true, style: { marginTop: 18 } },
  359. h(A.Descriptions.Item, { label: '联系人' }, d.contactName + (d.contactPhone ? ' · ' + d.contactPhone : '')),
  360. h(A.Descriptions.Item, { label: '地址' }, d.address || '-'),
  361. d.note ? h(A.Descriptions.Item, { label: '备注' }, d.note) : null
  362. ),
  363. shipped ? h(A.Descriptions, { title: '物流信息', column: 1, size: 'small', bordered: true, style: { marginTop: 18 } },
  364. h(A.Descriptions.Item, { label: '承运商' }, d.carrier),
  365. h(A.Descriptions.Item, { label: '运单号' },
  366. h('span', null, h('b', { style: { letterSpacing: '0.04em' } }, d.trackingNo), ' ',
  367. h(A.Button, { size: 'small', type: 'link', onClick: function () { copyTracking(d.trackingNo); } }, '复制')))
  368. ) : h(A.Alert, {
  369. type: d.status === 'completed' || d.status === 'cancelled' ? 'info' : 'warning',
  370. message: d.status === 'shipped' ? '物流信息录入中' : '尚未发货',
  371. description: d.status === 'cancelled' ? '订单已取消' : '工厂发货后将在此展示快递公司与运单号,可直接复制查询。',
  372. showIcon: true, style: { marginTop: 18 }
  373. }),
  374. h('div', { style: { margin: '20px 0 6px', fontWeight: 700 } }, '进度时间线'),
  375. h(A.Timeline, {
  376. items: events.slice().reverse().map(function (e) {
  377. return {
  378. color: e.kind === 'logistics' ? 'geekblue' : (e.kind === 'status' && e.title.indexOf('取消') >= 0 ? 'gray' : 'green'),
  379. children: h('div', null,
  380. h('div', { style: { fontWeight: 600 } }, e.title),
  381. e.detail ? h('div', { style: { fontSize: 12, color: '#7d7466' } }, e.detail) : null,
  382. h('div', { style: { fontSize: 11, color: '#a79d8d' } }, fmtTime(e.createdAt))
  383. )
  384. };
  385. })
  386. }),
  387. (canPay || canCancel) ? h('div', { style: { display: 'flex', gap: 10, marginTop: 16 } },
  388. canPay ? h(A.Popconfirm, {
  389. title: '模拟支付', description: '确认支付 ¥' + Number(order.total).toFixed(2) + '?(演示环境不会真实扣款)',
  390. onConfirm: function () { doPay(order); }
  391. }, h(A.Button, { type: 'primary', loading: state.detailBusy }, '立即支付')) : null,
  392. canCancel ? h(A.Popconfirm, {
  393. title: '取消订单', description: '确定取消该订单吗?',
  394. onConfirm: function () { doCancel(order); }
  395. }, h(A.Button, { danger: true }, '取消订单')) : null
  396. ) : null
  397. ) : h('div', { style: { padding: 60, textAlign: 'center' } }, h(A.Spin, null))
  398. );
  399. }
  400. function App() {
  401. const user = window.PL.auth ? window.PL.auth.user() : null;
  402. const locals = state.page === 1 ? state.local : [];
  403. const list = locals.concat(state.items);
  404. return h('div', null,
  405. Header(user),
  406. h('main', { className: 'pl-orders-main' },
  407. !user ? LoginGate() :
  408. h('div', null,
  409. h('div', { style: { display: 'flex', alignItems: 'center', marginBottom: 16 } },
  410. h('h2', { style: { margin: 0, fontSize: 22, letterSpacing: '-0.02em' } }, '我的订单'),
  411. h('span', { style: { color: '#a79d8d', fontSize: 12.5, marginLeft: 10 } }, '共 ' + state.total + ' 单')),
  412. state.loading && !list.length
  413. ? h('div', { style: { padding: 80, textAlign: 'center' } }, h(A.Spin, null))
  414. : (list.length
  415. ? h('div', null,
  416. list.map(OrderCard),
  417. state.total > state.pageSize ? h('div', { style: { textAlign: 'center', marginTop: 20 } },
  418. h(A.Pagination, {
  419. current: state.page, total: state.total, pageSize: state.pageSize,
  420. showSizeChanger: false,
  421. onChange: function (p) { state.page = p; loadList(); }
  422. })) : null)
  423. : h(A.Empty, { description: '还没有订单,去设计一款包装吧', image: A.Empty.PRESENTED_IMAGE_SIMPLE },
  424. h(A.Button, { type: 'primary', href: 'studio.html' }, '开始设计'))),
  425. DetailDrawer()
  426. )
  427. )
  428. );
  429. }
  430. function render() {
  431. UI.render(document.getElementById('root'), App());
  432. }
  433. document.addEventListener('pl:auth', function () {
  434. const user = window.PL.auth ? window.PL.auth.user() : null;
  435. if (user) { state.page = 1; loadList(); } else { state.items = []; state.local = []; state.total = 0; }
  436. render();
  437. });
  438. document.addEventListener('pl:auth-expired', function () {
  439. state.items = []; state.local = []; state.total = 0; state.drawer = null; state.detail = null;
  440. UI.message.warning('登录已失效,请重新登录');
  441. render();
  442. });
  443. const user = window.PL.auth ? window.PL.auth.user() : null;
  444. if (user) loadList();
  445. render();
  446. })();