256 Commits
Author SHA1 Message Date
liuyihe e433f5086b 优化 2026-11-03 16:52:02 +08:00
liuyihe 95fb17c5aa 优化 2026-11-03 11:43:56 +08:00
liuyihe 5a1cde6c0f 优化 2026-11-02 17:15:55 +08:00
ouyangxq 63193d04de 恢复账单明细入口并完善采购状态展示 2026-10-30 18:50:56 +08:00
liuyihe 119b4d6d66 优化 2026-10-30 18:15:16 +08:00
liuyihe f76dc4c7e3 Merge origin/release/test preserving asynchronous order funding and retry coverage 2026-10-30 18:03:37 +08:00
liuyihe ad72ab8406 优化 2026-10-30 17:59:48 +08:00
ouyangxq 55868177cd 完善企业编辑页面并修复采购建单重试 2026-10-30 15:42:38 +08:00
liuyihe d6ef770e48 优化 2026-10-30 11:20:03 +08:00
ouyangxq bda33648f3 统一海外仓新增页样式与字段校验 2026-10-29 16:14:44 +08:00
liuyihe 3abcdcbd89 优化 2026-10-29 15:49:59 +08:00
liuyihe aacaf4fdde 优化 2026-10-29 14:38:49 +08:00
ouyangxq e3d94d06c9 统一客户端采购与运输新增页样式及必填提示 2026-10-29 14:15:27 +08:00
liuyihe b977ccd89d Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-29 13:37:30 +08:00
liuyihe f51e51d50f 优化 2026-10-29 13:37:28 +08:00
ouyangxq 8dd7b16d1d 精简采购下单提示并压缩模块间距 2026-10-29 12:03:31 +08:00
ouyangxq 57be5316d0 优化海外采购新增页布局和预算摘要 2026-10-29 11:39:01 +08:00
liuyihe 338c28c304 优化 2026-10-29 10:53:47 +08:00
ouyangxq fdf646227e 精简客户采购及头程计费详情展示 2026-10-28 16:56:33 +08:00
liuyihe e5c4003e3d 优化 2026-10-28 16:33:35 +08:00
liuyihe 510db2bb8c 优化 2026-10-28 14:45:17 +08:00
ouyangxq c187544a94 修复客户订单列设置持久化并统一最新计费量展示 2026-10-28 11:56:49 +08:00
liuyihe 3ce0f2e234 优化 2026-10-28 11:30:12 +08:00
liuyihe e98718dcf2 优化 2026-10-28 10:55:19 +08:00
liuyihe 298f1d9fe3 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-27 17:39:30 +08:00
liuyihe dd64f443cf 优化 2026-10-27 17:39:28 +08:00
ouyangxq 44a93d8606 Merge remote-tracking branch 'origin/main' into release/test 2026-10-26 17:44:56 +08:00
liuyihe b913a931ff Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-26 13:43:56 +08:00
liuyihe fe6d925e7c 优化 2026-10-26 13:43:20 +08:00
admin 2b5525ce49 灰度晋级:2026-10-23 晚间 apps/client-web
User-authorized fixed-source promotion; deployment and data preservation verified separately.
2026-10-23 21:00:48 +08:00
ouyangxq 2c98d121ca fix(client): clarify customs documents close action 2026-10-23 18:45:48 +08:00
admin d1eeaab067 发布:将已验 TEST 功能更新至既有生产灰度(2026-10-23)
Promote the fixed, reviewed TEST source to the existing production release. Runtime deployment remains a separate controlled step.
2026-10-23 10:51:31 +08:00
ouyangxq 3ffa706b89 fix: complete October 22 workflow feedback and request failure recovery 2026-10-22 23:06:02 +08:00
liuyihe 22baa5b5c0 Merge origin/release/test and resolve client conflicts 2026-10-22 10:38:47 +08:00
liuyihe 9f47b1b276 优化 2026-10-22 10:23:38 +08:00
ouyangxq 7adb97d145 优化头程订单工具栏与报关资料弹框 2026-10-21 23:20:11 +08:00
liuyihe 24439b15a3 优化 2026-10-21 17:46:02 +08:00
ouyangxq 7842791c10 优化 2026-10-21 16:58:41 +08:00
liuyihe 78893f1144 优化 2026-10-20 18:44:53 +08:00
liuyihe 20858dbe33 优化 2026-10-20 18:19:25 +08:00
liuyihe 99922bbc34 优化 2026-10-20 17:59:06 +08:00
liuyihe c38a7384aa 优化 2026-10-20 15:07:39 +08:00
liuyihe 5594e8fa02 优化 2026-10-20 15:02:14 +08:00
liuyihe f851f5667d Merge origin/release/test and resolve frontend conflicts 2026-10-20 14:58:58 +08:00
liuyihe 9b1dec75dd 优化 2026-10-20 14:52:22 +08:00
ouyangxq b52ad0c3e3 优化 2026-10-20 14:24:55 +08:00
liuyihe 64697276ec 优化 2026-10-20 14:00:59 +08:00
ouyangxq 1e26ddad4b docs(client): add module-level AGENTS indexes for all 11 modules
新增 11 个模块级 AGENTS.md,覆盖企业工作台全部业务模块,入口表统一指向模块指引。

- 统一四段式:路径基准 / 页面与入口表 / 关键边界 / 验证入口
- 补明“页面 -> store -> API”的调用链路,避免只给目录
- 仅索引文档,未改动业务代码
2026-10-20 12:42:07 +08:00
liuyihe 8abc058a65 优化 2026-10-20 11:54:44 +08:00
ouyangxq 5036593195 fix(first-leg): default new orders to truck self-delivery 2026-10-20 10:56:38 +08:00
ouyangxq de31c14695 优化 2026-10-19 17:56:27 +08:00
ouyangxq 513bbe2bb0 Merge remote-tracking branch 'origin/release/test' into release/test 2026-10-19 17:40:25 +08:00
ouyangxq d910b24755 feat(first-leg): reorder pickup choices and collect optional courier tracking 2026-10-19 17:40:25 +08:00
liuyihe 666be8a80d 优化 2026-10-19 16:40:30 +08:00
liuyihe 33db45f1c6 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-19 15:59:06 +08:00
liuyihe dcdaf1438c 优化 2026-10-19 15:59:04 +08:00
ouyangxq 17580fb0a2 feat(transport): unify client truck and looseboard demand forms 2026-10-19 15:50:39 +08:00
ouyangxq 34650b06df feat(looseboard): simplify client demand and split route contacts 2026-10-19 15:11:15 +08:00
ouyangxq 04a06668a1 merge: retain latest client presentation and truck compile fix 2026-10-19 15:04:43 +08:00
ouyangxq f1436f2889 fix(trucking): remove unreachable looseboard fields from truck form 2026-10-19 15:04:08 +08:00
liuyihe 82dcc5a14d Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-19 14:53:59 +08:00
liuyihe 9a24e0c83d 优化 2026-10-19 14:53:57 +08:00
ouyangxq 07590dd4d3 merge: preserve remote client updates and truck demand contract 2026-10-19 14:42:03 +08:00
ouyangxq 88c9ff2cb5 feat(trucking): refine client truck order form and details 2026-10-19 14:37:03 +08:00
liuyihe f7dd39c7ed 优化样式 2026-10-19 14:30:52 +08:00
liuyihe 7e68d978dd 优化 2026-10-19 14:06:37 +08:00
liuyihe 4b5113a690 优化 2026-10-19 10:23:47 +08:00
liuyihe e0726444cc 优化 2026-10-16 18:25:56 +08:00
liuyihe fbaa48337d 优化 2026-10-16 17:43:42 +08:00
liuyihe af3cacd2db 合并远程分支并保留仓储转运整单补箱与打印入口 2026-10-16 16:57:14 +08:00
liuyihe a674ec2435 优化 2026-10-16 16:52:49 +08:00
ouyangxq 8c064cfb0d fix(warehouse): add forecast quantity input hint 2026-10-16 16:30:15 +08:00
ouyangxq d1e9002bef Merge remote-tracking branch 'origin/release/test' into release/test 2026-10-16 16:28:49 +08:00
ouyangxq ded625f2a1 fix(warehouse): preserve cached transfer list context on detail navigation 2026-10-16 16:28:49 +08:00
liuyihe 3d3ca053a6 优化 2026-10-16 16:19:31 +08:00
liuyihe 3d73f1c82d 优化 2026-10-16 14:22:00 +08:00
liuyihe bb674eb3a0 优化 2026-10-16 13:58:08 +08:00
liuyihe c79b5492c6 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-16 11:43:01 +08:00
liuyihe 9b58c12012 优化 2026-10-16 11:42:59 +08:00
ouyangxq d89830fe41 fix(order): show authoritative progress and billing in customer detail 2026-10-15 19:39:35 +08:00
liuyihe 4d7b6eb6dc 优化 2026-10-15 18:25:32 +08:00
liuyihe 5b320a3293 优化 2026-10-15 15:45:22 +08:00
liuyihe 63e169b051 优化 2026-10-14 17:41:04 +08:00
liuyihe f5a6c7fd88 优化 2026-10-14 12:14:37 +08:00
liuyihe d67da9af82 优化 2026-10-14 11:43:38 +08:00
liuyihe d28408f678 优化 2026-10-13 21:27:46 +08:00
liuyihe 90ef9893f3 优化 2026-10-13 18:06:28 +08:00
liuyihe aa68e93b08 优化 2026-10-13 17:43:05 +08:00
liuyihe c168afa1e1 优化 2026-10-13 17:16:21 +08:00
liuyihe 6355bb69df 优化样式 2026-10-13 17:15:15 +08:00
liuyihe 15015d8bfc 优化样式 2026-10-13 17:15:03 +08:00
liuyihe bd8f9433ed 优化 2026-10-13 16:49:17 +08:00
liuyihe 4db8700817 优化 2026-10-13 14:46:59 +08:00
liuyihe c72c819f95 优化 2026-10-13 13:47:03 +08:00
liuyihe a0e9ad808b 优化 2026-10-13 10:16:32 +08:00
liuyihe cd06e264ff 优化 2026-10-12 21:55:43 +08:00
liuyihe aaab5041f9 优化 2026-10-12 21:48:28 +08:00
liuyihe 700074e983 优化 2026-10-12 21:19:13 +08:00
liuyihe 06f91c8b91 优化 2026-10-12 15:56:07 +08:00
liuyihe 6cb9b91435 优化 2026-10-12 14:33:17 +08:00
liuyihe 6d0eb2a5f3 优化 2026-10-12 13:43:29 +08:00
admin 15b51b6139 Merge pull request '发布采购、拼车、预约及匹配端侧修复至灰度' (#14) from release/test into main 2026-10-12 10:21:08 +08:00
ouyangxq db44d24eb4 Merge remote-tracking branch 'origin/release/test' into release/test 2026-10-12 00:25:02 +08:00
ouyangxq 3692f9d27f fix: coalesce concurrent notification count reads 2026-10-12 00:24:21 +08:00
liuyihe 90e1e646ec 优化提交 2026-10-10 13:47:47 +08:00
ouyangxq 5751973c83 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-10 02:20:16 +08:00
ouyangxq d7f8365ecc feat(procurement): show customer sample fulfillment and charges 2026-10-10 02:19:39 +08:00
liuyihe 3cdd14a521 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-09 20:39:40 +08:00
liuyihe 509dc677cb 优化 2026-10-09 20:39:38 +08:00
ouyangxq c0b151bc15 feat(client): show actionable customs count on sidebar 2026-10-09 18:14:19 +08:00
ouyangxq 639b1ae22c fix(client): preserve order category counts while refreshing 2026-10-09 17:53:42 +08:00
ouyangxq 33d86d2a64 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-09 17:36:36 +08:00
ouyangxq 9891ac3e29 优化 2026-10-09 17:36:34 +08:00
liuyihe d2bbd5024b 优化 2026-10-09 15:25:27 +08:00
liuyihe 07ba9fcb7c 优化 2026-10-09 11:48:52 +08:00
admin 985cab06b0 Merge pull request '发布已通过 TEST 回归的 2026-10-08 批次至灰度' (#13) from release/test into main 2026-10-08 22:20:47 +08:00
ouyangxq 2aa20b7172 test(client): verify return labels preserve server print templates 2026-10-08 20:18:39 +08:00
ouyangxq c63fb704a2 优化 2026-10-08 18:20:10 +08:00
ouyangxq d39c1f4ea7 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-08 17:08:06 +08:00
ouyangxq bc84686658 优化 2026-10-08 17:08:05 +08:00
liuyihe 62cf7829d3 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-10-08 15:34:39 +08:00
liuyihe 0be4088fa9 优化 2026-10-08 15:34:37 +08:00
admin 8b0decbaca Merge pull request 'Release internal fleet capacity pool to gray' (#12) from release/test into main 2026-10-08 08:13:46 +08:00
ouyangxq 7759c7e9f3 fix(client): prevent arrangement labels overlapping values 2026-10-07 20:59:34 +08:00
ouyangxq 19f060727b fix(client): localize transport mode in order detail 2026-10-07 20:43:30 +08:00
ouyangxq 47385d46f2 fix(orders): retain nullable palletizing facts in customer summaries 2026-10-07 19:44:44 +08:00
ouyangxq a853b1e0c2 feat(orders): show actual pooled freight fulfillment 2026-10-07 16:46:58 +08:00
admin ffa2b82c73 Merge pull request '发布当前测试版本至临时灰度环境' (#11) from release/test into main 2026-10-07 11:11:54 +08:00
ouyangxq b7fcc14e59 fix(deploy): support isolated temporary production release 2026-10-07 11:09:42 +08:00
ouyangxq b3f78207b8 fix(client): clarify cabinet customs totals 2026-10-05 18:13:02 +08:00
ouyangxq 3703d0a677 fix(auth): revoke captured client sessions safely on logout 2026-10-05 17:13:46 +08:00
ouyangxq e139c5c87b feat(firstleg): show actual and estimated transport nodes by loaded fragment 2026-10-05 01:06:13 +08:00
ouyangxq f0777ba2db fix(delivery): expose nullable actual signed quantity to clients 2026-10-03 23:10:44 +08:00
ouyangxq a0736239e4 fix(client): retain requested page during loading and failed queries 2026-10-03 19:16:09 +08:00
ouyangxq 40f6753cca fix(client): request complete server-paged order workbench 2026-10-03 14:57:54 +08:00
ouyangxq 78315873d7 fix(customs): keep result section pending until detail refresh finishes 2026-10-03 12:57:26 +08:00
ouyangxq fc32d0b390 perf(customs): filter loaded refund orders before pagination 2026-10-03 12:23:57 +08:00
ouyangxq 1fe2cada15 test(customs): verify page navigation and refresh recovery 2026-10-03 12:15:04 +08:00
ouyangxq 8e5fa0bebc fix(first-leg): identify and localize picking status in cabinet summary 2026-10-03 11:53:50 +08:00
ouyangxq 5c53eba31b fix(client): clear protected views on logout and show customer customs state 2026-10-03 03:54:06 +08:00
ouyangxq b1f538b3ac fix(customs): expose clearance query failure with scoped retry 2026-10-03 02:35:28 +08:00
ouyangxq 81a2e6473d fix(first-leg): render complete warehouse address snapshot once 2026-10-03 00:16:10 +08:00
ouyangxq 5f963f326e fix(auth): restore cross-tab permissions and bind retries to session identity 2026-10-02 23:29:20 +08:00
ouyangxq e564353a80 fix(first-leg): freeze versioned submission commands across retries 2026-10-02 23:08:58 +08:00
ouyangxq 187deb5047 fix(first-leg): show cancelled orders as terminal details 2026-10-02 22:26:42 +08:00
ouyangxq dae119a1e8 fix(first-leg): preserve edit commands and add versioned cancellation 2026-10-02 21:36:10 +08:00
ouyangxq c06c105836 perf(customs): request only tax refund orders 2026-10-02 14:45:09 +08:00
ouyangxq c3a213d039 fix(client): describe empty order queues accurately 2026-10-02 12:49:16 +08:00
ouyangxq 2f1babae45 fix(client): count only pending customs uploads 2026-10-02 12:38:28 +08:00
ouyangxq 1bd1664e9c fix(client): read all customs order pages with bounded concurrency 2026-10-02 12:31:11 +08:00
ouyangxq 1e707f613c fix(client): ignore stale customs dialog responses 2026-10-02 12:21:04 +08:00
ouyangxq 605388e666 fix(client): retain customs access after order completion 2026-10-02 11:33:51 +08:00
ouyangxq c115f1c504 fix(client): label delivery fees and verify receipt downloads 2026-10-02 11:25:12 +08:00
ouyangxq 162e9a2336 fix(client): keep delivery filters and latest query result consistent 2026-10-02 10:58:00 +08:00
ouyangxq d19b1b2f8c fix(client): keep customs dialog actions visible 2026-09-30 16:35:09 +08:00
liuyihe 3c36c55809 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-30 14:53:41 +08:00
liuyihe ff0754810a 优化 2026-09-30 14:53:39 +08:00
ouyangxq fce1356cb6 优化 2026-09-30 14:02:16 +08:00
ouyangxq 706e3e871e fix(navigation): expose permitted inbound and delivery order lists 2026-09-30 13:28:48 +08:00
ouyangxq 6564d41285 Merge remote-tracking branch 'origin/release/test' into release/test 2026-09-30 12:10:35 +08:00
ouyangxq 6abb8b7388 feat(delivery): let customers read and download signed receipts 2026-09-30 12:09:22 +08:00
liuyihe 151106250f Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-29 20:52:36 +08:00
liuyihe d45cd19361 优化 2026-09-29 20:52:34 +08:00
ouyangxq fa9bfd5f97 优化 2026-09-29 18:47:46 +08:00
ouyangxq a427aca5c3 优化 2026-09-29 17:56:03 +08:00
ouyangxq ffbe3480a8 fix(client): align customs completion notice and warehouse labels 2026-09-28 17:01:36 +01:00
ouyangxq 32c5241a01 fix(client): avoid duplicate sailing channel request 2026-09-28 16:47:19 +01:00
ouyangxq 9e133779ab Merge remote-tracking branch 'origin/release/test' into hotfix 2026-09-28 16:36:02 +01:00
ouyangxq 214fe4ff50 fix(client): preserve tax mode in customs candidates 2026-09-28 16:35:40 +01:00
liuyihe 225e3b0e71 merge client changes into release/test 2026-09-28 17:32:06 +08:00
liuyihe f24674dddc 优化提交 2026-09-28 17:26:37 +08:00
admin b03cb1dd3d Merge pull request 'Release/test' (#10) from release/test into main
Reviewed-on: #10
2026-09-28 15:59:06 +08:00
ouyangxq e681eadfcd fix(client): complete warehouse transfer contracts 2026-09-28 15:04:54 +08:00
ouyangxq 21be160668 fix(client): restore scroll after quote order navigation 2026-09-28 14:54:33 +08:00
ouyangxq 8fd406331a feat(customs): show receipt action history in client 2026-09-28 13:21:59 +08:00
ouyangxq 8acfbb1074 fix(client): finish sailing quote result handling 2026-09-28 12:03:39 +08:00
ouyangxq bea42ccca3 fix(client): pass quote charge mode 2026-09-28 10:48:25 +08:00
ouyangxq 3e2847814a feat(client): show customs receipt history 2026-09-28 09:49:53 +08:00
ouyangxq 5ebfa71248 test(client): align delivery idempotency assertion 2026-09-28 07:59:40 +08:00
ouyangxq 983df11081 fix(client): render estimated sailing fields from unified orders 2026-09-28 07:45:57 +08:00
ouyangxq 8c8fdbc2ab feat(client): show customs clearance results 2026-09-27 20:41:38 +08:00
ouyangxq a2934aad9d fix(client): normalize sailing quote dimensions 2026-09-27 20:30:49 +08:00
ouyangxq 146dee0587 fix(client): allow single-dimension sailing quote input 2026-09-27 20:25:30 +08:00
ouyangxq 23fd82632b style(client): compact sailing quote cards 2026-09-27 20:10:11 +08:00
ouyangxq 20ea6adc6f fix(client): show only FBA warehouse code 2026-09-27 00:09:50 +08:00
ouyangxq 34cdf4fc4f fix(client): show broker execution state in customs documents 2026-09-26 22:55:32 +08:00
ouyangxq 7eda66bc4d fix(client): show chargeable quantity in quote summary 2026-09-26 22:53:19 +08:00
ouyangxq 8aed079d02 fix(client): style sailing quote dialog root 2026-09-26 22:51:14 +08:00
ouyangxq 58c4be7fc0 feat(client): align sailing quote inquiry with prototype 2026-09-26 22:49:17 +08:00
ouyangxq 682d75f201 style(client): remove duplicate sailing page heading 2026-09-26 22:35:30 +08:00
ouyangxq b0d4e6ed33 fix(client): fit sailing inquiry controls at desktop width 2026-09-26 18:17:28 +08:00
ouyangxq b1c2d2cc15 fix(client): keep sailing inquiry fields in one row 2026-09-26 18:14:13 +08:00
ouyangxq c71a9945df style(client): align customs and sailing pages with prototype 2026-09-26 18:10:37 +08:00
ouyangxq 92e0586089 feat(client): expose customs receipt and final files 2026-09-26 13:28:33 +08:00
ouyangxq 5feb44abff test(client): update customs write contract count 2026-09-26 12:08:28 +08:00
ouyangxq df1ea86278 fix(client): restore destination warehouse from pricing quote 2026-09-25 23:23:56 +08:00
ouyangxq 806c9f393b feat(client): make pricing pages standalone and quick order 2026-09-25 23:21:43 +08:00
ouyangxq 78d94c3cbc feat(client): add customs and pricing permissions 2026-09-25 23:15:19 +08:00
ouyangxq 2923b545d1 fix(client): use explicit sailing price radio values 2026-09-25 23:09:56 +08:00
ouyangxq e62278e1c9 feat(client): add customs documents and sailing prices pages 2026-09-25 22:23:11 +08:00
ouyangxq fc008886fc 增加客户退税回执确认交互 2026-09-24 16:29:58 +08:00
liuyihe aa189146a0 提交 2026-09-24 10:11:16 +08:00
liuyihe 671351fa7c 解决客户工作台合并冲突 2026-09-24 09:02:34 +08:00
liuyihe 6926e99bd2 提交 2026-09-24 08:55:27 +08:00
ouyangxq 5bfe284e22 优化 2026-09-23 17:47:56 +08:00
liuyihe bc5c56d0e4 贴标优化0923 2026-09-23 11:25:35 +08:00
ouyangxq 06e0598e39 Merge remote-tracking branch 'origin/release/test' into release/test
# Conflicts:
#	src/modules/overseas-warehouse/views/WarehouseServiceView.vue
2026-09-23 10:27:47 +08:00
liuyihe 25db3c1777 提交 2026-09-23 09:06:20 +08:00
liuyihe 5de5f30b20 合并 release/test 前端冲突 2026-09-22 08:51:26 +08:00
liuyihe eb884c2790 修改提交 2026-09-22 08:47:31 +08:00
wujinliang 0fa80874bc 1Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test
# Conflicts:
#	src/modules/overseas-warehouse/views/WarehouseServiceView.vue
2026-09-21 19:37:33 +08:00
wujinliang b4403ab188 1 2026-09-21 19:36:37 +08:00
admin da0f306d9b Merge pull request 'Release/test' (#9) from release/test into main
Reviewed-on: #9
2026-09-21 11:35:42 +08:00
ouyangxq befd22af96 优化 2026-09-21 11:17:13 +08:00
ouyangxq bdb42f1256 fix: allow manual quote without carrier rate 2026-09-21 10:44:30 +08:00
admin 8048279465 Merge pull request 'fix: keep Client BaoTa proxy stable' (#8) from release/test into main 2026-09-20 23:41:54 +08:00
ouyangxq a96cbbd57d fix: preserve stable Client proxy port 2026-09-20 23:39:39 +08:00
admin 524cf79952 Merge pull request 'feat: production blue-green deployment for Client' (#7) from release/test into main
Reviewed-on: #7
2026-09-20 22:23:18 +08:00
ouyangxq 3cdd04e9b7 优化 2026-09-20 22:13:59 +08:00
ouyangxq 386ff8cced 优化 2026-09-20 21:52:15 +08:00
ouyangxq 5887837407 feat: add production blue-green frontend deployment 2026-09-20 21:44:56 +08:00
ouyangxq 97d0f82256 优化 2026-09-20 21:16:20 +08:00
ouyangxq 3ab07188d1 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-20 20:53:24 +08:00
ouyangxq dd7306c7fc 优化 2026-09-20 20:53:23 +08:00
liuyihe 8a3a90217c Merge branches 'release/test' and 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-20 20:52:57 +08:00
liuyihe 4b7becf9c2 优化 2026-09-20 20:48:01 +08:00
admin ca7021a145 Merge pull request 'Release/test' (#6) from release/test into main
Reviewed-on: #6
2026-09-20 19:49:23 +08:00
ouyangxq e89b9d3722 优化 2026-09-20 18:51:13 +08:00
ouyangxq d6b9d44431 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-20 18:25:24 +08:00
ouyangxq 4f515982f4 优化 2026-09-20 18:25:23 +08:00
liuyihe 63d1bcef26 优化样式 2026-09-20 17:53:41 +08:00
liuyihe 308f7573c1 优化 2026-09-20 16:55:27 +08:00
ouyangxq 486d5163b2 优化 2026-09-20 16:02:10 +08:00
liuyihe 375e5e53ce merge release test changes and preserve local frontend updates 2026-09-20 15:23:50 +08:00
ouyangxq c08a10a125 优化 2026-09-20 15:03:31 +08:00
admin 1dcb93c69d Merge pull request '优化' (#5) from release/test into main
Reviewed-on: #5
2026-09-20 11:24:29 +08:00
ouyangxq 653e79d3e7 优化 2026-09-20 11:23:35 +08:00
admin 3f39264141 Merge pull request 'Release/test' (#4) from release/test into main
Reviewed-on: #4
2026-09-20 11:11:23 +08:00
ouyangxq 40f2b2ba11 优化 2026-09-20 11:09:59 +08:00
ouyangxq e3d9f8c637 优化 2026-09-20 10:47:51 +08:00
ouyangxq 6355529627 优化 2026-09-20 10:45:31 +08:00
admin 138d4a64dd Merge pull request 'Release/test' (#3) from release/test into main
Reviewed-on: #3
2026-09-19 22:58:22 +08:00
ouyangxq 60e875b2c6 优化 2026-09-19 17:30:27 +08:00
ouyangxq 514abf6eda 优化 2026-09-19 17:02:11 +08:00
ouyangxq 4eb17ece4f 优化 2026-09-18 18:50:49 +08:00
admin 0303168c26 Merge pull request 'Release/test' (#2) from release/test into main
Reviewed-on: #2
2026-09-18 18:03:44 +08:00
ouyangxq 3c17f6a5cd 优化 2026-09-18 18:02:31 +08:00
ouyangxq 77afdb1c42 优化 2026-09-18 16:49:14 +08:00
ouyangxq fcb9e584ad Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-18 16:49:12 +08:00
ouyangxq 1d407620d2 优化 2026-09-18 16:48:35 +08:00
wujinliang 8fbefcf657 1 2026-09-18 11:40:41 +08:00
wujinliang e3cca80ff2 Merge branch 'release/test' of http://8.163.30.128:10082/html/client-web into release/test 2026-09-18 09:15:28 +08:00
wujinliang bb94f88bb3 1 2026-09-18 09:15:15 +08:00
ouyangxq 5542ee80e6 优化 2026-09-17 18:32:43 +08:00
ouyangxq f5f5525a1b 优化 2026-09-17 18:25:08 +08:00
admin cee2818944 Merge pull request 'Release/test 合并上生产' (#1) from release/test into main
Reviewed-on: #1
2026-09-17 11:51:49 +08:00
220 changed files with 15243 additions and 4170 deletions
+3 -1
View File
@@ -4,6 +4,8 @@
dist dist
node_modules node_modules
node_modules.broken-by-path node_modules.broken-by-path
.env.local .env
.env.*
!.env.example
npm-debug.log* npm-debug.log*
pnpm-debug.log* pnpm-debug.log*
+7 -2
View File
@@ -1,5 +1,10 @@
VITE_API_BASE_URL=/api VITE_API_BASE_URL=/api
VITE_OVERSEAS_API_BASE_URL=/overseas-api
OVERSEAS_API_PROXY_TARGET=http://127.0.0.1:9300
API_PROXY_TARGET=http://127.0.0.1:9000 API_PROXY_TARGET=http://127.0.0.1:9000
VITE_ADMIN_WEB_ORIGIN=http://localhost:5173 VITE_ADMIN_WEB_ORIGIN=http://localhost:5173
# Test container deployment (Jenkins environment or untracked .env).
# API_UPSTREAM: unified Gateway origin, no /api suffix.
# TEST_NETWORK: shared test Docker network.
API_UPSTREAM=http://gateway:9000
TEST_NETWORK=firstleg-test-network
IMAGE_TAG=
+30 -35
View File
@@ -4,7 +4,7 @@
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。 - 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。 - 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及海外 API、海外 Token 或跨区域事件时读取 `../../docs/跨区域认证与服务通信契约.md`。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。 - 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及统一 API、Token、会话撤销或可靠事件时按需读取 `../../docs/统一认证与服务通信契约.md` 对应章节。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。 - 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
## 技术基线 ## 技术基线
@@ -26,37 +26,38 @@
- 模块内 `store/`:该业务跨页面状态;局部表单状态仍留在页面或组件内。跨模块使用 store 时只能导入其公开 store 文件,不得读取模块内部页面或组件实现。 - 模块内 `store/`:该业务跨页面状态;局部表单状态仍留在页面或组件内。跨模块使用 store 时只能导入其公开 store 文件,不得读取模块内部页面或组件实现。
- `src/api/`:只保留 HTTP、会话令牌、响应类型等全局请求基础设施;业务接口放入对应模块的 `api/`。页面不得直接创建独立 Axios 客户端。 - `src/api/`:只保留 HTTP、会话令牌、响应类型等全局请求基础设施;业务接口放入对应模块的 `api/`。页面不得直接创建独立 Axios 客户端。
- 模块之间不得通过相对路径或内部目录穿透;确需协作时只能从目标模块的 `public.ts` 导入。模块内稳定契约放在 `contracts.ts`,稳定的跨应用模型仍应上移到 `@chongchong/shared`。 - 模块之间不得通过相对路径或内部目录穿透;确需协作时只能从目标模块的 `public.ts` 导入。模块内稳定契约放在 `contracts.ts`,稳定的跨应用模型仍应上移到 `@chongchong/shared`。
- `VITE_API_BASE_URL`、`VITE_OVERSEAS_API_BASE_URL` 分别控制国内和海外浏览器前缀;`API_PROXY_TARGET`、`OVERSEAS_API_PROXY_TARGET` 只由 Vite 开发代理读取,不进入客户端构建。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。 - `VITE_API_BASE_URL` 控制唯一浏览器 API 前缀;全部业务共用 `src/api/http.ts` 和同一 Access/Refresh Token。`API_PROXY_TARGET` 仅供本地 Vite 代理连接测试入口,不进入客户端构建。独立海外 HTTP 客户端与代理已移除。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
- `src/styles/`:全局设计令牌和布局;优先复用现有 `--primary`、`--navy`、`--border`、`--muted`。 - `src/styles/`:全局设计令牌和布局;优先复用现有 `--primary`、`--navy`、`--border`、`--muted`。
- 本应用多个模块稳定复用的前端模型放到应用内 `shared/`,客户工作台专属类型保留在对应业务模块。不要链接应用目录之外的 TypeScript 包,服务端契约以 `baiyue-firstleg` Controller/OpenAPI 为准。 - 本应用多个模块稳定复用的前端模型放到应用内 `shared/`,客户工作台专属类型保留在对应业务模块。不要链接应用目录之外的 TypeScript 包,服务端契约以 `baiyue-firstleg` Controller/OpenAPI 为准。
## 开发环境样式验收 ## 测试环境样式验收
- 开发环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。 - 测试环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。
- 账号与密码不写入仓库;从本机未提交环境变量或 `C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env` 读取。若显式验收凭据不存在,再向用户索取。 - 账号与密码不写入仓库;从本机未提交环境变量或 `C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env` 读取。若显式验收凭据不存在,再向用户索取。
- 该身份仅适用于开发环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;开发环境变更时只更新本机凭据。 - 当前只有一个测试环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;测试环境变更时只更新本机凭据。
- 由人工使用该身份进入真实页面,按 `1920×1080` 视口和 `100%` 浏览器缩放完成操作与截图,再把截图发送给 AI 核对加载、空态、错误态、权限态和桌面布局;AI 默认不主动调用截图或视觉类技能取证。 - 由人工使用该身份进入真实页面,按 `1920×1080` 视口和 `100%` 浏览器缩放完成操作与截图,再把截图发送给 AI 核对加载、空态、错误态、权限态和桌面布局;AI 默认不主动调用截图或视觉类技能取证。
## 模块快速查询 ## 模块快速查询
退货预报与签收结果:`src/modules/overseas-warehouse/views/ReturnOrdersView.vue`、`api/returnOrders.ts`;菜单仍名为“退货换标”,正式路由 `return-relabel` 已使用独立页面,不再由 `WarehouseServiceView.vue` 承载。客户退货库存/箱号共用 `views/ReturnInventoryView.vue`、`api/returnInventory.ts`,`return-cartons` 传 `cartonOnly=true`。Backend 为 Lastleg `returnreceipt/`,退货单签收完成不等于换标或退货出库完成;后续换标、出库须按各自业务状态核对。 本表只保留首个入口;完整 API、字段、状态与恢复规则见 [按需业务索引](docs/business-index.md)。从本应用根执行 `rg -n -F '任务词或文件名' docs/business-index.md` 读取命中条款;涉及业务行为变更时必须核对对应细则,纯定位不全文加载。保留所有适用的最近模块指引。
先从 `src/modules/registry.ts` 确认模块,再按目标模块的 `routes.ts → views/ → api/、store/、contracts.ts 或 public.ts` 查询。页面是否正式开放以 `routes.ts` 的 `release` 为准,不从任务或进度文档推断。 表中路径均相对本应用根目录。模块指引中的后端类名以服务名起算,如 `firstleg/service/X.java` 即 `baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/service/X.java`。
| 业务 | 模块入口 | 联查模块或服务端 | | 业务 | 首个入口 |
|---|---|---| |---|---|
| 登录、注册与会话 | `src/modules/auth/`、`src/api/session.ts`、`src/api/http.ts` | Backend `auth/`、`iam/`;正常旋转的国内/海外 Token 会话统一持久化,“记住账号”只记登录标识;访问令牌失效但刷新令牌仍在时先恢复会话,公开认证接口不得携带旧 Token | | 登录、注册与会话 | `src/modules/auth/AGENTS.md`、`src/api/session.ts`、`src/api/http.ts` |
| 企业资料、成员与角色 | `src/modules/tenant-management/`、`src/modules/account/` | Backend `iam/`、`auth/`、`file/`;公司联系电话/邮箱是企业资料,不作为登录标识;成员登录手机号可选,修改时同步 Auth、撤销该账号会话并审计。审核必填资质仅营业执照与统一社会信用代码;法人身份证选填,可随营业执照提交,也可在已有营业执照后单独补传或替换。前端角色树到服务端权限的映射统一维护在 `contracts.ts` 的 `FRONTEND_TO_MERCHANT_PERMISSION_CODES`,海外入仓、采购、本土卡车和散板权限必须显式进入该映射 | | 企业资料、成员与角色 | `src/modules/tenant-management/AGENTS.md`、`src/modules/account/AGENTS.md` |
| 工作台与系统入口 | `src/modules/dashboard/`、`src/modules/system/` | `src/navigation/clientNavigation.ts`、`src/router/index.ts` | | 工作台与系统入口 | `src/modules/dashboard/AGENTS.md`、`src/modules/system/AGENTS.md` |
| 企业成员消息收件箱 | `src/modules/notifications/` | Backend `iam/src/main/java/com/baiyue/iam/notification/`;列表、详情、已读与未读数契约见 `iam/src/main/resources/openapi/notification-v1.yaml` | | 企业成员消息收件箱 | `src/modules/notifications/AGENTS.md` |
| 头程下单、中文批量导入、入仓码关系、箱唛、履约进度与入库费用确认 | `src/modules/first-leg/`;列表与批量入口 `views/FirstLegOrdersView.vue`,模板/导入 API `api/firstLeg.ts`,入仓详情 `components/InboundCodeAssociationDialog.vue`、`api/inboundCodeAssociations.ts`,独立计费重弹框 `components/InboundBillingPanel.vue`、`api/inboundBilling.ts` | 中文 XLSX 模板按当前客户生成地址、全部有效仓库和渠道下拉,最多 50 行,只创建草稿并支持部分/原子导入;导入结果只显示 Excel 行号,不展示内部 `clientRowId`。所有订单行均可进入计费重弹框,尚未推送时展示明确空态;只有具备编辑权限且服务端返回当前 `SENT` 费用时才可二次确认并提交 `expectedFeeVersion` 与幂等键,成功后版本锁定、平台不得再修改。Backend `order/`、`firstleg/`、`warehouse/`,不得用内部 ID 补齐缺失业务编号 | | 头程下单、中文批量导入、入仓码关系、箱唛、履约进度与入库费用确认 | `src/modules/first-leg/AGENTS.md` |
| 装柜完成后的退税报关资料 | `src/modules/first-leg/views/FirstLegOrdersView.vue` 的“报关资料”、`components/CustomsDocumentsDialog.vue`、`api/customs.ts` | 只显示登录客户在同柜的退税入仓码;报关开始前可上传、替换、调整同一资料覆盖的一个或多个入仓码及删除误传,全部写入携带幂等键和版本;开始后只读冻结资料,整柜完成后才能下载平台回传的一对一完成文件。Backend `firstleg/customs/container/`、`customs-v1.yaml`,二进制归 `file/` | | 装柜完成后的退税报关资料 | `src/modules/first-leg/AGENTS.md`、`src/modules/first-leg/components/CustomsDocumentsDialog.vue` |
| 统一订单展示 | `src/modules/order-management/` | `src/modules/first-leg/` 与对应后端订单契约 | | 统一订单展示 | `src/modules/order-management/AGENTS.md` |
| 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `src/modules/finance/`;确认与明细入口 `views/FinanceBillsView.vue`、`api/finance.ts`,入仓码通过 `src/modules/first-leg/public.ts` 复用 `InboundCodeAssociationDialog` | Backend `finance/`;账单行只显示服务端 `inboundCode` 并按登录客户查询业务关系,缺失显示“—”,不得回退内部 ID。收款方式由服务端枚举映射中文。出账或已出账调整后为 `PENDING_CONFIRMATION`,客户确认提交登录成员、`expectedVersion` 和幂等键 | | 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `src/modules/finance/AGENTS.md` |
| 客户资金账户、授信与充值申请 | `src/modules/finance/views/FinanceAccountView.vue`、`api/account.ts` | 显示当前企业 CNY 实际余额、冻结金额、授信额度、授信有效期、已用授信、冻结授信、总可用余额和不可变流水;数据加载前显示“—”,不得先伪装为零。授信到期日当天仍有效,次日已用授信并入实际余额,负数实际余额会阻止提交新订单。充值只展示服务端启用的微信/支付宝静态收款码,客户上传 JPG/PNG 付款截图后进入待审核。客户范围只取登录态,无收款码时禁止提交,不模拟支付成功 | | 客户资金账户、授信与充值申请 | `src/modules/finance/AGENTS.md` |
| 海外采购、美国本土卡与美本土散板 | `src/modules/cross-border/routes.ts`、`components/BusinessOrdersView.vue`、`api/businessOrders.ts` | 三个路由均为 `active`,客户范围只取 Token;采购创建的 `customerName` 只取当前认证会话企业名称,不允许自由输入或冒用其他客户。Backend `lastleg-service/` 的 `procurement/`、`trucking/`、`looseboard/` 客户接口 | | 海外采购 | `src/modules/cross-border/AGENTS.md` |
| 海外仓入库订单 | `src/modules/order-management/routes.ts`、`views/InboundOrdersView.vue`、`api/inboundPlans.ts` | `orders/inbound` 为只读列表/详情,权限 `merchant:warehouse:inbound:list`;不展示或提交内部 ID | | 美国本土卡与美本土散板 | `src/modules/cross-border/AGENTS.md` |
| 海外仓贴标、仓储转运、货物废弃 | `src/modules/overseas-warehouse/routes.ts`、`views/WarehouseServiceView.vue`、`api/warehouseServices.ts` | 三个路由均为 `active`;退货预报另见本节独立入口;贴标申请先选国外中转仓和有库存历史入仓单,换标类型为只换 SKU、只换箱唛、SKU+箱唛。涉及箱唛换标时,整张贴标申请只选择一个 FBA 目的仓,全部箱级明细统一提交该目的仓,模板和明细不再逐行选择目的仓。箱唛换标明细一行固定代表一箱,箱数不可编辑,提交也固定为 1。货物明细外层始终提供“SKU 关联”“箱号关联”“SKU 混箱换标”三套模板的下载、上传,不随换标类型切换;上传只进入待导入关系区,客户可勾选部分或全选后导入本次明细,只有进入明细的库存才随申请提交和冻结。明细也支持手动新增编辑,组合换标以仓库唛头连接旧/新 SKU 和新 FBA 箱唛关系。涉及箱唛换标时必须选择卡车、自提或快递;快递可选择打印面单并上传 PDF/图片。PDA 逐箱换标、上传照片并由仓库复核后,客户详情展示完工照片和“换标完成确认”;客户确认前不得继续出库,确认后卡车进入预排车,自提/快递进入换标出库待创建。历史库存位置不能解释成箱唛与具体托盘快照,客户页面不暴露托盘、库位和内部库存 ID | | 海外仓入库订单 | `src/modules/order-management/AGENTS.md` |
| 海外仓贴标、仓储转运、货物废弃 | `src/modules/overseas-warehouse/AGENTS.md` |
## 租户、认证与数据安全 ## 租户、认证与数据安全
@@ -65,18 +66,19 @@
- 任何查询和变更都必须以服务端确认的当前租户为边界;绝不从可篡改的前端参数推断授权租户。 - 任何查询和变更都必须以服务端确认的当前租户为边界;绝不从可篡改的前端参数推断授权租户。
- 企业成员、角色和权限只能管理当前企业范围。前端隐藏不是安全控制,服务端必须重复校验租户与权限。 - 企业成员、角色和权限只能管理当前企业范围。前端隐藏不是安全控制,服务端必须重复校验租户与权限。
- 注册时登录手机号同时初始化公司联系电话;注册完成后两者独立维护。企业资料只修改 `contactPhone`,个人资料或成员管理中的登录手机号由 IAM/Auth 同步并撤销该账号现有会话,不得在前端互相回填或联动提交。 - 注册时登录手机号同时初始化公司联系电话;注册完成后两者独立维护。企业资料只修改 `contactPhone`,个人资料或成员管理中的登录手机号由 IAM/Auth 同步并撤销该账号现有会话,不得在前端互相回填或联动提交。
- 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;国内请求使用国内 Access Token,海外请求统一由 `src/api/overseasHttp.ts` 读取短时海外 Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。 - 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;全部请求共用统一 Access Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。
- 当前认证仍包含模拟数据。接入真实 API 后移除对应模拟分支,生产环境不得回退为模拟成功。 - 当前认证仍包含模拟数据。接入真实 API 后移除对应模拟分支,生产环境不得回退为模拟成功。
- 头程订单统一使用当前正式读写契约;不得继续扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API、历史部分响应兼容或其他新旧并跑逻辑。触及该链路时按根无兼容规则同步删除生产分支、类型、文案、Mock 和测试,不以现有代码或测试仍覆盖旧路径作为保留依据。 - 头程订单统一使用当前正式读写契约;不得继续扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API、历史部分响应兼容或其他新旧并跑逻辑。触及该链路时按根无兼容规则同步删除生产分支、类型、文案、Mock 和测试,不以现有代码或测试仍覆盖旧路径作为保留依据。
- 注册、上传资质、成员邀请和订单操作必须提供明确校验、幂等保护、提交中状态和可恢复的失败反馈。 - 注册、上传资质、成员邀请和订单操作必须提供明确校验、幂等保护、提交中状态和可恢复的失败反馈。
## UI 与交互 ## UI 与交互
- 修改已有 Client 原型页面前先读 `../../docs/Admin-Client前端原型还原验收规则.md`,按页面和操作形成原型核对矩阵;本节维护 Client 的实现约束,不复制跨前端验收文档全文。 - 后续客户端新增、新建、下单操作统一执行 [Client 界面样式规范](../../docs/Client界面样式规范.md) 的“新增页面”章节,作为当前通用外观依据;列表按同文列表条款。只读取本轮适用章节,不因规范更新批量改造其他操作或公共外框。
- 已向客户讲解或确认过的产品原型是页面视觉与布局实现的直接事实来源。字段顺序、字段分组、字段摆放、列宽、控件宽高、对齐方式、换行方式、区块层级、上下左右边距、内边距、间隙、留白、圆角、边框、阴影、背景色、文字颜色和字号均必须按原型还原,不得只参考大致风格后自行重新排版。 - 视觉还原、布局/交互承载方式变更或真实页面验收时读取 `../../docs/Admin-Client前端原型还原验收规则.md`,只为受影响操作形成原型核对矩阵;纯文案、逻辑或测试修改不自动读取。自动检查与人工视觉验收分开报告,无视觉变化时标记“无需视觉验收”。
- 已向客户讲解或确认过的产品原型是页面字段、分组、摆放及承载方式的直接依据;新增页的通用外观以当前 Client 样式规范明确替代的条款为准。未被替代的列宽、控件宽高、对齐方式、换行方式、区块层级、边距、圆角、边框、阴影、背景色、文字颜色和字号仍按原型还原,不得只参考大致风格后自行重新排版。
- 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。 - 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。
- 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。 - 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。
- 上述原型还原规则优先于本文件中“延续现有视觉体系”、默认组件样式和默认图标库等一般性规则。只有用户当前明确要求、阶段范围、真实字段长度、响应式、可访问性或接口事实与原型冲突时才允许做最小调整,并须在修改前说明具体差异、原因和影响范围;不得以技术实现方便为由偏离原型。 - 当前 Client 样式规范明确替代的外观及上述原型还原规则,优先于本文件中“延续现有视觉体系”、默认组件样式和默认图标库等一般性规则。后续用户明确确认的例外优先;阶段范围、真实字段长度、响应式、可访问性或接口事实与原型冲突时只做最小调整,并须在修改前说明具体差异、原因和影响范围,不得以技术实现方便为由偏离。
- 详情、新增、编辑、审核等操作采用独立页面、居中弹框、侧滑面板或其他承载方式,必须逐页面按对应原型确认,不得全局写死为某一种容器。原型为独立页面时使用正式路由和页面布局;原型为居中弹框时使用模态弹框;只有原型明确为侧滑面板时才使用抽屉。不得因为已有公共组件或改动方便,把原型中的独立页面改成弹框、把弹框改成抽屉,或反向替换。 - 详情、新增、编辑、审核等操作采用独立页面、居中弹框、侧滑面板或其他承载方式,必须逐页面按对应原型确认,不得全局写死为某一种容器。原型为独立页面时使用正式路由和页面布局;原型为居中弹框时使用模态弹框;只有原型明确为侧滑面板时才使用抽屉。不得因为已有公共组件或改动方便,把原型中的独立页面改成弹框、把弹框改成抽屉,或反向替换。
- 延续现有客户工作台的可信、简洁和服务型视觉语言,与内部管理后台保持品牌关联但不照搬高密度管理界面。 - 延续现有客户工作台的可信、简洁和服务型视觉语言,与内部管理后台保持品牌关联但不照搬高密度管理界面。
- 优先使用 Element Plus 和 Lucide 图标;不使用表情符号代替功能图标,不引入第二套组件库。 - 优先使用 Element Plus 和 Lucide 图标;不使用表情符号代替功能图标,不引入第二套组件库。
@@ -96,8 +98,8 @@ pnpm typecheck
pnpm build pnpm build
``` ```
- 日常变更至少运行 `pnpm typecheck`;交付前运行 `pnpm build`。 - 按 `../../docs/AI工程执行与协作约束.md` 的“验证范围选择”执行;命令表不是每轮清单。文案/纯展示核对差异,小逻辑跑定向测试;类型/签名变化加最小类型检查,公共能力覆盖实际消费者。不因源码修改或交付自动 typecheck、全量测试或构建;构建和全量测试分别说明触发原因,相同编译不重复跑。纯文档/索引只检查路径、链接及索引合同。
- 当前测试使用 Node.js 内置测试运行器,执行 `pnpm test`;项目仍未声明 lint 脚本,不得声称 lint 已通过。 - 当前测试使用 Node.js 内置测试运行器,局部改动指定受影响测试文件,`pnpm test` 是全量入口;项目未声明 lint 脚本,不得声称 lint 已通过。
- 不手工修改 `dist/` 或 `node_modules/`;依赖变更必须同步当前项目依赖清单和锁文件。 - 不手工修改 `dist/` 或 `node_modules/`;依赖变更必须同步当前项目依赖清单和锁文件。
## 全量验收脚本 ## 全量验收脚本
@@ -109,11 +111,4 @@ pnpm build
## Client 全量验收快速索引 ## Client 全量验收快速索引
当前按客户侧全量业务闭环验收。业务域文档用于核对功能来源和验收证据,不限制本次验收的模块范围;按“模块 `routes.ts` → 页面/组件 → `api`、store、contracts”定位。本表只描述 Client 页面与客户可见契约,服务端实现详见后端模块指引。 全量验收的两类客户可见范围按需查 `docs/business-index.md` 同名节;平台/PDA 操作与内部证据不得因此暴露给客户。普通修改保持最小模块范围,不自动加载验收资料。
| 验收域 | Client 范围与代码入口 | 验收首读 |
|---|---|---|
| 客户基础与订单 | 登录/注册、企业资料与资质、成员/角色权限、工作台和订单 | `src/modules/auth/`、`tenant-management/`、`account/`、`system/`、`dashboard/`、`first-leg/`、`order-management/`;按客户可见契约核对权限、状态、幂等和错误处理 |
| 履约、海外仓与财务 | 入库计费、柜次进度、船期、海外仓贴标/转运/废弃/退货换标、消息和客户账单 | `src/modules/first-leg/`、`overseas-warehouse/`、`finance/`、`notifications/`;按服务端权限核对客户可见字段、客户隔离和只读/写入边界 |
客户侧边界:仍以服务端权限和客户可见字段为准;PDA、平台后台操作和内部证据不因全量验收自动暴露到 Client。财务按 `../../docs/财务管理/` 与 `src/modules/finance/routes.ts` 定位。
Vendored
+27 -141
View File
@@ -1,176 +1,62 @@
pipeline { pipeline {
agent { agent { label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : 'java-test'}" }
label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : (env.JOB_BASE_NAME?.endsWith('-dev') ? 'java-dev' : 'java-test')}"
}
environment {
DEVELOPMENT_COMPOSE_FILE = 'docker-compose.development.yml'
DEVELOPMENT_COMPOSE_PROJECT = 'client-web'
REGISTRY_HOST = '172.31.198.7:10082'
REGISTRY_CREDENTIALS = 'gitea-registry-token'
NODE_BASE_IMAGE = '172.31.198.7:10082/java-project/node:22-alpine'
NGINX_BASE_IMAGE = '172.31.198.7:10082/java-project/nginx:1.27-alpine'
PRODUCTION_IMAGE_REPOSITORY = 'git.buggoglobal.com/html/client-web'
}
options { options {
timestamps() timestamps()
disableConcurrentBuilds() disableConcurrentBuilds()
} }
stages { stages {
stage('确认提交版本') { stage('检查测试发布参数') {
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
steps { steps {
script { script {
env.IS_DEVELOPMENT = env.JOB_BASE_NAME?.endsWith('-dev') ? 'true' : 'false' if (env.JOB_BASE_NAME?.endsWith('-dev')) {
env.IS_PRODUCTION = env.JOB_BASE_NAME?.endsWith('-prod') ? 'true' : 'false' error('此流水线仅支持 test 和本轮授权的 prod 灰度')
if (env.IS_PRODUCTION == 'true') {
sh '''
set -eu
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)" || {
echo "生产部署只允许 origin/main 当前提交;请先合并代码到 main" >&2
exit 1
} }
env.IMAGE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
}
sh '''set -eu
export API_UPSTREAM="${API_UPSTREAM:-http://gateway:9000}"
export TEST_NETWORK="${TEST_NETWORK:-firstleg-test-network}"
: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN 未设置}"
docker network inspect "$TEST_NETWORK" >/dev/null
docker compose -f docker-compose.test.yml config --quiet
''' '''
} }
env.SOURCE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
} }
sh 'git log -1 --oneline'
}
}
stage('构建并部署测试前端') { stage('构建并部署测试前端') {
when { expression { env.IS_DEVELOPMENT != 'true' && env.IS_PRODUCTION != 'true' } } when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
steps { steps {
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) { sh '''set -eu
sh '''
set -eu
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
rm -rf "$DOCKER_CONFIG"
mkdir -p "$DOCKER_CONFIG"
cleanup_registry() {
docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true
rm -rf "$DOCKER_CONFIG"
}
trap cleanup_registry EXIT HUP INT TERM
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
docker compose -f docker-compose.test.yml build --pull=false docker compose -f docker-compose.test.yml build --pull=false
docker compose -f docker-compose.test.yml up -d --remove-orphans docker compose -f docker-compose.test.yml up -d --wait --wait-timeout 120
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
''' '''
} }
} }
} stage('发布临时生产灰度') {
when { expression { env.JOB_BASE_NAME?.endsWith('-prod') } }
stage('构建并发布生产镜像') {
when { expression { env.IS_PRODUCTION == 'true' } }
steps { steps {
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) { lock(resource: 'firstleg-production-client-web-deploy') {
sh '''
set -eu
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
rm -rf "$DOCKER_CONFIG"
mkdir -p "$DOCKER_CONFIG"
cleanup_registry() {
docker logout git.buggoglobal.com >/dev/null 2>&1 || true
rm -rf "$DOCKER_CONFIG"
}
trap cleanup_registry EXIT HUP INT TERM
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin git.buggoglobal.com
image="$PRODUCTION_IMAGE_REPOSITORY:$SOURCE_TAG"
docker build \
--build-arg NODE_IMAGE="$NODE_BASE_IMAGE" \
--build-arg NGINX_IMAGE="$NGINX_BASE_IMAGE" \
--build-arg VITE_ADMIN_WEB_ORIGIN=https://admin.buggoglobal.com \
-t "$image" .
docker push "$image"
'''
}
}
}
stage('确认部署生产前端') {
when { expression { env.IS_PRODUCTION == 'true' } }
steps {
input message: "确认将 main 提交 ${env.SOURCE_TAG} 部署到 app.buggoglobal.com?", ok: '确认部署'
}
}
stage('部署生产前端') {
when { expression { env.IS_PRODUCTION == 'true' } }
steps {
lock(resource: 'firstleg-production-client-web-deploy', inversePrecedence: true) {
withCredentials([ withCredentials([
usernamePassword(credentialsId: 'gitea-registry-token', usernameVariable: 'BUILD_REGISTRY_USER', passwordVariable: 'BUILD_REGISTRY_PASSWORD'),
usernamePassword(credentialsId: 'gitea-production-pull-token', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD'), usernamePassword(credentialsId: 'gitea-production-pull-token', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD'),
sshUserPrivateKey(credentialsId: 'firstleg-production-ssh', keyFileVariable: 'TARGET_SSH_KEY', usernameVariable: 'TARGET_SSH_USER'), sshUserPrivateKey(credentialsId: 'firstleg-production-ssh', keyFileVariable: 'TARGET_SSH_KEY', usernameVariable: 'TARGET_SSH_USER'),
string(credentialsId: 'firstleg-production-host', variable: 'TARGET_SSH_HOST'), string(credentialsId: 'firstleg-production-host', variable: 'TARGET_SSH_HOST'),
file(credentialsId: 'firstleg-production-known-hosts', variable: 'TARGET_SSH_KNOWN_HOSTS') file(credentialsId: 'firstleg-production-known-hosts', variable: 'TARGET_SSH_KNOWN_HOSTS')
]) { ]) {
withEnv([ sh 'sh scripts/deploy-production.sh'
'TARGET_DEPLOY_DIR=/data/firstleg/deploy/frontend',
'TARGET_SSH_TARGET=' + env.TARGET_SSH_USER + '@' + env.TARGET_SSH_HOST
]) {
sh "sh scripts/deploy-production.sh client-web '${env.PRODUCTION_IMAGE_REPOSITORY}' '${env.SOURCE_TAG}' docker-compose.production.yml"
} }
} }
} }
} }
} }
stage('构建并部署开发前端') {
when { expression { env.IS_DEVELOPMENT == 'true' } }
steps {
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
sh '''
set -eu
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
rm -rf "$DOCKER_CONFIG"
mkdir -p "$DOCKER_CONFIG"
cleanup_registry() {
docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true
rm -rf "$DOCKER_CONFIG"
}
trap cleanup_registry EXIT HUP INT TERM
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
image="client-web-development:${SOURCE_TAG}"
docker build \
--build-arg NODE_IMAGE="$NODE_BASE_IMAGE" \
--build-arg NGINX_IMAGE="$NGINX_BASE_IMAGE" \
--build-arg VITE_ADMIN_WEB_ORIGIN=http://8.163.49.32:9001 \
-t "$image" .
export IMAGE_TAG="$SOURCE_TAG"
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" up -d --remove-orphans --pull never
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" ps
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" exec -T client-web wget -qO- http://127.0.0.1/healthz
'''
}
}
}
stage('部署检查') {
when { expression { env.IS_DEVELOPMENT != 'true' && env.IS_PRODUCTION != 'true' } }
steps {
sh '''
set -eu
docker compose -f docker-compose.test.yml ps
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
'''
}
}
}
post { post {
failure { failure {
sh ''' script {
if [ "${IS_PRODUCTION:-false}" = "true" ]; then if (!env.JOB_BASE_NAME?.endsWith('-prod')) {
echo "生产部署失败,请查看上方远程部署日志" sh 'docker compose -f docker-compose.test.yml logs --tail=100 || true'
elif [ "${IS_DEVELOPMENT:-false}" = "true" ]; then }
docker logs --tail=100 client-web-development || true }
else
docker compose -f docker-compose.test.yml logs --tail=100 || true
fi
'''
} }
} }
} }
+9 -3
View File
@@ -10,7 +10,7 @@ pnpm install
pnpm dev pnpm dev
``` ```
生产构建: 发布资源构建:
```bash ```bash
pnpm typecheck pnpm typecheck
@@ -35,7 +35,7 @@ pnpm test
依赖和 `pnpm-lock.yaml` 均保存在当前前端项目中,不需要在仓库根目录安装 Node 依赖。 依赖和 `pnpm-lock.yaml` 均保存在当前前端项目中,不需要在仓库根目录安装 Node 依赖。
订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经海外 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。开发代理通过 `API_PROXY_TARGET` 与 `OVERSEAS_API_PROXY_TARGET` 分别配置国内、海外 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。 订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经统一 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。本地代理仅通过 `API_PROXY_TARGET` 配置统一 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
认证会话保存 Access Token 和轮换后的 Refresh Token,并对并发 401 请求执行单次刷新。刷新或会话上下文加载遇到临时网络故障、超时等非认证错误时保留当前有效 Token,只有服务端明确返回 401/会话失效才清理登录状态。客户端只接受 `app_code` 为 `MERCHANT` 的 JWT;页面权限通过当前用户授权接口实时加载,不从 JWT 携带或解析角色权限。前端权限仅用于导航和交互控制,服务端仍须按用户、客户和权限编码完成最终授权。 认证会话保存 Access Token 和轮换后的 Refresh Token,并对并发 401 请求执行单次刷新。刷新或会话上下文加载遇到临时网络故障、超时等非认证错误时保留当前有效 Token,只有服务端明确返回 401/会话失效才清理登录状态。客户端只接受 `app_code` 为 `MERCHANT` 的 JWT;页面权限通过当前用户授权接口实时加载,不从 JWT 携带或解析角色权限。前端权限仅用于导航和交互控制,服务端仍须按用户、客户和权限编码完成最终授权。
@@ -47,4 +47,10 @@ pnpm test
头程订单列表、详情、仓库查询、创建/编辑草稿和提交已经接入真实 API,并显式映射后端 `transportMode`、`containerMode` 和订单状态。创建与提交请求携带幂等键,`merchant:order:create`、`merchant:order:edit`、`merchant:order:submit` 分别映射到独立前端操作权限。页面补齐渠道、提货方式、报关模式、目的仓类型、包装类型等后端必填字段;API 模式先清空本地记录,请求失败不会回退模拟成功。FBA 和海外仓按公共仓类型筛选,选择后由仓库主数据生成目的仓字段,不再要求客户重复选择收货单位;私人仓才填写并按当前用户缓存收件资料。只有“我司提货”需要填写提货联系人和地址,其他送货方式不发送发货方快照,订单也不再依赖往来单位 `customerId`。快递信息仍由平台维护、客户只读。订单取消不属于本轮本地订单与客户验收,客户端不暴露取消写操作。订单产品状态仍按已确认的七状态执行,不设置“已驳回”;若兼容旧接口数据收到 `REJECTED`,只按待审核展示且不开放编辑。 头程订单列表、详情、仓库查询、创建/编辑草稿和提交已经接入真实 API,并显式映射后端 `transportMode`、`containerMode` 和订单状态。创建与提交请求携带幂等键,`merchant:order:create`、`merchant:order:edit`、`merchant:order:submit` 分别映射到独立前端操作权限。页面补齐渠道、提货方式、报关模式、目的仓类型、包装类型等后端必填字段;API 模式先清空本地记录,请求失败不会回退模拟成功。FBA 和海外仓按公共仓类型筛选,选择后由仓库主数据生成目的仓字段,不再要求客户重复选择收货单位;私人仓才填写并按当前用户缓存收件资料。只有“我司提货”需要填写提货联系人和地址,其他送货方式不发送发货方快照,订单也不再依赖往来单位 `customerId`。快递信息仍由平台维护、客户只读。订单取消不属于本轮本地订单与客户验收,客户端不暴露取消写操作。订单产品状态仍按已确认的七状态执行,不设置“已驳回”;若兼容旧接口数据收到 `REJECTED`,只按待审核展示且不开放编辑。
联调远端 Gateway 时,进程环境变量优先于 `.env` 文件。浏览器国内业务统一请求同源 `/api`,海外业务请求同源 `/overseas-api`,由代理分别转发并确保最终路径只有一个 `/api` 前缀。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。 联调远端 Gateway 时,进程环境变量优先于 `.env` 文件。浏览器全部业务统一请求同源 `/api`,由同一代理转发并确保最终路径只有一个 `/api` 前缀。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。
## 唯一测试部署入口
仅保留 `docker-compose.test.yml` 与 test Jenkins Job。发布前注入 `API_UPSTREAM`(统一 Gateway origin,不含 `/api`)、`TEST_NETWORK`(后端共享测试网络)、`VITE_ADMIN_WEB_ORIGIN`(管理后台 origin,构建时用于安全代登录)与 `IMAGE_TAG`(Jenkins 从当前提交生成)。`HOST_PORT` 默认 9002 且仅绑定 loopback;宿主机反向代理负责外部入口。可选 `NODE_BASE_IMAGE`/`NGINX_BASE_IMAGE`,私有镜像认证由构建节点管理。不得把本地构建结果描述为测试环境已发布。
同机目标默认值:`API_UPSTREAM=http://gateway:9000`、`TEST_NETWORK=firstleg-test-network`;必须与后端同批 test Compose 配置一致。
-21
View File
@@ -1,21 +0,0 @@
services:
client-web:
image: client-web-development:${IMAGE_TAG:?IMAGE_TAG is required}
container_name: client-web-development
restart: unless-stopped
ports:
- "127.0.0.1:9002:80"
environment:
API_UPSTREAM: "http://firstleg-development-gateway:9000"
OVERSEAS_API_UPSTREAM: "http://firstleg-development-gateway-overseas:9300"
networks:
- development-backend
- development-overseas-backend
networks:
development-backend:
external: true
name: firstleg-development-network
development-overseas-backend:
external: true
name: firstleg-development-overseas-network
+11 -8
View File
@@ -1,19 +1,22 @@
name: firstleg-prod-client-web name: firstleg-prod-client-web
services: services:
client-web: client-web:
image: ${IMAGE_REPOSITORY:?IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required} image: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required}"
container_name: firstleg-prod-client-web container_name: firstleg-prod-client-web
restart: unless-stopped restart: unless-stopped
ports: ports:
- "127.0.0.1:${HOST_PORT:-9002}:80" - "127.0.0.1:${HOST_PORT:-29012}:80"
environment: environment:
API_UPSTREAM: "http://gateway:9000" API_UPSTREAM: "http://gateway:9000"
OVERSEAS_API_UPSTREAM: "http://gateway-overseas:9300" healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
interval: 5s
timeout: 3s
retries: 12
start_period: 5s
networks: networks:
- infra-network - backend
networks: networks:
infra-network: backend:
external: true external: true
name: firstleg-prod-infra-network name: firstleg-production-network
+17 -7
View File
@@ -1,19 +1,29 @@
name: firstleg-test-client-web
services: services:
client-web: client-web:
build: build:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
args: args:
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:-https://test-admin.buggoglobal.com}"
NODE_IMAGE: "${NODE_BASE_IMAGE:-node:22-alpine}" NODE_IMAGE: "${NODE_BASE_IMAGE:-node:22-alpine}"
NGINX_IMAGE: "${NGINX_BASE_IMAGE:-nginx:1.27-alpine}" NGINX_IMAGE: "${NGINX_BASE_IMAGE:-nginx:1.27-alpine}"
image: client-web-test:local VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN is required}"
image: client-web-test:${IMAGE_TAG:?IMAGE_TAG is required}
container_name: client-web-test container_name: client-web-test
restart: unless-stopped restart: unless-stopped
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
interval: 5s
timeout: 3s
retries: 12
start_period: 5s
ports: ports:
- "${HOST_PORT:-9002}:80" - "127.0.0.1:${HOST_PORT:-9002}:80"
extra_hosts:
- "host.docker.internal:host-gateway"
environment: environment:
API_UPSTREAM: "${API_UPSTREAM:-http://host.docker.internal:9000}" API_UPSTREAM: "${API_UPSTREAM:-http://gateway:9000}"
OVERSEAS_API_UPSTREAM: "${OVERSEAS_API_UPSTREAM:-http://host.docker.internal:9300}" networks:
- test-backend
networks:
test-backend:
external: true
name: "${TEST_NETWORK:-firstleg-test-network}"
+42
View File
@@ -0,0 +1,42 @@
# Client业务详细索引
本文件保存当前页面/API 入口及业务规则,是[应用指引](../AGENTS.md)的按需补充。涉及字段、状态、权限、金额、资源或作业恢复时必须读取受影响条款,不作为普通定位任务的全文首读。
正文代码路径以工作区 `apps/client-web/` 应用根起算,源码包缩写与裸文件名沿对应条目的目录解释;明确标注“工作区”的路径从工作区根起算。Markdown 相对链接以本文件所在的 `docs/` 为起点。已知文件直接定位;行为变更同时核对最近模块指引及服务端合同。
原条款在本文件维护,主 AGENTS 仅保留短入口和通用边界;不要将新业务细节复制回主指引。
## 模块快速查询
退货预报与签收结果:`src/modules/overseas-warehouse/views/ReturnOrdersView.vue`、`api/returnOrders.ts`;菜单仍名为“退货换标”。列表路由 `return-relabel`、独立新建路由 `return-relabel/create` 与详情路由均复用该页面,并分别由 `createPage/detailPage` 明确模式;新建页直接填写海外仓、联系人、客户参考号及 SKU 预报明细,取消或提交后返回列表,不再由 `WarehouseServiceView.vue` 或列表内弹框承载。客户退货库存/箱号共用 `views/ReturnInventoryView.vue`、`api/returnInventory.ts`,`return-cartons` 传 `cartonOnly=true`。Backend 为 Lastleg `returnreceipt/`,退货单签收完成不等于换标或退货出库完成;后续换标、出库须按各自业务状态核对。
先从 `src/modules/registry.ts` 确认模块,再按目标模块的 `routes.ts → views/ → api/、store/、contracts.ts 或 public.ts` 查询。页面是否正式开放以 `routes.ts` 的 `release` 为准,不从任务或进度文档推断。
| 业务 | 模块入口 | 联查模块或服务端 |
|---|---|---|
| 登录、注册与会话 | `src/modules/auth/`、`src/api/session.ts`、`src/api/http.ts` | Backend `auth/`、`iam/`;正常轮换的统一 Access/Refresh Token 会话持久化,“记住账号”只记登录标识;访问令牌失效但刷新令牌仍在时先恢复会话,公开认证接口不得携带旧 Token |
| 企业资料、成员与角色 | `src/modules/tenant-management/`、`src/modules/account/` | Backend `iam/`、`auth/`、`file/`;公司联系电话/邮箱是企业资料,不作为登录标识;成员登录手机号可选,修改时同步 Auth、撤销该账号会话并审计。审核必填资质仅营业执照与统一社会信用代码;法人身份证选填,可随营业执照提交,也可在已有营业执照后单独补传或替换。前端角色树到服务端权限的映射统一维护在 `contracts.ts` 的 `FRONTEND_TO_MERCHANT_PERMISSION_CODES`,海外入仓、采购、本土卡车和散板权限必须显式进入该映射 |
| 工作台与系统入口 | `src/modules/dashboard/`、`src/modules/system/` | `src/navigation/clientNavigation.ts`、`src/router/index.ts` |
| 企业成员消息收件箱 | `src/modules/notifications/` | Backend `iam/src/main/java/com/baiyue/iam/notification/`;列表、详情、已读与未读数契约见 `iam/src/main/resources/openapi/notification-v1.yaml` |
| 头程下单、中文批量导入、入仓码关系、箱唛、履约进度与入库费用确认 | `src/modules/first-leg/`;列表与批量入口 `views/FirstLegOrdersView.vue`,模板/导入 API `api/firstLeg.ts`,入仓详情 `components/InboundCodeAssociationDialog.vue`、`api/inboundCodeAssociations.ts`,费用确认弹框 `components/InboundBillingPanel.vue`、`api/inboundBilling.ts` | 中文 XLSX 模板按当前客户生成地址、全部有效仓库和渠道下拉,最多 50 行,只创建草稿并支持部分/原子导入;导入结果只显示 Excel 行号,不展示内部 `clientRowId`。列表“确认计费重”仅在具备确认权限且服务端 `customerFeeConfirmationRequired=true` 时显示,已确认或未推送费用时隐藏;详情可查看费用;确认提交 `expectedFeeVersion` 与幂等键,成功后版本锁定、平台不得再修改。Backend `order/`、`firstleg/`、`warehouse/`,不得用内部 ID 补齐缺失业务编号 |
| 装柜完成后的退税报关资料 | `src/modules/first-leg/views/FirstLegOrdersView.vue` 的“报关资料”、`components/CustomsDocumentsDialog.vue`、`api/customs.ts` | 只显示登录客户在同柜的退税入仓码;报关开始前可上传、替换、调整同一资料覆盖的一个或多个入仓码及删除误传,全部写入携带幂等键和版本;开始后只读冻结资料,整柜完成后才能下载平台回传的一对一完成文件。Backend `firstleg/customs/container/`、`customs-v1.yaml`,二进制归 `file/` |
| 统一订单展示 | `src/modules/order-management/` | `src/modules/first-leg/` 与对应后端订单契约 |
| 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `src/modules/finance/`;确认与明细入口 `views/FinanceBillsView.vue`、`api/finance.ts`,入仓码通过 `src/modules/first-leg/public.ts` 复用 `InboundCodeAssociationDialog` | Backend `finance/`;账单行只显示服务端 `inboundCode` 并按登录客户查询业务关系,缺失显示“—”,不得回退内部 ID。收款方式由服务端枚举映射中文。出账或已出账调整后为 `PENDING_CONFIRMATION`,客户确认提交登录成员、`expectedVersion` 和幂等键 |
| 客户资金账户、授信与充值申请 | `src/modules/finance/views/FinanceAccountView.vue`、`api/account.ts` | 显示当前企业 CNY 实际余额、冻结金额、授信额度、授信有效期、已用授信、冻结授信、总可用余额和不可变流水;数据加载前显示“—”,不得先伪装为零。授信到期日当天仍有效,次日已用授信并入实际余额,负数实际余额会阻止提交新订单。充值只展示服务端启用的平台统一静态收款码,客户上传 JPG/PNG 付款截图后进入待审核。客户范围只取登录态,无收款码时禁止提交,不模拟支付成功 |
| 海外采购 | `src/modules/cross-border/routes.ts`、`views/ProcurementView.vue`、`components/ProcurementDetailPanel.vue`、`api/procurement.ts` | 独立列表、新建及详情路由;客户范围只取 Token,创建的 `customerName` 只取认证会话企业名称。七状态简化流程展示分批收货、分批出库与费用,待客户确认时提供当前客户确认动作;不开放内部文件或平台操作。Backend `lastleg-service/procurement/`;规则见 `baiyue-firstleg/lastleg-service/docs/procurement-workflow.md`(工作区路径) |
| 美国本土卡与美本土散板 | `src/modules/cross-border/routes.ts`、`components/BusinessOrdersView.vue`、`api/businessOrders.ts` | 两个运输业务共用列表/表单组件,客户范围只取 Token;不消费采购字段或状态。Backend `lastleg-service/` 的 `trucking/`、`looseboard/` 客户接口 |
| 海外仓入库订单 | `src/modules/order-management/routes.ts`、`views/InboundOrdersView.vue`、`api/inboundPlans.ts` | `orders/inbound` 为只读列表/详情,权限 `merchant:warehouse:inbound:list`;不展示或提交内部 ID |
| 海外仓贴标、仓储转运、货物废弃 | `src/modules/overseas-warehouse/routes.ts`、`views/WarehouseServiceView.vue`、`api/warehouseServices.ts` | 三个路由均为 `active`;退货预报另见本节独立入口;贴标申请先选国外中转仓和有库存历史入仓单,换标类型为只换 SKU、只换箱唛、SKU+箱唛。涉及箱唛换标时,整张贴标申请只选择一个 FBA 目的仓,全部箱级明细统一提交该目的仓,模板和明细不再逐行选择目的仓。箱唛换标明细一行固定代表一箱,箱数不可编辑,提交也固定为 1。货物明细外层提供统一贴标明细模板,使用“贴标类型”列区分只换箱唛、只换 SKU 标签和 SKU+箱唛三种模式;上传只进入待导入关系区,客户可勾选部分或全选后导入本次明细,同一份文件不得混用多种类型,只有进入明细的库存才随申请提交和冻结。明细也支持手动新增编辑,组合换标以仓库唛头连接旧/新 SKU 和新 FBA 箱唛关系。涉及箱唛换标时必须选择卡车、自提或快递;快递可选择打印面单并上传 PDF/图片。PDA 逐箱换标、上传照片并由仓库复核后,客户详情展示完工照片和“换标完成确认”;客户确认前不得继续出库,确认后卡车进入预排车,自提/快递进入换标出库待创建。历史库存位置不能解释成箱唛与具体托盘快照,客户页面不暴露托盘、库位和内部库存 ID |
## Client 全量验收快速索引
当前按客户侧全量业务闭环验收。业务域文档用于核对功能来源和验收证据,不限制本次验收的模块范围;按“模块 `routes.ts` → 页面/组件 → `api`、store、contracts”定位。本表只描述 Client 页面与客户可见契约,服务端实现详见后端模块指引。
| 验收域 | Client 范围与代码入口 | 验收首读 |
|---|---|---|
| 客户基础与订单 | 登录/注册、企业资料与资质、成员/角色权限、工作台和订单 | `src/modules/auth/`、`tenant-management/`、`account/`、`system/`、`dashboard/`、`first-leg/`、`order-management/`;按客户可见契约核对权限、状态、幂等和错误处理 |
| 履约、海外仓与财务 | 入库计费、柜次进度、船期、海外仓贴标/转运/废弃/退货换标、消息和客户账单 | `src/modules/first-leg/`、`overseas-warehouse/`、`finance/`、`notifications/`;按服务端权限核对客户可见字段、客户隔离和只读/写入边界 |
客户侧边界:仍以服务端权限和客户可见字段为准;PDA、平台后台操作和内部证据不因全量验收自动暴露到 Client。财务按 `../../docs/财务管理/` 与 `src/modules/finance/routes.ts` 定位。
- 货物废弃:有箱唛按具体箱选择,备注选填;无箱唛但有托盘时只填申请总箱数与必填备注,预留相关托盘供PDA扫描现场箱唛自动计数。详情展示废弃备注、托盘、实际废弃箱唛与实际数量;现场扫描清单与申请选箱快照分别展示。
-11
View File
@@ -35,17 +35,6 @@ server {
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
} }
# 海外业务使用独立 Gateway;浏览器前缀只在此处改写一次为 /api。
location /overseas-api/ {
client_max_body_size 55m;
rewrite ^/overseas-api/(.*)$ /api/$1 break;
proxy_pass ${OVERSEAS_API_UPSTREAM};
proxy_http_version 1.1;
proxy_set_header Host $proxy_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 支持 Vue Router history 路由直接刷新。 # 支持 Vue Router history 路由直接刷新。
location / { location / {
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

+52 -87
View File
@@ -1,93 +1,58 @@
#!/usr/bin/env sh #!/bin/sh
set -eu set -eu
set +x
if [ "$#" -ne 4 ]; then : "${PUBLIC_WEB_ORIGIN:?PUBLIC_WEB_ORIGIN is required}"
echo "用法: $0 <服务名> <镜像仓库> <镜像标签> <Compose 文件>" >&2 : "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}"
exit 2 : "${TARGET_SSH_KEY:?}"
fi : "${TARGET_SSH_USER:?}"
: "${TARGET_SSH_HOST:?}"
SERVICE="$1" : "${TARGET_SSH_KNOWN_HOSTS:?}"
IMAGE_REPOSITORY="$2" : "${BUILD_REGISTRY_USER:?}"
IMAGE_TAG="$3" : "${BUILD_REGISTRY_PASSWORD:?}"
COMPOSE_FILE="$4" : "${REGISTRY_USER:?}"
IMAGE="$IMAGE_REPOSITORY:$IMAGE_TAG" : "${REGISTRY_PASSWORD:?}"
REGISTRY_HOST="${IMAGE_REPOSITORY%%/*}" case "$PUBLIC_WEB_ORIGIN" in https://*) ;; *) echo 'prod requires HTTPS web origin' >&2; exit 2 ;; esac
SSH_TARGET="${TARGET_SSH_TARGET:?TARGET_SSH_TARGET 未设置}" # Only an origin (optionally a trailing slash) is accepted; no shell/env-file metacharacters.
SSH_KEY="${TARGET_SSH_KEY:?TARGET_SSH_KEY 未设置}" printf '%s' "$PUBLIC_WEB_ORIGIN" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]+)?/?$'
SSH_KNOWN_HOSTS="${TARGET_SSH_KNOWN_HOSTS:?TARGET_SSH_KNOWN_HOSTS 未设置}" printf '%s' "$PRODUCTION_IMAGE_REPOSITORY" | grep -Eq '^[A-Za-z0-9.-]+(:[0-9]+)?/[a-z0-9._/-]+$'
REMOTE_DIR="${TARGET_DEPLOY_DIR:?TARGET_DEPLOY_DIR 未设置}" git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
: "${REGISTRY_USER:?REGISTRY_USER 未设置}" test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)"
: "${REGISTRY_PASSWORD:?REGISTRY_PASSWORD 未设置}" IMAGE_TAG=$(git rev-parse --short=12 HEAD)
registry=${PRODUCTION_IMAGE_REPOSITORY%%/*}
image="$PRODUCTION_IMAGE_REPOSITORY:$IMAGE_TAG"
TARGET_SSH_TARGET="$TARGET_SSH_USER@$TARGET_SSH_HOST"
remote_dir=/data/firstleg/deploy/gray-client-web
run_ssh() { run_ssh() {
ssh -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \ ssh -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$SSH_TARGET" "$@" -o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$TARGET_SSH_TARGET" "$@"
} }
run_scp() { run_scp() {
scp -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \ scp -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$@" -o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$@"
} }
export DOCKER_CONFIG
run_ssh install -d -m 750 "$REMOTE_DIR" DOCKER_CONFIG=$(mktemp -d)
REMOTE_COMPOSE="$REMOTE_DIR/docker-compose.$SERVICE.yml" cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
run_scp "$COMPOSE_FILE" "$SSH_TARGET:$REMOTE_COMPOSE.tmp" trap cleanup EXIT HUP INT TERM
run_ssh sh -s -- "$REMOTE_COMPOSE.tmp" "$REMOTE_COMPOSE" <<'REMOTE_PREPARE' printf '%s' "$BUILD_REGISTRY_PASSWORD" | docker login -u "$BUILD_REGISTRY_USER" --password-stdin "$registry"
docker build --build-arg NODE_IMAGE="${NODE_BASE_IMAGE:-node:22-alpine}" \
--build-arg NGINX_IMAGE="${NGINX_BASE_IMAGE:-nginx:1.27-alpine}" \
--build-arg VITE_ADMIN_WEB_ORIGIN="$PUBLIC_WEB_ORIGIN" -t "$image" .
docker push "$image"
run_ssh install -d -m 750 "$remote_dir"
run_scp docker-compose.production.yml "$TARGET_SSH_TARGET:$remote_dir/compose.yml"
# The remote env file contains only image coordinates and public web origin, never credentials.
printf 'PRODUCTION_IMAGE_REPOSITORY=%s\nIMAGE_TAG=%s\nPUBLIC_WEB_ORIGIN=%s\n' \
"$PRODUCTION_IMAGE_REPOSITORY" "$IMAGE_TAG" "$PUBLIC_WEB_ORIGIN" | run_ssh sh -c "'umask 077; cat > $remote_dir/release.env'"
# Registry credentials exist only in an isolated temporary Docker config, removed after pull.
printf '%s' "$REGISTRY_USER" | grep -Eq '^[A-Za-z0-9_.@-]+$'
run_scp scripts/pull-production-image.sh "$TARGET_SSH_TARGET:$remote_dir/pull-image.sh"
printf '%s' "$REGISTRY_PASSWORD" | run_ssh sh "$remote_dir/pull-image.sh" "$REGISTRY_USER" "$registry" "$image"
run_ssh sh -s -- "$remote_dir" <<'REMOTE'
set -eu set -eu
compose_tmp="$1" cd "$1"
compose_target="$2" docker network inspect firstleg-production-network >/dev/null
chmod 644 "$compose_tmp" docker compose --env-file release.env -f compose.yml config --quiet
mv -f "$compose_tmp" "$compose_target" docker compose --env-file release.env -f compose.yml up -d --wait --wait-timeout 120
REMOTE_PREPARE docker compose --env-file release.env -f compose.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
REMOTE
printf '%s' "$REGISTRY_PASSWORD" | run_ssh docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
trap 'run_ssh docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true' EXIT HUP INT TERM
run_ssh docker pull "$IMAGE"
run_ssh sh -s -- "$REMOTE_DIR" "$SERVICE" "$IMAGE_REPOSITORY" "$IMAGE_TAG" <<'REMOTE_DEPLOY'
set -eu
remote_dir="$1"
service="$2"
image_repository="$3"
image_tag="$4"
compose_file="docker-compose.$service.yml"
project_name="firstleg-prod-$service"
cd "$remote_dir"
export IMAGE_REPOSITORY="$image_repository" IMAGE_TAG="$image_tag"
compose() {
docker compose --project-name "$project_name" -f "$compose_file" "$@"
}
container_id="$(compose ps --all --quiet "$service" | head -n 1)"
previous_image=""
if [ -n "$container_id" ]; then
previous_image="$(docker inspect --format '{{.Config.Image}}' "$container_id")"
fi
if compose up -d --no-deps --pull never "$service" && \
compose exec -T "$service" wget -qO- http://127.0.0.1/healthz >/dev/null; then
echo "生产前端部署成功: $image_repository:$image_tag"
compose ps "$service"
exit 0
fi
echo "生产前端健康检查失败,准备回滚" >&2
compose logs --tail=100 "$service" >&2 || true
case "$previous_image" in
"$image_repository:"*) ;;
'') echo "首次部署无旧镜像可回滚" >&2; exit 1 ;;
*) echo "旧镜像不属于当前应用,拒绝回滚: $previous_image" >&2; exit 1 ;;
esac
previous_tag="${previous_image#"$image_repository:"}"
if [ "$previous_tag" = "$image_tag" ]; then
echo "旧镜像与新镜像一致,无法回滚" >&2
exit 1
fi
docker pull "$previous_image"
export IMAGE_TAG="$previous_tag"
compose up -d --no-deps --pull never "$service"
compose exec -T "$service" wget -qO- http://127.0.0.1/healthz >/dev/null || true
echo "已回滚至: $previous_image" >&2
exit 1
REMOTE_DEPLOY
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
set +x
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
trap cleanup EXIT HUP INT TERM
docker login -u "$1" --password-stdin "$2"
docker pull "$3"
+1
View File
@@ -92,6 +92,7 @@ export const FIRST_LEG_ORDER_STATUSES = [
{ code: 'LOADED', label: '装柜完成' }, { code: 'LOADED', label: '装柜完成' },
{ code: 'DELIVERED', label: '派送完成' }, { code: 'DELIVERED', label: '派送完成' },
{ code: 'COMPLETED', label: '已完成' }, { code: 'COMPLETED', label: '已完成' },
{ code: 'CANCELLED', label: '已取消' },
] as const ] as const
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code'] export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
+104 -16
View File
@@ -1,8 +1,8 @@
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios' import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
import { parseApiJsonResponse } from '@chongchong/shared' import { parseApiJsonResponse } from '@chongchong/shared'
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session' import { accessTokenIdentity, clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails' import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
import { ApiError, isApiEnvelope, type ApiEnvelope } from '@/api/types' import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh' import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
const transport = axios.create({ const transport = axios.create({
@@ -13,9 +13,18 @@ const transport = axios.create({
interface RetryableRequest extends InternalAxiosRequestConfig { interface RetryableRequest extends InternalAxiosRequestConfig {
_retriedAfterRefresh?: boolean _retriedAfterRefresh?: boolean
_sessionIdentity?: string | null
_logoutGeneration?: number
} }
function unwrap<T>(envelope: ApiEnvelope<T>) { function unwrap<T>(envelope: ApiEnvelope<T>) {
if (!isApiEnvelope(envelope)) {
const invalid: unknown = envelope
if (isApiFailure(invalid)) {
throw new ApiError(invalid.message, invalid.code, undefined, undefined, invalid.traceId, invalid.requestId)
}
throw new ApiError('接口响应格式错误', 'INVALID_RESPONSE')
}
if (envelope.code !== '200') { if (envelope.code !== '200') {
const fieldErrors = asFieldErrors(envelope.data) const fieldErrors = asFieldErrors(envelope.data)
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId, envelope.requestId) throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId, envelope.requestId)
@@ -28,8 +37,8 @@ function mapError(error: unknown) {
if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败') if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败')
const body = error.response?.data const body = error.response?.data
if (isApiEnvelope(body)) { if (isApiEnvelope(body) || isApiFailure(body)) {
const fieldErrors = asFieldErrors(body.data) const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
return new ApiError( return new ApiError(
apiErrorMessage(body.message, fieldErrors), apiErrorMessage(body.message, fieldErrors),
body.code, body.code,
@@ -44,9 +53,12 @@ function mapError(error: unknown) {
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status) return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
} }
let refreshExchange: { identity: string; refreshToken: string; promise: Promise<TokenPair> } | null = null
let logoutGeneration = 0
let refreshPromise: Promise<string> | null = null let refreshPromise: Promise<string> | null = null
let refreshIdentity: string | null = null
let redirectingToLogin = false let redirectingToLogin = false
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/impersonations/exchange'] const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout', '/auth/impersonations/exchange']
function isPublicAuthRequest(url?: string) { function isPublicAuthRequest(url?: string) {
return publicAuthPaths.some((path) => url?.endsWith(path)) return publicAuthPaths.some((path) => url?.endsWith(path))
@@ -63,29 +75,46 @@ function redirectToLoginAfterSessionExpiry() {
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`) window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
} }
function requireCurrentIdentity(identity: string | null | undefined, accessToken = getAccessToken()) {
if (!identity || accessTokenIdentity(accessToken) !== identity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
}
export async function refreshAuthenticatedSession() { export async function refreshAuthenticatedSession() {
const observedIdentity = accessTokenIdentity(getAccessToken())
requireCurrentIdentity(observedIdentity)
const observedRefreshToken = getRefreshToken() const observedRefreshToken = getRefreshToken()
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401) if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
if (!refreshPromise) { if (!refreshPromise) {
refreshIdentity = observedIdentity
refreshPromise = coordinateCrossTabRefresh({ refreshPromise = coordinateCrossTabRefresh({
lockName: 'cc-client-auth-refresh', lockName: 'cc-client-auth-refresh',
observedRefreshToken, observedRefreshToken,
currentRefreshToken: getRefreshToken, currentRefreshToken: getRefreshToken,
reuseCurrentSession: async () => { reuseCurrentSession: async () => {
requireCurrentIdentity(observedIdentity)
const currentAccessToken = getAccessToken() const currentAccessToken = getAccessToken()
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401) if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
return currentAccessToken return currentAccessToken
}, },
refresh: async (currentRefreshToken) => { refresh: async (currentRefreshToken) => {
const response = await transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }) requireCurrentIdentity(observedIdentity)
const tokens = unwrap(response.data) const exchange = { identity: observedIdentity!, refreshToken: currentRefreshToken, promise: transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }).then(response => unwrap(response.data)) }
refreshExchange = exchange
let tokens: TokenPair
try { tokens = await exchange.promise } finally { if (refreshExchange === exchange) refreshExchange = null }
requireCurrentIdentity(observedIdentity)
requireCurrentIdentity(observedIdentity, tokens.accessToken)
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401) if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
if (getRefreshToken() !== currentRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
persistTokenPair(tokens) persistTokenPair(tokens)
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('cc-client-session-updated'))
return tokens.accessToken return tokens.accessToken
}, },
}) })
.catch((error) => { .catch((error) => {
requireCurrentIdentity(observedIdentity)
if (error instanceof CrossTabRefreshTimeoutError) { if (error instanceof CrossTabRefreshTimeoutError) {
if (getRefreshToken() && getRefreshToken() !== observedRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
const expiredError = new ApiError(error.message, 'A0401', 401) const expiredError = new ApiError(error.message, 'A0401', 401)
clearSessionTokens() clearSessionTokens()
window.dispatchEvent(new CustomEvent('cc-client-session-expired')) window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
@@ -96,33 +125,60 @@ export async function refreshAuthenticatedSession() {
}) })
.finally(() => { .finally(() => {
refreshPromise = null refreshPromise = null
refreshIdentity = null
}) })
} }
return refreshPromise if (refreshIdentity !== observedIdentity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
const refreshed = await refreshPromise
requireCurrentIdentity(observedIdentity)
return refreshed
} }
transport.interceptors.request.use((config) => { transport.interceptors.request.use((config) => {
const token = getAccessToken() const token = getAccessToken()
if (token && !isPublicAuthRequest(config.url)) config.headers.Authorization = `Bearer ${token}` const request = config as RetryableRequest
if (request._retriedAfterRefresh && !isPublicAuthRequest(config.url)) requireCurrentIdentity(request._sessionIdentity, token)
if (token && !isPublicAuthRequest(config.url)) {
if (!request._retriedAfterRefresh) {
request._sessionIdentity = accessTokenIdentity(token)
request._logoutGeneration = logoutGeneration
}
config.headers.Authorization = `Bearer ${token}`
}
return config return config
}) })
transport.interceptors.response.use( transport.interceptors.response.use(
(response) => response, (response) => {
const request = response.config as RetryableRequest
if (request._sessionIdentity) {
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
requireCurrentIdentity(request._sessionIdentity)
}
return response
},
async (error: AxiosError) => { async (error: AxiosError) => {
const request = error.config as RetryableRequest | undefined const request = error.config as RetryableRequest | undefined
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) { if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
throw mapError(error) throw mapError(error)
} }
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
requireCurrentIdentity(request._sessionIdentity)
request._retriedAfterRefresh = true request._retriedAfterRefresh = true
const refreshTokenBeforeRetry = getRefreshToken()
try { try {
const accessToken = await refreshAuthenticatedSession() const accessToken = await refreshAuthenticatedSession()
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
requireCurrentIdentity(request._sessionIdentity)
request.headers.Authorization = `Bearer ${accessToken}` request.headers.Authorization = `Bearer ${accessToken}`
return await transport.request(request) return await transport.request(request)
} catch (refreshError) { } catch (refreshError) {
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
requireCurrentIdentity(request._sessionIdentity)
const mappedError = mapError(refreshError) const mappedError = mapError(refreshError)
if (mappedError.status === 401 || mappedError.code === 'A0401') { if (mappedError.status === 401 || mappedError.code === 'A0401') {
if (getRefreshToken() && getRefreshToken() !== refreshTokenBeforeRetry) throw mappedError
clearSessionTokens() clearSessionTokens()
window.dispatchEvent(new CustomEvent('cc-client-session-expired')) window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
redirectToLoginAfterSessionExpiry() redirectToLoginAfterSessionExpiry()
@@ -132,6 +188,33 @@ transport.interceptors.response.use(
}, },
) )
// Captured revocation never persists credentials or restores local login state.
export async function revokeCapturedSession(accessToken: string, refreshToken: string) {
logoutGeneration++
const identity = accessTokenIdentity(accessToken)
if (!identity || !refreshToken) throw new ApiError('服务器会话注销未确认', 'SESSION_CHANGED')
const pending = refreshExchange?.identity === identity && refreshExchange.refreshToken === refreshToken ? refreshExchange.promise : null
const revoke = (pair: Pick<TokenPair, 'accessToken' | 'refreshToken'>) => apiRequest<void>({
method: 'POST', url: '/auth/logout', data: { refreshToken: pair.refreshToken },
headers: { Authorization: `Bearer ${pair.accessToken}` },
})
const validate = (pair: TokenPair) => {
if (accessTokenIdentity(pair.accessToken) !== identity || !pair.refreshToken) throw new ApiError('刷新身份不一致,服务器会话注销未确认', 'SESSION_CHANGED')
return pair
}
// An already sent refresh can rotate the pair. Consume its actual result
// without issuing a competing refresh or restoring it to local storage.
if (pending) {
await revoke(validate(await pending))
return
}
try { await revoke({ accessToken, refreshToken }) } catch (error) {
if (!(error instanceof ApiError) || error.status !== 401) throw error
const pair = await apiRequest<TokenPair>({ method: 'POST', url: '/auth/refresh', data: { refreshToken } })
await revoke(validate(pair))
}
}
export async function apiRequest<T>(config: AxiosRequestConfig) { export async function apiRequest<T>(config: AxiosRequestConfig) {
try { try {
const response = await transport.request<ApiEnvelope<T>>(config) const response = await transport.request<ApiEnvelope<T>>(config)
@@ -144,6 +227,7 @@ export async function apiRequest<T>(config: AxiosRequestConfig) {
export async function apiBlobRequest(config: AxiosRequestConfig) { export async function apiBlobRequest(config: AxiosRequestConfig) {
try { try {
const response = await transport.request<Blob>({ ...config, responseType: 'blob' }) const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
await throwBlobApiError(response.data, response.status)
return response.data return response.data
} catch (error) { } catch (error) {
await throwBlobApiError(error) await throwBlobApiError(error)
@@ -154,6 +238,7 @@ export async function apiBlobRequest(config: AxiosRequestConfig) {
export async function apiBlobResponseRequest(config: AxiosRequestConfig) { export async function apiBlobResponseRequest(config: AxiosRequestConfig) {
try { try {
const response = await transport.request<Blob>({ ...config, responseType: 'blob' }) const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
await throwBlobApiError(response.data, response.status)
return { blob: response.data, headers: response.headers } return { blob: response.data, headers: response.headers }
} catch (error) { } catch (error) {
await throwBlobApiError(error) await throwBlobApiError(error)
@@ -161,16 +246,19 @@ export async function apiBlobResponseRequest(config: AxiosRequestConfig) {
} }
} }
async function throwBlobApiError(error: unknown) { async function throwBlobApiError(error: unknown, responseStatus?: number) {
if (!axios.isAxiosError(error) || !(error.response?.data instanceof Blob)) return const blob = error instanceof Blob
? error
: axios.isAxiosError(error) && error.response?.data instanceof Blob ? error.response.data : null
if (!blob || !blob.type.toLowerCase().includes('json')) return
try { try {
const body = JSON.parse(await error.response.data.text()) as unknown const body = JSON.parse(await blob.text()) as unknown
if (!isApiEnvelope(body)) return if (!isApiEnvelope(body) && !isApiFailure(body)) return
const fieldErrors = asFieldErrors(body.data) const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
throw new ApiError( throw new ApiError(
apiErrorMessage(body.message, fieldErrors), apiErrorMessage(body.message, fieldErrors),
body.code, body.code,
error.response.status, responseStatus ?? (axios.isAxiosError(error) ? error.response?.status : undefined),
fieldErrors, fieldErrors,
typeof body.traceId === 'string' ? body.traceId : null, typeof body.traceId === 'string' ? body.traceId : null,
typeof body.requestId === 'string' ? body.requestId : null, typeof body.requestId === 'string' ? body.requestId : null,
+3 -3
View File
@@ -26,8 +26,8 @@ test('does not accept malformed or data-less successful responses', () => {
assert.equal(isApiEnvelope({ code: '200', message: 'OK', data: [] }), true) assert.equal(isApiEnvelope({ code: '200', message: 'OK', data: [] }), true)
}) })
test('overseas transport handles business-code and HTTP security failures', async () => { test('unified transport handles business-code and HTTP security failures', async () => {
const transport = await readFile(new URL('./overseasHttp.ts', import.meta.url), 'utf8') const transport = await readFile(new URL('./http.ts', import.meta.url), 'utf8')
assert.match(transport, /if \(isApiFailure\(response.data\)\)/) assert.match(transport, /if \(isApiFailure\(invalid\)\)/)
assert.match(transport, /isApiEnvelope\(body\) \|\| isApiFailure\(body\)/) assert.match(transport, /isApiEnvelope\(body\) \|\| isApiFailure\(body\)/)
}) })
-91
View File
@@ -1,91 +0,0 @@
import axios, { type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
import { parseApiJsonResponse } from '@chongchong/shared'
import { ApiError, isApiEnvelope, isApiFailure } from '@/api/types'
import { getOverseasAccessToken } from '@/api/session'
import { refreshAuthenticatedSession } from '@/api/http'
interface RetryableRequest extends InternalAxiosRequestConfig { _retriedOverseasAuth?: boolean }
const transport = axios.create({
baseURL: import.meta.env.VITE_OVERSEAS_API_BASE_URL || '/overseas-api',
timeout: 15_000,
transformResponse: [(data: unknown) => parseApiJsonResponse(data)],
})
async function requireToken() {
const current = getOverseasAccessToken()
if (current) return current
await refreshAuthenticatedSession()
const refreshed = getOverseasAccessToken()
if (!refreshed) throw new ApiError('当前环境未签发海外访问令牌', 'OVERSEAS_TOKEN_UNAVAILABLE')
return refreshed
}
transport.interceptors.request.use(async (config) => {
config.headers.Authorization = `Bearer ${await requireToken()}`
return config
})
transport.interceptors.response.use((response) => response, async (error) => {
const request = error.config as RetryableRequest | undefined
if (error.response?.status !== 401 || !request || request._retriedOverseasAuth) throw error
request._retriedOverseasAuth = true
await refreshAuthenticatedSession()
request.headers.Authorization = `Bearer ${await requireToken()}`
return transport.request(request)
})
export async function overseasApiRequest<T>(config: AxiosRequestConfig) {
try {
const response = await transport.request<unknown>(config)
if (isApiFailure(response.data)) {
throw new ApiError(response.data.message, response.data.code, response.status, undefined,
response.data.traceId, response.data.requestId)
}
if (!isApiEnvelope(response.data) || response.data.code !== '200') {
throw new ApiError(
isApiEnvelope(response.data) ? response.data.message : '海外接口响应格式错误',
isApiEnvelope(response.data) ? response.data.code : 'INVALID_RESPONSE',
undefined,
undefined,
isApiEnvelope(response.data) ? response.data.traceId : null,
isApiEnvelope(response.data) ? response.data.requestId : null,
)
}
return response.data.data as T
} catch (error) {
if (error instanceof ApiError) throw error
if (axios.isAxiosError(error)) {
const body = error.response?.data
if (isApiEnvelope(body) || isApiFailure(body)) {
throw new ApiError(body.message, body.code, error.response?.status, undefined, body.traceId, body.requestId)
}
throw new ApiError(error.code === 'ERR_NETWORK' ? '无法连接海外服务' : error.message, error.code || 'OVERSEAS_HTTP_ERROR', error.response?.status)
}
throw new ApiError(error instanceof Error ? error.message : '海外接口请求失败')
}
}
export async function overseasBlobRequest(config: AxiosRequestConfig) {
try {
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
return response.data
} catch (error) {
if (error instanceof ApiError) throw error
if (axios.isAxiosError(error)) {
const body = error.response?.data
if (body instanceof Blob && body.type.includes('json')) {
try {
const parsed: unknown = JSON.parse(await body.text())
if (isApiEnvelope(parsed) || isApiFailure(parsed)) {
throw new ApiError(parsed.message, parsed.code, error.response?.status, undefined, parsed.traceId, parsed.requestId)
}
} catch (parseError) {
if (parseError instanceof ApiError) throw parseError
}
}
throw new ApiError(error.code === 'ERR_NETWORK' ? '无法连接海外服务' : error.message, error.code || 'OVERSEAS_HTTP_ERROR', error.response?.status)
}
throw new ApiError(error instanceof Error ? error.message : '海外文件下载失败')
}
}
+32
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import test from 'node:test' import test from 'node:test'
import { import {
accessTokenIdentity,
ACCESS_TOKEN_KEY, ACCESS_TOKEN_KEY,
REFRESH_TOKEN_KEY, REFRESH_TOKEN_KEY,
REMEMBERED_LOGIN_ID_KEY, REMEMBERED_LOGIN_ID_KEY,
@@ -56,3 +57,34 @@ test('remembers only the login id and keeps it when session tokens are cleared',
persistRememberedLoginId('merchant-user', false) persistRememberedLoginId('merchant-user', false)
assert.equal(getRememberedLoginId(), '') assert.equal(getRememberedLoginId(), '')
}) })
test('normal token rotation never removes either shared token between writes', () => {
installStorage()
localStorage.setItem(ACCESS_TOKEN_KEY, 'old-access')
localStorage.setItem(REFRESH_TOKEN_KEY, 'old-refresh')
const removed = []
const remove = localStorage.removeItem
localStorage.removeItem = key => { removed.push(key); remove(key) }
persistTokenPair({ accessToken: 'new-access', refreshToken: 'new-refresh' })
assert.ok(!removed.includes(ACCESS_TOKEN_KEY))
assert.ok(!removed.includes(REFRESH_TOKEN_KEY))
})
function rawIdentity(overrides = '') {
return `test.${Buffer.from(`{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"${overrides}}`).toString('base64url')}.test`
}
test('identity preserves low digits of numeric 19 digit user customer and membership',()=>{
const original=rawIdentity();const json=Buffer.from(original.split('.')[1],'base64url').toString();
for(const field of ['user_id','tenant_id','membership_id']){
const changed=json.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`)
assert.notEqual(accessTokenIdentity(original),accessTokenIdentity(`test.${Buffer.from(changed).toString('base64url')}.test`))
}
})
test('identity string and numeric integers are equivalent without changing other strings',()=>{
const a=rawIdentity();const raw=Buffer.from(a.split('.')[1],'base64url').toString();
const b=`test.${Buffer.from(raw.replaceAll(':2107003446494334978',':"2107003446494334978"')).toString('base64url')}.test`
assert.equal(accessTokenIdentity(a),accessTokenIdentity(b))
const decorated=rawIdentity(',"username":'+JSON.stringify('number 2107003446494334979 and "tenant_id":2107003446494334979')+',"note":"1234567890123456789"')
assert.equal(accessTokenIdentity(a),accessTokenIdentity(decorated))
assert.ok(accessTokenIdentity(a).includes('2107003446494334978'))
})
+29 -20
View File
@@ -1,7 +1,5 @@
export const ACCESS_TOKEN_KEY = 'cc-client-access-token' export const ACCESS_TOKEN_KEY = 'cc-client-access-token'
export const REFRESH_TOKEN_KEY = 'cc-client-refresh-token' export const REFRESH_TOKEN_KEY = 'cc-client-refresh-token'
export const OVERSEAS_ACCESS_TOKEN_KEY = 'cc-client-overseas-access-token'
export const OVERSEAS_EXPIRES_AT_KEY = 'cc-client-overseas-expires-at'
export const REMEMBERED_LOGIN_ID_KEY = 'cc-client-remembered-login-id' export const REMEMBERED_LOGIN_ID_KEY = 'cc-client-remembered-login-id'
export interface TokenPair { export interface TokenPair {
@@ -10,14 +8,8 @@ export interface TokenPair {
expiresIn: number expiresIn: number
refreshToken: string refreshToken: string
refreshExpiresIn: number refreshExpiresIn: number
overseasAccessToken?: string | null
overseasExpiresIn?: number
} }
function activeStorage() {
if (localStorage.getItem(ACCESS_TOKEN_KEY)) return localStorage
return sessionStorage
}
export function getAccessToken() { export function getAccessToken() {
return localStorage.getItem(ACCESS_TOKEN_KEY) || sessionStorage.getItem(ACCESS_TOKEN_KEY) || '' return localStorage.getItem(ACCESS_TOKEN_KEY) || sessionStorage.getItem(ACCESS_TOKEN_KEY) || ''
@@ -27,21 +19,40 @@ export function getRefreshToken() {
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || '' return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
} }
export function getOverseasAccessToken() { // Only binds a retry to its original identity; never grants permissions. Expired
const storage = activeStorage() // access tokens remain readable here because they are the normal refresh trigger.
const expiresAt = Number(storage.getItem(OVERSEAS_EXPIRES_AT_KEY) || 0) export function accessTokenIdentity(token: string): string | null {
if (expiresAt <= Date.now() + 30_000) return '' try {
return storage.getItem(OVERSEAS_ACCESS_TOKEN_KEY) || '' const encoded = token.split('.')[1]
if (!encoded) return null
const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
const bytes = Uint8Array.from(atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')), character => character.charCodeAt(0))
const json = new TextDecoder().decode(bytes)
// Match whole JSON strings first so digits inside arbitrary string values
// are never rewritten. Preserve integer identity claims before JSON.parse
// can round them; number/string representations then share one identity.
const exactIdentityJson = json.replace(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (part, offset: number) => {
if (!/^-?\d+$/.test(part)) return part
const key = json.slice(0, offset).match(/"(user_id|tenant_id|membership_id|operator_tenant_id)"\s*:\s*$/)
return key ? JSON.stringify(part) : part
})
const value = JSON.parse(exactIdentityJson)
if (!value?.user_id || !value.tenant_id || !value.membership_id || value.app_code !== 'MERCHANT') return null
return JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type].map(item => item == null ? null : String(item)))
} catch {
return null
}
} }
export function persistTokenPair(tokens: TokenPair) { export function persistTokenPair(tokens: TokenPair) {
clearSessionTokens() // Replace the pair without publishing a transient logout to other tabs.
sessionStorage.removeItem(ACCESS_TOKEN_KEY)
sessionStorage.removeItem(REFRESH_TOKEN_KEY)
sessionStorage.removeItem('cc-client-token')
localStorage.removeItem('cc-client-token')
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken) localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken) localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
if (tokens.overseasAccessToken && Number(tokens.overseasExpiresIn) > 0) {
localStorage.setItem(OVERSEAS_ACCESS_TOKEN_KEY, tokens.overseasAccessToken)
localStorage.setItem(OVERSEAS_EXPIRES_AT_KEY, String(Date.now() + Number(tokens.overseasExpiresIn) * 1000))
}
} }
export function getRememberedLoginId() { export function getRememberedLoginId() {
@@ -62,8 +73,6 @@ export function clearSessionTokens() {
for (const storage of [localStorage, sessionStorage]) { for (const storage of [localStorage, sessionStorage]) {
storage.removeItem(ACCESS_TOKEN_KEY) storage.removeItem(ACCESS_TOKEN_KEY)
storage.removeItem(REFRESH_TOKEN_KEY) storage.removeItem(REFRESH_TOKEN_KEY)
storage.removeItem(OVERSEAS_ACCESS_TOKEN_KEY)
storage.removeItem(OVERSEAS_EXPIRES_AT_KEY)
storage.removeItem('cc-client-token') storage.removeItem('cc-client-token')
} }
} }
+222
View File
@@ -0,0 +1,222 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import axios from 'axios'
function compile(name, dependencies = {}) {
const source = readFileSync(new URL(name, import.meta.url), 'utf8')
.replace('import.meta.env.VITE_API_BASE_URL', "'/api'")
const code = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
}).outputText
const exports = {}
new Function('require', 'exports', code)((id) => {
assert.ok(id in dependencies, `unexpected dependency ${id}`)
return dependencies[id]
}, exports)
return exports
}
function access(user, tenant = 1, membership = 1, nonce = 'original') {
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, app_code: 'MERCHANT', nonce })).toString('base64url')}.test`
}
const oldAccess = access(1)
const newAccess = access(1, 1, 1, 'rotated')
const otherAccess = access(2, 2, 2)
function harness(adapter) {
let token = oldAccess
let refreshToken = 'old-refresh'
const http = compile('./http.ts', {
axios: { ...axios, create: (config) => axios.create({ ...config, adapter }) },
'@chongchong/shared': { parseApiJsonResponse: (data) => data },
'@/api/session': {
accessTokenIdentity: compile('./session.ts').accessTokenIdentity,
getAccessToken: () => token, getRefreshToken: () => refreshToken,
persistTokenPair: (tokens) => { token = tokens.accessToken; refreshToken = tokens.refreshToken },
clearSessionTokens: () => { token = ''; refreshToken = '' },
},
'@/api/errorDetails': compile('./errorDetails.ts'),
'@/api/types': compile('./types.ts'),
'@/api/crossTabRefresh': compile('./crossTabRefresh.ts'),
})
return { ...http, setSession: (access, refresh) => { token = access; refreshToken = refresh }, session: () => ({ token, refreshToken }) }
}
test('order and lastleg 401s share one refresh and replay the unified access token', async () => {
let refreshes = 0
const calls = []
const http = harness(async (config) => {
calls.push({ url: config.url, base: config.baseURL, token: config.headers.Authorization })
if (config.url === '/auth/refresh') {
refreshes++
await new Promise((resolve) => setTimeout(resolve, 10))
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
}
if (config.headers.Authorization === `Bearer ${oldAccess}`) {
throw new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
}
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: config.url } }
})
const urls = ['/merchant/v1/orders', '/merchant/v1/last-leg/inbound-plans']
assert.deepEqual(await Promise.all(urls.map((url) => http.apiRequest({ url }))), urls)
assert.equal(refreshes, 1)
assert.ok(calls.every((call) => call.base === '/api'))
assert.equal(calls.find((call) => call.url === '/auth/refresh').token, undefined)
assert.equal(calls.filter((call) => call.token === `Bearer ${newAccess}`).length, 2)
})
test('successful order submit with explicit null data is accepted', async () => {
const http = harness(async (config) => ({
config, status: 200, headers: {}, data: { code: '200', message: 'success', data: null },
}))
assert.equal(await http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/order-1/submit' }), null)
})
test('data-less security failures preserve diagnostics and malformed success is rejected', async () => {
for (const data of [{ code: 'A0403', message: 'Denied', traceId: 'trace-1', requestId: 'request-1' }, { code: '200', message: 'OK' }]) {
const http = harness(async (config) => ({ config, status: 200, headers: {}, data }))
await assert.rejects(http.apiRequest({ url: '/merchant/v1/last-leg/inbound-plans' }), (error) => {
assert.equal(error.code, data.code === '200' ? 'INVALID_RESPONSE' : 'A0403')
if (data.code !== '200') { assert.equal(error.traceId, 'trace-1'); assert.equal(error.requestId, 'request-1') }
return true
})
}
})
test('late refresh response cannot overwrite a session changed in another tab', async () => {
let complete, started
const ready = new Promise(resolve => { started = resolve })
const response = new Promise(resolve => { complete = resolve })
const http = harness(async config => { started(); await response; return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: oldAccess, refreshToken: 'stale-refresh' } } } })
const pending = http.refreshAuthenticatedSession()
await ready
http.setSession(otherAccess, 'other-refresh')
complete()
await pending.catch(error => assert.equal(error.code, 'SESSION_CHANGED'))
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'other-refresh' })
})
function deferred() { let resolve; const promise = new Promise(yes => { resolve = yes }); return { promise, resolve } }
function unauthorized(config) {
return new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
}
test('late A write 401 after user, customer or membership switch never refreshes or replays under B', async () => {
for (const next of [access(2), access(1, 2), access(1, 1, 2)]) {
const sent = deferred(), release = deferred(), calls = []
const http = harness(async config => {
calls.push(config.url); sent.resolve(); await release.promise
throw unauthorized(config)
})
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit', data: { expectedVersion: 1 } })
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
await sent.promise; http.setSession(next, 'refresh-b'); release.resolve(); await rejected
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit'])
assert.deepEqual(http.session(), { token: next, refreshToken: 'refresh-b' })
}
})
test('switch during in-flight refresh cannot reuse B token to replay an A write', async () => {
const refreshing = deferred(), release = deferred(), calls = []
const http = harness(async config => {
calls.push(config.url)
if (config.url === '/auth/refresh') {
refreshing.resolve(); await release.promise
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
}
throw unauthorized(config)
})
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
await refreshing.promise; http.setSession(otherAccess, 'refresh-b'); release.resolve(); await rejected
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit', '/auth/refresh'])
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'refresh-b' })
})
test('refresh lock wait reuses same-identity rotation but rejects changed-identity reuse', async t => {
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
t.after(() => { if (originalNavigator) Object.defineProperty(globalThis, 'navigator', originalNavigator); else delete globalThis.navigator })
for (const next of [newAccess, otherAccess]) {
const waiting = deferred(), release = deferred(), calls = []
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: { request: async (_name, _options, run) => {
waiting.resolve(); await release.promise; return run()
} } } })
const http = harness(async config => {
calls.push({ url: config.url, authorization: config.headers.Authorization })
if (config.headers.Authorization === `Bearer ${oldAccess}`) throw unauthorized(config)
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: null } }
})
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
const outcome = next === otherAccess ? assert.rejects(pending, error => error.code === 'SESSION_CHANGED') : pending
await waiting.promise; http.setSession(next, 'rotated-refresh'); release.resolve(); await outcome
assert.equal(calls.some(call => call.url === '/auth/refresh'), false)
assert.equal(calls.length, next === otherAccess ? 1 : 2)
assert.deepEqual(http.session(), { token: next, refreshToken: 'rotated-refresh' })
}
})
function authApi(http) { return compile('../modules/auth/api/auth.ts', { '@/api/http': http }) }
function ok(config, data = null) { return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data } } }
test('logout after immediate local clear revokes captured Bearer and Refresh', async () => {
const calls=[]; const http=harness(async c=>{calls.push(c);return ok(c)})
http.setSession('', '');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
assert.equal(calls.length,1);assert.equal(calls[0].headers.Authorization,`Bearer ${oldAccess}`)
assert.deepEqual(JSON.parse(calls[0].data),{refreshToken:'old-refresh'});assert.deepEqual(http.session(),{token:'',refreshToken:''})
})
test('only explicit logout401 refreshes once and revokes same-identity replacement without storing it', async () => {
const calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'});if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
http.setSession('','');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
assert.deepEqual(calls.map(x=>x.url),['/auth/logout','/auth/refresh','/auth/logout']);assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[2].data).refreshToken,'new-refresh');assert.deepEqual(http.session(),{token:'',refreshToken:''})
})
test('unknown logout failure never refreshes; changed identity cannot be revoked as replacement', async () => {
for(const mode of ['network','wrongIdentity','second401']){const calls=[];const http=harness(async c=>{calls.push(c);if(mode==='network')throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c);if(c.url==='/auth/refresh')return ok(c,{accessToken:mode==='wrongIdentity'?otherAccess:newAccess,refreshToken:'replacement'});throw unauthorized(c)})
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(oldAccess,'old-refresh'));assert.equal(calls.length,mode==='network'?1:mode==='wrongIdentity'?2:3);assert.deepEqual(http.session(),{token:'',refreshToken:''})}
})
test('logout consumes already inflight refresh once while old business caller cannot revive session',async()=>{
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}return ok(c)})
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing,e=>e.code==='SESSION_CHANGED');await started.promise
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');release.resolve();await leaving;await rejected
assert.deepEqual(calls.map(x=>x.url),['/auth/refresh','/auth/logout']);assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:'',refreshToken:''})
})
test('late successful business response after logout rejects even after same-identity new login',async()=>{
const started=deferred(),release=deferred();const http=harness(async c=>{if(c.url==='/merchant/v1/orders'){started.resolve();await release.promise}return ok(c,'old-data')})
const pending=http.apiRequest({url:'/merchant/v1/orders'});const rejected=assert.rejects(pending,e=>e.code==='SESSION_CHANGED');await started.promise
await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected;assert.equal(http.session().refreshToken,'new-login-refresh')
})
test('inflight refresh unknown outcome stops logout without competing retry and preserves later login',async()=>{
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);started.resolve();await release.promise;throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c)})
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');const failure=assert.rejects(leaving,e=>e.code==='NETWORK_ERROR');http.setSession(otherAccess,'other-refresh');release.resolve();await failure;await rejected
assert.equal(calls.length,1);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
})
test('logout401 refresh and replacement revocation cannot overwrite later login',async()=>{
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');await started.promise;http.setSession(otherAccess,'other-refresh');release.resolve();await leaving
assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
})
test('late old business401 after logout does not refresh or replay under same-identity new login',async()=>{
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/merchant/v1/orders/first-leg/one/submit'){started.resolve();await release.promise;throw unauthorized(c)}return ok(c)})
const request=http.apiRequest({method:'POST',url:'/merchant/v1/orders/first-leg/one/submit'});const rejected=assert.rejects(request,e=>e.code==='SESSION_CHANGED');await started.promise;await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected
assert.deepEqual(calls.map(x=>x.url),['/merchant/v1/orders/first-leg/one/submit','/auth/logout']);assert.equal(http.session().refreshToken,'new-login-refresh')
})
test('same identity new pair logout does not adopt another session inflight refresh',async()=>{
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'old-session-rotated'})}return ok(c)})
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise;http.setSession(newAccess,'new-login-refresh')
const leaving=authApi(http).logoutMerchant(newAccess,'new-login-refresh');http.setSession('','');await leaving
assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[1].data).refreshToken,'new-login-refresh');release.resolve();await rejected;assert.deepEqual(http.session(),{token:'',refreshToken:''})
})
test('logout rejects refreshed 19 digit identity differing only in low digit',async()=>{
const raw='{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"}'
const original=`test.${Buffer.from(raw).toString('base64url')}.test`
for(const field of ['user_id','tenant_id','membership_id']){
const changed=raw.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`),calls=[]
const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:`test.${Buffer.from(changed).toString('base64url')}.test`,refreshToken:'replacement'});throw unauthorized(c)})
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(original,'original-refresh'),e=>e.code==='SESSION_CHANGED');assert.equal(calls.length,2)
}
})
+1 -1
View File
@@ -6,5 +6,5 @@
// biome-ignore lint: disable // biome-ignore lint: disable
export {} export {}
declare global { declare global {
const ElMessageBox: typeof import('element-plus/es').ElMessageBox
} }
+3 -2
View File
@@ -22,9 +22,9 @@ declare module 'vue' {
ElCard: typeof import('element-plus/es')['ElCard'] ElCard: typeof import('element-plus/es')['ElCard']
ElCheckbox: typeof import('element-plus/es')['ElCheckbox'] ElCheckbox: typeof import('element-plus/es')['ElCheckbox']
ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup'] ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup']
ElCollapse: typeof import('element-plus/es')['ElCollapse']
ElCollapseItem: typeof import('element-plus/es')['ElCollapseItem']
ElDatePicker: typeof import('element-plus/es')['ElDatePicker'] ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
ElDescriptions: typeof import('element-plus/es')['ElDescriptions']
ElDescriptionsItem: typeof import('element-plus/es')['ElDescriptionsItem']
ElDialog: typeof import('element-plus/es')['ElDialog'] ElDialog: typeof import('element-plus/es')['ElDialog']
ElDrawer: typeof import('element-plus/es')['ElDrawer'] ElDrawer: typeof import('element-plus/es')['ElDrawer']
ElDropdown: typeof import('element-plus/es')['ElDropdown'] ElDropdown: typeof import('element-plus/es')['ElDropdown']
@@ -42,6 +42,7 @@ declare module 'vue' {
ElRadio: typeof import('element-plus/es')['ElRadio'] ElRadio: typeof import('element-plus/es')['ElRadio']
ElRadioButton: typeof import('element-plus/es')['ElRadioButton'] ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup'] ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
ElResult: typeof import('element-plus/es')['ElResult']
ElSelect: typeof import('element-plus/es')['ElSelect'] ElSelect: typeof import('element-plus/es')['ElSelect']
ElSkeleton: typeof import('element-plus/es')['ElSkeleton'] ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
ElSwitch: typeof import('element-plus/es')['ElSwitch'] ElSwitch: typeof import('element-plus/es')['ElSwitch']
+34 -6
View File
@@ -1,12 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue' import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue' import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue'
import { import {
clientNavigation, clientNavigation,
filterNavigationByPermissions, filterNavigationByPermissions,
getNavigationParentKeys, getNavigationParentKeys,
getNavigationLeaves,
} from '@/navigation/clientNavigation' } from '@/navigation/clientNavigation'
import { useAuthStore } from '@/modules/auth/public' import { useAuthStore } from '@/modules/auth/public'
import { useCustomsPendingStore } from '@/modules/first-leg/public'
const props = defineProps<{ const props = defineProps<{
activePath: string activePath: string
@@ -16,14 +18,39 @@ const emit = defineEmits<{
navigate: [path: string] navigate: [path: string]
}>() }>()
const auth = useAuthStore() const auth = useAuthStore()
const visibleNavigation = computed(() => filterNavigationByPermissions(clientNavigation, auth.permissionCodes)) const customsPending = useCustomsPendingStore()
const badges = computed(() => ({ 'first-leg-customs-documents': { count: customsPending.count, error: customsPending.error } }))
watch(() => auth.isAuthenticated && auth.hasPermission('order:first-leg:customs-list') ? auth.user?.id ?? '' : '', scope => {
customsPending.setScope(scope)
if (scope) void customsPending.refresh()
}, { immediate: true, flush: 'sync' })
function refreshCustomsPending() {
if (document.visibilityState === 'visible') void customsPending.refresh()
}
let refreshTimer: ReturnType<typeof setInterval> | undefined
onMounted(() => {
refreshTimer = setInterval(refreshCustomsPending, 60_000)
window.addEventListener('focus', refreshCustomsPending)
document.addEventListener('visibilitychange', refreshCustomsPending)
})
onBeforeUnmount(() => {
clearInterval(refreshTimer)
window.removeEventListener('focus', refreshCustomsPending)
document.removeEventListener('visibilitychange', refreshCustomsPending)
customsPending.setScope('')
})
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath))) const visibleNavigation = computed(() => filterNavigationByPermissions(clientNavigation, auth.permissionCodes))
const activeNavigationPath = computed(() => getNavigationLeaves(visibleNavigation.value)
.filter(node => node.path === props.activePath || (node.path !== '/' && props.activePath.startsWith(`${node.path}/`)))
.sort((left, right) => right.path.length - left.path.length)[0]?.path ?? props.activePath)
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, activeNavigationPath.value)))
const openedKeys = ref<ReadonlySet<string>>(new Set(activeParentKeys.value)) const openedKeys = ref<ReadonlySet<string>>(new Set(activeParentKeys.value))
// Expand the order group by default so the three customer order shortcuts are visible.
openedKeys.value = new Set([...openedKeys.value, 'order-center'])
function handleToggle(key: string) { function handleToggle(key: string) {
if (activeParentKeys.value.has(key)) return
const next = new Set(openedKeys.value) const next = new Set(openedKeys.value)
if (next.has(key)) next.delete(key) if (next.has(key)) next.delete(key)
else next.add(key) else next.add(key)
@@ -49,7 +76,8 @@ function handleSelect(path: string) {
v-for="node in visibleNavigation" v-for="node in visibleNavigation"
:key="node.key" :key="node.key"
:node="node" :node="node"
:active-path="activePath" :badges="badges"
:active-path="activeNavigationPath"
:opened-keys="openedKeys" :opened-keys="openedKeys"
:active-parent-keys="activeParentKeys" :active-parent-keys="activeParentKeys"
:level="0" :level="0"
+15 -1
View File
@@ -8,6 +8,7 @@ const props = defineProps<{
activePath: string activePath: string
openedKeys: ReadonlySet<string> openedKeys: ReadonlySet<string>
activeParentKeys: ReadonlySet<string> activeParentKeys: ReadonlySet<string>
badges?: Readonly<Record<string, { count: number | null; error: string }>>
level?: number level?: number
}>() }>()
@@ -16,6 +17,9 @@ const emit = defineEmits<{
toggle: [key: string] toggle: [key: string]
}>() }>()
const badge = computed(() => props.badges?.[props.node.key])
const badgeTitle = computed(() => badge.value?.error || `${badge.value?.count ?? 0} 个柜次待上传资料或确认回执`)
const groupId = computed(() => `client-nav-group-${props.node.key}`) const groupId = computed(() => `client-nav-group-${props.node.key}`)
</script> </script>
@@ -23,6 +27,7 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
<li <li
class="client-nav-node" class="client-nav-node"
v-if="node.children" v-if="node.children"
:data-nav-key="node.key"
:class="{ :class="{
'has-divider-before': node.dividerBefore, 'has-divider-before': node.dividerBefore,
'is-active-parent': activeParentKeys.has(node.key), 'is-active-parent': activeParentKeys.has(node.key),
@@ -54,6 +59,7 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
v-for="child in node.children" v-for="child in node.children"
:key="child.key" :key="child.key"
:node="child" :node="child"
:badges="badges"
:active-path="activePath" :active-path="activePath"
:opened-keys="openedKeys" :opened-keys="openedKeys"
:active-parent-keys="activeParentKeys" :active-parent-keys="activeParentKeys"
@@ -64,7 +70,7 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
</ul> </ul>
</li> </li>
<li v-else class="client-nav-node" :class="{ 'has-divider-before': node.dividerBefore }"> <li v-else class="client-nav-node" :data-nav-key="node.key" :class="{ 'has-divider-before': node.dividerBefore }">
<RouterLink <RouterLink
:to="node.path" :to="node.path"
class="client-sidebar-link" class="client-sidebar-link"
@@ -78,6 +84,14 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
aria-hidden="true" aria-hidden="true"
/> />
<span>{{ node.title }}</span> <span>{{ node.title }}</span>
<span v-if="badge?.error || (badge?.count != null && badge.count > 0)" class="client-nav-badge"
:title="badgeTitle" :aria-label="badgeTitle" role="status">
{{ badge?.error ? '!' : badge!.count! > 99 ? '99+' : badge?.count }}
</span>
</RouterLink> </RouterLink>
</li> </li>
</template> </template>
<style scoped>
.client-sidebar-link .client-nav-badge { display: inline-flex; flex: 0 0 auto; min-width: 23px; height: 23px; align-items: center; justify-content: center; margin-left: auto; padding: 0 5px; border: 2px solid #fff; border-radius: 999px; background: #ef4444; color: #fff; box-shadow: 0 3px 9px rgb(239 68 68 / 24%); font-size: 12px; font-weight: 700; line-height: 1; }
</style>
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { parse, compileScript } from 'vue/compiler-sfc'
import ts from 'typescript'
import * as vue from 'vue'
const source = readFileSync(new URL('./DataTable.vue', import.meta.url), 'utf8')
function paginationHarness(t) {
const descriptor = parse(source).descriptor
const compiled = compileScript(descriptor, { id: 'data-table-pagination-test' })
const code = ts.transpileModule(compiled.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const exports = {}
const deps = { vue, '@lucide/vue': { ChevronLeft: {}, ChevronRight: {} }, './tableActions': {} }
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
const component = exports.default
component.render = () => null
const state = vue.reactive({ page: 5, total: 5542, loading: false, error: false })
const emitted = []
const renderer = vue.createRenderer({
createElement: tag => ({ tag }), createText: text => ({ text }), createComment: text => ({ text }),
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
parentNode: () => null, nextSibling: () => null,
})
const app = renderer.createApp({ render: () => vue.h(component, {
data: [], columns: [], page: state.page, pageSize: 50, total: state.total, loading: state.loading,
'onUpdate:page': value => { emitted.push(value); state.page = value },
}, state.error ? { error: () => vue.h('div', 'Request failed') } : {}) })
app.mount({})
t.after(() => app.unmount())
return { state, emitted }
}
test('server-page loading must not reset the requested page when total temporarily clears', async t => {
const { state, emitted } = paginationHarness(t)
state.loading = true; state.total = 0
await vue.nextTick()
assert.equal(state.page, 5)
assert.deepEqual(emitted, [])
state.total = 5542; state.loading = false
await vue.nextTick()
assert.equal(state.page, 5)
assert.deepEqual(emitted, [])
})
test('failed server page retains its page for explicit retry and emits no automatic fallback request', async t => {
const { state, emitted } = paginationHarness(t)
state.loading = true; state.total = 0
await vue.nextTick()
state.error = true; state.loading = false
await vue.nextTick()
assert.equal(state.page, 5)
assert.deepEqual(emitted, [])
state.error = false; state.loading = true
await vue.nextTick()
state.total = 5542; state.loading = false
await vue.nextTick()
assert.equal(state.page, 5)
assert.deepEqual(emitted, [])
})
test('settled successful totals still clamp out-of-range and empty pages', async t => {
const { state, emitted } = paginationHarness(t)
state.total = 120
await vue.nextTick()
assert.equal(state.page, 3)
state.total = 0
await vue.nextTick()
assert.equal(state.page, 1)
assert.deepEqual(emitted, [3, 1])
})
test('keeps action-only table toolbars on the left', () => {
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
assert.match(source, /\.data-table__toolbar--actions-only \{ justify-content: flex-start; \}/)
})
+11 -6
View File
@@ -88,7 +88,9 @@ watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
page.value = 1 page.value = 1
}, { immediate: true }) }, { immediate: true })
watch([page, pageCount], ([value, count]) => { watch([page, pageCount, () => props.loading, () => Boolean(slots.error)], ([value, count, loading, hasError]) => {
// A cleared total is not an authoritative page count while loading or showing a request error.
if (loading || hasError) return
const nextValue = normalizePage(value, count) const nextValue = normalizePage(value, count)
if (value !== nextValue) page.value = nextValue if (value !== nextValue) page.value = nextValue
}, { immediate: true }) }, { immediate: true })
@@ -143,8 +145,8 @@ function setPage(value: number) {
<template> <template>
<div class="data-table" :class="$attrs.class"> <div class="data-table" :class="$attrs.class">
<header v-if="$slots.toolbar || $slots['toolbar-actions']" class="data-table__toolbar"> <header v-if="$slots.toolbar || $slots['toolbar-actions']" class="data-table__toolbar" :class="{ 'data-table__toolbar--actions-only': !$slots.toolbar }">
<div class="data-table__toolbar-heading"><slot name="toolbar" /></div> <div v-if="$slots.toolbar" class="data-table__toolbar-heading"><slot name="toolbar" /></div>
<div class="data-table__toolbar-actions"><slot name="toolbar-actions" /></div> <div class="data-table__toolbar-actions"><slot name="toolbar-actions" /></div>
</header> </header>
<slot name="before-table" /> <slot name="before-table" />
@@ -163,7 +165,7 @@ function setPage(value: number) {
</template> </template>
<template v-if="column.slotName === 'actions' && rowActions" #default="{ row }"> <template v-if="column.slotName === 'actions' && rowActions" #default="{ row }">
<div class="data-table__row-actions"> <div class="data-table__row-actions">
<el-button v-for="action in splitTableActions(rowActions(row)).visible" :key="action.key" <el-button v-for="action in splitTableActions(rowActions(row)).visible" :key="action.key" link type="primary"
:disabled="action.disabled" :loading="action.loading" @click="runTableAction(action)"> :disabled="action.disabled" :loading="action.loading" @click="runTableAction(action)">
{{ action.label }} {{ action.label }}
</el-button> </el-button>
@@ -227,14 +229,17 @@ function setPage(value: number) {
<style scoped> <style scoped>
.data-table { min-width: 0; } .data-table { min-width: 0; }
.data-table__toolbar { display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--client-gap); padding: var(--client-toolbar-padding); border-bottom: 1px solid var(--client-border); } .data-table__toolbar { display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--client-gap); padding: var(--client-toolbar-padding); border-bottom: 1px solid var(--client-border); }
.data-table__toolbar--actions-only { justify-content: flex-start; }
.data-table__toolbar-heading, .data-table__toolbar-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--client-gap); } .data-table__toolbar-heading, .data-table__toolbar-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--client-gap); }
.data-table__toolbar-heading { color: var(--client-muted); font-size: 12px; } .data-table__toolbar-heading { color: var(--client-muted); font-size: 12px; }
.data-table__toolbar-heading :slotted(strong) { color: var(--client-text); font-size: 14px; } .data-table__toolbar-heading :slotted(strong) { color: var(--client-text); font-size: 14px; }
.data-table__toolbar-actions :deep(.el-button + .el-button) { margin-left: 0; } .data-table__toolbar-actions :deep(.el-button + .el-button) { margin-left: 0; }
.data-table__row-actions { display: flex; align-items: center; gap: var(--client-gap); white-space: nowrap; } .data-table__row-actions { display: flex; align-items: center; gap: var(--client-gap); white-space: nowrap; }
.data-table__row-actions :deep(.el-button) { height: var(--client-row-action-height); padding: 0 8px; margin: 0; } .data-table__row-actions :deep(.el-button) { height: var(--client-row-action-height); padding: 0 4px; margin: 0; }
.data-table__row-actions :deep(.el-button.is-link + .el-button.is-link) { position: relative; }
.data-table__row-actions :deep(.el-button.is-link + .el-button.is-link)::before { position: absolute; left: -5px; width: 1px; height: 12px; background: var(--client-border); content: ''; }
.data-table :deep(.data-table__system-cell .data-table__row-actions .el-button + .el-button), .data-table :deep(.data-table__system-cell .data-table__row-actions .el-button + .el-dropdown) { margin-left: 0; } .data-table :deep(.data-table__system-cell .data-table__row-actions .el-button + .el-button), .data-table :deep(.data-table__system-cell .data-table__row-actions .el-button + .el-dropdown) { margin-left: 0; }
.data-table__more { min-width: 28px; } .data-table__more { min-width: 28px; width: 28px; padding: 0; }
:global(.client-ui .data-table .el-table) { color: var(--client-text); font-size: var(--client-font-size); --el-table-border-color: var(--client-border); --el-table-header-bg-color: var(--client-header-bg); --el-table-row-hover-bg-color: var(--client-hover-bg); } :global(.client-ui .data-table .el-table) { color: var(--client-text); font-size: var(--client-font-size); --el-table-border-color: var(--client-border); --el-table-header-bg-color: var(--client-header-bg); --el-table-row-hover-bg-color: var(--client-hover-bg); }
:global(.client-ui .data-table th.el-table__cell) { height: var(--client-table-header-height); padding: 0; color: var(--client-muted); font-weight: 600; } :global(.client-ui .data-table th.el-table__cell) { height: var(--client-table-header-height); padding: 0; color: var(--client-muted); font-weight: 600; }
:global(.client-ui .data-table td.el-table__cell) { height: var(--client-table-row-height); padding: 0; } :global(.client-ui .data-table td.el-table__cell) { height: var(--client-table-row-height); padding: 0; }
+3 -2
View File
@@ -121,8 +121,8 @@ defineExpose({ search, reset })
</label> </label>
</div> </div>
<div class="query-toolbar__actions"> <div class="query-toolbar__actions">
<el-button type="primary" @click="search"><Search :size="16" />{{ searchText }}</el-button> <el-button class="query-toolbar__search" type="primary" @click="search"><Search :size="16" />{{ searchText }}</el-button>
<el-button @click="reset"><RotateCcw :size="16" />{{ resetText }}</el-button> <el-button class="query-toolbar__reset" @click="reset"><RotateCcw :size="16" />{{ resetText }}</el-button>
<slot name="actions" /> <slot name="actions" />
</div> </div>
</section> </section>
@@ -136,6 +136,7 @@ defineExpose({ search, reset })
.query-toolbar__filters :deep(.el-input), .query-toolbar__filters :deep(.el-select), .query-toolbar__filters :deep(.el-date-editor) { width: 260px; max-width: 100%; min-width: 0; } .query-toolbar__filters :deep(.el-input), .query-toolbar__filters :deep(.el-select), .query-toolbar__filters :deep(.el-date-editor) { width: 260px; max-width: 100%; min-width: 0; }
.query-toolbar__actions { display: flex; flex: 0 0 auto; flex-wrap: wrap; justify-content: flex-start; gap: 8px; } .query-toolbar__actions { display: flex; flex: 0 0 auto; flex-wrap: wrap; justify-content: flex-start; gap: 8px; }
.query-toolbar__actions :deep(.el-button + .el-button) { margin-left: 0; } .query-toolbar__actions :deep(.el-button + .el-button) { margin-left: 0; }
.query-toolbar__actions :deep(.query-toolbar__search), .query-toolbar__actions :deep(.query-toolbar__reset) { min-width: 72px; }
.query-toolbar--grid { display: block; padding: var(--client-query-padding); border: 1px solid var(--client-border); border-radius: var(--client-radius); } .query-toolbar--grid { display: block; padding: var(--client-query-padding); border: 1px solid var(--client-border); border-radius: var(--client-radius); }
.query-toolbar--grid .query-toolbar__filters { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px 16px; } .query-toolbar--grid .query-toolbar__filters { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px 16px; }
.query-toolbar--grid .query-toolbar__field { min-width: 0; } .query-toolbar--grid .query-toolbar__field { min-width: 0; }
+24
View File
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const recoverySource = readFileSync(new URL('./staticAssetRecovery.ts', import.meta.url), 'utf8')
const mainSource = readFileSync(new URL('../main.ts', import.meta.url), 'utf8')
test('refreshes once when a deployment invalidates lazy chunks or same-origin scripts and styles', () => {
assert.match(mainSource, /installStaticAssetRecovery\(router\)/)
assert.match(recoverySource, /vite:preloadError/)
assert.match(recoverySource, /router\.onError/)
assert.match(recoverySource, /HTMLScriptElement/)
assert.match(recoverySource, /HTMLLinkElement/)
assert.match(recoverySource, /window\.location\.reload\(\)/)
assert.match(recoverySource, /RECOVERY_COOLDOWN_MS/)
assert.match(recoverySource, /previous\?\.href === window\.location\.href/)
})
test('does not turn ordinary application errors or third-party asset failures into refresh loops', () => {
assert.match(recoverySource, /isStaticAssetLoadError\(error\)/)
assert.match(recoverySource, /origin !== window\.location\.origin/)
assert.match(recoverySource, /sessionStorage/)
assert.match(recoverySource, /setTimeout\(clearRecoveryRecord, RECOVERY_STABLE_MS\)/)
})
+91
View File
@@ -0,0 +1,91 @@
import type { Router } from 'vue-router'
const RECOVERY_KEY = 'client-static-asset-recovery'
const RECOVERY_COOLDOWN_MS = 60_000
const RECOVERY_STABLE_MS = 15_000
interface RecoveryRecord {
href: string
refreshedAt: number
}
function errorMessage(error: unknown) {
if (error instanceof Error) return `${error.name}: ${error.message}`
return typeof error === 'string' ? error : ''
}
export function isStaticAssetLoadError(error: unknown) {
return /ChunkLoadError|Loading chunk [\w-]+ failed|Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test(errorMessage(error))
}
function readRecoveryRecord(): RecoveryRecord | null {
try {
const raw = window.sessionStorage.getItem(RECOVERY_KEY)
if (!raw) return null
const value = JSON.parse(raw) as Partial<RecoveryRecord>
return typeof value.href === 'string' && typeof value.refreshedAt === 'number'
? { href: value.href, refreshedAt: value.refreshedAt }
: null
} catch {
return null
}
}
function writeRecoveryRecord(record: RecoveryRecord) {
try {
window.sessionStorage.setItem(RECOVERY_KEY, JSON.stringify(record))
return true
} catch {
// Without a persistent guard, reloading could loop while the deployment is still unavailable.
return false
}
}
function clearRecoveryRecord() {
try {
window.sessionStorage.removeItem(RECOVERY_KEY)
} catch {
// Storage availability must not affect application startup.
}
}
function recoverFromStaticAssetFailure(error: unknown, confirmedAssetFailure = false) {
if (!confirmedAssetFailure && !isStaticAssetLoadError(error)) return false
const now = Date.now()
const previous = readRecoveryRecord()
if (previous?.href === window.location.href && now - previous.refreshedAt < RECOVERY_COOLDOWN_MS) return false
if (!writeRecoveryRecord({ href: window.location.href, refreshedAt: now })) return false
window.location.reload()
return true
}
function failedApplicationAsset(event: Event) {
const target = event.target
if (target instanceof HTMLScriptElement) return target.src
if (target instanceof HTMLLinkElement && ['stylesheet', 'modulepreload', 'preload'].includes(target.rel)) return target.href
return ''
}
export function installStaticAssetRecovery(router: Router) {
window.addEventListener('vite:preloadError', (event) => {
const preloadEvent = event as Event & { payload?: unknown }
if (recoverFromStaticAssetFailure(preloadEvent.payload, true)) preloadEvent.preventDefault()
})
window.addEventListener('error', (event) => {
const assetUrl = failedApplicationAsset(event)
if (!assetUrl) return
try {
if (new URL(assetUrl, window.location.href).origin !== window.location.origin) return
} catch {
return
}
recoverFromStaticAssetFailure(assetUrl, true)
}, true)
router.onError((error) => {
recoverFromStaticAssetFailure(error)
})
window.setTimeout(clearRecoveryRecord, RECOVERY_STABLE_MS)
}
+51 -53
View File
@@ -1,65 +1,63 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs' import { readFileSync, existsSync } from 'node:fs'
import test from 'node:test' import test from 'node:test'
const config = readFileSync(new URL('../../nginx/default.conf.template', import.meta.url), 'utf8') const root = new URL('../../', import.meta.url)
const testCompose = readFileSync(new URL('../../docker-compose.test.yml', import.meta.url), 'utf8') const config = readFileSync(new URL('nginx/default.conf.template', root), 'utf8')
const developmentCompose = readFileSync(new URL('../../docker-compose.development.yml', import.meta.url), 'utf8') const compose = readFileSync(new URL('docker-compose.test.yml', root), 'utf8')
const productionCompose = readFileSync(new URL('../../docker-compose.production.yml', import.meta.url), 'utf8') const jenkins = readFileSync(new URL('Jenkinsfile', root), 'utf8')
const jenkinsfile = readFileSync(new URL('../../Jenkinsfile', import.meta.url), 'utf8') const vite = readFileSync(new URL('vite.config.ts', root), 'utf8')
const dockerfile = readFileSync(new URL('../../Dockerfile', import.meta.url), 'utf8')
test('allows 50 MiB uploads with multipart overhead through both API proxies', () => { test('all business traffic uses one Gateway without rewriting API paths', () => {
assert.match(config, /location \/api\/ \{[\s\S]*?client_max_body_size 55m;/) assert.match(config, /location \/api\//)
assert.match(config, /location \/overseas-api\/ \{[\s\S]*?client_max_body_size 55m;/) assert.match(config, /proxy_pass \$\{API_UPSTREAM\};/)
assert.equal(config.match(/client_max_body_size 55m;/g)?.length, 2) assert.doesNotMatch(config, /overseas-api|OVERSEAS_API_UPSTREAM|rewrite/)
}) assert.match(config, /client_max_body_size 55m;/)
test('does not cache the SPA entry while keeping hashed assets immutable', () => {
assert.match(config, /location = \/index\.html[\s\S]*no-store, no-cache, must-revalidate/)
assert.match(config, /location \/assets\/[\s\S]*max-age=31536000, immutable/)
assert.match(config, /location \/ \{[\s\S]*no-store, no-cache, must-revalidate[\s\S]*try_files \$uri \$uri\/ \/index\.html/)
})
test('routes domestic and overseas browser APIs to their test gateways without duplicate api prefixes', () => {
assert.match(testCompose, /- "host\.docker\.internal:host-gateway"/)
assert.match(testCompose, /API_UPSTREAM: "\$\{API_UPSTREAM:-http:\/\/host\.docker\.internal:9000\}"/)
assert.match(testCompose, /OVERSEAS_API_UPSTREAM: "\$\{OVERSEAS_API_UPSTREAM:-http:\/\/host\.docker\.internal:9300\}"/)
assert.doesNotMatch(testCompose, /http:\/\/test-api-(?:cn|global)\.buggoglobal\.com/)
assert.match(testCompose, /VITE_ADMIN_WEB_ORIGIN: "\$\{VITE_ADMIN_WEB_ORIGIN:-https:\/\/test-admin\.buggoglobal\.com\}"/)
assert.match(config, /location \/overseas-api\/ \{[\s\S]*?rewrite \^\/overseas-api\/\(\.\*\)\$ \/api\/\$1 break;[\s\S]*?proxy_pass \$\{OVERSEAS_API_UPSTREAM\};/)
assert.match(config, /proxy_set_header Host \$proxy_host;/) assert.match(config, /proxy_set_header Host \$proxy_host;/)
assert.doesNotMatch(config, /\/api\/api/) assert.doesNotMatch(vite, /OVERSEAS_API|AUTH_API_PROXY_TARGET|IAM_API_PROXY_TARGET|WAREHOUSE_API_PROXY_TARGET/)
}) })
test('connects the development client proxy to both development gateways', () => { test('test deployment requires an explicit shared network, Gateway and version', () => {
assert.match(developmentCompose, /API_UPSTREAM: "http:\/\/firstleg-development-gateway:9000"/) for (const key of ['IMAGE_TAG']) {
assert.match(developmentCompose, /OVERSEAS_API_UPSTREAM: "http:\/\/firstleg-development-gateway-overseas:9300"/) assert.ok(compose.includes('${' + key + ':?'))
assert.match(developmentCompose, /- development-backend/) }
assert.match(developmentCompose, /- development-overseas-backend/) assert.ok(compose.includes('${API_UPSTREAM:-http://gateway:9000}'))
assert.match(developmentCompose, /development-overseas-backend:[\s\S]*?external: true[\s\S]*?name: firstleg-development-overseas-network/) assert.ok(compose.includes('${TEST_NETWORK:-firstleg-test-network}'))
assert.doesNotMatch(developmentCompose, /test-api|prod(?:uction)?/i) assert.match(compose, /external: true/)
assert.match(compose, /127\.0\.0\.1:/)
assert.doesNotMatch(compose, /overseas|host\.docker\.internal|production|development/)
assert.match(jenkins, /'java-builder' : 'java-test'/)
assert.match(jenkins, /docker compose -f docker-compose\.test\.yml config --quiet/)
assert.match(jenkins, /docker network inspect/)
assert.match(jenkins, /scripts\/deploy-production\.sh/)
assert.match(jenkins, /firstleg-production-ssh/)
}) })
test('keeps local environments on target nodes and uses credential-managed SSH for production', () => { test('application shell is revalidated and missing chunks remain 404', () => {
assert.match(jenkinsfile, /env\.JOB_BASE_NAME\?\.endsWith\('-prod'\) \? 'java-builder'/) assert.match(config, /location = \/index\.html/)
assert.match(jenkinsfile, /DEVELOPMENT_COMPOSE_PROJECT = 'client-web'/) assert.match(config, /no-store/)
assert.match(jenkinsfile, /docker compose -p "\$DEVELOPMENT_COMPOSE_PROJECT" -f "\$DEVELOPMENT_COMPOSE_FILE" up -d/) assert.match(config, /max-age=31536000, immutable/)
assert.doesNotMatch(jenkinsfile, /\/var\/jenkins_home\/\.ssh|docker save/) assert.match(config, /try_files \$uri =404;/)
assert.match(jenkinsfile, /credentialsId: 'firstleg-production-ssh'/) assert.match(config, /try_files \$uri \$uri\/ \/index\.html;/)
assert.match(jenkinsfile, /git rev-parse origin\/main/)
assert.match(productionCompose, /127\.0\.0\.1:\$\{HOST_PORT:-9002\}:80/)
assert.match(productionCompose, /API_UPSTREAM: "http:\/\/gateway:9000"/)
assert.match(productionCompose, /name: firstleg-prod-infra-network/)
}) })
test('uses authenticated internal base images in CI', () => {
assert.match(dockerfile, /ARG NODE_IMAGE=node:22-alpine/) test('container build excludes local environment values and waits for Nginx health', () => {
assert.match(dockerfile, /ARG NGINX_IMAGE=nginx:1\.27-alpine/) const ignore = readFileSync(new URL('.dockerignore', root), 'utf8')
assert.match(dockerfile, /FROM \$\{NODE_IMAGE\} AS build/) assert.match(ignore, /^\.env$/m)
assert.match(dockerfile, /FROM \$\{NGINX_IMAGE\}/) assert.match(ignore, /^\.env\.\*$/m)
assert.match(jenkinsfile, /NODE_BASE_IMAGE = '172\.31\.198\.7:10082\/java-project\/node:22-alpine'/) assert.match(compose, /healthcheck:/)
assert.match(jenkinsfile, /NGINX_BASE_IMAGE = '172\.31\.198\.7:10082\/java-project\/nginx:1\.27-alpine'/) assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
assert.match(jenkinsfile, /withCredentials\(\[usernamePassword\(/) assert.match(jenkins, /up -d --wait --wait-timeout 120/)
assert.match(jenkinsfile, /export DOCKER_CONFIG="\$\{WORKSPACE\}@tmp\/docker-auth"/) })
test('gray production is isolated from TEST and routes to the single Gateway', () => {
const production = readFileSync(new URL('docker-compose.production.yml', root), 'utf8')
assert.match(production, /name: firstleg-production-network/)
assert.match(production, /API_UPSTREAM: "http:\/\/gateway:9000"/)
assert.match(production, /127\.0\.0\.1:/)
assert.match(production, /healthcheck:/)
assert.doesNotMatch(production, /test-network|gateway-overseas|gateway-active|routing-network/)
assert.doesNotMatch(jenkins, /wecom|sendProductionWeComNotification/)
}) })
+1
View File
@@ -11,6 +11,7 @@ declare module 'vue-router' {
requiresAuth?: boolean requiresAuth?: boolean
permission?: string permission?: string
workspaceTab?: boolean workspaceTab?: boolean
workspaceTitle?: string
keepAlive?: boolean keepAlive?: boolean
} }
} }
+73 -15
View File
@@ -1,6 +1,8 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import test from 'node:test' import test from 'node:test'
import ts from 'typescript'
import * as vue from 'vue'
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8') const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8') const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
@@ -13,12 +15,13 @@ test('source contract: renders the grouped sidebar menu and mobile drawer contro
assert.match(layoutSource, /import \{ computed, nextTick, onBeforeUnmount, onMounted, ref, watch \} from 'vue'/) assert.match(layoutSource, /import \{ computed, nextTick, onBeforeUnmount, onMounted, ref, watch \} from 'vue'/)
assert.match(layoutSource, /import \{[\s\S]*?\bX\s*\} from '@lucide\/vue'/) assert.match(layoutSource, /import \{[\s\S]*?\bX\s*\} from '@lucide\/vue'/)
assert.match(layoutSource, /import ClientSidebarMenu from '@\/components\/ClientSidebarMenu\.vue'/) assert.match(layoutSource, /import ClientSidebarMenu from '@\/components\/ClientSidebarMenu\.vue'/)
assert.match(layoutSource, /:class="\{ 'mobile-menu-open': mobileMenuOpen \}"/) assert.match(layoutSource, /:class="\{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route\.path === '\/' \}"/)
assert.match(layoutSource, /<button\s+v-if="mobileMenuOpen"[^>]*class="client-sidebar-scrim"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"/s) assert.match(layoutSource, /<button\s+v-if="mobileMenuOpen"[^>]*class="client-sidebar-scrim"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"/s)
assert.match(layoutSource, /<aside\s+ref="sidebarRef"\s+id="client-sidebar"\s+class="client-sidebar"\s+:inert="!desktopViewport && !mobileMenuOpen"\s+:aria-hidden="!desktopViewport && !mobileMenuOpen \? 'true' : undefined"\s*>/) assert.match(layoutSource, /<aside\s+ref="sidebarRef"\s+id="client-sidebar"\s+class="client-sidebar"\s+:inert="!desktopViewport && !mobileMenuOpen"\s+:aria-hidden="!desktopViewport && !mobileMenuOpen \? 'true' : undefined"\s*>/)
assert.doesNotMatch(layoutSource, /<aside[^>]*aria-label=/) assert.doesNotMatch(layoutSource, /<aside[^>]*aria-label=/)
assert.match(layoutSource, /<nav aria-label="客户工作台导航">/) assert.match(layoutSource, /<nav aria-label="客户工作台导航">/)
assert.match(layoutSource, /<div class="client-sidebar-brand">[\s\S]*?<RouterLink class="client-sidebar-brand-link" to="\/" aria-label="返回业务总览" @click="closeMobileMenu">[\s\S]*?alt="柏悦物流"[\s\S]*?客户工作台/s) assert.match(layoutSource, /<div class="client-sidebar-brand">[\s\S]*?<RouterLink class="client-sidebar-brand-link" to="\/" aria-label="返回业务总览" @click="closeMobileMenu">[\s\S]*?alt="柏悦物流"/s)
assert.doesNotMatch(layoutSource, /client-sidebar-brand-copy/)
assert.match(layoutSource, /<button[^>]*ref="sidebarCloseButtonRef"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"[^>]*>\s*<X :size="20" \/>/s) assert.match(layoutSource, /<button[^>]*ref="sidebarCloseButtonRef"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"[^>]*>\s*<X :size="20" \/>/s)
assert.match(layoutSource, /<ClientSidebarMenu\s+:active-path="route\.path"\s+@navigate="closeMobileMenu"\s*\/>/s) assert.match(layoutSource, /<ClientSidebarMenu\s+:active-path="route\.path"\s+@navigate="closeMobileMenu"\s*\/>/s)
assert.match(layoutSource, /<button type="button" class="client-sidebar-logout" @click="handleLogout">[\s\S]*?退出登录/s) assert.match(layoutSource, /<button type="button" class="client-sidebar-logout" @click="handleLogout">[\s\S]*?退出登录/s)
@@ -45,11 +48,13 @@ test('source contract: removes the header and main content from the accessibilit
assert.match(layoutSource, /<main\s+class="client-main"\s+:inert="mobileMenuOpen"\s+:aria-hidden="mobileMenuOpen \? 'true' : undefined"\s*>/) assert.match(layoutSource, /<main\s+class="client-main"\s+:inert="mobileMenuOpen"\s+:aria-hidden="mobileMenuOpen \? 'true' : undefined"\s*>/)
}) })
test('source contract: keeps route context and user identity in the compact header', () => { test('source contract: keeps the prototype greeting and fixed message and profile utilities in the compact header', () => {
assert.match(layoutSource, /const pageTitle = computed\(\(\) => route\.meta\.title \|\| '业务总览'\)/) assert.match(layoutSource, /const pageTitle = computed\(\(\) => route\.meta\.title \|\| '业务总览'\)/)
assert.match(layoutSource, /const pageDescription = computed\(\(\) => route\.meta\.description \|\| ''\)/) assert.doesNotMatch(layoutSource, /const pageDescription/)
assert.match(layoutSource, /<div class="client-header-heading">\s*<h1>\{\{ pageTitle \}\}<\/h1>\s*<p v-if="pageDescription">\{\{ pageDescription \}\}<\/p>/s) assert.match(layoutSource, /<p class="client-header-greeting">Hi, 客户<\/p>/)
assert.match(layoutSource, /<div class="client-user">[\s\S]*\{\{ auth\.user\?\.name \}\}/) assert.match(layoutSource, /<div class="client-user">[\s\S]*\{\{ auth\.user\?\.name \}\}/)
assert.match(layoutSource, /class="client-header-notifications" to="\/notifications" aria-label="打开我的消息"/)
assert.match(layoutSource, /class="client-header-profile"[\s\S]*to="\/account\/profile"[\s\S]*aria-label="打开我的信息"/)
assert.doesNotMatch(layoutSource, /<div class="client-user">[\s\S]*aria-label="退出登录"/) assert.doesNotMatch(layoutSource, /<div class="client-user">[\s\S]*aria-label="退出登录"/)
assert.doesNotMatch(layoutSource, /Building2|tenant-name|tenantName/) assert.doesNotMatch(layoutSource, /Building2|tenant-name|tenantName/)
assert.doesNotMatch(routerSource, /showPageHeading|showTenantName/) assert.doesNotMatch(routerSource, /showPageHeading|showTenantName/)
@@ -58,19 +63,25 @@ test('source contract: keeps route context and user identity in the compact head
test('source contract: renders the complete route breadcrumb before page content', () => { test('source contract: renders the complete route breadcrumb before page content', () => {
assert.match(layoutSource, /import \{ getFirstAccessiblePath, getRouteBreadcrumbs \} from '@\/navigation\/clientNavigation'/) assert.match(layoutSource, /import \{ getFirstAccessiblePath, getRouteBreadcrumbs \} from '@\/navigation\/clientNavigation'/)
assert.match(layoutSource, /const breadcrumbs = computed\(\(\) => getRouteBreadcrumbs\(route\.path, String\(pageTitle\.value\)\)\)/) assert.match(layoutSource, /const breadcrumbs = computed\(\(\) => getRouteBreadcrumbs\(route\.path, String\(pageTitle\.value\)\)\)/)
assert.match(layoutSource, /<nav class="client-breadcrumb" aria-label="页面路径">[\s\S]*?v-for="\(item, index\) in breadcrumbs"[\s\S]*?<RouterLink v-if="item\.path" :to="item\.path">[\s\S]*?<strong v-else aria-current="page">/) assert.match(layoutSource, /<nav v-if="route\.path !== '\/'" class="client-breadcrumb" aria-label="页面路径">[\s\S]*?v-for="\(item, index\) in breadcrumbs"[\s\S]*?<RouterLink v-if="item\.path" :to="item\.path">[\s\S]*?<strong v-else aria-current="page">/)
assert.match(shellStyles, /\.client-breadcrumb \{[^}]*margin: 0 0 14px;/) assert.match(shellStyles, /\.client-breadcrumb \{[^}]*margin: 0 0 14px;/)
}) })
test('source contract: aligns the light top bar beside the prototype-inspired dark sidebar and bounds the mobile header', () => { test('source contract: aligns the blue-tinted prototype shell around a compact sidebar and bounds the mobile header', () => {
assert.match(shellStyles, /\.top-header \{[^}]*inset: 0 0 auto 250px;[^}]*max-width: calc\(100vw - 250px\);[^}]*padding: 0 24px;/) assert.match(shellStyles, /\.top-header \{[^}]*inset: 0 0 auto 224px;[^}]*max-width: calc\(100vw - 224px\);[^}]*padding: 0 24px;/)
assert.match(shellStyles, /\.top-header \{[^}]*background: rgba\(255, 255, 255, \.96\)/) assert.match(shellStyles, /\.top-header \{[^}]*background: rgba\(255, 255, 255, \.98\)/)
assert.match(shellStyles, /\.client-sidebar \{[^}]*inset: 0 auto 0 0;[^}]*width: 250px;[^}]*background: linear-gradient\(180deg, #0b1f3a 0%, #0c2a52 100%\)/) assert.match(shellStyles, /\.client-sidebar \{[^}]*inset: 0 auto 0 0;[^}]*width: 224px;[^}]*border-right: 1px solid #dfe8f3;[^}]*background: linear-gradient\(180deg, #f5f8ff 0%, #edf5fc 100%\)/)
assert.match(shellStyles, /\.client-sidebar-brand \{[^}]*border-bottom: 1px solid rgba\(255, 255, 255, \.09\)/) assert.match(shellStyles, /\.client-sidebar-brand \{[^}]*border-radius: 15px;[^}]*background: linear-gradient\(145deg, #0a2b50, #0b3d6c\)/)
assert.match(shellStyles, /\.client-main \{[^}]*padding: 134px 20px 40px;/) assert.match(shellStyles, /\.client-main \{[^}]*padding: 126px 20px 40px;/)
assert.match(shellStyles, /\.is-dashboard-route \.client-main \{ padding-top: 88px; \}/)
assert.match(globalStyles, /@media \(max-width: 720px\) \{[\s\S]*\.top-header \{ inset: 0;[^}]*padding: 0 14px; \}/) assert.match(globalStyles, /@media \(max-width: 720px\) \{[\s\S]*\.top-header \{ inset: 0;[^}]*padding: 0 14px; \}/)
assert.match(globalStyles, /\.client-header-menu-button \{ display: grid; \}/) assert.match(globalStyles, /\.client-header-menu-button \{ display: grid; \}/)
assert.match(globalStyles, /\.client-header-heading p, \.client-user-copy \{ display: none; \}/) assert.match(globalStyles, /\.client-header-greeting, \.client-user-copy \{ display: none; \}/)
})
test('source contract: keeps the dashboard free of a redundant workspace tab', () => {
assert.match(layoutSource, /<WorkspaceTabs\s+v-if="route\.path !== '\/'"/)
assert.match(layoutSource, /'is-dashboard-route': route\.path === '\/'/)
}) })
test('source contract: closes the mobile menu on route changes and Escape', () => { test('source contract: closes the mobile menu on route changes and Escape', () => {
@@ -99,7 +110,7 @@ test('source contract: locks body scrolling while open and restores it on close
}) })
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => { test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
assert.match(layoutSource, /async function handleLogout\(\) \{\s*try \{/) assert.match(layoutSource, /async function handleLogout\(\) \{\s*const logoutToken = auth.token\s*try \{/)
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/) assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
}) })
@@ -110,7 +121,8 @@ test('source contract: uses a native recursive disclosure list without Element m
assert.match(sidebarMenuSource, /const activeParentKeys = computed\(\(\) => new Set\(getNavigationParentKeys\(visibleNavigation\.value, props\.activePath\)\)\)/) assert.match(sidebarMenuSource, /const activeParentKeys = computed\(\(\) => new Set\(getNavigationParentKeys\(visibleNavigation\.value, props\.activePath\)\)\)/)
assert.match(sidebarMenuSource, /const openedKeys = ref<ReadonlySet<string>>\(new Set\(activeParentKeys\.value\)\)/) assert.match(sidebarMenuSource, /const openedKeys = ref<ReadonlySet<string>>\(new Set\(activeParentKeys\.value\)\)/)
assert.match(sidebarMenuSource, /openedKeys\.value = new Set\(\[\.\.\.openedKeys\.value, \.\.\.activeParentKeys\.value\]\)/) assert.match(sidebarMenuSource, /openedKeys\.value = new Set\(\[\.\.\.openedKeys\.value, \.\.\.activeParentKeys\.value\]\)/)
assert.match(sidebarMenuSource, /if \(activeParentKeys\.value\.has\(key\)\) return/) assert.doesNotMatch(sidebarMenuSource, /if \(activeParentKeys\.value\.has\(key\)\) return/)
assert.match(sidebarMenuSource, /if \(next\.has\(key\)\) next\.delete\(key\)/)
assert.match(sidebarMenuSource, /<ul class="client-nav-menu">/) assert.match(sidebarMenuSource, /<ul class="client-nav-menu">/)
assert.match(sidebarMenuSource, /:active-path="activePath"/) assert.match(sidebarMenuSource, /:active-path="activePath"/)
assert.match(sidebarMenuSource, /:opened-keys="openedKeys"/) assert.match(sidebarMenuSource, /:opened-keys="openedKeys"/)
@@ -138,3 +150,49 @@ test('source contract: routes denied pages to an explicit 403 state', () => {
assert.match(routerSource, /!auth\.hasPermission\(permission\)/) assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/) assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
}) })
function logoutHarness(t) {
const script = layoutSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
const ast = ts.createSourceFile('layout.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
const nodes = ast.statements.filter(node => (ts.isFunctionDeclaration(node) && node.name?.text === 'handleLogout') || (ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes('() => auth.isAuthenticated')))
const code = ts.transpileModule(nodes.map(node => node.getText(ast)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
let rejectLogout, confirm
const remote = new Promise((_, no) => { rejectLogout = no })
const confirmation = new Promise(yes => { confirm = yes })
const calls = [], warnings = []
const auth = vue.reactive({ token: 'A', isAuthenticated: true, logout: () => { calls.push('logout'); auth.token = ''; auth.isAuthenticated = false; return remote } })
const scope = vue.effectScope(); t.after(() => scope.stop())
const handler = scope.run(() => new Function('watch', 'auth', 'workspace', 'unsaved', 'router', 'ElMessageBox', 'ElMessage', code + ';return handleLogout')(vue.watch, auth, { clear: () => calls.push('workspace') }, { hasDirty: false, clear: () => calls.push('unsaved') }, { replace: path => { calls.push(path); return Promise.resolve() } }, { confirm: () => confirmation }, { warning: value => warnings.push(value) }))
return { auth, handler, confirm, rejectLogout, calls, warnings }
}
test('logout navigates before remote completion and late failure cannot affect a new login', async t => {
const h = logoutHarness(t)
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
assert.deepEqual(h.calls, ['logout', 'workspace', 'unsaved', '/login'])
assert.equal(h.auth.isAuthenticated, false)
h.auth.token = 'B'; h.auth.isAuthenticated = true; await vue.nextTick()
h.rejectLogout(new Error('SESSION_CHANGED')); await Promise.resolve(); await vue.nextTick()
assert.equal(h.auth.token, 'B'); assert.equal(h.auth.isAuthenticated, true)
assert.equal(h.calls.filter(item => item === '/login').length, 1)
assert.equal(h.warnings.length, 0)
})
test('cross-tab logout leaves protected route and stale confirmation never logs out a new identity', async t => {
const h = logoutHarness(t)
const clicked = h.handler()
h.auth.token = 'B'; h.confirm(); await clicked
assert.equal(h.calls.length, 0)
h.auth.token = ''; h.auth.isAuthenticated = false; await vue.nextTick()
assert.deepEqual(h.calls, ['workspace', 'unsaved', '/login'])
assert.match(layoutSource, /<div v-if="auth.isAuthenticated" class="client-shell"/)
})
test('remote logout failure reports incomplete server revocation without leaving protected content visible', async t => {
const h = logoutHarness(t)
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
h.rejectLogout(new Error('offline')); await Promise.resolve()
assert.equal(h.auth.isAuthenticated, false)
assert.ok(h.calls.includes('/login'))
assert.deepEqual(h.warnings, ['已退出本页,服务器会话注销未完成'])
})
+24 -13
View File
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue' import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, LogOut, Menu, X } from '@lucide/vue' import { Bell, LogOut, Menu, X } from '@lucide/vue'
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png' import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue' import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
@@ -24,7 +24,6 @@ const notifications = useNotificationsStore()
const workspace = useWorkspaceTabsStore() const workspace = useWorkspaceTabsStore()
const unsaved = useUnsavedWorkStore() const unsaved = useUnsavedWorkStore()
const pageTitle = computed(() => route.meta.title || '业务总览') const pageTitle = computed(() => route.meta.title || '业务总览')
const pageDescription = computed(() => route.meta.description || '')
const breadcrumbs = computed(() => getRouteBreadcrumbs(route.path, String(pageTitle.value))) const breadcrumbs = computed(() => getRouteBreadcrumbs(route.path, String(pageTitle.value)))
const mobileMenuOpen = ref(false) const mobileMenuOpen = ref(false)
const desktopViewport = ref(true) const desktopViewport = ref(true)
@@ -109,6 +108,7 @@ watch(
watch( watch(
() => auth.permissionCodes.join('|'), () => auth.permissionCodes.join('|'),
() => { () => {
if (!auth.isAuthenticated) return
const result = workspace.reconcile(isAllowedTab) const result = workspace.reconcile(isAllowedTab)
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes)) if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
}, },
@@ -120,6 +120,7 @@ watch(
if (authenticated) return if (authenticated) return
workspace.clear() workspace.clear()
unsaved.clear() unsaved.clear()
void router.replace('/login')
}, },
) )
@@ -164,6 +165,7 @@ function handleBeforeUnload(event: BeforeUnloadEvent) {
} }
async function handleLogout() { async function handleLogout() {
const logoutToken = auth.token
try { try {
await ElMessageBox.confirm(unsaved.hasDirty await ElMessageBox.confirm(unsaved.hasDirty
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?' ? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
@@ -177,15 +179,16 @@ async function handleLogout() {
throw error throw error
} }
workspace.clear() if (auth.token !== logoutToken) return
unsaved.clear() void auth.logout().catch(() => {
await auth.logout() if (!auth.isAuthenticated) ElMessage.warning('已退出本页,服务器会话注销未完成')
await router.replace('/login') })
} }
</script> </script>
<template> <template>
<div class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen }"> <div v-if="auth.isAuthenticated" class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined"> <header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
<button <button
ref="menuButtonRef" ref="menuButtonRef"
@@ -198,14 +201,22 @@ async function handleLogout() {
> >
<Menu :size="20" /> <Menu :size="20" />
</button> </button>
<div class="client-header-heading"> <p class="client-header-greeting">Hi, 客户</p>
<h1>{{ pageTitle }}</h1>
<p v-if="pageDescription">{{ pageDescription }}</p>
</div>
<div class="client-user"> <div class="client-user">
<RouterLink v-if="auth.hasPermission('merchant:notification:view')" class="client-header-notifications" to="/notifications" aria-label="打开我的消息"><Bell :size="19" /><span v-if="notifications.unreadCount !== null && notifications.unreadCount > 0" class="client-header-notifications-badge">{{ notifications.unreadCount > 99 ? '99+' : notifications.unreadCount }}</span></RouterLink> <RouterLink v-if="auth.hasPermission('merchant:notification:view')" class="client-header-notifications" to="/notifications" aria-label="打开我的消息"><Bell :size="19" /><span v-if="notifications.unreadCount !== null && notifications.unreadCount > 0" class="client-header-notifications-badge">{{ notifications.unreadCount > 99 ? '99+' : notifications.unreadCount }}</span></RouterLink>
<RouterLink
v-if="auth.hasPermission('account:profile:view')"
class="client-header-profile"
to="/account/profile"
aria-label="打开我的信息"
>
<span class="client-avatar">{{ auth.user?.name.slice(0, 1) }}</span> <span class="client-avatar">{{ auth.user?.name.slice(0, 1) }}</span>
<span class="client-user-copy"><strong>{{ auth.user?.name }}</strong><small>{{ auth.user?.roles.join('、') }}</small></span> <span class="client-user-copy"><strong>{{ auth.user?.name }}</strong><small>{{ auth.user?.roles.join('、') }}</small></span>
</RouterLink>
<template v-else>
<span class="client-avatar">{{ auth.user?.name.slice(0, 1) }}</span>
<span class="client-user-copy"><strong>{{ auth.user?.name }}</strong><small>{{ auth.user?.roles.join('、') }}</small></span>
</template>
</div> </div>
</header> </header>
@@ -227,7 +238,6 @@ async function handleLogout() {
<div class="client-sidebar-brand"> <div class="client-sidebar-brand">
<RouterLink class="client-sidebar-brand-link" to="/" aria-label="返回业务总览" @click="closeMobileMenu"> <RouterLink class="client-sidebar-brand-link" to="/" aria-label="返回业务总览" @click="closeMobileMenu">
<img class="client-sidebar-brand-logo" :src="baiyueLogoDark" alt="柏悦物流" /> <img class="client-sidebar-brand-logo" :src="baiyueLogoDark" alt="柏悦物流" />
<span class="client-sidebar-brand-copy"><small>客户工作台</small></span>
</RouterLink> </RouterLink>
<button <button
ref="sidebarCloseButtonRef" ref="sidebarCloseButtonRef"
@@ -251,6 +261,7 @@ async function handleLogout() {
</aside> </aside>
<WorkspaceTabs <WorkspaceTabs
v-if="route.path !== '/'"
:inert="mobileMenuOpen" :inert="mobileMenuOpen"
:aria-hidden="mobileMenuOpen ? 'true' : undefined" :aria-hidden="mobileMenuOpen ? 'true' : undefined"
/> />
@@ -260,7 +271,7 @@ async function handleLogout() {
:inert="mobileMenuOpen" :inert="mobileMenuOpen"
:aria-hidden="mobileMenuOpen ? 'true' : undefined" :aria-hidden="mobileMenuOpen ? 'true' : undefined"
> >
<nav class="client-breadcrumb" aria-label="页面路径"> <nav v-if="route.path !== '/'" class="client-breadcrumb" aria-label="页面路径">
<template v-for="(item, index) in breadcrumbs" :key="`${item.title}-${index}`"> <template v-for="(item, index) in breadcrumbs" :key="`${item.title}-${index}`">
<span v-if="index" aria-hidden="true">/</span> <span v-if="index" aria-hidden="true">/</span>
<RouterLink v-if="item.path" :to="item.path">{{ item.title }}</RouterLink> <RouterLink v-if="item.path" :to="item.path">{{ item.title }}</RouterLink>
+3
View File
@@ -6,9 +6,12 @@ import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn' import zhCn from 'element-plus/es/locale/lang/zh-cn'
import App from './App.vue' import App from './App.vue'
import router from './router' import router from './router'
import { installStaticAssetRecovery } from './core/staticAssetRecovery'
import 'element-plus/es/components/message/style/css' import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css' import 'element-plus/es/components/message-box/style/css'
import './styles/index.css' import './styles/index.css'
installStaticAssetRecovery(router)
const app = createApp({ render: () => h(ElConfigProvider, { locale: zhCn }, { default: () => h(App) }) }) const app = createApp({ render: () => h(ElConfigProvider, { locale: zhCn }, { default: () => h(App) }) })
app.use(createPinia()).use(router).mount('#app') app.use(createPinia()).use(router).mount('#app')
+26
View File
@@ -0,0 +1,26 @@
# Client 个人资料模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/account/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
- 只有 `views/AccountProfileView.vue`、`utils/accountProfile.ts`;路由 `account/profile`。
- 后端:个人资料归 `iam/`(`PersonalProfileService.java`),登录手机号变更经 `auth/` 同步并撤销会话。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 个人资料查看与修改 | `views/AccountProfileView.vue`;`account/profile` | `../tenant-management/api/merchantIam.ts`;`iam/` |
| 表单校验与展示映射 | `utils/accountProfile.ts` | 服务端字段 |
## 关键边界
- 个人资料只改本人信息;企业资料(含 `contactPhone`)归 `../tenant-management/`,两处不互相回填。
- 登录手机号修改由 IAM/Auth 处理并撤销该账号现有会话,前端不自行清理 Token。
- 敏感字段(证件号、密码)不在页面持久化,也不写入日志或快照。
- 保存需要明确成功/失败反馈,失败保留已填内容。
## 验证
- 定向:`pnpm test src/modules/account/<目标测试>`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+30
View File
@@ -0,0 +1,30 @@
# Client 登录与注册模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/auth/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
- 页面:`views/LoginView.vue`、`views/RegisterView.vue`、`views/LegalDocumentView.vue`(`/login`、`/register`、`/legal/*`);会话状态在 `store/auth.ts`,请求在 `api/auth.ts`。
- 后端:登录与 Token 归 `auth/`,注册与资质归 `iam/` + `file/`。
## 页面与入口
| 目标 | 页面/入口 | API 与后端 |
|---|---|---|
| 登录、记住账号 | `views/LoginView.vue` | `api/auth.ts`、`store/auth.ts`;`auth/` |
| 企业注册与资质上传 | `views/RegisterView.vue` | `api/auth.ts`;`iam/`、`file/` |
| 用户协议与隐私政策 | `views/LegalDocumentView.vue`、`legalDocuments.ts` | 静态文案 |
| 认证壳层与布局 | `components/AuthShell.vue` | — |
| 令牌解析与刷新 | `store/auth.ts`、`utils/jwt.ts` | `../../api/http.ts`、`../../api/session.ts` |
## 关键边界
- 页面不拼 `Authorization`、不自行持久化密码;Access/Refresh Token 只在 `store/auth.ts` 与 `src/api/session.ts` 编排。
- 注册时登录手机号同时初始化公司联系电话,注册完成后两者独立维护;企业资料只改 `contactPhone`。
- “记住账号”只保存登录 ID,不改变 Token 的持久化与续期策略。
- 注册必填资质仅营业执照与统一社会信用代码,法人身份证选填;上传成功不等于审核通过。
- 并发或跨标签页 401 共用一次刷新,每个原请求最多重放一次。
## 验证
- 定向:`pnpm test src/modules/auth/<目标测试>`;登录或注册字段变化同时核对 `auth/`、`iam/` 合同。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+3 -3
View File
@@ -1,4 +1,4 @@
import { apiRequest } from '@/api/http' import { apiRequest, revokeCapturedSession } from '@/api/http'
import type { TokenPair } from '@/api/session' import type { TokenPair } from '@/api/session'
export interface RegisterMerchantRequest { export interface RegisterMerchantRequest {
@@ -35,8 +35,8 @@ export function registerMerchant(payload: RegisterMerchantRequest) {
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload }) return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
} }
export function logoutMerchant(refreshToken: string) { export function logoutMerchant(accessToken: string, refreshToken: string) {
return apiRequest<void>({ method: 'POST', url: '/auth/logout', data: { refreshToken } }) return revokeCapturedSession(accessToken, refreshToken)
} }
export function changeCurrentPassword(oldPassword: string, newPassword: string) { export function changeCurrentPassword(oldPassword: string, newPassword: string) {
+103 -97
View File
@@ -61,18 +61,34 @@ export const useAuthStore = defineStore('client-auth', () => {
const permissionCodes = ref<string[]>([]) const permissionCodes = ref<string[]>([])
const sessionRestored = ref(false) const sessionRestored = ref(false)
let logoutRequest: { accessToken: string; refreshToken: string; promise: Promise<void> } | undefined
let generation = 0
let contextRequest: { generation: number; promise: Promise<void> } | undefined
let restoreTimer: ReturnType<typeof setTimeout> | undefined
function identity(value: MerchantJwtPayload | null) {
return value ? JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type]) : ''
}
function applyToken(accessToken: string) { function applyToken(accessToken: string) {
const decoded = decodeMerchantToken(accessToken) const decoded = decodeMerchantToken(accessToken)
const changedIdentity = identity(decoded) !== identity(payload.value)
if (accessToken === token.value && payload.value && !changedIdentity) return
generation++
if (changedIdentity) {
user.value = null
profile.value = { ...emptyProfile }
permissionCodes.value = mapPermissions()
}
payload.value = decoded payload.value = decoded
token.value = accessToken token.value = accessToken
user.value = currentUser(decoded, user.value?.tenantName) user.value = currentUser(decoded, user.value?.tenantName)
profile.value.username = decoded.username profile.value.username = decoded.username
profile.value.realName = decoded.username sessionRestored.value = false
permissionCodes.value = mapPermissions()
} }
function clearSession() { function resetLocalSession() {
clearSessionTokens() generation++
token.value = '' token.value = ''
payload.value = null payload.value = null
user.value = null user.value = null
@@ -81,137 +97,123 @@ export const useAuthStore = defineStore('client-auth', () => {
sessionRestored.value = true sessionRestored.value = true
} }
function clearSession() {
clearSessionTokens()
resetLocalSession()
}
function applyStoredSession() { function applyStoredSession() {
const storedToken = getAccessToken() const storedToken = getAccessToken()
if (!storedToken) { if (!storedToken) {
token.value = '' resetLocalSession()
payload.value = null
user.value = null
permissionCodes.value = []
profile.value = { ...emptyProfile }
sessionRestored.value = true
return return
} }
try { try {
applyToken(storedToken) applyToken(storedToken)
sessionRestored.value = false
} catch {
clearSession()
}
}
if (token.value) {
try {
applyToken(token.value)
} catch (error) { } catch (error) {
if (!(error instanceof MerchantTokenExpiredError && getRefreshToken())) clearSession() resetLocalSession()
if (error instanceof MerchantTokenExpiredError && getRefreshToken()) sessionRestored.value = false
} }
} }
applyStoredSession()
const isAuthenticated = computed(() => Boolean(token.value && payload.value)) const isAuthenticated = computed(() => Boolean(token.value && payload.value))
async function loadSessionContext() {
if (!payload.value) return
const currentPermissionCodes = await getCurrentMerchantPermissionCodes()
const currentAccessToken = getAccessToken()
if (currentAccessToken && currentAccessToken !== token.value) applyToken(currentAccessToken)
permissionCodes.value = mapPermissions(currentPermissionCodes)
const [tenant, personalProfile] = await Promise.all([
getTenantProfile(),
getMerchantPersonalProfile(),
])
user.value = currentUser(payload.value, tenant.tenantName)
profile.value = {
...profile.value,
realName: personalProfile.displayName || payload.value.username,
phone: personalProfile.phone || '',
email: personalProfile.email || '',
tenantName: tenant.tenantName,
}
}
async function restoreSession() { async function restoreSession() {
if (sessionRestored.value) return if (sessionRestored.value) return
if (contextRequest?.generation === generation) return contextRequest.promise
let requestGeneration = generation
let requestAccessToken = getAccessToken()
const isCurrent = () => requestGeneration === generation && getAccessToken() === requestAccessToken
const promise = (async () => {
try {
if (!isAuthenticated.value) { if (!isAuthenticated.value) {
if (!getRefreshToken()) { if (!getRefreshToken()) return
sessionRestored.value = true const refreshedToken = await refreshAuthenticatedSession()
return if (requestGeneration !== generation) return restoreSession()
applyToken(refreshedToken)
requestAccessToken = refreshedToken
requestGeneration = generation
if (contextRequest) contextRequest.generation = generation
} }
try { const requestPayload = payload.value
applyToken(await refreshAuthenticatedSession()) if (!requestPayload) return
const [codes, tenant, personalProfile] = await Promise.all([
getCurrentMerchantPermissionCodes(), getTenantProfile(), getMerchantPersonalProfile(),
])
if (!isCurrent()) {
applyStoredSession()
return restoreSession()
}
permissionCodes.value = mapPermissions(codes)
user.value = currentUser(requestPayload, tenant.tenantName)
profile.value = {
username: requestPayload.username,
realName: personalProfile.displayName || requestPayload.username,
phone: personalProfile.phone || '', email: personalProfile.email || '', tenantName: tenant.tenantName,
}
sessionRestored.value = true
} catch (error) { } catch (error) {
if (!isCurrent()) return
sessionRestored.value = false
if (isExpiredSessionError(error)) { if (isExpiredSessionError(error)) {
clearSession() clearSession()
throw error throw error
} }
sessionRestored.value = true }
return })()
contextRequest = { generation: requestGeneration, promise }
try { await promise } finally {
if (contextRequest?.promise === promise) contextRequest = undefined
} }
} }
try {
await loadSessionContext() function synchronizeSession() {
} catch (error) { // Identity changes and logout revoke local rights immediately. Coalesce pair writes
if (isExpiredSessionError(error)) { // before loading the new context; same-identity rotation retains confirmed rights.
clearSession() applyStoredSession()
throw error if (restoreTimer) clearTimeout(restoreTimer)
} restoreTimer = setTimeout(() => {
sessionRestored.value = true restoreTimer = undefined
return void restoreSession().catch(() => {})
} }, 0)
sessionRestored.value = true
} }
async function login(loginId: string, password: string, remember = false) { async function login(loginId: string, password: string, remember = false) {
const attempt = ++generation
const tokens = await loginMerchant(loginId, password) const tokens = await loginMerchant(loginId, password)
const decoded = decodeMerchantToken(tokens.accessToken) if (attempt !== generation) return
decodeMerchantToken(tokens.accessToken)
persistTokenPair(tokens) persistTokenPair(tokens)
persistRememberedLoginId(loginId, remember) persistRememberedLoginId(loginId, remember)
token.value = tokens.accessToken applyToken(tokens.accessToken)
payload.value = decoded await restoreSession()
user.value = currentUser(decoded)
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
permissionCodes.value = mapPermissions()
sessionRestored.value = false
try {
await loadSessionContext()
sessionRestored.value = true
} catch (error) {
if (isExpiredSessionError(error)) {
clearSession()
throw error
}
sessionRestored.value = true
}
} }
async function acceptImpersonationCode(code: string) { async function acceptImpersonationCode(code: string) {
const attempt = ++generation
const exchanged = await exchangeImpersonationCode(code) const exchanged = await exchangeImpersonationCode(code)
const decoded = decodeMerchantToken(exchanged.accessToken) if (attempt !== generation) return
decodeMerchantToken(exchanged.accessToken)
persistTemporaryAccessToken(exchanged.accessToken) persistTemporaryAccessToken(exchanged.accessToken)
token.value = exchanged.accessToken applyToken(exchanged.accessToken)
payload.value = decoded await restoreSession()
user.value = currentUser(decoded)
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
permissionCodes.value = mapPermissions()
sessionRestored.value = false
try {
await loadSessionContext()
} catch (error) {
if (isExpiredSessionError(error)) {
clearSession()
throw error
}
}
sessionRestored.value = true
} }
async function logout() { function logout() {
const accessToken = getAccessToken()
const refreshToken = getRefreshToken() const refreshToken = getRefreshToken()
try { if (logoutRequest && ((!accessToken && !refreshToken)
if (refreshToken) await logoutMerchant(refreshToken) || (logoutRequest.accessToken === accessToken && logoutRequest.refreshToken === refreshToken))) return logoutRequest.promise
} finally { const pending = accessToken || refreshToken
? logoutMerchant(accessToken, refreshToken)
: Promise.resolve()
clearSession() clearSession()
} const request = { accessToken, refreshToken, promise: pending.finally(() => {
if (logoutRequest === request) logoutRequest = undefined
}) }
logoutRequest = request
return request.promise
} }
function hasPermission(permission?: string) { function hasPermission(permission?: string) {
@@ -224,10 +226,13 @@ export const useAuthStore = defineStore('client-auth', () => {
} }
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) { async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
const requestGeneration = generation
const requestToken = getAccessToken()
const updated = await updateMerchantPersonalProfile({ const updated = await updateMerchantPersonalProfile({
displayName: next.realName.trim(), displayName: next.realName.trim(),
email: next.email.trim(), email: next.email.trim(),
}) })
if (requestGeneration !== generation || requestToken !== getAccessToken()) return
updateProfile({ updateProfile({
realName: updated.displayName, realName: updated.displayName,
phone: updated.phone || '', phone: updated.phone || '',
@@ -236,8 +241,9 @@ export const useAuthStore = defineStore('client-auth', () => {
} }
window.addEventListener('cc-client-session-expired', clearSession) window.addEventListener('cc-client-session-expired', clearSession)
window.addEventListener('cc-client-session-updated', synchronizeSession)
window.addEventListener('storage', (event) => { window.addEventListener('storage', (event) => {
if (event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token') applyStoredSession() if (event.storageArea === localStorage && (event.key === null || event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token')) synchronizeSession()
}) })
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile } return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
+168
View File
@@ -0,0 +1,168 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import * as pinia from 'pinia'
function compile(path, dependencies = {}) {
const code = ts.transpileModule(readFileSync(new URL(path, import.meta.url), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText
const exports = {}
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
return exports
}
function storage() {
const values = new Map()
return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key) }
}
function token(user = 1, tenant = 1, membership = 1, nonce = 'a') {
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, username: `user-${user}`, app_code: 'MERCHANT', exp: 4102444800, nonce })).toString('base64url')}.test`
}
const flush = () => new Promise(resolve => setTimeout(resolve, 10))
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
function harness(t, expired = false) {
globalThis.localStorage = storage(); globalThis.sessionStorage = storage()
const listeners = new Map()
globalThis.window = { addEventListener: (name, fn) => listeners.set(name, fn) }
const session = compile('../../../api/session.ts')
const initial = expired ? `test.${Buffer.from(JSON.stringify({ user_id: 1, tenant_id: 1, membership_id: 1, username: 'user-1', app_code: 'MERCHANT', exp: 1 })).toString('base64url')}.test` : token()
session.persistTokenPair({ accessToken: initial, refreshToken: 'refresh-a' })
let reads = 0
const behavior = { permissions: async () => ['edit'], tenant: async () => ({ tenantName: 'company' }) }
class ApiError extends Error { constructor(status) { super('failed'); this.status = status } }
const module = compile('./auth.ts', {
vue, pinia, '@/api/session': session,
'@/modules/auth/api/auth': { logoutMerchant: async (access, refresh) => behavior.logout?.(refresh, access) },
'@/modules/auth/utils/jwt': compile('../utils/jwt.ts'),
'@/api/http': { ApiError, refreshAuthenticatedSession: async () => {
session.persistTokenPair({ accessToken: token(1, 1, 1, 'refreshed'), refreshToken: 'refresh-new' })
listeners.get('cc-client-session-updated')()
return session.getAccessToken()
} },
'@/modules/tenant-management/public': {
FRONTEND_TO_MERCHANT_PERMISSION_CODES: { 'order:first-leg:edit': 'edit' },
hasMappedMerchantPermission: (_, codes) => codes.has('edit'),
getCurrentMerchantPermissionCodes: () => { reads++; return behavior.permissions() },
getTenantProfile: () => behavior.tenant(), getMerchantPersonalProfile: async () => ({}),
},
})
const context = pinia.createPinia(); pinia.setActivePinia(context)
t.after(async () => { await flush(); pinia.disposePinia(context) })
const auth = module.useAuthStore()
const event = key => listeners.get('storage')({ key, storageArea: localStorage })
function rotate(nextToken = token(1, 1, 1, 'b')) {
session.persistTokenPair({ accessToken: nextToken, refreshToken: 'refresh-b' })
event(session.ACCESS_TOKEN_KEY); event(session.REFRESH_TOKEN_KEY)
}
return { auth, session, event, rotate, behavior, listeners, ApiError, reads: () => reads }
}
test('pair storage rotation retains same-identity rights and automatically reloads once without navigation', async t => {
const h = harness(t); await h.auth.restoreSession()
h.behavior.permissions = async () => []
h.rotate()
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
assert.equal(h.auth.sessionRestored, false)
await flush()
assert.equal(h.auth.sessionRestored, true)
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false, 'new server rights replace the retained snapshot')
assert.equal(h.reads(), 2)
h.listeners.get('cc-client-session-updated')()
await flush()
assert.equal(h.reads(), 2, 'already applied token does not reload twice')
})
test('startup expired-token refresh waits for restored rights even when local rotation emits an event', async t => {
const h = harness(t, true)
await h.auth.restoreSession()
assert.equal(h.auth.isAuthenticated, true)
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
assert.equal(h.auth.sessionRestored, true)
assert.equal(h.reads(), 1)
})
test('logout storage event immediately clears rights and late context cannot restore them', async t => {
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
const pending = h.auth.restoreSession()
h.session.clearSessionTokens(); h.event(h.session.ACCESS_TOKEN_KEY)
assert.equal(h.auth.isAuthenticated, false)
assert.deepEqual(h.auth.permissionCodes, [])
old.resolve(['edit']); await pending; await flush()
assert.equal(h.auth.user, null)
assert.deepEqual(h.auth.permissionCodes, [])
})
test('account, customer and membership switches revoke rights immediately and reject stale request results', async t => {
const h = harness(t); await h.auth.restoreSession()
const old = deferred(); h.behavior.permissions = () => old.promise
h.rotate(); await flush()
h.behavior.permissions = async () => []
h.rotate(token(2, 2, 2, 'new'))
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
assert.equal(h.auth.user.id, '2')
await flush(); old.resolve(['edit']); await flush()
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
assert.equal(h.auth.user.id, '2')
h.behavior.permissions = async () => ['edit']; h.rotate(token(2, 3, 3, 'next')); await flush()
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
h.rotate(token(2, 3, 4, 'membership'))
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
})
test('context failure is not marked restored and explicit retry coalesces concurrent callers', async t => {
const h = harness(t)
h.behavior.permissions = async () => { throw new Error('offline') }
await h.auth.restoreSession()
assert.equal(h.auth.sessionRestored, false)
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
const pending = deferred(); h.behavior.permissions = () => pending.promise
const first = h.auth.restoreSession(), second = h.auth.restoreSession()
assert.equal(h.reads(), 2)
pending.resolve(['edit']); await Promise.all([first, second])
assert.equal(h.auth.sessionRestored, true)
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
})
test('stale unauthorized context response cannot clear a newer account', async t => {
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
const pending = h.auth.restoreSession()
h.behavior.permissions = async () => []
h.rotate(token(2, 2, 2)); await flush()
old.reject(new h.ApiError(401)); await pending
assert.equal(h.auth.user.id, '2')
assert.equal(h.auth.isAuthenticated, true)
assert.equal(h.auth.sessionRestored, true)
})
test('store logout clears immediately and late revocation failure preserves a later cross-tab login', async t => {
const h = harness(t); await h.auth.restoreSession()
const remote = deferred(); let sentRefresh
h.behavior.logout = refresh => { sentRefresh = refresh; return remote.promise }
const pending = h.auth.logout()
const rejected = assert.rejects(pending, /offline/)
assert.equal(sentRefresh, 'refresh-a')
assert.equal(h.auth.isAuthenticated, false)
assert.equal(h.session.getAccessToken(), '')
h.rotate(token(2, 2, 2)); await flush()
remote.reject(new Error('offline')); await rejected
assert.equal(h.auth.user.id, '2')
assert.equal(h.auth.isAuthenticated, true)
assert.equal(h.session.getRefreshToken(), 'refresh-b')
})
test('duplicate logout joins captured pair revocation and does not send again',async t=>{
const h=harness(t);const remote=deferred();let count=0,sent
h.behavior.logout=(refresh,access)=>{count++;sent={refresh,access};return remote.promise}
const a=h.auth.logout(),b=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(sent.access,token());assert.equal(sent.refresh,'refresh-a');assert.equal(count,1);remote.resolve();await Promise.all([a,b])
})
test('B logout during A pending revokes B; A finally cannot release B deduplication',async t=>{
const h=harness(t);const a=deferred(),b=deferred(),calls=[]
h.behavior.logout=(refresh,access)=>{calls.push({refresh,access});return calls.length===1?a.promise:b.promise}
const leavingA=h.auth.logout();h.rotate(token(2,2,2));await flush();assert.equal(h.auth.isAuthenticated,true)
const leavingB=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(h.session.getAccessToken(),'');assert.equal(calls.length,2);assert.equal(calls[1].access,token(2,2,2))
a.resolve();await leavingA;const duplicateB=h.auth.logout();assert.equal(calls.length,2);let duplicateFinished=false;void duplicateB.then(()=>{duplicateFinished=true});await flush();assert.equal(duplicateFinished,false);b.resolve();await Promise.all([leavingB,duplicateB])
})
+5 -3
View File
@@ -102,7 +102,8 @@ test('opens complete service and privacy documents from registration', () => {
test('uses real auth endpoints and single-flight refresh handling', () => { test('uses real auth endpoints and single-flight refresh handling', () => {
assert.match(authApiSource, /\/auth\/login/) assert.match(authApiSource, /\/auth\/login/)
assert.match(authApiSource, /\/auth\/register/) assert.match(authApiSource, /\/auth\/register/)
assert.match(authApiSource, /\/auth\/logout/) assert.match(authApiSource, /revokeCapturedSession\(accessToken, refreshToken\)/)
assert.match(httpSource, /\/auth\/logout/)
assert.match(httpSource, /refreshPromise/) assert.match(httpSource, /refreshPromise/)
assert.match(httpSource, /\/auth\/refresh/) assert.match(httpSource, /\/auth\/refresh/)
assert.match(httpSource, /persistTokenPair\(tokens\)/) assert.match(httpSource, /persistTokenPair\(tokens\)/)
@@ -117,7 +118,8 @@ test('uses real auth endpoints and single-flight refresh handling', () => {
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/) assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
assert.match(authStoreSource, /decodeMerchantToken/) assert.match(authStoreSource, /decodeMerchantToken/)
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/) assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
assert.match(authStoreSource, /applyToken\(await refreshAuthenticatedSession\(\)\)/) assert.match(authStoreSource, /const refreshedToken = await refreshAuthenticatedSession\(\)/)
assert.match(authStoreSource, /applyToken\(refreshedToken\)/)
assert.doesNotMatch(authStoreSource, /mock-client:/) assert.doesNotMatch(authStoreSource, /mock-client:/)
}) })
@@ -152,7 +154,7 @@ test('shows a forced re-login notice after login identifiers change', () => {
test('keeps a valid local session during temporary context and refresh outages', () => { test('keeps a valid local session during temporary context and refresh outages', () => {
assert.match(authStoreSource, /function isExpiredSessionError/) assert.match(authStoreSource, /function isExpiredSessionError/)
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/) assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
assert.match(authStoreSource, /sessionRestored\.value = true\s+return/) assert.match(authStoreSource, /if \(!isCurrent\(\)\) return\s+sessionRestored\.value = false/)
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/) assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/) assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
}) })
+30
View File
@@ -0,0 +1,30 @@
# Client 跨境业务模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/cross-border/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,业务细则见 `../../../docs/business-index.md`。
- 三条业务线共用本模块:`procurement`(海外采购)、`domestic-trucking`(本土卡车)、`pallet-shipping`(美本土散板);每条都是独立列表 + 建单 + 详情路由。
- 后端只查 `lastleg-service/` 的 `procurement/`、`trucking/`、`looseboard/`;纯页面与文案不读后端。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 海外采购列表、建单与详情 | `views/ProcurementView.vue`、`components/ProcurementDetailPanel.vue`;`cross-border/procurement`、`.../create`、`.../:orderNo/detail` | `api/procurement.ts`、`procurementSubmission.ts`、`procurementPresentation.ts`;`lastleg-service/procurement/` |
| 本土卡车列表、建单与详情 | `views/DomesticTruckingView.vue`、`components/TransportDemandForm.vue`;`cross-border/domestic-trucking`、`.../create`、`.../:orderNo/detail` | `api/businessOrders.ts`、`transportDemandForm.ts`;`lastleg-service/trucking/` |
| 美本土散板列表、建单与详情 | `views/PalletShippingView.vue`;`cross-border/pallet-shipping`、`.../create`、`.../:orderNo/detail` | `api/businessOrders.ts`;`lastleg-service/looseboard/` |
| 通用业务单展示与车次安排 | `components/BusinessOrdersView.vue`、`fleetArrangement.ts` | `api/businessOrders.ts`;`lastleg-service/fleet/trip/` |
| 柜型与规格换算 | `containerSpecifications.ts` | 本地换算,服务端复核 |
## 关键边界
- 三条线都是客户自助下单,提交后由平台审核;客户侧不提供审核、改价或内部作业动作。
- 客户与仓库范围只取服务端当前租户上下文,不从前端参数推断;跨客户查询一律拒绝。
- 提交需要幂等键、提交中状态与可恢复失败反馈;失败保留已填内容。
- 海外采购按 `baiyue-firstleg/lastleg-service/docs/procurement-workflow.md`(工作区路径)的七状态流程执行;详情展示分批收货、出库与费用,待客户确认时由当前客户确认,不恢复旧装箱与两段核费节点。
- 页面承载方式按已确认原型:列表 + 独立建单/详情路由,不改为弹框或抽屉。
## 验证
- 定向:`pnpm test src/modules/cross-border/<目标测试>`;接口或类型变化同时运行 `pnpm typecheck`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
@@ -0,0 +1,64 @@
# 本土卡车字段调整核对
## 2026-11-03 运输照片回显
| 页面 | 承载与依据 | 验收 |
|---|---|---|
| 美本土散板、本土卡车详情 | 按本轮用户截图及文字要求,在订单信息下显示取货照片、派送照片;缩略图横向换行、点击放大,不显示图片名称,不提供客户上传或删除操作 | 定向测试及类型检查通过;待人工截图确认 |
## 2026-11-02 用户截图问题修复
| 页面 | 操作及承载 | 截图依据与调整 | 验收 |
|---|---|---|---|
| 美本土散板 | 既有独立详情页 | 本轮第1张截图:地址跨两列时由网格紧密填补空位,备注占满一行,保留所有字段 | 定向测试与类型检查通过;待人工1920×1080、100%截图确认 |
| 美国本土卡车 | 既有独立新增页 | 本轮第6、10张截图与文字确认:双地址必填;标题右侧补返回列表,沿用Client新增页按钮外观 | 定向测试与类型检查通过;待人工截图确认 |
| 美国本土卡车 | 列表、详情及状态筛选 | 本轮第7、11张截图:补齐当前正式状态中文文案,DISPATCHED显示待取货 | 当前全部正式状态的定向测试通过 |
依据:用户提供的下单页截图 `codex-clipboard-c458c2e1-e9a8-4726-a8cd-4581e5e7102f.png` 及本轮字段、必填和时分确认。当前需求规则见 `docs/海外仓业务/README.md`“美国本土卡独立下单”。
| 页面 | 操作 | 依据及承载 | 当前调整 | 验收 |
|---|---|---|---|---|
| 美国本土卡 | 新增 | 用户截图:独立页面、单列表单、取消和提交按钮 | 保留容器、按钮;按确认删除字段,新增车型及两端联系人和时间 | 自动验证与人工视觉验收分开;待人工截图确认 |
| 美国本土卡 | 列表 | 现有 `BusinessOrdersView.vue` 的独立列表与左侧操作列 | 对应列展示车型和取送时间 | 待人工截图确认 |
| 美国本土卡 | 详情 | 现有独立详情路由及键值网格 | 展示保存的两端联系信息、车型和取送时间;加宽长字段标签 | 待人工截图确认 |
本节记录本土卡车调整;散板最新范围见下节。无新增审核、删除或附件操作。
## 本土散板简化需求合同
当前字段规则见 `docs/海外仓业务/README.md`“本土散板简化下单”;依据用户提供的 Admin 简化原型及本轮同步消费者确认,不改变客户认证范围。
| 页面 | 操作 | 承载与范围 | 验收 |
|---|---|---|---|
| 美本土散板 | 新增 | 保持现有独立路由和表单容器;同步商品、预计托数、四项联系信息及必填的当地取送时间;删除运输方式、柜型和下单安排项 | 自动测试与人工视觉分开;待人工截图确认 |
| 美本土散板 | 列表、详情 | 保持现有独立路由;展示同一保存值和真实承运安排,不访问运力池 | 待人工截图确认 |
## Admin / Client 统一运输下单表单(2026-10-19)
依据:当前对话明确要求“最多 Admin 添加客户选项,Client 从登录客户下单”,覆盖此前两端独立排版结论。保留应用壳层、正式路由及权限;业务表单统一为同一字段清单、排列、控件、默认值、校验及提交转换。
| 页面 | 操作 | 承载与现有依据 | 本轮统一结论 | 验收 |
|---|---|---|---|---|
| 本土卡车 | Client 新增、Admin 新增/编辑 | 既有独立页面;原客户端截图及当前统一确认 | 运输信息双列,车辆必选;两端联系人/电话及详细地址左右对应;货物件重体;费用币种与两个分钟时间;备注;底部取消/提交。Admin 新增前置客户选择 | 自动合同及行为测试;待人工 1920×1080、100% 截图 |
| 本土散板 | Client 新增、Admin 新增/编辑 | 既有独立页面;当前统一确认 | 与卡车共用表单;保留商品名、预计托数和件重体,移除车型;其余相同。Admin 新增前置客户选择 | 同上 |
| 两类业务 | 列表、详情、承运安排 | 既有独立路由及只读承运摘要 | 本轮不改变承载;Client 不新增编辑路由 | 既有行为回归 |
统一表单组件和转换逻辑各自位于应用内部,运行时不跨应用引用。两端业务组件源码一致性另作定向检查;下单数据不允许混入客户标识,Admin 在 API 参数显式选择客户,Client 由认证会话确定客户。
2026-10-29 用户截图调整:采购待确认支持确认或必填原因驳回;四张实收/库存数量卡片置顶,商品及收件信息置底。本土卡车数量改托数,托数及预算须为正数。采购及卡车先等待Finance余额/授信冻结成功,再以同一幂等键建单;不足保留表单并提示原因。自动检查与人工视觉验收分别记录;待人工1920×1080、100%截图确认。
## 海外采购下单与结果处理(2026-10-30)
依据:当前对话的下单页与详情页截图,以及用户明确要求“商品链接下单必填”“下单成功返回列表”“驳回/确认移至列表,弹窗显示照片和采购数量,驳回必填理由”“确认后两个按钮隐藏”。
| 页面 | 操作及承载 | 调整 | 验收 |
|---|---|---|---|
| 海外采购下单 | 既有独立页面 | 商品链接标记必填并校验非空及有效 HTTP/HTTPS 地址;成功返回采购列表,失败保留表单 | 定向自动测试;待人工截图确认 |
| 海外采购列表 | 待客户确认行的操作列 | 提供详情、驳回、确认采购结果;确认/驳回成功刷新列表,离开待客户确认状态后隐藏两项动作 | 状态与权限自动测试;待人工截图确认 |
| 采购结果确认/驳回 | 居中弹窗 | 显示单号、商品、采购数量、累计收货、逐批数量与可放大的收货照片;驳回原因必填,最多1000字;失败保留内容供重试 | 定向自动测试;待人工1920×1080、100%截图确认 |
| 海外采购详情 | 既有独立页面 | 移除结果确认与驳回按钮,保留详情和刷新 | 源码合同核对;待人工截图确认 |
2026-10-30 照片布局按用户截图反馈收紧:收货批次按横向三列排列,照片缩略图为112×84,同批照片横向排列,超出可横向滚动;保留批次数量、时间和点击放大预览。待人工截图确认。
+94 -77
View File
@@ -1,4 +1,4 @@
import { overseasApiRequest } from '@/api/overseasHttp' import { apiRequest, apiBlobRequest } from '@/api/http'
export interface PageResult<T> { export interface PageResult<T> {
records: T[] records: T[]
@@ -8,7 +8,7 @@ export interface PageResult<T> {
pages: number pages: number
} }
export type CrossBorderBusinessKind = 'procurement' | 'trucking' | 'looseboard' export type CrossBorderBusinessKind = 'trucking' | 'looseboard'
export interface BusinessOrderQuery { export interface BusinessOrderQuery {
page: number page: number
@@ -16,81 +16,48 @@ export interface BusinessOrderQuery {
orderNo?: string orderNo?: string
status?: string status?: string
routeKeyword?: string routeKeyword?: string
productName?: string
purchaseCategory?: string
transportType?: string transportType?: string
transportMode?: string vehicleType?: 'PALLET_15' | 'PALLET_30'
pickupFrom?: string
pickupTo?: string
requestedFrom?: string requestedFrom?: string
requestedTo?: string requestedTo?: string
createdFrom?: string createdFrom?: string
createdTo?: string createdTo?: string
} }
export interface ProcurementSummary {
orderNo: string
purchaseCategory: string
productName: string
productSpecification: string | null
purchaseQuantity: number
budgetUnitPrice: number | null
currency: string | null
inboundQuantity: number
outboundQuantity: number
inventoryQuantity: number
status: string
version: number
createdAt: string
updatedAt: string
}
export interface ProcurementDetail {
summary: ProcurementSummary
productUrl: string | null
receivingAddress: string | null
contactName: string
contactPhone: string
domesticCarrier: string | null
domesticTrackingNo: string | null
overseasCarrier: string | null
overseasTrackingNo: string | null
estimatedArrivalAt: string | null
remark: string | null
reviewRemark: string | null
}
export interface ProcurementCreate {
customerName: string
purchaseCategory: string
productName: string
productSpecification?: string
productUrl?: string
purchaseQuantity: number
budgetUnitPrice?: number
currency?: string
receivingAddress?: string
contactName: string
contactPhone: string
remark?: string
idempotencyKey: string
}
export interface TransportSummary { export interface TransportSummary {
deliveryMode?: 'DELIVERY_TO_WAREHOUSE' | 'WAREHOUSE_PICKUP'
operatingWarehouseId?: string
destinationType?: 'FBA' | 'PRIVATE'
destinationPostalCode?: string
deliveryContactName?: string
deliveryContactPhone?: string
estimatedArrivalAt?: string
trackingNo?: string
transferNo?: string
fleetArrangement: import('../fleetArrangement').FleetArrangement | null
orderNo: string orderNo: string
transportType: string transportType?: string
transportMode?: string palletRequired?: string | null
palletRequired?: string
origin: string origin: string
destination: string destination: string
containerType: string | null
palletCount?: number palletCount?: number
packageCount: number packageCount: number
totalWeightKg: number totalWeightKg: number
totalVolumeCbm: number totalVolumeCbm: number
budgetAmount: number | null budgetAmount: number | null
currency: string | null currency: string | null
contactName: string | null productName?: string | null
contactInfo: string | null estimatedPalletCount?: number | null
requestedDate: string | null vehicleType?: 'PALLET_15' | 'PALLET_30' | null
originContactName?: string | null
originContactPhone?: string | null
destinationContactName?: string | null
destinationContactPhone?: string | null
pickupAt?: string | null
deliveryAt?: string | null
status: string status: string
version: number version: number
createdAt: string createdAt: string
@@ -102,26 +69,58 @@ export interface TransportDetail {
originAddress: string | null originAddress: string | null
destinationAddress: string | null destinationAddress: string | null
remark: string | null remark: string | null
histories?: Array<{ operationType: string; toStatus: string; remark: string | null }>
} }
export interface TransportCreate { export interface TransportCreate {
transportType: string deliveryMode?: 'DELIVERY_TO_WAREHOUSE' | 'WAREHOUSE_PICKUP'
transportMode?: string operatingWarehouseId?: string
palletRequired?: string destinationType?: 'FBA' | 'PRIVATE'
destinationPostalCode?: string
deliveryContactName?: string
deliveryContactPhone?: string
estimatedArrivalAt?: string
trackingNo?: string
transferNo?: string
productName?: string
estimatedPalletCount: number
origin: string origin: string
originAddress?: string originAddress?: string
destination: string destination: string
destinationAddress?: string destinationAddress?: string
containerType?: string
palletCount?: number
packageCount: number packageCount: number
totalWeightKg: number totalWeightKg: number
totalVolumeCbm: number totalVolumeCbm: number
budgetAmount?: number budgetAmount?: number
currency?: string currency?: string
contactName?: string originContactName: string
contactInfo?: string originContactPhone: string
requestedDate?: string destinationContactName: string
destinationContactPhone: string
pickupAt: string
deliveryAt: string
remark?: string
idempotencyKey: string
}
export interface TruckCreate {
vehicleType: 'PALLET_15' | 'PALLET_30'
origin: string
originAddress?: string
destination: string
destinationAddress?: string
originContactName: string
originContactPhone: string
destinationContactName: string
destinationContactPhone: string
pickupAt: string
deliveryAt: string
palletCount: number
totalWeightKg: number
totalVolumeCbm: number
budgetAmount?: number
currency?: string
remark?: string remark?: string
idempotencyKey: string idempotencyKey: string
} }
@@ -130,8 +129,11 @@ export interface TransportUpdate extends Omit<TransportCreate, 'idempotencyKey'>
version: number version: number
} }
export interface TruckUpdate extends Omit<TruckCreate, 'idempotencyKey'> {
version: number
}
const endpointByKind: Record<CrossBorderBusinessKind, string> = { const endpointByKind: Record<CrossBorderBusinessKind, string> = {
procurement: '/merchant/v1/last-leg/overseas-procurements',
trucking: '/merchant/v1/last-leg/us-truck-orders', trucking: '/merchant/v1/last-leg/us-truck-orders',
looseboard: '/merchant/v1/last-leg/local-looseboard-orders', looseboard: '/merchant/v1/last-leg/local-looseboard-orders',
} }
@@ -141,25 +143,40 @@ function normalizePage<T>(data: PageResult<T>): PageResult<T> {
} }
export function listBusinessOrders<T>(kind: CrossBorderBusinessKind, params: BusinessOrderQuery) { export function listBusinessOrders<T>(kind: CrossBorderBusinessKind, params: BusinessOrderQuery) {
return overseasApiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage) return apiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage)
} }
export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: string) { export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: string) {
return overseasApiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` }) return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
} }
export function createProcurement(payload: ProcurementCreate) { export interface TransportPhoto { fileId: string; fileName: string; contentType: string; sizeBytes: number }
return overseasApiRequest<ProcurementDetail>({ method: 'POST', url: endpointByKind.procurement, data: payload }) export interface TransportPhotos { pickupPhotos: TransportPhoto[]; arrivalPhotos: TransportPhoto[] }
export type TransportPhotoPhase = 'PICKUP' | 'ARRIVAL'
export function getTransportPhotos(kind: CrossBorderBusinessKind, orderNo: string) {
return apiRequest<TransportPhotos>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}/transport-photos` })
}
export function readTransportPhoto(kind: CrossBorderBusinessKind, orderNo: string, phase: TransportPhotoPhase, fileId: string) {
return apiBlobRequest({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}/transport-photos/${phase}/${encodeURIComponent(fileId)}/content` })
} }
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) { export function createTransport(kind: 'trucking', payload: TruckCreate): Promise<TransportDetail>
return overseasApiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload }) export function createTransport(kind: 'looseboard', payload: TransportCreate): Promise<TransportDetail>
export function createTransport(kind: CrossBorderBusinessKind, payload: TransportCreate | TruckCreate) {
return apiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
} }
export function updateTransport(kind: 'trucking' | 'looseboard', orderNo: string, payload: TransportUpdate) { export function updateTransport(kind: 'trucking', orderNo: string, payload: TruckUpdate): Promise<TransportDetail>
return overseasApiRequest<TransportDetail>({ export function updateTransport(kind: 'looseboard', orderNo: string, payload: TransportUpdate): Promise<TransportDetail>
export function updateTransport(kind: CrossBorderBusinessKind, orderNo: string, payload: TransportUpdate | TruckUpdate) {
return apiRequest<TransportDetail>({
method: kind === 'trucking' ? 'PATCH' : 'PUT', method: kind === 'trucking' ? 'PATCH' : 'PUT',
url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}`, url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}`,
data: payload, data: payload,
}) })
} }
/** 客户按当前版本取消待审核本土卡车订单。 */
export function cancelTruckOrder(orderNo: string, payload: { version: number; status: 'CANCELLED'; idempotencyKey: string; remark: string }) {
return apiRequest<TransportDetail>({ method: 'PATCH', url: endpointByKind.trucking + '/' + encodeURIComponent(orderNo) + '/status', data: payload })
}
@@ -0,0 +1,10 @@
import { apiRequest } from '@/api/http'
export interface BudgetResult { status: string; usable: boolean; amountCny: number | string; message: string; orderNo: string | null }
const base = '/merchant/v1/last-leg/order-budgets'
// 创建订单时后端在同一事务记录冻结请求,客户端只在详情核对状态和重试明确失败。
export function readOrderFunding(kind: 'procurement' | 'trucking', orderNo: string) {
return apiRequest<BudgetResult>({ method: 'GET', url: base + '/' + kind + '/orders/' + encodeURIComponent(orderNo) })
}
export function retryOrderFunding(kind: 'procurement' | 'trucking', orderNo: string) {
return apiRequest<BudgetResult>({ method: 'POST', url: base + '/' + kind + '/orders/' + encodeURIComponent(orderNo) + '/retry' })
}
+156
View File
@@ -0,0 +1,156 @@
import { apiBlobRequest, apiRequest } from '@/api/http'
import type { PageResult } from './businessOrders'
export type Amount = number | string
export interface ProcurementSummary {
procurementDirection?: import('../procurementPresentation').ProcurementDirection
orderNo: string
purchaseCategory: string
productName: string
productSpecification: string | null
purchaseQuantity: number
budgetUnitPrice: Amount | null
currency: string | null
status: string
reviewRemark?: string | null
version: number
createdAt: string
updatedAt: string
}
export interface ProcurementOrder extends ProcurementSummary {
productUrl: string | null
receivingAddress: string
contactName: string
contactPhone: string
estimatedArrivalAt: string | null
plannedWarehouseName: string | null
actualWarehouseCode: string | null
actualWarehouseName: string | null
remark: string | null
}
export interface ProcurementFee {
feeNo: string
purpose: string
name: string
version: number | null
active: boolean
determination: string
amount: Amount
currency: string
originalAmount: Amount | null
originalCurrency: string | null
exchangeRate: Amount | null
exchangeRateMonth: string | null
businessDate: string | null
parentFeeNo: string | null
walletStatus: string | null
sourceLinked: boolean
}
export interface ProcurementBox {
cartonNo: string
quantity: number
lengthCm: Amount
widthCm: Amount
heightCm: Amount
grossWeightKg: Amount
}
export interface ProcurementShipment {
shipmentNo: string
leg: 'OVERSEAS' | 'DOMESTIC'
shippedAt: string
cartonNo: string
quantity: number
carrier: string
trackingNo: string
}
export interface ProcurementDetail {
order: ProcurementOrder
budget: { totalAmount: Amount | null; currency: string; authorizedAt: string | null }
purchased: boolean
purchaseConfirmed: boolean
purchaseNeedsAttention: boolean
progress: { key: string; title: string; completedAt: string | null }[]
boxes: ProcurementBox[]
shipments: ProcurementShipment[]
fees: ProcurementFee[]
exceptionSummaries: string[]
}
export interface ProcurementCreate {
procurementDirection?: import('../procurementPresentation').ProcurementDirection
customerName: string
purchaseCategory: string
productName: string
productSpecification?: string
productUrl?: string
purchaseQuantity: number
budgetUnitPrice: number
currency: 'CNY' | 'USD'
receivingAddress: string
contactName: string
contactPhone: string
remark?: string
idempotencyKey: string
}
export interface ProcurementQuery {
page: number
size: number
orderNo?: string
productName?: string
purchaseCategory?: string
status?: string
}
export interface ProcurementWorkflowFile { fileId: string; fileName: string; contentType: string }
export interface ProcurementReceipt {
id: string
quantity: number
fileIds: string[]
receivedAt: string
}
export interface ProcurementOutbound {
id: string
outboundNo: string
quantity: number
trackingNo: string
status: string
fileIds: string[]
createdAt: string
completedAt: string | null
}
export interface ProcurementWorkflow {
orderNo: string
version: number
status: string
rejectionReason: string | null
photosNeedUpdate: boolean
receivedQuantity: number
stockQuantity: number
reservedQuantity: number
availableQuantity: number
files: ProcurementWorkflowFile[]
receipts: ProcurementReceipt[]
outbounds: ProcurementOutbound[]
}
const endpoint = '/merchant/v1/last-leg/overseas-procurements'
export async function listProcurements(params: ProcurementQuery) {
const result = await apiRequest<PageResult<ProcurementSummary>>({ method: 'GET', url: endpoint, params })
return { ...result, page: Number(result.page), size: Number(result.size), total: Number(result.total), pages: Number(result.pages) }
}
export function getProcurement(orderNo: string) {
return apiRequest<ProcurementDetail>({ method: 'GET', url: `${endpoint}/${encodeURIComponent(orderNo)}` })
}
export function createProcurement(data: ProcurementCreate) {
return apiRequest<ProcurementDetail>({ method: 'POST', url: endpoint, data })
}
export function getProcurementWorkflow(orderNo: string) {
return apiRequest<ProcurementWorkflow>({ method: 'GET', url: `${endpoint}/${encodeURIComponent(orderNo)}/workflow` })
}
export function confirmProcurement(orderNo: string, data: { version: number; idempotencyKey: string }) {
return apiRequest<ProcurementWorkflow>({ method: 'POST', url: `${endpoint}/${encodeURIComponent(orderNo)}/confirm`, data })
}
export function rejectProcurement(orderNo: string, data: { version: number; idempotencyKey: string; reason: string }) {
return apiRequest<ProcurementWorkflow>({ method: 'POST', url: `${endpoint}/${encodeURIComponent(orderNo)}/reject`, data })
}
export function getProcurementFile(orderNo: string, fileId: string) {
return apiBlobRequest({ method: 'GET', url: `${endpoint}/${encodeURIComponent(orderNo)}/files/${encodeURIComponent(fileId)}/content` })
}
+223 -15
View File
@@ -1,24 +1,74 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import test from 'node:test' import test from 'node:test'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
const api = readFileSync(new URL('./api/businessOrders.ts', import.meta.url), 'utf8') const api = readFileSync(new URL('./api/businessOrders.ts', import.meta.url), 'utf8')
const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8') const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8')
const view = readFileSync(new URL('./components/BusinessOrdersView.vue', import.meta.url), 'utf8') const view = readFileSync(new URL('./components/BusinessOrdersView.vue', import.meta.url), 'utf8')
const demandComponent = readFileSync(new URL('./components/TransportDemandForm.vue', import.meta.url), 'utf8')
const demandLogic = ts.transpileModule(readFileSync(new URL('./transportDemandForm.ts', import.meta.url), 'utf8'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText.replace(/^export /gm, '')
const demandHelpers = runInNewContext(`${demandLogic}\n({ createTransportDemandForm, transportDemandRules, transportDemandError, buildTransportDemand })`)
const procurementApi = readFileSync(new URL('./api/procurement.ts', import.meta.url), 'utf8')
const procurementView = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
test('all current truck statuses display Chinese labels in lists and details', () => {
const labelsCode = ts.transpileModule(readFileSync(new URL('./fleetArrangement.ts', import.meta.url), 'utf8'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText.replace(/^export /gm, '')
const { poolOrderStatusLabels } = runInNewContext(`${labelsCode}\n({ poolOrderStatusLabels })`)
const helpers = view.slice(view.indexOf('function read('), view.indexOf('function idempotencyKey('))
const compiled = ts.transpileModule(helpers, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const { statusLabel, displayCell } = runInNewContext(`${compiled}\n({ statusLabel, displayCell })`, { poolOrderStatusLabels })
for (const status of ['PENDING_REVIEW', 'FUNDING_PENDING', 'FUNDING_FAILED', 'WAITING_INBOUND', 'RECEIVING', 'WAITING_CONSOLIDATION', 'PALLET_OVERAGE_REVIEW', 'PARTIALLY_ALLOCATED', 'ALLOCATED', 'PENDING_DISPATCH', 'DISPATCHED', 'IN_TRANSIT', 'COMPLETED', 'REJECTED', 'CANCELLED']) {
assert.match(statusLabel(status), /[\u4e00-\u9fff]/, status)
assert.equal(displayCell({ status }, 'status'), statusLabel(status))
}
assert.equal(statusLabel('DISPATCHED'), '待取货')
})
test('renders unknown pallet service and container type as dashes while preserving explicit values', () => {
const helpers = view.slice(view.indexOf('function read('), view.indexOf('function idempotencyKey('))
const compiled = ts.transpileModule(helpers, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const { displayCell, yesNo, text } = runInNewContext(`${compiled}\n({ displayCell, yesNo, text })`)
assert.equal(displayCell({ palletRequired: null }, 'palletRequired'), '—')
assert.equal(displayCell({ palletRequired: 'NO' }, 'palletRequired'), '否')
assert.equal(displayCell({ palletRequired: 'YES' }, 'palletRequired'), '是')
assert.equal(displayCell({ containerType: null }, 'containerType'), '—')
assert.equal(displayCell({ containerType: '40HQ' }, 'containerType'), '40HQ')
assert.equal(yesNo(null), '—')
assert.equal(text(null), '—')
assert.match(api, /palletRequired\?: string \| null/)
const create = api.slice(api.indexOf('export interface TransportCreate'), api.indexOf('export interface TransportUpdate'))
assert.doesNotMatch(create, /palletRequired\?: string \| null/)
})
test('shows merchant-owned arrangement facts without a pool request or editable status control', () => {
assert.match(api, /fleetArrangement: import\('\.\.\/fleetArrangement'\)\.FleetArrangement \| null/)
assert.match(view, /aria-label="承运安排"/)
for (const field of ['signedPackages', 'unsignedPackages', 'returnedPackages']) assert.ok(view.includes(`fleetArrangement.${field}`))
assert.doesNotMatch(api, /capacity-offers|fleet\/trips/)
assert.match(view, /if \(query\.page !== 1\) query\.page = 1\s+else void load\(\)/)
assert.match(view, /if \(reloadDirectly\) void load\(\)/)
})
test('activates all three customer cross-border pages with frozen permissions', () => { test('activates all three customer cross-border pages with frozen permissions', () => {
for (const [path, permission] of [ for (const [path, permission] of [
['cross-border/procurement', 'merchant:cross-border:procurement'], ['cross-border/procurement', 'merchant:cross-border:procurement:list'],
['cross-border/domestic-trucking', 'merchant:cross-border:domestic-trucking'], ['cross-border/domestic-trucking', 'merchant:cross-border:domestic-trucking:list'],
['cross-border/pallet-shipping', 'merchant:cross-border:pallet-shipping'], ['cross-border/pallet-shipping', 'merchant:cross-border:pallet-shipping:list'],
]) { ]) {
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?release: 'active'[\\s\\S]*?permission: '${permission}'`)) assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?release: 'active'[\\s\\S]*?permission: '${permission}'`))
} }
assert.doesNotMatch(view, /PrototypeFeatureView|mock|customerId|tenantId/i) assert.doesNotMatch(view, /PrototypeFeatureView|mock|customerId|tenantId/i)
assert.match(procurementView, /merchant:cross-border:procurement:create/)
assert.match(view, /merchant:cross-border:domestic-trucking:create/)
assert.match(view, /merchant:cross-border:pallet-shipping:create/)
assert.match(view, /v-if="canCreate"[^>]*type="primary"/)
}) })
test('uses only merchant overseas endpoints and keeps retry idempotency stable', () => { test('uses only merchant overseas endpoints and keeps retry idempotency stable', () => {
assert.match(api, /overseas-procurements/) assert.match(procurementApi, /overseas-procurements/)
assert.doesNotMatch(api, /overseas-procurements|ProcurementSummary|ProcurementDetail/)
assert.match(api, /us-truck-orders/) assert.match(api, /us-truck-orders/)
assert.match(api, /local-looseboard-orders/) assert.match(api, /local-looseboard-orders/)
assert.doesNotMatch(api, /\/platform\/|\/internal\/|customerId|tenantId/) assert.doesNotMatch(api, /\/platform\/|\/internal\/|customerId|tenantId/)
@@ -32,21 +82,179 @@ test('covers list detail create loading error empty pagination and actions-first
assert.match(view, /mode\.value = 'list'/) assert.match(view, /mode\.value = 'list'/)
assert.match(view, /mode = 'create'/) assert.match(view, /mode = 'create'/)
assert.match(view, /v-loading="loading"/) assert.match(view, /v-loading="loading"/)
assert.match(view, /type="error"/) assert.match(view, /class="business-load-error"/)
assert.match(view, /empty-text="暂无订单"/) assert.match(view, /empty-text="暂无订单"/)
assert.match(view, /<el-pagination/) assert.match(view, /<QueryToolbar[^>]*layout="grid"/)
assert.match(view, /<el-table-column label="操作"[^>]*fixed="left"/) assert.match(view, /<DataTable[^>]*:row-actions="getRowActions"/)
assert.match(view, /PENDING_OUTBOUND: '待出库'/) assert.match(view, /key: 'actions', label: '操作', width: 90, fixed: 'left'/)
assert.match(view, /PARTIALLY_OUTBOUND: '部分出库'/) assert.match(view, /class="business-table-card"/)
assert.match(view, /OUTBOUNDED: '全部出库'/) assert.doesNotMatch(procurementView, /inventoryQuantity|outboundQuantity/)
assert.match(view, /\['入库量', read\(summary, 'inboundQuantity'\)\]/) assert.match(procurementView, /label: '失败 \/ 拒绝原因'/)
assert.match(view, /\['审核备注', current\.reviewRemark\]/) assert.match(procurementView, /reviewRemark/)
assert.match(procurementView, /procurementStatuses/)
assert.match(procurementView, /ProcurementDetailPanel/)
}) })
test('keeps procurement filters, details and forms readable at PDA width', () => { test('opens every dashboard cross-border action on a dedicated protected create page', () => {
for (const [path, permission] of [
['cross-border/procurement/create', 'merchant:cross-border:procurement:create'],
['cross-border/domestic-trucking/create', 'merchant:cross-border:domestic-trucking:create'],
['cross-border/pallet-shipping/create', 'merchant:cross-border:pallet-shipping:create'],
]) {
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?props: \\{ createPage: true \\}[\\s\\S]*?permission: '${permission}'`))
}
assert.match(view, /props\.createPage \? 'create' : 'list'/)
assert.match(view, /if \(props\.createPage\) await router\.push/)
})
test('opens all cross-border details on dedicated protected routes', () => {
for (const [path, routeName] of [
['cross-border/procurement/:orderNo/detail', 'cross-border-procurement-detail'],
['cross-border/domestic-trucking/:orderNo/detail', 'cross-border-domestic-trucking-detail'],
['cross-border/pallet-shipping/:orderNo/detail', 'cross-border-pallet-shipping-detail'],
]) {
assert.match(routes, new RegExp(`path: '${path.replaceAll('/', '\\/')}'[\\s\\S]*?name: '${routeName}'`))
}
assert.match(view, /name: detailRouteName\.value, params: \{ orderNo: row\.orderNo \}/)
assert.match(view, /class="business-detail-error"/)
})
test('preserves the existing transport responsive rules without adding a narrow-screen procurement acceptance gate', () => {
assert.match(view, /@media \(max-width: 767px\)/) assert.match(view, /@media \(max-width: 767px\)/)
assert.match(view, /\.filter-card :deep\(\.el-form\) \{ display: grid; grid-template-columns: 1fr; \}/) assert.match(view, /queryFields/)
assert.match(view, /\.detail-grid \{ grid-template-columns: 1fr; \}/) assert.match(view, /\.detail-grid \{ grid-template-columns: 1fr; \}/)
assert.match(view, /\.form-card :deep\(\.el-form-item\) \{ display: block; \}/) assert.match(view, /\.form-card :deep\(\.el-form-item\) \{ display: block; \}/)
assert.match(view, /\.budget-form-item :deep\(\.el-form-item__content\) \{ display: flex; flex-wrap: nowrap; \}/) assert.match(demandComponent, /\.transport-demand-budget \{ display: grid; width: 100%/)
})
test('uses the shared dense order-list and detail visual language', () => {
assert.match(view, /class="business-orders client-ui"/)
assert.match(view, /\.business-detail-page \{[^}]*border: 1px solid var\(--client-border\);[^}]*border-radius: var\(--client-radius\);/)
assert.match(view, /\.detail-grid \{[^}]*grid-template-columns: repeat\(4, minmax\(0, 1fr\)\)/)
assert.match(view, /\.detail-grid div \{[^}]*min-height: 34px;[^}]*grid-template-columns: 76px minmax\(0, 1fr\)/)
})
function transportHarness(kind = 'trucking', failFirst = false, budgetCheck = async () => {}) {
const calls = []
const script = view.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
const compiled = ts.transpileModule(script, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText
.replace(/^import .*?;$/gm, '').replace(/^export \{\};$/gm, '')
const harness = runInNewContext(`${compiled}\n({ form, formRef, submit, detail, detailFields, configuration })`, {
defineProps: () => ({ kind, createPage: true, detailPage: false }),
withDefaults: props => props,
computed: getter => ({ get value() { return typeof getter === 'function' ? getter() : getter.get() } }),
reactive: value => value, ref: value => ({ value }), onMounted: () => {}, watch: () => {},
useAuthStore: () => ({ hasPermission: () => true }), useRouter: () => ({ push: async () => {} }), useRoute: () => ({ params: {} }),
...demandHelpers, poolOrderStatusLabels: {}, requireOrderBudget: budgetCheck,
ElMessage: { success: () => {}, error: () => {} },
createTransport: async (business, payload) => { calls.push({ business, payload: { ...payload } }); if (failFirst && calls.length === 1) throw new Error('retry'); },
})
Object.assign(harness.form, { deliveryMode: 'WAREHOUSE_PICKUP', operatingWarehouseId: '9', destinationType: 'FBA', originAddress: '123 Pickup Road', destinationAddress: '456 Delivery Road' })
harness.formRef.value = { validate: async () => true, clearValidate: () => {} }
return { ...harness, calls, rules: { get value() { return demandHelpers.transportDemandRules(kind === 'trucking' ? 'truck' : 'looseboard', harness.form) } } }
}
test('truck requires both contacts vehicle and minute times without inheriting looseboard fields', () => {
const truck = transportHarness()
for (const key of ['vehicleType', 'originContactName', 'originContactPhone', 'destinationContactName', 'destinationContactPhone', 'pickupAt', 'deliveryAt']) assert.equal(truck.rules.value[key][0].required, true)
for (const key of ['palletCount', 'contactName', 'contactInfo', 'requestedDate']) assert.equal(truck.rules.value[key], undefined)
const loose = transportHarness('looseboard')
assert.equal(loose.rules.value.contactName, undefined)
assert.equal(loose.rules.value.contactInfo, undefined)
assert.equal(loose.rules.value.transportMode, undefined)
for (const key of ['originContactName', 'originContactPhone', 'destinationContactName', 'destinationContactPhone', 'pickupAt', 'deliveryAt']) assert.equal(loose.rules.value[key][0].required, true)
truck.form.pickupAt = '2026-10-20T09:30:00'
let failure
truck.rules.value.deliveryAt[1].validator({}, '2026-10-20T09:29:00', error => { failure = error })
assert.equal(failure.message, '送达时间不能早于取货时间')
})
test('truck retry submits the complete new contract with identical local times and idempotency key', async () => {
const current = transportHarness('trucking', true)
Object.assign(current.form, { vehicleType: 'PALLET_30', estimatedPalletCount: 3, budgetAmount: 100, origin: 'Los Angeles', destination: 'Ontario', originContactName: 'A', originContactPhone: '+1-555-0100', destinationContactName: 'B', destinationContactPhone: '+1-555-0101', pickupAt: '2026-10-20T09:30:00', deliveryAt: '2026-10-20T15:45:00' })
await current.submit()
assert.equal(current.form.destinationContactName, 'B')
await current.submit()
assert.equal(current.calls.length, 2)
const first = current.calls[0].payload
const second = current.calls[1].payload
assert.equal(first.idempotencyKey, second.idempotencyKey)
assert.equal(second.vehicleType, 'PALLET_30')
assert.equal(second.palletCount, 3)
assert.equal(second.originContactPhone, '+1-555-0100')
assert.equal(second.destinationContactName, 'B')
assert.equal(second.pickupAt, '2026-10-20T09:30:00')
assert.equal(second.deliveryAt, '2026-10-20T15:45:00')
for (const field of ['transportType', 'containerType', 'packageCount', 'contactName', 'contactInfo', 'requestedDate']) assert.equal(Object.hasOwn(second, field), false)
})
test('truck details render saved minute times and unknown pool demand without timezone conversion', () => {
const current = transportHarness()
current.detail.value = { summary: { vehicleType: null, palletCount: 3, packageCount: 0, pickupAt: '2026-10-20T09:30:00', deliveryAt: null }, originAddress: null, destinationAddress: null, remark: null }
const fields = new Map(current.detailFields.value)
assert.equal(fields.get('车辆类型'), '—')
assert.equal(fields.get('取货时间'), '2026-10-20 09:30')
assert.equal(fields.get('送达时间'), '—')
assert.equal(fields.has('柜型'), false)
assert.equal(fields.has('托盘数'), false)
assert.equal(fields.get('托数'), 3)
assert.equal(fields.has('件数'), false)
const columns = current.configuration.value.columns
assert.equal(columns.find(column => column.label === '托数').key, 'palletCount')
assert.equal(columns.some(column => column.key === 'packageCount'), false)
})
test('looseboard saves split contacts and both local minute times without obsolete fields', async () => {
const current = transportHarness('looseboard', true)
Object.assign(current.form, { originContactName: 'A', originContactPhone: '1', destinationContactName: 'B', destinationContactPhone: '2', productName: '家居用品', estimatedPalletCount: 3, packageCount: 8, origin: 'LA', destination: 'ONT', pickupAt: '2026-10-20T09:00:00', deliveryAt: '2026-10-20T15:30:00' })
await current.submit(); await current.submit()
const payload = current.calls[1].payload
assert.equal(payload.estimatedPalletCount, 3)
assert.equal(payload.packageCount, 8)
assert.equal(payload.productName, '家居用品')
assert.equal(payload.pickupAt, '2026-10-20T09:00:00')
assert.equal(payload.originContactName, 'A')
assert.equal(payload.destinationContactPhone, '2')
assert.equal(payload.deliveryAt, '2026-10-20T15:30:00')
assert.equal(payload.idempotencyKey, current.calls[0].payload.idempotencyKey)
current.detail.value = { summary: { ...payload }, originAddress: null, destinationAddress: null, remark: null }
const fields = new Map(current.detailFields.value)
assert.equal(fields.get('件数'), 8)
assert.equal(fields.get('预计托数'), 3)
assert.equal(fields.has('托数'), false)
assert.equal(current.configuration.value.columns.some(column => column.key === 'palletCount'), false)
for (const field of ['palletRequired', 'transportType', 'transportMode', 'containerType', 'contactName', 'contactInfo', 'requestedDate']) assert.equal(Object.hasOwn(payload, field), false)
})
test('looseboard requires both times and rejects backwards schedule', () => {
const current = transportHarness('looseboard')
assert.equal(current.rules.value.pickupAt[0].required, true)
assert.equal(current.rules.value.deliveryAt[0].required, true)
let failure
current.form.pickupAt = '2026-10-20T10:30:00'
current.rules.value.deliveryAt[1].validator({}, '2026-10-20T10:29:00', error => { failure = error })
assert.ok(failure)
})
test('truck creation does not block on a separate budget reservation', async () => {
const current = transportHarness('trucking', false, async () => { throw new Error('旧冻结接口不应调用') })
Object.assign(current.form, { vehicleType: 'PALLET_30', estimatedPalletCount: 3, budgetAmount: 100, origin: 'LA', destination: 'ONT', originContactName: 'A', originContactPhone: '1', destinationContactName: 'B', destinationContactPhone: '2', pickupAt: '2026-10-20T09:00:00', deliveryAt: '2026-10-20T15:00:00' })
await current.submit()
assert.equal(current.calls.length, 1)
})
test('customer truck cancellation uses encoded order identity and current version without client scope', async () => {
const compiled = ts.transpileModule(api.replace(/^import .*$/gm, ''), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText.replace(/^export /gm, '')
let sent
const { cancelTruckOrder } = runInNewContext(compiled + '\n({ cancelTruckOrder })', { apiRequest: input => { sent = input; return Promise.resolve({}) } })
const payload = { version: 3, status: 'CANCELLED', idempotencyKey: 'cancel-1', remark: '客户取消' }
await cancelTruckOrder('TR/1', payload)
assert.equal(sent.method, 'PATCH')
assert.equal(sent.url, '/merchant/v1/last-leg/us-truck-orders/TR%2F1/status')
assert.equal(sent.data, payload)
assert.match(view, /summary.status === 'PENDING_REVIEW'/)
assert.match(view, /merchant:cross-border:domestic-trucking:edit/)
}) })
@@ -1,76 +1,47 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus' import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import TransportDemandForm from './TransportDemandForm.vue'
import OrderFundingStatus from './OrderFundingStatus.vue'
import TransportPhotoGallery from './TransportPhotoGallery.vue'
import { createTransportDemandForm, transportDemandError, buildTransportDemand, type TransportDemandForm as DemandFormModel } from '../transportDemandForm'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
import type { TableAction } from '@/components/common/tableActions'
import { useAuthStore } from '@/modules/auth/public' import { useAuthStore } from '@/modules/auth/public'
import { import {
createProcurement, cancelTruckOrder,
createTransport, createTransport,
getBusinessOrder, getBusinessOrder,
listBusinessOrders, listBusinessOrders,
type CrossBorderBusinessKind, type CrossBorderBusinessKind,
type ProcurementDetail,
type ProcurementSummary,
type TransportDetail, type TransportDetail,
type TransportSummary, type TransportSummary,
} from '../api/businessOrders' } from '../api/businessOrders'
import { CONTAINER_SPECIFICATIONS, DEFAULT_CONTAINER_TYPE } from '../containerSpecifications' import { poolOrderStatusLabels } from '../fleetArrangement'
const props = defineProps<{ kind: CrossBorderBusinessKind }>() const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
const auth = useAuthStore() const auth = useAuthStore()
const router = useRouter()
const route = useRoute()
const detailOrderNo = computed(() => String(route.params.orderNo || ''))
const canCreate = computed(() => auth.hasPermission(({
trucking: 'merchant:cross-border:domestic-trucking:create',
looseboard: 'merchant:cross-border:pallet-shipping:create',
} as Record<CrossBorderBusinessKind, string>)[props.kind]))
type BusinessRow = ProcurementSummary | TransportSummary type BusinessRow = TransportSummary
type BusinessDetail = ProcurementDetail | TransportDetail type BusinessDetail = TransportDetail
type PageMode = 'list' | 'create' | 'detail' type PageMode = 'list' | 'create' | 'detail'
interface ColumnDefinition { key: string; label: string; width?: number } interface ColumnDefinition { key: string; label: string; width?: number }
interface BusinessForm { type BusinessForm = DemandFormModel
purchaseCategory: string
productName: string
productSpecification: string
productUrl: string
purchaseQuantity: number
transportMode: string
palletRequired: string
transportType: string
origin: string
originAddress: string
destination: string
destinationAddress: string
containerType: string
palletCount: number
packageCount: number
totalWeightKg: number
totalVolumeCbm: number
budgetAmount?: number
currency: string
contactName: string
contactInfo: string
requestedDate: string
receivingAddress: string
remark: string
}
const configuration = computed(() => ({ const configuration = computed(() => ({
procurement: {
title: '海外采购',
description: '查询并管理海外采购订单',
columns: [
{ key: 'orderNo', label: '订单号', width: 180 },
{ key: 'purchaseCategory', label: '采购品类', width: 130 },
{ key: 'productName', label: '商品名称', width: 160 },
{ key: 'productSpecification', label: '商品规格', width: 160 },
{ key: 'purchaseQuantity', label: '采购数量', width: 100 },
{ key: 'budgetUnitPrice', label: '预算单价', width: 110 },
{ key: 'inboundQuantity', label: '入库量', width: 90 },
{ key: 'outboundQuantity', label: '出库量', width: 90 },
{ key: 'inventoryQuantity', label: '库存量', width: 90 },
{ key: 'status', label: '状态', width: 120 },
{ key: 'createdAt', label: '创建时间', width: 170 },
] satisfies ColumnDefinition[],
},
trucking: { trucking: {
title: '美国本土卡', title: '美国本土卡车',
description: '查询并管理美国本土卡订单', description: '查询并管理美国本土卡订单',
columns: transportColumns(false), columns: transportColumns(false),
}, },
@@ -82,107 +53,169 @@ const configuration = computed(() => ({
})[props.kind]) })[props.kind])
function transportColumns(looseboard: boolean): ColumnDefinition[] { function transportColumns(looseboard: boolean): ColumnDefinition[] {
const originLabel = looseboard ? '起运地' : '取货地'
const destinationLabel = looseboard ? '目的地' : '送达地'
const pickupLabel = looseboard ? '取货时间' : '取货时间'
const deliveryLabel = looseboard ? '送货时间' : '送达时间'
return [ return [
{ key: 'orderNo', label: '订单编号', width: 180 }, { key: 'orderNo', label: '订单编号', width: 180 },
...(looseboard ? [{ key: 'transportMode', label: '运输方式', width: 120 }, { key: 'palletRequired', label: '是否打盘', width: 100 }] : []), ...(!looseboard ? [{ key: 'vehicleType', label: '车辆类型', width: 110 }] : []),
{ key: 'transportType', label: '运输类型', width: 130 }, { key: 'origin', label: originLabel, width: 150 },
{ key: 'origin', label: '起运地', width: 150 }, { key: 'destination', label: destinationLabel, width: 150 },
{ key: 'destination', label: '目的地', width: 150 }, ...(looseboard ? [{ key: 'productName', label: '商品名称', width: 150 }, { key: 'estimatedPalletCount', label: '预计托数', width: 100 }] : []),
{ key: 'containerType', label: '柜型', width: 100 }, ...(!looseboard ? [{ key: 'palletCount', label: '托数', width: 80 }] : []),
{ key: 'totalWeightKg', label: '总重量(kg)', width: 120 }, { key: 'totalWeightKg', label: '总重量(kg)', width: 120 },
{ key: 'budgetAmount', label: '预算总价', width: 110 }, { key: 'budgetAmount', label: '预算总价', width: 110 },
{ key: 'requestedDate', label: '要求时间', width: 120 }, ...([
{ key: 'pickupAt', label: pickupLabel, width: 165 }, { key: 'deliveryAt', label: deliveryLabel, width: 165 },
]),
{ key: 'status', label: '状态', width: 130 }, { key: 'status', label: '状态', width: 130 },
...(!looseboard ? [{ key: 'failureReason', label: '失败 / 拒绝原因', width: 240 }] : []),
...(looseboard
? [{ key: 'fleetArrangement', label: '承运安排', width: 190 }]
: [{ key: 'createdAt', label: '创建时间', width: 180 }]),
] ]
} }
const mode = ref<PageMode>('list') const mode = ref<PageMode>(props.detailPage ? 'detail' : props.createPage ? 'create' : 'list')
const loading = ref(false) const loading = ref(false)
const submitting = ref(false) const submitting = ref(false)
const submitKey = ref('') const submitKey = ref('')
const error = ref('') const error = ref('')
const rows = ref<BusinessRow[]>([]) const rows = ref<BusinessRow[]>([])
const detail = ref<BusinessDetail | null>(null) const detail = ref<BusinessDetail | null>(null)
const photoRefresh = ref(0)
const fleetArrangement = computed(() => detail.value ? (detail.value as TransportDetail).summary.fleetArrangement : null)
const formRef = ref<FormInstance>() const formRef = ref<FormInstance>()
const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' }) const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '' })
const total = ref(0) const total = ref(0)
const queryModel = computed<QueryModel>({
get: () => ({
orderNo: query.orderNo,
routeKeyword: query.routeKeyword,
status: query.status,
}),
set: (value) => {
query.orderNo = String(value.orderNo || '')
query.routeKeyword = String(value.routeKeyword || '')
query.status = String(value.status || '')
},
})
const queryFields = computed<QueryField[]>(() => [
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: props.kind === 'trucking' ? '请输入取货地或目的地' : '请输入起运地或目的地' },
{
key: 'status',
label: '状态',
type: 'select',
placeholder: '全部',
options: props.kind === 'trucking' ? [
{ label: '订单受理中', value: 'FUNDING_PENDING' },
{ label: '订单处理失败', value: 'FUNDING_FAILED' },
{ label: '待审核', value: 'PENDING_REVIEW' },
{ label: '待排车', value: 'PENDING_DISPATCH' },
{ label: '待取货', value: 'DISPATCHED' },
{ label: '运输中', value: 'IN_TRANSIT' },
{ label: '已完成', value: 'COMPLETED' },
{ label: '已拒绝', value: 'REJECTED' },
{ label: '已取消', value: 'CANCELLED' },
] : [
{ label: '订单受理中', value: 'FUNDING_PENDING' },
{ label: '订单处理失败', value: 'FUNDING_FAILED' },
{ label: '待审核', value: 'PENDING_REVIEW' },
{ label: '已通过', value: 'APPROVED' },
{ label: '已拒绝', value: 'REJECTED' },
{ label: '待接单', value: 'PENDING_ACCEPTANCE' },
...Object.entries(poolOrderStatusLabels).filter(([value]) => !['IN_TRANSIT', 'COMPLETED', 'CANCELLED'].includes(value)).map(([value, label]) => ({ value, label })),
{ label: '处理中', value: 'PROCESSING' },
{ label: '运输中', value: 'IN_TRANSIT' },
{ label: '已完成', value: 'COMPLETED' },
{ label: '已取消', value: 'CANCELLED' },
],
},
])
const form = reactive<BusinessForm>(emptyForm()) const form = reactive<BusinessForm>(emptyForm())
const rules: FormRules<BusinessForm> = { watch(() => JSON.stringify(form), () => { submitKey.value = '' })
purchaseCategory: [{ required: true, message: '请输入采购品类', trigger: 'blur' }],
productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
purchaseQuantity: [{ required: true, type: 'number', min: 1, message: '采购数量至少为 1', trigger: 'change' }],
origin: [{ required: true, message: '请输入起运地', trigger: 'blur' }],
destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
palletCount: [{ required: true, type: 'number', min: 1, message: '托盘数至少为 1', trigger: 'change' }],
contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
contactInfo: [{ required: true, message: '请输入联系电话或联系方式', trigger: 'blur' }],
requestedDate: [{ required: true, message: '请选择要求时间', trigger: 'change' }],
}
const detailFields = computed(() => { const detailFields = computed(() => {
if (!detail.value) return [] if (!detail.value) return []
const summary = detail.value.summary const summary = detail.value.summary
if (props.kind === 'procurement') {
const current = detail.value as ProcurementDetail
return [
['订单号', summary.orderNo], ['采购品类', read(summary, 'purchaseCategory')],
['商品名称', read(summary, 'productName')], ['商品规格', read(summary, 'productSpecification')],
['采购数量', read(summary, 'purchaseQuantity')], ['预算单价', money(read(summary, 'budgetUnitPrice'), read(summary, 'currency'))],
['入库量', read(summary, 'inboundQuantity')], ['出库量', read(summary, 'outboundQuantity')],
['库存量', read(summary, 'inventoryQuantity')], ['预计到达时间', dateTime(current.estimatedArrivalAt)],
['联系人', current.contactName], ['联系电话', current.contactPhone],
['收货地址', current.receivingAddress], ['商品链接', current.productUrl],
['国内运单', joinText(current.domesticCarrier, current.domesticTrackingNo)],
['海外运单', joinText(current.overseasCarrier, current.overseasTrackingNo)],
['状态', statusLabel(summary.status)], ['审核备注', current.reviewRemark], ['备注', current.remark],
]
}
const current = detail.value as TransportDetail const current = detail.value as TransportDetail
return [ return [
['订单编号', summary.orderNo], ['运输方式', read(summary, 'transportMode')], ...(props.kind === 'looseboard' ? [
['是否打盘', yesNo(read(summary, 'palletRequired'))], ['运输类型', transportTypeLabel(read(summary, 'transportType'))], ['商品名称', summary.productName], ['预计托数', summary.estimatedPalletCount],
['起运地', read(summary, 'origin')], ['起运地址', current.originAddress], ] : [['车辆类型', vehicleTypeLabel(summary.vehicleType)]]),
['目的地', read(summary, 'destination')], ['目的地址', current.destinationAddress], [props.kind === 'trucking' ? '取货地' : '起运地', read(summary, 'origin')], [props.kind === 'trucking' ? '取货地址' : '起运地址', current.originAddress],
['柜型', read(summary, 'containerType')], ['托盘数', read(summary, 'palletCount')], [props.kind === 'trucking' ? '送达地' : '目的地', read(summary, 'destination')], [props.kind === 'trucking' ? '送达地址' : '目的地址', current.destinationAddress],
['件数', read(summary, 'packageCount')], ['总重量(kg)', read(summary, 'totalWeightKg')], [props.kind === 'trucking' ? '托数' : '件数', read(summary, props.kind === 'trucking' ? 'palletCount' : 'packageCount')], ['总重量(kg)', read(summary, 'totalWeightKg')],
['总体积(m³)', read(summary, 'totalVolumeCbm')], ['预算总价', money(read(summary, 'budgetAmount'), read(summary, 'currency'))], ['总体积(m³)', read(summary, 'totalVolumeCbm')], ['预算总价', money(read(summary, 'budgetAmount'), read(summary, 'currency'))],
['联系人', read(summary, 'contactName')], ['联系方式', read(summary, 'contactInfo')], [props.kind === 'trucking' ? '取货联系人' : '起运地联系人', summary.originContactName], [props.kind === 'trucking' ? '取货联系电话' : '起运地联系电话', summary.originContactPhone],
['要求时间', read(summary, 'requestedDate')], ['状态', statusLabel(summary.status)], ['备注', current.remark], [props.kind === 'trucking' ? '送达联系人' : '目的地联系人', summary.destinationContactName], [props.kind === 'trucking' ? '送达联系电话' : '目的地联系电话', summary.destinationContactPhone],
[props.kind === 'trucking' ? '取货时间' : '取货时间', localMinute(summary.pickupAt)], [props.kind === 'trucking' ? '送达时间' : '送货时间', localMinute(summary.deliveryAt)], ['备注', current.remark],
] ]
}) })
function emptyForm(): BusinessForm { const tableColumns = computed<DataTableColumn[]>(() => [
return { { key: 'actions', label: '操作', width: 90, fixed: 'left', slotName: 'actions' },
purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: 1, ...configuration.value.columns.map((column) => ({
transportMode: 'SHARED_TRUCK', palletRequired: 'NO', transportType: 'PORT_PICKUP', origin: '', originAddress: '', ...column,
destination: '', destinationAddress: '', containerType: DEFAULT_CONTAINER_TYPE, palletCount: 1, packageCount: 0, prop: column.key,
totalWeightKg: 0, totalVolumeCbm: 0, currency: 'USD', contactName: '', contactInfo: '', requestedDate: '', slotName: ['orderNo', 'status', 'failureReason', 'fleetArrangement'].includes(column.key) ? column.key : undefined,
receivingAddress: '', remark: '', formatter: (row: object) => displayCell(row, column.key),
} })),
])
const canCancelTruck = computed(() => props.kind === 'trucking' && detail.value?.summary.status === 'PENDING_REVIEW'
&& auth.hasPermission('merchant:cross-border:domestic-trucking:edit'))
/** 取消前核对客户意愿,失败保留订单并刷新服务端状态。 */
async function cancelTruck() {
if (!canCancelTruck.value || !detail.value || submitting.value) return
let reason: string
try {
const result = await ElMessageBox.prompt('请填写取消原因', '取消订单', { inputValidator: value => Boolean(value?.trim()) || '请填写取消原因', confirmButtonText: '确认取消', cancelButtonText: '保留订单', type: 'warning' })
reason = result.value.trim()
} catch { return }
submitting.value = true
try {
detail.value = await cancelTruckOrder(detail.value.summary.orderNo, { version: detail.value.summary.version, status: 'CANCELLED', idempotencyKey: idempotencyKey(), remark: reason })
ElMessage.success('订单已取消')
} catch (cause) { ElMessage.error(errorMessage(cause)); await loadDetail() }
finally { submitting.value = false }
} }
const detailStatus = computed(() => detail.value ? statusLabel(detail.value.summary.status) : '—')
function emptyForm(): BusinessForm { return createTransportDemandForm() }
function resetForm() { Object.assign(form, emptyForm()); submitKey.value = ''; formRef.value?.clearValidate() } function resetForm() { Object.assign(form, emptyForm()); submitKey.value = ''; formRef.value?.clearValidate() }
function read(source: object, key: string) { return Reflect.get(source, key) as unknown } function read(source: object, key: string) { return Reflect.get(source, key) as unknown }
function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) } function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
function joinText(...values: unknown[]) { const result = values.filter(Boolean).join(' / '); return result || '—' }
function money(amount: unknown, currency: unknown) { return amount === null || amount === undefined ? '—' : `${text(currency)} ${Number(amount).toFixed(2)}` } function money(amount: unknown, currency: unknown) { return amount === null || amount === undefined ? '—' : `${text(currency)} ${Number(amount).toFixed(2)}` }
function dateTime(value: unknown) { return value ? new Date(String(value)).toLocaleString('zh-CN', { hour12: false }) : '—' } function dateTime(value: unknown) { return value ? new Date(String(value)).toLocaleString('zh-CN', { hour12: false }) : '—' }
function yesNo(value: unknown) { return value === 'YES' ? '是' : value === 'NO' ? '否' : text(value) } function yesNo(value: unknown) { return value === 'YES' ? '是' : value === 'NO' ? '否' : text(value) }
function vehicleTypeLabel(value: unknown) { return ({ PALLET_15: '15拖', PALLET_30: '30拖' } as Record<string, string>)[String(value)] || text(value) }
function localMinute(value: unknown) { return value ? String(value).replace('T', ' ').slice(0, 16) : '—' }
function transportTypeLabel(value: unknown) { return ({ PORT_PICKUP: '港口提柜', WAREHOUSE_TO_WAREHOUSE: '仓到仓', WAREHOUSE_TO_DOOR: '仓到门' } as Record<string, string>)[String(value)] || text(value) } function transportTypeLabel(value: unknown) { return ({ PORT_PICKUP: '港口提柜', WAREHOUSE_TO_WAREHOUSE: '仓到仓', WAREHOUSE_TO_DOOR: '仓到门' } as Record<string, string>)[String(value)] || text(value) }
function transportModeLabel(value: unknown) { return ({ SHARED_TRUCK: '拼车', PRIORITY_CONSOLIDATION: '优先拼载' } as Record<string, string>)[String(value)] || text(value) }
function statusLabel(value: unknown) { function statusLabel(value: unknown) {
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_OUTBOUND: '待出库', PARTIALLY_OUTBOUND: '部分出库', OUTBOUNDED: '全部出库', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value) if (poolOrderStatusLabels[String(value)]) return poolOrderStatusLabels[String(value)]
return ({ FUNDING_PENDING: '订单受理中', FUNDING_FAILED: '订单处理失败', PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
}
function statusTone(value: unknown) {
return ({ APPROVED: 'success', COMPLETED: 'success', REJECTED: 'danger', CANCELLED: 'info', FUNDING_PENDING: 'warning', FUNDING_FAILED: 'danger', PENDING_REVIEW: 'warning', PENDING_ACCEPTANCE: 'warning', PROCESSING: 'primary', IN_TRANSIT: 'primary' } as Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'>)[String(value)] || 'info'
} }
function displayCell(candidate: unknown, key: string) { function displayCell(candidate: unknown, key: string) {
const row = candidate as BusinessRow const row = candidate as BusinessRow
const value = read(row, key) const value = read(row, key)
if (key === 'status') return statusLabel(value) if (key === 'status') return statusLabel(value)
if (key === 'vehicleType') return vehicleTypeLabel(value)
if (key === 'pickupAt' || key === 'deliveryAt') return localMinute(value)
if (key === 'transportType') return transportTypeLabel(value) if (key === 'transportType') return transportTypeLabel(value)
if (key === 'transportMode') return transportModeLabel(value)
if (key === 'palletRequired') return yesNo(value) if (key === 'palletRequired') return yesNo(value)
if (key === 'createdAt') return dateTime(value) if (key === 'createdAt') return dateTime(value)
if (key === 'budgetUnitPrice' || key === 'budgetAmount') return money(value, read(row, 'currency')) if (key === 'budgetAmount') return money(value, read(row, 'currency'))
return text(value) return text(value)
} }
function idempotencyKey() { return globalThis.crypto?.randomUUID?.() || `client-${Date.now()}-${Math.random().toString(16).slice(2)}` } function idempotencyKey() { return globalThis.crypto?.randomUUID?.() || `client-${Date.now()}-${Math.random().toString(16).slice(2)}` }
@@ -194,12 +227,9 @@ async function load() {
try { try {
const params = { const params = {
page: query.page, size: query.size, orderNo: query.orderNo || undefined, status: query.status || undefined, page: query.page, size: query.size, orderNo: query.orderNo || undefined, status: query.status || undefined,
routeKeyword: query.routeKeyword || undefined, productName: query.productName || undefined, routeKeyword: query.routeKeyword || undefined,
purchaseCategory: query.purchaseCategory || undefined,
} }
const result = props.kind === 'procurement' const result = await listBusinessOrders<TransportSummary>(props.kind, params)
? await listBusinessOrders<ProcurementSummary>('procurement', params)
: await listBusinessOrders<TransportSummary>(props.kind, params)
rows.value = result.records rows.value = result.records
total.value = result.total total.value = result.total
} catch (cause) { } catch (cause) {
@@ -210,157 +240,201 @@ async function load() {
} }
function resetQuery() { function resetQuery() {
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' }) const reloadDirectly = query.page === 1
void load() Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '' })
if (reloadDirectly) void load()
} }
async function openDetail(candidate: unknown) { function searchOrders() {
if (query.page !== 1) query.page = 1
else void load()
}
function getRowActions(candidate: object): TableAction[] {
return [{ key: 'detail', label: '详情', run: () => openDetail(candidate) }]
}
function detailFieldClass(label: unknown) {
if (label === '备注') return 'is-full'
return [props.kind === 'trucking' ? '取货地址' : '起运地址', props.kind === 'trucking' ? '送达地址' : '目的地址'].includes(String(label)) ? 'is-wide' : ''
}
const listRouteName = computed(() => ({
trucking: 'cross-border-domestic-trucking',
looseboard: 'cross-border-pallet-shipping',
} as Record<CrossBorderBusinessKind, string>)[props.kind])
const detailRouteName = computed(() => ({
trucking: 'cross-border-domestic-trucking-detail',
looseboard: 'cross-border-pallet-shipping-detail',
} as Record<CrossBorderBusinessKind, string>)[props.kind])
function returnToList() {
if (props.createPage || props.detailPage) {
void router.push({ name: listRouteName.value })
return
}
mode.value = 'list'
}
function openDetail(candidate: unknown) {
const row = candidate as BusinessRow const row = candidate as BusinessRow
void router.push({ name: detailRouteName.value, params: { orderNo: row.orderNo } })
}
async function loadDetail() {
if (!detailOrderNo.value) return
loading.value = true loading.value = true
error.value = '' error.value = ''
try { try {
detail.value = props.kind === 'procurement' detail.value = await getBusinessOrder<TransportDetail>(props.kind, detailOrderNo.value)
? await getBusinessOrder<ProcurementDetail>('procurement', row.orderNo) photoRefresh.value++
: await getBusinessOrder<TransportDetail>(props.kind, row.orderNo)
mode.value = 'detail' mode.value = 'detail'
} catch (cause) { ElMessage.error(errorMessage(cause)) } } catch (cause) { detail.value = null; error.value = errorMessage(cause); ElMessage.error(error.value) }
finally { loading.value = false } finally { loading.value = false }
} }
async function submit() { async function submit() {
if (submitting.value) return
const failure = transportDemandError(props.kind === 'trucking' ? 'truck' : 'looseboard', form)
if (failure) { ElMessage.error(failure); return }
if (!await formRef.value?.validate().catch(() => false)) return if (!await formRef.value?.validate().catch(() => false)) return
submitting.value = true submitting.value = true
const stableSubmitKey = submitKey.value || idempotencyKey() const stableSubmitKey = submitKey.value || idempotencyKey()
submitKey.value = stableSubmitKey submitKey.value = stableSubmitKey
try { try {
if (props.kind === 'procurement') { if (props.kind === 'trucking') {
await createProcurement({ const payload = { ...buildTransportDemand('truck', form), idempotencyKey: stableSubmitKey }
customerName: auth.user?.tenantName || '', await createTransport('trucking', payload)
purchaseCategory: form.purchaseCategory, productName: form.productName,
productSpecification: form.productSpecification || undefined, productUrl: form.productUrl || undefined,
purchaseQuantity: form.purchaseQuantity, budgetUnitPrice: form.budgetAmount,
currency: form.currency || undefined, receivingAddress: form.receivingAddress || undefined,
contactName: form.contactName, contactPhone: form.contactInfo, remark: form.remark || undefined,
idempotencyKey: stableSubmitKey,
})
} else {
const base = {
transportType: form.transportType, origin: form.origin, originAddress: form.originAddress || undefined,
destination: form.destination, destinationAddress: form.destinationAddress || undefined,
containerType: form.containerType || undefined, packageCount: form.packageCount,
totalWeightKg: form.totalWeightKg, totalVolumeCbm: form.totalVolumeCbm,
budgetAmount: form.budgetAmount, currency: form.currency || undefined,
contactName: form.contactName || undefined, contactInfo: form.contactInfo || undefined,
requestedDate: form.requestedDate || undefined, remark: form.remark || undefined,
idempotencyKey: stableSubmitKey,
} }
await createTransport(props.kind, props.kind === 'trucking' else await createTransport('looseboard', { ...buildTransportDemand('looseboard', form), idempotencyKey: stableSubmitKey })
? { ...base, palletCount: form.palletCount } ElMessage.success(props.kind === 'trucking' ? '本土卡订单已受理,资金校验完成后进入平台审核' : '订单提交成功')
: { ...base, transportMode: form.transportMode, palletRequired: form.palletRequired })
}
ElMessage.success('订单提交成功')
mode.value = 'list'
resetForm() resetForm()
await load() if (props.createPage) await router.push({ name: listRouteName.value })
} catch (cause) { ElMessage.error(errorMessage(cause)) } else { mode.value = 'list'; await load() }
} catch (cause) {
if (/已释放|已过期/.test(errorMessage(cause))) submitKey.value = ''
ElMessage.error(errorMessage(cause))
}
finally { submitting.value = false } finally { submitting.value = false }
} }
onMounted(() => void load()) watch(() => [query.page, query.size], () => { if (!props.createPage && mode.value === 'list') void load() })
onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.createPage) void load() })
</script> </script>
<template> <template>
<section v-loading="loading" class="business-orders" :aria-busy="loading"> <section v-loading="loading" class="business-orders client-ui" :class="{ 'business-orders--create': mode === 'create' }" :aria-busy="loading">
<header class="page-head"> <header v-if="mode === 'create'" class="page-head">
<div> <div>
<h2>{{ mode === 'detail' ? `${configuration.title}订单详情` : mode === 'create' ? `${configuration.title}下单` : configuration.title }}</h2> <h2>{{ configuration.title }}下单</h2>
<p>{{ mode === 'list' ? configuration.description : mode === 'create' ? '请填写订单信息,带 * 项为必填项' : `订单号:${detail?.summary.orderNo || '—'}` }}</p>
</div> </div>
<el-button v-if="mode !== 'list'" @click="mode = 'list'">返回列表</el-button> <el-button @click="returnToList">返回列表</el-button>
<el-button v-else type="primary" @click="resetForm(); mode = 'create'">新增下单</el-button>
</header> </header>
<template v-if="mode === 'list'"> <template v-if="mode === 'list'">
<el-alert v-if="error" :title="error" type="error" show-icon :closable="false"> <QueryToolbar v-model="queryModel" layout="grid" ariaLabel="订单查询条件" :fields="queryFields" :search-on-reset="false" @search="searchOrders" @reset="resetQuery" />
<template #default><el-button size="small" @click="load">重新加载</el-button></template> <div class="business-table-card">
</el-alert> <DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" :row-actions="getRowActions" row-key="orderNo" empty-text="暂无订单">
<el-card shadow="never" class="filter-card"> <template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="resetForm(); mode = 'create'">新增下单</el-button></template>
<el-form inline @submit.prevent="query.page = 1; load()"> <template v-if="error" #error><div class="business-load-error" role="alert"><span>{{ error }}</span><el-button size="small" @click="load">重新加载</el-button></div></template>
<el-form-item label="订单号"><el-input v-model.trim="query.orderNo" clearable placeholder="请输入订单号" /></el-form-item> <template #orderNo="{ row }"><button class="business-order-link" type="button" @click="openDetail(row)">{{ (row as BusinessRow).orderNo }}</button></template>
<el-form-item v-if="kind === 'procurement'" label="采购品类"><el-input v-model.trim="query.purchaseCategory" clearable placeholder="请输入采购品类" /></el-form-item> <template #status="{ row }"><el-tag :type="statusTone((row as BusinessRow).status)" effect="light" size="small">{{ statusLabel((row as BusinessRow).status) }}</el-tag></template>
<el-form-item v-if="kind === 'procurement'" label="商品名称"><el-input v-model.trim="query.productName" clearable placeholder="请输入商品名称" /></el-form-item> <template #failureReason="{ row }"><OrderFundingStatus v-if="['FUNDING_FAILED', 'REJECTED'].includes((row as BusinessRow).status)" kind="trucking" :order-no="(row as BusinessRow).orderNo" :status="(row as BusinessRow).status" :can-retry="false" compact /><span v-else>—</span></template>
<el-form-item v-else label="运输路线"><el-input v-model.trim="query.routeKeyword" clearable placeholder="起运地或目的地" /></el-form-item> <template #fleetArrangement="{ row }"><template v-if="(row as TransportSummary).fleetArrangement"><div>{{ poolOrderStatusLabels[(row as TransportSummary).fleetArrangement!.fulfillmentStage] || '待核对履约进度' }}</div><small>{{ dateTime((row as TransportSummary).fleetArrangement!.plannedDepartureAt) }}</small></template><span v-else>—</span></template>
<el-form-item label="状态"><el-input v-model.trim="query.status" clearable placeholder="请输入状态" /></el-form-item> </DataTable>
<el-form-item><el-button type="primary" native-type="submit">查询</el-button><el-button @click="resetQuery">重置</el-button></el-form-item> </div>
</el-form>
</el-card>
<el-card shadow="never">
<el-table :data="rows" empty-text="暂无订单" border>
<el-table-column label="操作" width="90" fixed="left"><template #default="scope"><el-button link type="primary" @click="openDetail(scope.row)">查看</el-button></template></el-table-column>
<el-table-column v-for="column in configuration.columns" :key="column.key" :label="column.label" :width="column.width" show-overflow-tooltip>
<template #default="scope">{{ displayCell(scope.row, column.key) }}</template>
</el-table-column>
</el-table>
<el-pagination v-model:current-page="query.page" v-model:page-size="query.size" class="pagination" :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @change="load" />
</el-card>
</template> </template>
<el-card v-else-if="mode === 'detail'" shadow="never"> <section v-else-if="mode === 'detail'" class="business-detail-page" aria-label="订单详情">
<dl class="detail-grid"> <header class="business-detail-heading">
<div v-for="field in detailFields" :key="String(field[0])"><dt>{{ field[0] }}</dt><dd>{{ text(field[1]) }}</dd></div> <div class="business-detail-heading-main"><el-button link type="primary" @click="returnToList">← 返回列表</el-button><div><h2>{{ detail?.summary.orderNo || '订单详情' }}</h2></div></div>
<div class="business-detail-heading-actions"><el-button v-if="canCancelTruck" type="danger" :loading="submitting" :disabled="loading" @click="cancelTruck">取消订单</el-button><el-tag :type="statusTone(detail?.summary.status)" effect="light">{{ detailStatus }}</el-tag><el-button :disabled="loading" @click="loadDetail">刷新</el-button></div>
</header>
<OrderFundingStatus v-if="kind === 'trucking' && detail" kind="trucking" :order-no="detail.summary.orderNo" :status="detail.summary.status" :can-retry="canCreate" @changed="loadDetail" />
<div v-if="error" class="business-detail-error" role="alert"><strong>{{ error }}</strong><el-button size="small" @click="loadDetail">重新加载</el-button></div>
<section v-else class="business-detail-section">
<h3>订单信息</h3>
<dl class="detail-grid" :class="{ 'trucking-detail-grid': kind === 'trucking', 'looseboard-detail-grid': kind === 'looseboard' }">
<div v-for="field in detailFields" :key="String(field[0])" :class="detailFieldClass(field[0])"><dt>{{ field[0] }}</dt><dd>{{ text(field[1]) }}</dd></div>
</dl> </dl>
</el-card> </section>
<TransportPhotoGallery v-if="!error && detail" :kind="kind" :order-no="detail.summary.orderNo" :refresh-key="photoRefresh" />
<section v-if="!error && fleetArrangement" class="business-detail-section" aria-label="承运安排">
<h3>承运安排</h3>
<dl class="detail-grid arrangement-grid">
<div><dt>预订号</dt><dd>{{ fleetArrangement.bookingNo }}</dd></div>
<div><dt>计划发车</dt><dd>{{ dateTime(fleetArrangement.plannedDepartureAt) }}</dd></div>
<div><dt>起运仓</dt><dd>{{ text(fleetArrangement.originWarehouseName) }}</dd></div>
<div><dt>目的地</dt><dd>{{ text(fleetArrangement.destinationLabel) }}</dd></div>
<div><dt>交货方式</dt><dd>{{ fleetArrangement.deliveryMode === 'SELF_DELIVERY' ? '自行送至起运仓' : '线下安排提货至起运仓' }}</dd></div>
<div><dt>履约进度</dt><dd>{{ poolOrderStatusLabels[fleetArrangement.fulfillmentStage] || '待核对履约进度' }}</dd></div>
<div><dt>更新时间</dt><dd>{{ dateTime(fleetArrangement.stageOccurredAt) }}</dd></div>
<div><dt>约定运费(非实收)</dt><dd>{{ money(fleetArrangement.agreedFreightAmount, fleetArrangement.currency) }}</dd></div>
<div><dt>来货单号</dt><dd>{{ text(fleetArrangement.incomingNo) }}</dd></div>
<div><dt>派送单号</dt><dd>{{ text(fleetArrangement.deliveryNo) }}</dd></div>
<div><dt>已签 / 未签 / 退回箱数</dt><dd>{{ fleetArrangement.signedPackages ?? '—' }} / {{ fleetArrangement.unsignedPackages ?? '—' }} / {{ fleetArrangement.returnedPackages ?? '—' }}</dd></div>
<div class="is-wide"><dt>交货说明</dt><dd>{{ text(fleetArrangement.deliveryInstructions) }}</dd></div>
<div v-if="fleetArrangement.exceptionSummary" class="is-wide"><dt>履约说明</dt><dd>{{ fleetArrangement.exceptionSummary }}</dd></div>
</dl>
</section>
</section>
<el-card v-else shadow="never" class="form-card"> <el-card v-else shadow="never" class="form-card">
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px"> <TransportDemandForm ref="formRef" :model="form" :kind="kind === 'trucking' ? 'truck' : 'looseboard'" :submitting="submitting" :can-submit="canCreate" @submit="submit" @cancel="returnToList" />
<template v-if="kind === 'procurement'">
<el-form-item label="采购品类" prop="purchaseCategory"><el-input v-model.trim="form.purchaseCategory" maxlength="128" placeholder="请输入采购品类" /></el-form-item>
<el-form-item label="商品名称" prop="productName"><el-input v-model.trim="form.productName" maxlength="255" placeholder="请输入商品名称" /></el-form-item>
<el-form-item label="商品规格"><el-input v-model.trim="form.productSpecification" maxlength="500" placeholder="请输入规格、型号等信息" /></el-form-item>
<el-form-item label="商品链接"><el-input v-model.trim="form.productUrl" maxlength="2000" placeholder="请输入商品链接" /></el-form-item>
<el-form-item label="采购数量" prop="purchaseQuantity"><el-input-number v-model="form.purchaseQuantity" :min="1" placeholder="请输入数量" /></el-form-item>
<el-form-item label="收货地址"><el-input v-model.trim="form.receivingAddress" maxlength="1000" placeholder="请输入收货地址" /></el-form-item>
</template>
<template v-else>
<el-form-item v-if="kind === 'looseboard'" label="运输方式"><el-radio-group v-model="form.transportMode"><el-radio-button value="SHARED_TRUCK">拼车</el-radio-button><el-radio-button value="PRIORITY_CONSOLIDATION">优先拼载</el-radio-button></el-radio-group></el-form-item>
<el-form-item v-if="kind === 'looseboard'" label="是否打盘"><el-radio-group v-model="form.palletRequired"><el-radio-button value="NO">否</el-radio-button><el-radio-button value="YES">是</el-radio-button></el-radio-group></el-form-item>
<el-form-item label="运输类型"><el-select v-model="form.transportType"><el-option label="港口提柜" value="PORT_PICKUP" /><el-option label="仓到仓" value="WAREHOUSE_TO_WAREHOUSE" /><el-option label="仓到门" value="WAREHOUSE_TO_DOOR" /></el-select></el-form-item>
<el-form-item label="起运地" prop="origin"><el-input v-model.trim="form.origin" maxlength="255" placeholder="请输入起运地" /></el-form-item>
<el-form-item label="起运地址"><el-input v-model.trim="form.originAddress" maxlength="500" placeholder="请输入详细起运地址" /></el-form-item>
<el-form-item label="目的地" prop="destination"><el-input v-model.trim="form.destination" maxlength="255" placeholder="请输入目的地" /></el-form-item>
<el-form-item label="目的地址"><el-input v-model.trim="form.destinationAddress" maxlength="500" placeholder="请输入详细目的地址" /></el-form-item>
<el-form-item label="柜型"><el-select v-model="form.containerType"><el-option v-for="item in CONTAINER_SPECIFICATIONS" :key="item.type" :label="item.type" :value="item.type" /></el-select></el-form-item>
<el-form-item v-if="kind === 'trucking'" label="托盘数" prop="palletCount"><el-input-number v-model="form.palletCount" :min="1" placeholder="请输入托盘数" /></el-form-item>
<el-form-item label="件数"><el-input-number v-model="form.packageCount" :min="0" placeholder="请输入件数" /></el-form-item>
<el-form-item label="总重量(kg)"><el-input-number v-model="form.totalWeightKg" :min="0" :precision="2" placeholder="请输入总重量" /></el-form-item>
<el-form-item label="总体积(m³)"><el-input-number v-model="form.totalVolumeCbm" :min="0" :precision="3" placeholder="请输入总体积" /></el-form-item>
<el-form-item label="要求时间" :prop="kind === 'trucking' ? 'requestedDate' : undefined"><el-date-picker v-model="form.requestedDate" type="date" value-format="YYYY-MM-DD" /></el-form-item>
</template>
<el-form-item class="budget-form-item" :label="kind === 'procurement' ? '预算单价' : '预算金额'"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2" placeholder="请输入预算金额" /><el-select v-model="form.currency" class="currency"><el-option label="USD" value="USD" /><el-option label="CNY" value="CNY" /></el-select></el-form-item>
<el-form-item label="联系人" prop="contactName"><el-input v-model.trim="form.contactName" maxlength="128" placeholder="请输入联系人" /></el-form-item>
<el-form-item label="联系方式" prop="contactInfo"><el-input v-model.trim="form.contactInfo" maxlength="128" placeholder="请输入电话、微信或邮箱" /></el-form-item>
<el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请输入其他要求" /></el-form-item>
<el-form-item><el-button @click="mode = 'list'">取消</el-button><el-button type="primary" :loading="submitting" @click="submit">提交订单</el-button></el-form-item>
</el-form>
</el-card> </el-card>
</section> </section>
</template> </template>
<style scoped> <style scoped>
.business-orders { display: grid; gap: 18px; } .business-orders { display: grid; gap: var(--client-section-gap); }
.page-head { display: flex; align-items: center; justify-content: space-between; gap: 24px; } .page-head { display: flex; align-items: center; justify-content: space-between; gap: 24px; }
.page-head h2 { margin: 0; color: #111827; font-size: 26px; } .page-head h2 { margin: 0; color: #111827; font-size: 26px; }
.page-head p { margin: 7px 0 0; color: #64748b; font-size: 14px; } .page-head p { margin: 7px 0 0; color: #64748b; font-size: 14px; }
.filter-card :deep(.el-form-item) { margin-bottom: 0; } .business-table-card { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
.filter-card :deep(.el-input) { width: 190px; } .business-order-link { max-width: 100%; overflow: hidden; padding: 0; border: 0; background: transparent; color: var(--client-action); cursor: pointer; font: inherit; font-weight: 650; text-align: left; text-overflow: ellipsis; white-space: nowrap; }
.pagination { justify-content: flex-end; margin-top: 18px; } .business-order-link:hover { text-decoration: underline; text-underline-offset: 3px; }
.detail-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 0; } .business-load-error { display: flex; min-height: 84px; align-items: center; justify-content: center; gap: 12px; padding: 14px; color: #b42318; }
.detail-grid div { min-width: 0; padding: 18px 20px; border-right: 1px solid #ebeef5; border-bottom: 1px solid #ebeef5; } .business-detail-error { display: flex; min-height: 180px; align-items: center; justify-content: center; gap: 12px; color: #b42318; }
.detail-grid dt { margin-bottom: 7px; color: #8492a6; font-size: 13px; } .business-detail-page { min-width: 0; padding: 10px 14px 20px; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
.detail-grid dd { margin: 0; overflow-wrap: anywhere; color: #1f2937; line-height: 1.55; } .business-detail-heading { display: flex; min-height: 50px; align-items: center; justify-content: space-between; gap: 16px; padding: 5px 0; border-bottom: 1px solid var(--border); }
.form-card :deep(.el-form) { max-width: 860px; } .business-detail-heading-main { display: flex; min-width: 0; align-items: center; gap: 12px; }
.form-card :deep(.el-input), .form-card :deep(.el-textarea), .form-card :deep(.el-select) { width: 100%; } .business-detail-heading-main > div { min-width: 0; }
.form-card .currency { width: 110px; margin-left: 12px; } .business-detail-heading-actions { display: flex; align-items: center; gap: 12px; flex: 0 0 auto; }
.business-detail-heading h2 { margin: 0; overflow: hidden; color: var(--navy); font-size: 18px; text-overflow: ellipsis; white-space: nowrap; }
.business-detail-heading p { margin: 3px 0 0; color: var(--muted); font-size: 11px; }
.business-detail-section { margin-top: 10px; }
.business-detail-section h3 { margin: 0; padding: 0 0 5px; border-bottom: 1px solid #eaf0f7; color: var(--navy); font-size: 13px; }
.detail-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin: 0; border-top: 1px solid var(--border); border-left: 1px solid var(--border); }
.detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 76px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
.trucking-detail-grid div { grid-template-columns: 112px minmax(0, 1fr); }
.detail-grid div.is-wide { grid-column: span 2; }
.detail-grid div.is-full { grid-column: 1 / -1; }
.looseboard-detail-grid { grid-auto-flow: row dense; }
.detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
.arrangement-grid div { grid-template-columns: 124px minmax(0, 1fr); }
.arrangement-grid dt { white-space: normal; overflow-wrap: anywhere; }
.detail-grid dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--navy); font-size: 12px; font-weight: 600; line-height: 1.4; }
.form-card :deep(.el-card__body) { padding: 0; }
.business-orders--create { --client-action: #2f7bff; --client-action-hover: #1d5fe0; --client-border: #d5dce8; --client-control-height: 44px; --client-font-size: 14px; width: 100%; min-width: 0; gap: 12px; background: #f4f7fc; }
.business-orders--create .page-head { flex-wrap: wrap; gap: 16px; }
.business-orders--create .page-head h2 { color: #1f2937; font-weight: 700; }
.business-orders--create .page-head :deep(.el-button) { height: auto; min-height: 44px; padding: 10px 18px; border-radius: 6px; color: #1d5fe0; font-size: 14px; box-shadow: none; }
.business-orders--create .form-card { min-width: 0; overflow: visible; border: 0; border-radius: 0; background: transparent; box-shadow: none; }
/* The detail page is intentionally calmer than the list: the order identity is
separated from the data grid, while values remain easy to scan at desktop size. */
.business-detail-page { padding: 18px 20px 24px; border-color: #dbe4ef; border-radius: 10px; box-shadow: 0 2px 8px rgb(15 42 74 / 4%); }
.business-detail-heading { min-height: 58px; padding: 0 0 14px; border-bottom-color: #e5ebf3; }
.business-detail-heading-main { gap: 18px; }
.business-detail-heading-main :deep(.el-button) { padding: 0; font-size: 14px; }
.business-detail-heading h2 { font-size: 22px; letter-spacing: .01em; }
.business-detail-section { margin-top: 20px; }
.business-detail-section h3 { padding: 0 0 10px; border-bottom: 0; font-size: 15px; }
.detail-grid { border-color: #e2e8f0; }
.detail-grid div { min-height: 46px; gap: 12px; padding: 8px 14px; background: #fff; border-color: #e2e8f0; }
.detail-grid dt { color: #718096; font-size: 12px; }
.detail-grid dd { color: #1f3552; font-size: 14px; font-weight: 600; }
.arrangement-grid { background: #f8fafc; }
@media (max-width: 767px) { @media (max-width: 767px) {
.business-orders { gap: 14px; } .business-orders { gap: 14px; }
@@ -368,15 +442,11 @@ onMounted(() => void load())
.page-head h2 { font-size: 24px; } .page-head h2 { font-size: 24px; }
.page-head > div { min-width: 0; } .page-head > div { min-width: 0; }
.filter-card :deep(.el-form) { display: grid; grid-template-columns: 1fr; }
.filter-card :deep(.el-form-item) { width: 100%; margin-right: 0; margin-bottom: 12px; }
.filter-card :deep(.el-form-item:last-child) { margin-bottom: 0; }
.filter-card :deep(.el-form-item__content),
.filter-card :deep(.el-input) { width: 100%; }
.detail-grid { grid-template-columns: 1fr; } .detail-grid { grid-template-columns: 1fr; }
.detail-grid div { padding: 14px 16px; border-right: 0; } .detail-grid div, .detail-grid div.is-wide { grid-column: auto; }
.detail-grid dd { overflow-wrap: break-word; word-break: normal; } .detail-grid dd { overflow-wrap: break-word; word-break: normal; }
.business-detail-heading { align-items: flex-start; flex-direction: column; }
.business-detail-heading-actions { width: 100%; justify-content: space-between; }
.form-card :deep(.el-form-item) { display: block; } .form-card :deep(.el-form-item) { display: block; }
.form-card :deep(.el-form-item__label) { .form-card :deep(.el-form-item__label) {
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { onActivated, onBeforeUnmount, onDeactivated, ref, watch } from 'vue'
import { readOrderFunding, retryOrderFunding } from '../api/orderBudgets'
import { getBusinessOrder, type TransportDetail } from '../api/businessOrders'
const props = defineProps<{ kind: 'procurement' | 'trucking'; orderNo: string; status: string; canRetry: boolean; compact?: boolean }>()
const emit = defineEmits<{ changed: [] }>()
const message = ref(''), busy = ref(false)
let generation = 0, timer: ReturnType<typeof setTimeout> | undefined
let active = true
// 自动核对订单受理中状态;离开详情或切换订单时丢弃旧响应。
watch(() => [props.kind, props.orderNo, props.status], () => {
generation++; clearTimeout(timer); message.value = ''; busy.value = false
if (active && (['FUNDING_PENDING', 'FUNDING_FAILED'].includes(props.status) || (props.kind === 'trucking' && props.status === 'REJECTED'))) void check(generation, 0)
}, { immediate: true })
async function check(sequence: number, count: number) {
try {
// 卡车审核拒绝原因来自审核历史,不使用客户填写的订单备注。
if (props.kind === 'trucking' && props.status === 'REJECTED') {
const detail = await getBusinessOrder<TransportDetail>('trucking', props.orderNo)
if (sequence !== generation) return
const rejection = [...(detail.histories || [])].reverse().find(item => item.operationType === 'REVIEW' && item.toStatus === 'REJECTED')
message.value = rejection?.remark?.trim() || '未填写拒绝原因'
return
}
const result = await readOrderFunding(props.kind, props.orderNo)
if (sequence !== generation) return
message.value = result.status === 'FREEZE_PENDING' ? '订单受理中,处理完成后将自动进入待审核。' : result.message || (result.status === 'FAILED' ? '订单处理失败,请联系平台核对原因' : '')
if (result.status === 'FROZEN' || (result.status === 'FAILED' && props.status === 'FUNDING_PENDING') || (result.status === 'FREEZE_PENDING' && props.status === 'FUNDING_FAILED')) emit('changed')
else if (result.status === 'FREEZE_PENDING' && count < 30) timer = setTimeout(() => void check(sequence, count + 1), 2000)
} catch (cause) {
if (sequence === generation) message.value = cause instanceof Error ? cause.message : '处理原因读取失败,请刷新重试'
}
}
async function retry() {
if (!active || busy.value || !props.canRetry || props.status !== 'FUNDING_FAILED') return
const sequence = generation; busy.value = true
try {
await retryOrderFunding(props.kind, props.orderNo)
if (sequence === generation) emit('changed')
} catch (cause) {
if (sequence === generation) message.value = cause instanceof Error ? cause.message : '重试未完成,请稍后再试'
} finally { if (sequence === generation) busy.value = false }
}
function stop() { active = false; generation++; clearTimeout(timer) }
onDeactivated(stop)
onBeforeUnmount(stop)
onActivated(() => {
if (active) return
active = true; busy.value = false
if (['FUNDING_PENDING', 'FUNDING_FAILED'].includes(props.status) || (props.kind === 'trucking' && props.status === 'REJECTED')) void check(++generation, 0)
})
</script>
<template>
<div v-if="['FUNDING_PENDING', 'FUNDING_FAILED'].includes(status) || (kind === 'trucking' && status === 'REJECTED')" role="status" aria-live="polite">
<span v-if="compact">{{ message || '正在读取处理失败原因…' }}</span>
<template v-else>
<el-alert :type="status === 'FUNDING_PENDING' ? 'info' : 'error'" :closable="false" :title="status === 'REJECTED' ? '订单已拒绝' : status === 'FUNDING_FAILED' ? '订单处理失败' : '订单受理中'" :description="message" />
<el-button v-if="status === 'FUNDING_FAILED' && canRetry" :loading="busy" @click="retry">重新处理订单</el-button>
</template>
</div>
</template>
@@ -0,0 +1,97 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, shallowRef } from 'vue'
import { ElMessage } from 'element-plus'
import { accessTokenIdentity } from '@/api/session'
import { useAuthStore } from '@/modules/auth/public'
import { confirmProcurement, rejectProcurement, getProcurementWorkflow, getProcurementFile, type ProcurementSummary, type ProcurementWorkflow } from '../api/procurement'
import { procurementRequestKey } from '../procurementSubmission'
import { dateTime } from '../procurementPresentation'
const props = defineProps<{ order: ProcurementSummary; decision: 'confirm' | 'reject' }>()
const emit = defineEmits<{ close: []; changed: [] }>()
const auth = useAuthStore()
const owner = auth.token ? accessTokenIdentity(auth.token) : null
const current = () => active && !!owner && owner === (auth.token ? accessTokenIdentity(auth.token) : null)
const workflow = shallowRef<ProcurementWorkflow | null>(null)
const loading = ref(false), saving = ref(false), error = ref(''), photoError = ref(''), reason = ref('')
const photos = ref<Record<string, string>>({})
const isReject = computed(() => props.decision === 'reject')
const canSubmit = computed(() => !loading.value && workflow.value?.status === 'WAIT_CUSTOMER_CONFIRM' && auth.hasPermission('merchant:cross-border:procurement:create'))
let active = true, generation = 0, attempt: { fingerprint: string; key: string } | null = null
function clearPhotos() { Object.values(photos.value).forEach(url => URL.revokeObjectURL(url)); photos.value = {} }
async function load() {
if (loading.value || saving.value || !current()) return
const sequence = ++generation
loading.value = true; error.value = ''; photoError.value = ''; workflow.value = null; clearPhotos()
try {
const result = await getProcurementWorkflow(props.order.orderNo)
if (!current() || sequence !== generation) return
workflow.value = result
if (result.status !== 'WAIT_CUSTOMER_CONFIRM') { error.value = '订单状态已更新,当前不能确认或驳回,请返回列表刷新'; return }
const ids = [...new Set(result.receipts.flatMap(receipt => receipt.fileIds))]
await Promise.all(ids.map(async id => {
try {
const blob = await getProcurementFile(props.order.orderNo, id)
if (!current() || sequence !== generation) return
if (!/^image\/(png|jpeg|gif|webp|bmp)$/i.test(blob.type)) throw new Error('附件不是可预览的收货照片')
photos.value[id] = URL.createObjectURL(blob)
} catch { if (current() && sequence === generation) photoError.value = '部分收货照片加载失败,请重新加载后核对' }
}))
} catch (cause) { if (current() && sequence === generation) error.value = cause instanceof Error ? cause.message : '采购结果加载失败' }
finally { if (current() && sequence === generation) loading.value = false }
}
function fileName(id: string) { return workflow.value?.files?.find(file => file.fileId === id)?.fileName || '收货照片' }
async function submitDecision() {
if (saving.value || !current() || !canSubmit.value || !!photoError.value || !workflow.value) return
if (isReject.value && (!reason.value.trim() || reason.value.trim().length > 1000)) { error.value = '请填写驳回原因,最多1000字'; return }
const version = workflow.value.version, orderNo = props.order.orderNo
const fingerprint = JSON.stringify([owner, orderNo, version, props.decision, isReject.value ? reason.value.trim() : ''])
if (attempt?.fingerprint !== fingerprint) attempt = { fingerprint, key: procurementRequestKey() }
saving.value = true; error.value = ''
try {
const data = { version, idempotencyKey: attempt.key }
if (isReject.value) await rejectProcurement(orderNo, { ...data, reason: reason.value.trim() })
else await confirmProcurement(orderNo, data)
if (!current()) return
ElMessage.success(isReject.value ? '已驳回,等待平台重新上传照片' : '采购结果已确认')
emit('changed')
} catch (cause) { if (current()) error.value = cause instanceof Error ? cause.message : '操作失败,请重试' }
finally { saving.value = false }
}
onBeforeUnmount(() => { active = false; generation++; clearPhotos() })
void load()
</script>
<template>
<el-dialog :model-value="true" :title="isReject ? '驳回采购结果' : '确认采购结果'" width="800px" append-to-body :close-on-click-modal="false" :close-on-press-escape="!saving" :show-close="!saving" @close="!saving && emit('close')">
<div v-loading="loading" class="decision-content">
<dl class="decision-quantities"><div><dt>采购单号</dt><dd>{{ order.orderNo }}</dd></div><div><dt>商品名称</dt><dd>{{ order.productName }}</dd></div><div><dt>采购数量</dt><dd>{{ order.purchaseQuantity }} 件</dd></div><div><dt>累计收货数量</dt><dd>{{ workflow?.receivedQuantity ?? '—' }} 件</dd></div></dl>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<el-alert v-if="photoError" :title="photoError" type="error" :closable="false" />
<el-button v-if="error || photoError" :disabled="saving || loading" @click="load">重新加载</el-button>
<div class="decision-batches">
<section v-for="(receipt, index) in workflow?.receipts || []" :key="receipt.id" class="decision-batch">
<h3>第 {{ index + 1 }} 批:{{ receipt.quantity }} 件 <small>{{ dateTime(receipt.receivedAt) }}</small></h3>
<div class="decision-photos"><el-image v-for="id in receipt.fileIds" :key="id" :src="photos[id]" :alt="fileName(id)" :preview-src-list="Object.values(photos)" :initial-index="Object.keys(photos).indexOf(id)" fit="contain" preview-teleported><template #error><span>{{ fileName(id) }}:{{ loading ? '加载中' : '照片未加载' }}</span></template></el-image></div>
</section>
</div>
<p v-if="workflow && !workflow.receipts.length">暂无收货照片</p>
<el-form v-if="isReject" label-position="top" :disabled="saving"><el-form-item label="驳回原因" required><el-input v-model="reason" type="textarea" :rows="3" maxlength="1000" show-word-limit placeholder="请填写采购结果不符合要求的原因" /></el-form-item></el-form>
<p v-else>请核对采购数量和收货照片,确认后平台将安排出库。</p>
</div>
<template #footer><el-button :disabled="saving" @click="emit('close')">取消</el-button><el-button :type="isReject ? 'danger' : 'primary'" :loading="saving" :disabled="!canSubmit || !!photoError" @click="submitDecision">{{ isReject ? '提交驳回' : '确认采购结果' }}</el-button></template>
</el-dialog>
</template>
<style scoped>
.decision-content { min-height: 160px; }
.decision-quantities { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 0 0 16px; }
.decision-quantities > div { display: flex; gap: 12px; min-width: 0; }
dt { color: var(--muted); } dd { margin: 0; overflow-wrap: anywhere; }
.decision-batches { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin: 16px 0; }
.decision-batch { min-width: 0; }
h3 { margin: 0 0 8px; color: var(--navy); font-size: 14px; } small { display: block; margin-top: 4px; color: var(--muted); font-weight: 400; }
.decision-photos { display: flex; flex-direction: row; flex-wrap: nowrap; align-items: center; gap: 8px; overflow-x: auto; padding: 2px 0 6px; }
.decision-photos :deep(.el-image) { flex: 0 0 112px; width: 112px; height: 84px; border: 1px solid var(--border); border-radius: 4px; }
.decision-photos span { padding: 12px; overflow-wrap: anywhere; }
</style>
@@ -0,0 +1,107 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { getProcurementFile, type ProcurementDetail, type ProcurementFee, type ProcurementWorkflow } from '../api/procurement'
import { directionLabel, dateTime, feeStatus, feeTone, feeTotals, money, productHref, statusLabel, text } from '../procurementPresentation'
const props = defineProps<{ detail: ProcurementDetail; workflow: ProcurementWorkflow }>()
const previewUrl = ref(''), previewName = ref(''), previewImage = ref(false), fileLoading = ref(''), fileError = ref('')
let active = true
function clearPreview() { if (previewUrl.value) URL.revokeObjectURL(previewUrl.value); previewUrl.value = '' }
function fileName(fileId: string, index: string | number) { return props.workflow.files.find(file => file.fileId === fileId)?.fileName || '附件 ' + (Number(index) + 1) }
async function openFile(fileId: string) {
if (fileLoading.value) return
fileLoading.value = fileId; fileError.value = ''
try {
const blob = await getProcurementFile(props.workflow.orderNo, fileId)
if (!active) return
clearPreview(); previewUrl.value = URL.createObjectURL(blob)
previewName.value = props.workflow.files.find(file => file.fileId === fileId)?.fileName || '附件'
previewImage.value = /^image\/(png|jpeg|gif|webp|bmp)$/i.test(blob.type)
} catch (cause) { if (active) fileError.value = cause instanceof Error ? cause.message : '附件加载失败' }
finally { fileLoading.value = '' }
}
onBeforeUnmount(() => { active = false; clearPreview() })
const totals = computed(() => feeTotals(props.detail.fees))
</script>
<template>
<el-alert v-if="fileError" :title="fileError" type="error" :closable="false" />
<section class="procurement-section" aria-label="采购数量统计">
<dl class="procurement-grid money-grid">
<div><dt>累计收货</dt><dd>{{ workflow.receivedQuantity }} 件</dd></div>
<div><dt>采购库存</dt><dd>{{ workflow.stockQuantity }} 件</dd></div>
<div><dt>出库处理中</dt><dd>{{ workflow.reservedQuantity }} 件</dd></div>
<div><dt>可出库</dt><dd>{{ workflow.availableQuantity }} 件</dd></div>
</dl>
</section>
<section class="procurement-section" aria-label="分批收货">
<h3>收货记录</h3>
<el-table :data="workflow.receipts" border stripe empty-text="暂无收货记录" row-key="id">
<el-table-column label="批次" width="80" align="center"><template #default="{ $index }">{{ $index + 1 }}</template></el-table-column>
<el-table-column prop="quantity" label="收货数量(件)" width="145" align="right" />
<el-table-column label="收货时间" width="185"><template #default="{ row }">{{ dateTime(row.receivedAt) }}</template></el-table-column>
<el-table-column label="收货照片" min-width="160"><template #default="{ row }"><span v-if="!row.fileIds.length">—</span><el-button v-for="(fileId, index) in row.fileIds" :key="fileId" link type="primary" :loading="fileLoading === fileId" :disabled="!!fileLoading" @click="openFile(fileId)">{{ fileName(fileId, index) }}</el-button></template></el-table-column>
</el-table>
</section>
<section class="procurement-section" aria-label="分批出库">
<h3>出库记录</h3>
<el-table :data="workflow.outbounds.filter(row => row.status !== 'IN_TRANSIT' && row.status !== 'CANCELLED')" border stripe empty-text="暂无出库记录" row-key="id">
<el-table-column prop="outboundNo" label="出库单号" min-width="180" />
<el-table-column prop="quantity" label="出库数量(件)" width="145" align="right" />
<el-table-column prop="trackingNo" label="物流跟踪号" min-width="160" />
<el-table-column label="状态" width="100" align="center"><template #default="{ row }">{{ statusLabel(row.status) }}</template></el-table-column>
<el-table-column label="创建时间" width="185"><template #default="{ row }">{{ dateTime(row.createdAt) }}</template></el-table-column>
<el-table-column label="签收时间" width="185"><template #default="{ row }">{{ dateTime(row.completedAt) }}</template></el-table-column>
<el-table-column label="签收凭证" min-width="220"><template #default="{ row }"><span v-if="!row.fileIds.length">—</span><el-button v-for="(fileId, index) in row.fileIds" :key="fileId" link type="primary" :loading="fileLoading === fileId" :disabled="!!fileLoading" @click="openFile(fileId)">{{ fileName(fileId, index) }}</el-button></template></el-table-column>
</el-table>
</section>
<section class="procurement-section" aria-label="费用明细">
<h3>费用明细 <span class="fee-total">已扣款 {{ money(totals?.net) }}</span></h3>
<el-table :data="detail.fees" border stripe empty-text="暂无费用" row-key="feeNo">
<el-table-column prop="name" label="费用名称" min-width="180" />
<el-table-column label="原币金额" min-width="145" align="right"><template #default="{ row }">{{ money(row.originalAmount, row.originalCurrency) }}</template></el-table-column>
<el-table-column label="人民币金额" min-width="145" align="right"><template #default="{ row }">{{ money(row.amount) }}</template></el-table-column>
<el-table-column label="扣款结果" min-width="160" align="center"><template #default="{ row }"><el-tag :type="feeTone(row as ProcurementFee)" size="small">{{ feeStatus(row as ProcurementFee) }}</el-tag></template></el-table-column>
</el-table>
</section>
<section class="procurement-section" aria-label="商品与收件信息">
<h3>商品与收件信息</h3>
<dl class="procurement-grid">
<div><dt>采购方向</dt><dd>{{ directionLabel(detail.order.procurementDirection) }}</dd></div>
<div><dt>商品名称</dt><dd>{{ detail.order.productName }}</dd></div>
<div><dt>商品规格</dt><dd>{{ text(detail.order.productSpecification) }}</dd></div>
<div><dt>采购品类</dt><dd>{{ text(detail.order.purchaseCategory) }}</dd></div>
<div><dt>采购数量</dt><dd>{{ detail.order.purchaseQuantity }} 件</dd></div>
<div><dt>预算单价</dt><dd>{{ money(detail.order.budgetUnitPrice, detail.order.currency) }}</dd></div>
<div><dt>预算合计</dt><dd>{{ money(detail.budget.totalAmount, detail.budget.currency) }}</dd></div>
<div><dt>采购仓</dt><dd>{{ detail.order.actualWarehouseName || detail.order.plannedWarehouseName || '待审核指定' }}<span v-if="detail.order.actualWarehouseCode">({{ detail.order.actualWarehouseCode }})</span></dd></div>
<div><dt>收件人</dt><dd>{{ detail.order.contactName }}</dd></div>
<div><dt>联系电话</dt><dd>{{ detail.order.contactPhone }}</dd></div>
<div class="wide"><dt>收货地址</dt><dd>{{ detail.order.receivingAddress }}</dd></div>
<div v-if="detail.order.remark" class="full"><dt>采购备注</dt><dd>{{ detail.order.remark }}</dd></div>
<div v-if="detail.order.productUrl" class="full"><dt>商品链接</dt><dd><a v-if="productHref(detail.order.productUrl)" :href="productHref(detail.order.productUrl)" target="_blank" rel="noopener noreferrer">查看商品</a><span v-else>{{ text(detail.order.productUrl) }}</span></dd></div>
</dl>
</section>
<el-dialog :model-value="!!previewUrl" :title="previewName" width="800px" append-to-body @close="clearPreview">
<img v-if="previewImage" :src="previewUrl" :alt="previewName" style="display: block; max-width: 100%; max-height: 70vh; margin: auto" />
<a v-else :href="previewUrl" :download="previewName">下载 {{ previewName }}</a>
</el-dialog>
</template>
<style scoped>
.procurement-section { margin-top: 18px; min-width: 0; }
.fee-total { margin-left: 14px; font-weight: 400; font-size: 12px; color: var(--muted); }
h3 { margin: 0 0 10px; padding-bottom: 7px; border-bottom: 1px solid var(--border); color: var(--navy); font-size: 14px; }
.procurement-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin: 0; border-left: 1px solid var(--border); border-top: 1px solid var(--border); }
.procurement-grid > div { display: grid; grid-template-columns: 110px minmax(0, 1fr); align-items: center; gap: 8px; padding: 9px 12px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); min-width: 0; }
.procurement-grid dt { font-size: 12px; color: var(--muted); }.procurement-grid dd { margin: 0; font-size: 13px; line-height: 1.6; color: var(--navy); overflow-wrap: anywhere; }
.procurement-grid .wide { grid-column: span 2; }.money-grid { gap: 16px; border: 0; }.money-grid > div { grid-template-columns: minmax(0, 1fr); padding: 18px; border: 1px solid var(--border); border-radius: 8px; background: #f8fbff; }.money-grid dd { font-size: 16px; font-weight: 600; }
.procurement-grid .full { grid-column: 1 / -1; }
.procurement-section :deep(.el-table .cell) { overflow-wrap: anywhere; font-variant-numeric: tabular-nums; }
.procurement-section :deep(.el-table .el-button.is-link) { display: flex; justify-content: flex-start; max-width: 100%; height: auto; margin: 0; padding: 3px 0; white-space: normal; text-align: left; }
.procurement-section :deep(.el-table .el-button.is-link > span) { min-width: 0; overflow-wrap: anywhere; }
a { color: var(--client-action); }
@media (max-width: 767px) {
.procurement-grid { grid-template-columns: 1fr; }.procurement-grid .wide { grid-column: auto; }
}
</style>
@@ -0,0 +1,167 @@
<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/api/firstLeg'
import type { FormInstance } from 'element-plus'
import { transportDemandRules, type TransportDemandForm, type TransportDemandKind } from '../transportDemandForm'
const props = withDefaults(defineProps<{
model: TransportDemandForm
kind: TransportDemandKind
disabled?: boolean
submitting?: boolean
canSubmit?: boolean
editing?: boolean
}>(), { disabled: false, submitting: false, canSubmit: true, editing: false })
const emit = defineEmits<{ submit: []; cancel: [] }>()
const formRef = ref<FormInstance>()
const warehouses = ref<MerchantWarehouse[]>([]), warehouseError = ref(''), warehouseLoading = ref(false)
async function loadWarehouses() {
if (props.kind !== 'looseboard') return
warehouseLoading.value = true; warehouseError.value = ''
try { warehouses.value = (await getMerchantWarehouses({ warehouseType: 'OVERSEAS', status: 'ACTIVE', size: 200 })).records }
catch (cause) { warehouseError.value = cause instanceof Error ? cause.message : '仓库读取失败' }
finally { warehouseLoading.value = false }
}
function chooseWarehouse() {
const warehouse = warehouses.value.find(row => String(row.id) === String(props.model.operatingWarehouseId))
props.model.deliveryContactName = warehouse?.contactName || ''; props.model.deliveryContactPhone = warehouse?.contactPhone || ''
}
onMounted(loadWarehouses)
watch([() => props.model.operatingWarehouseId, warehouses], chooseWarehouse, { immediate: true })
const rules = computed(() => transportDemandRules(props.kind, props.model))
const isCreate = computed(() => !props.editing)
const createPopperClass = computed(() => isCreate.value ? 'transport-create-popper' : undefined)
defineExpose({
validate: () => formRef.value?.validate() ?? Promise.resolve(false),
clearValidate: (fields?: string | string[]) => formRef.value?.clearValidate(fields),
})
</script>
<template>
<el-form ref="formRef" class="transport-demand-form" :class="{ 'transport-demand-form--create': isCreate }" :model="model" :rules="rules" label-position="top" :disabled="disabled || submitting">
<slot name="customer" />
<section v-if="kind === 'looseboard'" class="transport-demand-section">
<h3>入仓安排</h3>
<div class="transport-demand-grid">
<el-form-item class="transport-demand-wide" label="送货方式" prop="deliveryMode"><el-radio-group v-model="model.deliveryMode"><el-radio-button value="DELIVERY_TO_WAREHOUSE">送货到仓</el-radio-button><el-radio-button value="WAREHOUSE_PICKUP">仓库上门取货</el-radio-button></el-radio-group></el-form-item>
<el-form-item label="收货仓库" prop="operatingWarehouseId"><el-select v-model="model.operatingWarehouseId" :loading="warehouseLoading" filterable placeholder="请选择收货仓库"><el-option v-for="warehouse in warehouses" :key="String(warehouse.id)" :value="String(warehouse.id)" :label="warehouse.warehouseName" /></el-select><span v-if="warehouseError" role="alert">{{ warehouseError }} <el-button link @click="loadWarehouses">重试</el-button></span></el-form-item>
<template v-if="model.deliveryMode === 'DELIVERY_TO_WAREHOUSE'">
<el-form-item label="到仓联系人" prop="deliveryContactName"><el-input v-model="model.deliveryContactName" readonly placeholder="随收货仓库带出,未维护请联系仓库" /></el-form-item>
<el-form-item label="到仓联系电话" prop="deliveryContactPhone"><el-input v-model="model.deliveryContactPhone" readonly placeholder="随收货仓库带出,未维护请联系仓库" /></el-form-item>
<el-form-item label="预计到货时间" prop="estimatedArrivalAt"><el-date-picker v-model="model.estimatedArrivalAt" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" format="YYYY-MM-DD HH:mm" /></el-form-item>
<el-form-item label="物流跟踪号" prop="trackingNo"><el-input v-model.trim="model.trackingNo" maxlength="255" /></el-form-item>
</template>
</div>
</section>
<section class="transport-demand-section">
<h3>运输信息</h3>
<div class="transport-demand-grid transport-demand-route-grid">
<el-form-item v-if="kind === 'looseboard' && model.destinationType === 'PRIVATE'" label="目的地邮编" prop="destinationPostalCode"><el-input v-model.trim="model.destinationPostalCode" maxlength="32" /></el-form-item>
<el-form-item v-if="kind === 'truck'" class="transport-demand-wide transport-demand-vehicle" label="车辆类型" prop="vehicleType">
<el-select v-model="model.vehicleType" :popper-class="createPopperClass" :placeholder="isCreate ? '请选择车辆类型' : ''"><el-option label="15拖" value="PALLET_15" /><el-option label="30拖" value="PALLET_30" /></el-select>
</el-form-item>
<el-form-item v-if="kind === 'truck' || model.deliveryMode === 'WAREHOUSE_PICKUP'" :label="kind === 'truck' ? '取货地' : '起运地'" prop="origin"><el-input v-model.trim="model.origin" maxlength="255" placeholder="城市 / 港口 / 州" /></el-form-item>
<el-form-item v-if="!isCreate" :label="kind === 'truck' ? '送达地' : '目的地'" prop="destination"><el-input v-model.trim="model.destination" maxlength="255" placeholder="城市 / 州" /></el-form-item>
<el-form-item v-if="kind === 'truck' || model.deliveryMode === 'WAREHOUSE_PICKUP'" :label="kind === 'truck' ? '取货联系人' : '起运地联系人'" prop="originContactName"><el-input v-model.trim="model.originContactName" maxlength="128" :placeholder="isCreate ? (kind === 'truck' ? '请输入取货联系人姓名' : '请输入起运地联系人姓名') : ''" /></el-form-item>
<el-form-item v-if="!isCreate" :label="kind === 'truck' ? '送达联系人' : '目的地联系人'" prop="destinationContactName"><el-input v-model.trim="model.destinationContactName" maxlength="128" placeholder="" /></el-form-item>
<el-form-item v-if="kind === 'truck' || model.deliveryMode === 'WAREHOUSE_PICKUP'" :label="kind === 'truck' ? '取货联系电话' : '起运地联系电话'" prop="originContactPhone"><el-input v-model.trim="model.originContactPhone" type="tel" maxlength="128" :placeholder="isCreate ? (kind === 'truck' ? '请输入取货联系电话' : '请输入起运地联系电话') : ''" /></el-form-item>
<template v-if="isCreate">
<el-form-item :label="kind === 'truck' ? '送达地' : '目的地'" prop="destination"><el-input v-model.trim="model.destination" maxlength="255" placeholder="城市 / 州" /></el-form-item>
<el-form-item :label="kind === 'truck' ? '送达联系人' : '目的地联系人'" prop="destinationContactName"><el-input v-model.trim="model.destinationContactName" maxlength="128" :placeholder="kind === 'truck' ? '请输入送达联系人姓名' : '请输入目的地联系人姓名'" /></el-form-item>
</template>
<el-form-item :label="kind === 'truck' ? '送达联系电话' : '目的地联系电话'" prop="destinationContactPhone"><el-input v-model.trim="model.destinationContactPhone" type="tel" maxlength="128" :placeholder="isCreate ? (kind === 'truck' ? '请输入送达联系电话' : '请输入目的地联系电话') : ''" /></el-form-item>
<el-form-item v-if="kind === 'truck' || model.deliveryMode === 'WAREHOUSE_PICKUP'" class="transport-demand-address" :label="kind === 'truck' ? '取货地址' : '起运详细地址'" prop="originAddress"><el-input v-model.trim="model.originAddress" maxlength="500" placeholder="请输入详细地址" /></el-form-item>
<el-form-item class="transport-demand-address" :label="kind === 'truck' ? '送达地址' : '目的详细地址'" prop="destinationAddress"><el-input v-model.trim="model.destinationAddress" maxlength="500" :placeholder="kind === 'truck' ? '请输入详细地址' : model.destinationType === 'PRIVATE' ? '请输入目的详细地址' : '街道 / 门牌等补充信息(选填)'" /></el-form-item>
</div>
</section>
<section class="transport-demand-section">
<h3>货物信息</h3>
<div class="transport-demand-grid" :class="kind === 'looseboard' && !isCreate ? 'transport-demand-cargo-four' : 'transport-demand-cargo-three'">
<el-form-item v-if="kind === 'looseboard'" label="商品名称"><el-input v-model.trim="model.productName" maxlength="255" :placeholder="isCreate ? '请输入商品名称(选填)' : ''" /></el-form-item>
<el-form-item v-if="kind === 'looseboard'" label="预计托数" prop="estimatedPalletCount"><el-input-number v-model="model.estimatedPalletCount" :min="0" :precision="0" controls-position="right" :placeholder="isCreate ? '请输入预计托数' : ''" /></el-form-item>
<el-form-item v-if="kind === 'truck'" label="托数" prop="estimatedPalletCount"><el-input-number v-model="model.estimatedPalletCount" :min="1" :precision="0" controls-position="right" :placeholder="isCreate ? '请输入托数' : ''" /></el-form-item>
<el-form-item label="总重量 (kg)" prop="totalWeightKg"><el-input-number v-model="model.totalWeightKg" :min="0" :precision="3" controls-position="right" :placeholder="isCreate ? '请输入总重量' : ''" /></el-form-item>
<el-form-item label="总体积 (m³)" prop="totalVolumeCbm"><el-input-number v-model="model.totalVolumeCbm" :min="0" :precision="6" controls-position="right" :placeholder="isCreate ? '请输入总体积' : ''" /></el-form-item>
<el-form-item v-if="kind === 'looseboard'" label="件数" prop="packageCount"><el-input-number v-model="model.packageCount" :min="0" :precision="0" controls-position="right" :placeholder="isCreate ? '请输入件数' : ''" /></el-form-item>
</div>
</section>
<section class="transport-demand-section">
<h3>费用与时效</h3>
<div class="transport-demand-grid">
<el-form-item label="预算总价" prop="budgetAmount"><div class="transport-demand-budget">
<el-input-number v-model="model.budgetAmount" :min="0" :precision="2" controls-position="right" :placeholder="isCreate ? (kind === 'truck' ? '请输入预算总价' : '请输入预算总价(选填)') : ''" />
<el-select v-model="model.currency" :popper-class="createPopperClass" aria-label="预算币种" placeholder=""><el-option label="USD" value="USD" /><el-option label="CNY" value="CNY" /></el-select>
</div></el-form-item>
<div />
<el-form-item :label="kind === 'truck' ? '取货时间' : '取货时间'" prop="pickupAt"><el-date-picker v-model="model.pickupAt" :popper-class="createPopperClass" type="datetime" format="YYYY-MM-DD HH:mm" time-format="HH:mm" value-format="YYYY-MM-DDTHH:mm:ss" :placeholder="isCreate ? '请选择取货日期和时间' : ''" @change="formRef?.validateField('deliveryAt').catch(() => undefined)" /></el-form-item>
<el-form-item :label="kind === 'truck' ? '送达时间' : '送货时间'" prop="deliveryAt"><el-date-picker v-model="model.deliveryAt" :popper-class="createPopperClass" type="datetime" format="YYYY-MM-DD HH:mm" time-format="HH:mm" value-format="YYYY-MM-DDTHH:mm:ss" :placeholder="isCreate ? (kind === 'truck' ? '请选择送达日期和时间' : '请选择送货日期和时间') : ''" /></el-form-item>
<el-form-item class="transport-demand-wide" label="备注"><el-input v-model="model.remark" type="textarea" :rows="3" maxlength="1000" :show-word-limit="!isCreate" :placeholder="isCreate ? '请输入运输要求或其他补充信息(选填)' : ''" /><span v-if="isCreate" class="transport-demand-character-count">{{ model.remark.length }} / 1000</span></el-form-item>
</div>
</section>
<footer class="transport-demand-actions">
<el-button v-if="!isCreate" :disabled="submitting" @click="emit('cancel')">取消</el-button>
<el-button v-if="canSubmit" type="primary" :loading="submitting" :disabled="disabled" @click="emit('submit')">{{ editing ? '保存修改' : '提交订单' }}</el-button>
</footer>
</el-form>
</template>
<style scoped>
.transport-demand-form { --el-component-size: 36px; width: 100%; max-width: 1180px; margin: 0; background: #fff; }
.transport-demand-section { padding: 20px 24px 0; border-bottom: 1px solid #e7ebf1; }
.transport-demand-section h3 { margin: 0 0 16px; color: #27364d; font-size: 14px; font-weight: 600; }
.transport-demand-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 24px; }
.transport-demand-cargo-three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.transport-demand-cargo-four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.transport-demand-wide { grid-column: 1 / -1; }
.transport-demand-form :deep(.el-form-item) { min-width: 0; margin-bottom: 18px; }
.transport-demand-form :deep(.el-form-item__label) { height: auto; padding-bottom: 6px; font-size: 13px; line-height: 20px; }
.transport-demand-form :deep(.el-input), .transport-demand-form :deep(.el-input-number), .transport-demand-form :deep(.el-select), .transport-demand-form :deep(.el-date-editor) { width: 100%; }
.transport-demand-budget { display: grid; width: 100%; grid-template-columns: minmax(0, 1fr) 100px; gap: 10px; }
.transport-demand-actions { display: flex; justify-content: flex-end; gap: 10px; padding: 18px 24px; }
.transport-demand-actions :deep(.el-button + .el-button) { margin-left: 0; }
.transport-demand-form--create {
--el-component-size: 44px;
--el-color-primary: #2f7bff;
--el-text-color-regular: #1f2937;
--el-text-color-placeholder: #b0b7c3;
max-width: none;
min-width: 0;
background: transparent;
color: #1f2937;
font: 14px/1.5 "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif;
}
.transport-demand-form--create .transport-demand-section { margin-bottom: 12px; padding: 0; border: 0; }
.transport-demand-form--create .transport-demand-section h3 { display: flex; align-items: center; gap: 10px; margin: 0 0 10px; color: #1f2937; font-size: 18px; font-weight: 700; }
.transport-demand-form--create .transport-demand-section h3::before { content: ''; width: 9px; height: 9px; flex: 0 0 9px; border-radius: 50%; background: #2f7bff; }
.transport-demand-form--create .transport-demand-section:nth-of-type(2) h3::before { background: #0ea5a4; }
.transport-demand-form--create .transport-demand-grid { min-width: 0; gap: 12px 20px; padding: 16px; border: 1px solid #e3e8f0; border-radius: 10px; background: #fff; }
.transport-demand-form--create .transport-demand-route-grid { grid-template-columns: repeat(6, minmax(0, 1fr)); }
.transport-demand-form--create .transport-demand-route-grid > .el-form-item { grid-column: span 2; }
.transport-demand-form--create .transport-demand-route-grid > .transport-demand-vehicle { grid-column: 1 / -1; }
.transport-demand-form--create .transport-demand-route-grid > .transport-demand-address { grid-column: span 3; }
.transport-demand-form--create :deep(.el-form-item) { margin: 0; }
.transport-demand-form--create .transport-demand-vehicle { width: calc((100% - 40px) / 3); }
.transport-demand-form--create :deep(.el-form-item__label) { height: auto; margin-bottom: 6px; padding: 0; color: #374151; font-size: 14px; font-weight: 600; line-height: 20px; }
.transport-demand-form--create :deep(.el-form-item.is-required .el-form-item__label::before) { color: #e5484d; }
/* Show validation beside the label without adding height below the control. */
.transport-demand-form--create :deep(.el-form-item__content) { min-width: 0; line-height: 20px; }
.transport-demand-form--create :deep(.el-form-item__error) { position: absolute; top: auto; bottom: calc(100% + 6px); right: 0; left: auto; width: auto; max-width: calc(100% - 120px); padding: 0; font-size: 12px; line-height: 20px; text-align: right; }
.transport-demand-form--create :deep(.el-input__wrapper), .transport-demand-form--create :deep(.el-select__wrapper), .transport-demand-form--create :deep(.el-textarea__inner) { border: 1px solid #d5dce8; border-radius: 6px; background: #fff; box-shadow: none; font-family: inherit; font-size: 14px; }
.transport-demand-form--create :deep(.el-input__wrapper), .transport-demand-form--create :deep(.el-select__wrapper) { min-height: 44px; padding: 10px 14px; }
.transport-demand-form--create :deep(.el-input__inner) { height: 22px; color: #1f2937; line-height: 22px; }
.transport-demand-form--create :deep(.el-input-number .el-input__wrapper) { padding-right: 40px; }
.transport-demand-form--create :deep(.el-input-number.is-controls-right .el-input-number__increase), .transport-demand-form--create :deep(.el-input-number.is-controls-right .el-input-number__decrease) { width: 32px; }
.transport-demand-form--create :deep(.el-textarea__inner) { min-height: 110px; padding: 11px 14px; color: #1f2937; line-height: 20px; resize: vertical; }
.transport-demand-form--create :deep(.el-input__inner::placeholder), .transport-demand-form--create :deep(.el-textarea__inner::placeholder) { color: var(--el-text-color-placeholder); opacity: 1; }
.transport-demand-form--create :deep(.el-input__wrapper.is-focus), .transport-demand-form--create :deep(.el-select__wrapper.is-focused), .transport-demand-form--create :deep(.el-textarea__inner:focus) { outline: 2px solid #2f7bff; outline-offset: 0; }
.transport-demand-form--create :deep(.el-form-item.is-error .el-input__wrapper), .transport-demand-form--create :deep(.el-form-item.is-error .el-select__wrapper), .transport-demand-form--create :deep(.el-form-item.is-error .el-textarea__inner) { border-color: #e5484d; box-shadow: none; }
.transport-demand-form--create :deep(.el-input.is-disabled .el-input__wrapper), .transport-demand-form--create :deep(.el-select__wrapper.is-disabled), .transport-demand-form--create :deep(.el-textarea.is-disabled .el-textarea__inner) { background: #f6f9ff; }
.transport-demand-form--create :deep(.el-input.is-disabled .el-input__inner), .transport-demand-form--create :deep(.el-textarea.is-disabled .el-textarea__inner) { color: #98a2b3; -webkit-text-fill-color: #98a2b3; }
.transport-demand-character-count { width: 100%; margin-top: 4px; color: #6b7280; font-size: 13px; text-align: right; }
.transport-demand-form--create .transport-demand-actions { flex-wrap: wrap; gap: 12px; padding: 0; }
.transport-demand-form--create .transport-demand-actions :deep(.el-button) { height: auto; min-height: 44px; margin-left: 0; padding: 10px 18px; border-radius: 6px; color: #1d5fe0; font-size: 14px; box-shadow: none; }
.transport-demand-form--create .transport-demand-actions :deep(.el-button--primary) { padding: 12px 28px; color: #fff; }
.transport-demand-form--create .transport-demand-actions :deep(.el-button.is-disabled) { color: #98a2b3; }
:global(.transport-create-popper.el-popper) { --el-color-primary: #2f7bff; border: 1px solid #d5dce8; box-shadow: none; }
</style>
@@ -0,0 +1,56 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { getTransportPhotos, readTransportPhoto, type CrossBorderBusinessKind, type TransportPhotos, type TransportPhotoPhase } from '../api/businessOrders'
const props = defineProps<{ kind: CrossBorderBusinessKind; orderNo: string; refreshKey: number }>()
const photos = ref<TransportPhotos | null>(null), urls = ref<Record<string, string>>({}), loading = ref(false), error = ref('')
const groups: { phase: TransportPhotoPhase; key: keyof TransportPhotos; label: string }[] = [
{ phase: 'PICKUP', key: 'pickupPhotos', label: '取货照片' }, { phase: 'ARRIVAL', key: 'arrivalPhotos', label: '派送照片' },
]
const previewUrls = computed(() => groups.flatMap(group => (photos.value?.[group.key] || []).filter(file => file.contentType.startsWith('image/')).map(file => urls.value[`${group.phase}:${file.fileId}`]).filter((url): url is string => Boolean(url))))
let sequence = 0
function clear() { Object.values(urls.value).forEach(url => URL.revokeObjectURL(url)); urls.value = {} }
async function load() {
const current = ++sequence, kind = props.kind, number = props.orderNo
loading.value = true; error.value = ''; photos.value = null; clear()
try {
const value = await getTransportPhotos(kind, number)
if (current !== sequence) return
photos.value = value
await Promise.all(groups.flatMap(group => value[group.key].map(async file => {
try {
const blob = await readTransportPhoto(kind, number, group.phase, file.fileId)
if (current === sequence) urls.value[`${group.phase}:${file.fileId}`] = URL.createObjectURL(blob)
} catch { if (current === sequence) error.value = '部分照片加载失败,请重试' }
})))
} catch (cause) { if (current === sequence) error.value = cause instanceof Error ? cause.message : '运输照片加载失败' }
finally { if (current === sequence) loading.value = false }
}
watch(() => [props.kind, props.orderNo, props.refreshKey], () => void load(), { immediate: true })
onBeforeUnmount(() => { sequence++; clear() })
</script>
<template>
<section class="transport-photos" aria-label="运输照片" v-loading="loading">
<div v-if="error" class="photo-error" role="alert">{{ error }} <el-button link type="primary" :disabled="loading" @click="load">重试</el-button></div>
<section v-for="group in groups" :key="group.phase" class="photo-group">
<h3>{{ group.label }}</h3>
<div class="photo-row">
<template v-for="file in photos?.[group.key] || []" :key="file.fileId">
<el-image v-if="file.contentType.startsWith('image/')" :src="urls[group.phase + ':' + file.fileId]" :alt="group.label" fit="contain" :preview-src-list="previewUrls" :initial-index="previewUrls.indexOf(urls[group.phase + ':' + file.fileId] || '')" preview-teleported><template #error><span>{{ loading ? '加载中' : '未加载' }}</span></template></el-image>
<a v-else :href="urls[group.phase + ':' + file.fileId]" target="_blank" rel="noopener">查看凭证</a>
</template>
<span v-if="!loading && !photos?.[group.key].length" class="photo-empty">—</span>
</div>
</section>
</section>
</template>
<style scoped>
.transport-photos { margin-top: 20px; }
.photo-group + .photo-group { margin-top: 16px; }
.photo-group h3 { margin: 0 0 10px; color: var(--navy); font-size: 15px; }
.photo-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
.photo-row :deep(.el-image) { width: 112px; height: 84px; border: 1px solid var(--border); border-radius: 4px; }
.photo-row :deep(.el-image__error) { font-size: 12px; }
.photo-empty { color: var(--muted); }
.photo-error { margin-bottom: 10px; color: var(--el-color-danger); }
</style>
@@ -0,0 +1,29 @@
export interface FleetArrangement {
sourceType: 'FLEET_CAPACITY_OFFER'
businessType: 'LOCAL_LOOSEBOARD' | 'US_TRUCK'
businessOrderNo: string
bookingNo: string
tripNo: string
plannedDepartureAt: string | null
originWarehouseName: string
destinationLabel: string
deliveryMode: 'SELF_DELIVERY' | 'MANUAL_PICKUP_TO_WAREHOUSE'
deliveryInstructions: string | null
fulfillmentStage: string
stageOccurredAt: string | null
agreedFreightAmount: number | null
currency: string | null
incomingNo: string | null
dispatchNo: string | null
deliveryNo: string | null
signedPackages: number | null
unsignedPackages: number | null
returnedPackages: number | null
exceptionSummary: string | null
readOnlyReason: string
}
export const poolOrderStatusLabels: Record<string, string> = {
WAITING_INBOUND: '待入仓', RECEIVING: '收货中', WAITING_CONSOLIDATION: '待合托',
PALLET_OVERAGE_REVIEW: '托数超量待审核', PARTIALLY_ALLOCATED: '部分已排车', ALLOCATED: '已排车', DISPATCHED: '待取货',
PENDING_DISPATCH: '待派车', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消',
}
@@ -0,0 +1,95 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
const source = readFileSync(new URL('./components/OrderFundingStatus.vue', import.meta.url), 'utf8')
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1].replace(/^import .*$/gm, '')
function harness({ status = 'FUNDING_PENDING', read = async () => ({ status: 'FREEZE_PENDING' }), retry = async () => ({}), detail = async () => ({}) } = {}) {
const props = { kind: 'procurement', orderNo: 'CG1', status, canRetry: true }
const timers = new Map(), events = [], hooks = {}
let nextTimer = 0
const context = {
defineProps: () => props, defineEmits: () => event => events.push(event), ref: value => ({ value }),
watch: (_getter, callback) => { hooks.watch = callback },
onBeforeUnmount: callback => { hooks.unmount = callback },
onActivated: callback => { hooks.activate = callback },
onDeactivated: callback => { hooks.deactivate = callback },
setTimeout: callback => { const id = ++nextTimer; timers.set(id, callback); return id },
clearTimeout: id => timers.delete(id), readOrderFunding: read, retryOrderFunding: retry, getBusinessOrder: detail,
}
const compiled = ts.transpileModule(script, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const api = runInNewContext(`${compiled}\n({check, retry, message, busy})`, context)
return { ...api, props, timers, events, hooks }
}
test('truck rejection uses latest review reason and never customer remarks', async () => {
const h = harness({ status: 'REJECTED', detail: async () => ({ remark: '客户备注', histories: [
{ operationType: 'REVIEW', toStatus: 'REJECTED', remark: '旧原因' },
{ operationType: 'REVIEW', toStatus: 'REJECTED', remark: '路线暂不支持' },
{ operationType: 'UPDATE', toStatus: 'REJECTED', remark: '内部修改' },
] }) })
h.props.kind = 'trucking'
await h.check(0, 0)
assert.equal(h.message.value, '路线暂不支持')
assert.equal(h.timers.size, 0)
const missing = harness({ status: 'REJECTED', detail: async () => ({ remark: '客户备注' }) })
missing.props.kind = 'trucking'; await missing.check(0, 0)
assert.equal(missing.message.value, '未填写拒绝原因')
})
test('funding status polls for a bounded time and refreshes detail only on a result', async () => {
let count = 0
const h = harness({ read: async () => { count++; return { status: 'FREEZE_PENDING' } } })
await h.check(0, 0)
assert.equal(h.timers.size, 1)
for (let i = 1; i <= 30; i++) {
const [id, callback] = h.timers.entries().next().value
h.timers.delete(id); callback(); await new Promise(resolve => setImmediate(resolve))
}
assert.equal(count, 31)
assert.equal(h.timers.size, 0)
assert.equal(h.events.length, 0)
for (const status of ['FROZEN', 'FAILED']) {
const terminal = harness({ read: async () => ({ status, message: '余额不足' }) })
await terminal.check(0, 0)
assert.equal(terminal.events.join(','), 'changed')
assert.equal(terminal.timers.size, 0)
}
})
test('retry keeps original order and suppresses double clicks and stale responses', async () => {
let resolve, calls = 0
const h = harness({ status: 'FUNDING_FAILED', retry: (kind, no) => {
calls++; assert.equal(kind, 'procurement'); assert.equal(no, 'CG1')
return new Promise(done => { resolve = done })
} })
const first = h.retry(); await h.retry()
assert.equal(calls, 1)
h.hooks.deactivate(); resolve({}); await first
assert.equal(h.events.length, 0)
const denied = harness({ status: 'FUNDING_FAILED', retry: async () => { throw new Error('should not call') } })
denied.props.canRetry = false; await denied.retry()
assert.equal(denied.message.value, '')
})
test('switching or leaving an order ignores the old funding result', async () => {
let resolve
const h = harness({ read: () => new Promise(done => { resolve = done }) })
const pending = h.check(0, 0)
h.hooks.unmount(); resolve({ status: 'FAILED', message: 'old order' }); await pending
assert.equal(h.message.value, '')
assert.equal(h.events.length, 0)
assert.equal(h.timers.size, 0)
})
test('failed orders display finance reason and refresh when another session retries', async () => {
const failed = harness({ status: 'FUNDING_FAILED', read: async () => ({ status: 'FAILED', message: '可用余额及授信不足' }) })
await failed.check(0, 0)
assert.equal(failed.message.value, '可用余额及授信不足')
assert.equal(failed.events.length, 0)
const retried = harness({ status: 'FUNDING_FAILED' })
await retried.check(0, 0)
assert.equal(retried.events.join(','), 'changed')
})
@@ -0,0 +1,395 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import * as vue from 'vue'
import { parse, compileScript } from 'vue/compiler-sfc'
import { renderToString } from 'vue/server-renderer'
const { default: Schema } = createRequire(import.meta.resolve('element-plus'))('async-validator')
let nextKey = 0
const crypto = { randomUUID: () => `test-key-${++nextKey}` }
function moduleFrom(source, require = () => { throw new Error('unexpected import') }) {
const context = { exports: {}, require, URL, Error, crypto }
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
runInNewContext(code, context)
return context.exports
}
const presentation = moduleFrom(readFileSync(new URL('./procurementPresentation.ts', import.meta.url), 'utf8'))
const submission = moduleFrom(readFileSync(new URL('./procurementSubmission.ts', import.meta.url), 'utf8'), name => {
if (name === './procurementPresentation') return presentation
throw new Error(`unexpected import ${name}`)
})
const normalized = value => JSON.parse(JSON.stringify(value))
const draft = () => ({ ...presentation.emptyProcurementDraft(), purchaseCategory: 'Sample', productName: 'Test product', productSpecification: 'A',
productUrl: 'https://example.com/product', purchaseQuantity: '3', budgetUnitPrice: '0.29', receivingAddress: '测试省测试市测试街 1 号', contactName: '测试收件人', contactPhone: '13800000000' })
const fee = (purpose, walletStatus, amount) => ({ purpose, walletStatus, amount, currency: 'CNY' })
test('budget distinguishes unknown from zero, preserves cents, and requires a real telephone/address', () => {
assert.equal(presentation.draftBudgetTotal(draft()), '0.87')
const valid = presentation.buildProcurementCreate(draft(), 'Authenticated Company', 'same-key')
assert.equal(valid.customerName, 'Authenticated Company')
assert.equal(valid.budgetUnitPrice, 0.29)
for (const value of ['', '-1', '1.001', '90071992547409.91']) assert.throws(() => presentation.buildProcurementCreate({ ...draft(), budgetUnitPrice: value }, 'Company', 'key'), /预算/)
assert.equal(presentation.buildProcurementCreate({ ...draft(), budgetUnitPrice: '0' }, 'Company', 'key').budgetUnitPrice, 0)
for (const patch of [{ contactPhone: 'wechat-name' }, { contactPhone: 'a@test.invalid' }, { receivingAddress: '' }, { purchaseQuantity: '1.5' }]) {
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), ...patch }, 'Company', 'key'))
}
assert.equal(presentation.measurement(20, 2), '20.00')
assert.equal(presentation.measurement('5.125', 3), '5.125')
assert.equal(presentation.measurement('1.234', 2), '待核对')
assert.equal(presentation.money(null), '—')
assert.equal(presentation.money(0), 'CNY 0.00')
assert.equal(presentation.productHref('javascript:alert(1)'), undefined)
assert.equal(presentation.productHref('https://example.com/item'), 'https://example.com/item')
})
test('successful net debit excludes the original estimate and counts only successful refunds and differences', () => {
const result = presentation.feeTotals([fee('INTERNATIONAL_ESTIMATE', 'SETTLED', '100'), fee('INTERNATIONAL_FREIGHT', 'SETTLED', '100'),
fee('ADJUSTMENT', 'SETTLED', '20'), fee('ADJUSTMENT', 'SETTLED', '10'), fee('REFUND', 'REFUNDED', '20'), fee('REFUND', 'REFUND_PENDING', '5')])
assert.deepEqual(normalized(result), { paid: '130.00', refunded: '20.00', net: '110.00', estimatedHold: '0.00' })
assert.equal(presentation.feeTotals([fee('INTERNATIONAL_ESTIMATE', 'RELEASE_PENDING', '100')]).estimatedHold, '100.00')
assert.equal(presentation.feeTotals([fee('DUTY', 'SETTLED', 'unknown')]), null)
assert.equal(presentation.feeStatus(fee('INTERNATIONAL_ESTIMATE', 'FROZEN', 100)), '已冻结,未扣款')
assert.equal(presentation.feeStatus(fee('INTERNATIONAL_ESTIMATE', 'SETTLED', 100)), '原预估已结清')
assert.equal(presentation.feeStatus(fee('DUTY', null, 100)), '待核定')
})
test('new requests get unique keys without restoring stored submissions', () => {
assert.notEqual(submission.procurementRequestKey(crypto), submission.procurementRequestKey(crypto))
})
class ApiError extends Error { constructor(message, code, status) { super(message); this.code = code; this.status = status } }
const flush = async () => { await vue.nextTick(); await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
test('shows only the active procurement rejection, hiding it after reupload, resubmission and confirmation', async () => {
const source = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
const template = source.match(/<el-alert\b[^>]*title="采购结果驳回原因"[^>]*\/>/)?.[0]
assert.ok(template)
for (const [status, photosNeedUpdate, rejectionReason, visible] of [
['RECEIVING', true, '照片不清晰', true],
['RECEIVING', false, '照片不清晰', true],
['RECEIVING', false, null, false],
['WAIT_CUSTOMER_CONFIRM', true, '照片不清晰', false],
['CONFIRMED', true, '照片不清晰', false],
['RECEIVING', true, null, false],
]) {
const app = vue.createSSRApp({ render: vue.compile(template), setup: () => ({ workflow: { status, photosNeedUpdate, rejectionReason } }) })
app.component('ElAlert', { props: ['title', 'description'], setup: props => () => vue.h('aside', `${props.title} ${props.description}`) })
const html = await renderToString(app)
assert.equal(html.includes('采购结果驳回原因'), visible, `${status}, photosNeedUpdate=${photosNeedUpdate}`)
assert.equal(html.includes('照片不清晰'), visible)
}
})
function viewHarness({ createPage = false, detailPage = false, api = {}, storage = new Map() } = {}) {
const props = vue.reactive({ createPage, detailPage })
const route = vue.reactive({ params: { orderNo: detailPage ? 'PO-1' : '' } })
const auth = vue.reactive({ token: 'identity-A', user: { tenantName: 'Company' }, profile: { tenantName: 'Company' }, hasPermission: () => true })
const pushes = [], dispose = []
const defaults = { getProcurementWorkflow: async orderNo => ({ orderNo, version: 1, status: 'WAIT_CUSTOMER_CONFIRM', receipts: [], outbounds: [] }), confirmProcurement: async () => ({ orderNo: 'PO-1', version: 2, status: 'CONFIRMED' }), listProcurements: async () => ({ records: [], total: 0 }), getProcurement: async orderNo => ({ order: { orderNo } }), createProcurement: async () => ({ order: { orderNo: 'PO-CREATED' } }) }
const { descriptor } = parse(readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8'))
const source = compileScript(descriptor, { id: 'procurement-test' }).content
const context = { exports: {}, Error, crypto, sessionStorage: { getItem: key => storage.get(key) || null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) },
require(name) {
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => dispose.push(callback), watch: (...args) => { const stop = vue.watch(...args); dispose.push(stop); return stop } }
if (name === 'vue-router') return { useRoute: () => route, useRouter: () => ({ push: async target => pushes.push(target) }) }
if (name === 'element-plus') return { ElMessage: { success: () => {} }, ElMessageBox: { confirm: async () => {}, prompt: async (...args) => { const value = api.rejectionReason ?? '照片不清晰'; const valid = args[2].inputValidator(value); if (valid !== true) throw new Error(valid); return { value } } } }
if (name === '@/api/types') return { ApiError }
if (name === '@/api/session') return { accessTokenIdentity: token => token }
if (name === '@/modules/auth/public') return { useAuthStore: () => auth }
if (name === '../api/orderBudgets') return { requireOrderBudget: api.requireOrderBudget || (async () => {}) }
if (name === '../api/procurement') return { ...defaults, ...api }
if (name === '../procurementPresentation') return presentation
if (name === '../procurementSubmission') return submission
if (name.endsWith('.vue')) return { default: {} }
throw new Error(`unexpected view import ${name}`)
},
}
runInNewContext(ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText, context)
const state = context.exports.default.setup(props, { expose: () => {} })
state.formRef.value = {
validate: async () => { await new Schema(state.formRules).validate(state.form); return true },
clearValidate: () => {},
}
return { state, props, route, auth, pushes, storage, dispose: () => dispose.forEach(callback => callback()) }
}
test('procurement required fields validate individually and blank submissions never call the API', async () => {
const calls = []
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => { calls.push(payload); return { order: { orderNo: 'PO-VALID' } } } } })
try {
const fields = ['procurementDirection', 'productName', 'productUrl', 'purchaseQuantity', 'budgetUnitPrice', 'currency', 'contactName', 'contactPhone', 'receivingAddress']
const source = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
for (const field of fields) {
assert.match(source, new RegExp(`<el-form-item[^>]*prop="${field}"`))
const schema = new Schema({ [field]: harness.state.formRules[field] })
await assert.rejects(schema.validate({ [field]: '' }), error => Boolean(error.fields[field]))
}
await assert.rejects(new Schema(harness.state.formRules).validate({ ...draft(), productName: ' ' }))
await harness.state.submit()
assert.equal(calls.length, 0)
assert.equal(harness.state.submitting.value, false)
assert.equal(harness.state.submitError.value, '')
Object.assign(harness.state.form, draft(), { budgetUnitPrice: '0' })
await harness.state.submit()
assert.equal(calls.length, 1)
assert.equal(calls[0].budgetUnitPrice, 0)
assert.deepEqual(normalized(harness.pushes), [{ name: 'cross-border-procurement' }])
} finally { harness.dispose() }
})
test('create summary follows the current form, preserves cents and clears with the draft', () => {
const harness = viewHarness({ createPage: true })
try {
assert.equal(harness.state.summaryQuantity.value, '1')
assert.equal(harness.state.summaryUnitPrice.value, '—')
assert.equal(harness.state.budgetTotal.value, null)
assert.equal(harness.state.summaryCurrencyName.value, '美元')
Object.assign(harness.state.form, draft())
assert.equal(harness.state.summaryQuantity.value, '3')
assert.equal(harness.state.summaryUnitPrice.value, '0.29')
assert.equal(harness.state.budgetTotal.value, '0.87')
harness.state.form.currency = 'CNY'
assert.equal(harness.state.summaryCurrencyName.value, '人民币')
assert.equal(presentation.money(harness.state.budgetTotal.value, harness.state.form.currency), 'CNY 0.87')
harness.state.form.budgetUnitPrice = '0'
assert.equal(harness.state.summaryUnitPrice.value, '0.00')
assert.equal(harness.state.budgetTotal.value, '0.00')
harness.state.resetForm()
assert.equal(harness.state.summaryQuantity.value, '1')
assert.equal(harness.state.summaryUnitPrice.value, '—')
assert.equal(harness.state.budgetTotal.value, null)
assert.equal(harness.state.summaryCurrencyName.value, '美元')
} finally { harness.dispose() }
})
test('create summary never retains a stale budget when quantity or price becomes invalid', () => {
const harness = viewHarness({ createPage: true })
try {
Object.assign(harness.state.form, draft())
for (const quantity of ['', '0', '-1', '1.5', '9007199254740992']) {
harness.state.form.purchaseQuantity = quantity
assert.equal(harness.state.summaryQuantity.value, '—')
assert.equal(harness.state.budgetTotal.value, null)
assert.equal(harness.state.form.purchaseQuantity, quantity)
}
harness.state.form.purchaseQuantity = '3'
assert.equal(harness.state.budgetTotal.value, '0.87')
for (const price of ['', '-1', '1.001', 'invalid']) {
harness.state.form.budgetUnitPrice = price
assert.equal(harness.state.summaryUnitPrice.value, '—')
assert.equal(harness.state.budgetTotal.value, null)
assert.equal(harness.state.form.budgetUnitPrice, price)
}
harness.state.form.budgetUnitPrice = '0.29'
assert.equal(harness.state.budgetTotal.value, '0.87')
} finally { harness.dispose() }
})
test('detail has one in-flight request and an older response cannot overwrite another order', async () => {
const calls = [], pending = new Map()
const harness = viewHarness({ detailPage: true, api: { getProcurement: orderNo => { calls.push(orderNo); return new Promise(resolve => pending.set(orderNo, resolve)) } } })
try {
assert.deepEqual(calls, ['PO-1'])
await harness.state.loadDetail(); assert.equal(calls.length, 1)
harness.route.params.orderNo = 'PO-2'; await flush(); assert.deepEqual(calls, ['PO-1', 'PO-2'])
pending.get('PO-1')({ order: { orderNo: 'PO-1' } }); await flush(); assert.equal(harness.state.detail.value, null)
pending.get('PO-2')({ order: { orderNo: 'PO-2' } }); await flush(); assert.equal(harness.state.detail.value.order.orderNo, 'PO-2')
assert.equal(harness.state.loading.value, false)
} finally { harness.dispose() }
})
test('timeout releases the form and another click submits the edited current values', async () => {
const calls = []
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => { calls.push(normalized(payload)); throw new ApiError('timeout', 'TIMEOUT') } } })
try {
Object.assign(harness.state.form, draft()); await harness.state.submit()
assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
harness.state.form.productName = 'changed'; await harness.state.submit()
assert.equal(calls[1].productName, 'changed'); assert.notEqual(calls[0].idempotencyKey, calls[1].idempotencyKey)
assert.equal(harness.state.submitting.value, false)
} finally { harness.dispose() }
})
test('submission double-click sends once and definitive validation rejection permits correction', async () => {
let reject, calls = 0
const harness = viewHarness({ createPage: true, api: { createProcurement: () => { calls++; return new Promise((_, failure) => { reject = failure }) } } })
try {
Object.assign(harness.state.form, draft()); const first = harness.state.submit(); await harness.state.submit(); await flush(); assert.equal(calls, 1)
reject(new ApiError('invalid', 'A0422')); await first
assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
} finally { harness.dispose() }
})
test('pagination batches one request and switching account clears old rows before the new response', async () => {
const calls = []; let resolveSecond
const harness = viewHarness({ api: { listProcurements: async params => {
calls.push(normalized(params)); if (calls.length < 3) return { records: [{ orderNo: 'PO-A' }], total: 100 }
return new Promise(resolve => { resolveSecond = resolve })
} } })
try {
await flush(); assert.equal(calls.length, 1)
harness.state.query.page = 2; harness.state.query.size = 50; await flush(); assert.equal(calls.length, 2)
harness.auth.token = 'identity-B'; await vue.nextTick(); assert.equal(harness.state.rows.value.length, 0); assert.equal(harness.state.total.value, 0)
resolveSecond({ records: [{ orderNo: 'PO-B' }], total: 1 }); await flush(); assert.equal(harness.state.rows.value[0].orderNo, 'PO-B')
assert.ok(calls.every(params => !('customerId' in params) && !('tenantId' in params)))
} finally { harness.dispose() }
})
test('consecutive timeout and permission failures never persist or freeze a submission', async () => {
let attempt = 0
const harness = viewHarness({ createPage: true, api: { createProcurement: async () => { throw new ApiError('failed', ++attempt === 1 ? 'TIMEOUT' : 'A0403') } } })
try {
Object.assign(harness.state.form, draft()); await harness.state.submit(); await harness.state.submit()
assert.equal(attempt, 2); assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
harness.state.form.productName = 'editable'; assert.equal(harness.state.form.productName, 'editable')
} finally { harness.dispose() }
})
test('purchase category is optional while its length remains bounded', () => {
const payload = presentation.buildProcurementCreate({ ...draft(), purchaseCategory: ' ' }, 'Company', 'key')
assert.equal(payload.purchaseCategory, '')
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), purchaseCategory: 'x'.repeat(129) }, 'Company', 'key'), /品类/)
})
test('domestic purchase creates an export order and displays the actual origin and destination regions', () => {
const payload = presentation.buildProcurementCreate({ ...draft(), procurementDirection: 'DOMESTIC_TO_OVERSEAS', receivingAddress: 'US, CA, Los Angeles, test destination' }, 'Authenticated Company', 'export-key')
assert.equal(payload.procurementDirection, 'DOMESTIC_TO_OVERSEAS')
assert.equal(payload.receivingAddress, 'US, CA, Los Angeles, test destination')
assert.equal(presentation.statusLabel('RECEIVING', payload.procurementDirection), '收货中')
assert.equal(presentation.statusLabel('DELIVERING', payload.procurementDirection), '派送中')
assert.equal(presentation.statusLabel('WAIT_CUSTOMER_CONFIRM', payload.procurementDirection), '待客户确认')
assert.equal(presentation.statusLabel('COMPLETED'), '签收完成')
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), procurementDirection: 'INVALID' }, 'Company', 'key'), /采购方向/)
const source = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
assert.match(source, /v-model="form.procurementDirection"/)
assert.match(source, /regionText\('最终国内收件资料', form.procurementDirection\)/)
})
test('unchanged create retries reuse the idempotency key', async () => {
const calls = []
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => { calls.push(payload); throw new ApiError('timeout', 'TIMEOUT') } } })
try {
Object.assign(harness.state.form, draft()); await harness.state.submit(); await harness.state.submit()
assert.equal(calls[0].idempotencyKey, calls[1].idempotencyKey)
assert.equal(harness.pushes.length, 0)
} finally { harness.dispose() }
})
test('a lost create response recovers the original order after review releases its budget', async () => {
for (const status of ['RELEASE_PENDING', 'RELEASED', 'RELEASE_FAILED']) {
const budgetCalls = [], createCalls = []
let boundOrder = null
const budgets = moduleFrom(readFileSync(new URL('./api/orderBudgets.ts', import.meta.url), 'utf8'), name => {
assert.equal(name, '@/api/http')
return { apiRequest: async request => {
budgetCalls.push(normalized(request))
return { status, usable: false, orderNo: boundOrder, message: '本次资金预占已释放' }
} }
})
const harness = viewHarness({ createPage: true, api: {
requireOrderBudget: async (...args) => { budgetCalls.push(args); throw new Error('创建订单不应调用旧资金预占接口') },
createProcurement: async payload => {
createCalls.push(normalized(payload))
if (!boundOrder) { boundOrder = 'CG-EXISTING'; throw new ApiError('timeout', 'TIMEOUT') }
assert.equal(payload.idempotencyKey, createCalls[0].idempotencyKey)
return { order: { orderNo: boundOrder, status: 'REJECTED' } }
},
} })
try {
Object.assign(harness.state.form, draft())
await harness.state.submit()
assert.equal(harness.state.submitError.value, 'timeout')
const funding = await budgets.readOrderFunding('procurement', boundOrder)
assert.equal(funding.status, status)
assert.equal(funding.usable, false)
await harness.state.submit()
assert.equal(createCalls.length, 2, status)
assert.deepEqual(budgetCalls, [{ method: 'GET', url: '/merchant/v1/last-leg/order-budgets/procurement/orders/CG-EXISTING' }])
assert.equal(harness.state.submitError.value, '')
assert.equal(harness.state.submittedOrder.value, 'CG-EXISTING')
assert.equal(harness.pushes[0].name, 'cross-border-procurement')
await harness.state.submit()
assert.equal(createCalls.length, 2)
} finally { harness.dispose() }
}
})
test('funding APIs preserve server results and retry the same order only when requested', async () => {
for (const kind of ['procurement', 'trucking']) for (const status of ['FREEZE_PENDING', 'FROZEN', 'RELEASE_PENDING', 'RELEASED', 'RELEASE_FAILED', 'FAILED']) {
const calls = []
const result = { status, usable: false, orderNo: 'CG/EXISTING', message: '资金校验失败' }
const budgets = moduleFrom(readFileSync(new URL('./api/orderBudgets.ts', import.meta.url), 'utf8'), name => {
assert.equal(name, '@/api/http')
return { apiRequest: async request => { calls.push(normalized(request)); return result } }
})
assert.deepEqual(await budgets.readOrderFunding(kind, result.orderNo), result)
assert.deepEqual(calls, [{ method: 'GET', url: `/merchant/v1/last-leg/order-budgets/${kind}/orders/CG%2FEXISTING` }])
await budgets.retryOrderFunding(kind, result.orderNo)
assert.deepEqual(calls[1], { method: 'POST', url: `/merchant/v1/last-leg/order-budgets/${kind}/orders/CG%2FEXISTING/retry` })
assert.equal(calls.length, 2)
}
})
test('bill-settled manual fees show review results without counting a balance debit', () => {
const bill = determination => ({ ...fee('OTHER', 'NOT_REQUIRED', '100'), determination })
assert.equal(presentation.feeStatus(bill('PENDING')), '账单结算 · 待审核')
assert.equal(presentation.feeStatus(bill('APPROVED')), '账单结算 · 已确认')
assert.equal(presentation.feeStatus(bill('REJECTED')), '账单结算 · 已拒绝')
assert.equal(presentation.feeTone(bill('REJECTED')), 'danger')
assert.equal(presentation.feeTotals([bill('PENDING'), bill('APPROVED'), bill('REJECTED')]).paid, '0.00')
})
test('procurement creates immediately while funding is asynchronous and exposes funding states', async () => {
let creates = 0
const harness = viewHarness({ createPage: true, api: { createProcurement: async () => { creates++; return { order: { orderNo: 'CG-PENDING', status: 'FUNDING_PENDING' } } } } })
try {
Object.assign(harness.state.form, draft()); await harness.state.submit()
assert.equal(creates, 1); assert.equal(harness.state.submitError.value, '')
assert.equal(harness.state.submittedOrder.value, 'CG-PENDING')
assert.equal(presentation.statusLabel('FUNDING_PENDING'), '订单受理中')
assert.equal(presentation.statusLabel('FUNDING_FAILED'), '订单处理失败')
} finally { harness.dispose() }
})
test('confirmation and rejection are list actions only while waiting for customer confirmation', async () => {
let status = 'WAIT_CUSTOMER_CONFIRM'
const harness = viewHarness({ api: { listProcurements: async () => ({ records: [{ orderNo: 'PO-1', status, purchaseQuantity: 10 }], total: 1 }) } })
try {
await flush()
const actions = harness.state.rowActions(harness.state.rows.value[0])
assert.deepEqual(normalized(actions.map(action => action.key)), ['detail', 'reject', 'confirm'])
actions[1].run(); assert.equal(harness.state.decision.value, 'reject')
assert.equal(harness.state.decisionTarget.value.orderNo, 'PO-1')
status = 'CONFIRMED'; harness.state.decisionChanged(); await flush()
assert.equal(harness.state.decisionTarget.value, null)
assert.deepEqual(normalized(harness.state.rowActions(harness.state.rows.value[0]).map(action => action.key)), ['detail'])
harness.auth.hasPermission = () => false
assert.equal(harness.state.rowActions({ orderNo: 'PO-1', status: 'WAIT_CUSTOMER_CONFIRM' }).length, 1)
const source = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
const detailHeader = source.slice(source.indexOf('<header class="procurement-heading">'), source.indexOf('</header>', source.indexOf('<header class="procurement-heading">')))
assert.doesNotMatch(detailHeader, /确认采购结果|驳回/)
} finally { harness.dispose() }
})
test('product links must be nonblank and use HTTP or HTTPS before budget reservation', async () => {
for (const productUrl of ['', ' ', 'javascript:alert(1)', 'invalid', 'https://' ]) {
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), productUrl }, 'Company', 'key'), /商品链接/)
}
let budgets = 0, creates = 0
const harness = viewHarness({ createPage: true, api: { requireOrderBudget: async () => { budgets++ }, createProcurement: async () => { creates++ } } })
try {
for (const productUrl of ['', ' ']) {
Object.assign(harness.state.form, draft(), { productUrl }); await harness.state.submit()
}
assert.equal(budgets, 0); assert.equal(creates, 0); assert.equal(harness.pushes.length, 0)
} finally { harness.dispose() }
})
@@ -0,0 +1,138 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import * as vue from 'vue'
import { parse, compileScript } from 'vue/compiler-sfc'
const source = readFileSync(new URL('./components/ProcurementDecisionDialog.vue', import.meta.url), 'utf8')
const { descriptor } = parse(source)
const code = ts.transpileModule(compileScript(descriptor, { id: 'decision-test' }).content, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
const flush = async () => { await vue.nextTick(); await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
let key = 0
function harness({ decision = 'confirm', api = {} } = {}) {
const props = vue.reactive({ order: { orderNo: 'PO-1', productName: '商品', purchaseQuantity: 10 }, decision })
const auth = vue.reactive({ token: 'customer-A', hasPermission: () => true })
const calls = [], events = [], disposers = [], created = [], revoked = []
const workflow = { orderNo: 'PO-1', status: 'WAIT_CUSTOMER_CONFIRM', version: 7, receivedQuantity: 8, files: [{ fileId: 'F-1', fileName: 'photo.png' }], receipts: [{ id: 'R-1', quantity: 5, fileIds: ['F-1'], receivedAt: '' }, { id: 'R-2', quantity: 3, fileIds: ['F-2'], receivedAt: '' }] }
const defaults = {
getProcurementWorkflow: async () => workflow,
getProcurementFile: async () => ({ type: 'image/png' }),
confirmProcurement: async (orderNo, payload) => { calls.push({ orderNo, ...payload }); return { ...workflow, status: 'CONFIRMED' } },
rejectProcurement: async (orderNo, payload) => { calls.push({ orderNo, ...payload }); return { ...workflow, status: 'RECEIVING' } },
}
const context = { exports: {}, Error, URL: { createObjectURL: () => { const url = `blob:${created.length}`; created.push(url); return url }, revokeObjectURL: url => revoked.push(url) }, require(name) {
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => disposers.push(callback) }
if (name === 'element-plus') return { ElMessage: { success: () => {} } }
if (name === '@/api/session') return { accessTokenIdentity: token => token }
if (name === '@/modules/auth/public') return { useAuthStore: () => auth }
if (name === '../api/procurement') return { ...defaults, ...api }
if (name === '../procurementSubmission') return { procurementRequestKey: () => `key-${++key}` }
if (name === '../procurementPresentation') return { dateTime: value => value }
throw new Error(`unexpected import ${name}`)
} }
runInNewContext(code, context)
const state = context.exports.default.setup(props, { expose: () => {}, emit: (...args) => events.push(args) })
return { state, auth, calls, events, created, revoked, workflow, dispose: () => disposers.forEach(callback => callback()) }
}
test('both decisions load receipt photos and batch quantities with preview URL cleanup', async () => {
for (const decision of ['confirm', 'reject']) {
const h = harness({ decision })
try {
await flush()
assert.equal(h.state.workflow.value.receivedQuantity, 8)
assert.equal(h.state.workflow.value.receipts.length, 2)
assert.equal(Object.keys(h.state.photos.value).length, 2)
assert.equal(h.state.canSubmit.value, true)
assert.equal(h.state.fileName('F-1'), 'photo.png')
assert.match(source, /order.purchaseQuantity/)
assert.match(source, /receipt.quantity/)
assert.match(source, /<el-image/)
assert.match(source, /preview-src-list/)
} finally { h.dispose() }
assert.deepEqual(h.revoked, h.created)
}
})
test('confirmation uses current version, prevents double submits, and signals list refresh', async () => {
let finish, calls = []
const h = harness({ api: { confirmProcurement: (orderNo, command) => { calls.push({ orderNo, ...command }); return new Promise(resolve => { finish = resolve }) } } })
try {
await flush()
const pending = h.state.submitDecision(); await h.state.submitDecision()
assert.equal(calls.length, 1); assert.equal(calls[0].version, 7); assert.equal(calls[0].orderNo, 'PO-1')
finish({ status: 'CONFIRMED' }); await pending
assert.deepEqual(h.events, [['changed']])
} finally { h.dispose() }
})
test('rejection requires a trimmed reason and retries unchanged payload with the same key', async () => {
const calls = []
const h = harness({ decision: 'reject', api: { rejectProcurement: async (orderNo, command) => { calls.push({ orderNo, ...command }); throw new Error('网络失败') } } })
try {
await flush()
for (const reason of ['', ' ', 'x'.repeat(1001)]) {
h.state.reason.value = reason; await h.state.submitDecision()
assert.match(h.state.error.value, /请填写驳回原因/)
}
assert.equal(calls.length, 0)
h.state.reason.value = ' 照片不清晰 '
await h.state.submitDecision(); await h.state.submitDecision()
assert.equal(calls.length, 2); assert.equal(calls[0].reason, '照片不清晰'); assert.equal(calls[0].version, 7)
assert.equal(calls[0].idempotencyKey, calls[1].idempotencyKey)
assert.equal(h.state.reason.value, ' 照片不清晰 '); assert.equal(h.events.length, 0)
h.state.reason.value = '数量不符'; await h.state.submitDecision()
assert.notEqual(calls[1].idempotencyKey, calls[2].idempotencyKey)
} finally { h.dispose() }
})
test('confirmation retry preserves the loaded evidence and idempotency key', async () => {
const calls = []
const h = harness({ api: { confirmProcurement: async (_, command) => { calls.push(command); throw new Error('版本已更新,请刷新') } } })
try {
await flush(); await h.state.submitDecision(); await h.state.submitDecision()
assert.equal(calls.length, 2); assert.equal(calls[0].idempotencyKey, calls[1].idempotencyKey)
assert.equal(h.state.workflow.value.version, 7); assert.equal(Object.keys(h.state.photos.value).length, 2)
assert.equal(h.state.saving.value, false); assert.equal(h.events.length, 0)
} finally { h.dispose() }
})
test('successful rejection sends the trimmed reason and signals list refresh', async () => {
const h = harness({ decision: 'reject' })
try {
await flush(); h.state.reason.value = ' 数量不符 '; await h.state.submitDecision()
assert.equal(h.calls[0].reason, '数量不符'); assert.equal(h.calls[0].version, 7)
assert.deepEqual(h.events, [['changed']])
} finally { h.dispose() }
})
test('photo loading failures can be retried before a decision is submitted', async () => {
let fail = true
const h = harness({ api: { getProcurementFile: async () => { if (fail) throw new Error('failed'); return { type: 'image/png' } } } })
try {
await flush(); await h.state.submitDecision()
assert.equal(h.calls.length, 0); assert.match(h.state.photoError.value, /照片加载失败/)
fail = false; await h.state.load(); await h.state.submitDecision()
assert.equal(h.calls.length, 1)
} finally { h.dispose() }
})
test('stale status, revoked permission and changed account cannot submit decisions', async () => {
const stale = harness({ api: { getProcurementWorkflow: async () => ({ status: 'CONFIRMED', receipts: [] }) } })
try { await flush(); await stale.state.submitDecision(); assert.equal(stale.calls.length, 0) } finally { stale.dispose() }
const h = harness()
try {
await flush(); h.auth.hasPermission = () => false; await h.state.submitDecision(); assert.equal(h.calls.length, 0)
h.auth.hasPermission = () => true; h.auth.token = 'customer-B'; await h.state.submitDecision(); assert.equal(h.calls.length, 0)
} finally { h.dispose() }
})
test('late photo responses after closing do not allocate preview URLs', async () => {
const pending = []
const h = harness({ api: { getProcurementFile: () => new Promise(resolve => pending.push(resolve)) } })
await flush(); h.dispose()
pending.forEach(resolve => resolve({ type: 'image/png' })); await flush()
assert.equal(h.created.length, 0); assert.equal(h.events.length, 0)
})
@@ -0,0 +1,144 @@
import type { Amount, ProcurementCreate, ProcurementFee } from './api/procurement'
export const procurementStatuses: Record<string, string> = {
FUNDING_PENDING: '订单受理中', FUNDING_FAILED: '订单处理失败', PENDING_REVIEW: '待审核', RECEIVING: '收货中', WAIT_CUSTOMER_CONFIRM: '待客户确认', CONFIRMED: '已确认',
IN_TRANSIT: '运输中', DELIVERING: '派送中', COMPLETED: '签收完成',
REJECTED: '已拒绝', CANCELLED: '已取消',
}
export const feePurposes: Record<string, string> = {
SAMPLE_PAYMENT: '样品货款', INTERNATIONAL_ESTIMATE: '预估国际运费', INTERNATIONAL_FREIGHT: '实际国际运费',
DUTY: '关税', DOMESTIC_FREIGHT: '国内运费', OTHER: '其他费用', ADJUSTMENT: '追加费用', REFUND: '退款',
}
export function statusLabel(status: string | null | undefined, direction?: string | null) { return regionText(status ? procurementStatuses[status] || '待核对进度' : '—', direction) }
export function statusTone(status: string | null | undefined): 'success' | 'warning' | 'danger' | 'info' | 'primary' {
if (status === 'COMPLETED' || status === 'CONFIRMED') return 'success'
if ((status === 'REJECTED' || status === 'FUNDING_FAILED')) return 'danger'
if (status === 'CANCELLED') return 'info'
if (status === 'IN_TRANSIT' || status === 'DELIVERING') return 'primary'
return 'warning'
}
function cents(value: Amount | null | undefined): bigint | null {
if (value === null || value === undefined) return null
const match = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(String(value).trim())
if (!match) return null
const result = BigInt(match[2]) * 100n + BigInt((match[3] || '').padEnd(2, '0'))
return match[1] ? -result : result
}
function decimal(value: bigint) {
const absolute = value < 0n ? -value : value
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`
}
export function money(value: Amount | null | undefined, currency: string | null | undefined = 'CNY') {
const amount = cents(value)
return amount === null ? '—' : `${currency || '—'} ${decimal(amount)}`
}
export function dateTime(value: string | null | undefined) { return value ? value.replace('T', ' ').replace(/\.\d+$/, '') : '—' }
export function measurement(value: Amount | null | undefined, scale: number) {
if (value === null || value === undefined) return '—'
const parts = /^(\d+)(?:\.(\d+))?$/.exec(String(value))
if (!parts || (parts[2] || '').length > scale) return '待核对'
return `${parts[1]}.${(parts[2] || '').padEnd(scale, '0')}`
}
export function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
export function productHref(value: string | null | undefined) {
if (!value) return undefined
try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) ? url.href : undefined } catch { return undefined }
}
export function feeStatus(fee: ProcurementFee) {
if (fee.walletStatus === 'NOT_REQUIRED') {
if (fee.determination === 'PENDING') return '账单结算 · 待审核'
if (fee.determination === 'APPROVED') return '账单结算 · 已确认'
if (fee.determination === 'REJECTED') return '账单结算 · 已拒绝'
return '账单结算'
}
if (fee.purpose === 'INTERNATIONAL_ESTIMATE') {
const label: Record<string, string> = { FROZEN: '已冻结,未扣款', ZERO: '零预估已确认', SETTLED: '原预估已结清', RELEASED: '预估已释放' }
if (fee.walletStatus && label[fee.walletStatus]) return label[fee.walletStatus]
}
const labels: Record<string, string> = {
FREEZE_PENDING: '冻结处理中', FREEZE_FAILED: '冻结未成功', FROZEN: '等待扣款', SETTLE_PENDING: '扣款处理中', SETTLE_ACTUAL_PENDING: '实际费用结算中',
SETTLE_FAILED: '扣款未成功', SETTLE_ACTUAL_FAILED: '实际费用未结清', SETTLED: '已扣款', RELEASE_PENDING: '释放处理中', RELEASE_FAILED: '释放未成功',
RELEASED: '已释放冻结', REFUND_PENDING: '退款处理中', REFUND_FAILED: '退款未成功', REFUNDED: '已退款', ZERO: '已确认零元', NOT_APPLICABLE: '不适用', TERMINATED: '已终止',
}
return fee.walletStatus ? labels[fee.walletStatus] || '待核定' : '待核定'
}
export function feeTone(fee: ProcurementFee): 'success' | 'warning' | 'danger' | 'info' {
if (fee.determination === 'REJECTED') return 'danger'
if (fee.walletStatus === 'NOT_REQUIRED' && fee.determination === 'APPROVED') return 'info'
if (fee.walletStatus?.endsWith('_FAILED')) return 'danger'
if (['SETTLED', 'REFUNDED', 'ZERO', 'NOT_APPLICABLE', 'RELEASED'].includes(fee.walletStatus || '')) return 'success'
if (fee.walletStatus === 'TERMINATED') return 'info'
return 'warning'
}
export function feeTotals(fees: ProcurementFee[]) {
let paid = 0n, refunded = 0n, estimatedHold = 0n
for (const fee of fees) {
const estimate = fee.purpose === 'INTERNATIONAL_ESTIMATE'
const include = (!estimate && fee.walletStatus === 'SETTLED') || fee.walletStatus === 'REFUNDED'
|| (estimate && ['FROZEN', 'RELEASE_PENDING', 'RELEASE_FAILED'].includes(fee.walletStatus || ''))
if (!include) continue
const amount = cents(fee.amount)
if (amount === null || amount < 0n || fee.currency !== 'CNY') return null
if (estimate) estimatedHold += amount
else if (fee.walletStatus === 'REFUNDED') refunded += amount
else paid += amount
}
return { paid: decimal(paid), refunded: decimal(refunded), net: decimal(paid - refunded), estimatedHold: decimal(estimatedHold) }
}
export interface ProcurementDraft {
procurementDirection?: ProcurementDirection
purchaseCategory: string
productName: string
productSpecification: string
productUrl: string
purchaseQuantity: string
budgetUnitPrice: string
currency: 'CNY' | 'USD'
receivingAddress: string
contactName: string
contactPhone: string
remark: string
}
export function emptyProcurementDraft(): ProcurementDraft {
return { procurementDirection: 'OVERSEAS_TO_DOMESTIC', purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: '1', budgetUnitPrice: '', currency: 'USD', receivingAddress: '', contactName: '', contactPhone: '', remark: '' }
}
export function draftBudgetTotal(draft: ProcurementDraft) {
const price = cents(draft.budgetUnitPrice)
if (price === null || price < 0n || !/^\d+$/.test(draft.purchaseQuantity)) return null
return decimal(price * BigInt(draft.purchaseQuantity))
}
export function buildProcurementCreate(draft: ProcurementDraft, customerName: string, key: string): ProcurementCreate {
for (const [field, label, max] of [
['productName', '商品名称', 255], ['receivingAddress', '完整目的地收货地址', 1000],
['contactName', '最终收件人', 128], ['contactPhone', '联系电话', 64],
] as const) {
if (!draft[field].trim() || draft[field].trim().length > max) throw new Error(`请填写有效的${label}`)
}
if (draft.purchaseCategory.trim().length > 128) throw new Error('采购品类超过长度限制')
if (!customerName.trim()) throw new Error('当前企业信息尚未加载,请刷新登录信息后重试')
if (!/^\d+$/.test(draft.purchaseQuantity) || !Number.isSafeInteger(Number(draft.purchaseQuantity)) || Number(draft.purchaseQuantity) <= 0) throw new Error('采购数量必须为正整数')
const price = cents(draft.budgetUnitPrice)
if (price === null || price < 0n) throw new Error('请明确填写非负预算单价,最多两位小数;免费样品填写 0')
if (price > BigInt(Number.MAX_SAFE_INTEGER) || cents(Number(decimal(price))) !== price) throw new Error('预算金额过大,无法准确表示,请核对金额')
if (!['CNY', 'USD'].includes(draft.currency)) throw new Error('预算币种只支持 CNY 或 USD')
if (!/^[+0-9][0-9 ()-]{5,63}$/.test(draft.contactPhone.trim())) throw new Error('请填写快递可联系的电话号码,微信或邮箱不能代替电话')
if (!draft.productUrl.trim()) throw new Error('请输入商品链接')
if (!productHref(draft.productUrl.trim()) || draft.productUrl.trim().length > 2000) throw new Error('商品链接须为有效的 http 或 https 地址')
if (draft.productSpecification.length > 500 || draft.remark.length > 1000) throw new Error('商品规格或备注超过长度限制')
if (draft.procurementDirection && !['OVERSEAS_TO_DOMESTIC', 'DOMESTIC_TO_OVERSEAS'].includes(draft.procurementDirection)) throw new Error('请选择有效采购方向')
return { procurementDirection: draft.procurementDirection || 'OVERSEAS_TO_DOMESTIC', customerName: customerName.trim(), purchaseCategory: draft.purchaseCategory.trim(), productName: draft.productName.trim(),
productSpecification: draft.productSpecification.trim() || undefined, productUrl: draft.productUrl.trim() || undefined,
purchaseQuantity: Number(draft.purchaseQuantity), budgetUnitPrice: Number(decimal(price)), currency: draft.currency,
receivingAddress: draft.receivingAddress.trim(), contactName: draft.contactName.trim(), contactPhone: draft.contactPhone.trim(),
remark: draft.remark.trim() || undefined, idempotencyKey: key }
}
export type ProcurementDirection = 'OVERSEAS_TO_DOMESTIC' | 'DOMESTIC_TO_OVERSEAS'
export const procurementDirections: Record<ProcurementDirection, string> = {
OVERSEAS_TO_DOMESTIC: '海外采购,发往国内', DOMESTIC_TO_OVERSEAS: '国内采购,发往海外',
}
export function directionLabel(direction?: string | null) { return direction === 'DOMESTIC_TO_OVERSEAS' ? procurementDirections.DOMESTIC_TO_OVERSEAS : procurementDirections.OVERSEAS_TO_DOMESTIC }
// 两个历史段编码表示起运段和目的地段,展示区域按订单方向转换。
export function regionText(text: string, direction?: string | null) {
return direction === 'DOMESTIC_TO_OVERSEAS' ? text.replaceAll('海外', '__ORIGIN__').replaceAll('国内', '海外').replaceAll('__ORIGIN__', '国内') : text
}
@@ -0,0 +1,4 @@
export function procurementRequestKey(provider: Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>> = globalThis.crypto) {
if (provider.randomUUID) return provider.randomUUID()
return `proc-${Array.from(provider.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('')}`
}
+42 -3
View File
@@ -5,28 +5,67 @@ export const crossBorderModule = {
key: 'cross-border', key: 'cross-border',
navigationGroup: { title: '出海下单', icon: PlaneTakeoff }, navigationGroup: { title: '出海下单', icon: PlaneTakeoff },
routes: [ routes: [
{
path: 'cross-border/procurement/create',
name: 'cross-border-procurement-create',
component: () => import('./views/ProcurementView.vue'),
props: { createPage: true },
release: 'active',
meta: { title: '海外采购下单', workspaceTitle: '海外采购 · 新建', description: '填写并提交海外采购订单', permission: 'merchant:cross-border:procurement:create' },
},
{
path: 'cross-border/procurement/:orderNo/detail', name: 'cross-border-procurement-detail',
component: () => import('./views/ProcurementView.vue'), props: { detailPage: true }, release: 'active',
meta: { title: '海外采购详情', workspaceTitle: '海外采购 · 详情', description: '查看海外采购订单详情', permission: 'merchant:cross-border:procurement:list', keepAlive: false },
},
{ {
path: 'cross-border/procurement', path: 'cross-border/procurement',
name: 'cross-border-procurement', name: 'cross-border-procurement',
component: () => import('./views/ProcurementView.vue'), component: () => import('./views/ProcurementView.vue'),
release: 'active', release: 'active',
meta: { title: '海外采购', description: '管理海外采购订单', permission: 'merchant:cross-border:procurement' }, meta: { title: '海外采购', description: '管理海外采购订单', permission: 'merchant:cross-border:procurement:list' },
navigation: { key: 'cross-border-procurement', icon: Package }, navigation: { key: 'cross-border-procurement', icon: Package },
}, },
{
path: 'cross-border/domestic-trucking/create',
name: 'cross-border-domestic-trucking-create',
component: () => import('./views/DomesticTruckingView.vue'),
props: { createPage: true },
release: 'active',
meta: { title: '美国本土卡下单', workspaceTitle: '美国本土卡 · 新建', description: '填写并提交美国本土卡车运输订单', permission: 'merchant:cross-border:domestic-trucking:create' },
},
{
path: 'cross-border/domestic-trucking/:orderNo/detail', name: 'cross-border-domestic-trucking-detail',
component: () => import('./views/DomesticTruckingView.vue'), props: { detailPage: true }, release: 'active',
meta: { title: '美国本土卡详情', workspaceTitle: '美国本土卡 · 详情', description: '查看美国本土卡订单详情', permission: 'merchant:cross-border:domestic-trucking:list', keepAlive: false },
},
{ {
path: 'cross-border/domestic-trucking', path: 'cross-border/domestic-trucking',
name: 'cross-border-domestic-trucking', name: 'cross-border-domestic-trucking',
component: () => import('./views/DomesticTruckingView.vue'), component: () => import('./views/DomesticTruckingView.vue'),
release: 'active', release: 'active',
meta: { title: '美国本土卡', description: '创建美国本土卡车运输订单', permission: 'merchant:cross-border:domestic-trucking' }, meta: { title: '美国本土卡', description: '创建美国本土卡车运输订单', permission: 'merchant:cross-border:domestic-trucking:list' },
navigation: { key: 'cross-border-domestic-trucking', icon: Truck }, navigation: { key: 'cross-border-domestic-trucking', icon: Truck },
}, },
{
path: 'cross-border/pallet-shipping/create',
name: 'cross-border-pallet-shipping-create',
component: () => import('./views/PalletShippingView.vue'),
props: { createPage: true },
release: 'active',
meta: { title: '美本土散板下单', workspaceTitle: '美本土散板 · 新建', description: '填写并提交美国本土散板运输订单', permission: 'merchant:cross-border:pallet-shipping:create' },
},
{
path: 'cross-border/pallet-shipping/:orderNo/detail', name: 'cross-border-pallet-shipping-detail',
component: () => import('./views/PalletShippingView.vue'), props: { detailPage: true }, release: 'active',
meta: { title: '美本土散板详情', workspaceTitle: '美本土散板 · 详情', description: '查看美本土散板运输订单详情', permission: 'merchant:cross-border:pallet-shipping:list', keepAlive: false },
},
{ {
path: 'cross-border/pallet-shipping', path: 'cross-border/pallet-shipping',
name: 'cross-border-pallet-shipping', name: 'cross-border-pallet-shipping',
component: () => import('./views/PalletShippingView.vue'), component: () => import('./views/PalletShippingView.vue'),
release: 'active', release: 'active',
meta: { title: '美本土散板', description: '创建美国本土散板运输订单', permission: 'merchant:cross-border:pallet-shipping' }, meta: { title: '美本土散板', description: '创建美国本土散板运输订单', permission: 'merchant:cross-border:pallet-shipping:list' },
navigation: { key: 'cross-border-pallet-shipping', icon: Ship }, navigation: { key: 'cross-border-pallet-shipping', icon: Ship },
}, },
], ],
@@ -0,0 +1,89 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import ts from 'typescript'
const source = readFileSync(new URL('./transportDemandForm.ts', import.meta.url), 'utf8')
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText.replace(/^export /gm, '')
const { createTransportDemandForm, transportDemandRules, transportDemandError, buildTransportDemand } = runInNewContext(`${code}\n({ createTransportDemandForm, transportDemandRules, transportDemandError, buildTransportDemand })`)
const valid = () => ({ ...createTransportDemandForm(), deliveryMode: 'WAREHOUSE_PICKUP', operatingWarehouseId: '9', destinationType: 'FBA', packageCount: 8, vehicleType: 'PALLET_15', estimatedPalletCount: 3, budgetAmount: 100, origin: ' LA ', originAddress: '123 Test Road', destinationAddress: '456 Delivery Road', destination: ' ONT ', originContactName: ' 发货人 ', originContactPhone: ' +1-555-0100 ', destinationContactName: ' 收货人 ', destinationContactPhone: ' +1-555-0101 ', pickupAt: '2026-10-20T09:30:45', deliveryAt: '2026-10-20T15:45:12' })
test('truck requires both full addresses in form validation and submission', () => {
for (const [field, label] of [['originAddress', '取货地址'], ['destinationAddress', '送达地址']]) {
for (const value of ['', ' ']) {
const form = { ...valid(), [field]: value }
assert.equal(transportDemandRules('truck', form)[field][0].required, true)
assert.equal(transportDemandError('truck', form), `请输入${label}`)
assert.throws(() => buildTransportDemand('truck', form), new RegExp(label))
}
}
})
test('delivery to warehouse permits no tracking number while requiring receiving contacts and arrival time', () => {
const form = { ...valid(), deliveryMode: 'DELIVERY_TO_WAREHOUSE', deliveryContactName: '仓库收货员', deliveryContactPhone: '10003', estimatedArrivalAt: '2026-10-20T09:00:00', trackingNo: '' }
assert.equal(transportDemandError('looseboard', form), undefined)
assert.equal(buildTransportDemand('looseboard', form).trackingNo, undefined)
for (const field of ['deliveryContactName', 'deliveryContactPhone', 'estimatedArrivalAt']) assert.ok(transportDemandError('looseboard', { ...form, [field]: '' }))
})
test('initial form leaves contacts and times blank, zeroes cargo and distinguishes blank budget from zero', () => {
const form = createTransportDemandForm()
for (const key of ['originContactName', 'originContactPhone', 'destinationContactName', 'destinationContactPhone', 'pickupAt', 'deliveryAt']) assert.equal(form[key], '')
for (const key of ['estimatedPalletCount', 'packageCount', 'totalWeightKg', 'totalVolumeCbm']) assert.equal(form[key], 0)
assert.equal(form.budgetAmount, undefined)
assert.equal(form.currency, 'USD')
assert.throws(() => buildTransportDemand('truck', { ...valid(), budgetAmount: undefined }), /预算/)
assert.throws(() => buildTransportDemand('truck', { ...valid(), budgetAmount: 0 }), /预算/)
})
for (const kind of ['truck', 'looseboard']) {
test(`${kind} requires both route contacts and both service times before building a payload`, () => {
for (const field of ['origin', 'destination', 'originContactName', 'originContactPhone', 'destinationContactName', 'destinationContactPhone', 'pickupAt', 'deliveryAt']) {
const form = { ...valid(), [field]: '' }
assert.ok(transportDemandError(kind, form), field)
assert.throws(() => buildTransportDemand(kind, form), undefined, field)
}
})
test(`${kind} rejects negative cargo, fractional counts, invalid budgets and reversed times`, () => {
for (const field of ['packageCount', 'totalWeightKg', 'totalVolumeCbm', 'budgetAmount']) {
assert.ok(transportDemandError(kind, { ...valid(), [field]: -1 }), field)
assert.ok(transportDemandError(kind, { ...valid(), [field]: Number.NaN }), field)
}
assert.ok(transportDemandError(kind, { ...valid(), packageCount: 1.5 }))
assert.ok(transportDemandError(kind, { ...valid(), deliveryAt: '2026-10-20T09:29:00' }))
assert.ok(transportDemandError(kind, { ...valid(), currency: 'EUR' }))
})
test(`${kind} sends minute wall-clock values, trims contacts, and excludes customer and old fields`, () => {
const payload = buildTransportDemand(kind, { ...valid(), customerId: 'forged', tenantId: 'forged', transportMode: 'OLD', containerType: '40HQ' })
assert.equal(payload.pickupAt, '2026-10-20T09:30:00')
assert.equal(payload.deliveryAt, '2026-10-20T15:45:00')
assert.equal(payload.origin, 'LA')
assert.equal(payload.originContactName, '发货人')
assert.equal(payload.destinationContactPhone, '+1-555-0101')
for (const key of ['customerId', 'tenantId', 'transportMode', 'transportType', 'containerType', 'contactName', 'contactInfo', 'requestedDate']) assert.equal(Object.hasOwn(payload, key), false, key)
assert.equal(transportDemandError(kind, { ...valid(), deliveryAt: '2026-10-20T09:30:01' }), undefined)
})
}
test('truck accepts only the two vehicle types and does not submit looseboard cargo forecasts', () => {
assert.ok(transportDemandError('truck', { ...valid(), vehicleType: 'PALLET_99' }))
const truck = buildTransportDemand('truck', { ...valid(), productName: 'cargo', estimatedPalletCount: 3 })
assert.equal(Object.hasOwn(truck, 'productName'), false)
assert.equal(Object.hasOwn(truck, 'estimatedPalletCount'), false)
assert.equal(truck.palletCount, 3)
assert.equal(Object.hasOwn(truck, 'packageCount'), false)
const loose = buildTransportDemand('looseboard', { ...valid(), vehicleType: '', productName: ' cargo ', estimatedPalletCount: 3, packageCount: 8 })
assert.equal(Object.hasOwn(loose, 'vehicleType'), false)
assert.equal(loose.productName, 'cargo')
assert.equal(loose.estimatedPalletCount, 3)
assert.equal(loose.packageCount, 8)
})
test('warehouse delivery clears hidden origin data and pickup requires the full origin address', () => {
const form={...valid(),deliveryMode:'DELIVERY_TO_WAREHOUSE',deliveryContactName:'warehouse',deliveryContactPhone:'000',estimatedArrivalAt:'2026-10-20T09:00:00'}
for(const field of ['origin','originAddress','originContactName','originContactPhone']) assert.equal(transportDemandError('looseboard',{...form,[field]:''}),undefined)
const payload=buildTransportDemand('looseboard',form)
assert.equal(payload.origin,'');assert.equal(payload.originAddress,undefined);assert.equal(payload.originContactName,'');assert.equal(payload.originContactPhone,'')
assert.match(transportDemandError('looseboard',{...valid(),originAddress:''}),/详细地址/)
})
@@ -0,0 +1,143 @@
import type { FormRules } from 'element-plus'
export type TransportDemandKind = 'truck' | 'looseboard'
export interface TransportDemandForm {
deliveryMode: 'DELIVERY_TO_WAREHOUSE' | 'WAREHOUSE_PICKUP'
operatingWarehouseId: string
deliveryContactName: string
deliveryContactPhone: string
estimatedArrivalAt: string
trackingNo: string
destinationType: 'FBA' | 'PRIVATE'
destinationPostalCode: string
vehicleType: '' | 'PALLET_15' | 'PALLET_30'
origin: string
destination: string
originAddress: string
destinationAddress: string
originContactName: string
originContactPhone: string
destinationContactName: string
destinationContactPhone: string
productName: string
estimatedPalletCount: number
packageCount: number
totalWeightKg: number
totalVolumeCbm: number
budgetAmount: number | undefined
currency: 'USD' | 'CNY'
pickupAt: string
deliveryAt: string
remark: string
}
export function createTransportDemandForm(): TransportDemandForm {
return {
deliveryMode: 'DELIVERY_TO_WAREHOUSE', operatingWarehouseId: '', deliveryContactName: '', deliveryContactPhone: '', estimatedArrivalAt: '', trackingNo: '', destinationType: 'PRIVATE', destinationPostalCode: '',
vehicleType: '', origin: '', destination: '', originAddress: '', destinationAddress: '',
originContactName: '', originContactPhone: '', destinationContactName: '', destinationContactPhone: '',
productName: '', estimatedPalletCount: 0, packageCount: 0, totalWeightKg: 0, totalVolumeCbm: 0,
budgetAmount: undefined, currency: 'USD', pickupAt: '', deliveryAt: '', remark: '',
}
}
const requiredText = (kind: TransportDemandKind, form: TransportDemandForm) => ({
...(kind === 'truck' ? { originAddress: '取货地址', destinationAddress: '送达地址' } : {}),
...(kind === 'truck' || form.deliveryMode === 'WAREHOUSE_PICKUP' ? { origin: kind === 'truck' ? '取货地' : '起运地', originContactName: kind === 'truck' ? '取货联系人' : '起运地联系人', originContactPhone: kind === 'truck' ? '取货联系电话' : '起运地联系电话' } : {}),
destination: kind === 'truck' ? '送达地' : '目的地',
destinationContactName: kind === 'truck' ? '送达联系人' : '目的地联系人',
destinationContactPhone: kind === 'truck' ? '送达联系电话' : '目的地联系电话',
} as const)
export function localMinuteInput(value: unknown) {
return typeof value === 'string' && value ? `${value.slice(0, 16)}:00` : ''
}
export function transportDemandRules(kind: TransportDemandKind, form: TransportDemandForm): FormRules<TransportDemandForm> {
const rules: FormRules<TransportDemandForm> = {}
const labels = requiredText(kind, form)
for (const [field, label] of Object.entries(labels)) {
rules[field as keyof typeof labels] = [{ required: true, whitespace: true, message: `请输入${label}`, trigger: 'blur' }]
}
if (kind === 'looseboard') {
if (form.deliveryMode === 'WAREHOUSE_PICKUP') rules.originAddress = [{ required: true, whitespace: true, message: '请输入起运详细地址', trigger: 'blur' }]
rules.operatingWarehouseId = [{ required: true, message: '请选择收货仓库', trigger: 'change' }]
if (form.destinationType === 'PRIVATE') {
rules.destinationAddress = [{ required: true, whitespace: true, message: '请输入目的详细地址', trigger: 'blur' }]
rules.destinationPostalCode = [{ required: true, whitespace: true, message: '请输入目的地邮编', trigger: 'blur' }]
}
if (form.deliveryMode === 'DELIVERY_TO_WAREHOUSE') {
for (const [field, label] of [['deliveryContactName', '到仓联系人'], ['deliveryContactPhone', '到仓联系电话'], ['estimatedArrivalAt', '预计到货时间']] as const) rules[field] = [{ required: true, message: '请填写' + label, trigger: 'change' }]
}
}
if (kind === 'truck') rules.vehicleType = [{ required: true, message: '请选择车辆类型', trigger: 'change' }]
for (const [field, label] of [['packageCount', '件数'], ['estimatedPalletCount', '预计托数'], ['totalWeightKg', '总重量'], ['totalVolumeCbm', '总体积']] as const) {
if (field === 'packageCount' && kind === 'truck') continue
rules[field] = [{ required: true, type: 'number', min: 0, message: `${label}须为不小于 0 的数字`, trigger: 'change' }]
}
rules.budgetAmount = [{ required: kind === 'truck', type: 'number', min: kind === 'truck' ? 0.01 : 0, message: '请输入大于 0 的预算总价', trigger: 'change' }]
const pickupLabel = kind === 'truck' ? '取货时间' : '取货时间', deliveryLabel = kind === 'truck' ? '送达时间' : '送货时间'
rules.pickupAt = [{ required: true, message: `请选择${pickupLabel}`, trigger: 'change' }]
rules.deliveryAt = [{ required: true, message: `请选择${deliveryLabel}`, trigger: 'change' }, {
validator: (_rule, value, callback) => callback(value && form.pickupAt && localMinuteInput(value) < localMinuteInput(form.pickupAt) ? new Error(`${deliveryLabel}不能早于${pickupLabel}`) : undefined), trigger: 'change',
}]
return rules
}
export function transportDemandError(kind: TransportDemandKind, form: TransportDemandForm): string | undefined {
if (kind === 'looseboard') {
if (!form.operatingWarehouseId) return '请选择收货仓库'
if (!['DELIVERY_TO_WAREHOUSE', 'WAREHOUSE_PICKUP'].includes(form.deliveryMode)) return '请选择送货方式'
if (form.destinationType === 'PRIVATE' && (!form.destinationAddress.trim() || !form.destinationPostalCode.trim())) return '请填写目的详细地址和邮编'
if (form.deliveryMode === 'DELIVERY_TO_WAREHOUSE' && (!form.deliveryContactName.trim() || !form.deliveryContactPhone.trim() || !form.estimatedArrivalAt)) return '送货到仓须填写仓库联系人和预计到货时间'
if (form.deliveryMode === 'WAREHOUSE_PICKUP' && !form.originAddress.trim()) return '请输入起运详细地址'
if (form.packageCount < 1) return '散板收货件数须大于 0'
}
if (kind === 'truck' && !['PALLET_15', 'PALLET_30'].includes(form.vehicleType)) return '请选择车辆类型'
const labels = requiredText(kind, form)
for (const [field, label] of Object.entries(labels)) {
if (!String(form[field as keyof typeof labels] || '').trim()) return `请输入${label}`
}
const pickupLabel = kind === 'truck' ? '取货时间' : '取货时间', deliveryLabel = kind === 'truck' ? '送达时间' : '送货时间'
for (const [field, label] of [['pickupAt', pickupLabel], ['deliveryAt', deliveryLabel]] as const) {
if (!form[field]) return `请选择${label}`
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?$/.test(form[field])) return `请选择有效的${label}`
}
if (localMinuteInput(form.deliveryAt) < localMinuteInput(form.pickupAt)) return `${deliveryLabel}不能早于${pickupLabel}`
for (const [field, label] of [['packageCount', '件数'], ['totalWeightKg', '总重量'], ['totalVolumeCbm', '总体积'], ...(kind === 'looseboard' ? [['estimatedPalletCount', '预计托数'] as const] : [])] as const) {
if (!Number.isFinite(form[field]) || form[field] < 0) return `${label}须为不小于 0 的数字`
}
if (!Number.isInteger(form.packageCount) || kind === 'looseboard' && !Number.isInteger(form.estimatedPalletCount)) return '件数和预计托数须为整数'
if (kind === 'truck' && (!Number.isSafeInteger(form.estimatedPalletCount) || form.estimatedPalletCount <= 0)) return '请输入大于 0 的托数'
if (kind === 'truck' && (form.budgetAmount == null || !Number.isFinite(form.budgetAmount) || form.budgetAmount <= 0)) return '请输入大于 0 的预算总价'
if (form.budgetAmount != null && (!Number.isFinite(form.budgetAmount) || form.budgetAmount < 0)) return '预算总价不能小于 0'
if (!['USD', 'CNY'].includes(form.currency)) return '请选择预算币种'
return undefined
}
function commonPayload(form: TransportDemandForm) {
return {
origin: form.origin.trim(), destination: form.destination.trim(),
originAddress: form.originAddress.trim() || undefined, destinationAddress: form.destinationAddress.trim() || undefined,
originContactName: form.originContactName.trim(), originContactPhone: form.originContactPhone.trim(),
destinationContactName: form.destinationContactName.trim(), destinationContactPhone: form.destinationContactPhone.trim(),
packageCount: form.packageCount, totalWeightKg: form.totalWeightKg, totalVolumeCbm: form.totalVolumeCbm,
budgetAmount: form.budgetAmount ?? undefined, currency: form.currency,
pickupAt: localMinuteInput(form.pickupAt), deliveryAt: localMinuteInput(form.deliveryAt), remark: form.remark.trim() || undefined,
}
}
type CommonPayload = ReturnType<typeof commonPayload>
type TruckPayload = Omit<CommonPayload, 'packageCount'> & { palletCount: number; vehicleType: 'PALLET_15' | 'PALLET_30' }
type LooseboardPayload = CommonPayload & { deliveryMode: 'DELIVERY_TO_WAREHOUSE' | 'WAREHOUSE_PICKUP'; operatingWarehouseId: string; destinationType: 'FBA' | 'PRIVATE'; destinationPostalCode?: string; deliveryContactName?: string; deliveryContactPhone?: string; estimatedArrivalAt?: string; trackingNo?: string; productName: string | undefined; estimatedPalletCount: number }
export function buildTransportDemand(kind: 'truck', form: TransportDemandForm): TruckPayload
export function buildTransportDemand(kind: 'looseboard', form: TransportDemandForm): LooseboardPayload
export function buildTransportDemand(kind: TransportDemandKind, form: TransportDemandForm): TruckPayload | LooseboardPayload {
const failure = transportDemandError(kind, form)
if (failure) throw new Error(failure)
const common = commonPayload(form)
return kind === 'truck'
? { ...(({ packageCount: _packages, ...rest }) => rest)(common), palletCount: form.estimatedPalletCount, vehicleType: form.vehicleType as 'PALLET_15' | 'PALLET_30' }
: { ...common, ...(form.deliveryMode === 'DELIVERY_TO_WAREHOUSE' ? { origin: '', originAddress: undefined, originContactName: '', originContactPhone: '' } : {}), deliveryMode: form.deliveryMode, operatingWarehouseId: form.operatingWarehouseId, deliveryContactName: form.deliveryMode === 'DELIVERY_TO_WAREHOUSE' ? form.deliveryContactName.trim() : undefined, deliveryContactPhone: form.deliveryMode === 'DELIVERY_TO_WAREHOUSE' ? form.deliveryContactPhone.trim() : undefined, estimatedArrivalAt: form.deliveryMode === 'DELIVERY_TO_WAREHOUSE' ? localMinuteInput(form.estimatedArrivalAt) : undefined, trackingNo: form.deliveryMode === 'DELIVERY_TO_WAREHOUSE' ? form.trackingNo.trim() || undefined : undefined, destinationType: form.destinationType, destinationPostalCode: form.destinationType === 'PRIVATE' ? form.destinationPostalCode.trim() : undefined, productName: form.productName.trim() || undefined, estimatedPalletCount: form.estimatedPalletCount }
}
@@ -0,0 +1,60 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import ts from 'typescript'
import * as vue from 'vue'
import { parse, compileScript } from 'vue/compiler-sfc'
const source = readFileSync(new URL('./components/TransportPhotoGallery.vue', import.meta.url), 'utf8')
const { descriptor } = parse(source)
const code = ts.transpileModule(compileScript(descriptor, { id: 'transport-photos' }).content, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
const flush = async () => { await vue.nextTick(); await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
function harness(kind, overrides = {}) {
const props = vue.reactive({ kind, orderNo: 'ORDER/1', refreshKey: 0 }), calls = [], disposers = [], created = [], revoked = []
const photos = { pickupPhotos: [{ fileId: '71', fileName: 'pickup.png', contentType: 'image/png', sizeBytes: 5 }], arrivalPhotos: [{ fileId: '72', fileName: 'arrival.png', contentType: 'image/png', sizeBytes: 6 }] }
const api = { getTransportPhotos: async (...args) => { calls.push(['list', ...args]); return photos }, readTransportPhoto: async (...args) => { calls.push(['file', ...args]); return {} }, ...overrides }
const context = { exports: {}, Error, URL: { createObjectURL: () => { const url = `blob:${created.length}`; created.push(url); return url }, revokeObjectURL: url => revoked.push(url) }, require(name) {
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => disposers.push(callback) }
if (name === '../api/businessOrders') return api
throw Error(name)
} }
runInNewContext(code, context)
const state = context.exports.default.setup(props, { expose() {} })
return { state, props, calls, created, revoked, photos, dispose: () => disposers.forEach(fn => fn()) }
}
for (const kind of ['looseboard', 'trucking']) test(`${kind} loads both photo nodes and refreshes with URL cleanup`, async () => {
const h = harness(kind); await flush()
assert.deepEqual(h.calls, [['list', kind, 'ORDER/1'], ['file', kind, 'ORDER/1', 'PICKUP', '71'], ['file', kind, 'ORDER/1', 'ARRIVAL', '72']])
assert.equal(h.state.previewUrls.value.length, 2)
h.props.refreshKey++; await flush()
assert.equal(h.revoked.length, 2)
assert.equal(h.state.previewUrls.value.length, 2)
h.dispose(); assert.equal(h.revoked.length, 4)
})
test('failed photo reads preserve the saved lists and allow retry', async () => {
let failed = true
const h = harness('looseboard', { readTransportPhoto: async () => { if (failed) throw Error('offline'); return {} } }); await flush()
assert.match(h.state.error.value, /加载失败/); assert.equal(h.state.photos.value.pickupPhotos.length, 1)
failed = false; await h.state.load(); await flush()
assert.equal(h.state.error.value, ''); assert.equal(h.state.previewUrls.value.length, 2); h.dispose()
})
test('responses after unmount do not allocate preview URLs', async () => {
let finish
const response = new Promise(resolve => { finish = resolve })
const h = harness('trucking', { readTransportPhoto: () => response }); await flush()
h.dispose(); finish({}); await flush(); assert.equal(h.created.length, 0)
})
test('merchant photo API uses order and phase routes with authenticated blob requests', async () => {
const api = readFileSync(new URL('./api/businessOrders.ts', import.meta.url), 'utf8')
const compiled = ts.transpileModule(api, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
const calls = [], context = { exports: {}, require: () => ({ apiRequest: request => calls.push(request), apiBlobRequest: request => calls.push(request) }) }
runInNewContext(compiled, context)
for (const [kind, route] of [['looseboard', 'local-looseboard-orders'], ['trucking', 'us-truck-orders']]) {
context.exports.getTransportPhotos(kind, 'ORDER/1')
assert.equal(calls.at(-1).url, `/merchant/v1/last-leg/${route}/ORDER%2F1/transport-photos`)
context.exports.readTransportPhoto(kind, 'ORDER/1', 'ARRIVAL', '72')
assert.equal(calls.at(-1).url, `/merchant/v1/last-leg/${route}/ORDER%2F1/transport-photos/ARRIVAL/72/content`)
}
assert.match(source, /preview-teleported/)
assert.match(source, /flex-wrap: wrap/)
})
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import BusinessOrdersView from '../components/BusinessOrdersView.vue' import BusinessOrdersView from '../components/BusinessOrdersView.vue'
defineProps<{ createPage?: boolean; detailPage?: boolean }>()
</script> </script>
<template><BusinessOrdersView kind="trucking" /></template> <template><BusinessOrdersView kind="trucking" :create-page="createPage" :detail-page="detailPage" /></template>
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import BusinessOrdersView from '../components/BusinessOrdersView.vue' import BusinessOrdersView from '../components/BusinessOrdersView.vue'
defineProps<{ createPage?: boolean; detailPage?: boolean }>()
</script> </script>
<template><BusinessOrdersView kind="looseboard" /></template> <template><BusinessOrdersView kind="looseboard" :create-page="createPage" :detail-page="detailPage" /></template>
@@ -1,5 +1,308 @@
<script setup lang="ts"> <script setup lang="ts">
import BusinessOrdersView from '../components/BusinessOrdersView.vue' import { computed, onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ApiError } from '@/api/types'
import { accessTokenIdentity } from '@/api/session'
import { useAuthStore } from '@/modules/auth/public'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
import type { TableAction } from '@/components/common/tableActions'
import ProcurementDetailPanel from '../components/ProcurementDetailPanel.vue'
import ProcurementDecisionDialog from '../components/ProcurementDecisionDialog.vue'
import { createProcurement, getProcurement, getProcurementWorkflow, listProcurements, type ProcurementDetail, type ProcurementSummary, type ProcurementWorkflow } from '../api/procurement'
import { procurementDirections, directionLabel, regionText, buildProcurementCreate, dateTime, draftBudgetTotal, emptyProcurementDraft, money, procurementStatuses, statusLabel, statusTone } from '../procurementPresentation'
import OrderFundingStatus from '../components/OrderFundingStatus.vue'
import { procurementRequestKey } from '../procurementSubmission'
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
const auth = useAuthStore(), route = useRoute(), router = useRouter()
const mode = computed(() => props.detailPage ? 'detail' : props.createPage ? 'create' : 'list')
const orderNo = computed(() => typeof route.params.orderNo === 'string' ? route.params.orderNo : '')
const canCreate = computed(() => auth.hasPermission('merchant:cross-border:procurement:create'))
const canList = computed(() => auth.hasPermission('merchant:cross-border:procurement:list'))
const identity = computed(() => auth.token ? accessTokenIdentity(auth.token) : null)
const companyName = computed(() => auth.profile.tenantName || (auth.user?.tenantName && !/^企业租户 \d+$/.test(auth.user.tenantName) ? auth.user.tenantName : ''))
const form = reactive(emptyProcurementDraft())
const formRef = ref<FormInstance>()
const formRules: FormRules<typeof form> = {
procurementDirection: [{ required: true, message: '请选择采购方向', trigger: 'change' }],
productName: [{ required: true, whitespace: true, message: '请输入商品名称', trigger: 'blur' }],
productUrl: [{ required: true, whitespace: true, message: '请输入商品链接', trigger: 'blur' }],
purchaseQuantity: [{ required: true, whitespace: true, message: '请输入采购数量', trigger: 'blur' }],
budgetUnitPrice: [{ required: true, whitespace: true, message: '请输入预算单价', trigger: 'blur' }],
currency: [{ required: true, message: '请选择预算币种', trigger: 'change' }],
contactName: [{ required: true, whitespace: true, message: '请输入收件人姓名', trigger: 'blur' }],
contactPhone: [{ required: true, whitespace: true, message: '请输入联系电话', trigger: 'blur' }],
receivingAddress: [{ required: true, whitespace: true, message: '请输入完整收货地址', trigger: 'blur' }],
}
const summaryQuantity = computed(() => /^\d+$/.test(form.purchaseQuantity) && Number.isSafeInteger(Number(form.purchaseQuantity)) && Number(form.purchaseQuantity) > 0 ? String(Number(form.purchaseQuantity)) : '—')
const summaryUnitPrice = computed(() => draftBudgetTotal({ ...form, purchaseQuantity: '1' }) ?? '—')
const summaryCurrencyName = computed(() => form.currency === 'USD' ? '美元' : '人民币')
const budgetTotal = computed(() => summaryQuantity.value === '—' ? null : draftBudgetTotal(form))
const submitError = ref(''), submittedOrder = ref('')
const submitting = ref(false), loading = ref(false), error = ref('')
const detail = shallowRef<ProcurementDetail | null>(null)
const workflow = shallowRef<ProcurementWorkflow | null>(null)
const decisionTarget = shallowRef<ProcurementSummary | null>(null)
const decision = ref<'confirm' | 'reject'>('confirm')
const rows = ref<ProcurementSummary[]>([]), total = ref(0)
const query = reactive({ page: 1, size: 20, orderNo: '', purchaseCategory: '', productName: '', status: '' })
let requestSequence = 0, active = true, inFlight = ''
let createAttempt: { fingerprint: string; key: string } | null = null
const queryModel = computed<QueryModel>({
get: () => ({ orderNo: query.orderNo, purchaseCategory: query.purchaseCategory, productName: query.productName, status: query.status }),
set: value => { for (const key of ['orderNo', 'purchaseCategory', 'productName', 'status'] as const) query[key] = String(value[key] || '') },
})
const queryFields: QueryField[] = [
{ key: 'orderNo', label: '采购单号', type: 'input' }, { key: 'purchaseCategory', label: '采购品类', type: 'input' },
{ key: 'productName', label: '商品名称', type: 'input' },
{ key: 'status', label: '履约进度', type: 'select', options: Object.entries(procurementStatuses).map(([value, label]) => ({ value, label })) },
]
const columns: DataTableColumn[] = [
{ key: 'actions', label: '操作', width: 260, fixed: 'left', slotName: 'actions' },
{ prop: 'procurementDirection', label: '采购方向', minWidth: 170, slotName: 'direction' },
{ prop: 'orderNo', label: '采购单号', minWidth: 250, slotName: 'orderNo' },
{ prop: 'purchaseCategory', label: '采购品类', width: 120 }, { prop: 'productName', label: '商品名称', minWidth: 200 },
{ prop: 'productSpecification', label: '商品规格', minWidth: 160 }, { prop: 'purchaseQuantity', label: '采购数量(件)', width: 135 },
{ prop: 'budgetUnitPrice', label: '预算单价', width: 155, slotName: 'budget' },
{ prop: 'status', label: '履约进度', width: 180, slotName: 'status' }, { prop: 'reviewRemark', label: '失败 / 拒绝原因', minWidth: 220, slotName: 'reviewRemark' }, { prop: 'createdAt', label: '下单时间', width: 185, slotName: 'createdAt' },
]
function rowActions(row: object): TableAction[] {
const order = row as ProcurementSummary
const actions: TableAction[] = [{ key: 'detail', label: '详情', run: () => openDetail(order) }]
if (canCreate.value && order.status === 'WAIT_CUSTOMER_CONFIRM') {
actions.push({ key: 'reject', label: '驳回', run: () => beginDecision(order, 'reject') }, { key: 'confirm', label: '确认采购结果', run: () => beginDecision(order, 'confirm') })
}
return actions
}
function beginDecision(order: ProcurementSummary, kind: 'confirm' | 'reject') {
if (!canCreate.value || order.status !== 'WAIT_CUSTOMER_CONFIRM') return
decision.value = kind; decisionTarget.value = order
}
function decisionChanged() { decisionTarget.value = null; void loadList() }
function openDetail(row: ProcurementSummary) { if (row.orderNo) void router.push({ name: 'cross-border-procurement-detail', params: { orderNo: row.orderNo } }) }
function returnToList() { if (canList.value) void router.push({ name: 'cross-border-procurement' }) }
function message(cause: unknown) {
if (cause instanceof ApiError && ((cause.status || 0) >= 500 || cause.code.startsWith('B'))) return '服务暂不可用,请稍后重试'
return cause instanceof Error ? cause.message : '请求失败,请稍后重试'
}
async function loadList() {
const params = { page: query.page, size: query.size, orderNo: query.orderNo || undefined, productName: query.productName || undefined, purchaseCategory: query.purchaseCategory || undefined, status: query.status || undefined }
const key = JSON.stringify([identity.value, params])
if (inFlight === key) return
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''
try { const result = await listProcurements(params); if (sequence === requestSequence) { rows.value = result.records; total.value = result.total } }
catch (cause) { if (sequence === requestSequence) { rows.value = []; total.value = 0; error.value = message(cause) } }
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
}
async function loadDetail() {
if (!orderNo.value) { error.value = '采购单号缺失'; return }
const key = JSON.stringify([identity.value, orderNo.value])
if (inFlight === key) return
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''; detail.value = null; workflow.value = null
try {
const [result, currentWorkflow] = await Promise.all([getProcurement(orderNo.value), getProcurementWorkflow(orderNo.value)])
if (sequence === requestSequence) { detail.value = result; workflow.value = currentWorkflow }
}
catch (cause) { if (sequence === requestSequence) error.value = message(cause) }
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
}
function search() { if (query.page === 1) void loadList(); else query.page = 1 }
function resetQuery() { const reload = query.page === 1; Object.assign(query, { page: 1, orderNo: '', purchaseCategory: '', productName: '', status: '' }); if (reload) void loadList() }
function resetForm() { submitError.value = ''; submittedOrder.value = ''; Object.assign(form, emptyProcurementDraft()); formRef.value?.clearValidate(); createAttempt = null }
async function submit() {
if (submitting.value || !canCreate.value || !identity.value || submittedOrder.value) return
const owner = identity.value; submitting.value = true; submitError.value = ''
try {
if (!formRef.value || !await formRef.value.validate().catch(() => false)) return
if (!active || owner !== identity.value) return
const payload = buildProcurementCreate(form, companyName.value, '')
const fingerprint = JSON.stringify([owner, payload])
if (createAttempt?.fingerprint !== fingerprint) createAttempt = { fingerprint, key: procurementRequestKey() }
if (!active || owner !== identity.value) return
const result = await createProcurement({ ...payload, idempotencyKey: createAttempt.key })
if (!active || owner !== identity.value) return
createAttempt = null; submittedOrder.value = result.order.orderNo
ElMessage.success(result.order.status === 'FUNDING_PENDING' ? '采购订单已受理,资金校验完成后进入平台审核' : '采购订单已提交')
if (canList.value) await router.push({ name: 'cross-border-procurement' })
} catch (cause) {
if (/已释放|已过期/.test(message(cause))) createAttempt = null
if (active && owner === identity.value) submitError.value = message(cause)
}
finally { submitting.value = false }
}
watch(() => [mode.value, orderNo.value, query.page, query.size, identity.value], (values, previous) => {
if (values[4] !== previous?.[4]) { rows.value = []; total.value = 0; createAttempt = null }
decisionTarget.value = null
++requestSequence; inFlight = ''; loading.value = false; error.value = ''; detail.value = null; workflow.value = null
if (mode.value === 'create') resetForm()
else if (mode.value === 'detail') void loadDetail()
else void loadList()
}, { immediate: true })
onBeforeUnmount(() => { active = false; ++requestSequence })
</script> </script>
<template><BusinessOrdersView kind="procurement" /></template> <template>
<section class="procurement-page client-ui" :class="{ 'procurement-page--create': mode === 'create' }" :aria-busy="loading || submitting">
<template v-if="mode === 'list'">
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="采购订单查询条件" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetQuery" />
<div class="procurement-table-card">
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="columns" :row-actions="rowActions" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" row-key="orderNo" empty-text="暂无采购订单">
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="router.push({ name: 'cross-border-procurement-create' })">新增下单</el-button></template>
<template v-if="error" #error><div class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadList">重新加载</el-button></div></template>
<template #orderNo="{ row }"><button class="procurement-link" type="button" @click="openDetail(row as ProcurementSummary)">{{ (row as ProcurementSummary).orderNo || '—' }}</button></template>
<template #budget="{ row }">{{ money((row as ProcurementSummary).budgetUnitPrice, (row as ProcurementSummary).currency) }}</template>
<template #direction="{ row }">{{ directionLabel((row as ProcurementSummary).procurementDirection) }}</template>
<template #status="{ row }"><el-tag :type="statusTone((row as ProcurementSummary).status)" size="small">{{ statusLabel((row as ProcurementSummary).status, (row as ProcurementSummary).procurementDirection) }}</el-tag></template>
<template #reviewRemark="{ row }"><OrderFundingStatus v-if="(row as ProcurementSummary).status === 'FUNDING_FAILED'" kind="procurement" :order-no="(row as ProcurementSummary).orderNo" :status="(row as ProcurementSummary).status" :can-retry="false" compact /><span v-else-if="(row as ProcurementSummary).status === 'REJECTED'">{{ (row as ProcurementSummary).reviewRemark || '未填写原因' }}</span><span v-else>—</span></template>
<template #createdAt="{ row }">{{ dateTime((row as ProcurementSummary).createdAt) }}</template>
</DataTable>
</div>
</template>
<section v-else-if="mode === 'detail'" v-loading="loading" class="procurement-detail" aria-label="采购订单详情">
<header class="procurement-heading"><div><el-button link type="primary" @click="returnToList">← 返回列表</el-button><h2>{{ detail?.order.orderNo || '采购订单详情' }}</h2></div><div><el-tag v-if="detail" :type="statusTone(workflow?.status || detail.order.status)">{{ statusLabel(workflow?.status || detail.order.status, detail.order.procurementDirection) }}</el-tag><el-button :disabled="loading" @click="loadDetail">刷新</el-button></div></header>
<OrderFundingStatus v-if="detail" kind="procurement" :order-no="detail.order.orderNo" :status="detail.order.status" :can-retry="canCreate" @changed="loadDetail" />
<div v-if="error" class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadDetail">重新加载</el-button></div>
<template v-else-if="detail && workflow"><el-alert v-if="workflow.status === 'RECEIVING' && workflow.rejectionReason" title="采购结果驳回原因" :description="workflow.rejectionReason" type="warning" :closable="false" /><ProcurementDetailPanel :detail="detail" :workflow="workflow" /></template><el-skeleton v-else :rows="8" animated />
</section>
<section v-else class="procurement-create" aria-label="采购下单">
<header class="procurement-create-heading">
<div><h1>海外采购下单</h1></div>
<el-button v-if="canList" :disabled="submitting" @click="returnToList">返回列表</el-button>
</header>
<el-result v-if="!canCreate" icon="warning" title="没有采购下单权限" sub-title="请联系企业管理员配置权限" />
<el-result v-else-if="submittedOrder" icon="success" title="采购订单已提交" :sub-title="submittedOrder"><template #extra><el-button @click="resetForm">新建另一单</el-button></template></el-result>
<template v-else>
<el-alert v-if="submitError" class="submit-error" :title="submitError" type="error" :closable="false" />
<section class="procurement-summary" aria-label="采购预算概览">
<article class="procurement-summary-card">
<div class="procurement-summary-title">
<span class="procurement-summary-icon procurement-summary-icon--quantity" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z" /><path d="M4 7.5l8 4.5 8-4.5M12 12v9" /></svg></span>
<h2>采购数量</h2>
</div>
<div class="procurement-summary-value">{{ summaryQuantity }}<small>件</small></div>
</article>
<article class="procurement-summary-card">
<div class="procurement-summary-title">
<span class="procurement-summary-icon procurement-summary-icon--price" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M3 12h4l3-8 4 16 3-8h4" /></svg></span>
<h2>预算单价</h2>
</div>
<div class="procurement-summary-value">{{ summaryUnitPrice }}</div>
</article>
<article class="procurement-summary-card">
<div class="procurement-summary-title">
<span class="procurement-summary-icon procurement-summary-icon--currency" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" /><path d="M12 7v10M9 9.5c0-1 1.3-1.7 3-1.7s3 .7 3 1.7-1.3 1.5-3 2-3 1-3 2.2 1.3 1.8 3 1.8 3-.8 3-1.8" /></svg></span>
<h2>预算币种</h2>
</div>
<div class="procurement-summary-value">{{ form.currency }}<small>{{ summaryCurrencyName }}</small></div>
</article>
</section>
<el-form ref="formRef" :model="form" :rules="formRules" label-position="top" :disabled="submitting" scroll-to-error @submit.prevent="submit">
<section class="procurement-form-section" aria-labelledby="procurement-product-heading">
<h3 id="procurement-product-heading"><span class="procurement-section-dot" aria-hidden="true" />商品与预算</h3>
<div class="procurement-form-card">
<el-form-item class="procurement-direction" label="采购方向" for="procurement-direction" prop="procurementDirection" required><el-select id="procurement-direction" v-model="form.procurementDirection" popper-class="procurement-create-select"><el-option v-for="(label, value) in procurementDirections" :key="value" :label="label" :value="value" /></el-select></el-form-item>
<div class="procurement-form-grid">
<el-form-item label="采购品类" for="procurement-category"><el-input id="procurement-category" v-model.trim="form.purchaseCategory" maxlength="128" placeholder="请输入品类" /></el-form-item>
<el-form-item label="商品名称" for="procurement-product" prop="productName" required><el-input id="procurement-product" v-model.trim="form.productName" maxlength="255" placeholder="请输入商品名称" /></el-form-item>
<el-form-item label="商品规格" for="procurement-specification"><el-input id="procurement-specification" v-model.trim="form.productSpecification" maxlength="500" placeholder="规格、型号" /></el-form-item>
<el-form-item label="采购数量(件)" for="procurement-quantity" prop="purchaseQuantity" required><el-input id="procurement-quantity" v-model.trim="form.purchaseQuantity" inputmode="numeric" maxlength="18" placeholder="正整数" /></el-form-item>
<el-form-item label="预算单价" for="procurement-price" prop="budgetUnitPrice" required><el-input id="procurement-price" v-model.trim="form.budgetUnitPrice" inputmode="decimal" maxlength="20" placeholder="请明确填写;免费样品填 0" /></el-form-item>
<el-form-item label="预算币种" for="procurement-currency" prop="currency" required><el-select id="procurement-currency" v-model="form.currency" popper-class="procurement-create-select"><el-option label="美元 USD" value="USD" /><el-option label="人民币 CNY" value="CNY" /></el-select></el-form-item>
<el-form-item class="full" label="商品链接" for="procurement-url" prop="productUrl" required><el-input id="procurement-url" v-model.trim="form.productUrl" maxlength="2000" placeholder="https://..." /></el-form-item>
</div>
<div class="procurement-budget-total">货款预算总上限:{{ money(budgetTotal, form.currency) }}</div>
</div>
</section>
<section class="procurement-form-section" aria-labelledby="procurement-recipient-heading">
<h3 id="procurement-recipient-heading"><span class="procurement-section-dot procurement-section-dot--recipient" aria-hidden="true" />{{ regionText('最终国内收件资料', form.procurementDirection) }}</h3>
<div class="procurement-form-card procurement-form-grid">
<el-form-item label="收件人" for="procurement-contact" prop="contactName" required><el-input id="procurement-contact" v-model.trim="form.contactName" maxlength="128" placeholder="实际收件人姓名" /></el-form-item>
<el-form-item label="联系电话" for="procurement-phone" prop="contactPhone" required><el-input id="procurement-phone" v-model.trim="form.contactPhone" maxlength="64" type="tel" placeholder="快递可联系的电话" /></el-form-item>
<el-form-item class="full" :label="regionText('完整国内地址', form.procurementDirection)" for="procurement-address" prop="receivingAddress" required><el-input id="procurement-address" v-model.trim="form.receivingAddress" maxlength="1000" :placeholder="form.procurementDirection === 'DOMESTIC_TO_OVERSEAS' ? '国家、州/省、市、邮编及详细地址' : '省、市、区县、街道及详细门牌'" /></el-form-item>
<el-form-item class="full" label="采购要求" for="procurement-requirements">
<el-input id="procurement-requirements" v-model="form.remark" type="textarea" :rows="4" maxlength="1000" resize="vertical" placeholder="填写采购要求(选填)" aria-describedby="procurement-requirements-count" />
<div id="procurement-requirements-count" class="procurement-character-count">{{ form.remark.length }} / 1000</div>
</el-form-item>
</div>
</section>
</el-form>
<footer class="procurement-form-actions"><el-button type="primary" :loading="submitting" :disabled="!companyName || !identity" @click="submit">提交采购订单</el-button></footer>
</template>
</section>
<ProcurementDecisionDialog v-if="decisionTarget" :key="`${identity}:${decisionTarget.orderNo}:${decision}`" :order="decisionTarget" :decision="decision" @close="decisionTarget = null" @changed="decisionChanged" />
</section>
</template>
<style scoped>
.procurement-page { display: grid; gap: var(--client-section-gap); min-width: 0; }
.procurement-table-card, .procurement-detail { min-width: 0; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
.procurement-table-card { overflow: hidden; }.procurement-detail { padding: 16px 20px 24px; }
.procurement-heading { display: flex; justify-content: space-between; align-items: center; gap: 20px; min-height: 54px; border-bottom: 1px solid var(--border); padding-bottom: 12px; }
.procurement-heading > div { display: flex; align-items: center; gap: 14px; min-width: 0; }.procurement-heading h2 { margin: 0; color: var(--navy); font-size: 18px; overflow-wrap: anywhere; }
.procurement-heading p { margin: 7px 0 0; font-size: 13px; color: var(--muted); }
.procurement-link { padding: 0; border: 0; background: transparent; color: var(--client-action); font: inherit; cursor: pointer; text-align: left; }.procurement-link:hover { text-decoration: underline; }
.procurement-error { min-height: 160px; display: flex; justify-content: center; align-items: center; gap: 16px; color: #b42318; }.procurement-error span { max-width: 900px; overflow-wrap: anywhere; }
.procurement-page--create { width: 100%; background: #f4f7fc; }
.procurement-create {
--client-action: #2f7bff;
--client-action-hover: #1d5fe0;
--client-border: #d5dce8;
--client-control-height: 44px;
--client-font-size: 14px;
--el-color-primary: #2f7bff;
--el-text-color-regular: #1f2937;
--el-text-color-placeholder: #b0b7c3;
min-width: 0;
color: #1f2937;
font: 14px/1.5 "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif;
}
.procurement-create-heading { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px; margin-bottom: 12px; }
.procurement-create-heading h1 { margin: 0; font-size: 26px; line-height: 1.4; font-weight: 700; }
.procurement-summary { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin-bottom: 12px; }
.procurement-summary-card { display: flex; flex-direction: column; gap: 8px; min-width: 0; padding: 12px 16px; border: 1px solid #e3e8f0; border-radius: 10px; background: #fff; }
.procurement-summary-title { display: flex; align-items: center; gap: 12px; }
.procurement-summary-title h2 { margin: 0; font-size: 15px; font-weight: 600; }
.procurement-summary-icon { display: grid; width: 44px; height: 44px; flex: 0 0 44px; place-items: center; border-radius: 8px; }
.procurement-summary-icon--quantity { color: #2f7bff; background: #eaf2ff; }
.procurement-summary-icon--price { color: #16a34a; background: #e8f8f0; }
.procurement-summary-icon--currency { color: #d97706; background: #fff5e0; }
.procurement-summary-icon svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.procurement-summary-value { color: #1d5fe0; font-size: 30px; font-weight: 700; line-height: 1.2; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.procurement-summary-value small { margin-left: 4px; color: #6b7280; font-size: 14px; font-weight: 500; }
.procurement-form-section { margin-bottom: 12px; }
.procurement-form-section h3 { display: flex; align-items: center; gap: 10px; margin: 0 0 10px; font-size: 18px; font-weight: 700; }
.procurement-section-dot { width: 9px; height: 9px; flex: 0 0 9px; border-radius: 50%; background: #2f7bff; }
.procurement-section-dot--recipient { background: #0ea5a4; }
.procurement-form-card { padding: 16px; border: 1px solid #e3e8f0; border-radius: 10px; background: #fff; }
.procurement-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px 20px; }
.procurement-form-grid .full { grid-column: 1 / -1; }
.procurement-create :deep(.el-form-item) { min-width: 0; margin: 0; }
.procurement-create :deep(.el-form-item__label) { height: auto; margin-bottom: 6px; padding: 0; color: #374151; font-size: 14px; font-weight: 600; line-height: 20px; }
.procurement-create :deep(.el-form-item.is-required .el-form-item__label::before) { color: #e5484d; }
.procurement-create :deep(.el-form-item__content) { min-width: 0; line-height: 20px; }
.procurement-create :deep(.el-form-item__error) { position: absolute; top: auto; bottom: calc(100% + 6px); right: 0; left: auto; width: auto; max-width: calc(100% - 120px); padding: 0; font-size: 12px; line-height: 20px; text-align: right; }
.procurement-create :deep(.procurement-direction) { width: calc((100% - 40px) / 3); margin-bottom: 12px; }
.procurement-create :deep(.el-select) { width: 100%; }
.procurement-create :deep(.el-input__wrapper), .procurement-create :deep(.el-select__wrapper), .procurement-create :deep(.el-textarea__inner) { border: 1px solid #d5dce8; border-radius: 6px; background: #fff; box-shadow: none; font-family: inherit; font-size: 14px; }
.procurement-create :deep(.el-input__wrapper), .procurement-create :deep(.el-select__wrapper) { min-height: 44px; padding: 10px 14px; }
.procurement-create :deep(.el-input__inner) { height: 22px; color: #1f2937; line-height: 22px; }
.procurement-create :deep(.el-textarea__inner) { min-height: 110px !important; padding: 11px 14px; color: #1f2937; line-height: 20px; }
.procurement-create :deep(.el-input__inner::placeholder), .procurement-create :deep(.el-textarea__inner::placeholder) { color: var(--el-text-color-placeholder); opacity: 1; }
.procurement-create :deep(.el-input__wrapper.is-focus), .procurement-create :deep(.el-select__wrapper.is-focused), .procurement-create :deep(.el-textarea__inner:focus) { outline: 2px solid #2f7bff; outline-offset: 0; }
.procurement-create :deep(.el-form-item.is-error .el-input__wrapper), .procurement-create :deep(.el-form-item.is-error .el-select__wrapper), .procurement-create :deep(.el-form-item.is-error .el-textarea__inner) { border-color: #e5484d; box-shadow: none; }
.procurement-create :deep(.el-input.is-disabled .el-input__wrapper), .procurement-create :deep(.el-select__wrapper.is-disabled), .procurement-create :deep(.el-textarea.is-disabled .el-textarea__inner) { background: #f6f9ff; }
.procurement-character-count { width: 100%; margin-top: 4px; color: #6b7280; font-size: 13px; text-align: right; }
.procurement-budget-total { margin-top: 10px; color: #6b7280; font-size: 13px; line-height: 20px; overflow-wrap: anywhere; }
.procurement-form-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 12px; }
.procurement-create :deep(.el-button) { margin-left: 0; padding: 10px 18px; border-radius: 6px; color: #1d5fe0; box-shadow: none; }
.procurement-create :deep(.el-button--primary) { height: auto; min-height: 44px; padding: 12px 28px; color: #fff; }
.procurement-create :deep(.el-button.is-disabled) { color: #98a2b3; }
.submit-error { margin: 0 0 20px; }
:global(.procurement-create-select.el-popper) { border: 1px solid #d5dce8; box-shadow: none; }
@media (max-width: 767px) {
.procurement-form-grid, .procurement-summary { grid-template-columns: 1fr; }.procurement-heading, .procurement-heading > div { flex-wrap: wrap; }
.procurement-create :deep(.procurement-direction) { width: 100%; }
}
</style>
+26
View File
@@ -0,0 +1,26 @@
# Client 工作台模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/dashboard/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
- 只有 `views/DashboardView.vue` 与 `overview.ts`;路由为空路径(登录后默认页)。
- 后端按卡片来源分别查 `order/`、`firstleg/`、`lastleg-service/`;本模块只做聚合展示。
## 页面与入口
| 目标 | 页面/入口 | API 与后端 |
|---|---|---|
| 业务总览卡片与快捷入口 | `views/DashboardView.vue` | `overview.ts`;按卡片对应的服务 |
| 卡片数据映射与跳转 | `overview.ts` | 各业务模块的公开 API |
## 关键边界
- 只展示服务端或既有模块返回的数据,不在首页二次统计或补算。
- 快捷入口跳转带明确业务筛选,不用标题文字反推状态。
- 首页不新增跨客户对比或内部经营指标;客户只能看到本企业数据。
- 卡片加载失败要单卡片降级,不阻塞整页。
## 验证
- 定向:`pnpm test src/modules/dashboard/<目标测试>`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+156
View File
@@ -0,0 +1,156 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import { loadDashboardOverview } from './overview.ts'
const dashboardView = readFileSync(new URL('./views/DashboardView.vue', import.meta.url), 'utf8')
const profile = 'company:profile:view'
const list = 'order:first-leg:list'
const edit = 'order:first-leg:edit'
const company = { tenantName: '示例企业', status: 'ACTIVE' }
function order(overrides = {}) {
return {
orderId: 101,
orderNo: 'ORDER-101',
inboundCode: 'INBOUND-101',
destinationWarehouseName: '示例目的仓',
channelName: '示例渠道',
mainStatus: 'WAIT_MEASURE',
customerFeeConfirmationRequired: false,
createdAt: '2026-09-18T08:00:00Z',
...overrides,
}
}
function draft(overrides = {}) {
return { ...order(), status: 'DRAFT', ...overrides }
}
function requests(overrides = {}) {
return {
company: async () => company,
orders: async () => ({ records: [order()] }),
drafts: async () => ({ records: [draft()] }),
...overrides,
}
}
test('only calls sources allowed by their complete permission requirements', async (t) => {
const cases = [
{ permissions: [], expected: [] },
{ permissions: [profile], expected: ['company'] },
{ permissions: [list], expected: ['orders'] },
{ permissions: [edit], expected: [] },
{ permissions: [list, edit], expected: ['orders', 'drafts'] },
{ permissions: [profile, list, edit], expected: ['company', 'orders', 'drafts'] },
]
for (const { permissions, expected } of cases) {
await t.test(permissions.join(',') || 'no permissions', async () => {
const calls = []
const result = await loadDashboardOverview(permissions, requests({
company: async () => { calls.push('company'); return company },
orders: async () => { calls.push('orders'); return { records: [order()] } },
drafts: async () => { calls.push('drafts'); return { records: [draft()] } },
}))
assert.deepEqual(calls, expected)
assert.equal(result.company, expected.includes('company') ? company : null)
assert.equal(result.orders.length, expected.includes('orders') ? 1 : 0)
assert.equal(result.drafts.length, expected.includes('drafts') ? 1 : 0)
assert.deepEqual(result.errors, {})
})
}
})
test('one failed source preserves successful sources and exposes its error', async (t) => {
for (const failedSource of ['company', 'orders', 'drafts']) {
await t.test(failedSource, async () => {
const result = await loadDashboardOverview([profile, list, edit], requests({
[failedSource]: async () => { throw new Error(`${failedSource} unavailable`) },
}))
assert.deepEqual(result.errors, { [failedSource]: `${failedSource} unavailable` })
assert.equal(result.company, failedSource === 'company' ? null : company)
assert.equal(result.orders.length, failedSource === 'orders' ? 0 : 1)
assert.equal(result.drafts.length, failedSource === 'drafts' ? 0 : 1)
})
}
})
test('loads sources concurrently and distinguishes a failed source from an empty result', async () => {
const pending = new Map()
const operation = loadDashboardOverview([profile, list, edit], requests(Object.fromEntries(
['company', 'orders', 'drafts'].map((source) => [source, () => new Promise((resolve, reject) => pending.set(source, { resolve, reject }))]),
)))
assert.deepEqual([...pending.keys()], ['company', 'orders', 'drafts'])
pending.get('company').resolve(company)
pending.get('orders').resolve({ records: [] })
pending.get('drafts').reject(null)
const result = await operation
assert.deepEqual(result.orders, [])
assert.equal(result.errors.orders, undefined)
assert.deepEqual(result.drafts, [])
assert.equal(result.errors.drafts, '订单草稿加载失败,请重试')
})
test('sorts each source by creation time and includes only actual drafts', async () => {
const orders = [
order({ orderId: 1, createdAt: '2026-09-16T08:00:00Z' }),
order({ orderId: 2, createdAt: '2026-09-18T08:00:00Z', mainStatus: 'COMPLETED', customerFeeConfirmationRequired: true }),
]
const drafts = [
draft({ orderId: 3, createdAt: '2026-09-15T08:00:00Z' }),
draft({ orderId: 4, status: 'SUBMITTED', createdAt: '2026-09-19T08:00:00Z' }),
draft({ orderId: 5, createdAt: '2026-09-17T08:00:00Z' }),
]
const result = await loadDashboardOverview([list, edit], requests({
orders: async () => ({ records: orders }),
drafts: async () => ({ records: drafts }),
}))
assert.deepEqual(result.orders.map(({ id }) => id), ['2', '1'])
assert.deepEqual(result.drafts.map(({ id }) => id), ['5', '3'])
assert.equal(result.orders[0].status, 'COMPLETED')
assert.equal(result.orders[0].requiresFeeConfirmation, true)
assert.ok(result.drafts.every(({ status, requiresFeeConfirmation }) => status === 'DRAFT' && !requiresFeeConfirmation))
assert.deepEqual(orders.map(({ orderId }) => orderId), [1, 2])
assert.deepEqual(drafts.map(({ orderId }) => orderId), [3, 4, 5])
})
test('keeps absent business numbers null and internal identifiers out of display fields', async () => {
const missing = { orderId: 987654, orderNo: null, inboundCode: null, destinationWarehouseName: null, channelName: null }
const result = await loadDashboardOverview([list, edit], requests({
orders: async () => ({ records: [order(missing)] }),
drafts: async () => ({ records: [draft(missing)] }),
}))
for (const item of [...result.orders, ...result.drafts]) {
assert.equal(item.id, '987654')
assert.equal(item.orderNo, null)
assert.equal(item.inboundCode, null)
assert.equal(item.destination, null)
assert.equal(item.channel, null)
}
})
test('matches the updated six-action icon and motion treatment', () => {
assert.match(dashboardView, /icon: Forklift/)
assert.doesNotMatch(dashboardView, /PanelsTopLeft/)
assert.match(dashboardView, /featured: true/)
assert.match(dashboardView, /quick-action--featured/)
assert.match(dashboardView, /featured-aura 5s ease-in-out infinite/)
assert.match(dashboardView, /featured-shine 3\.6s ease-in-out infinite/)
assert.match(dashboardView, /\.quick-action:hover \{[^}]*border-color:[^}]*transform: translateY\(-9px\);/)
assert.match(dashboardView, /prefers-reduced-motion: reduce/)
assert.match(dashboardView, /\.client-dashboard a:focus-visible/)
})
test('opens all six dashboard businesses through their dedicated create pages', () => {
for (const route of [
'/orders/first-leg/create',
'/overseas-warehouse/return-relabel/create',
'/cross-border/domestic-trucking/create',
'/cross-border/pallet-shipping/create',
'/cross-border/procurement/create',
'/overseas-warehouse/labeling/create',
]) assert.match(dashboardView, new RegExp(`route: '${route.replaceAll('/', '\\/')}'`))
assert.match(dashboardView, /title: '退货换标'[\s\S]*?permission: 'merchant:overseas-warehouse:return-order:create'/)
})
+94
View File
@@ -0,0 +1,94 @@
import type { FirstLegOrderStatus } from '@chongchong/shared'
import type { MerchantFirstLegOrderRow, MerchantUnifiedOrderRow } from '@/modules/first-leg/public'
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
export interface DashboardCompany {
tenantName: string
status: MerchantTenantStatus
}
export interface DashboardOrder {
id: string
orderNo: string | null
inboundCode: string | null
destination: string | null
channel: string | null
status: FirstLegOrderStatus
createdAt: string
requiresFeeConfirmation: boolean
}
export type DashboardSource = 'company' | 'orders' | 'drafts'
export interface DashboardOverview {
company: DashboardCompany | null
orders: DashboardOrder[]
drafts: DashboardOrder[]
errors: Partial<Record<DashboardSource, string>>
}
interface DashboardRequests {
company: () => Promise<DashboardCompany>
orders: () => Promise<{ records: MerchantUnifiedOrderRow[] }>
drafts: () => Promise<{ records: MerchantFirstLegOrderRow[] }>
}
const sourceErrorMessages: Record<DashboardSource, string> = {
company: '企业资料加载失败,请重试',
orders: '订单动态加载失败,请重试',
drafts: '订单草稿加载失败,请重试',
}
function newestFirst(records: DashboardOrder[]) {
return records.sort((left, right) => (Date.parse(right.createdAt) || 0) - (Date.parse(left.createdAt) || 0))
}
export async function loadDashboardOverview(permissions: readonly string[], requests: DashboardRequests): Promise<DashboardOverview> {
const result: DashboardOverview = { company: null, orders: [], drafts: [], errors: {} }
const allowed = new Set(permissions)
const tasks: Array<{ source: DashboardSource; run: () => Promise<void> }> = []
if (allowed.has('company:profile:view')) {
tasks.push({ source: 'company', run: async () => { result.company = await requests.company() } })
}
if (allowed.has('order:first-leg:list')) {
tasks.push({ source: 'orders', run: async () => {
const response = await requests.orders()
result.orders = newestFirst(response.records.map((order) => ({
id: String(order.orderId),
orderNo: order.orderNo ?? null,
inboundCode: order.inboundCode ?? null,
destination: order.destinationWarehouseName ?? null,
channel: order.channelName ?? null,
status: order.mainStatus,
createdAt: order.createdAt,
requiresFeeConfirmation: order.customerFeeConfirmationRequired === true,
})))
} })
if (allowed.has('order:first-leg:edit')) {
tasks.push({ source: 'drafts', run: async () => {
const response = await requests.drafts()
result.drafts = newestFirst(response.records.filter((order) => order.status === 'DRAFT').map((order) => ({
id: String(order.orderId),
orderNo: order.orderNo ?? null,
inboundCode: order.inboundCode ?? null,
destination: order.destinationWarehouseName ?? null,
channel: order.channelName ?? null,
status: 'DRAFT',
createdAt: order.createdAt,
requiresFeeConfirmation: false,
})))
} })
}
}
const settled = await Promise.allSettled(tasks.map(async (task) => task.run()))
settled.forEach((outcome, index) => {
if (outcome.status === 'fulfilled') return
const source = tasks[index]!.source
result.errors[source] = outcome.reason instanceof Error && outcome.reason.message.trim()
? outcome.reason.message
: sourceErrorMessages[source]
})
return result
}
+1 -1
View File
@@ -9,7 +9,7 @@ export const dashboardModule = {
name: 'dashboard', name: 'dashboard',
component: () => import('./views/DashboardView.vue'), component: () => import('./views/DashboardView.vue'),
release: 'active', release: 'active',
meta: { title: '业务总览', description: '企业账户与头程业务概览', permission: 'dashboard:view' }, meta: { title: '业务总览', description: '企业账户与头程业务概览', permission: 'dashboard:view', workspaceTab: false },
navigation: { key: 'dashboard', icon: Gauge }, navigation: { key: 'dashboard', icon: Gauge },
}, },
], ],
@@ -1,49 +0,0 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const source = readFileSync(new URL('./DashboardView.vue', import.meta.url), 'utf8')
test('loads real dashboard data allowed by the current permissions', () => {
assert.match(source, /auth\.hasPermission\('company:profile:view'\).*tenant\.loadCompanyContext\(\)/)
assert.match(source, /auth\.hasPermission\('company:member:list'\).*tenant\.loadMembers\(\)/)
assert.match(source, /auth\.hasPermission\('order:first-leg:list'\).*orders\.load\(\)/)
assert.match(source, /onMounted\(async \(\) => \{\s*await loadDashboardData\(\)\s*showQualificationReminderOnce\(\)\s*\}\)/)
})
test('prompts once per session for incomplete company qualification and opens the upload dialog', () => {
assert.match(source, /\['PROFILE_REQUIRED', 'REJECTED'\]\.includes\(tenant\.company\.auditStatus\)/)
assert.match(source, /sessionStorage\.getItem\(reminderKey\)/)
assert.match(source, /sessionStorage\.setItem\(reminderKey, 'shown'\)/)
assert.match(source, /title="完善企业认证资料"/)
assert.match(source, /立即上传认证资料/)
assert.match(source, /router\.push\(\{ path: '\/company\/profile', query: \{ qualification: 'upload' \} \}\)/)
})
test('isolates recoverable dashboard failures without hiding successful sections', () => {
assert.match(source, /Promise\.allSettled/)
assert.match(source, /Partial<Record<DashboardDataSource, string>>/)
assert.match(source, /:aria-busy="loading"/)
assert.match(source, /role="alert"/)
assert.match(source, /部分业务数据加载失败/)
assert.match(source, /ordersUnavailable/)
assert.match(source, /companyUnavailable/)
assert.match(source, /订单数据暂不可用,请重新加载后查看。/)
assert.match(source, /企业资料暂不可用,请重新加载后查看。/)
assert.match(source, /@click="loadDashboardData"/)
assert.doesNotMatch(source, /<template v-else>\s*<section class="quick-order-band">/)
})
test('matches the prototype business overview and routes each card to its real business page', () => {
assert.match(source, /选择业务,快速下单/)
assert.match(source, /海外采购/)
assert.match(source, /美国本土卡/)
assert.match(source, /美本土散板/)
assert.match(source, /route: '\/cross-border\/procurement'/)
assert.match(source, /route: '\/cross-border\/domestic-trucking'/)
assert.match(source, /route: '\/cross-border\/pallet-shipping'/)
assert.match(source, /auth\.hasPermission\(business\.permission\)/)
assert.match(source, /order\.status === 'DELIVERED'/)
assert.match(source, /currentMonthOrderCount/)
assert.match(source, /提交订单后,专属客户经理将在 24 小时内与您联系/)
})
+84 -620
View File
@@ -1,640 +1,104 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue' import { computed } from 'vue'
import { useRouter } from 'vue-router' import { ArrowRight, Forklift, PackageOpen, RefreshCcw, Ship, ShoppingCart, Tags, Truck, Warehouse } from '@lucide/vue'
import { ElMessage } from 'element-plus'
import {
AlertTriangle,
ArrowRight,
CircleQuestionMark,
Headphones,
Lightbulb,
PanelsTopLeft,
ShoppingCart,
Tags,
Truck,
} from '@lucide/vue'
import { useFirstLegOrdersStore } from '@/modules/first-leg/public'
import { useTenantAdministrationStore } from '@/modules/tenant-management/public'
import { useAuthStore } from '@/modules/auth/public' import { useAuthStore } from '@/modules/auth/public'
import { FirstLegOrdersView } from '@/modules/first-leg/public'
const router = useRouter()
const orders = useFirstLegOrdersStore()
const tenant = useTenantAdministrationStore()
const auth = useAuthStore() const auth = useAuthStore()
const loading = ref(false)
const qualificationReminderOpen = ref(false)
type DashboardDataSource = 'company' | 'members' | 'orders'
const loadErrors = ref<Partial<Record<DashboardDataSource, string>>>({})
const dataSourceLabels: Record<DashboardDataSource, string> = {
company: '企业资料',
members: '企业成员',
orders: '头程订单',
}
const companyUnavailable = computed(() => Boolean(loadErrors.value.company)) const primaryActions = computed(() => [
const ordersUnavailable = computed(() => Boolean(loadErrors.value.orders)) { title: '头程下单', description: '国内提货 · 海运订舱 · 清关派送', icon: Ship, route: '/orders/first-leg/create', permission: 'order:first-leg:create', tone: 'blue', featured: true },
const loadErrorItems = computed(() => { title: '退货换标', description: '退件接收 · 标签更换 · 重新入仓', icon: RefreshCcw, route: '/overseas-warehouse/return-relabel/create', permission: 'merchant:overseas-warehouse:return-order:create', tone: 'purple', featured: false },
(Object.keys(loadErrors.value) as DashboardDataSource[]).map((key) => ({ { title: '美国本土卡', description: '港口提柜 · 仓到仓 · 仓到门', icon: Truck, route: '/cross-border/domestic-trucking/create', permission: 'merchant:cross-border:domestic-trucking:create', tone: 'green', featured: false },
key, { title: '美本土散板', description: '拼车拼载 · 打盘服务 · 灵活派送', icon: Forklift, route: '/cross-border/pallet-shipping/create', permission: 'merchant:cross-border:pallet-shipping:create', tone: 'cyan', featured: false },
label: dataSourceLabels[key], { title: '海外采购', description: '采购代购 · 验货质检 · 集中发货', icon: ShoppingCart, route: '/cross-border/procurement/create', permission: 'merchant:cross-border:procurement:create', tone: 'orange', featured: false },
message: loadErrors.value[key] ?? '请求失败', { title: '贴标申请', description: '产品建档 · 标签上传 · 批量贴标', icon: Tags, route: '/overseas-warehouse/labeling/create', permission: 'merchant:overseas-warehouse:relabel:create', tone: 'rose', featured: false },
})), { title: '仓储转运', description: '仓储管理 · 货物转运', icon: Warehouse, route: '/overseas-warehouse/storage-transfer/create', permission: 'merchant:overseas-warehouse:transfer:create', tone: 'teal', featured: false, actionLabel: '开始办理' },
) { title: '货物废弃', description: '废弃申请 · 处理进度', icon: PackageOpen, route: '/overseas-warehouse/cargo-disposal/create', permission: 'merchant:overseas-warehouse:discard:create', tone: 'brown', featured: false, actionLabel: '开始办理' },
const canViewOrders = computed(() => auth.hasPermission('order:first-leg:list')) ].filter((action) => auth.hasPermission(action.permission)))
const accountName = computed(() => {
if (!companyUnavailable.value && tenant.company.companyName) return tenant.company.companyName
return auth.user?.tenantName || auth.user?.name || '企业客户'
})
const accountInitial = computed(() => accountName.value.trim().slice(0, 1).toUpperCase() || 'C')
const completedOrderCount = computed(() => orders.orders.filter((order) => order.status === 'DELIVERED').length)
const currentMonthOrderCount = computed(() => {
const now = new Date()
return orders.orders.filter((order) => {
const createdAt = new Date(order.createdAt)
return !Number.isNaN(createdAt.getTime())
&& createdAt.getFullYear() === now.getFullYear()
&& createdAt.getMonth() === now.getMonth()
}).length
})
const overviewStats = computed(() => [
{ label: '进行中订单', value: dashboardOrderValue(orders.activeCount) },
{ label: '已完成订单', value: dashboardOrderValue(completedOrderCount.value) },
{ label: '本月下单', value: dashboardOrderValue(currentMonthOrderCount.value) },
])
const businessCards = [
{
title: '海外采购',
description: '采购代购 · 验货质检 · 集中发货',
icon: ShoppingCart,
tone: 'blue',
route: '/cross-border/procurement',
permission: 'merchant:cross-border:procurement',
},
{
title: '美国本土卡',
description: '港口提柜 · 仓到仓 · 仓到门',
icon: Truck,
tone: 'green',
route: '/cross-border/domestic-trucking',
permission: 'merchant:cross-border:domestic-trucking',
},
{
title: '美本土散板',
description: '拼车拼载 · 打盘服务 · 灵活派送',
icon: PanelsTopLeft,
tone: 'teal',
route: '/cross-border/pallet-shipping',
permission: 'merchant:cross-border:pallet-shipping',
},
] as const
function dashboardOrderValue(value: number) {
if (!canViewOrders.value || ordersUnavailable.value) return '—'
return String(value)
}
function errorMessage(error: unknown) {
return error instanceof Error ? error.message : '请求失败,请稍后重试'
}
async function loadDashboardData() {
loading.value = true
loadErrors.value = {}
const requests: Array<{ source: DashboardDataSource; request: Promise<unknown> }> = []
if (auth.hasPermission('company:profile:view')) requests.push({ source: 'company', request: tenant.loadCompanyContext() })
if (auth.hasPermission('company:member:list')) requests.push({ source: 'members', request: tenant.loadMembers() })
if (auth.hasPermission('order:first-leg:list')) requests.push({ source: 'orders', request: orders.load() })
try {
const results = await Promise.allSettled(requests.map(({ request }) => request))
const nextErrors: Partial<Record<DashboardDataSource, string>> = {}
results.forEach((result, index) => {
const request = requests[index]
if (request && result.status === 'rejected') nextErrors[request.source] = errorMessage(result.reason)
})
loadErrors.value = nextErrors
} finally {
loading.value = false
}
}
function showQualificationReminderOnce() {
if (companyUnavailable.value || !auth.hasPermission('company:qualification:upload')) return
if (!['PROFILE_REQUIRED', 'REJECTED'].includes(tenant.company.auditStatus)) return
const reminderKey = `client-qualification-reminder:${auth.user?.id ?? 'current'}`
if (sessionStorage.getItem(reminderKey)) return
sessionStorage.setItem(reminderKey, 'shown')
qualificationReminderOpen.value = true
}
async function openQualificationUpload() {
qualificationReminderOpen.value = false
await router.push({ path: '/company/profile', query: { qualification: 'upload' } })
}
function openBusinessOrder(business: typeof businessCards[number]) {
if (auth.hasPermission(business.permission)) {
void router.push(business.route)
return
}
ElMessage.warning(`当前账号暂无${business.title}权限,请联系企业管理员。`)
}
function showSupportMessage(type: 'service' | 'faq' | 'quote') {
const messages = {
service: '客服联系方式正在配置中,请联系您的专属客户经理。',
faq: '常见问题页面即将上线。',
quote: '提交订单后,客户经理将根据货物信息为您提供报价。',
}
ElMessage.info(messages[type])
}
onMounted(async () => {
await loadDashboardData()
showQualificationReminderOnce()
})
</script> </script>
<template> <template>
<div v-loading="loading" class="client-dashboard" :aria-busy="loading"> <div class="client-dashboard">
<el-dialog v-model="qualificationReminderOpen" title="完善企业认证资料" width="min(520px, 92vw)" append-to-body> <header class="business-intro">
<p class="qualification-reminder-copy">请先上传营业执照和统一社会信用代码并提交审核;法人身份证及其他资质可选填。审核通过后即可提交头程订单。</p> <h1>选择业务,快速下单</h1>
<template #footer><el-button @click="qualificationReminderOpen = false">稍后处理</el-button><el-button type="primary" @click="openQualificationUpload">立即上传认证资料</el-button></template>
</el-dialog>
<div v-if="loadErrorItems.length" class="dashboard-load-error" role="alert">
<AlertTriangle :size="20" aria-hidden="true" />
<div>
<strong>部分业务数据加载失败</strong>
<ul>
<li v-for="item in loadErrorItems" :key="item.key">
<span>{{ item.label }}:</span>{{ item.message }}
</li>
</ul>
</div>
<el-button :loading="loading" @click="loadDashboardData">重新加载</el-button>
</div>
<div class="dashboard-layout">
<main class="dashboard-business" aria-labelledby="dashboard-heading">
<header class="dashboard-intro">
<h2 id="dashboard-heading">选择业务,快速下单</h2>
<p>请选择您需要的业务类型,填写信息后提交订单,我们将尽快为您安排。</p>
</header> </header>
<section class="business-card-grid" aria-label="可选业务"> <section class="quick-actions" aria-label="业务选择">
<button <RouterLink v-for="(action, index) in primaryActions" :key="action.route" :to="action.route" class="quick-action" :class="[`quick-action--${action.tone}`, { 'quick-action--featured': action.featured }]" :style="{ '--entry-index': index }">
v-for="business in businessCards" <span class="action-icon"><component :is="action.icon" :size="25" :stroke-width="2.2" aria-hidden="true" /></span>
:key="business.title" <span class="action-copy"><strong>{{ action.title }}</strong><small>{{ action.description }}</small></span>
type="button" <span class="action-enter"><span>{{ action.actionLabel ?? '开始下单' }}</span><ArrowRight :size="15" aria-hidden="true" /></span>
class="business-card" </RouterLink>
:class="`business-card--${business.tone}`" <p v-if="!primaryActions.length" class="no-actions">当前账号暂无常用业务权限,请通过已授权菜单办理业务,或联系企业管理员。</p>
@click="openBusinessOrder(business)"
>
<span class="business-card__icon" aria-hidden="true">
<component :is="business.icon" :size="29" :stroke-width="2.4" />
</span>
<span class="business-card__copy">
<strong>{{ business.title }}</strong>
<small>{{ business.description }}</small>
</span>
<span class="business-card__action">
{{ auth.hasPermission(business.permission) ? '开始下单' : '暂无权限' }}
<ArrowRight :size="18" aria-hidden="true" />
</span>
</button>
</section>
</main>
<aside class="dashboard-aside" aria-label="账户与业务信息">
<section class="aside-card account-card">
<h3>账户信息</h3>
<div class="account-summary">
<span class="account-avatar">{{ accountInitial }}</span>
<span class="account-copy">
<strong>{{ accountName }}</strong>
<small>企业客户</small>
</span>
</div>
<p v-if="companyUnavailable" class="account-load-error" role="status">企业资料暂不可用,请重新加载后查看。</p>
</section> </section>
<section class="aside-card"> <FirstLegOrdersView v-if="auth.hasPermission('order:first-leg:list')" :show-create-action="false" class="dashboard-order-list" />
<h3>数据概览</h3> <section v-else class="orders-permission-empty">
<dl class="overview-stats"> <strong>暂无头程订单查看权限</strong>
<div v-for="stat in overviewStats" :key="stat.label"> <span>需要查看企业订单时,请联系企业管理员开通。</span>
<dt>{{ stat.label }}</dt>
<dd>{{ stat.value }}</dd>
</div>
</dl>
<p v-if="ordersUnavailable" class="dashboard-section-error" role="status">订单数据暂不可用,请重新加载后查看。</p>
</section> </section>
<section class="aside-card">
<h3>帮助与支持</h3>
<div class="support-links">
<button type="button" @click="showSupportMessage('service')"><Headphones :size="19" /><span>联系客服</span></button>
<button type="button" @click="showSupportMessage('faq')"><CircleQuestionMark :size="19" /><span>常见问题</span></button>
<button type="button" @click="showSupportMessage('quote')"><Tags :size="19" /><span>获取报价</span></button>
</div>
</section>
<div class="dashboard-tip">
<Lightbulb :size="19" aria-hidden="true" />
<p>提交订单后,专属客户经理将在 24 小时内与您联系,确认运输方案与报价。</p>
</div>
</aside>
</div>
</div> </div>
</template> </template>
<style scoped> <style scoped>
.client-dashboard { .client-dashboard { display: flex; min-width: 0; container-name: dashboard-content; container-type: inline-size; flex-direction: column; gap: 14px; padding: 0 8px 18px; color: var(--navy); animation: dashboard-enter .3s ease-out both; }
--dashboard-blue: #1565c0; .business-intro { padding-top: 0; }
--dashboard-green: #3f9f47; .business-intro h1 { margin: 0; color: #172033; font-size: 27px; font-weight: 750; letter-spacing: -.5px; line-height: 1.3; }
--dashboard-teal: #078a99; .business-intro p { margin: 5px 0 0; color: #7a8495; font-size: 13px; line-height: 1.55; }
display: block; .quick-actions { display: grid; grid-template-columns: repeat(8, minmax(150px, 1fr)); gap: 10px; overflow-x: auto; padding: 0 0 6px; scroll-snap-type: x proximity; scrollbar-color: #bdc9dc transparent; scrollbar-width: thin; }
min-height: calc(100vh - 128px); .quick-actions::-webkit-scrollbar { height: 7px; }
} .quick-actions::-webkit-scrollbar-thumb { border-radius: 999px; background: #bdc9dc; }
.quick-actions::-webkit-scrollbar-track { background: transparent; }
.dashboard-load-error { .quick-action { scroll-snap-align: start; }
margin-bottom: 20px; .quick-action { --action-a: #2563eb; --action-b: #3730a3; --action-soft: rgba(37, 99, 235, .18); position: relative; isolation: isolate; display: flex; min-width: 0; min-height: 190px; overflow: hidden; align-items: center; flex-direction: column; padding: 21px 10px 18px; border: 1px solid rgba(148, 163, 184, .2); border-radius: 17px; background: linear-gradient(155deg, #fff 8%, rgba(248, 250, 252, .96) 100%); color: inherit; text-align: center; text-decoration: none; box-shadow: 0 12px 34px rgba(15, 23, 42, .07); backdrop-filter: blur(10px); animation: action-enter .4s cubic-bezier(.22, 1, .36, 1) both; animation-delay: calc(var(--entry-index) * 55ms); transition: border-color .35s ease, box-shadow .35s ease, transform .35s cubic-bezier(.22, 1, .36, 1); }
} .quick-action::before { position: absolute; width: 120px; height: 120px; border-radius: 50%; background: radial-gradient(circle, var(--action-soft), transparent 70%); content: ''; right: -62px; top: -66px; transition: transform .4s ease; }
.quick-action::after { position: absolute; right: 20%; bottom: 0; left: 20%; height: 3px; border-radius: 99px 99px 0 0; background: linear-gradient(90deg, var(--action-a), var(--action-b)); content: ''; opacity: .55; transform: scaleX(.35); transition: all .35s ease; }
.qualification-reminder-copy { margin: 0; color: #475467; font-size: 14px; line-height: 1.75; } .quick-action--blue { --action-a: #2563eb; --action-b: #3730a3; --action-soft: rgba(37, 99, 235, .18); }
.quick-action--purple { --action-a: #8b5cf6; --action-b: #c026d3; --action-soft: rgba(139, 92, 246, .18); }
.dashboard-load-error ul { .quick-action--green { --action-a: #059669; --action-b: #0f766e; --action-soft: rgba(5, 150, 105, .18); }
display: grid; .quick-action--cyan { --action-a: #0891b2; --action-b: #0e7490; --action-soft: rgba(8, 145, 178, .18); }
gap: 3px; .quick-action--orange { --action-a: #f59e0b; --action-b: #dc6b12; --action-soft: rgba(245, 158, 11, .2); }
margin: 0; .quick-action--rose { --action-a: #e11d48; --action-b: #be185d; --action-soft: rgba(225, 29, 72, .17); }
padding: 0; .quick-action--teal { --action-a: #0f766e; --action-b: #0e7490; --action-soft: rgba(15, 118, 110, .18); }
list-style: none; .quick-action--brown { --action-a: #b45309; --action-b: #c2410c; --action-soft: rgba(180, 83, 9, .18); }
} .quick-action:hover { border-color: color-mix(in srgb, var(--action-a) 35%, transparent); box-shadow: 0 24px 54px rgba(15, 23, 42, .14), 0 0 0 1px color-mix(in srgb, var(--action-a) 16%, transparent); transform: translateY(-9px); }
.quick-action:hover::before { transform: scale(1.25); }
.dashboard-load-error li { .quick-action:hover::after { right: 12%; left: 12%; opacity: 1; transform: scaleX(1); }
overflow-wrap: anywhere; .action-icon { position: relative; display: grid; width: 58px; height: 58px; flex: 0 0 auto; place-items: center; margin-bottom: 16px; border-radius: 18px; background: linear-gradient(135deg, var(--action-a), var(--action-b)); color: #fff; box-shadow: 0 11px 22px color-mix(in srgb, var(--action-a) 25%, transparent); transition: transform .35s ease; }
color: var(--muted); .action-icon::before { position: absolute; inset: 7px; border-radius: 12px; background: linear-gradient(135deg, rgba(255, 255, 255, .32), transparent 42%); content: ''; pointer-events: none; }
font-size: 12px; .action-icon::after { position: absolute; border: 1px solid color-mix(in srgb, var(--action-a) 20%, transparent); border-radius: 22px; content: ''; inset: -5px; }
line-height: 1.5; .quick-action:hover .action-icon { transform: translateY(-3px) scale(1.06) rotate(-3deg); }
} .action-copy { position: relative; display: flex; min-width: 0; width: 100%; align-items: center; flex-direction: column; }
.action-copy strong { color: #172033; font-size: 16px; font-weight: 800; line-height: 1.35; white-space: nowrap; }
.dashboard-load-error li span { .action-copy small { overflow: hidden; width: 100%; margin-top: 6px; color: #718096; font-size: 11px; line-height: 1.5; text-overflow: ellipsis; white-space: nowrap; }
color: #9a5a09; .action-enter { position: relative; display: inline-flex; align-items: center; gap: 6px; margin-top: auto; color: var(--action-a); font-size: 11px; font-weight: 750; }
font-weight: 650; .action-enter svg { transition: transform .25s ease; }
} .quick-action:hover .action-enter svg { transform: translateX(4px); }
.quick-action--featured { border-color: rgba(49, 126, 255, .62); background: radial-gradient(circle at 8% 2%, rgba(34, 211, 238, .23), transparent 32%), radial-gradient(circle at 100% 100%, rgba(79, 70, 229, .22), transparent 44%), linear-gradient(145deg, #f2fbff 0%, #f8faff 45%, #eef2ff 100%); box-shadow: 0 20px 48px rgba(37, 99, 235, .2), 0 0 0 1px rgba(255, 255, 255, .88) inset, 0 0 34px rgba(34, 211, 238, .1); }
.dashboard-layout { .quick-action--featured::before { width: 220px; height: 220px; right: -88px; top: -112px; background: radial-gradient(circle, rgba(34, 211, 238, .35) 0%, rgba(59, 130, 246, .2) 34%, transparent 69%); filter: blur(1px); animation: featured-aura 5s ease-in-out infinite; }
display: grid; .quick-action--featured::after { right: 8%; left: 8%; height: 4px; background: linear-gradient(90deg, #22d3ee 0%, #2563eb 48%, #4f46e5 100%); box-shadow: 0 -4px 16px rgba(37, 99, 235, .44), 0 -1px 6px rgba(34, 211, 238, .55); opacity: 1; transform: scaleX(1); }
grid-template-columns: minmax(0, 1fr) 286px; .quick-action--featured:hover { border-color: rgba(34, 211, 238, .8); box-shadow: 0 30px 70px rgba(37, 99, 235, .27), 0 0 0 1px rgba(255, 255, 255, .95) inset, 0 0 40px rgba(34, 211, 238, .15); transform: translateY(-11px) scale(1.015); }
gap: clamp(24px, 3vw, 42px); .quick-action--featured .action-icon { width: 64px; height: 64px; margin-bottom: 17px; border-radius: 20px; background: linear-gradient(145deg, #22c7df 0%, #2875ef 48%, #4338ca 100%); box-shadow: 0 16px 32px rgba(37, 99, 235, .37), 0 0 0 7px rgba(59, 130, 246, .09), 0 0 26px rgba(34, 211, 238, .24); }
align-items: start; .quick-action--featured .action-icon::after { inset: -6px; border-color: rgba(59, 130, 246, .25); border-radius: 25px; box-shadow: 0 0 0 1px rgba(34, 211, 238, .09); }
} .quick-action--featured .action-copy strong { color: #15233e; font-size: 17px; }
.quick-action--featured .action-enter { overflow: hidden; padding: 8px 15px; border-radius: 999px; background: linear-gradient(100deg, #12b8d0 0%, #2563eb 52%, #4338ca 100%); box-shadow: 0 10px 24px rgba(37, 99, 235, .3), 0 0 18px rgba(34, 211, 238, .12); color: #fff; }
.dashboard-business { .quick-action--featured .action-enter::before { position: absolute; top: -60%; bottom: -60%; left: -55%; width: 38%; transform: rotate(18deg); background: linear-gradient(90deg, transparent, rgba(255, 255, 255, .55), transparent); content: ''; animation: featured-shine 3.6s ease-in-out infinite; }
min-width: 0; .quick-action--featured .action-enter > * { position: relative; z-index: 1; }
padding: 14px 0 24px; .no-actions { margin: 0; padding: 20px; border: 1px solid var(--border); border-radius: 10px; background: #fff; color: #667085; font-size: 14px; }
} .dashboard-order-list { min-width: 0; }
.orders-permission-empty { display: flex; min-height: 180px; align-items: center; justify-content: center; flex-direction: column; gap: 8px; border: 1px solid var(--border); border-radius: 10px; background: #fff; color: #7b8494; }
.dashboard-intro { .orders-permission-empty strong { color: #475467; font-size: 15px; }
margin-bottom: 34px; .orders-permission-empty span { font-size: 12px; }
} .client-dashboard a:focus-visible { border-radius: 6px; outline: 2px solid var(--primary); outline-offset: 4px; }
@keyframes dashboard-enter { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
.dashboard-intro h2 { @keyframes action-enter { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: translateY(0); } }
max-width: 720px; @keyframes featured-aura { 0%, 100% { opacity: .86; transform: translate3d(0, 0, 0) scale(1); } 50% { opacity: 1; transform: translate3d(-10px, 9px, 0) scale(1.08); } }
margin: 0; @keyframes featured-shine { 0%, 55% { left: -55%; opacity: 0; } 65% { opacity: 1; } 88%, 100% { left: 125%; opacity: 0; } }
color: #111827; @container dashboard-content (max-width: 1180px) { .quick-actions { grid-template-columns: repeat(8, minmax(178px, 1fr)); } }
font-size: clamp(30px, 3.2vw, 46px); @media (max-width: 720px) { .client-dashboard { padding: 0; gap: 16px; } .business-intro h1 { font-size: 25px; } .quick-actions { grid-template-columns: repeat(2, minmax(150px, 1fr)); } }
line-height: 1.18; @media (max-width: 420px) { .quick-actions { grid-template-columns: repeat(8, minmax(168px, 1fr)); } }
letter-spacing: -.025em; @media (prefers-reduced-motion: reduce) { .client-dashboard, .quick-action, .quick-action--featured::before, .quick-action--featured .action-enter::before { animation: none; } .quick-action, .quick-action::before, .quick-action::after, .action-icon, .action-enter svg { transition: none; } }
}
.dashboard-intro p {
max-width: 720px;
margin: 16px 0 0;
color: #697586;
font-size: 15px;
line-height: 1.7;
}
.business-card-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 18px;
}
.business-card {
--card-accent: var(--dashboard-blue);
display: flex;
min-width: 0;
min-height: 286px;
flex-direction: column;
align-items: flex-start;
padding: 30px;
border: 0;
border-radius: 16px;
background: #fff;
box-shadow: 0 12px 36px rgba(23, 50, 77, .08);
color: #111827;
cursor: pointer;
text-align: left;
transition: transform .25s cubic-bezier(.16, 1, .3, 1), box-shadow .25s cubic-bezier(.16, 1, .3, 1);
}
.business-card--green { --card-accent: var(--dashboard-green); }
.business-card--teal { --card-accent: var(--dashboard-teal); }
.business-card:hover {
transform: translateY(-5px);
box-shadow: 0 20px 46px rgba(23, 50, 77, .14);
}
.business-card:focus-visible {
outline: 3px solid color-mix(in srgb, var(--card-accent) 36%, white);
outline-offset: 4px;
}
.business-card__icon {
display: grid;
width: 60px;
height: 60px;
place-items: center;
border-radius: 16px;
background: var(--card-accent);
box-shadow: 0 8px 18px color-mix(in srgb, var(--card-accent) 24%, transparent);
color: #fff;
}
.business-card__copy {
display: flex;
min-width: 0;
flex-direction: column;
gap: 10px;
margin-top: 34px;
}
.business-card__copy strong {
font-size: 22px;
line-height: 1.35;
}
.business-card__copy small {
color: #697586;
font-size: 14px;
line-height: 1.65;
}
.business-card__action {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: auto;
padding-top: 28px;
color: var(--card-accent);
font-size: 14px;
font-weight: 700;
}
.business-card__action svg {
transition: transform .2s cubic-bezier(.16, 1, .3, 1);
}
.business-card:hover .business-card__action svg {
transform: translateX(3px);
}
.dashboard-aside {
display: flex;
flex-direction: column;
gap: 14px;
}
.aside-card {
padding: 20px;
border: 1px solid #e9eef5;
border-radius: 14px;
background: #f8fafc;
}
.aside-card h3 {
margin: 0 0 18px;
color: #8b9bb2;
font-size: 12px;
font-weight: 750;
letter-spacing: .06em;
}
.account-summary {
display: flex;
min-width: 0;
align-items: center;
gap: 14px;
}
.account-avatar {
display: grid;
width: 52px;
height: 52px;
flex: 0 0 52px;
place-items: center;
border-radius: 14px;
background: linear-gradient(135deg, #1976d2, #00a993);
color: #fff;
font-size: 20px;
font-weight: 750;
}
.account-copy {
display: flex;
min-width: 0;
flex-direction: column;
gap: 5px;
}
.account-copy strong {
overflow: hidden;
color: #111827;
font-size: 15px;
line-height: 1.35;
text-overflow: ellipsis;
white-space: nowrap;
}
.account-copy small {
color: #66758a;
font-size: 12px;
}
.account-load-error {
margin: 14px 0 0;
color: #8a5a22;
font-size: 12px;
line-height: 1.55;
}
.overview-stats {
margin: 0;
}
.overview-stats div {
display: flex;
min-height: 48px;
align-items: center;
justify-content: space-between;
gap: 16px;
border-bottom: 1px dashed #dfe6ef;
}
.overview-stats div:last-child {
border-bottom: 0;
}
.overview-stats dt {
color: #475569;
font-size: 13px;
}
.overview-stats dd {
margin: 0;
color: #111827;
font-size: 15px;
font-weight: 750;
}
.dashboard-section-error {
margin: 10px 0 0;
padding: 10px 0 0;
border-top: 1px solid #e9eef5;
color: #8a5a22;
font-size: 12px;
line-height: 1.55;
}
.support-links {
display: grid;
gap: 3px;
}
.support-links button {
display: flex;
width: 100%;
min-height: 44px;
align-items: center;
gap: 11px;
padding: 0 9px;
border: 0;
border-radius: 9px;
background: transparent;
color: #334155;
cursor: pointer;
font-size: 14px;
text-align: left;
}
.support-links button svg {
flex: 0 0 19px;
color: #00a993;
}
.support-links button:hover {
background: #edf2f7;
color: var(--dashboard-blue);
}
.support-links button:focus-visible {
outline: 2px solid var(--dashboard-blue);
outline-offset: 2px;
}
.dashboard-tip {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
gap: 10px;
padding: 16px;
border: 1px solid rgba(0, 169, 147, .24);
border-radius: 14px;
background: #eef9f8;
color: #53657a;
}
.dashboard-tip svg {
margin-top: 2px;
color: #00a993;
}
.dashboard-tip p {
margin: 0;
font-size: 12px;
line-height: 1.75;
}
@media (max-width: 1180px) {
.dashboard-layout {
grid-template-columns: 1fr;
}
.dashboard-aside {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
align-items: stretch;
}
.dashboard-tip {
grid-column: 1 / -1;
}
}
@media (max-width: 960px) {
.business-card-grid {
grid-template-columns: 1fr;
}
.business-card {
min-height: 232px;
}
}
@media (max-width: 720px) {
.client-dashboard {
min-height: calc(100vh - 118px);
}
.dashboard-business {
padding-top: 2px;
}
.dashboard-intro {
margin-bottom: 24px;
}
.dashboard-intro h2 {
font-size: 28px;
}
.dashboard-intro p {
margin-top: 12px;
font-size: 14px;
}
.business-card {
min-height: 220px;
padding: 24px;
}
.business-card__copy {
margin-top: 24px;
}
.dashboard-aside {
grid-template-columns: 1fr;
}
.dashboard-tip {
grid-column: auto;
}
}
@media (prefers-reduced-motion: reduce) {
.business-card,
.business-card__action svg {
transition: none;
}
}
</style> </style>
+29
View File
@@ -0,0 +1,29 @@
# Client 财务模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/finance/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,账单与资金细则见 `../../../docs/business-index.md`。
- 本模块只做客户可见的账单查询、客户确认与资金账户;费用来源、核销与账期归 `backend finance/`,不在前端重算。
- 后端只查 `finance/`(账单、收款、账户与授信);文件下载归 `file/`。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 客户财务账单列表、筛选与未收余额 | `views/FinanceBillsView.vue`;`finance/bills` | `api/finance.ts`;`finance/` 账单 |
| 账单详情、入仓码联查与客户确认 | `views/FinanceBillDetailView.vue`;`finance/bills/:billNo/detail` | `api/finance.ts`、`adapters.ts`;`finance/` |
| 客户资金账户、授信与充值申请 | `views/FinanceAccountView.vue`;`finance/account` | `api/account.ts`;`finance/` 资金账户 |
| 跨页契约与稳定类型 | `contracts.ts` | 服务端 DTO |
## 关键边界
- 账单行只显示服务端返回的 `inboundCode`;缺失时显示“—”,不用内部 ID 或本地拼接回退。
- 实际、冻结、可用余额、授信与流水只消费 Finance 权威结果,前端不自行汇总或推算。
- 客户确认按服务端允许动作开放,提交金额与状态以服务端返回为准;已确认账单不得在前端改回。
- 充值申请与账户操作携带幂等键与提交中状态,失败保留原输入。
- 费用明细与柜级分摊只展示服务端结果;前端不参与分摊计算,也不把退税额或汇率写死。
## 验证
- 定向:`pnpm test src/modules/finance/<目标测试>`;接口或金额字段变化同时运行 `pnpm typecheck`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+1 -16
View File
@@ -61,14 +61,12 @@ export interface AccountLedgerEntry {
createdAt: string createdAt: string
} }
export type RechargePaymentMethod = 'WECHAT' | 'ALIPAY'
export type RechargeStatus = 'PENDING' | 'APPROVED' | 'REJECTED' export type RechargeStatus = 'PENDING' | 'APPROVED' | 'REJECTED'
export interface RechargeRequest { export interface RechargeRequest {
requestId: string requestId: string
requestNo: string requestNo: string
amount: string amount: string
paymentMethod: RechargePaymentMethod
voucherFileId: string voucherFileId: string
voucherFileName: string voucherFileName: string
status: RechargeStatus status: RechargeStatus
@@ -80,13 +78,6 @@ export interface RechargeRequest {
reviewedAt: string | null reviewedAt: string | null
} }
export interface RechargeChannel {
paymentMethod: RechargePaymentMethod
displayName: string
enabled: boolean
qrCodeUrl: string | null
}
export function getFinanceAccount() { export function getFinanceAccount() {
return apiRequest<FinanceAccount>({ method: 'GET', url: '/client/finance/v1/account' }) return apiRequest<FinanceAccount>({ method: 'GET', url: '/client/finance/v1/account' })
} }
@@ -109,15 +100,9 @@ export async function getRechargeRequests(page: number, size: number) {
return normalizePageResult(result) return normalizePageResult(result)
} }
export function getRechargeChannels() { export function createRechargeRequest(amount: string, file: File, idempotencyKey: string) {
return apiRequest<RechargeChannel[]>({ method: 'GET', url: '/client/finance/v1/recharge-channels' })
}
export function createRechargeRequest(amount: string, paymentMethod: RechargePaymentMethod, file: File,
idempotencyKey: string) {
const formData = new FormData() const formData = new FormData()
formData.append('amount', amount) formData.append('amount', amount)
formData.append('paymentMethod', paymentMethod)
formData.append('file', file, file.name) formData.append('file', file, file.name)
return apiRequest<RechargeRequest>({ return apiRequest<RechargeRequest>({
method: 'POST', method: 'POST',
+5
View File
@@ -21,5 +21,10 @@ export const financeModule = {
meta: { title: '客户账单', description: '查看本企业账单、收款记录和未收余额', permission: 'finance:bill:view' }, meta: { title: '客户账单', description: '查看本企业账单、收款记录和未收余额', permission: 'finance:bill:view' },
navigation: { key: 'finance-bills', title: '客户账单', icon: ReceiptText }, navigation: { key: 'finance-bills', title: '客户账单', icon: ReceiptText },
}, },
{
path: 'finance/bills/:billNo/detail', name: 'finance-bill-detail',
component: () => import('./views/FinanceBillDetailView.vue'), release: 'active',
meta: { title: '账单详情', workspaceTitle: '客户账单 · 详情', description: '查看费用明细、收款记录和客户确认信息', permission: 'finance:bill:view', keepAlive: false },
},
], ],
} satisfies ClientModuleManifest } satisfies ClientModuleManifest
@@ -8,13 +8,13 @@ const routesSource = readFileSync(new URL('../routes.ts', import.meta.url), 'utf
const permissionsSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8') const permissionsSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8')
test('uses only authenticated client finance account endpoints without customer scope', () => { test('uses only authenticated client finance account endpoints without customer scope', () => {
for (const path of ['/client/finance/v1/account', '/client/finance/v1/account/ledger', '/client/finance/v1/recharge-requests', '/client/finance/v1/recharge-channels']) { for (const path of ['/client/finance/v1/account', '/client/finance/v1/account/ledger', '/client/finance/v1/recharge-requests']) {
assert.match(apiSource, new RegExp(path.replaceAll('/', '\\/'))) assert.match(apiSource, new RegExp(path.replaceAll('/', '\\/')))
} }
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/) assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
assert.match(apiSource, /formData\.append\('amount', amount\)/) assert.match(apiSource, /formData\.append\('amount', amount\)/)
assert.match(apiSource, /formData\.append\('paymentMethod', paymentMethod\)/)
assert.match(apiSource, /formData\.append\('file', file, file\.name\)/) assert.match(apiSource, /formData\.append\('file', file, file\.name\)/)
assert.doesNotMatch(apiSource, /RechargePaymentMethod|paymentMethod|WECHAT|ALIPAY/)
assert.doesNotMatch(apiSource, /customerId|tenantId|mock|fallback/i) assert.doesNotMatch(apiSource, /customerId|tenantId|mock|fallback/i)
}) })
@@ -23,12 +23,14 @@ test('activates the account route and maps read and recharge permissions indepen
assert.match(permissionsSource, /'merchant:finance:account:view': \['merchant:finance:account:view'\]/) assert.match(permissionsSource, /'merchant:finance:account:view': \['merchant:finance:account:view'\]/)
assert.match(permissionsSource, /'merchant:finance:recharge:create': \['merchant:finance:recharge:create'\]/) assert.match(permissionsSource, /'merchant:finance:recharge:create': \['merchant:finance:recharge:create'\]/)
assert.match(viewSource, /auth\.hasPermission\('merchant:finance:recharge:create'\)/) assert.match(viewSource, /auth\.hasPermission\('merchant:finance:recharge:create'\)/)
assert.match(viewSource, /<el-button v-if="canRecharge"/) assert.match(viewSource, /class="balance-title"[\s\S]*?<el-button v-if="canRecharge" size="small" type="primary"/)
assert.match(viewSource, /\.balance-summary \{[^}]*grid-template-columns: repeat\(6,/)
assert.doesNotMatch(viewSource, /class="account-actions"|class="balance-grid"/)
assert.doesNotMatch(viewSource, /class="account-heading"/)
}) })
test('renders server balances, ledger and recharge states without internal identifiers', () => { test('renders server balances, ledger and recharge states without internal identifiers', () => {
for (const field of ['actualBalance', 'frozenBalance', 'availableBalance', 'creditLimit', 'creditUsed', 'availableCredit']) assert.match(viewSource, new RegExp(`account\\?\\.${field}`)) for (const field of ['actualBalance', 'frozenBalance', 'availableBalance', 'creditLimit', 'creditUsed', 'availableCredit']) assert.match(viewSource, new RegExp(`account\\?\\.${field}`))
for (const field of ['creditUsedAfter', 'availableCreditAfter']) assert.match(viewSource, new RegExp(`row\\.${field}`))
assert.match(viewSource, /实际可用资金与可用授信合计/) assert.match(viewSource, /实际可用资金与可用授信合计/)
assert.match(viewSource, /CREDIT_LIMIT: '授信调整'/) assert.match(viewSource, /CREDIT_LIMIT: '授信调整'/)
assert.match(viewSource, /row-key="businessNo"/) assert.match(viewSource, /row-key="businessNo"/)
@@ -39,9 +41,12 @@ test('renders server balances, ledger and recharge states without internal ident
assert.match(viewSource, /v-loading="pageLoading"/) assert.match(viewSource, /v-loading="pageLoading"/)
assert.match(viewSource, /function formatAccountAmount[\s\S]*value == null \? '—' : formatAmount\(value\)/) assert.match(viewSource, /function formatAccountAmount[\s\S]*value == null \? '—' : formatAmount\(value\)/)
assert.match(viewSource, /formatAccountAmount\(account\?\.actualBalance\)/) assert.match(viewSource, /formatAccountAmount\(account\?\.actualBalance\)/)
assert.match(viewSource, /:default-current-page="ledgerPage"/) assert.match(viewSource, /<DataTable v-model:page="ledgerPage" v-model:page-size="ledgerPageSize"/)
assert.match(viewSource, /:default-current-page="rechargePage"/) assert.match(viewSource, /<DataTable v-model:page="rechargePage" v-model:page-size="rechargePageSize"/)
assert.doesNotMatch(viewSource, /<el-pagination (?:v-model:current-page|:current-page)=/) assert.match(viewSource, /const ledgerColumns: DataTableColumn\[]/)
assert.match(viewSource, /const rechargeColumns: DataTableColumn\[]/)
assert.doesNotMatch(viewSource, /label: '已用授信'|label: '可用授信'/)
assert.doesNotMatch(viewSource, /<el-table|<el-pagination/)
assert.match(apiSource, /function normalizePageResult<[\s\S]*total: Number\(result\.total\)/) assert.match(apiSource, /function normalizePageResult<[\s\S]*total: Number\(result\.total\)/)
assert.match(apiSource, /page: Number\(result\.page\)/) assert.match(apiSource, /page: Number\(result\.page\)/)
assert.doesNotMatch(viewSource, /requestId|ledgerId|customerId|tenantId/) assert.doesNotMatch(viewSource, /requestId|ledgerId|customerId|tenantId/)
@@ -49,13 +54,16 @@ test('renders server balances, ledger and recharge states without internal ident
test('matches the frozen recharge workflow and preserves an idempotency key for failed retries', () => { test('matches the frozen recharge workflow and preserves an idempotency key for failed retries', () => {
assert.match(viewSource, /title="账户充值" width="760px"/) assert.match(viewSource, /title="账户充值" width="760px"/)
for (const amount of ['50.00', '100.00', '200.00', '500.00']) assert.match(viewSource, new RegExp(amount.replace('.', '\\.'))) for (const amount of ['1000', '5000', '20000', '50000']) assert.match(viewSource, new RegExp(amount))
assert.match(viewSource, /\['WECHAT', 'ALIPAY'\]/) assert.match(viewSource, /自定义/)
assert.match(viewSource, /selectedChannel\.value\?\.enabled && selectedChannel\.value\.qrCodeUrl/) assert.match(viewSource, /src="\/customer-recharge-qr\.png"/)
assert.match(viewSource, /alt="平台收款二维码"/)
assert.match(viewSource, /请扫描平台收款二维码,付款后上传截图。/)
assert.match(viewSource, /accept="\.jpg,\.jpeg,\.png,image\/jpeg,image\/png"/) assert.match(viewSource, /accept="\.jpg,\.jpeg,\.png,image\/jpeg,image\/png"/)
assert.match(viewSource, /if \(!pendingIdempotencyKey\)[\s\S]*globalThis\.crypto\?\.randomUUID\?\.\(\)/) assert.match(viewSource, /if \(!pendingIdempotencyKey\)[\s\S]*globalThis\.crypto\?\.randomUUID\?\.\(\)/)
assert.match(viewSource, /pendingIdempotencyKey = ''[\s\S]*rechargeVisible\.value = false/) assert.match(viewSource, /pendingIdempotencyKey = ''[\s\S]*rechargeVisible\.value = false/)
assert.match(viewSource, /:disabled="!canSubmit"/) assert.match(viewSource, /:disabled="!canSubmit"/)
assert.match(viewSource, /await loadAccountData\(\)/) assert.match(viewSource, /await loadAccountData\(\)/)
assert.doesNotMatch(viewSource, /payment SDK|支付成功|模拟成功/) assert.doesNotMatch(viewSource, /payment SDK|支付成功|模拟成功/)
assert.doesNotMatch(viewSource, /微信支付|支付宝|payment-methods|paymentMethod/)
}) })
@@ -3,18 +3,16 @@ import { computed, onMounted, reactive, ref, watch } from 'vue'
import { CircleDollarSign, RefreshCcw, Upload } from '@lucide/vue' import { CircleDollarSign, RefreshCcw, Upload } from '@lucide/vue'
import { ElMessage, type UploadFile, type UploadFiles, type UploadInstance } from 'element-plus' import { ElMessage, type UploadFile, type UploadFiles, type UploadInstance } from 'element-plus'
import { ApiError } from '@/api/http' import { ApiError } from '@/api/http'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import { useAuthStore } from '@/modules/auth/public' import { useAuthStore } from '@/modules/auth/public'
import { import {
createRechargeRequest, createRechargeRequest,
getAccountLedger, getAccountLedger,
getFinanceAccount, getFinanceAccount,
getRechargeChannels,
getRechargeRequests, getRechargeRequests,
type AccountChangeType, type AccountChangeType,
type AccountLedgerEntry, type AccountLedgerEntry,
type FinanceAccount, type FinanceAccount,
type RechargeChannel,
type RechargePaymentMethod,
type RechargeRequest, type RechargeRequest,
type RechargeStatus, type RechargeStatus,
} from '../api/account' } from '../api/account'
@@ -23,15 +21,15 @@ const auth = useAuthStore()
const account = ref<FinanceAccount | null>(null) const account = ref<FinanceAccount | null>(null)
const ledger = ref<AccountLedgerEntry[]>([]) const ledger = ref<AccountLedgerEntry[]>([])
const rechargeRequests = ref<RechargeRequest[]>([]) const rechargeRequests = ref<RechargeRequest[]>([])
const channels = ref<RechargeChannel[]>([])
const pageLoading = ref(false) const pageLoading = ref(false)
const pageError = ref('') const pageError = ref('')
const channelsError = ref('') const qrCodeLoadError = ref(false)
const ledgerPage = ref(1) const ledgerPage = ref(1)
const ledgerTotal = ref(0) const ledgerTotal = ref(0)
const ledgerPageSize = ref(10)
const rechargePage = ref(1) const rechargePage = ref(1)
const rechargeTotal = ref(0) const rechargeTotal = ref(0)
const pageSize = 10 const rechargePageSize = ref(10)
const rechargeVisible = ref(false) const rechargeVisible = ref(false)
const submitting = ref(false) const submitting = ref(false)
const submitError = ref('') const submitError = ref('')
@@ -39,11 +37,11 @@ const voucherFile = ref<File | null>(null)
const voucherUpload = ref<UploadInstance>() const voucherUpload = ref<UploadInstance>()
let pendingIdempotencyKey = '' let pendingIdempotencyKey = ''
const form = reactive({ amount: '100.00', paymentMethod: 'WECHAT' as RechargePaymentMethod }) const form = reactive({ amount: '1000' })
const quickAmounts = ['50.00', '100.00', '200.00', '500.00'] const quickAmounts = ['1000', '5000', '20000', '50000']
const amountMode = ref<'preset' | 'custom'>('preset')
const canRecharge = computed(() => auth.hasPermission('merchant:finance:recharge:create')) const canRecharge = computed(() => auth.hasPermission('merchant:finance:recharge:create'))
const selectedChannel = computed(() => channels.value.find((item) => item.paymentMethod === form.paymentMethod)) const channelReady = computed(() => !qrCodeLoadError.value)
const channelReady = computed(() => Boolean(selectedChannel.value?.enabled && selectedChannel.value.qrCodeUrl))
const amountValid = computed(() => { const amountValid = computed(() => {
const value = Number(form.amount) const value = Number(form.amount)
return Number.isFinite(value) && value > 0 && /^\d+(?:\.\d{1,2})?$/.test(form.amount.trim()) return Number.isFinite(value) && value > 0 && /^\d+(?:\.\d{1,2})?$/.test(form.amount.trim())
@@ -54,7 +52,27 @@ const changeLabels: Record<AccountChangeType, string> = {
RECHARGE: '充值', DEDUCTION: '扣款', FREEZE: '冻结', UNFREEZE: '解冻', CONSUMPTION: '消费', CREDIT_LIMIT: '授信调整', RECHARGE: '充值', DEDUCTION: '扣款', FREEZE: '冻结', UNFREEZE: '解冻', CONSUMPTION: '消费', CREDIT_LIMIT: '授信调整',
} }
const statusLabels: Record<RechargeStatus, string> = { PENDING: '待审核', APPROVED: '已通过', REJECTED: '已驳回' } const statusLabels: Record<RechargeStatus, string> = { PENDING: '待审核', APPROVED: '已通过', REJECTED: '已驳回' }
const methodLabels: Record<RechargePaymentMethod, string> = { WECHAT: '微信支付', ALIPAY: '支付宝' } const ledgerColumns: DataTableColumn[] = [
{ label: '业务单号', prop: 'businessNo', minWidth: 180 },
{ label: '变动类型', slotName: 'changeType', width: 100 },
{ label: '变动金额', slotName: 'amount', width: 120, align: 'right' },
{ label: '实际余额', slotName: 'actualBalance', width: 120, align: 'right' },
{ label: '冻结金额', slotName: 'frozenBalance', width: 120, align: 'right' },
{ label: '可用余额', slotName: 'availableBalance', width: 120, align: 'right' },
{ label: '操作人', slotName: 'operatorName', width: 120 },
{ label: '备注', slotName: 'remark', minWidth: 180 },
{ label: '发生时间', slotName: 'createdAt', width: 160 },
]
const rechargeColumns: DataTableColumn[] = [
{ label: '充值申请单号', prop: 'requestNo', minWidth: 180 },
{ label: '金额', slotName: 'amount', width: 120, align: 'right' },
{ label: '付款截图', prop: 'voucherFileName', minWidth: 150 },
{ label: '状态', slotName: 'status', width: 100 },
{ label: '提交人', slotName: 'submittedByName', width: 120 },
{ label: '审核备注', slotName: 'reviewRemark', minWidth: 180 },
{ label: '提交时间', slotName: 'createdAt', width: 160 },
{ label: '审核时间', slotName: 'reviewedAt', width: 160 },
]
function messageOf(error: unknown, fallback: string) { function messageOf(error: unknown, fallback: string) {
return error instanceof ApiError ? error.message : fallback return error instanceof ApiError ? error.message : fallback
@@ -86,8 +104,8 @@ function amountClass(amount: string) {
async function loadAccountData() { async function loadAccountData() {
pageLoading.value = true pageLoading.value = true
pageError.value = '' pageError.value = ''
channelsError.value = '' qrCodeLoadError.value = false
const requests = [getFinanceAccount(), getAccountLedger(ledgerPage.value, pageSize), getRechargeRequests(rechargePage.value, pageSize)] as const const requests = [getFinanceAccount(), getAccountLedger(ledgerPage.value, ledgerPageSize.value), getRechargeRequests(rechargePage.value, rechargePageSize.value)] as const
try { try {
const [accountResult, ledgerResult, rechargeResult] = await Promise.all(requests) const [accountResult, ledgerResult, rechargeResult] = await Promise.all(requests)
account.value = accountResult account.value = accountResult
@@ -105,20 +123,11 @@ async function loadAccountData() {
} finally { } finally {
pageLoading.value = false pageLoading.value = false
} }
if (canRecharge.value) {
try {
channels.value = await getRechargeChannels()
} catch (error) {
channels.value = []
channelsError.value = messageOf(error, '充值渠道加载失败,请稍后重试')
}
}
} }
async function changeLedgerPage(nextPage: number) { async function changeLedgerPage(nextPage: number) {
ledgerPage.value = nextPage
try { try {
const result = await getAccountLedger(nextPage, pageSize) const result = await getAccountLedger(nextPage, ledgerPageSize.value)
ledger.value = result.records ledger.value = result.records
ledgerTotal.value = result.total ledgerTotal.value = result.total
} catch (error) { } catch (error) {
@@ -127,9 +136,8 @@ async function changeLedgerPage(nextPage: number) {
} }
async function changeRechargePage(nextPage: number) { async function changeRechargePage(nextPage: number) {
rechargePage.value = nextPage
try { try {
const result = await getRechargeRequests(nextPage, pageSize) const result = await getRechargeRequests(nextPage, rechargePageSize.value)
rechargeRequests.value = result.records rechargeRequests.value = result.records
rechargeTotal.value = result.total rechargeTotal.value = result.total
} catch (error) { } catch (error) {
@@ -139,13 +147,26 @@ async function changeRechargePage(nextPage: number) {
function openRecharge() { function openRecharge() {
submitError.value = '' submitError.value = ''
qrCodeLoadError.value = false
amountMode.value = 'preset'
form.amount = '1000'
rechargeVisible.value = true rechargeVisible.value = true
} }
function handleQrCodeError() {
qrCodeLoadError.value = true
}
function chooseAmount(amount: string) { function chooseAmount(amount: string) {
amountMode.value = 'preset'
form.amount = amount form.amount = amount
} }
function chooseCustomAmount() {
amountMode.value = 'custom'
if (quickAmounts.includes(form.amount)) form.amount = ''
}
function handleVoucherChange(uploadFile: UploadFile, _uploadFiles: UploadFiles) { function handleVoucherChange(uploadFile: UploadFile, _uploadFiles: UploadFiles) {
const file = uploadFile.raw const file = uploadFile.raw
if (!file) return if (!file) return
@@ -175,7 +196,7 @@ async function submitRecharge() {
return return
} }
if (!channelReady.value) { if (!channelReady.value) {
submitError.value = `${methodLabels[form.paymentMethod]}收款二维码尚未配置,暂不能提交充值申请` submitError.value = '收款二维码尚未配置,暂不能提交充值申请'
return return
} }
if (!voucherFile.value) { if (!voucherFile.value) {
@@ -187,7 +208,7 @@ async function submitRecharge() {
} }
submitting.value = true submitting.value = true
try { try {
await createRechargeRequest(normalizedAmount(), form.paymentMethod, voucherFile.value, pendingIdempotencyKey) await createRechargeRequest(normalizedAmount(), voucherFile.value, pendingIdempotencyKey)
pendingIdempotencyKey = '' pendingIdempotencyKey = ''
rechargeVisible.value = false rechargeVisible.value = false
voucherFile.value = null voucherFile.value = null
@@ -201,28 +222,26 @@ async function submitRecharge() {
} }
} }
watch([() => form.amount, () => form.paymentMethod, voucherFile], () => { watch([() => form.amount, voucherFile], () => {
if (!submitting.value) pendingIdempotencyKey = '' if (!submitting.value) pendingIdempotencyKey = ''
submitError.value = '' submitError.value = ''
}) })
watch([ledgerPage, ledgerPageSize], () => { void changeLedgerPage(ledgerPage.value) })
watch([rechargePage, rechargePageSize], () => { void changeRechargePage(rechargePage.value) })
onMounted(() => { void loadAccountData() }) onMounted(() => { void loadAccountData() })
</script> </script>
<template> <template>
<div v-loading="pageLoading" class="finance-account-page" :aria-busy="pageLoading"> <div v-loading="pageLoading" class="finance-account-page" :aria-busy="pageLoading">
<div class="account-heading">
<div><h2>资金账户</h2><p>查看本企业 CNY 资金、授信额度、账户流水和充值申请状态。</p></div>
<el-button v-if="canRecharge" type="primary" @click="openRecharge"><CircleDollarSign :size="17" />账户充值</el-button>
</div>
<div v-if="pageError" class="account-state account-state--error" role="alert"> <div v-if="pageError" class="account-state account-state--error" role="alert">
<p>{{ pageError }}</p><el-button @click="loadAccountData"><RefreshCcw :size="15" />重新加载</el-button> <p>{{ pageError }}</p><el-button @click="loadAccountData"><RefreshCcw :size="15" />重新加载</el-button>
</div> </div>
<template v-else> <template v-else>
<section class="balance-grid" aria-label="账户余额"> <section class="balance-summary" aria-label="账户余额">
<article><span>实际余额</span><strong>¥ {{ formatAccountAmount(account?.actualBalance) }}</strong><small>当前账户实际资金</small></article> <article><div class="balance-title"><span>实际余额</span><el-button v-if="canRecharge" size="small" type="primary" @click="openRecharge"><CircleDollarSign :size="15" />账户充值</el-button></div><strong>¥ {{ formatAccountAmount(account?.actualBalance) }}</strong><small>当前账户实际资金</small></article>
<article><span>冻结金额</span><strong>¥ {{ formatAccountAmount(account?.frozenBalance) }}</strong><small>暂不可使用的资金</small></article> <article><span>冻结金额</span><strong>¥ {{ formatAccountAmount(account?.frozenBalance) }}</strong><small>暂不可使用的资金</small></article>
<article class="balance-available"><span>总可用余额</span><strong>¥ {{ formatAccountAmount(account?.availableBalance) }}</strong><small>实际可用资金与可用授信合计</small></article> <article class="balance-available"><span>总可用余额</span><strong>¥ {{ formatAccountAmount(account?.availableBalance) }}</strong><small>实际可用资金与可用授信合计</small></article>
<article><span>授信额度</span><strong>¥ {{ formatAccountAmount(account?.creditLimit) }}</strong><small>{{ account?.creditExpiresOn ? `${account.creditExpiresOn} ${account.creditActive ? '到期' : '已到期'}` : '未设置有效期' }}</small></article> <article><span>授信额度</span><strong>¥ {{ formatAccountAmount(account?.creditLimit) }}</strong><small>{{ account?.creditExpiresOn ? `${account.creditExpiresOn} ${account.creditActive ? '到期' : '已到期'}` : '未设置有效期' }}</small></article>
@@ -232,57 +251,46 @@ onMounted(() => { void loadAccountData() })
<section class="account-card"> <section class="account-card">
<div class="section-heading"><div><h3>账户流水</h3><p>每次资金变动均生成唯一业务单号。</p></div></div> <div class="section-heading"><div><h3>账户流水</h3><p>每次资金变动均生成唯一业务单号。</p></div></div>
<el-table :data="ledger" row-key="businessNo" empty-text="暂无资金流水"> <DataTable v-model:page="ledgerPage" v-model:page-size="ledgerPageSize" :data="ledger" :columns="ledgerColumns" :total="ledgerTotal" :page-sizes="[10, 20, 50]" row-key="businessNo" empty-text="暂无资金流水">
<el-table-column prop="businessNo" label="业务单号" min-width="190" /> <template #changeType="{ row }">{{ changeLabels[row.changeType as AccountChangeType] }}</template>
<el-table-column label="变动类型" width="110"><template #default="{ row }">{{ changeLabels[row.changeType as AccountChangeType] }}</template></el-table-column> <template #amount="{ row }"><strong :class="amountClass(row.amount)">{{ Number(row.amount) >= 0 ? '+' : '' }}¥ {{ formatAmount(row.amount) }}</strong></template>
<el-table-column label="变动金额" width="145" align="right"><template #default="{ row }"><strong :class="amountClass(row.amount)">{{ Number(row.amount) >= 0 ? '+' : '' }}¥ {{ formatAmount(row.amount) }}</strong></template></el-table-column> <template #actualBalance="{ row }">¥ {{ formatAmount(row.actualBalanceAfter) }}</template>
<el-table-column label="实际余额" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.actualBalanceAfter) }}</template></el-table-column> <template #frozenBalance="{ row }">¥ {{ formatAmount(row.frozenBalanceAfter) }}</template>
<el-table-column label="冻结金额" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.frozenBalanceAfter) }}</template></el-table-column> <template #availableBalance="{ row }">¥ {{ formatAmount(row.availableBalanceAfter) }}</template>
<el-table-column label="可用余额" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.availableBalanceAfter) }}</template></el-table-column> <template #operatorName="{ row }">{{ row.operatorName || '—' }}</template>
<el-table-column label="已用授信" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.creditUsedAfter) }}</template></el-table-column> <template #remark="{ row }">{{ row.remark || '—' }}</template>
<el-table-column label="可用授信" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.availableCreditAfter) }}</template></el-table-column> <template #createdAt="{ row }">{{ formatDateTime(row.createdAt) }}</template>
<el-table-column prop="operatorName" label="操作人" min-width="130"><template #default="{ row }">{{ row.operatorName || '—' }}</template></el-table-column> </DataTable>
<el-table-column prop="remark" label="备注" min-width="180"><template #default="{ row }">{{ row.remark || '—' }}</template></el-table-column>
<el-table-column label="发生时间" width="170"><template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template></el-table-column>
</el-table>
<div v-if="ledgerTotal" class="pagination-row"><span>共 {{ ledgerTotal }} 条</span><el-pagination :default-current-page="ledgerPage" :page-size="pageSize" layout="prev, pager, next" :total="ledgerTotal" @current-change="changeLedgerPage" /></div>
</section> </section>
<section class="account-card"> <section class="account-card">
<div class="section-heading"><div><h3>充值申请</h3><p>付款后上传截图,平台审核通过后资金入账。</p></div></div> <div class="section-heading"><div><h3>充值申请</h3><p>付款后上传截图,平台审核通过后资金入账。</p></div></div>
<el-table :data="rechargeRequests" row-key="requestNo" empty-text="暂无充值申请"> <DataTable v-model:page="rechargePage" v-model:page-size="rechargePageSize" :data="rechargeRequests" :columns="rechargeColumns" :total="rechargeTotal" :page-sizes="[10, 20, 50]" row-key="requestNo" empty-text="暂无充值申请">
<el-table-column prop="requestNo" label="充值申请单号" min-width="190" /> <template #amount="{ row }">¥ {{ formatAmount(row.amount) }}</template>
<el-table-column label="金额" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.amount) }}</template></el-table-column> <template #status="{ row }"><el-tag :type="statusType(row.status as RechargeStatus)">{{ statusLabels[row.status as RechargeStatus] }}</el-tag></template>
<el-table-column label="付款方式" width="120"><template #default="{ row }">{{ methodLabels[row.paymentMethod as RechargePaymentMethod] }}</template></el-table-column> <template #submittedByName="{ row }">{{ row.submittedByName || '—' }}</template>
<el-table-column prop="voucherFileName" label="付款截图" min-width="170" /> <template #reviewRemark="{ row }">{{ row.reviewRemark || '—' }}</template>
<el-table-column label="状态" width="110"><template #default="{ row }"><el-tag :type="statusType(row.status as RechargeStatus)">{{ statusLabels[row.status as RechargeStatus] }}</el-tag></template></el-table-column> <template #createdAt="{ row }">{{ formatDateTime(row.createdAt) }}</template>
<el-table-column prop="submittedByName" label="提交人" min-width="120"><template #default="{ row }">{{ row.submittedByName || '—' }}</template></el-table-column> <template #reviewedAt="{ row }">{{ formatDateTime(row.reviewedAt) }}</template>
<el-table-column prop="reviewRemark" label="审核备注" min-width="180"><template #default="{ row }">{{ row.reviewRemark || '—' }}</template></el-table-column> </DataTable>
<el-table-column label="提交时间" width="170"><template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template></el-table-column>
<el-table-column label="审核时间" width="170"><template #default="{ row }">{{ formatDateTime(row.reviewedAt) }}</template></el-table-column>
</el-table>
<div v-if="rechargeTotal" class="pagination-row"><span>共 {{ rechargeTotal }} 条</span><el-pagination :default-current-page="rechargePage" :page-size="pageSize" layout="prev, pager, next" :total="rechargeTotal" @current-change="changeRechargePage" /></div>
</section> </section>
</template> </template>
<el-dialog v-model="rechargeVisible" title="账户充值" width="760px" :close-on-click-modal="false" :close-on-press-escape="!submitting" :show-close="!submitting" class="recharge-dialog"> <el-dialog v-model="rechargeVisible" title="账户充值" width="760px" :close-on-click-modal="false" :close-on-press-escape="!submitting" :show-close="!submitting" class="recharge-dialog">
<div class="recharge-form"> <div class="recharge-form">
<label class="field-label" for="recharge-amount">充值金额</label> <label class="field-label" for="recharge-amount">充值金额</label>
<el-input id="recharge-amount" v-model="form.amount" size="large" inputmode="decimal" placeholder="请输入充值金额" aria-label="充值金额"><template #prefix>¥</template></el-input> <el-input v-if="amountMode === 'custom'" id="recharge-amount" v-model="form.amount" size="large" inputmode="decimal" placeholder="请输入充值金额" aria-label="充值金额"><template #prefix>¥</template></el-input>
<div class="quick-amounts" aria-label="快捷充值金额"> <div class="quick-amounts" aria-label="快捷充值金额">
<button v-for="amount in quickAmounts" :key="amount" type="button" :class="{ active: form.amount === amount }" @click="chooseAmount(amount)">¥{{ Number(amount) }}</button> <button v-for="amount in quickAmounts" :key="amount" type="button" :class="{ active: amountMode === 'preset' && form.amount === amount }" @click="chooseAmount(amount)">¥{{ Number(amount).toLocaleString() }}</button>
<button type="button" :class="{ active: amountMode === 'custom' }" @click="chooseCustomAmount">自定义</button>
</div> </div>
<div class="payment-methods" aria-label="付款方式"> <div v-if="channelReady" class="qr-panel">
<button v-for="method in (['WECHAT', 'ALIPAY'] as RechargePaymentMethod[])" :key="method" type="button" :class="[`payment-${method.toLowerCase()}`, { active: form.paymentMethod === method }]" @click="form.paymentMethod = method"><span>{{ method === 'WECHAT' ? '微' : '支' }}</span>{{ methodLabels[method] }}</button> <img src="/customer-recharge-qr.png" alt="平台收款二维码" @error="handleQrCodeError">
<div><strong>扫码付款</strong><p>请扫描平台收款二维码,付款后上传截图。</p></div>
</div> </div>
<div v-else-if="qrCodeLoadError" class="channel-warning" role="alert">平台收款二维码资源不可用,请联系管理员更新二维码</div>
<div v-if="channelsError" class="channel-warning" role="alert">{{ channelsError }}</div> <div v-else class="channel-warning" role="status">收款二维码尚未配置,暂不能提交充值申请。</div>
<div v-else-if="channelReady" class="qr-panel">
<img :src="selectedChannel?.qrCodeUrl || ''" :alt="`${methodLabels[form.paymentMethod]}收款二维码`">
<p>请使用{{ methodLabels[form.paymentMethod] }}扫码完成付款</p>
</div>
<div v-else class="channel-warning" role="status">{{ methodLabels[form.paymentMethod] }}收款二维码尚未配置,暂不能提交充值申请。</div>
<div class="voucher-upload"> <div class="voucher-upload">
<span class="field-label">付款截图</span> <span class="field-label">付款截图</span>
@@ -300,18 +308,21 @@ onMounted(() => { void loadAccountData() })
<style scoped> <style scoped>
.finance-account-page { display: flex; min-height: 420px; flex-direction: column; gap: 16px; } .finance-account-page { display: flex; min-height: 420px; flex-direction: column; gap: 16px; }
.account-heading, .section-heading, .pagination-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; } .section-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
.account-heading h2, .section-heading h3 { margin: 0; color: var(--navy); }.account-heading h2 { font-size: 22px; }.section-heading h3 { font-size: 16px; } .section-heading h3 { margin: 0; color: var(--navy); font-size: 16px; }
.account-heading p, .section-heading p { margin: 5px 0 0; color: var(--muted); font-size: 13px; }.account-heading .el-button { display: inline-flex; align-items: center; gap: 6px; } .section-heading p { margin: 5px 0 0; color: var(--muted); font-size: 13px; }
.balance-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; } .balance-summary { display: grid; overflow: hidden; grid-template-columns: repeat(6, minmax(0, 1fr)); border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
.balance-grid article { display: flex; min-height: 132px; flex-direction: column; padding: 22px 24px; border: 1px solid var(--border); border-radius: 10px; background: #fff; } .balance-summary article { display: flex; min-width: 0; min-height: 104px; flex-direction: column; padding: 14px 16px; border-right: 1px solid var(--client-border); }
.balance-grid span { color: var(--muted); font-size: 13px; }.balance-grid strong { margin-top: 14px; color: var(--navy); font-size: 28px; line-height: 1; }.balance-grid small { margin-top: auto; color: #8a98a8; }.balance-grid .balance-available { border-color: #b9e1db; background: #f3faf8; }.balance-grid .balance-available strong { color: #058b78; } .balance-summary article:last-child { border-right: 0; }
.account-card { min-width: 0; padding: 18px; border: 1px solid var(--border); border-radius: 8px; background: #fff; }.section-heading { margin-bottom: 14px; } .balance-summary span { color: var(--muted); font-size: 12px; }.balance-summary strong { margin-top: 10px; overflow: hidden; color: var(--navy); font-size: 22px; line-height: 1.1; text-overflow: ellipsis; white-space: nowrap; }.balance-summary small { margin-top: auto; overflow: hidden; color: #8a98a8; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.pagination-row { padding-top: 14px; color: var(--muted); font-size: 12px; }.amount-positive { color: #078a72; }.amount-negative { color: #b42318; } .balance-title { display: flex; min-height: 28px; align-items: center; justify-content: space-between; gap: 8px; }.balance-title .el-button { flex: 0 0 auto; height: 28px; padding: 0 9px; }.balance-title .el-button :deep(span) { display: inline-flex; align-items: center; gap: 4px; color: inherit; }
.balance-summary .balance-available { background: #f3faf8; }.balance-summary .balance-available strong { color: #058b78; }
.account-card { min-width: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }.section-heading { padding: 14px 16px; border-bottom: 1px solid var(--client-border); }
.amount-positive { color: #078a72; }.amount-negative { color: #b42318; }
.account-state { display: flex; min-height: 240px; align-items: center; justify-content: center; flex-direction: column; gap: 12px; border-radius: 8px; }.account-state--error { border: 1px solid #f5c2bd; background: #fff8f7; color: #b42318; }.account-state p { margin: 0; } .account-state { display: flex; min-height: 240px; align-items: center; justify-content: center; flex-direction: column; gap: 12px; border-radius: 8px; }.account-state--error { border: 1px solid #f5c2bd; background: #fff8f7; color: #b42318; }.account-state p { margin: 0; }
.recharge-form { display: flex; flex-direction: column; gap: 16px; }.field-label { color: #4e6075; font-size: 14px; font-weight: 650; } .recharge-form { display: flex; flex-direction: column; gap: 16px; }.field-label { color: #4e6075; font-size: 14px; font-weight: 650; }
.quick-amounts, .payment-methods { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; }.quick-amounts button, .payment-methods button { min-height: 54px; border: 1px solid #dbe3ed; border-radius: 10px; background: #f8fafc; color: #506077; cursor: pointer; font: inherit; }.quick-amounts button.active, .payment-methods button.active { border: 2px solid #1671c9; background: #eef8f7; color: #1467b8; font-weight: 700; } .quick-amounts { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; }.quick-amounts button { min-height: 54px; border: 1px solid #dbe3ed; border-radius: 10px; background: #f8fafc; color: #506077; cursor: pointer; font: inherit; }.quick-amounts button.active { border: 2px solid #1671c9; background: #eef8f7; color: #1467b8; font-weight: 700; }
.payment-methods { grid-template-columns: repeat(2, 1fr); }.payment-methods button { display: flex; align-items: center; justify-content: center; gap: 10px; font-size: 17px; font-weight: 650; }.payment-methods span { display: grid; width: 26px; height: 26px; place-items: center; border-radius: 7px; background: #1685ef; color: #fff; font-size: 14px; }.payment-wechat span { background: #09ae42; } .qr-panel { display: grid; grid-template-columns: 210px minmax(0, 1fr); align-items: center; gap: 24px; padding: 20px; border: 1px solid #dbe3ed; border-radius: 12px; background: #f8fafc; }.qr-panel img { width: 210px; height: 210px; border: 1px solid #dae3ed; border-radius: 10px; background: #fff; object-fit: contain; }.qr-panel strong { color: var(--navy); font-size: 17px; }.qr-panel p { margin: 8px 0 0; color: #62758d; }
.qr-panel { display: flex; align-items: center; flex-direction: column; gap: 14px; padding: 22px; border: 1px dashed #bed0e4; border-radius: 12px; background: #f8fafc; }.qr-panel img { width: 210px; height: 210px; border: 1px solid #dae3ed; border-radius: 10px; background: #fff; object-fit: contain; }.qr-panel p { margin: 0; color: #62758d; }
.channel-warning { padding: 24px; border: 1px solid #f0d39b; border-radius: 10px; background: #fff9ed; color: #8b5b12; text-align: center; }.voucher-upload { display: grid; gap: 10px; }.voucher-upload :deep(.el-button) { display: inline-flex; align-items: center; gap: 6px; }.submit-error { margin: 0; color: #b42318; font-size: 13px; }.dialog-actions { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }.dialog-actions .el-button { min-height: 46px; margin: 0; } .channel-warning { padding: 24px; border: 1px solid #f0d39b; border-radius: 10px; background: #fff9ed; color: #8b5b12; text-align: center; }.voucher-upload { display: grid; gap: 10px; }.voucher-upload :deep(.el-button) { display: inline-flex; align-items: center; gap: 6px; }.submit-error { margin: 0; color: #b42318; font-size: 13px; }.dialog-actions { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }.dialog-actions .el-button { min-height: 46px; margin: 0; }
@media (max-width: 1200px) { .balance-summary { grid-template-columns: repeat(3, minmax(0, 1fr)); }.balance-summary article { border-bottom: 1px solid var(--client-border); }.balance-summary article:nth-child(3n) { border-right: 0; }.balance-summary article:nth-last-child(-n + 3) { border-bottom: 0; } }
</style> </style>
@@ -0,0 +1,85 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft } from '@lucide/vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ApiError } from '@/api/http'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import { useAuthStore } from '@/modules/auth/public'
import { InboundCodeAssociationDialog } from '@/modules/first-leg/public'
import { confirmMerchantFinanceStatement, getMerchantFinanceBill, getMerchantFinanceBills, getMerchantFinanceReceipts } from '../api/finance'
import type { FinanceBillDetail, FinanceBillSummary, FinanceBillStatus, FinanceCustomerConfirmationStatus } from '../contracts'
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const billNo = computed(() => String(route.params.billNo || ''))
const loading = ref(false)
const errorMessage = ref('')
const detail = ref<FinanceBillDetail | null>(null)
const confirming = ref(false)
const inboundAssociationVisible = ref(false)
const inboundAssociationCode = ref('')
const canConfirm = computed(() => auth.hasPermission('finance:bill:confirm'))
const lineColumns: DataTableColumn[] = [
{ key: 'inboundCode', label: '入仓码', slotName: 'inboundCode', minWidth: 180 },
{ prop: 'feeName', label: '费用项目', minWidth: 220 },
{ key: 'amount', label: '金额', slotName: 'amount', width: 150, align: 'right', headerAlign: 'right' },
]
const receiptColumns: DataTableColumn[] = [
{ key: 'receivedAt', label: '收款日期', slotName: 'receivedAt', width: 130 },
{ prop: 'receiptNo', label: '收款编号', minWidth: 180 },
{ key: 'allocatedAmount', label: '本次金额', slotName: 'allocatedAmount', width: 150, align: 'right', headerAlign: 'right' },
{ key: 'method', label: '方式', slotName: 'method', minWidth: 120 },
]
function formatAmount(value?: string | null) { const number = Number(value); return Number.isFinite(number) ? number.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : value || '0.00' }
function formatDate(value?: string | null) { return value ? value.slice(0, 10) : '—' }
function formatDateTime(value?: string | null) { return value ? value.replace('T', ' ').replace(/Z$/, '').slice(0, 16) : '—' }
function statusLabel(status: FinanceBillStatus) { return ({ DRAFT: '草稿', ISSUED: '已出账', PARTIALLY_PAID: '部分收款', PAID: '已收清', VOIDED: '作废' } as Record<string, string>)[status] || status }
function statusType(status: FinanceBillStatus) { return ({ ISSUED: 'info', PARTIALLY_PAID: 'warning', PAID: 'success', VOIDED: 'danger', DRAFT: 'info' } as const)[status] }
function confirmationLabel(status: FinanceCustomerConfirmationStatus) { return ({ NOT_REQUIRED: '无需确认', PENDING_CONFIRMATION: '待确认', CONFIRMED: '已确认' })[status] }
function paymentMethodLabel(method?: string | null) { return ({ BANK_TRANSFER: '银行转账', CASH: '现金', OTHER: '其他' } as Record<string, string>)[method || ''] || '其他' }
function messageOf(error: unknown) { return error instanceof ApiError ? error.message : '账单详情加载失败,请稍后重试' }
async function load() {
if (!billNo.value) return
loading.value = true
errorMessage.value = ''
try {
const result = await getMerchantFinanceBills({ keyword: billNo.value, page: 1, size: 100 })
const summary = result.records.find(item => item.billNo === billNo.value)
if (!summary) throw new Error('未找到该账单')
const [bill, receipts] = await Promise.all([getMerchantFinanceBill(summary.id), getMerchantFinanceReceipts(summary.id)])
detail.value = { ...bill, receipts }
} catch (error) { detail.value = null; errorMessage.value = error instanceof Error ? error.message : messageOf(error) }
finally { loading.value = false }
}
async function confirmStatement(statement: FinanceBillSummary) {
if (!canConfirm.value || statement.customerConfirmationStatus !== 'PENDING_CONFIRMATION' || confirming.value) return
try { await ElMessageBox.confirm(`确认账单 ${statement.billNo}(¥ ${formatAmount(statement.totalAmount)})金额与费用明细无误?`, '确认客户账单', { type: 'warning', confirmButtonText: '确认无误', cancelButtonText: '取消' }) } catch { return }
confirming.value = true
try { await confirmMerchantFinanceStatement(statement.id, statement.version); ElMessage.success('账单已确认'); await load() }
catch (error) { ElMessage.error(messageOf(error)) }
finally { confirming.value = false }
}
function openInboundAssociation(value?: string | null) { if (!value) return; inboundAssociationCode.value = value; inboundAssociationVisible.value = true }
</script>
<template>
<article v-loading="loading" class="bill-detail-surface">
<template v-if="detail">
<header class="bill-detail-header"><button type="button" class="bill-detail-back" @click="router.push({ name: 'finance-bills' })"><ArrowLeft :size="16" />返回列表</button><div class="bill-detail-title"><strong>{{ detail.billNo }}</strong><span>出账 {{ formatDate(detail.issueDate) }} · 到期 {{ formatDate(detail.dueDate) }}</span></div><div class="bill-detail-actions"><el-tag :type="statusType(detail.status)" effect="light">{{ statusLabel(detail.status) }}</el-tag><el-tag effect="light">{{ confirmationLabel(detail.customerConfirmationStatus) }}</el-tag><el-button v-if="detail.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm" type="primary" :loading="confirming" @click="confirmStatement(detail)">确认账单</el-button></div></header>
<section class="bill-detail-section"><h3>账单概览</h3><dl class="bill-detail-grid"><div><dt>账单金额</dt><dd>¥ {{ formatAmount(detail.totalAmount) }}</dd></div><div><dt>已收金额</dt><dd>¥ {{ formatAmount(detail.receivedAmount) }}</dd></div><div><dt>未收余额</dt><dd class="amount-warning">¥ {{ formatAmount(detail.outstandingAmount) }}</dd></div><div><dt>客户确认</dt><dd>{{ confirmationLabel(detail.customerConfirmationStatus) }}</dd></div><div><dt>确认成员</dt><dd>{{ detail.customerConfirmedByName || '—' }}</dd></div><div><dt>确认时间</dt><dd>{{ formatDateTime(detail.customerConfirmedAt) }}</dd></div></dl></section>
<section class="bill-detail-section"><h3>费用明细</h3><DataTable :data="detail.lines" :columns="lineColumns" row-key="id" empty-text="暂无费用明细"><template #inboundCode="{ row }"><el-button v-if="row.inboundCode" link type="primary" @click="openInboundAssociation(row.inboundCode)">{{ row.inboundCode }}</el-button><span v-else>—</span></template><template #amount="{ row }">¥ {{ formatAmount(row.amount) }}</template></DataTable></section>
<section class="bill-detail-section"><h3>收款记录</h3><DataTable :data="detail.receipts" :columns="receiptColumns" row-key="id" empty-text="暂无收款记录"><template #receivedAt="{ row }">{{ formatDate(row.receivedAt) }}</template><template #allocatedAmount="{ row }">¥ {{ formatAmount(row.allocatedAmount) }}</template><template #method="{ row }">{{ paymentMethodLabel(row.method) }}</template></DataTable></section>
<p class="bill-detail-notice">如对账单内容有疑问,请先联系平台财务,核对无误后再确认。</p>
</template>
<div v-else-if="errorMessage" class="bill-detail-error" role="alert"><strong>{{ errorMessage }}</strong><el-button @click="load">重新加载</el-button></div>
</article>
<InboundCodeAssociationDialog v-model="inboundAssociationVisible" :inbound-code="inboundAssociationCode" />
</template>
<style scoped>
.bill-detail-surface{overflow:hidden;min-height:240px;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff}.bill-detail-header{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:14px;min-height:64px;padding:10px 16px;border-bottom:1px solid var(--client-border)}.bill-detail-back{display:inline-flex;align-items:center;gap:5px;padding:5px 0;border:0;background:transparent;color:var(--el-color-primary);cursor:pointer}.bill-detail-title{display:flex;min-width:0;flex-direction:column;gap:3px}.bill-detail-title strong{overflow:hidden;color:#1f2d45;font-size:18px;text-overflow:ellipsis;white-space:nowrap}.bill-detail-title span{color:var(--client-muted);font-size:12px}.bill-detail-actions{display:flex;align-items:center;gap:8px}.bill-detail-section+.bill-detail-section{border-top:1px solid var(--client-border)}.bill-detail-section>h3{display:flex;min-height:40px;align-items:center;margin:0;padding:0 16px;border-bottom:1px solid var(--client-border);background:var(--client-header-bg);font-size:14px}.bill-detail-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:0}.bill-detail-grid div{display:grid;min-height:42px;grid-template-columns:88px minmax(0,1fr);align-items:center;gap:8px;padding:5px 12px;border-right:1px solid var(--client-border);border-bottom:1px solid var(--client-border)}.bill-detail-grid dt{color:var(--client-muted);font-size:12px}.bill-detail-grid dd{margin:0;overflow:hidden;color:var(--client-text);font-size:13px;font-weight:600;text-overflow:ellipsis;white-space:nowrap}.amount-warning{color:#b45309!important}.bill-detail-notice{margin:0;padding:10px 14px;border-top:1px solid var(--client-border);background:#f5faf8;color:#45615d;font-size:12px}.bill-detail-error{display:flex;min-height:220px;align-items:center;justify-content:center;gap:12px;color:#b42318}@media(max-width:1100px){.bill-detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.bill-detail-header{grid-template-columns:1fr auto}.bill-detail-back{grid-column:1/-1}.bill-detail-grid{grid-template-columns:1fr}}
</style>
@@ -5,6 +5,7 @@ import ts from 'typescript'
const routesSource = readFileSync(new URL('../routes.ts', import.meta.url), 'utf8') const routesSource = readFileSync(new URL('../routes.ts', import.meta.url), 'utf8')
const viewSource = readFileSync(new URL('./FinanceBillsView.vue', import.meta.url), 'utf8') const viewSource = readFileSync(new URL('./FinanceBillsView.vue', import.meta.url), 'utf8')
const detailViewSource = readFileSync(new URL('./FinanceBillDetailView.vue', import.meta.url), 'utf8')
const apiSource = readFileSync(new URL('../api/finance.ts', import.meta.url), 'utf8') const apiSource = readFileSync(new URL('../api/finance.ts', import.meta.url), 'utf8')
const adapterSource = readFileSync(new URL('../api/adapters.ts', import.meta.url), 'utf8') const adapterSource = readFileSync(new URL('../api/adapters.ts', import.meta.url), 'utf8')
const permissionSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8') const permissionSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8')
@@ -22,6 +23,8 @@ const permissionContracts = await importTypeScriptModule(new URL('../../tenant-m
test('activates the customer finance route with its existing list and detail permission', () => { test('activates the customer finance route with its existing list and detail permission', () => {
assert.match(routesSource, /path: 'finance\/bills'/) assert.match(routesSource, /path: 'finance\/bills'/)
assert.match(routesSource, /path: 'finance\/bills\/:billNo\/detail'/)
assert.match(routesSource, /name: 'finance-bill-detail'/)
assert.match(routesSource, /FinanceBillsView\.vue/) assert.match(routesSource, /FinanceBillsView\.vue/)
assert.match(routesSource, /release: 'active'/) assert.match(routesSource, /release: 'active'/)
assert.match(routesSource, /permission: 'finance:bill:view'/) assert.match(routesSource, /permission: 'finance:bill:view'/)
@@ -52,8 +55,16 @@ test('adapts the Finance Java DTO contract and filters nested receipt allocation
assert.doesNotMatch(adapterSource, /bill_no|customer_name|bill_date|total_amount|outstanding_amount|receipt_no|bill_id|applied_amount/) assert.doesNotMatch(adapterSource, /bill_no|customer_name|bill_date|total_amount|outstanding_amount|receipt_no|bill_id|applied_amount/)
assert.doesNotMatch(adapterSource, /receipt\.billId|receipt\.appliedAmount/) assert.doesNotMatch(adapterSource, /receipt\.billId|receipt\.appliedAmount/)
assert.doesNotMatch(adapterSource, /voucherNo|voucher_no/) assert.doesNotMatch(adapterSource, /voucherNo|voucher_no/)
assert.match(viewSource, /loadDetail\(row\.id\)/) assert.doesNotMatch(viewSource, /key: 'detail'|label: '查看'/)
assert.doesNotMatch(viewSource, /loadDetail\(row\.billNo\)/) assert.match(detailViewSource, /getMerchantFinanceBill\(summary\.id\)/)
assert.match(detailViewSource, /getMerchantFinanceReceipts\(summary\.id\)/)
assert.doesNotMatch(detailViewSource, /getMerchantFinanceBill\(billNo\.value\)/)
})
test('keeps bill numbers linked to business-number details independently of confirmation actions', () => {
assert.match(viewSource, /label: '账单编号',\s*prop: 'billNo',\s*slotName: 'billNo'/)
assert.match(viewSource, /<template #billNo="\{ row \}">\s*<RouterLink[^>]*:to="\{ name: 'finance-bill-detail', params: \{ billNo: row\.billNo \} \}"[^>]*>\{\{ row\.billNo \}\}<\/RouterLink>\s*<\/template>/)
assert.doesNotMatch(viewSource.match(/<template #billNo[^]*?<\/template>/)?.[0] || '', /canConfirm|confirmationStatus|row\.id/)
}) })
test('does not expose draft or voided bills returned by the server', () => { test('does not expose draft or voided bills returned by the server', () => {
@@ -114,30 +125,44 @@ test('requires both finance statement authorities for the page permission', () =
}) })
test('keeps actions first and exposes list, balance, detail, confirmation, receipt, empty and error states', () => { test('keeps actions first and exposes list, balance, detail, confirmation, receipt, empty and error states', () => {
const actionIndex = viewSource.indexOf('label="操作"') const tableDefinition = viewSource.slice(viewSource.indexOf('const tableColumns'))
const billNumberIndex = viewSource.indexOf('label="账单编号"') const actionIndex = tableDefinition.indexOf("label: '操作'")
const billNumberIndex = tableDefinition.indexOf("label: '账单编号'")
assert.ok(actionIndex >= 0 && actionIndex < billNumberIndex) assert.ok(actionIndex >= 0 && actionIndex < billNumberIndex)
for (const expected of ['未收余额', '账单详情', '确认账单', '客户确认信息', '收款记录', '暂无账单', '暂无收款记录', 'state-panel--error']) { for (const expected of ['未收余额', '确认账单', '暂无账单', 'state-panel--error']) {
assert.match(viewSource, new RegExp(expected)) assert.match(viewSource, new RegExp(expected))
} }
assert.match(viewSource, /BANK_TRANSFER: '银行转账'/) for (const expected of ['账单概览', '费用明细', '收款记录', '暂无收款记录']) assert.match(detailViewSource, new RegExp(expected))
assert.match(viewSource, /paymentMethodLabel\(row\.method\)/) assert.match(detailViewSource, /BANK_TRANSFER: '银行转账'/)
assert.match(viewSource, /label="入仓码"/) assert.match(detailViewSource, /paymentMethodLabel\(row\.method\)/)
assert.match(viewSource, /openInboundAssociation\(row\.inboundCode\)/) assert.match(detailViewSource, /label: '入仓码'/)
assert.match(viewSource, /InboundCodeAssociationDialog/) assert.match(detailViewSource, /openInboundAssociation\(row\.inboundCode\)/)
assert.match(viewSource, /:inbound-code="inboundAssociationCode"/) assert.match(detailViewSource, /InboundCodeAssociationDialog/)
assert.match(detailViewSource, /:inbound-code="inboundAssociationCode"/)
assert.match(viewSource, /auth\.hasPermission\('finance:bill:confirm'\)/) assert.match(viewSource, /auth\.hasPermission\('finance:bill:confirm'\)/)
assert.match(viewSource, /row\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm/) assert.match(viewSource, /statement\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm\.value/)
assert.match(viewSource, /size="small" type="success" plain/) assert.match(viewSource, /label: '确认账单'/)
assert.match(viewSource, /confirmStatement\(row as FinanceBillSummary\)/) assert.match(viewSource, /run: \(\) => confirmStatement\(statement\)/)
assert.match(viewSource, /detail\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm/) assert.match(detailViewSource, /detail\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm/)
assert.match(viewSource, /confirmStatement\(detail\)/) assert.match(detailViewSource, /confirmStatement\(detail\)/)
assert.match(viewSource, /confirmMerchantFinanceStatement\(statementId, statement\.version, key\)/) assert.match(viewSource, /confirmMerchantFinanceStatement\(statementId, statement\.version, key\)/)
assert.match(viewSource, /ElMessage\.success\('对账单已确认'\)/) assert.match(viewSource, /ElMessage\.success\('对账单已确认'\)/)
assert.match(viewSource, /ElMessage\.error\(error instanceof ApiError \? error\.message : '对账单确认失败,请重试'\)/) assert.match(viewSource, /ElMessage\.error\(error instanceof ApiError \? error\.message : '对账单确认失败,请重试'\)/)
for (const forbidden of ['发起争议', '新增收款', '核销', '修改金额']) { for (const forbidden of ['发起争议', '新增收款', '核销', '修改金额']) {
assert.doesNotMatch(viewSource, new RegExp(forbidden)) assert.doesNotMatch(viewSource, new RegExp(forbidden))
assert.doesNotMatch(detailViewSource, new RegExp(forbidden))
} }
assert.doesNotMatch(viewSource, /<el-drawer|InboundCodeAssociationDialog/)
assert.match(detailViewSource, /class="bill-detail-surface"/)
assert.match(detailViewSource, /bill-detail-error/)
})
test('uses the shared compact query, table and pagination layout', () => {
assert.match(viewSource, /<QueryToolbar[^>]*layout="grid"/)
assert.match(viewSource, /<DataTable[^>]*:row-actions="rowActions"/)
assert.match(viewSource, /v-model:page="page" v-model:page-size="pageSize"/)
assert.match(viewSource, /:page-sizes="\[20, 50, 100\]"/)
assert.doesNotMatch(viewSource, /class="filter-bar"|class="pagination-row"|class="table-empty"/)
}) })
test('keeps the existing customer finance view permission mapping', () => { test('keeps the existing customer finance view permission mapping', () => {
+64 -105
View File
@@ -1,24 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { CircleDollarSign, Eye, RefreshCcw, Search } from '@lucide/vue' import { RefreshCcw } from '@lucide/vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { RouterLink } from 'vue-router'
import { ApiError } from '@/api/http' import { ApiError } from '@/api/http'
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import type { TableAction } from '@/components/common/tableActions'
import { useAuthStore } from '@/modules/auth/public' import { useAuthStore } from '@/modules/auth/public'
import { InboundCodeAssociationDialog } from '@/modules/first-leg/public' import { confirmMerchantFinanceStatement, getMerchantFinanceBills } from '../api/finance'
import { confirmMerchantFinanceStatement, getMerchantFinanceBill, getMerchantFinanceBills, getMerchantFinanceReceipts } from '../api/finance' import type { FinanceBillQuery, FinanceBillStatus, FinanceBillSummary, FinanceCustomerConfirmationStatus } from '../contracts'
import type { FinanceBillDetail, FinanceBillQuery, FinanceBillStatus, FinanceBillSummary, FinanceCustomerConfirmationStatus } from '../contracts'
const loading = ref(false) const loading = ref(false)
const auth = useAuthStore() const auth = useAuthStore()
const detailLoading = ref(false)
const errorMessage = ref('') const errorMessage = ref('')
const detailError = ref('')
const bills = ref<FinanceBillSummary[]>([]) const bills = ref<FinanceBillSummary[]>([])
const detail = ref<FinanceBillDetail | null>(null)
const selectedBillId = ref('')
const detailVisible = ref(false)
const inboundAssociationVisible = ref(false)
const inboundAssociationCode = ref('')
const confirmingBillId = ref('') const confirmingBillId = ref('')
const confirmationKeys = new Map<string, string>() const confirmationKeys = new Map<string, string>()
const page = ref(1) const page = ref(1)
@@ -34,7 +30,23 @@ const statusOptions: Array<{ label: string; value: FinanceBillStatus }> = [
{ label: '作废', value: 'VOIDED' }, { label: '作废', value: 'VOIDED' },
] ]
const hasData = computed(() => bills.value.length > 0) const queryModel = ref<QueryModel>({ keyword: '', status: '' })
const queryFields: QueryField[] = [
{ key: 'keyword', label: '账单编号', type: 'input', placeholder: '请输入账单编号' },
{ key: 'status', label: '账单状态', type: 'select', placeholder: '全部', options: statusOptions },
]
const tableColumns: DataTableColumn[] = [
{ label: '操作', slotName: 'actions', width: 190, fixed: 'left' },
{ label: '账单编号', prop: 'billNo', slotName: 'billNo', minWidth: 160 },
{ label: '出账日期', slotName: 'issueDate', width: 120 },
{ label: '到期日', slotName: 'dueDate', width: 120 },
{ label: '账单金额', slotName: 'totalAmount', width: 145, align: 'right' },
{ label: '已收', slotName: 'receivedAmount', width: 145, align: 'right' },
{ label: '未收余额', slotName: 'outstandingAmount', width: 145, align: 'right' },
{ label: '状态', slotName: 'status', width: 110 },
{ label: '客户确认', slotName: 'confirmationStatus', width: 110 },
]
const canConfirm = computed(() => auth.hasPermission('finance:bill:confirm')) const canConfirm = computed(() => auth.hasPermission('finance:bill:confirm'))
function formatAmount(value: string | null | undefined) { function formatAmount(value: string | null | undefined) {
@@ -48,15 +60,6 @@ function formatDate(value: string | null | undefined) {
return value.slice(0, 10) return value.slice(0, 10)
} }
function formatDateTime(value: string | null | undefined) {
return value ? value.replace('T', ' ').replace(/Z$/, '').slice(0, 16) : '-'
}
function paymentMethodLabel(method: string | null | undefined) {
if (!method) return '—'
return ({ BANK_TRANSFER: '银行转账', CASH: '现金', OTHER: '其他' })[method] ?? '其他'
}
function statusLabel(status: FinanceBillStatus) { function statusLabel(status: FinanceBillStatus) {
return ({ DRAFT: '草稿', ISSUED: '已出账', PARTIALLY_PAID: '部分收款', PAID: '已收清', VOIDED: '作废' })[status] ?? status return ({ DRAFT: '草稿', ISSUED: '已出账', PARTIALLY_PAID: '部分收款', PAID: '已收清', VOIDED: '作废' })[status] ?? status
} }
@@ -100,24 +103,19 @@ async function loadBills(nextPage = page.value) {
} }
} }
async function openDetail(row: FinanceBillSummary) { function rowActions(row: object): TableAction[] {
selectedBillId.value = row.id const statement = row as FinanceBillSummary
await loadDetail(row.id) const actions: TableAction[] = []
} if (statement.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm.value) {
actions.push({
async function loadDetail(billId: string) { key: 'confirm',
detailVisible.value = true label: '确认账单',
detailLoading.value = true loading: confirmingBillId.value === statement.id,
detailError.value = '' disabled: Boolean(confirmingBillId.value),
detail.value = null run: () => confirmStatement(statement),
try { })
const [bill, receipts] = await Promise.all([getMerchantFinanceBill(billId), getMerchantFinanceReceipts(billId)])
detail.value = { ...bill, receipts }
} catch (error) {
detailError.value = messageOf(error)
} finally {
detailLoading.value = false
} }
return actions
} }
async function confirmStatement(statement: FinanceBillSummary) { async function confirmStatement(statement: FinanceBillSummary) {
@@ -143,9 +141,7 @@ async function confirmStatement(statement: FinanceBillSummary) {
await confirmMerchantFinanceStatement(statementId, statement.version, key) await confirmMerchantFinanceStatement(statementId, statement.version, key)
confirmationKeys.delete(statementId) confirmationKeys.delete(statementId)
ElMessage.success('对账单已确认') ElMessage.success('对账单已确认')
const refreshes: Array<Promise<void>> = [loadBills(page.value)] await loadBills(page.value)
if (detailVisible.value && selectedBillId.value === statementId) refreshes.push(loadDetail(statementId))
await Promise.all(refreshes)
} catch (error) { } catch (error) {
ElMessage.error(error instanceof ApiError ? error.message : '对账单确认失败,请重试') ElMessage.error(error instanceof ApiError ? error.message : '对账单确认失败,请重试')
} finally { } finally {
@@ -153,23 +149,19 @@ async function confirmStatement(statement: FinanceBillSummary) {
} }
} }
function resetFilters() { function applyQuery(model: QueryModel) {
filters.keyword = '' filters.keyword = String(model.keyword || '')
filters.status = undefined filters.status = (model.status || undefined) as FinanceBillStatus | undefined
void loadBills(1) if (page.value !== 1) page.value = 1
else void loadBills(1)
} }
function handlePageChange(nextPage: number) { function resetFilters(model: QueryModel) {
void loadBills(nextPage) queryModel.value = model
} applyQuery(model)
function openInboundAssociation(inboundCode: string | null) {
const code = inboundCode?.trim()
if (!code) return
inboundAssociationCode.value = code
inboundAssociationVisible.value = true
} }
watch([page, pageSize], () => { void loadBills(page.value) })
onMounted(() => { void loadBills(1) }) onMounted(() => { void loadBills(1) })
</script> </script>
@@ -181,65 +173,32 @@ onMounted(() => { void loadBills(1) })
<span class="amount-warning">未收 <strong>¥ {{ formatAmount(totals.outstanding) }}</strong></span> <span class="amount-warning">未收 <strong>¥ {{ formatAmount(totals.outstanding) }}</strong></span>
</section> </section>
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="客户账单筛选" :fields="queryFields" :search-on-reset="false" @search="applyQuery" @reset="resetFilters" />
<section class="content-card"> <section class="content-card">
<form class="filter-bar" @submit.prevent="loadBills(1)"> <DataTable v-model:page="page" v-model:page-size="pageSize" :data="bills" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[20, 50, 100]" :row-actions="rowActions" row-key="billNo" empty-text="暂无账单">
<el-input v-model="filters.keyword" clearable placeholder="搜索账单编号" aria-label="搜索账单编号" class="keyword-input"> <template v-if="errorMessage" #error><div class="state-panel state-panel--error" role="alert"><p>{{ errorMessage }}</p><el-button @click="loadBills(1)"><RefreshCcw :size="15" />重试</el-button></div></template>
<template #prefix><Search :size="16" /></template> <template #billNo="{ row }"><RouterLink class="bill-number-link" :to="{ name: 'finance-bill-detail', params: { billNo: row.billNo } }">{{ row.billNo }}</RouterLink></template>
</el-input> <template #issueDate="{ row }">{{ formatDate(row.issueDate) }}</template>
<el-select v-model="filters.status" clearable placeholder="全部状态" aria-label="账单状态" class="status-select"> <template #dueDate="{ row }">{{ formatDate(row.dueDate) }}</template>
<el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" /> <template #totalAmount="{ row }">¥ {{ formatAmount(row.totalAmount) }}</template>
</el-select> <template #receivedAmount="{ row }">¥ {{ formatAmount(row.receivedAmount) }}</template>
<el-button type="primary" native-type="submit" :loading="loading">查询</el-button> <template #outstandingAmount="{ row }"><strong :class="{ 'amount-warning': row.outstandingAmount !== '0' }">¥ {{ formatAmount(row.outstandingAmount) }}</strong></template>
<el-button :disabled="loading" @click="resetFilters">重置</el-button> <template #status="{ row }"><el-tag :type="statusType(row.status)">{{ statusLabel(row.status) }}</el-tag></template>
</form> <template #confirmationStatus="{ row }"><el-tag :type="confirmationType(row.customerConfirmationStatus)">{{ confirmationLabel(row.customerConfirmationStatus) }}</el-tag></template>
</DataTable>
<div v-if="errorMessage" class="state-panel state-panel--error" role="alert">
<p>{{ errorMessage }}</p>
<el-button @click="loadBills(1)"><RefreshCcw :size="15" />重试</el-button>
</div>
<el-table v-else v-loading="loading" :data="bills" row-key="billNo" class="finance-table" aria-label="客户账单列表">
<el-table-column label="操作" width="190" fixed="left">
<template #default="{ row }"><div class="table-actions"><el-button link type="primary" @click="openDetail(row as FinanceBillSummary)"><Eye :size="15" />查看</el-button><el-button v-if="row.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm" size="small" type="success" plain :loading="confirmingBillId === row.id" :disabled="Boolean(confirmingBillId)" @click="confirmStatement(row as FinanceBillSummary)">确认账单</el-button></div></template>
</el-table-column>
<el-table-column prop="billNo" label="账单编号" min-width="160" />
<el-table-column prop="issueDate" label="出账日期" width="120"><template #default="{ row }">{{ formatDate(row.issueDate) }}</template></el-table-column>
<el-table-column prop="dueDate" label="到期日" width="120"><template #default="{ row }">{{ formatDate(row.dueDate) }}</template></el-table-column>
<el-table-column label="账单金额" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.totalAmount) }}</template></el-table-column>
<el-table-column label="已收" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.receivedAmount) }}</template></el-table-column>
<el-table-column label="未收余额" width="145" align="right"><template #default="{ row }"><strong :class="{ 'amount-warning': row.outstandingAmount !== '0' }">¥ {{ formatAmount(row.outstandingAmount) }}</strong></template></el-table-column>
<el-table-column label="状态" width="110"><template #default="{ row }"><el-tag :type="statusType(row.status)">{{ statusLabel(row.status) }}</el-tag></template></el-table-column>
<el-table-column label="客户确认" width="110"><template #default="{ row }"><el-tag :type="confirmationType(row.customerConfirmationStatus)">{{ confirmationLabel(row.customerConfirmationStatus) }}</el-tag></template></el-table-column>
<template #empty><div class="table-empty"><CircleDollarSign :size="32" /><strong>暂无账单</strong><span>平台财务出账后,这里会显示本企业账单。</span></div></template>
</el-table>
<div v-if="!errorMessage && hasData" class="pagination-row"><span>共 {{ total }} 条</span><el-pagination v-model:current-page="page" :page-size="pageSize" layout="prev, pager, next" :total="total" @current-change="handlePageChange" /></div>
</section> </section>
<el-drawer v-model="detailVisible" title="账单详情" size="min(680px, 100%)" destroy-on-close>
<div v-loading="detailLoading" class="detail-content">
<div v-if="detailError" class="state-panel state-panel--error" role="alert"><p>{{ detailError }}</p><el-button @click="loadDetail(selectedBillId)">重试</el-button></div>
<template v-else-if="detail">
<div class="detail-heading"><div><h2>{{ detail.billNo }}</h2><p>出账 {{ formatDate(detail.issueDate) }} · 到期 {{ formatDate(detail.dueDate) }} · 未收 <strong class="amount-warning">¥ {{ formatAmount(detail.outstandingAmount) }}</strong></p></div><div class="detail-statuses"><el-tag :type="statusType(detail.status)">{{ statusLabel(detail.status) }}</el-tag><el-tag :type="confirmationType(detail.customerConfirmationStatus)">{{ confirmationLabel(detail.customerConfirmationStatus) }}</el-tag></div></div>
<section class="confirmation-panel" aria-label="客户确认信息"><div><strong>{{ confirmationLabel(detail.customerConfirmationStatus) }}</strong><p v-if="detail.customerConfirmationStatus === 'CONFIRMED'">{{ detail.customerConfirmedByName || '当前企业成员' }} · {{ formatDateTime(detail.customerConfirmedAt) }}</p><p v-else>请核对本期金额和费用明细,确认后将记录当前登录成员与确认时间。</p></div><el-button v-if="detail.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm" type="primary" :loading="confirmingBillId === detail.id" :disabled="Boolean(confirmingBillId)" @click="confirmStatement(detail)">确认账单</el-button></section>
<section class="detail-section"><h3>费用明细</h3><el-table :data="detail.lines" size="small"><el-table-column label="入仓码" min-width="170"><template #default="{ row }"><el-button v-if="row.inboundCode" link type="primary" :aria-label="`查看入仓码 ${row.inboundCode} 详情`" @click="openInboundAssociation(row.inboundCode)">{{ row.inboundCode }}</el-button><span v-else>—</span></template></el-table-column><el-table-column prop="feeName" label="费用项目" min-width="180" /><el-table-column label="金额" width="130" align="right"><template #default="{ row }">¥ {{ formatAmount(row.amount) }}</template></el-table-column></el-table></section>
<section class="detail-section"><h3>收款记录</h3><el-table v-if="detail.receipts.length" :data="detail.receipts" size="small"><el-table-column prop="receivedAt" label="收款日期" width="110"><template #default="{ row }">{{ formatDate(row.receivedAt) }}</template></el-table-column><el-table-column prop="receiptNo" label="收款编号" min-width="130" /><el-table-column label="本次金额" width="130" align="right"><template #default="{ row }">¥ {{ formatAmount(row.allocatedAmount) }}</template></el-table-column><el-table-column label="方式" min-width="100"><template #default="{ row }">{{ paymentMethodLabel(row.method) }}</template></el-table-column></el-table><div v-else class="sub-empty">暂无收款记录</div></section>
<p class="readonly-notice">如对账单内容有疑问,请先线下联系平台财务,核对无误后再确认。</p>
</template>
</div>
</el-drawer>
<InboundCodeAssociationDialog v-model="inboundAssociationVisible" :inbound-code="inboundAssociationCode" />
</div> </div>
</template> </template>
<style scoped> <style scoped>
.finance-bills-page { display: flex; flex-direction: column; gap: 12px; } .finance-bills-page { display: flex; flex-direction: column; gap: 12px; }
.bill-number-link { color: var(--primary); text-decoration: none; }
.bill-number-link:hover { text-decoration: underline; }
.finance-summary { display: flex; flex-wrap: wrap; gap: 8px 26px; color: var(--muted); font-size: 13px; }.finance-summary strong { margin-left: 6px; color: var(--navy); font-size: 18px; }.amount-warning, .amount-warning strong { color: #b45309; } .finance-summary { display: flex; flex-wrap: wrap; gap: 8px 26px; color: var(--muted); font-size: 13px; }.finance-summary strong { margin-left: 6px; color: var(--navy); font-size: 18px; }.amount-warning, .amount-warning strong { color: #b45309; }
.content-card { min-width: 0; padding: 16px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface, #fff); } .content-card { min-width: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: var(--surface, #fff); }
.filter-bar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }.keyword-input { width: 260px; }.status-select { width: 140px; }
.finance-table { width: 100%; }.finance-table :deep(.el-button) { display: inline-flex; align-items: center; gap: 4px; }.table-actions { display: flex; align-items: center; gap: 8px; white-space: nowrap; }
.state-panel { display: flex; min-height: 180px; align-items: center; justify-content: center; gap: 12px; flex-direction: column; color: var(--muted); text-align: center; }.state-panel p { margin: 0; }.state-panel--error { color: #b42318; background: #fff8f7; border: 1px solid #f5c2bd; border-radius: 6px; } .state-panel { display: flex; min-height: 180px; align-items: center; justify-content: center; gap: 12px; flex-direction: column; color: var(--muted); text-align: center; }.state-panel p { margin: 0; }.state-panel--error { color: #b42318; background: #fff8f7; border: 1px solid #f5c2bd; border-radius: 6px; }
.table-empty { display: flex; align-items: center; flex-direction: column; gap: 8px; padding: 42px 12px; color: var(--muted); }.table-empty strong { color: var(--navy); }.table-empty span { font-size: 12px; }
.pagination-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 14px; color: var(--muted); font-size: 12px; }
.detail-content { min-height: 300px; }.detail-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.detail-heading h2 { margin: 0 0 5px; color: var(--navy); font-size: 18px; }.detail-heading p { margin: 0; color: var(--muted); font-size: 13px; }.detail-statuses { display: flex; align-items: center; gap: 8px; }.confirmation-panel { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-top: 18px; padding: 14px 16px; border: 1px solid #d7e9e4; border-radius: 8px; background: #f3f9f7; }.confirmation-panel strong { color: var(--navy); }.confirmation-panel p { margin: 4px 0 0; color: var(--muted); font-size: 12px; }.detail-section { margin-top: 22px; }.detail-section h3 { margin: 0 0 10px; color: var(--navy); font-size: 14px; }.sub-empty { padding: 22px; color: var(--muted); font-size: 12px; text-align: center; background: #f7fafb; }.readonly-notice { margin: 22px 0 0; padding: 11px 12px; color: #45615d; background: #edf6f4; font-size: 12px; } .detail-content { min-height: 300px; }.detail-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.detail-heading h2 { margin: 0 0 5px; color: var(--navy); font-size: 18px; }.detail-heading p { margin: 0; color: var(--muted); font-size: 13px; }.detail-statuses { display: flex; align-items: center; gap: 8px; }.confirmation-panel { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-top: 18px; padding: 14px 16px; border: 1px solid #d7e9e4; border-radius: 8px; background: #f3f9f7; }.confirmation-panel strong { color: var(--navy); }.confirmation-panel p { margin: 4px 0 0; color: var(--muted); font-size: 12px; }.detail-section { margin-top: 22px; }.detail-section h3 { margin: 0 0 10px; color: var(--navy); font-size: 14px; }.sub-empty { padding: 22px; color: var(--muted); font-size: 12px; text-align: center; background: #f7fafb; }.readonly-notice { margin: 22px 0 0; padding: 11px 12px; color: #45615d; background: #edf6f4; font-size: 12px; }
@media (max-width: 720px) { .keyword-input, .status-select { width: 100%; }.filter-bar > .el-button { flex: 1; }.content-card { padding: 12px; }.pagination-row { align-items: flex-start; flex-direction: column; }.finance-summary { align-items: flex-start; flex-direction: column; gap: 6px; } } @media (max-width: 720px) { .finance-summary { align-items: flex-start; flex-direction: column; gap: 6px; } }
</style> </style>
+35
View File
@@ -0,0 +1,35 @@
# Client 头程模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/first-leg/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,字段与接口细则见 `../../../docs/business-index.md`。
- 模块分层固定:`views/` 页面、`components/` 业务组件、`api/` 请求、`store/` 跨页状态、`types/`、`utils/`、`data/`;跨模块只能从本目录 `public.ts` 导入。
- 后端只查 `order/`(订单读写与批量导入)、`firstleg/`(履约进度、入库费用、报关资料)、`file/`(资质与附件);纯页面与文案不读后端。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 头程订单列表、详情、草稿编辑 | `views/FirstLegOrdersView.vue`;`orders/first-leg`、`orders/first-leg/:orderId/detail`、`orders/first-leg/:draftId/edit` | `api/firstLeg.ts`;`store/firstLegOrders.ts`;`order/` |
| 创建订单入口(选业务类型) | `views/FirstLegOrderCreateHubView.vue`;`orders/first-leg/create` | `components/FirstLegOrderEditorShell.vue` |
| 快速下单(按渠道/目的仓/SKU 生成草稿) | `views/QuickOrderView.vue`;`first-leg/quick-order` | `api/firstLeg.ts`;只生成草稿,不提交、不审核 |
| 中文批量导入与逐行结果 | 订单列表导入入口 | `api/firstLeg.ts`;`order/` 批量导入;入仓码与失败原因逐行展示 |
| 履约进度与入仓码关系 | `components/OrderProgressPanel.vue`、`components/InboundCodeAssociationDialog.vue` | `api/inboundCodeAssociations.ts`、`utils/orderProgress.ts`;`firstleg/` |
| 运输事实与商品图片 | `components/TransportFactsTable.vue`(纯展示)、`utils/transportFacts.ts`、`utils/productImage.ts` | 行数据类型来自 `api/unifiedOrders.ts`;图片读取归 `file/` |
| 入库费用确认与计费重 | `components/InboundBillingPanel.vue` | `api/inboundBilling.ts`;`firstleg/service/MerchantInboundBillingService.java` |
| 装柜后的退税报关资料 | `views/CustomsDocumentsView.vue`、`components/CustomsDocumentsDialog.vue` | `api/customs.ts`、`store/customsPending.ts`、`utils/customsEligibility.ts`;`firstleg/customs/`、`file/` |
| 船期与参考价格 | `views/SailingPricesView.vue`;`first-leg/sailing-prices` | `api/firstLeg.ts`;`firstleg/` 船期价格 |
| 往来单位候选 | `data/firstLegParties.ts`、`api/partners.ts` | `warehouse/` 公共往来单位 |
## 关键边界
- 头程订单只用当前正式读写契约;不得扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API、历史部分响应兼容或其他新旧并跑逻辑。触及该链路时同步删除生产分支、类型、文案、Mock 和测试。
- 快速下单只创建草稿,不提交、不审核;逐行失败必须回填原因与入仓码,不用内部 ID 代替业务编号。
- 入库费用确认携带 `expectedFeeVersion` 与幂等键,金额与冻结状态只认服务端结果;列表“确认计费重”仅在具备确认权限且服务端 `customerFeeConfirmationRequired=true` 时显示,已确认或未推送费用的订单不显示;详情保留费用查看入口。
- 报关资料在开始后只读冻结资料,未装柜或无资格时不展示入口;`utils/customsEligibility.ts` 是唯一资格判断入口。
- 模块间协作只能从本模块 `public.ts` 导入,不穿透其他模块的 `views/` 或内部目录。
## 验证
- 定向:`pnpm test src/modules/first-leg/<目标测试>`;接口或类型变化同时运行 `pnpm typecheck`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+13
View File
@@ -0,0 +1,13 @@
# 头程下单交货方式调整
依据:当前对话 2026-10-19 用户确认“卡车自送排第一,我司提货排第二,快递自提排第三;快递自提增加非必填快递单号”。该确认优先于历史原型对应字段。
2026-10-20 补充确认:新建、重置头程订单默认选择“卡车自送”;快速下单生成的草稿同步使用该默认值,编辑已有草稿保留原取货方式。
| 页面 | 操作 | 承载方式 | 布局 | 当前实现 | 结论 |
|---|---|---|---|---|---|
| 头程下单 | 新增 | 现有独立页面 | 保持现有国内交货区布局 | 快递自送、我司提货、卡车自送;无快递单号输入 | 按确认顺序排列;第三项改为快递自提,下方条件显示选填快递单号 |
| 头程订单 | 编辑草稿 | 现有居中弹框 | 复用新增表单 | 无快递单号输入 | 同步新增规则,回显已保存单号 |
| 头程订单 | 详情 | 现有独立页面 | 保持现有信息区 | 已有快递单号只读展示 | 复用当前展示;说明客户可在快递自提草稿填写单号 |
自动检查与人工视觉验收分别记录;1920×1080、100% 缩放的页面效果待人工截图确认。
+1 -1
View File
@@ -22,7 +22,7 @@ test('sends multi-inbound scope, optimistic versions and idempotency for every w
assert.match(source, /params\.append\('inboundIds', id\)/) assert.match(source, /params\.append\('inboundIds', id\)/)
assert.match(source, /expectedVersion: document\.source\.version/) assert.match(source, /expectedVersion: document\.source\.version/)
assert.match(source, /params: \{ expectedVersion: document\.source\.version \}/) assert.match(source, /params: \{ expectedVersion: document\.source\.version \}/)
assert.equal(source.match(/'Idempotency-Key'/g)?.length, 4) assert.equal(source.match(/'Idempotency-Key'/g)?.length, 6)
assert.match(source, /data\.append\('file', file\)/) assert.match(source, /data\.append\('file', file\)/)
assert.match(source, /file\.size > MAX_CUSTOMS_FILE_SIZE/) assert.match(source, /file\.size > MAX_CUSTOMS_FILE_SIZE/)
}) })
+87 -4
View File
@@ -14,6 +14,24 @@ export interface MerchantCustomsFile {
uploadedAt: string uploadedAt: string
} }
export interface MerchantCustomsReceiptVersion {
version: number
file: MerchantCustomsFile
operatorName: string | null
createdAt: string
}
export type MerchantCustomsConfirmationAction = 'CONFIRM' | 'REJECT'
export interface MerchantCustomsConfirmationHistory {
id: string
receiptVersion: number
action: MerchantCustomsConfirmationAction
reason: string | null
operatorName: string
createdAt: string
}
export interface MerchantCustomsInbound { export interface MerchantCustomsInbound {
inboundId: string inboundId: string
orderId: string orderId: string
@@ -32,7 +50,12 @@ export interface MerchantCustomsDocument {
inboundIds: string[] inboundIds: string[]
inboundCodes: string[] inboundCodes: string[]
frozen: boolean frozen: boolean
completion: MerchantCustomsFile | null receipt: MerchantCustomsFile | null
receiptStatus: 'PENDING' | 'CONFIRMED' | 'REJECTED' | null
receiptRejectReason: string | null
finalDocument: MerchantCustomsFile | null
receiptHistory?: MerchantCustomsReceiptVersion[]
confirmationHistory: MerchantCustomsConfirmationHistory[]
} }
export interface MerchantCustomsContainer { export interface MerchantCustomsContainer {
@@ -47,12 +70,32 @@ export interface MerchantCustomsContainer {
version: number version: number
taxRefundCount: number taxRefundCount: number
coveredTaxRefundCount: number coveredTaxRefundCount: number
actualBoxCount: number
inbounds: MerchantCustomsInbound[] inbounds: MerchantCustomsInbound[]
documents: MerchantCustomsDocument[] documents: MerchantCustomsDocument[]
startedAt?: string | null startedAt?: string | null
brokerSubmittedAt?: string | null
completedAt?: string | null completedAt?: string | null
} }
export type MerchantClearanceResultType = 'INSPECTION' | 'SUPPLEMENT_REQUIRED' | 'RELEASED' | 'DETAINED' | 'OTHER'
export type MerchantClearanceResultStatus = 'OPEN' | 'RESOLVED' | 'CANCELLED'
export interface MerchantClearanceResult {
id: string
declarationBatchId: string
customsContainerId: string
resultType: MerchantClearanceResultType
resultStatus: MerchantClearanceResultStatus
customsEntryNo: string | null
occurredAt: string
resolution: string | null
evidenceFileId: string | null
recordedByName: string
recordedAt: string
previousResultId: string | null
}
export interface ApiErrorMeta { export interface ApiErrorMeta {
code: string code: string
requestId: string | null requestId: string | null
@@ -100,6 +143,13 @@ export function getMerchantCustomsForOrder(orderId: string) {
}) })
} }
export function getMerchantClearanceResults(orderId: string) {
return apiRequest<MerchantClearanceResult[]>({
method: 'GET',
url: `/merchant/v1/customs/orders/${encodedId(orderId)}/clearance-results`,
})
}
export function uploadMerchantCustomsDocument(planId: string, inboundIds: string[], file: File) { export function uploadMerchantCustomsDocument(planId: string, inboundIds: string[], file: File) {
validateMerchantCustomsFile(file) validateMerchantCustomsFile(file)
return apiRequest<MerchantCustomsDocument>({ return apiRequest<MerchantCustomsDocument>({
@@ -183,13 +233,38 @@ export function downloadMerchantCustomsSource(document: MerchantCustomsDocument)
return download(`/merchant/v1/customs/documents/${encodedId(document.documentId)}/download`, document.source.fileName) return download(`/merchant/v1/customs/documents/${encodedId(document.documentId)}/download`, document.source.fileName)
} }
export function downloadMerchantCustomsCompletion(document: MerchantCustomsDocument) { export function downloadMerchantCustomsReceipt(document: MerchantCustomsDocument) {
return download( return download(
`/merchant/v1/customs/documents/${encodedId(document.documentId)}/completion/download`, `/merchant/v1/customs/documents/${encodedId(document.documentId)}/receipt/download`,
document.completion?.fileName || `customs-completion-${document.documentId}`, document.receipt?.fileName || `customs-receipt-${document.documentId}`,
) )
} }
export function downloadMerchantCustomsFinal(document: MerchantCustomsDocument) {
return download(
`/merchant/v1/customs/documents/${encodedId(document.documentId)}/final/download`,
document.finalDocument?.fileName || `customs-final-${document.documentId}`,
)
}
export function confirmMerchantCustomsReceipt(document: MerchantCustomsDocument) {
return apiRequest<MerchantCustomsContainer>({
method: 'POST',
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}/receipt/confirm`,
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-receipt-confirm-${document.documentId}`) },
data: { expectedVersion: document.receipt?.version ?? 0, confirm: true, remark: null },
})
}
export function rejectMerchantCustomsReceipt(document: MerchantCustomsDocument, reason: string) {
return apiRequest<MerchantCustomsContainer>({
method: 'POST',
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}/receipt/reject`,
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-receipt-reject-${document.documentId}`) },
data: { expectedVersion: document.receipt?.version ?? 0, confirm: false, remark: reason },
})
}
export function merchantCustomsErrorMeta(error: unknown): ApiErrorMeta | null { export function merchantCustomsErrorMeta(error: unknown): ApiErrorMeta | null {
if (!(error instanceof ApiError)) return null if (!(error instanceof ApiError)) return null
return { code: error.code, requestId: error.requestId ?? null, traceId: error.traceId ?? null } return { code: error.code, requestId: error.requestId ?? null, traceId: error.traceId ?? null }
@@ -208,3 +283,11 @@ export function merchantCustomsErrorMessage(error: unknown, fallback: string) {
export function isMerchantCustomsUnavailable(error: unknown) { export function isMerchantCustomsUnavailable(error: unknown) {
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404') return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
} }
export async function getMerchantCustomsPendingCount() {
const result = await apiRequest<{ pendingCount: string | number }>({ method: 'GET', url: '/merchant/v1/customs/pending-summary' })
const count = Number(result.pendingCount)
if (result.pendingCount == null || result.pendingCount === '' || !Number.isSafeInteger(count) || count < 0) throw new Error('报关待办数量返回不完整')
return count
}
+12 -3
View File
@@ -139,6 +139,7 @@ export interface FirstLegOrderSaveRequest {
privateDestinationAddressId?: number | string privateDestinationAddressId?: number | string
cargoes: FirstLegOrderCargoPayload[] cargoes: FirstLegOrderCargoPayload[]
pickupMethod: ApiPickupMethod pickupMethod: ApiPickupMethod
expressTrackingNo?: string
receivingWarehouseId: number | string receivingWarehouseId: number | string
receivingWarehouseName: string receivingWarehouseName: string
receivingWarehouseAddress?: string | null receivingWarehouseAddress?: string | null
@@ -296,6 +297,8 @@ export interface MerchantFirstLegOrderRow {
inboundedAt: string | null inboundedAt: string | null
businessDate: string | null businessDate: string | null
shipmentId: string | null shipmentId: string | null
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
lxCode?: string | null
createdAt: string createdAt: string
cargoes?: Array<{ skuNo?: string | null }> cargoes?: Array<{ skuNo?: string | null }>
} }
@@ -439,6 +442,7 @@ export interface MerchantPriceEstimateRequest {
destinationWarehouseId?: number | string destinationWarehouseId?: number | string
destinationName?: string destinationName?: string
pricingTaxMode: ApiPricingTaxMode pricingTaxMode: ApiPricingTaxMode
chargeMode?: 'KG' | 'CBM'
actualWeightKg: number actualWeightKg: number
actualVolumeCbm: number actualVolumeCbm: number
} }
@@ -563,14 +567,19 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
}) })
} }
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) { export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload }) return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
} }
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) { export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
}
export function submitMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number }, idempotencyKey: string) {
return apiRequest<void>({ return apiRequest<void>({
method: 'POST', method: 'POST',
url: `/merchant/v1/orders/first-leg/${id}/submit`, url: `/merchant/v1/orders/first-leg/${id}/submit`,
data: payload,
headers: { 'Idempotency-Key': idempotencyKey }, headers: { 'Idempotency-Key': idempotencyKey },
}) })
} }
@@ -1,9 +1,28 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import test from 'node:test' import test from 'node:test'
import ts from 'typescript'
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8') const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
test('forwards optional tax mode and pagination through the current GET endpoint', async () => {
const calls = []
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
const api = {}
new Function('require', 'exports', code)(id => {
assert.equal(id, '@/api/http')
return { apiRequest: async config => { calls.push(config); return { records: [] } } }
}, api)
await api.getMerchantUnifiedOrders({ page: 2, size: 200, taxMode: 'TAX_REFUND' })
await api.getMerchantUnifiedOrders({ taxMode: 'BUY_DECLARATION' })
await api.getMerchantUnifiedOrders()
assert.deepEqual(calls, [
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 2, size: 200, taxMode: 'TAX_REFUND' } },
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200, taxMode: 'BUY_DECLARATION' } },
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200 } },
])
})
test('keeps the merchant unified-order boundary and one-click palletization status', () => { test('keeps the merchant unified-order boundary and one-click palletization status', () => {
assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/) assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/) assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
+66 -9
View File
@@ -1,5 +1,5 @@
import { ApiError, apiRequest } from '@/api/http' import { apiRequest } from '@/api/http'
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg' import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
export type ApiUnifiedOrderMainStatus = export type ApiUnifiedOrderMainStatus =
| 'PENDING_REVIEW' | 'PENDING_REVIEW'
@@ -48,17 +48,24 @@ export interface MerchantUnifiedTransportSummary {
cabinetNo: string | null cabinetNo: string | null
vesselName: string | null vesselName: string | null
voyageNo: string | null voyageNo: string | null
sailingAt: string | null estimatedSailingAt: string | null
portArrivalAt: string | null actualSailingAt: string | null
effectiveSailingAt: string | null
effectiveSailingAtEstimated: boolean | null
estimatedPortArrivalAt: string | null
actualPortArrivalAt: string | null
effectivePortArrivalAt: string | null
effectivePortArrivalAtEstimated: boolean | null
} }
export interface MerchantUnifiedOrderRow { export interface MerchantUnifiedOrderRow {
orderId: number | string orderId: number | string
orderVersion: number
tenantId: number | string tenantId: number | string
orderNo: string | null orderNo: string | null
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
lxCode?: string | null lxCode?: string | null
mainStatus: ApiUnifiedOrderMainStatus mainStatus: ApiUnifiedOrderMainStatus | 'DRAFT' | 'CANCELLED'
nextAction: string | null nextAction: string | null
customerFeeConfirmationRequired: boolean customerFeeConfirmationRequired: boolean
internalOrderStatus: ApiFirstLegStatus | null internalOrderStatus: ApiFirstLegStatus | null
@@ -77,6 +84,8 @@ export interface MerchantUnifiedOrderRow {
actualGrossWeightKg: number | null actualGrossWeightKg: number | null
actualVolumeCbm: number | null actualVolumeCbm: number | null
pickupMethod: ApiPickupMethod | null pickupMethod: ApiPickupMethod | null
taxMode: ApiTaxMode | null
customsInspection: boolean | null
requestedPickupAt: string | null requestedPickupAt: string | null
containerMode: ApiContainerMode | null containerMode: ApiContainerMode | null
destinationType: ApiDestinationType | null destinationType: ApiDestinationType | null
@@ -124,7 +133,26 @@ export interface MerchantUnifiedCustomNode {
attachmentIds: Array<number | string> attachmentIds: Array<number | string>
} }
export interface MerchantTransportNode {
standardNode: string
nodeSequence: number
providerCode: string | null
estimatedAt: string | null
actualAt: string | null
locationCode: string | null
locationName: string | null
}
export interface MerchantTransportFragment {
inboundCode: string | null
cabinetNo: string | null
containerNo: string | null
nodes: MerchantTransportNode[]
}
export interface MerchantUnifiedOrderDetail { export interface MerchantUnifiedOrderDetail {
progress: MerchantOrderProgress
transportFragments: MerchantTransportFragment[]
summary: MerchantUnifiedOrderRow summary: MerchantUnifiedOrderRow
order: MerchantFirstLegOrderDetail order: MerchantFirstLegOrderDetail
timeline: MerchantUnifiedTimelineEvent[] timeline: MerchantUnifiedTimelineEvent[]
@@ -133,6 +161,8 @@ export interface MerchantUnifiedOrderDetail {
} }
export interface MerchantUnifiedOrderQuery { export interface MerchantUnifiedOrderQuery {
taxMode?: ApiTaxMode
loaded?: boolean
keyword?: string keyword?: string
fbaCode?: string fbaCode?: string
orderNo?: string orderNo?: string
@@ -148,6 +178,37 @@ export interface MerchantUnifiedOrderQuery {
const unifiedOrderBaseUrl = '/merchant/v1/orders' const unifiedOrderBaseUrl = '/merchant/v1/orders'
export type OrderQueue = 'all' | 'fee' | 'customs' | 'draft' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
export type OrderProgressStage = 'none' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
export interface MerchantOrderProgress { orderId: string | number; stage: OrderProgressStage; partial: boolean }
export type OrderQueueCounts = Record<OrderQueue, number>
export interface MerchantOrderWorkbenchQuery {
cargoKeyword?: string
receivingWarehouseId?: string
channelName?: string
destinationType?: string
trackingNumber?: string
mainStatus?: string
createdFrom?: string
createdTo?: string
queue?: OrderQueue
page?: number
size?: number
}
export interface MerchantOrderWorkbench {
page: PageResult<MerchantUnifiedOrderRow>
queues: OrderQueueCounts
progress: MerchantOrderProgress[]
channelNames: string[]
}
export function getMerchantOrderWorkbench(params: MerchantOrderWorkbenchQuery = {}) {
return apiRequest<MerchantOrderWorkbench>({ method: 'GET', url: `${unifiedOrderBaseUrl}/workbench`,
params: { ...params, page: params.page ?? 1, size: params.size ?? 10 } })
}
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) { export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
const { page, size, ...filters } = params const { page, size, ...filters } = params
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({ return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
@@ -163,7 +224,3 @@ export function getMerchantUnifiedOrder(orderId: number | string) {
url: `${unifiedOrderBaseUrl}/${orderId}`, url: `${unifiedOrderBaseUrl}/${orderId}`,
}) })
} }
export function isUnifiedOrderQueryUnavailable(error: unknown) {
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
}
@@ -0,0 +1,149 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
function harness(t) {
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
const code = ts.transpileModule(source + '\nexport { loadDetail, detail, clearanceResults, loading, errorMessage, selectedInboundIds, clearanceError, clearanceLoading, retryClearanceResults, close }', { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
const props = vue.reactive({ modelValue: false, orderId: 'A', canEdit: true }), requests = [], clearances = [], updates = [], view = {}
const unmounts = []
const dependencies = { '../store/customsPending': { useCustomsPendingStore: () => ({ refresh: async () => {} }) }, vue: { ...vue, onBeforeUnmount: fn => unmounts.push(fn) }, 'element-plus': { ElMessage: {} }, '@/modules/first-leg/api/customs': {
getMerchantCustomsForOrder: id => { const pending = deferred(); requests.push({ id, ...pending }); return pending.promise },
getMerchantClearanceResults: id => { const pending = deferred(); clearances.push({ id, ...pending }); return pending.promise },
merchantCustomsErrorMessage: error => error.message,
} }
const scope = vue.effectScope()
scope.run(() => new Function('require', 'exports', 'defineProps', 'defineEmits', code)(id => {
assert.ok(id in dependencies, id); return dependencies[id]
}, view, () => props, () => (...args) => updates.push(args)))
t.after(() => scope.stop())
return { props, requests, clearances, updates, view, unmount: () => unmounts.forEach(fn => fn()) }
}
const detail = id => ({ loadingPlanId: id, inbounds: [{ orderId: id, inboundId: `IN-${id}`, taxMode: 'TAX_REFUND' }] })
const tick = async () => { await Promise.resolve(); await vue.nextTick(); await Promise.resolve() }
test('result section stays pending while the refreshed detail is still loading', async t => {
const h = harness(t)
h.props.initialDetail = detail('A')
h.props.modelValue = true
await tick()
assert.equal(h.view.detail.value.loadingPlanId, 'A')
assert.equal(h.view.loading.value, true)
assert.equal(h.view.clearanceLoading.value, false)
assert.equal(h.clearances.length, 0)
const template = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
assert.match(template, /v-else-if="loading \|\| clearanceLoading"/)
h.requests[0].resolve(detail('A')); await tick()
assert.equal(h.view.clearanceLoading.value, true)
h.clearances[0].resolve([]); await tick()
assert.equal(h.view.loading.value, false)
assert.equal(h.view.clearanceLoading.value, false)
assert.deepEqual(h.view.clearanceResults.value, [])
})
test('switching orders while open starts the new request and ignores stale detail', async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.props.orderId = 'B'; await tick()
assert.deepEqual(h.requests.map(r => r.id), ['A', 'B'])
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
h.requests[0].resolve(detail('A')); await tick()
assert.equal(h.view.detail.value.loadingPlanId, 'B')
assert.deepEqual(h.view.selectedInboundIds.value, ['IN-B'])
assert.deepEqual(h.clearances.map(r => r.id), ['B'])
assert.equal(h.updates.length, 1)
})
test('closing before detail response prevents stale data and events', async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.props.modelValue = false; await tick()
h.requests[0].resolve(detail('A')); await tick()
assert.equal(h.view.detail.value, null); assert.equal(h.view.loading.value, false)
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0)
})
test('closing and reopening ignores the previous clearance response', async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.requests[0].resolve(detail('A')); await tick()
h.props.modelValue = false; await tick(); h.props.orderId = 'B'; h.props.modelValue = true; await tick()
h.requests[1].resolve(detail('B')); await tick()
h.clearances[1].resolve([{ kind: 'B' }]); await tick()
h.clearances[0].resolve([{ kind: 'A' }]); await tick()
assert.deepEqual(h.view.clearanceResults.value, [{ kind: 'B' }])
assert.equal(h.view.detail.value.loadingPlanId, 'B'); assert.equal(h.updates.length, 1)
})
test('stale detail failure cannot clear the next request loading or show an error', async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.props.orderId = 'B'; await tick(); h.requests[0].reject(new Error('old failure')); await tick()
assert.equal(h.view.loading.value, true); assert.equal(h.view.errorMessage.value, '')
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
assert.equal(h.view.loading.value, false); assert.equal(h.view.detail.value.loadingPlanId, 'B')
})
test('unmount invalidates pending detail requests', async t => {
const h = harness(t); h.props.modelValue = true; await tick(); h.unmount()
h.requests[0].resolve(detail('A')); await tick()
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0); assert.equal(h.view.detail.value, null)
})
test('result failure retains documents and exposes error; retry queries only results and deduplicates clicks', async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.requests[0].resolve({ ...detail('A'), documents: [{ documentId: 'document-A' }] }); await tick()
h.clearances[0].reject(new Error('结果服务暂不可用')); await tick()
assert.equal(h.view.errorMessage.value, '')
assert.equal(h.view.clearanceError.value, '结果服务暂不可用')
assert.equal(h.view.detail.value.documents[0].documentId, 'document-A')
assert.equal(h.view.loading.value, false)
const retry = h.view.retryClearanceResults()
await h.view.retryClearanceResults()
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 2)
assert.equal(h.view.clearanceLoading.value, true)
h.clearances[1].resolve([{ id: 'result-A' }]); await retry
assert.equal(h.view.clearanceError.value, '')
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'result-A' }])
assert.equal(h.view.clearanceLoading.value, false)
})
test('normal open requests detail and results exactly once and distinguishes successful empty results', async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].resolve([]); await tick()
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 1)
assert.equal(h.view.clearanceError.value, '')
assert.equal(h.view.clearanceLoading.value, false)
})
for (const transition of ['switch', 'close', 'unmount']) {
for (const outcome of ['resolve', 'reject']) {
test(`${transition} ignores stale result retry ${outcome}`, async t => {
const h = harness(t); h.props.modelValue = true; await tick()
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].reject(new Error('first failure')); await tick()
const retry = h.view.retryClearanceResults()
if (transition === 'switch') { h.props.orderId = 'B'; await tick() }
else if (transition === 'close') { h.view.close(); h.props.modelValue = false; await tick() }
else h.unmount()
if (outcome === 'resolve') h.clearances[1].resolve([{ id: 'old-A' }])
else h.clearances[1].reject(new Error('old retry failure'))
await retry
assert.equal(h.view.clearanceError.value, '')
assert.deepEqual(h.view.clearanceResults.value, [])
if (transition === 'switch') {
h.requests[1].resolve(detail('B')); await tick(); h.clearances[2].resolve([{ id: 'B' }]); await tick()
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'B' }])
} else {
await h.view.retryClearanceResults()
assert.equal(h.clearances.length, 2)
}
})
}
}
test('result error and retry reuse existing section error styling before the empty state', () => {
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
assert.match(source, /v-if="clearanceError" class="customs-error" role="alert"/)
assert.match(source, /@click="retryClearanceResults"/)
assert.match(source, /v-else-if="loading \|\| clearanceLoading"/)
assert.match(source, /v-else-if="!clearanceResults.length"/)
})
@@ -1,22 +1,31 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue' import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue' import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue'
import CustomsHelp from './CustomsHelp.vue'
import { import {
MERCHANT_CUSTOMS_STATUS_LABELS, MERCHANT_CUSTOMS_STATUS_LABELS,
deleteMerchantCustomsDocument, deleteMerchantCustomsDocument,
downloadMerchantCustomsCompletion, confirmMerchantCustomsReceipt,
downloadMerchantCustomsReceipt,
downloadMerchantCustomsFinal,
downloadMerchantCustomsSource, downloadMerchantCustomsSource,
getMerchantCustomsForOrder, getMerchantCustomsForOrder,
getMerchantClearanceResults,
merchantCustomsErrorMessage, merchantCustomsErrorMessage,
replaceMerchantCustomsDocument, replaceMerchantCustomsDocument,
rejectMerchantCustomsReceipt,
updateMerchantCustomsDocumentInbounds, updateMerchantCustomsDocumentInbounds,
uploadMerchantCustomsDocument, uploadMerchantCustomsDocument,
validateMerchantCustomsFile, validateMerchantCustomsFile,
type MerchantCustomsContainer, type MerchantCustomsContainer,
type MerchantCustomsDocument, type MerchantCustomsDocument,
type MerchantClearanceResult,
} from '@/modules/first-leg/api/customs' } from '@/modules/first-leg/api/customs'
import { useCustomsPendingStore } from '../store/customsPending'
const customsPending = useCustomsPendingStore()
const props = defineProps<{ const props = defineProps<{
modelValue: boolean modelValue: boolean
orderId: string orderId: string
@@ -40,8 +49,16 @@ const uploadInput = ref<HTMLInputElement>()
const replaceInput = ref<HTMLInputElement>() const replaceInput = ref<HTMLInputElement>()
const mutating = ref(false) const mutating = ref(false)
const downloadingKey = ref('') const downloadingKey = ref('')
const clearanceResults = ref<MerchantClearanceResult[]>([])
const clearanceError = ref('')
const clearanceLoading = ref(false)
let clearanceRequest = 0
let disposed = false
let detailRequest = 0
onBeforeUnmount(() => { disposed = true; detailRequest += 1; resetClearanceResults() })
const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? []) const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? [])
const pendingReceipts = computed(() => detail.value?.documents.filter((item) => item.receipt && item.receiptStatus !== 'CONFIRMED') ?? [])
const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED') const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED')
const merchantStatusLabel = computed(() => detail.value?.merchantStatus const merchantStatusLabel = computed(() => detail.value?.merchantStatus
? MERCHANT_CUSTOMS_STATUS_LABELS[detail.value.merchantStatus] ? MERCHANT_CUSTOMS_STATUS_LABELS[detail.value.merchantStatus]
@@ -60,31 +77,81 @@ function initializeSelection(value: MerchantCustomsContainer) {
selectedInboundIds.value = currentOrderIds selectedInboundIds.value = currentOrderIds
} }
function resetClearanceResults() {
clearanceRequest += 1
clearanceResults.value = []
clearanceError.value = ''
clearanceLoading.value = false
}
async function loadClearanceResults() {
if (disposed || !props.modelValue || !props.orderId || !detail.value || clearanceLoading.value) return
const request = ++clearanceRequest
const parentRequest = detailRequest
const orderId = props.orderId
const isCurrent = () => !disposed && request === clearanceRequest && parentRequest === detailRequest && props.modelValue && props.orderId === orderId
clearanceLoading.value = true
clearanceError.value = ''
try {
const results = await getMerchantClearanceResults(orderId)
if (isCurrent()) clearanceResults.value = results
} catch (error) {
if (isCurrent()) clearanceError.value = merchantCustomsErrorMessage(error, '海关申报结果加载失败')
} finally {
if (isCurrent()) clearanceLoading.value = false
}
}
async function retryClearanceResults() {
if (loading.value) return
await loadClearanceResults()
}
async function loadDetail() { async function loadDetail() {
if (!props.orderId) return if (disposed || !props.modelValue || !props.orderId) return
void customsPending.refresh(true)
const request = ++detailRequest
resetClearanceResults()
const orderId = props.orderId
const isCurrent = () => request === detailRequest && props.modelValue && props.orderId === orderId
loading.value = true loading.value = true
errorMessage.value = '' errorMessage.value = ''
try { try {
const result = await getMerchantCustomsForOrder(props.orderId) const result = await getMerchantCustomsForOrder(orderId)
if (!isCurrent()) return
detail.value = result detail.value = result
initializeSelection(result) initializeSelection(result)
await loadClearanceResults()
if (!isCurrent()) return
emit('updated', result) emit('updated', result)
} catch (error) { } catch (error) {
if (!isCurrent()) return
detail.value = null detail.value = null
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败') errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
} finally { } finally {
loading.value = false if (isCurrent()) loading.value = false
} }
} }
watch(() => props.modelValue, (open) => { watch(() => [props.modelValue, props.orderId] as const, ([open]) => {
detailRequest += 1
detail.value = null
resetClearanceResults()
selectedInboundIds.value = []
editingDocument.value = null
replacingDocument.value = null
errorMessage.value = ''
loading.value = false
if (!open) return if (!open) return
detail.value = props.initialDetail ?? null const initial = props.initialDetail
detail.value = initial?.inbounds.some((item) => item.orderId === props.orderId) ? initial : null
if (detail.value) initializeSelection(detail.value) if (detail.value) initializeSelection(detail.value)
void loadDetail() void loadDetail()
}) }, { immediate: true })
function close() { function close() {
detailRequest += 1
resetClearanceResults()
emit('update:modelValue', false) emit('update:modelValue', false)
} }
@@ -192,13 +259,13 @@ function saveDownload(blob: Blob, fileName: string) {
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
} }
async function downloadFile(document: MerchantCustomsDocument, kind: 'source' | 'completion') { async function downloadFile(document: MerchantCustomsDocument, kind: 'source' | 'receipt' | 'final') {
const key = `${document.documentId}:${kind}` const key = `${document.documentId}:${kind}`
downloadingKey.value = key downloadingKey.value = key
try { try {
const result = kind === 'source' const result = kind === 'source'
? await downloadMerchantCustomsSource(document) ? await downloadMerchantCustomsSource(document)
: await downloadMerchantCustomsCompletion(document) : kind === 'receipt' ? await downloadMerchantCustomsReceipt(document) : await downloadMerchantCustomsFinal(document)
saveDownload(result.blob, result.fileName) saveDownload(result.blob, result.fileName)
} catch (error) { } catch (error) {
ElMessage.error(merchantCustomsErrorMessage(error, '文件下载失败')) ElMessage.error(merchantCustomsErrorMessage(error, '文件下载失败'))
@@ -207,23 +274,78 @@ async function downloadFile(document: MerchantCustomsDocument, kind: 'source' |
} }
} }
async function confirmReceipt() {
const documents = pendingReceipts.value
if (!documents.length) return
let confirmedCount = 0
try {
await ElMessageBox.confirm(`确认已核对 ${documents.length} 份报关行回执吗?确认后平台会把确认结果发送给报关行执行。`, '确认报关行回执', { type: 'warning' })
mutating.value = true
for (const document of documents) {
await confirmMerchantCustomsReceipt(document)
confirmedCount += 1
}
ElMessage.success(`已确认 ${documents.length} 份回执`)
await loadDetail()
} catch (error) {
if (error === 'cancel' || error === 'close') return
if (confirmedCount) await loadDetail()
ElMessage.error(`${confirmedCount ? `已确认 ${confirmedCount}/${documents.length} 份,` : ''}${merchantCustomsErrorMessage(error, '回执确认失败')}`)
} finally { mutating.value = false }
}
async function rejectReceipt() {
const documents = pendingReceipts.value
if (!documents.length) return
let rejectedCount = 0
try {
const reason = await ElMessageBox.prompt('请填写打回原因', '打回报关行回执', { inputValidator: (value) => value.trim() ? true : '请输入打回原因' })
mutating.value = true
for (const document of documents) {
await rejectMerchantCustomsReceipt(document, reason.value)
rejectedCount += 1
}
ElMessage.success(`已打回 ${documents.length} 份回执`)
await loadDetail()
} catch (error) {
if (error === 'cancel' || error === 'close') return
if (rejectedCount) await loadDetail()
ElMessage.error(`${rejectedCount ? `已打回 ${rejectedCount}/${documents.length} 份,` : ''}${merchantCustomsErrorMessage(error, '回执打回失败')}`)
} finally { mutating.value = false }
}
function formatDateTime(value: string | null | undefined) { function formatDateTime(value: string | null | undefined) {
if (!value) return '-' if (!value) return '-'
const date = new Date(value) const date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false }) return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
} }
function receiptHistoryLabel(document: MerchantCustomsDocument) {
return (document.receiptHistory || []).map((item) => `V${item.version}`).join('、') || '—'
}
function confirmationActionLabel(action: MerchantCustomsDocument['confirmationHistory'][number]['action']) {
return action === 'CONFIRM' ? '确认' : '打回'
}
function formatSize(bytes: number) { function formatSize(bytes: number) {
if (bytes < 1024) return `${bytes} B` if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB` return `${(bytes / 1024 / 1024).toFixed(1)} MB`
} }
function clearanceResultLabel(value: MerchantClearanceResult) {
return ({ INSPECTION: '查验', SUPPLEMENT_REQUIRED: '补充资料', RELEASED: '放行', DETAINED: '扣留', OTHER: '其他' } as Record<string, string>)[value.resultType] || value.resultType
}
function clearanceResultStatusLabel(value: MerchantClearanceResult) {
return value.resultStatus === 'RESOLVED' ? '已处理' : value.resultStatus === 'CANCELLED' ? '已取消' : '待处理'
}
</script> </script>
<template> <template>
<el-dialog <el-dialog
:model-value="modelValue" :model-value="modelValue"
class="customs-documents-dialog" class="customs-documents-dialog client-ui"
title="退税报关资料" title="退税报关资料"
width="920px" width="920px"
append-to-body append-to-body
@@ -246,17 +368,22 @@ function formatSize(bytes: number) {
<span>资料覆盖</span> <span>资料覆盖</span>
<strong>{{ detail.coveredTaxRefundCount }} / {{ detail.taxRefundCount }} 票</strong> <strong>{{ detail.coveredTaxRefundCount }} / {{ detail.taxRefundCount }} 票</strong>
</div> </div>
<div>
<span>实际箱数</span>
<strong>{{ detail.actualBoxCount }}</strong>
</div>
<el-tag :type="statusTagType" effect="light">{{ merchantStatusLabel }}</el-tag> <el-tag :type="statusTagType" effect="light">{{ merchantStatusLabel }}</el-tag>
</header> </header>
<div v-if="locked" class="customs-locked" role="status"> <div v-if="locked" class="customs-locked" role="status">
<LockKeyhole :size="18" /> <LockKeyhole :size="18" />
<div><strong>报关资料已锁定</strong><span>报关开始后仅可查看和下载,不提供退回或解锁。</span></div> <div v-if="detail.status === 'COMPLETED'"><strong>报关已完成</strong><span>真实报关完税文件已齐全,可查看和下载资料、回执及完税文件。</span></div>
<div v-else><strong>{{ detail.brokerSubmittedAt ? '已发送报关行执行' : '报关资料已锁定' }}</strong><span>{{ detail.brokerSubmittedAt ? '平台已将客户确认后的回执发送给报关行,等待真实报关完税文件。' : '客户原始资料已冻结,仍可确认或打回待确认的报关行回执。' }}</span></div>
</div> </div>
<section class="customs-section"> <section class="customs-section">
<div class="customs-section-title"> <div class="customs-section-title">
<div><h3>上传资料</h3><p>支持任意格式,单个文件不超过 50MB;可关联同柜内当前企业的一票或多票退税入仓码。</p></div> <div class="customs-help-heading"><h3>上传资料</h3><CustomsHelp title="报关资料上传说明"><p>支持任意格式,单个文件不超过 50MB;可关联同柜内当前企业的一票或多票退税入仓码。</p></CustomsHelp></div>
<el-button v-if="canEdit && !locked" type="primary" :loading="mutating" @click="chooseUpload"><Upload :size="16" />选择文件上传</el-button> <el-button v-if="canEdit && !locked" type="primary" :loading="mutating" @click="chooseUpload"><Upload :size="16" />选择文件上传</el-button>
</div> </div>
<el-checkbox-group v-model="selectedInboundIds" class="customs-inbound-options" :disabled="!canEdit || locked" aria-label="选择资料关联入仓码"> <el-checkbox-group v-model="selectedInboundIds" class="customs-inbound-options" :disabled="!canEdit || locked" aria-label="选择资料关联入仓码">
@@ -269,9 +396,33 @@ function formatSize(bytes: number) {
<input ref="replaceInput" class="customs-hidden-input" type="file" @change="handleReplacementFile"> <input ref="replaceInput" class="customs-hidden-input" type="file" @change="handleReplacementFile">
</section> </section>
<section class="customs-section clearance-results-section">
<div class="customs-section-title">
<h3>海关申报结果</h3>
</div>
<div v-if="clearanceError" class="customs-error" role="alert">
<strong>海关申报结果加载失败</strong>
<span>{{ clearanceError }}</span>
<el-button :loading="clearanceLoading" @click="retryClearanceResults">重新加载</el-button>
</div>
<el-skeleton v-else-if="loading || clearanceLoading" :rows="2" animated />
<el-empty v-else-if="!clearanceResults.length" description="暂无海关结果" :image-size="48" />
<div v-else class="clearance-result-list">
<div v-for="item in clearanceResults" :key="item.id" class="clearance-result-row">
<div><strong>{{ clearanceResultLabel(item) }}</strong><span>{{ formatDateTime(item.occurredAt) }} · 报关单号 {{ item.customsEntryNo || '—' }}</span></div>
<el-tag size="small" :type="item.resultStatus === 'RESOLVED' ? 'success' : 'warning'">{{ clearanceResultStatusLabel(item) }}</el-tag>
<p v-if="item.resolution">{{ item.resolution }}</p>
</div>
</div>
</section>
<section class="customs-section"> <section class="customs-section">
<div class="customs-section-title"> <div class="customs-section-title">
<div><h3>资料版本历史</h3><p>每份当前资料展示服务端版本、关联票和上传时间;覆盖及删除操作由服务端保留不可变历史。</p></div> <h3>资料版本历史</h3>
<div v-if="pendingReceipts.length && detail.status === 'DECLARING'" class="customs-receipt-actions">
<el-button type="success" :disabled="mutating" @click="confirmReceipt">确认全部回执</el-button>
<el-button type="danger" plain :disabled="mutating" @click="rejectReceipt">打回全部回执</el-button>
</div>
</div> </div>
<el-empty v-if="!detail.documents.length" description="尚未上传退税报关资料" :image-size="54" /> <el-empty v-if="!detail.documents.length" description="尚未上传退税报关资料" :image-size="54" />
<div v-else class="customs-document-list"> <div v-else class="customs-document-list">
@@ -281,12 +432,16 @@ function formatSize(bytes: number) {
<div> <div>
<strong>{{ item.source.fileName }}</strong> <strong>{{ item.source.fileName }}</strong>
<span>版本 V{{ item.source.version }} · {{ formatSize(item.source.sizeBytes) }} · {{ formatDateTime(item.source.uploadedAt) }}</span> <span>版本 V{{ item.source.version }} · {{ formatSize(item.source.sizeBytes) }} · {{ formatDateTime(item.source.uploadedAt) }}</span>
<small v-if="item.receiptHistory?.length">报关行回执历史:{{ receiptHistoryLabel(item) }}</small>
<small v-for="history in item.confirmationHistory" :key="history.id">{{ confirmationActionLabel(history.action) }} · {{ formatDateTime(history.createdAt) }} · {{ history.operatorName || '—' }}<span v-if="history.reason"> · {{ history.reason }}</span></small>
<small>关联入仓码:{{ item.inboundCodes.join('、') || '—' }}</small> <small>关联入仓码:{{ item.inboundCodes.join('、') || '—' }}</small>
</div> </div>
</div> </div>
<div class="customs-document-actions"> <div class="customs-document-actions">
<el-button link type="primary" :loading="downloadingKey === `${item.documentId}:source`" @click="downloadFile(item, 'source')"><Download :size="15" />源文件</el-button> <el-button link type="primary" :loading="downloadingKey === `${item.documentId}:source`" @click="downloadFile(item, 'source')"><Download :size="15" />源文件</el-button>
<el-button v-if="detail.status === 'COMPLETED' && item.completion" link type="success" :loading="downloadingKey === `${item.documentId}:completion`" @click="downloadFile(item, 'completion')"><Download :size="15" />完成文件</el-button> <el-button v-if="item.receipt" link type="success" :loading="downloadingKey === `${item.documentId}:receipt`" @click="downloadFile(item, 'receipt')"><Download :size="15" />报关行回执</el-button>
<el-button v-if="item.finalDocument" link type="success" :loading="downloadingKey === `${item.documentId}:final`" @click="downloadFile(item, 'final')"><Download :size="15" />报关完税文件</el-button>
<el-tag v-if="item.receipt" size="small" :type="item.receiptStatus === 'CONFIRMED' ? 'success' : item.receiptStatus === 'REJECTED' ? 'danger' : 'warning'">{{ item.receiptStatus === 'CONFIRMED' ? '已确认' : item.receiptStatus === 'REJECTED' ? `已打回:${item.receiptRejectReason || '待补充'}` : '待确认' }}</el-tag>
<template v-if="canEdit && !locked && !item.frozen"> <template v-if="canEdit && !locked && !item.frozen">
<el-button link type="primary" :disabled="mutating" @click="beginEditInbounds(item)"><Pencil :size="15" />改关联</el-button> <el-button link type="primary" :disabled="mutating" @click="beginEditInbounds(item)"><Pencil :size="15" />改关联</el-button>
<el-button link type="primary" :disabled="mutating" @click="chooseReplacement(item)"><Upload :size="15" />覆盖</el-button> <el-button link type="primary" :disabled="mutating" @click="chooseReplacement(item)"><Upload :size="15" />覆盖</el-button>
@@ -303,39 +458,53 @@ function formatSize(bytes: number) {
</div> </div>
</section> </section>
</template> </template>
<template #footer><el-button @click="close">关闭</el-button></template>
</el-dialog> </el-dialog>
</template> </template>
<style scoped> <style scoped>
:global(.customs-documents-dialog.el-dialog) { display: flex; max-height: 70vh; flex-direction: column; overflow: hidden; padding: 0; border: 1px solid var(--client-border); border-radius: var(--client-radius); }
:global(.customs-documents-dialog .el-dialog__header) { flex: 0 0 auto; }
:global(.customs-documents-dialog .el-dialog__header) { margin: 0; padding: 18px 48px 18px 20px; border-bottom: 1px solid var(--client-border); }
:global(.customs-documents-dialog .el-dialog__title) { color: var(--client-text); font-size: 16px; font-weight: 600; line-height: 24px; }
:global(.customs-documents-dialog .el-dialog__headerbtn) { top: 8px; right: 8px; }
:global(.customs-documents-dialog .el-dialog__body) { min-height: 0; flex: 1 1 auto; overflow-y: auto; padding: 20px; color: var(--client-text); line-height: 1.6; overscroll-behavior: contain; }
.customs-error { display: grid; gap: 10px; justify-items: start; padding: 22px; border: 1px solid #f1b8b8; background: #fff7f7; color: #9f2d2d; } .customs-error { display: grid; gap: 10px; justify-items: start; padding: 22px; border: 1px solid #f1b8b8; background: #fff7f7; color: #9f2d2d; }
.customs-error span { overflow-wrap: anywhere; font-size: 12px; } .customs-error span { overflow-wrap: anywhere; font-size: 12px; }
.customs-summary { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)) auto; align-items: center; gap: 18px; padding: 16px 18px; border: 1px solid var(--border); background: #f8faf9; } .customs-summary { display: grid; grid-template-columns: minmax(0, 1.6fr) repeat(2, minmax(0, 1fr)) auto; align-items: center; gap: 18px; padding: 16px; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: var(--client-header-bg); }
.customs-summary div { min-width: 0; } .customs-summary div { min-width: 0; }
.customs-summary span { display: block; color: var(--muted); font-size: 11px; } .customs-summary > div > span { display: block; color: var(--muted); font-size: 11px; }
.customs-summary strong { display: block; margin-top: 5px; overflow-wrap: anywhere; color: var(--navy); font-size: 14px; } .customs-summary strong { display: block; margin-top: 5px; overflow-wrap: anywhere; color: var(--navy); font-size: 14px; }
.customs-locked { display: flex; align-items: flex-start; gap: 10px; margin-top: 14px; padding: 13px 15px; border: 1px solid #d5dde1; background: #f5f7f8; color: var(--muted); } .customs-locked { display: flex; align-items: flex-start; gap: 10px; margin-top: 14px; padding: 13px 15px; border: 1px solid #d5dde1; background: #f5f7f8; color: var(--muted); }
.customs-locked strong, .customs-locked span { display: block; } .customs-locked strong, .customs-locked span { display: block; }
.customs-locked strong { color: var(--navy); font-size: 12px; } .customs-locked strong { color: var(--navy); font-size: 12px; }
.customs-locked span { margin-top: 3px; font-size: 11px; } .customs-locked span { margin-top: 3px; font-size: 11px; }
.customs-section { margin-top: 18px; } .customs-section { margin-top: var(--client-section-gap); padding: 16px; border: 1px solid var(--client-border); border-radius: var(--client-radius); }
.customs-section-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 12px; } .customs-section :deep(.el-empty) { padding: 20px 0; }
.clearance-result-list { display:grid; gap:10px; }
.clearance-result-row { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:6px 14px; padding:12px 14px; border:1px solid var(--border); background:#fbfcfe; }
.clearance-result-row strong,.clearance-result-row span { display:block; }
.clearance-result-row span { margin-top:4px; color:var(--muted); font-size:11px; }
.clearance-result-row p { grid-column:1 / -1; margin:0; color:var(--navy); font-size:12px; }
.customs-section-title { display: flex; align-items: center; justify-content: space-between; gap: 18px; margin-bottom: 14px; }
.customs-section-title h3 { margin: 0; color: var(--navy); font-size: 14px; } .customs-section-title h3 { margin: 0; color: var(--navy); font-size: 14px; }
.customs-section-title p { margin: 5px 0 0; color: var(--muted); font-size: 11px; line-height: 1.55; } .customs-receipt-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.customs-inbound-options { display: flex; flex-wrap: wrap; gap: 8px 18px; padding: 13px 15px; border: 1px solid var(--border); } .customs-help-heading { display: flex; align-items: center; gap: 4px; }
.customs-inbound-options { display: flex; flex-wrap: wrap; gap: 8px 18px; padding: 12px 14px; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: var(--client-header-bg); }
.customs-inbound-options :deep(.el-checkbox) { margin-right: 0; } .customs-inbound-options :deep(.el-checkbox) { margin-right: 0; }
.customs-inbound-options :deep(.el-checkbox__label) { white-space: normal; overflow-wrap: anywhere; }
.customs-inbound-code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; } .customs-inbound-code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
.customs-inbound-options small { margin-left: 7px; color: var(--muted); } .customs-inbound-options small { margin-left: 7px; color: var(--muted); }
.customs-hidden-input { display: none; } .customs-hidden-input { display: none; }
.customs-document-list { display: grid; gap: 10px; } .customs-document-list { display: grid; gap: 10px; }
.customs-document-card { padding: 14px 16px; border: 1px solid var(--border); } .customs-document-card { padding: 14px 16px; border: 1px solid var(--client-border); border-radius: var(--client-radius); }
.customs-document-main { display: flex; align-items: flex-start; gap: 11px; min-width: 0; } .customs-document-main { display: flex; align-items: flex-start; gap: 11px; min-width: 0; }
.customs-document-main > svg { flex: 0 0 20px; color: var(--primary); } .customs-document-main > svg { flex: 0 0 20px; color: var(--primary); }
.customs-document-main > div { min-width: 0; } .customs-document-main > div { min-width: 0; }
.customs-document-main strong, .customs-document-main span, .customs-document-main small { display: block; overflow-wrap: anywhere; } .customs-document-main strong, .customs-document-main span, .customs-document-main small { display: block; overflow-wrap: anywhere; }
.customs-document-main strong { color: var(--navy); font-size: 13px; } .customs-document-main strong { color: var(--navy); font-size: 13px; line-height: 1.6; }
.customs-document-main span, .customs-document-main small { margin-top: 4px; color: var(--muted); font-size: 11px; } .customs-document-main span, .customs-document-main small { margin-top: 4px; color: var(--muted); font-size: 11px; }
.customs-document-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 2px; margin-top: 8px; } .customs-document-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; align-items: center; gap: 6px 10px; margin-top: 12px; padding-top: 10px; border-top: 1px solid var(--client-border); }
.customs-document-actions :deep(.el-button + .el-button) { margin-left: 0; }
.customs-scope-editor { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; margin-top: 12px; padding-top: 12px; border-top: 1px dashed var(--border); } .customs-scope-editor { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; margin-top: 12px; padding-top: 12px; border-top: 1px dashed var(--border); }
.customs-scope-editor :deep(.el-checkbox) { margin-right: 16px; } .customs-scope-editor :deep(.el-checkbox) { margin-right: 16px; }
</style> </style>
@@ -0,0 +1,21 @@
<script setup lang="ts">
import { Info } from '@lucide/vue'
defineProps<{ title: string }>()
</script>
<template>
<el-tooltip :trigger="['hover', 'focus']" placement="top" effect="light" :show-after="150" :hide-after="100" :enterable="true">
<template #content><div class="customs-help-content"><strong>{{ title }}</strong><slot /></div></template>
<button type="button" class="customs-help" :aria-label="`查看${title}`"><Info :size="14" aria-hidden="true" /></button>
</el-tooltip>
</template>
<style scoped>
.customs-help { display: inline-flex; width: 24px; height: 24px; flex: 0 0 24px; align-items: center; justify-content: center; margin: 0; padding: 0; border: 0; background: transparent; color: var(--muted); cursor: help; vertical-align: middle; }
.customs-help:hover,.customs-help:focus-visible { color: var(--primary); }
.customs-help:focus-visible { outline: 2px solid var(--primary); outline-offset: 2px; }
.customs-help-content { max-width: 320px; color: var(--navy); font-size: 12px; font-weight: 400; line-height: 1.6; white-space: normal; }
.customs-help-content > strong { display: block; margin-bottom: 4px; }
.customs-help-content :deep(p) { margin: 0; }
</style>
@@ -42,14 +42,24 @@ const emit = defineEmits<{
</template> </template>
<style scoped> <style scoped>
.first-leg-editor-page { min-width: 0; border: 1px solid #edf0f5; background: #fff; box-shadow: 0 5px 18px rgba(15, 31, 58, .04); } .first-leg-editor-page { min-width: 0; padding-bottom: 72px; border: 1px solid #edf0f5; background: #fff; box-shadow: 0 5px 18px rgba(15, 31, 58, .04); }
.editor-page-nav { display: flex; min-height: 52px; align-items: center; justify-content: space-between; gap: 16px; padding: 8px 24px; border-bottom: 1px solid #edf0f5; } .editor-page-nav { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 5px 16px; border-bottom: 1px solid #edf0f5; }
.editor-page-nav span { color: var(--muted); font-size: 12px; } .editor-page-nav span { color: var(--muted); font-size: 12px; }
.editor-page-body { padding: 26px 32px 34px; } .editor-page-body { padding: 16px 20px 24px; }
.editor-page-footer { position: sticky; z-index: 3; bottom: 0; display: flex; justify-content: center; padding: 12px 24px; border-top: 1px solid #edf0f5; background: rgba(255, 255, 255, 0.96); box-shadow: 0 -6px 18px rgba(15, 31, 58, .06); backdrop-filter: blur(10px); } .editor-page-footer { position: fixed; z-index: 18; right: 0; bottom: 0; left: 224px; display: flex; min-height: 68px; align-items: center; justify-content: center; padding: 10px 24px; border-top: 1px solid #dfe6ee; background: rgba(255, 255, 255, 0.97); box-shadow: 0 -6px 18px rgba(15, 31, 58, .08); backdrop-filter: blur(10px); }
.editor-page-footer :deep(.editor-actions) { width: min(100%, 900px); justify-content: center; } .editor-page-footer :deep(.editor-actions) { width: min(100%, 900px); justify-content: center; }
.editor-page-footer :deep(.editor-actions > .el-button) { min-width: 132px; min-height: 42px; } .editor-page-footer :deep(.editor-actions > .el-button) { min-width: 132px; min-height: 42px; }
.editor-page-footer :deep(.editor-actions > .el-button:last-child) { min-width: 172px; } .editor-page-footer :deep(.editor-actions > .el-button:last-child) { min-width: 172px; }
.editor-page-footer :deep(.submit-order-button) { position: relative; isolation: isolate; overflow: hidden; border-color: rgba(255, 255, 255, .24); background: linear-gradient(105deg, #08a9bd 0%, #167da2 28%, #2563eb 62%, #4338ca 100%); background-size: 220% 100%; box-shadow: 0 10px 24px rgba(23, 107, 135, .3), 0 0 0 1px rgba(34, 211, 238, .13), 0 0 26px rgba(37, 99, 235, .12); animation: submit-gradient 5s ease-in-out infinite, submit-pulse 2.8s ease-in-out infinite; }
.editor-page-footer :deep(.submit-order-button::before) { position: absolute; z-index: -1; top: -80%; bottom: -80%; left: -48%; width: 34%; transform: rotate(18deg); background: linear-gradient(90deg, transparent, rgba(255, 255, 255, .68), transparent); content: ''; animation: submit-shine 3.2s ease-in-out infinite; }
.editor-page-footer :deep(.submit-order-button::after) { position: absolute; z-index: -1; inset: 1px; border-radius: 5px; background: linear-gradient(180deg, rgba(255, 255, 255, .13), transparent 48%); content: ''; pointer-events: none; }
.editor-page-footer :deep(.submit-order-button:hover) { transform: translateY(-2px) scale(1.025); border-color: rgba(255, 255, 255, .3); background: linear-gradient(105deg, #08b8cb 0%, #167da2 28%, #2563eb 62%, #4338ca 100%); background-size: 220% 100%; box-shadow: 0 15px 30px rgba(23, 107, 135, .35), 0 0 0 1px rgba(34, 211, 238, .25), 0 0 34px rgba(37, 99, 235, .2); }
.editor-page-footer :deep(.submit-order-button svg) { position: relative; z-index: 1; filter: drop-shadow(0 2px 4px rgba(0, 0, 0, .18)); animation: submit-plane 2.6s ease-in-out infinite; }
@keyframes submit-gradient { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }
@keyframes submit-pulse { 0%, 100% { filter: saturate(1); } 50% { filter: saturate(1.12) brightness(1.04); } }
@keyframes submit-shine { 0%, 52% { left: -48%; opacity: 0; } 62% { opacity: 1; } 86%, 100% { left: 122%; opacity: 0; } }
@keyframes submit-plane { 0%, 100% { transform: translate3d(0, 1px, 0) rotate(-3deg); } 50% { transform: translate3d(3px, -2px, 0) rotate(2deg); } }
@media (prefers-reduced-motion: reduce) { .editor-page-footer :deep(.submit-order-button), .editor-page-footer :deep(.submit-order-button::before), .editor-page-footer :deep(.submit-order-button svg) { animation: none; } }
:global(.first-leg-editor-dialog.el-dialog) { display: flex; max-width: 1500px; height: 94vh; margin-bottom: 0; flex-direction: column; overflow: hidden; border-radius: 6px; } :global(.first-leg-editor-dialog.el-dialog) { display: flex; max-width: 1500px; height: 94vh; margin-bottom: 0; flex-direction: column; overflow: hidden; border-radius: 6px; }
:global(.first-leg-editor-dialog .el-dialog__header) { flex: 0 0 auto; margin-right: 0; padding: 17px 22px; border-bottom: 1px solid var(--border); } :global(.first-leg-editor-dialog .el-dialog__header) { flex: 0 0 auto; margin-right: 0; padding: 17px 22px; border-bottom: 1px solid var(--border); }
:global(.first-leg-editor-dialog .el-dialog__title) { color: var(--navy); font-size: 16px; font-weight: 700; } :global(.first-leg-editor-dialog .el-dialog__title) { color: var(--navy); font-size: 16px; font-weight: 700; }
@@ -58,10 +68,11 @@ const emit = defineEmits<{
:global(.first-leg-editor-dialog .el-dialog__footer) { flex: 0 0 auto; padding: 12px 22px; border-top: 1px solid var(--border); background: #fff; } :global(.first-leg-editor-dialog .el-dialog__footer) { flex: 0 0 auto; padding: 12px 22px; border-top: 1px solid var(--border); background: #fff; }
@media (max-width: 720px) { @media (max-width: 720px) {
.first-leg-editor-page { padding-bottom: 0; }
.editor-page-nav { align-items: flex-start; flex-direction: column; gap: 2px; padding: 10px 16px; } .editor-page-nav { align-items: flex-start; flex-direction: column; gap: 2px; padding: 10px 16px; }
.editor-page-nav span { padding-left: 1px; line-height: 1.5; } .editor-page-nav span { padding-left: 1px; line-height: 1.5; }
.editor-page-body { padding: 18px 16px 24px; } .editor-page-body { padding: 18px 16px 24px; }
.editor-page-footer { padding: 10px 16px; } .editor-page-footer { position: sticky; bottom: 0; left: auto; padding: 10px 16px; }
:global(.first-leg-editor-dialog.el-dialog) { width: calc(100vw - 24px) !important; height: 96vh; margin-top: 2vh; } :global(.first-leg-editor-dialog.el-dialog) { width: calc(100vw - 24px) !important; height: 96vh; margin-top: 2vh; }
} }
@@ -1,8 +1,39 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import test from 'node:test' import test from 'node:test'
import { compile, computed, createSSRApp, h, inject, provide } from 'vue'
import { renderToString } from 'vue/server-renderer'
import ts from 'typescript'
const source = readFileSync(new URL('./InboundBillingPanel.vue', import.meta.url), 'utf8') const source = readFileSync(new URL('./InboundBillingPanel.vue', import.meta.url), 'utf8')
const confirmationBody = source.slice(source.indexOf('<dl class="fee-dialog-summary"'), source.indexOf('<div class="fee-confirm-notice"'))
const formatterSource = readFileSync(new URL('../utils/inboundBilling.ts', import.meta.url), 'utf8')
const formatters = await import(`data:text/javascript;base64,${Buffer.from(ts.transpileModule(formatterSource, {
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
}).outputText).toString('base64')}`)
async function renderConfirmation(data) {
const app = createSSRApp({
render: compile(`<div>${confirmationBody}</div>`),
setup: () => ({ props: { data }, ...formatters }),
})
app.component('ElTable', {
props: ['data'],
setup(tableProps, { slots }) {
provide('billingRows', computed(() => tableProps.data))
return () => h('table', slots.default?.())
},
})
app.component('ElTableColumn', {
props: ['label', 'prop'],
setup(columnProps, { slots }) {
const rows = inject('billingRows')
return () => h('tr', [h('th', columnProps.label), ...rows.value.map(row =>
h('td', slots.default?.({ row }) ?? row[columnProps.prop] ?? ''))])
},
})
return renderToString(app)
}
test('renders loading, pending, isolated error, and published states', () => { test('renders loading, pending, isolated error, and published states', () => {
assert.match(source, /v-if="props\.loading"/) assert.match(source, /v-if="props\.loading"/)
@@ -20,29 +51,77 @@ test('supports a standalone dialog and keeps the unpushed billing-weight state v
assert.match(source, /watch\(\(\) => props\.autoOpen/) assert.match(source, /watch\(\(\) => props\.autoOpen/)
assert.match(source, /if \(autoOpen\) feeDialogOpen\.value = true/) assert.match(source, /if \(autoOpen\) feeDialogOpen\.value = true/)
assert.match(source, /v-else-if="props\.unavailable \|\| !props\.data"/) assert.match(source, /v-else-if="props\.unavailable \|\| !props\.data"/)
assert.match(source, /平台推送计费重后,可在这里核对并确认/) assert.match(source, /平台推送费用后,可在这里核对并确认/)
assert.match(source, /@closed="emit\('closed'\)"/) assert.match(source, /@closed="emit\('closed'\)"/)
}) })
test('shows the published merchant inbound, measurement details and customer confirmation entry', () => { test('shows the published merchant inbound, measurement details and customer confirmation entry', () => {
for (const label of ['入仓码', '平台收货仓', '实际毛重', '实测体积', '托盘与库位', '换算与精度', '最终计费量', '对客单价', '基础费用', '附加费用', '费用合计', '平台备注']) { for (const label of ['入仓码', '平台收货仓', '实际毛重', '实测体积', '换算与精度', '最终计费量', '单价', '基础费用', '附加费用', '费用合计', '平台备注']) {
assert.match(source, new RegExp(label)) assert.ok(source.includes(label), `missing label: ${label}`)
} }
assert.match(source, /formatInboundMoney\(props\.data\.latestFee\.totalAmount/) assert.match(source, /formatInboundMoney\(props\.data\.latestFee\.totalAmount/)
assert.match(source, /formatConversionPrecision\(/) assert.match(source, /formatConversionPrecision\(/)
assert.match(source, /确认费用/) assert.match(source, /title="确认计费重"/)
assert.match(source, /二次确认费用/) assert.match(source, /确认后当前费用版本将锁定/)
assert.match(source, /确认后该费用将锁定,平台不能再修改/)
assert.match(source, /customerConfirmationStatus === 'CONFIRMED'/) assert.match(source, /customerConfirmationStatus === 'CONFIRMED'/)
assert.match(source, /confirmMerchantInboundFee/) assert.match(source, /confirmMerchantInboundFee/)
assert.match(source, /measurementItems/) assert.match(source, /measurementItems/)
assert.doesNotMatch(source, /调整费用|发送费用|下载照片/) assert.doesNotMatch(source, /调整费用|发送费用|下载照片/)
assert.doesNotMatch(source, /internalNotes|statusHistory|files/) assert.doesNotMatch(source, /internalNotes|statusHistory|files|palletLocations|托盘与库位/)
assert.match(source, /latestFee\.ruleCode/) assert.doesNotMatch(source, /latestFee\.(feeVersion|ruleCode|rateCode|chargeRuleVersion|carrierRateVersion|sentAt)/)
assert.match(source, /latestFee\.rateCode/) assert.match(source, /箱规规则/)
assert.match(source, /latestFee\.chargeRuleVersion/) assert.match(source, /getCalculationRuleLabel\(row\.calculationRuleVersion\)/)
assert.match(source, /latestFee\.carrierRateVersion/) })
assert.doesNotMatch(source, /箱规规则|calculationRuleVersion/)
test('keeps the billing summary, confirmation table, notice and footer', () => {
assert.match(source, /width="min\(1180px, calc\(100vw - 40px\)\)"/)
assert.match(source, /class="fee-dialog-summary" aria-label="计费汇总"/)
for (const label of ['计算重', '单价', '总金额', '计费毛重', '计费体积', '计费方式', '最终计费量']) assert.ok(confirmationBody.includes(label), `missing billing label: ${label}`)
assert.match(source, /class="fee-confirm-notice"/)
assert.match(source, /请核对计费毛重、计费体积、计费量、单价和总金额。确认后当前费用版本将锁定。/)
assert.match(source, /确认计费量和费用/)
assert.match(source, /\.fee-dialog-summary \{ display:grid; grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/)
assert.match(source, /\.fee-dialog-table :deep\(\.el-table__body td\.el-table__cell\)/)
})
test('confirms the selected billing weight and volume even when outer carton totals differ', async () => {
const html = await renderConfirmation({
latestFee: {
actualWeightKg: 393, actualVolumeCbm: 3.6894, convertedQuantity: 616.1298,
chargeableQuantity: 616.1298, chargeMode: 'KG', chargeUnit: 'KG',
unitPrice: 13.6, totalAmount: 8379.37, currency: 'CNY',
},
billingBasis: { chargeableWeightKg: 650.298 },
measurementItems: [{ lengthCm: 63, widthCm: 53, heightCm: 53, packageCount: 22,
unitVolumeCbm: 0.177, totalVolumeCbm: 3.894, volumeWeightKg: 650.298 }],
})
assert.match(html, /393 kg/)
assert.match(html, /3\.6894 m³/)
assert.match(html, /616\.13 kg/)
assert.match(html, /8,379\.37/)
assert.match(html, /按体积重计费/)
assert.doesNotMatch(html, /按重量计费|按毛重计费/)
assert.doesNotMatch(html, /3\.894|650\.298|0\.177/)
assert.doesNotMatch(confirmationBody, /measurementItems|billingBasis|箱规长|每箱体积/)
})
test('uses the published volume charge quantity and retains six decimal places', async () => {
const html = await renderConfirmation({
latestFee: {
actualWeightKg: 600, actualVolumeCbm: 1.234567, convertedQuantity: 1.652893,
chargeableQuantity: 1.652893, chargeMode: 'CBM', chargeUnit: 'CBM',
unitPrice: 100, totalAmount: 165.29, currency: 'CNY',
},
billingBasis: { chargeableWeightKg: 600 }, measurementItems: [],
})
assert.match(html, /计费量/)
assert.match(html, /按重量折算体积计费/)
assert.match(html, /600 kg/)
assert.match(html, /1\.234567 m³/)
assert.match(html, /1\.652893 m³/)
assert.doesNotMatch(html, /1\.652893 kg/)
}) })
test('stacks core information for 720 and 360 pixel layouts', () => { test('stacks core information for 720 and 360 pixel layouts', () => {
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from 'vue' import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage } from 'element-plus'
import { Clock3, PackageCheck, RefreshCw, TriangleAlert } from '@lucide/vue' import { CircleAlert, Clock3, RefreshCw, TriangleAlert } from '@lucide/vue'
import { confirmMerchantInboundFee } from '@/modules/first-leg/api/inboundBilling' import { confirmMerchantInboundFee } from '@/modules/first-leg/api/inboundBilling'
import type { MerchantInboundBilling } from '@/modules/first-leg/types/inboundBilling' import type { MerchantInboundBilling } from '@/modules/first-leg/types/inboundBilling'
import { import {
@@ -10,6 +10,7 @@ import {
formatInboundMeasure, formatInboundMeasure,
formatInboundMoney, formatInboundMoney,
formatInboundNumber, formatInboundNumber,
getCalculationRuleLabel,
getChargeModeLabel, getChargeModeLabel,
getTaxModeLabel, getTaxModeLabel,
} from '@/modules/first-leg/utils/inboundBilling' } from '@/modules/first-leg/utils/inboundBilling'
@@ -54,15 +55,6 @@ async function confirmFee() {
ElMessage.info('当前费用已经确认,无需重复操作') ElMessage.info('当前费用已经确认,无需重复操作')
return return
} }
try {
await ElMessageBox.confirm(
`请再次确认费用单 ${fee.feeNo},合计 ${formatInboundMoney(fee.totalAmount, fee.currency)}。确认后该费用将锁定,平台不能再修改。`,
'二次确认费用',
{ type: 'warning', confirmButtonText: '确认费用无误', cancelButtonText: '返回核对' },
)
} catch {
return
}
confirming.value = true confirming.value = true
try { try {
await confirmMerchantInboundFee(orderId, fee.feeVersion) await confirmMerchantInboundFee(orderId, fee.feeVersion)
@@ -85,7 +77,7 @@ async function confirmFee() {
<el-tag :type="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' ? 'success' : 'warning'" effect="light"> <el-tag :type="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' ? 'success' : 'warning'" effect="light">
{{ props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' ? '客户已确认 · 费用已锁定' : '费用已发布 · 待确认' }} {{ props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' ? '客户已确认 · 费用已锁定' : '费用已发布 · 待确认' }}
</el-tag> </el-tag>
<el-button v-if="props.data.latestFee.customerConfirmationStatus !== 'CONFIRMED' && props.canConfirm" type="primary" @click="feeDialogOpen = true">确认费用</el-button> <el-button v-if="props.data.latestFee.customerConfirmationStatus !== 'CONFIRMED' && props.canConfirm" type="primary" @click="feeDialogOpen = true">确认计费重</el-button>
<el-button v-else plain @click="feeDialogOpen = true">查看费用</el-button> <el-button v-else plain @click="feeDialogOpen = true">查看费用</el-button>
</div> </div>
</header> </header>
@@ -139,38 +131,18 @@ async function confirmFee() {
<el-table-column label="每箱体积" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.unitVolumeCbm, 'm³') }}</template></el-table-column> <el-table-column label="每箱体积" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.unitVolumeCbm, 'm³') }}</template></el-table-column>
<el-table-column label="总体积" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.totalVolumeCbm, 'm³') }}</template></el-table-column> <el-table-column label="总体积" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.totalVolumeCbm, 'm³') }}</template></el-table-column>
<el-table-column label="总材积重" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.volumeWeightKg, 'kg') }}</template></el-table-column> <el-table-column label="总材积重" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.volumeWeightKg, 'kg') }}</template></el-table-column>
<el-table-column label="箱规规则" min-width="170"><template #default="{ row }">{{ getCalculationRuleLabel(row.calculationRuleVersion) }}</template></el-table-column>
<el-table-column prop="boxSpecification" label="备注" min-width="130" /> <el-table-column prop="boxSpecification" label="备注" min-width="130" />
</el-table> </el-table>
</div> </div>
<div class="inbound-result-section">
<div class="inbound-section-title">
<h4>托盘与库位</h4>
<span>{{ props.data.inbound.palletLocations.length }} 个托盘</span>
</div>
<div v-if="props.data.inbound.palletLocations.length" class="pallet-location-list">
<article v-for="item in props.data.inbound.palletLocations" :key="`${item.palletId}-${item.locationId}`">
<PackageCheck :size="18" />
<div class="pallet-location-main">
<strong>{{ item.palletCode }}</strong>
<span>库位 {{ item.locationCode }}</span>
</div>
<div class="pallet-location-quantity">
<span>{{ formatInboundMeasure(item.allocatedVolumeCbm, 'm³') }}</span>
<span>{{ formatInboundNumber(item.allocatedPackageCount, 0) }} 箱</span>
</div>
</article>
</div>
<p v-else class="inbound-inline-empty">暂无托盘和库位明细</p>
</div>
<div class="inbound-result-section fee-result"> <div class="inbound-result-section fee-result">
<div class="inbound-section-title"> <div class="inbound-section-title">
<h4>费用结果</h4> <h4>费用结果</h4>
<span>{{ props.data.latestFee.feeNo }} · 第 {{ props.data.latestFee.feeVersion }} 版</span> <span>{{ props.data.latestFee.feeNo }}</span>
</div> </div>
<dl class="fee-calculation-grid"> <dl class="fee-calculation-grid">
<div><dt>计费方式</dt><dd>{{ getChargeModeLabel(props.data.latestFee.chargeMode) }} · {{ getTaxModeLabel(props.data.latestFee.taxMode) }}</dd></div> <div><dt>计费方式</dt><dd>{{ getChargeModeLabel(props.data.latestFee.chargeMode, props.data.latestFee.actualWeightKg, props.data.latestFee.actualVolumeCbm, props.data.latestFee.convertedQuantity) }} · {{ getTaxModeLabel(props.data.latestFee.taxMode) }}</dd></div>
<div> <div>
<dt>换算与精度</dt> <dt>换算与精度</dt>
<dd>{{ formatConversionPrecision( <dd>{{ formatConversionPrecision(
@@ -179,8 +151,8 @@ async function confirmFee() {
props.data.latestFee.roundingMode, props.data.latestFee.roundingMode,
) }}</dd> ) }}</dd>
</div> </div>
<div><dt>实际重量</dt><dd>{{ formatInboundMeasure(props.data.latestFee.actualWeightKg, 'kg') }}</dd></div> <div><dt>计费毛重</dt><dd>{{ formatInboundMeasure(props.data.latestFee.actualWeightKg, 'kg') }}</dd></div>
<div><dt>实际体积</dt><dd>{{ formatInboundMeasure(props.data.latestFee.actualVolumeCbm, 'm³') }}</dd></div> <div><dt>计费体积</dt><dd>{{ formatInboundMeasure(props.data.latestFee.actualVolumeCbm, 'm³', 6) }}</dd></div>
<div><dt>体积重量</dt><dd>{{ formatInboundMeasure(props.data.latestFee.convertedQuantity, props.data.latestFee.chargeUnit) }}</dd></div> <div><dt>体积重量</dt><dd>{{ formatInboundMeasure(props.data.latestFee.convertedQuantity, props.data.latestFee.chargeUnit) }}</dd></div>
<div><dt>最终计费量</dt><dd>{{ formatInboundMeasure(props.data.latestFee.chargeableQuantity, props.data.latestFee.chargeUnit) }}</dd></div> <div><dt>最终计费量</dt><dd>{{ formatInboundMeasure(props.data.latestFee.chargeableQuantity, props.data.latestFee.chargeUnit) }}</dd></div>
<div><dt>单价</dt><dd>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit }}</dd></div> <div><dt>单价</dt><dd>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit }}</dd></div>
@@ -190,11 +162,9 @@ async function confirmFee() {
<div class="fee-total"> <div class="fee-total">
<div> <div>
<span>费用合计</span> <span>费用合计</span>
<small>{{ props.data.latestFee.ruleCode }} v{{ props.data.latestFee.chargeRuleVersion }} · {{ props.data.latestFee.rateCode }} v{{ props.data.latestFee.carrierRateVersion }}</small>
</div> </div>
<strong>{{ formatInboundMoney(props.data.latestFee.totalAmount, props.data.latestFee.currency) }}</strong> <strong>{{ formatInboundMoney(props.data.latestFee.totalAmount, props.data.latestFee.currency) }}</strong>
</div> </div>
<p class="fee-sent-time">发布于 {{ formatInboundDateTime(props.data.latestFee.sentAt) }}</p>
</div> </div>
<div v-if="props.data.inbound.publicRemark" class="inbound-public-remark"> <div v-if="props.data.inbound.publicRemark" class="inbound-public-remark">
@@ -205,53 +175,37 @@ async function confirmFee() {
</section> </section>
<el-dialog v-model="feeDialogOpen" title="确认测量与计费数据" width="min(980px, 94vw)" append-to-body @closed="emit('closed')"> <el-dialog v-model="feeDialogOpen" class="billing-confirm-dialog" title="确认计费重" width="min(1180px, calc(100vw - 40px))" append-to-body @closed="emit('closed')">
<div v-if="props.loading" class="inbound-billing-loading" aria-live="polite" aria-busy="true"> <div v-if="props.loading" class="inbound-billing-loading" aria-live="polite" aria-busy="true">
<el-skeleton :rows="4" animated /> <el-skeleton :rows="4" animated />
<span class="sr-only">正在加载计费重</span> <span class="sr-only">正在加载费用</span>
</div> </div>
<div v-else-if="props.error" class="inbound-billing-state is-error" role="alert"> <div v-else-if="props.error" class="inbound-billing-state is-error" role="alert">
<TriangleAlert :size="22" /> <TriangleAlert :size="22" />
<div><strong>计费重加载失败</strong><span>{{ props.error }}</span></div> <div><strong>费用加载失败</strong><span>{{ props.error }}</span></div>
<el-button @click="$emit('retry')"><RefreshCw :size="15" />重新加载</el-button> <el-button @click="$emit('retry')"><RefreshCw :size="15" />重新加载</el-button>
</div> </div>
<div v-else-if="props.unavailable || !props.data" class="inbound-billing-state is-pending" role="status"> <div v-else-if="props.unavailable || !props.data" class="inbound-billing-state is-pending" role="status">
<Clock3 :size="22" /> <Clock3 :size="22" />
<div><strong>{{ props.unavailableMessage }}</strong><span>平台推送计费重后,可在这里核对并确认。</span></div> <div><strong>{{ props.unavailableMessage }}</strong><span>平台推送费用后,可在这里核对并确认。</span></div>
</div> </div>
<template v-else> <template v-else>
<dl class="inbound-measurements fee-dialog-summary"> <dl class="fee-dialog-summary" aria-label="计费汇总">
<div><dt>计费总箱数</dt><dd>{{ formatInboundNumber(props.data.measurementSummary.actualPackageCount, 0) }}</dd></div> <div><dt>{{ props.data.latestFee.chargeUnit === 'KG' ? '计算重' : '计费量' }}</dt><dd>{{ formatInboundMeasure(props.data.latestFee.chargeableQuantity, props.data.latestFee.chargeUnit === 'KG' ? 'kg' : 'm³', props.data.latestFee.chargeUnit === 'KG' ? 3 : 6) }}</dd></div>
<div><dt>计费总毛重</dt><dd>{{ formatInboundMeasure(props.data.measurementSummary.actualGrossWeightKg, 'kg') }}</dd></div> <div><dt>单价</dt><dd>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit.toUpperCase() }}</dd></div>
<div><dt>外箱规总体积</dt><dd>{{ formatInboundMeasure(props.data.measurementSummary.actualVolumeCbm, 'm³') }}</dd></div> <div><dt>总金额</dt><dd>{{ formatInboundMoney(props.data.latestFee.totalAmount, props.data.latestFee.currency) }}</dd></div>
<div><dt>外箱规总材积重</dt><dd>{{ formatInboundMeasure(props.data.measurementSummary.volumeWeightKg, 'kg') }}</dd></div>
<div><dt>计费体积</dt><dd>{{ formatInboundMeasure(props.data.billingBasis.chargeableVolumeCbm, 'm³') }}</dd></div>
<div><dt>计费重量</dt><dd>{{ formatInboundMeasure(props.data.billingBasis.chargeableWeightKg, 'kg') }}</dd></div>
<div><dt>对客单价</dt><dd>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit }}</dd></div>
<div><dt>基础费用</dt><dd>{{ formatInboundMoney(props.data.latestFee.subtotalAmount, props.data.latestFee.currency) }}</dd></div>
<div><dt>附加费用</dt><dd>{{ formatInboundMoney(props.data.latestFee.additionalAmount, props.data.latestFee.currency) }}</dd></div>
<div><dt>费用合计</dt><dd>{{ formatInboundMoney(props.data.latestFee.totalAmount, props.data.latestFee.currency) }}</dd></div>
</dl> </dl>
<el-table v-if="props.data?.measurementItems.length" class="measurement-detail-table" :data="props.data.measurementItems" border size="small"> <el-table class="measurement-detail-table fee-dialog-table" :data="[props.data.latestFee]" border>
<el-table-column type="index" label="#" width="54" /> <el-table-column label="计费毛重" min-width="180"><template #default="{ row }">{{ formatInboundMeasure(row.actualWeightKg, 'kg') }}</template></el-table-column>
<el-table-column prop="lengthCm" label="箱规长(cm)" min-width="105" /> <el-table-column label="计费体积" min-width="180"><template #default="{ row }">{{ formatInboundMeasure(row.actualVolumeCbm, 'm³', 6) }}</template></el-table-column>
<el-table-column prop="widthCm" label="箱规宽(cm)" min-width="105" /> <el-table-column label="计费方式" min-width="150"><template #default="{ row }">{{ getChargeModeLabel(row.chargeMode, row.actualWeightKg, row.actualVolumeCbm, row.convertedQuantity) }}</template></el-table-column>
<el-table-column prop="heightCm" label="箱规高(cm)" min-width="105" /> <el-table-column label="最终计费量" min-width="180"><template #default="{ row }">{{ formatInboundMeasure(row.chargeableQuantity, row.chargeUnit === 'KG' ? 'kg' : 'm³', row.chargeUnit === 'KG' ? 3 : 6) }}</template></el-table-column>
<el-table-column prop="packageCount" label="箱数" min-width="76" />
<el-table-column label="每箱体积" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.unitVolumeCbm, 'm³') }}</template></el-table-column>
<el-table-column label="总体积" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.totalVolumeCbm, 'm³') }}</template></el-table-column>
<el-table-column label="总材积重" min-width="105"><template #default="{ row }">{{ formatInboundMeasure(row.volumeWeightKg, 'kg') }}</template></el-table-column>
<el-table-column prop="boxSpecification" label="备注" min-width="130" />
</el-table> </el-table>
<el-alert <div class="fee-confirm-notice" :class="{ 'is-confirmed': props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' }" role="status">
v-if="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED'" <CircleAlert :size="21" aria-hidden="true" />
class="fee-confirmed-alert" <span v-if="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED'">客户已于 {{ formatInboundDateTime(props.data.latestFee.customerConfirmedAt) }} 确认,费用已锁定,不允许修改。</span>
:title="`客户已于 ${formatInboundDateTime(props.data.latestFee.customerConfirmedAt)} 确认,费用已锁定,不允许修改。`" <span v-else>请核对计费毛重、计费体积、计费量、单价和总金额。确认后当前费用版本将锁定。</span>
type="success" </div>
:closable="false"
show-icon
/>
<el-alert v-else class="fee-confirmed-alert" title="请核对计费量、对客单价和费用合计。确认后当前费用版本将锁定。" type="warning" :closable="false" show-icon />
</template> </template>
<template #footer> <template #footer>
<el-button @click="feeDialogOpen = false">关闭</el-button> <el-button @click="feeDialogOpen = false">关闭</el-button>
@@ -261,15 +215,15 @@ async function confirmFee() {
</template> </template>
<style scoped> <style scoped>
.inbound-billing-panel { margin-top: 22px; } .inbound-billing-panel { margin-top: 14px; }
.inbound-billing-heading, .inbound-section-title, .fee-total { display: flex; align-items: center; justify-content: space-between; gap: 12px; } .inbound-billing-heading, .inbound-section-title, .fee-total { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.inbound-billing-actions { display: flex; align-items: center; gap: 10px; } .inbound-billing-actions { display: flex; align-items: center; gap: 10px; }
.inbound-billing-heading h3, .inbound-result-section h4 { margin: 0; color: var(--navy); } .inbound-billing-heading h3, .inbound-result-section h4 { margin: 0; color: var(--navy); }
.inbound-billing-heading h3 { font-size: 15px; } .inbound-billing-heading h3 { font-size: 13px; }
.inbound-result-section h4 { font-size: 13px; } .inbound-result-section h4 { font-size: 13px; }
.inbound-billing-loading { min-height: 180px; padding: 18px 0; } .inbound-billing-loading { min-height: 180px; padding: 18px 0; }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } .sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.inbound-billing-state { display: grid; min-height: 112px; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 13px; margin-top: 12px; padding: 18px; border: 1px dashed #cbd5da; } .inbound-billing-state { display: grid; min-height: 48px; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; margin-top: 8px; padding: 8px 10px; border: 1px dashed #cbd5da; }
.inbound-billing-state > svg { color: var(--primary); } .inbound-billing-state > svg { color: var(--primary); }
.inbound-billing-state > div { display: flex; min-width: 0; flex-direction: column; gap: 4px; } .inbound-billing-state > div { display: flex; min-width: 0; flex-direction: column; gap: 4px; }
.inbound-billing-state strong { color: var(--navy); font-size: 13px; } .inbound-billing-state strong { color: var(--navy); font-size: 13px; }
@@ -287,16 +241,25 @@ async function confirmFee() {
.inbound-measurements { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 10px 0 0; background: #f6f8f8; } .inbound-measurements { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 10px 0 0; background: #f6f8f8; }
.inbound-measurements > div { min-width: 0; padding: 12px; } .inbound-measurements > div { min-width: 0; padding: 12px; }
.measurement-detail-table { margin-top: 12px; } .measurement-detail-table { margin-top: 12px; }
.fee-dialog-summary { margin-top: 0; } .fee-dialog-summary { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; margin:0; }
.fee-confirmed-alert { margin-top: 14px; } .fee-dialog-summary > div { position:relative; min-width:0; overflow:hidden; padding:13px 17px; border:1px solid #e4e8f2; border-radius:11px; background:linear-gradient(145deg,#fff,#f8f9fc); box-shadow:0 5px 16px rgba(51,65,85,.04); }
.pallet-location-list { margin-top: 9px; border-top: 1px solid var(--border); } .fee-dialog-summary > div::before { position:absolute; inset:0 auto 0 0; width:4px; background:#a7b4ef; content:''; }
.pallet-location-list article { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding: 12px 0; border-bottom: 1px solid var(--border); } .fee-dialog-summary > div:nth-child(2)::before { background:#7d91eb; }
.pallet-location-list article > svg { color: var(--primary); } .fee-dialog-summary > div:nth-child(3) { border-color:#cdd7ff; background:linear-gradient(145deg,#f8faff,#eef2ff); box-shadow:0 8px 22px rgba(82,110,232,.09); }
.pallet-location-main, .pallet-location-quantity { display: flex; min-width: 0; flex-direction: column; gap: 3px; } .fee-dialog-summary > div:nth-child(3)::before { background:#526ee8; }
.pallet-location-main strong { overflow-wrap: anywhere; color: var(--navy); font-size: 12px; } .fee-dialog-summary dt { margin:0 0 3px; color:#7b8494; font-size:13px; font-weight:500; }
.pallet-location-main span, .pallet-location-quantity span { color: var(--muted); font-size: 10px; } .fee-dialog-summary dd { margin:0; overflow-wrap:anywhere; color:#283246; font-size:20px; font-weight:700; font-variant-numeric:tabular-nums; letter-spacing:0; }
.pallet-location-quantity { align-items: flex-end; } .fee-dialog-summary > div:nth-child(3) dt { color:#6578c5; }
.inbound-inline-empty { margin: 9px 0 0; padding: 14px; background: #f6f8f8; color: var(--muted); font-size: 11px; text-align: center; } .fee-dialog-summary > div:nth-child(3) dd { color:#405fd8; font-size:22px; }
.fee-dialog-table { margin-top:16px; overflow:hidden; border-radius:10px; box-shadow:0 5px 18px rgba(51,65,85,.04); }
.fee-dialog-table :deep(.el-table__header th.el-table__cell) { height:42px; padding:9px 0; background:linear-gradient(180deg,#f8f9fc,#f3f5f9); color:#697386; font-size:13px; font-weight:650; }
.fee-dialog-table :deep(.el-table__body td.el-table__cell) { height:82px; padding:9px 0; color:#515a6c; font-size:14px; font-variant-numeric:tabular-nums; }
.fee-dialog-table :deep(.el-table__body td:nth-child(2)), .fee-dialog-table :deep(.el-table__body td:nth-child(4)) { color:#34466b; font-weight:650; }
.fee-dialog-table :deep(.cell) { line-height:1.6; }
.fee-confirm-notice { display:flex; align-items:center; gap:10px; margin-top:14px; padding:10px 14px; border:1px solid #f5dfba; border-radius:9px; background:linear-gradient(90deg,#fff9ef,#fffaf2); color:#c6790c; font-size:14px; font-weight:500; }
.fee-confirm-notice > svg { flex:0 0 auto; fill:#eda332; color:#fff; filter:drop-shadow(0 2px 3px rgba(233,154,37,.25)); }
.fee-confirm-notice.is-confirmed { border-color:#b7dfc2; background:#f1faf3; color:#2d8a46; }
.fee-confirm-notice.is-confirmed > svg { fill:#4eae67; }
.fee-result { padding-top: 18px; border-top: 1px solid var(--border); } .fee-result { padding-top: 18px; border-top: 1px solid var(--border); }
.fee-calculation-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 10px 0 0; border: 1px solid var(--border); } .fee-calculation-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 10px 0 0; border: 1px solid var(--border); }
.fee-calculation-grid > div { min-width: 0; padding: 11px 12px; border-bottom: 1px solid var(--border); } .fee-calculation-grid > div { min-width: 0; padding: 11px 12px; border-bottom: 1px solid var(--border); }
@@ -305,27 +268,41 @@ async function confirmFee() {
.fee-total { padding: 15px 0 0; } .fee-total { padding: 15px 0 0; }
.fee-total > div { display: flex; min-width: 0; flex-direction: column; gap: 4px; } .fee-total > div { display: flex; min-width: 0; flex-direction: column; gap: 4px; }
.fee-total span { color: var(--navy); font-size: 12px; font-weight: 650; } .fee-total span { color: var(--navy); font-size: 12px; font-weight: 650; }
.fee-total small, .fee-sent-time { color: var(--muted); font-size: 10px; }
.fee-total strong { flex: 0 0 auto; color: var(--primary); font-size: 21px; } .fee-total strong { flex: 0 0 auto; color: var(--primary); font-size: 21px; }
.fee-sent-time { margin: 5px 0 0; text-align: right; }
.inbound-public-remark { margin-top: 16px; padding: 13px 14px; background: #f2f7f6; } .inbound-public-remark { margin-top: 16px; padding: 13px 14px; background: #f2f7f6; }
.inbound-public-remark strong { color: var(--navy); font-size: 11px; } .inbound-public-remark strong { color: var(--navy); font-size: 11px; }
.inbound-public-remark p { margin: 5px 0 0; overflow-wrap: anywhere; color: var(--muted); font-size: 11px; line-height: 1.55; white-space: pre-wrap; } .inbound-public-remark p { margin: 5px 0 0; overflow-wrap: anywhere; color: var(--muted); font-size: 11px; line-height: 1.55; white-space: pre-wrap; }
:global(.billing-confirm-dialog) { max-height:calc(100vh - 40px); overflow:hidden; border-radius:14px; box-shadow:0 28px 90px rgba(17,24,39,.33); }
:global(.billing-confirm-dialog .el-dialog__header) { display:flex; align-items:center; min-height:66px; margin:0; padding:16px 22px 14px; border-bottom:1px solid #edf0f5; }
:global(.billing-confirm-dialog .el-dialog__title) { color:#252b38; font-size:22px; font-weight:700; line-height:1.4; letter-spacing:0; }
:global(.billing-confirm-dialog .el-dialog__headerbtn) { top:14px; right:20px; width:36px; height:36px; border-radius:50%; background:#f5f6f9; }
:global(.billing-confirm-dialog .el-dialog__headerbtn:hover) { background:#e9edfa; }
:global(.billing-confirm-dialog .el-dialog__headerbtn .el-dialog__close) { color:#8b92a0; font-size:22px; }
:global(.billing-confirm-dialog .el-dialog__body) { max-height:calc(100vh - 174px); overflow:auto; padding:18px 22px; }
:global(.billing-confirm-dialog .el-dialog__footer) { padding:14px 22px 16px; border-top:1px solid #edf0f5; }
:global(.billing-confirm-dialog .el-dialog__footer .el-button) { min-height:40px; padding:0 20px; border-radius:8px; font-size:14px; font-weight:650; }
:global(.billing-confirm-dialog .el-dialog__footer .el-button--primary) { min-width:168px; border-color:#526ee8; background:linear-gradient(135deg,#647fec,#526ee8); box-shadow:0 7px 16px rgba(82,110,232,.17); }
@media (max-width: 720px) { @media (max-width: 720px) {
.fee-dialog-summary { grid-template-columns: 1fr; gap: 8px; }
.fee-dialog-summary dd, .fee-dialog-summary > div:nth-child(3) dd { font-size: 18px; }
:global(.billing-confirm-dialog) { width:calc(100vw - 16px) !important; max-height:calc(100vh - 16px); }
:global(.billing-confirm-dialog .el-dialog__header) { padding:14px 16px 11px; }
:global(.billing-confirm-dialog .el-dialog__title) { font-size:19px; }
:global(.billing-confirm-dialog .el-dialog__body) { max-height:calc(100vh - 145px); padding:14px 16px; }
:global(.billing-confirm-dialog .el-dialog__footer) { padding:12px 16px; }
:global(.billing-confirm-dialog .el-dialog__footer .el-button) { min-height:38px; padding:0 14px; font-size:13px; }
.inbound-billing-state { grid-template-columns: auto minmax(0, 1fr); } .inbound-billing-state { grid-template-columns: auto minmax(0, 1fr); }
.inbound-billing-state .el-button { grid-column: 1 / -1; width: 100%; min-height: 44px; } .inbound-billing-state .el-button { grid-column: 1 / -1; width: 100%; min-height: 44px; }
.inbound-overview, .inbound-measurements, .fee-calculation-grid { grid-template-columns: 1fr; } .inbound-overview, .inbound-measurements, .fee-calculation-grid { grid-template-columns: 1fr; }
.inbound-overview > div, .inbound-overview > div:nth-child(odd), .fee-calculation-grid > div, .fee-calculation-grid > div:not(:nth-child(3n)) { border-right: 0; border-bottom: 1px solid var(--border); } .inbound-overview > div, .inbound-overview > div:nth-child(odd), .fee-calculation-grid > div, .fee-calculation-grid > div:not(:nth-child(3n)) { border-right: 0; border-bottom: 1px solid var(--border); }
.inbound-overview > div:last-child, .fee-calculation-grid > div:last-child { border-bottom: 0; } .inbound-overview > div:last-child, .fee-calculation-grid > div:last-child { border-bottom: 0; }
.pallet-location-list article { grid-template-columns: auto minmax(0, 1fr); }
.pallet-location-quantity { grid-column: 2; align-items: flex-start; flex-direction: row; flex-wrap: wrap; gap: 8px; }
} }
@media (max-width: 360px) { @media (max-width: 360px) {
.inbound-billing-heading { align-items: flex-start; flex-direction: column; } .inbound-billing-heading { align-items: flex-start; flex-direction: column; }
.fee-total { align-items: flex-start; flex-direction: column; } .fee-total { align-items: flex-start; flex-direction: column; }
.fee-total strong { font-size: 19px; } .fee-total strong { font-size: 19px; }
.fee-sent-time { text-align: left; }
} }
</style> </style>
@@ -6,6 +6,8 @@ const source = readFileSync(new URL('./InboundCodeAssociationDialog.vue', import
test('loads only the customer-scoped server association and fails closed', () => { test('loads only the customer-scoped server association and fails closed', () => {
assert.match(source, /getMerchantInboundCodeAssociation\(inboundCode\)/) assert.match(source, /getMerchantInboundCodeAssociation\(inboundCode\)/)
assert.match(source, /getFirstLegStatusLabel\(association\.orderStatus\)/)
assert.doesNotMatch(source, /FIRST_LEG_ORDER_STATUSES/)
assert.match(source, /association\.value = null/) assert.match(source, /association\.value = null/)
assert.match(source, /关联摘要加载失败/) assert.match(source, /关联摘要加载失败/)
assert.match(source, /@click="loadAssociation"/) assert.match(source, /@click="loadAssociation"/)
@@ -13,11 +15,11 @@ test('loads only the customer-scoped server association and fails closed', () =>
}) })
test('renders business identifiers and names without internal long identifiers', () => { test('renders business identifiers and names without internal long identifiers', () => {
for (const label of ['入仓码', '订单号', '订单状态', '客户名称', '目的国家', '目的仓']) { for (const label of ['入仓码', '订单状态', '客户名称', '目的国家', '目的仓']) {
assert.match(source, new RegExp(label)) assert.match(source, new RegExp(label))
} }
assert.match(source, /association\.inboundCode/) assert.match(source, /association\.inboundCode/)
assert.match(source, /association\.orderNo/) assert.doesNotMatch(source, /association\.orderNo/)
assert.match(source, /association\.customerName/) assert.match(source, /association\.customerName/)
assert.match(source, /destinationWarehouseCode/) assert.match(source, /destinationWarehouseCode/)
assert.match(source, /destinationWarehouseName/) assert.match(source, /destinationWarehouseName/)
@@ -1,11 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue' import { computed, ref, watch } from 'vue'
import { AlertTriangle, Link2, RefreshCw } from '@lucide/vue' import { AlertTriangle, Link2, RefreshCw } from '@lucide/vue'
import { FIRST_LEG_ORDER_STATUSES } from '@chongchong/shared'
import { import {
getMerchantInboundCodeAssociation, getMerchantInboundCodeAssociation,
type MerchantInboundCodeAssociation, type MerchantInboundCodeAssociation,
} from '@/modules/first-leg/api/inboundCodeAssociations' } from '@/modules/first-leg/api/inboundCodeAssociations'
import { getFirstLegStatusLabel } from '@/modules/first-leg/utils/firstLegOrder'
const props = defineProps<{ const props = defineProps<{
modelValue: boolean modelValue: boolean
@@ -30,10 +30,6 @@ function displayValue(value: string | null | undefined) {
return value?.trim() || '—' return value?.trim() || '—'
} }
function statusLabel(value: string) {
return FIRST_LEG_ORDER_STATUSES.find((item) => item.code === value)?.label ?? displayValue(value)
}
function destinationLabel(value: MerchantInboundCodeAssociation) { function destinationLabel(value: MerchantInboundCodeAssociation) {
return [value.destinationWarehouseCode, value.destinationWarehouseName].filter(Boolean).join(' · ') || '—' return [value.destinationWarehouseCode, value.destinationWarehouseName].filter(Boolean).join(' · ') || '—'
} }
@@ -86,8 +82,7 @@ watch(() => [props.modelValue, props.inboundCode] as const, ([open]) => {
<div><span>入仓码</span><strong>{{ displayValue(association.inboundCode) }}</strong></div> <div><span>入仓码</span><strong>{{ displayValue(association.inboundCode) }}</strong></div>
</header> </header>
<dl class="inbound-association-grid"> <dl class="inbound-association-grid">
<div><dt>订单号</dt><dd>{{ displayValue(association.orderNo) }}</dd></div> <div><dt>订单状态</dt><dd>{{ getFirstLegStatusLabel(association.orderStatus) }}</dd></div>
<div><dt>订单状态</dt><dd>{{ statusLabel(association.orderStatus) }}</dd></div>
<div><dt>客户名称</dt><dd>{{ displayValue(association.customerName) }}</dd></div> <div><dt>客户名称</dt><dd>{{ displayValue(association.customerName) }}</dd></div>
<div><dt>目的国家</dt><dd>{{ displayValue(association.destinationCountryCode) }}</dd></div> <div><dt>目的国家</dt><dd>{{ displayValue(association.destinationCountryCode) }}</dd></div>
<div class="is-wide"><dt>目的仓</dt><dd>{{ destinationLabel(association) }}</dd></div> <div class="is-wide"><dt>目的仓</dt><dd>{{ destinationLabel(association) }}</dd></div>
@@ -5,8 +5,6 @@ import type { FirstLegOrder } from '@/modules/first-leg/types/firstLegOrder'
import { import {
FIRST_LEG_PROGRESS_STAGES, FIRST_LEG_PROGRESS_STAGES,
getFirstLegProgressIndex, getFirstLegProgressIndex,
getFirstLegStatusLabel,
getFirstLegStatusTone,
} from '@/modules/first-leg/utils/firstLegOrder' } from '@/modules/first-leg/utils/firstLegOrder'
const props = defineProps<{ order: FirstLegOrder }>() const props = defineProps<{ order: FirstLegOrder }>()
@@ -23,43 +21,42 @@ function stageState(index: number) {
<section class="order-progress" aria-labelledby="order-progress-title"> <section class="order-progress" aria-labelledby="order-progress-title">
<div class="progress-heading"> <div class="progress-heading">
<div> <div>
<h3 id="order-progress-title">订单进度</h3> <h3 id="order-progress-title">履约进度</h3>
<span>国内入仓、组托、装柜及后续履约同步</span> <span>订单主节点与关联柜次统一展示</span>
</div> </div>
<el-tag :type="getFirstLegStatusTone(order.status)" effect="light">
{{ getFirstLegStatusLabel(order.status) }}
</el-tag>
</div> </div>
<ol class="progress-stages" aria-label="订单主状态阶段"> <p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消</p>
<ol v-else class="progress-stages" aria-label="订单主状态阶段">
<li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined"> <li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined">
<span class="stage-marker" aria-hidden="true"><Check v-if="index < currentIndex" :size="13" /><CircleDot v-else :size="13" /></span> <span class="stage-marker" aria-hidden="true"><Check v-if="index < currentIndex" :size="13" /><CircleDot v-else :size="13" /></span>
<span class="stage-label">{{ stage.label }}</span> <span class="stage-label">{{ stage.label }}</span>
</li> </li>
</ol> </ol>
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">订单提交后开始记录主状态进度。</p> <p v-if="order.status === 'DRAFT'" class="draft-progress-note">待提交</p>
<div v-if="order.status !== 'CANCELLED'" class="progress-cabinet-detail"><slot name="cabinet" /></div>
</section> </section>
</template> </template>
<style scoped> <style scoped>
.order-progress { margin-top: 22px; } .order-progress { margin-top: 14px; }
.progress-heading { display: flex; align-items: center; } .progress-heading { display: flex; align-items: center; }
.progress-heading { justify-content: space-between; gap: 14px; } .progress-heading { justify-content: space-between; gap: 14px; }
.progress-heading > div { display: flex; min-width: 0; flex-direction: column; gap: 3px; } .progress-heading > div { display: flex; min-width: 0; flex-direction: column; gap: 3px; }
.progress-heading h3 { margin: 0; color: var(--navy); } .progress-heading h3 { margin: 0; color: var(--navy); }
.progress-heading h3 { font-size: 15px; } .progress-heading h3 { font-size: 13px; }
.progress-heading span { color: var(--muted); font-size: 11px; } .progress-heading span { color: var(--muted); font-size: 11px; }
.progress-stages { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(76px, 1fr); margin: 16px 0 0; padding: 0; overflow-x: auto; list-style: none; } .progress-stages { display: grid; grid-auto-flow: column; grid-auto-columns: minmax(76px, 1fr); margin: 9px 0 0; padding: 0; overflow-x: auto; list-style: none; }
.progress-stages li { position: relative; display: flex; min-width: 76px; align-items: center; flex-direction: column; gap: 7px; color: #96a0a6; font-size: 10px; text-align: center; } .progress-stages li { position: relative; display: flex; min-width: 76px; align-items: center; flex-direction: column; gap: 4px; color: #96a0a6; font-size: 10px; text-align: center; }
.progress-stages li::before { position: absolute; top: 10px; right: 50%; left: -50%; height: 2px; background: #e1e6e8; content: ''; } .progress-stages li::before { position: absolute; top: 8px; right: 50%; left: -50%; height: 2px; background: #e1e6e8; content: ''; }
.progress-stages li:first-child::before { display: none; } .progress-stages li:first-child::before { display: none; }
.progress-stages li.is-complete::before, .progress-stages li.is-current::before { background: var(--primary); } .progress-stages li.is-complete::before, .progress-stages li.is-current::before { background: var(--primary); }
.stage-marker { position: relative; z-index: 1; display: grid; width: 22px; height: 22px; place-items: center; border: 2px solid #d9e0e2; border-radius: 50%; background: #fff; } .stage-marker { position: relative; z-index: 1; display: grid; width: 18px; height: 18px; place-items: center; border: 2px solid #d9e0e2; border-radius: 50%; background: #fff; }
.is-complete .stage-marker, .is-current .stage-marker { border-color: var(--primary); color: var(--primary); } .is-complete .stage-marker, .is-current .stage-marker { border-color: var(--primary); color: var(--primary); }
.is-complete .stage-marker { background: var(--primary); color: #fff; } .is-complete .stage-marker { background: var(--primary); color: #fff; }
.is-current .stage-label { color: var(--navy); font-weight: 700; } .is-current .stage-label { color: var(--navy); font-weight: 700; }
.draft-progress-note { margin: 12px 0 0; padding: 10px 12px; background: #f6f8f8; color: var(--muted); font-size: 11px; } .draft-progress-note { margin: 8px 0 0; padding: 7px 9px; background: #f6f8f8; color: var(--muted); font-size: 10px; }
.progress-cabinet-detail { margin-top: 9px; }
@media (max-width: 720px) { @media (max-width: 720px) {
.progress-stages { grid-auto-columns: 82px; padding-bottom: 8px; } .progress-stages { grid-auto-columns: 82px; padding-bottom: 8px; }
.progress-heading { align-items: flex-start; } .progress-heading { align-items: flex-start; }
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { MerchantTransportFragment } from '../api/unifiedOrders'
import { customerTransportRows } from '../utils/transportFacts'
const props = defineProps<{ fragments: MerchantTransportFragment[] }>()
const rows = computed(() => customerTransportRows(props.fragments))
function time(value: string | null) { return value ? value.replace('T', ' ') : '—' }
</script>
<template>
<div class="transport-facts" aria-label="实际装载片段运输节点">
<strong>运输节点</strong>
<el-table v-if="rows.length" :data="rows" row-key="key" border size="small">
<el-table-column prop="inboundCode" label="入仓码" min-width="155" />
<el-table-column prop="cabinetNo" label="柜次" width="90" />
<el-table-column prop="containerNo" label="集装箱号" min-width="145" />
<el-table-column prop="nodeLabel" label="节点" min-width="150" />
<el-table-column label="实际时间" min-width="175"><template #default="{ row }">{{ time(row.actualAt) }}</template></el-table-column>
<el-table-column label="预计时间" min-width="175"><template #default="{ row }">{{ time(row.estimatedAt) }}</template></el-table-column>
<el-table-column prop="location" label="地点" min-width="130" />
<el-table-column prop="source" label="来源" width="105" />
</el-table>
<p v-else>暂无运输节点</p>
</div>
</template>
<style scoped>
.transport-facts { margin-top: 9px; }
.transport-facts > strong { display: block; padding: 7px 0 5px; color: var(--navy); font-size: 11px; }
.transport-facts > p { color: var(--muted); font-size: 11px; }
</style>
+4
View File
@@ -1,4 +1,8 @@
export { useFirstLegOrdersStore } from './store/firstLegOrders' export { useFirstLegOrdersStore } from './store/firstLegOrders'
export { getMerchantFirstLegOrders, type MerchantFirstLegOrderRow } from './api/firstLeg'
export { getMerchantUnifiedOrders, type MerchantUnifiedOrderRow } from './api/unifiedOrders'
export { getMerchantWarehouses, type MerchantWarehouse } from './api/firstLeg' export { getMerchantWarehouses, type MerchantWarehouse } from './api/firstLeg'
export { getFirstLegStatusLabel, getFirstLegStatusTone } from './utils/firstLegOrder' export { getFirstLegStatusLabel, getFirstLegStatusTone } from './utils/firstLegOrder'
export { default as InboundCodeAssociationDialog } from './components/InboundCodeAssociationDialog.vue' export { default as InboundCodeAssociationDialog } from './components/InboundCodeAssociationDialog.vue'
export { default as FirstLegOrdersView } from './views/FirstLegOrdersView.vue'
export { useCustomsPendingStore } from './store/customsPending'
+28 -6
View File
@@ -1,4 +1,4 @@
import { FileText, Ship, Zap } from '@lucide/vue' import { Calculator, FileText, Ship } from '@lucide/vue'
import type { ClientModuleManifest } from '../types.ts' import type { ClientModuleManifest } from '../types.ts'
export const firstLegModule = { export const firstLegModule = {
@@ -17,10 +17,17 @@ export const firstLegModule = {
{ {
path: 'orders/first-leg/create', path: 'orders/first-leg/create',
name: 'first-leg-order-create', name: 'first-leg-order-create',
component: () => import('./views/FirstLegOrdersView.vue'), component: () => import('./views/FirstLegOrderCreateHubView.vue'),
props: { createPage: true },
release: 'active', release: 'active',
meta: { title: '创建订单', description: '填写发货、目的地和货物信息', permission: 'order:first-leg:create' }, meta: { title: '创建订单', workspaceTitle: '头程订单 · 新建', description: '填写发货、目的地和货物信息', permission: 'order:first-leg:create', keepAlive: false },
},
{
path: 'orders/first-leg/:orderId/detail',
name: 'first-leg-order-detail',
component: () => import('./views/FirstLegOrdersView.vue'),
props: { detailPage: true },
release: 'active',
meta: { title: '订单详情', workspaceTitle: '头程订单 · 详情', description: '查看入仓码、运输与履约进度', permission: 'order:first-leg:list' },
}, },
{ {
path: 'orders/first-leg/:draftId/edit', path: 'orders/first-leg/:draftId/edit',
@@ -28,7 +35,7 @@ export const firstLegModule = {
component: () => import('./views/FirstLegOrdersView.vue'), component: () => import('./views/FirstLegOrdersView.vue'),
props: { createPage: true }, props: { createPage: true },
release: 'active', release: 'active',
meta: { title: '编辑订单草稿', description: '继续完善快速下单生成的草稿明细', permission: 'order:first-leg:edit' }, meta: { title: '编辑订单草稿', workspaceTitle: '头程订单 · 编辑', description: '继续完善快速下单生成的草稿明细', permission: 'order:first-leg:edit' },
}, },
{ {
path: 'first-leg/quick-order', path: 'first-leg/quick-order',
@@ -36,7 +43,22 @@ export const firstLegModule = {
component: () => import('./views/QuickOrderView.vue'), component: () => import('./views/QuickOrderView.vue'),
release: 'active', release: 'active',
meta: { title: '快速下单', description: '按渠道、目的仓和产品 SKU 快速生成订单草稿', permission: 'order:first-leg:quick-create' }, meta: { title: '快速下单', description: '按渠道、目的仓和产品 SKU 快速生成订单草稿', permission: 'order:first-leg:quick-create' },
navigation: { key: 'first-leg-quick-order', title: '快速下单', icon: Zap }, },
{
path: 'first-leg/customs-documents',
name: 'first-leg-customs-documents',
component: () => import('./views/CustomsDocumentsView.vue'),
release: 'active',
meta: { title: '报关资料', description: '管理装柜后的退税报关资料与回执', permission: 'order:first-leg:customs-list' },
navigation: { key: 'first-leg-customs-documents', title: '报关资料', icon: FileText },
},
{
path: 'first-leg/sailing-prices',
name: 'first-leg-sailing-prices',
component: () => import('./views/SailingPricesView.vue'),
release: 'active',
meta: { title: '船期价格', description: '查询渠道、参考船期与预估运费', permission: 'order:first-leg:pricing-list' },
navigation: { key: 'first-leg-sailing-prices', title: '船期价格', icon: Calculator },
}, },
], ],
} satisfies ClientModuleManifest } satisfies ClientModuleManifest
@@ -0,0 +1,39 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
import * as vue from 'vue'
import * as pinia from 'pinia'
const source = readFileSync(new URL('./customsPending.ts', import.meta.url), 'utf8')
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
function deferred() { let resolve, reject; const promise = new Promise((a,b) => { resolve=a; reject=b }); return { promise, resolve, reject } }
function harness(t, read) {
const context=pinia.createPinia();pinia.setActivePinia(context);t.after(()=>pinia.disposePinia(context))
const deps={vue,pinia,'../api/customs':{getMerchantCustomsPendingCount:read}}, exports={}
new Function('require','exports',code)(id=>{assert.ok(id in deps,id);return deps[id]},exports)
return exports.useCustomsPendingStore()
}
test('does not request without a permitted identity; preserves counts while refreshing and accepts zero',async t=>{
const pending=deferred();let calls=0
const store=harness(t,()=>++calls===1?Promise.resolve(2):pending.promise)
await store.refresh();assert.equal(calls,0)
store.setScope('customer-a');await store.refresh();assert.equal(store.count,2)
const load=store.refresh();await store.refresh();assert.equal(calls,2);assert.equal(store.count,2)
pending.resolve(0);await load;assert.equal(store.count,0);assert.equal(store.loading,false)
})
test('logout, permission removal and account switches discard old in-flight responses',async t=>{
const pending=deferred();const store=harness(t,()=>pending.promise)
store.setScope('a');const load=store.refresh();store.setScope('')
pending.resolve(9);await load;assert.equal(store.count,null);assert.equal(store.error,'')
store.setScope('b');assert.equal(store.count,null)
})
test('successful mutation can force a newer refresh without being overwritten by an older query',async t=>{
const a=deferred(),b=deferred();let calls=0;const store=harness(t,()=>++calls===1?a.promise:b.promise)
store.setScope('a');const first=store.refresh();const second=store.refresh(true)
b.resolve(1);await second;a.resolve(2);await first;assert.equal(store.count,1)
})
test('failure is distinguishable from zero and retry restores authoritative count',async t=>{
let fail=true;const store=harness(t,()=>fail?Promise.reject(new Error('offline')):Promise.resolve(3))
store.setScope('a');await store.refresh();assert.equal(store.count,null);assert.notEqual(store.error,'')
fail=false;await store.refresh();assert.equal(store.count,3);assert.equal(store.error,'')
})
@@ -0,0 +1,40 @@
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getMerchantCustomsPendingCount } from '../api/customs'
export const useCustomsPendingStore = defineStore('client-customs-pending', () => {
const count = ref<number | null>(null)
const loading = ref(false)
const error = ref('')
let scope = ''
let requestVersion = 0
function setScope(value: string) {
if (scope === value) return
scope = value
requestVersion++
count.value = null
error.value = ''
loading.value = false
}
async function refresh(force = false) {
if (!scope || (loading.value && !force)) return
const request = ++requestVersion
loading.value = true
try {
const result = await getMerchantCustomsPendingCount()
if (request !== requestVersion) return
count.value = result
error.value = ''
} catch {
if (request !== requestVersion) return
count.value = null
error.value = '报关待办数量加载失败,请进入报关资料刷新'
} finally {
if (request === requestVersion) loading.value = false
}
}
return { count, loading, error, setScope, refresh }
})

Some files were not shown because too many files have changed in this diff Show More