78 Commits
Author SHA1 Message Date
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
admin 15b51b6139 Merge pull request '发布采购、拼车、预约及匹配端侧修复至灰度' (#14) from release/test into main 2026-10-12 10:21:08 +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
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
admin ffa2b82c73 Merge pull request '发布当前测试版本至临时灰度环境' (#11) from release/test into main 2026-10-07 11:11:54 +08:00
96 changed files with 4783 additions and 1590 deletions
+23 -29
View File
@@ -39,25 +39,25 @@
## 模块快速查询 ## 模块快速查询
退货预报与签收结果:`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/`,退货单签收完成不等于换标或退货出库完成;后续换标、出库须按各自业务状态核对。 本表只保留首个入口;完整 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/`;正常轮换的统一 Access/Refresh 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`、`views/ProcurementView.vue`、`components/ProcurementDetailPanel.vue`、`api/procurement.ts` | 独立列表、新建及详情路由;客户范围只取 Token,创建的 `customerName` 只取认证会话企业名称。详情消费独立客户投影,展示履约、已确认箱明细、实际运单和费用结果,不开放内部文件或平台操作。Backend `lastleg-service/procurement/` | | 海外采购 | `src/modules/cross-border/AGENTS.md` |
| 美国本土卡与美本土散板 | `src/modules/cross-border/routes.ts`、`components/BusinessOrdersView.vue`、`api/businessOrders.ts` | 两个运输业务共用列表/表单组件,客户范围只取 Token;不消费采购字段或状态。Backend `lastleg-service/` 的 `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/order-management/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/overseas-warehouse/AGENTS.md` |
## 租户、认证与数据安全 ## 租户、认证与数据安全
@@ -73,11 +73,12 @@
## UI 与交互 ## UI 与交互
- 后续客户端新增、新建、下单操作统一执行 [Client 界面样式规范](../../docs/Client界面样式规范.md) 的“新增页面”章节,作为当前通用外观依据;列表按同文列表条款。只读取本轮适用章节,不因规范更新批量改造其他操作或公共外框。
- 视觉还原、布局/交互承载方式变更或真实页面验收时读取 `../../docs/Admin-Client前端原型还原验收规则.md`,只为受影响操作形成原型核对矩阵;纯文案、逻辑或测试修改不自动读取。自动检查与人工视觉验收分开报告,无视觉变化时标记“无需视觉验收”。 - 视觉还原、布局/交互承载方式变更或真实页面验收时读取 `../../docs/Admin-Client前端原型还原验收规则.md`,只为受影响操作形成原型核对矩阵;纯文案、逻辑或测试修改不自动读取。自动检查与人工视觉验收分开报告,无视觉变化时标记“无需视觉验收”。
- 已向客户讲解或确认过的产品原型是页面视觉与布局实现的直接事实来源。字段顺序、字段分组、字段摆放、列宽、控件宽高、对齐方式、换行方式、区块层级、上下左右边距、内边距、间隙、留白、圆角、边框、阴影、背景色、文字颜色和字号均必须按原型还原,不得只参考大致风格后自行重新排版。 - 已向客户讲解或确认过的产品原型是页面字段、分组、摆放及承载方式的直接依据;新增页的通用外观以当前 Client 样式规范明确替代的条款为准。未被替代的列宽、控件宽高、对齐方式、换行方式、区块层级、边距、圆角、边框、阴影、背景色、文字颜色和字号仍按原型还原,不得只参考大致风格后自行重新排版。
- 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。 - 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。
- 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。 - 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。
- 上述原型还原规则优先于本文件中“延续现有视觉体系”、默认组件样式和默认图标库等一般性规则。只有用户当前明确要求、阶段范围、真实字段长度、响应式、可访问性或接口事实与原型冲突时才允许做最小调整,并须在修改前说明具体差异、原因和影响范围;不得以技术实现方便为由偏离原型。 - 当前 Client 样式规范明确替代的外观及上述原型还原规则,优先于本文件中“延续现有视觉体系”、默认组件样式和默认图标库等一般性规则。后续用户明确确认的例外优先;阶段范围、真实字段长度、响应式、可访问性或接口事实与原型冲突时只做最小调整,并须在修改前说明具体差异、原因和影响范围,不得以技术实现方便为由偏离。
- 详情、新增、编辑、审核等操作采用独立页面、居中弹框、侧滑面板或其他承载方式,必须逐页面按对应原型确认,不得全局写死为某一种容器。原型为独立页面时使用正式路由和页面布局;原型为居中弹框时使用模态弹框;只有原型明确为侧滑面板时才使用抽屉。不得因为已有公共组件或改动方便,把原型中的独立页面改成弹框、把弹框改成抽屉,或反向替换。 - 详情、新增、编辑、审核等操作采用独立页面、居中弹框、侧滑面板或其他承载方式,必须逐页面按对应原型确认,不得全局写死为某一种容器。原型为独立页面时使用正式路由和页面布局;原型为居中弹框时使用模态弹框;只有原型明确为侧滑面板时才使用抽屉。不得因为已有公共组件或改动方便,把原型中的独立页面改成弹框、把弹框改成抽屉,或反向替换。
- 延续现有客户工作台的可信、简洁和服务型视觉语言,与内部管理后台保持品牌关联但不照搬高密度管理界面。 - 延续现有客户工作台的可信、简洁和服务型视觉语言,与内部管理后台保持品牌关联但不照搬高密度管理界面。
- 优先使用 Element Plus 和 Lucide 图标;不使用表情符号代替功能图标,不引入第二套组件库。 - 优先使用 Element Plus 和 Lucide 图标;不使用表情符号代替功能图标,不引入第二套组件库。
@@ -97,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/`;依赖变更必须同步当前项目依赖清单和锁文件。
## 全量验收脚本 ## 全量验收脚本
@@ -110,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` 定位。
+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扫描现场箱唛自动计数。详情展示废弃备注、托盘、实际废弃箱唛与实际数量;现场扫描清单与申请选箱快照分别展示。
+2
View File
@@ -43,6 +43,8 @@ const visibleNavigation = computed(() => filterNavigationByPermissions(clientNav
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath))) const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath)))
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) {
const next = new Set(openedKeys.value) const next = new Set(openedKeys.value)
+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`。
+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,37 @@
# 本土卡车字段调整核对
依据:用户提供的下单页截图 `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%截图确认。
+52 -17
View File
@@ -17,7 +17,9 @@ export interface BusinessOrderQuery {
status?: string status?: string
routeKeyword?: string routeKeyword?: 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
@@ -27,21 +29,25 @@ export interface BusinessOrderQuery {
export interface TransportSummary { export interface TransportSummary {
fleetArrangement: import('../fleetArrangement').FleetArrangement | null fleetArrangement: import('../fleetArrangement').FleetArrangement | null
orderNo: string orderNo: string
transportType: string transportType?: string
transportMode?: string
palletRequired?: string | null palletRequired?: string | null
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
@@ -56,23 +62,44 @@ export interface TransportDetail {
} }
export interface TransportCreate { export interface TransportCreate {
transportType: string productName?: string
transportMode?: string estimatedPalletCount: number
palletRequired?: string
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
} }
@@ -81,6 +108,10 @@ 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> = {
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',
@@ -98,11 +129,15 @@ export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: stri
return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` }) return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
} }
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) { export function createTransport(kind: 'trucking', payload: TruckCreate): Promise<TransportDetail>
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 }) 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>
export function updateTransport(kind: 'looseboard', orderNo: string, payload: TransportUpdate): Promise<TransportDetail>
export function updateTransport(kind: CrossBorderBusinessKind, orderNo: string, payload: TransportUpdate | TruckUpdate) {
return apiRequest<TransportDetail>({ return apiRequest<TransportDetail>({
method: kind === 'trucking' ? 'PATCH' : 'PUT', method: kind === 'trucking' ? 'PATCH' : 'PUT',
url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}`, url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}`,
@@ -0,0 +1,13 @@
import { apiRequest } from '@/api/http'
interface BudgetResult { status: string; usable: boolean; amountCny: number | string; message: string; orderNo: string | null }
const base = '/merchant/v1/last-leg/order-budgets'
// 资金回执成功才继续下单;超时保留当前幂等键,允许用户再次核对。
export async function requireOrderBudget(kind: 'procurement' | 'trucking', key: string, amount: number, currency: string) {
const url = `${base}/${kind}/${encodeURIComponent(key)}`
let result = await apiRequest<BudgetResult>({ method: 'POST', url, data: { amount, currency } })
for (let attempt = 0; result.status === 'FREEZE_PENDING' && attempt < 12; attempt++) {
await new Promise(resolve => setTimeout(resolve, 1000))
result = await apiRequest<BudgetResult>({ method: 'GET', url })
}
if (!result.usable) throw new Error(result.message || '余额及授信校验未完成,请稍后重试')
}
+47 -1
View File
@@ -1,8 +1,9 @@
import { apiRequest } from '@/api/http' import { apiBlobRequest, apiRequest } from '@/api/http'
import type { PageResult } from './businessOrders' import type { PageResult } from './businessOrders'
export type Amount = number | string export type Amount = number | string
export interface ProcurementSummary { export interface ProcurementSummary {
procurementDirection?: import('../procurementPresentation').ProcurementDirection
orderNo: string orderNo: string
purchaseCategory: string purchaseCategory: string
productName: string productName: string
@@ -73,6 +74,7 @@ export interface ProcurementDetail {
exceptionSummaries: string[] exceptionSummaries: string[]
} }
export interface ProcurementCreate { export interface ProcurementCreate {
procurementDirection?: import('../procurementPresentation').ProcurementDirection
customerName: string customerName: string
purchaseCategory: string purchaseCategory: string
productName: string productName: string
@@ -95,6 +97,37 @@ export interface ProcurementQuery {
purchaseCategory?: string purchaseCategory?: string
status?: 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' const endpoint = '/merchant/v1/last-leg/overseas-procurements'
export async function listProcurements(params: ProcurementQuery) { export async function listProcurements(params: ProcurementQuery) {
const result = await apiRequest<PageResult<ProcurementSummary>>({ method: 'GET', url: endpoint, params }) const result = await apiRequest<PageResult<ProcurementSummary>>({ method: 'GET', url: endpoint, params })
@@ -106,3 +139,16 @@ export function getProcurement(orderNo: string) {
export function createProcurement(data: ProcurementCreate) { export function createProcurement(data: ProcurementCreate) {
return apiRequest<ProcurementDetail>({ method: 'POST', url: endpoint, data }) 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` })
}
@@ -7,6 +7,9 @@ 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 procurementApi = readFileSync(new URL('./api/procurement.ts', import.meta.url), 'utf8')
const procurementView = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8') const procurementView = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
@@ -29,7 +32,7 @@ test('renders unknown pallet service and container type as dashes while preservi
test('shows merchant-owned arrangement facts without a pool request or editable status control', () => { test('shows merchant-owned arrangement facts without a pool request or editable status control', () => {
assert.match(api, /fleetArrangement: import\('\.\.\/fleetArrangement'\)\.FleetArrangement \| null/) assert.match(api, /fleetArrangement: import\('\.\.\/fleetArrangement'\)\.FleetArrangement \| null/)
assert.match(view, /aria-label="承运安排"/) assert.match(view, /aria-label="承运安排"/)
for (const field of ['signedPackages', 'unsignedPackages', 'returnedPackages', 'readOnlyReason']) assert.ok(view.includes(`fleetArrangement.${field}`)) for (const field of ['signedPackages', 'unsignedPackages', 'returnedPackages']) assert.ok(view.includes(`fleetArrangement.${field}`))
assert.doesNotMatch(api, /capacity-offers|fleet\/trips/) 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 \(query\.page !== 1\) query\.page = 1\s+else void load\(\)/)
assert.match(view, /if \(reloadDirectly\) void load\(\)/) assert.match(view, /if \(reloadDirectly\) void load\(\)/)
@@ -106,7 +109,7 @@ test('preserves the existing transport responsive rules without adding a narrow-
assert.match(view, /queryFields/) 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', () => { test('uses the shared dense order-list and detail visual language', () => {
@@ -115,3 +118,108 @@ test('uses the shared dense order-list and detail visual language', () => {
assert.match(view, /\.detail-grid \{[^}]*grid-template-columns: repeat\(4, minmax\(0, 1fr\)\)/) 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\)/) 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 })`, {
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'); },
})
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, 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)
})
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)
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 waits for budget freeze and never submits after insufficient funds', async () => {
let release
const gate = new Promise(resolve => { release = resolve })
const current = transportHarness('trucking', false, () => gate)
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' })
const pending = current.submit(); await Promise.resolve(); await Promise.resolve()
assert.equal(current.calls.length, 0)
release(); await pending; assert.equal(current.calls.length, 1)
const failed = transportHarness('trucking', false, async () => { throw new Error('余额及授信不足') })
Object.assign(failed.form, { ...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 failed.submit(); assert.equal(failed.calls.length, 0); assert.equal(failed.form.budgetAmount, 100)
})
@@ -1,7 +1,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus' import { ElMessage, type FormInstance } from 'element-plus'
import TransportDemandForm from './TransportDemandForm.vue'
import { requireOrderBudget } from '../api/orderBudgets'
import { createTransportDemandForm, transportDemandError, buildTransportDemand, type TransportDemandForm as DemandFormModel } from '../transportDemandForm'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue' import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue' import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
import type { TableAction } from '@/components/common/tableActions' import type { TableAction } from '@/components/common/tableActions'
@@ -14,7 +17,6 @@ import {
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' import { poolOrderStatusLabels } from '../fleetArrangement'
const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false }) const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
@@ -33,30 +35,11 @@ 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
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
remark: string
}
const configuration = computed(() => ({ const configuration = computed(() => ({
trucking: { trucking: {
title: '美国本土卡', title: '美国本土卡车',
description: '查询并管理美国本土卡订单', description: '查询并管理美国本土卡订单',
columns: transportColumns(false), columns: transportColumns(false),
}, },
@@ -68,16 +51,21 @@ 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 },
{ 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 },
{ key: 'fleetArrangement', label: '承运安排', width: 190 }, { key: 'fleetArrangement', label: '承运安排', width: 190 },
] ]
@@ -110,7 +98,7 @@ const queryModel = computed<QueryModel>({
const queryFields = computed<QueryField[]>(() => [ const queryFields = computed<QueryField[]>(() => [
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' }, { key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: '请输入起运地或目的地' }, { key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: props.kind === 'trucking' ? '请输入 B 点或 C 点' : '请输入起运地或目的地' },
{ {
key: 'status', key: 'status',
label: '状态', label: '状态',
@@ -131,29 +119,23 @@ const queryFields = computed<QueryField[]>(() => [
]) ])
const form = reactive<BusinessForm>(emptyForm()) const form = reactive<BusinessForm>(emptyForm())
const rules: FormRules<BusinessForm> = { watch(() => JSON.stringify(form), () => { submitKey.value = '' })
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
const current = detail.value as TransportDetail const current = detail.value as TransportDetail
return [ return [
['运输方式', transportModeLabel(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')], ['件数', read(summary, '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')], ['备注', 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],
] ]
}) })
@@ -169,14 +151,7 @@ const tableColumns = computed<DataTableColumn[]>(() => [
const detailStatus = computed(() => detail.value ? statusLabel(detail.value.summary.status) : '—') const detailStatus = computed(() => detail.value ? statusLabel(detail.value.summary.status) : '—')
function emptyForm(): BusinessForm { function emptyForm(): BusinessForm { return createTransportDemandForm() }
return {
transportMode: 'SHARED_TRUCK', palletRequired: 'NO', transportType: 'PORT_PICKUP', origin: '', originAddress: '',
destination: '', destinationAddress: '', containerType: DEFAULT_CONTAINER_TYPE, palletCount: 1, packageCount: 0,
totalWeightKg: 0, totalVolumeCbm: 0, currency: 'USD', contactName: '', contactInfo: '', requestedDate: '',
remark: '',
}
}
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 }
@@ -184,8 +159,9 @@ function text(value: unknown) { return value === null || value === undefined ||
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) {
if (poolOrderStatusLabels[String(value)]) return poolOrderStatusLabels[String(value)] if (poolOrderStatusLabels[String(value)]) return poolOrderStatusLabels[String(value)]
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value) return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
@@ -197,8 +173,9 @@ 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 === 'budgetAmount') return money(value, read(row, 'currency')) if (key === 'budgetAmount') return money(value, read(row, 'currency'))
@@ -241,7 +218,7 @@ function getRowActions(candidate: object): TableAction[] {
} }
function detailFieldClass(label: unknown) { function detailFieldClass(label: unknown) {
return ['备注', '起运地址', '目的地址'].includes(String(label)) ? 'is-wide' : '' return ['备注', props.kind === 'trucking' ? '取货地址' : '起运地址', props.kind === 'trucking' ? '送达地址' : '目的地址'].includes(String(label)) ? 'is-wide' : ''
} }
const listRouteName = computed(() => ({ const listRouteName = computed(() => ({
@@ -277,29 +254,25 @@ async function loadDetail() {
} }
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 {
const base = { if (props.kind === 'trucking') {
transportType: form.transportType, origin: form.origin, originAddress: form.originAddress || undefined, const payload = { ...buildTransportDemand('truck', form), idempotencyKey: stableSubmitKey }
destination: form.destination, destinationAddress: form.destinationAddress || undefined, await requireOrderBudget('trucking', stableSubmitKey, payload.budgetAmount!, payload.currency)
containerType: form.containerType || undefined, packageCount: form.packageCount, await createTransport('trucking', payload)
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 }
: { ...base, transportMode: form.transportMode, palletRequired: form.palletRequired })
ElMessage.success('订单提交成功') ElMessage.success('订单提交成功')
resetForm() resetForm()
if (props.createPage) await router.push({ name: listRouteName.value }) if (props.createPage) await router.push({ name: listRouteName.value })
else { mode.value = 'list'; await load() } else { mode.value = 'list'; await load() }
} catch (cause) { ElMessage.error(errorMessage(cause)) } } catch (cause) { if (/已释放|已过期/.test(errorMessage(cause))) submitKey.value = ''; ElMessage.error(errorMessage(cause)) }
finally { submitting.value = false } finally { submitting.value = false }
} }
@@ -308,11 +281,11 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
</script> </script>
<template> <template>
<section v-loading="loading" class="business-orders client-ui" :aria-busy="loading"> <section v-loading="loading" class="business-orders client-ui" :class="{ 'business-orders--create': mode === 'create' }" :aria-busy="loading">
<header v-if="mode === 'create'" class="page-head"> <header v-if="mode === 'create'" class="page-head">
<div> <div>
<h2>{{ configuration.title }}下单</h2> <h2>{{ configuration.title }}下单</h2>
<p>请填写订单信息,带 * 项为必填项</p>
</div> </div>
<el-button @click="returnToList">返回列表</el-button> <el-button @click="returnToList">返回列表</el-button>
</header> </header>
@@ -332,18 +305,18 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
<section v-else-if="mode === 'detail'" class="business-detail-page" aria-label="订单详情"> <section v-else-if="mode === 'detail'" class="business-detail-page" aria-label="订单详情">
<header class="business-detail-heading"> <header class="business-detail-heading">
<div class="business-detail-heading-main"><el-button link type="primary" @click="returnToList">← 返回列表</el-button><div><h2>{{ detail?.summary.orderNo || '订单详情' }}</h2><p>{{ configuration.title }}订单</p></div></div> <div class="business-detail-heading-main"><el-button link type="primary" @click="returnToList">← 返回列表</el-button><div><h2>{{ detail?.summary.orderNo || '订单详情' }}</h2></div></div>
<el-tag :type="statusTone(detail?.summary.status)" effect="light">{{ detailStatus }}</el-tag> <el-tag :type="statusTone(detail?.summary.status)" effect="light">{{ detailStatus }}</el-tag>
</header> </header>
<div v-if="error" class="business-detail-error" role="alert"><strong>{{ error }}</strong><el-button size="small" @click="loadDetail">重新加载</el-button></div> <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"> <section v-else class="business-detail-section">
<h3>订单信息</h3> <h3>订单信息</h3>
<dl class="detail-grid"> <dl class="detail-grid" :class="{ 'trucking-detail-grid': kind === 'trucking' }">
<div v-for="field in detailFields" :key="String(field[0])" :class="detailFieldClass(field[0])"><dt>{{ field[0] }}</dt><dd>{{ text(field[1]) }}</dd></div> <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>
</section> </section>
<section v-if="!error && fleetArrangement" class="business-detail-section" aria-label="承运安排"> <section v-if="!error && fleetArrangement" class="business-detail-section" aria-label="承运安排">
<h3>承运安排</h3><p>{{ fleetArrangement.readOnlyReason }}</p> <h3>承运安排</h3>
<dl class="detail-grid arrangement-grid"> <dl class="detail-grid arrangement-grid">
<div><dt>预订号</dt><dd>{{ fleetArrangement.bookingNo }}</dd></div> <div><dt>预订号</dt><dd>{{ fleetArrangement.bookingNo }}</dd></div>
<div><dt>计划发车</dt><dd>{{ dateTime(fleetArrangement.plannedDepartureAt) }}</dd></div> <div><dt>计划发车</dt><dd>{{ dateTime(fleetArrangement.plannedDepartureAt) }}</dd></div>
@@ -363,26 +336,7 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
</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" />
<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>
<el-form-item class="budget-form-item" label="预算金额"><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="returnToList">取消</el-button><el-button v-if="canCreate" type="primary" :loading="submitting" @click="submit">提交订单</el-button></el-form-item>
</el-form>
</el-card> </el-card>
</section> </section>
</template> </template>
@@ -407,14 +361,18 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
.business-detail-section h3 { margin: 0; padding: 0 0 5px; border-bottom: 1px solid #eaf0f7; color: var(--navy); font-size: 13px; } .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 { 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); } .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-wide { grid-column: span 2; }
.detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; } .detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
.arrangement-grid div { grid-template-columns: 124px minmax(0, 1fr); } .arrangement-grid div { grid-template-columns: 124px minmax(0, 1fr); }
.arrangement-grid dt { white-space: normal; overflow-wrap: anywhere; } .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; } .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-form) { max-width: 860px; } .form-card :deep(.el-card__body) { padding: 0; }
.form-card :deep(.el-input), .form-card :deep(.el-textarea), .form-card :deep(.el-select) { width: 100%; } .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; }
.form-card .currency { width: 110px; margin-left: 12px; } .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; }
@media (max-width: 767px) { @media (max-width: 767px) {
.business-orders { gap: 14px; } .business-orders { gap: 14px; }
@@ -1,106 +1,106 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue' import { computed, onBeforeUnmount, ref } from 'vue'
import type { ProcurementDetail, ProcurementFee } from '../api/procurement' import { getProcurementFile, type ProcurementDetail, type ProcurementFee, type ProcurementWorkflow } from '../api/procurement'
import { dateTime, feePurposes, feeStatus, feeTone, feeTotals, measurement, money, productHref, text } from '../procurementPresentation' import { directionLabel, dateTime, feeStatus, feeTone, feeTotals, money, productHref, statusLabel, text } from '../procurementPresentation'
const props = defineProps<{ detail: ProcurementDetail; workflow: ProcurementWorkflow }>()
const props = defineProps<{ detail: ProcurementDetail }>() 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)) const totals = computed(() => feeTotals(props.detail.fees))
const progress = computed(() => props.detail.progress.filter(step => step.key !== 'closed_at' || step.completedAt))
const ended = computed(() => ['REJECTED', 'CANCELLED', 'EXCEPTION_CLOSED', 'SHIPPED_TO_CUSTOMER'].includes(props.detail.order.status))
const hasPending = computed(() => props.detail.fees.some(f => f.walletStatus?.endsWith('_PENDING') || f.walletStatus?.endsWith('_FAILED')))
</script> </script>
<template> <template>
<section class="procurement-section" aria-label="采购履约进度"> <el-alert v-if="fileError" :title="fileError" type="error" :closable="false" />
<h3>履约进度</h3> <section class="procurement-section" aria-label="采购数量统计">
<ol class="procurement-progress"> <dl class="procurement-grid money-grid">
<li v-for="step in progress" :key="step.key" :class="{ 'is-complete': step.completedAt }"> <div><dt>累计收货</dt><dd>{{ workflow.receivedQuantity }} 件</dd></div>
<strong>{{ step.title }}</strong><span>{{ step.completedAt ? dateTime(step.completedAt) : ended ? '未执行' : '待处理' }}</span> <div><dt>采购库存</dt><dd>{{ workflow.stockQuantity }} 件</dd></div>
</li> <div><dt>出库处理中</dt><dd>{{ workflow.reservedQuantity }} 件</dd></div>
</ol> <div><dt>可出库</dt><dd>{{ workflow.availableQuantity }} 件</dd></div>
<p v-if="detail.purchaseNeedsAttention" class="procurement-note">购买资料正在核对,客服将协助处理。已发生的收货与费用结果仍保留在本单。</p> </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>
<section class="procurement-section" aria-label="商品与收件信息"> <section class="procurement-section" aria-label="商品与收件信息">
<h3>商品与收件信息</h3> <h3>商品与收件信息</h3>
<dl class="procurement-grid"> <dl class="procurement-grid">
<div><dt>采购品类</dt><dd>{{ detail.order.purchaseCategory }}</dd></div> <div><dt>采购方向</dt><dd>{{ directionLabel(detail.order.procurementDirection) }}</dd></div>
<div><dt>商品名称</dt><dd>{{ detail.order.productName }}</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.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>{{ detail.order.purchaseQuantity }} 件</dd></div>
<div><dt>下单预算单价</dt><dd>{{ money(detail.order.budgetUnitPrice, detail.order.currency) }}</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>{{ money(detail.budget.totalAmount, detail.budget.currency) }}</dd></div>
<div><dt>预算核验时间</dt><dd>{{ dateTime(detail.budget.authorizedAt) }}</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>{{ dateTime(detail.order.estimatedArrivalAt) }}</dd></div>
<div><dt>收件人</dt><dd>{{ detail.order.contactName }}</dd></div> <div><dt>收件人</dt><dd>{{ detail.order.contactName }}</dd></div>
<div><dt>联系电话</dt><dd>{{ detail.order.contactPhone }}</dd></div> <div><dt>联系电话</dt><dd>{{ detail.order.contactPhone }}</dd></div>
<div class="wide"><dt>下单收货地址</dt><dd>{{ detail.order.receivingAddress }}</dd></div> <div class="wide"><dt>收货地址</dt><dd>{{ detail.order.receivingAddress }}</dd></div>
<div class="wide"><dt>实际海外仓</dt><dd>{{ text(detail.order.actualWarehouseName) }}<span v-if="detail.order.actualWarehouseCode">({{ detail.order.actualWarehouseCode }})</span></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>
<div class="wide"><dt>商品链接</dt><dd><a v-if="productHref(detail.order.productUrl)" :href="productHref(detail.order.productUrl)" target="_blank" rel="noopener noreferrer">{{ detail.order.productUrl }}</a><span v-else>{{ text(detail.order.productUrl) }}</span></dd></div>
</dl> </dl>
</section> </section>
<section class="procurement-section" aria-label="已确认海外装箱清单"> <el-dialog :model-value="!!previewUrl" :title="previewName" width="800px" append-to-body @close="clearPreview">
<h3>已确认海外装箱清单</h3> <img v-if="previewImage" :src="previewUrl" :alt="previewName" style="display: block; max-width: 100%; max-height: 70vh; margin: auto" />
<el-table :data="detail.boxes" border stripe empty-text="尚无已确认的装箱清单" row-key="cartonNo"> <a v-else :href="previewUrl" :download="previewName">下载 {{ previewName }}</a>
<el-table-column prop="cartonNo" label="箱号" min-width="170" /> </el-dialog>
<el-table-column label="箱内商品" min-width="200"><template #default>{{ detail.order.productName }}</template></el-table-column>
<el-table-column label="规格" min-width="180"><template #default>{{ text(detail.order.productSpecification) }}</template></el-table-column>
<el-table-column prop="quantity" label="数量(件)" width="120" />
<el-table-column label="外箱长 × 宽 × 高(cm)" min-width="240"><template #default="{ row }">{{ measurement(row.lengthCm, 2) }} × {{ measurement(row.widthCm, 2) }} × {{ measurement(row.heightCm, 2) }}</template></el-table-column>
<el-table-column label="封箱毛重(kg)" width="170"><template #default="{ row }">{{ measurement(row.grossWeightKg, 3) }}</template></el-table-column>
</el-table>
</section>
<section class="procurement-section" aria-label="两段实际运输">
<h3>两段实际运输</h3>
<el-table :data="detail.shipments" border stripe empty-text="尚无实际交寄记录">
<el-table-column label="运输段" width="150"><template #default="{ row }">{{ row.leg === 'OVERSEAS' ? '国际段 · 海外交寄' : '国内段 · 寄客户' }}</template></el-table-column>
<el-table-column prop="shipmentNo" label="交寄编号" min-width="270" />
<el-table-column prop="cartonNo" label="原箱号" min-width="150" />
<el-table-column prop="quantity" label="实际件数" width="110" />
<el-table-column prop="carrier" label="承运商" min-width="140" />
<el-table-column prop="trackingNo" label="运单号" min-width="230" />
<el-table-column label="实际交寄时间" width="185"><template #default="{ row }">{{ dateTime(row.shippedAt) }}</template></el-table-column>
</el-table>
<p class="procurement-note">这里显示已实际交给承运方的记录;国内寄客户后,本单履约完成。</p>
</section>
<section class="procurement-section" aria-label="采购费用与资金结果">
<h3>费用与资金结果</h3>
<dl class="procurement-grid money-grid">
<div><dt>累计成功扣款</dt><dd>{{ money(totals?.paid) }}</dd></div>
<div><dt>累计成功退款</dt><dd>{{ money(totals?.refunded) }}</dd></div>
<div><dt>净实扣</dt><dd>{{ money(totals?.net) }}</dd></div>
<div><dt>预估国际运费占款</dt><dd>{{ money(totals?.estimatedHold) }}</dd></div>
</dl>
<p class="procurement-note">预算上限仅包含样品货款。预估国际运费只冻结、不直接扣款,最终以实际费用结算;表内保留原费用、追加及退款记录。</p>
<el-table :data="detail.fees" border stripe empty-text="尚无已核定费用" row-key="feeNo">
<el-table-column prop="feeNo" label="费用编号" min-width="270" />
<el-table-column label="费用用途" min-width="145"><template #default="{ row }">{{ feePurposes[row.purpose] || '待核定' }}</template></el-table-column>
<el-table-column prop="name" label="费用名称" min-width="145" />
<el-table-column label="原币金额" min-width="130"><template #default="{ row }">{{ money(row.originalAmount, row.originalCurrency) }}</template></el-table-column>
<el-table-column label="汇率 / 月份" min-width="150"><template #default="{ row }">{{ measurement(row.exchangeRate, 6) }}<br /><small>{{ text(row.exchangeRateMonth) }}</small></template></el-table-column>
<el-table-column label="人民币金额" min-width="130"><template #default="{ row }">{{ money(row.amount) }}</template></el-table-column>
<el-table-column label="处理结果" min-width="190"><template #default="{ row }"><el-tag :type="feeTone(row as ProcurementFee)" size="small">{{ feeStatus(row as ProcurementFee) }}</el-tag><small v-if="row.purpose !== 'INTERNATIONAL_ESTIMATE' && row.walletStatus === 'SETTLED' && !row.sourceLinked" class="fee-sync">费用结果同步中</small></template></el-table-column>
<el-table-column prop="parentFeeNo" label="关联原费用 / 预估" min-width="270"><template #default="{ row }">{{ text(row.parentFeeNo) }}</template></el-table-column>
</el-table>
<p v-if="hasPending" class="procurement-note">部分资金处理尚未完成,可点击页面“刷新”查看最新结果;如需协助请联系客户服务。</p>
</section>
<section v-if="detail.exceptionSummaries.length" class="procurement-section" aria-label="客服处理说明">
<h3>客服处理说明</h3><ul class="procurement-summaries"><li v-for="(summary, index) in detail.exceptionSummaries" :key="index">{{ summary }}</li></ul>
</section>
</template> </template>
<style scoped> <style scoped>
.procurement-section { margin-top: 18px; min-width: 0; } .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; } h3 { margin: 0 0 10px; padding-bottom: 7px; border-bottom: 1px solid var(--border); color: var(--navy); font-size: 14px; }
.procurement-progress { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0; padding: 0; margin: 0; list-style: none; border-top: 1px solid var(--border); border-left: 1px solid var(--border); }
.procurement-progress li { display: grid; gap: 7px; padding: 12px; border-bottom: 1px solid var(--border); border-right: 1px solid var(--border); color: var(--muted); }
.procurement-progress strong { font-size: 13px; font-weight: 600; }.procurement-progress span { font-size: 12px; }.procurement-progress .is-complete strong { color: var(--navy); }
.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 { 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 > 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 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 > div { grid-template-columns: minmax(0, 1fr); }.money-grid dd { font-size: 16px; font-weight: 600; } .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; }
a { color: var(--client-action); } .procurement-note { margin: 10px 0; color: var(--muted); font-size: 12px; line-height: 1.7; } .procurement-grid .full { grid-column: 1 / -1; }
.fee-sync { display: block; padding-top: 5px; color: var(--muted); }.procurement-summaries { margin: 0; padding-left: 22px; line-height: 1.8; color: var(--navy); font-size: 13px; white-space: pre-wrap; } .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) { @media (max-width: 767px) {
.procurement-progress, .procurement-grid { grid-template-columns: 1fr; }.procurement-grid .wide { grid-column: auto; } .procurement-grid { grid-template-columns: 1fr; }.procurement-grid .wide { grid-column: auto; }
} }
</style> </style>
@@ -0,0 +1,138 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
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 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 class="transport-demand-section">
<h3>运输信息</h3>
<div class="transport-demand-grid transport-demand-route-grid">
<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 :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 :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 :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 class="transport-demand-address" :label="kind === 'truck' ? '取货地址' : '起运详细地址'"><el-input v-model.trim="model.originAddress" maxlength="500" placeholder="街道 / 门牌等补充信息(选填)" /></el-form-item>
<el-form-item class="transport-demand-address" :label="kind === 'truck' ? '送达地址' : '目的详细地址'"><el-input v-model.trim="model.destinationAddress" maxlength="500" placeholder="街道 / 门牌等补充信息(选填)" /></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 :disabled="submitting" @click="emit('cancel')">{{ isCreate ? '返回列表' : '取消' }}</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>
+193 -36
View File
@@ -1,11 +1,14 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import test from 'node:test' import test from 'node:test'
import { readFileSync } from 'node:fs' import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { runInNewContext } from 'node:vm' import { runInNewContext } from 'node:vm'
import ts from 'typescript' import ts from 'typescript'
import * as vue from 'vue' import * as vue from 'vue'
import { parse, compileScript } from 'vue/compiler-sfc' import { parse, compileScript } from 'vue/compiler-sfc'
const { default: Schema } = createRequire(import.meta.resolve('element-plus'))('async-validator')
let nextKey = 0 let nextKey = 0
const crypto = { randomUUID: () => `test-key-${++nextKey}` } const crypto = { randomUUID: () => `test-key-${++nextKey}` }
function moduleFrom(source, require = () => { throw new Error('unexpected import') }) { function moduleFrom(source, require = () => { throw new Error('unexpected import') }) {
@@ -54,16 +57,8 @@ test('successful net debit excludes the original estimate and counts only succes
assert.equal(presentation.feeStatus(fee('DUTY', null, 100)), '待核定') assert.equal(presentation.feeStatus(fee('DUTY', null, 100)), '待核定')
}) })
test('request recovery preserves content and identity while malformed recovery cannot create a replacement', () => { test('new requests get unique keys without restoring stored submissions', () => {
const original = presentation.buildProcurementCreate(draft(), 'Company', 'fixed-key') assert.notEqual(submission.procurementRequestKey(crypto), submission.procurementRequestKey(crypto))
assert.deepEqual(normalized(submission.restoreProcurementSubmission(JSON.stringify(original))), normalized(original))
assert.throws(() => submission.restoreProcurementSubmission('{}'))
assert.throws(() => submission.restoreProcurementSubmission(JSON.stringify({ ...original, currency: 'EUR' })))
assert.equal(submission.definitelyRejected({ code: 'TIMEOUT' }), false)
assert.equal(submission.definitelyRejected({ status: 500 }), false)
assert.equal(submission.definitelyRejected({ status: 409 }), false)
assert.equal(submission.definitelyRejected({ status: 400 }), true)
assert.equal(submission.procurementRequestKey({ getRandomValues: target => { target.set([1, 2, 3, 4]); return target } }), 'proc-00000001000000020000000300000004')
}) })
class ApiError extends Error { constructor(message, code, status) { super(message); this.code = code; this.status = status } } class ApiError extends Error { constructor(message, code, status) { super(message); this.code = code; this.status = status } }
@@ -73,17 +68,18 @@ function viewHarness({ createPage = false, detailPage = false, api = {}, storage
const route = vue.reactive({ params: { orderNo: detailPage ? 'PO-1' : '' } }) 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 auth = vue.reactive({ token: 'identity-A', user: { tenantName: 'Company' }, profile: { tenantName: 'Company' }, hasPermission: () => true })
const pushes = [], dispose = [] const pushes = [], dispose = []
const defaults = { listProcurements: async () => ({ records: [], total: 0 }), getProcurement: async orderNo => ({ order: { orderNo } }), createProcurement: async () => ({ order: { orderNo: 'PO-CREATED' } }) } 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 { descriptor } = parse(readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8'))
const source = compileScript(descriptor, { id: 'procurement-test' }).content 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) }, 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) { 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') 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 === 'vue-router') return { useRoute: () => route, useRouter: () => ({ push: async target => pushes.push(target) }) }
if (name === 'element-plus') return { ElMessage: { success: () => {} } } 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/types') return { ApiError }
if (name === '@/api/session') return { accessTokenIdentity: token => token } if (name === '@/api/session') return { accessTokenIdentity: token => token }
if (name === '@/modules/auth/public') return { useAuthStore: () => auth } 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 === '../api/procurement') return { ...defaults, ...api }
if (name === '../procurementPresentation') return presentation if (name === '../procurementPresentation') return presentation
if (name === '../procurementSubmission') return submission if (name === '../procurementSubmission') return submission
@@ -93,9 +89,84 @@ function viewHarness({ createPage = false, detailPage = false, api = {}, storage
} }
runInNewContext(ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText, context) runInNewContext(ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText, context)
const state = context.exports.default.setup(props, { expose: () => {} }) 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()) } 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', '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)
} 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 () => { test('detail has one in-flight request and an older response cannot overwrite another order', async () => {
const calls = [], pending = new Map() const calls = [], pending = new Map()
const harness = viewHarness({ detailPage: true, api: { getProcurement: orderNo => { calls.push(orderNo); return new Promise(resolve => pending.set(orderNo, resolve)) } } }) const harness = viewHarness({ detailPage: true, api: { getProcurement: orderNo => { calls.push(orderNo); return new Promise(resolve => pending.set(orderNo, resolve)) } } })
@@ -109,27 +180,25 @@ test('detail has one in-flight request and an older response cannot overwrite an
} finally { harness.dispose() } } finally { harness.dispose() }
}) })
test('timeout retries the exact original body after reload and does not accept changed form data', async () => { test('timeout releases the form and another click submits the edited current values', async () => {
const storage = new Map(), calls = [] const calls = []
const first = viewHarness({ createPage: true, storage, api: { createProcurement: async payload => { calls.push(normalized(payload)); throw new ApiError('timeout', 'TIMEOUT') } } }) const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => { calls.push(normalized(payload)); throw new ApiError('timeout', 'TIMEOUT') } } })
try { try {
Object.assign(first.state.form, draft()); await first.state.submit(); assert.equal(calls.length, 1); assert.ok(first.state.pending.value) Object.assign(harness.state.form, draft()); await harness.state.submit()
first.state.form.productName = 'changed'; await first.state.submit(); assert.deepEqual(calls[1], calls[0]) assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
} finally { first.dispose() } harness.state.form.productName = 'changed'; await harness.state.submit()
const recovered = viewHarness({ createPage: true, storage, api: { createProcurement: async payload => { calls.push(normalized(payload)); return { order: { orderNo: 'PO-SAME' } } } } }) assert.equal(calls[1].productName, 'changed'); assert.notEqual(calls[0].idempotencyKey, calls[1].idempotencyKey)
try { assert.equal(harness.state.submitting.value, false)
assert.equal(recovered.state.form.productName, 'Test product'); await recovered.state.submit(); assert.deepEqual(calls[2], calls[0]) } finally { harness.dispose() }
assert.equal(storage.size, 0); assert.equal(recovered.pushes[0].params.orderNo, 'PO-SAME')
} finally { recovered.dispose() }
}) })
test('submission double-click sends once and definitive validation rejection permits correction', async () => { test('submission double-click sends once and definitive validation rejection permits correction', async () => {
let reject, calls = 0 let reject, calls = 0
const harness = viewHarness({ createPage: true, api: { createProcurement: () => { calls++; return new Promise((_, failure) => { reject = failure }) } } }) const harness = viewHarness({ createPage: true, api: { createProcurement: () => { calls++; return new Promise((_, failure) => { reject = failure }) } } })
try { try {
Object.assign(harness.state.form, draft()); const first = harness.state.submit(); await harness.state.submit(); assert.equal(calls, 1) 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 reject(new ApiError('invalid', 'A0422')); await first
assert.equal(harness.state.pending.value, null); assert.equal(harness.storage.size, 0) assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
} finally { harness.dispose() } } finally { harness.dispose() }
}) })
@@ -149,17 +218,105 @@ test('pagination batches one request and switching account clears old rows befor
}) })
test('replay rejection cannot discard an earlier unknown creation outcome', async () => { test('consecutive timeout and permission failures never persist or freeze a submission', async () => {
const calls = []; let attempt = 0 let attempt = 0
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => { const harness = viewHarness({ createPage: true, api: { createProcurement: async () => { throw new ApiError('failed', ++attempt === 1 ? 'TIMEOUT' : 'A0403') } } })
calls.push(normalized(payload)); attempt++
if (attempt === 1) throw new ApiError('timeout', 'TIMEOUT')
throw new ApiError('permission revoked', 'A0403')
} } })
try { try {
Object.assign(harness.state.form, draft()); await harness.state.submit() Object.assign(harness.state.form, draft()); await harness.state.submit(); await harness.state.submit()
const saved = [...harness.storage.values()][0]; await harness.state.submit() assert.equal(attempt, 2); assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
assert.equal([...harness.storage.values()][0], saved); assert.ok(harness.state.pending.value) harness.state.form.productName = 'editable'; assert.equal(harness.state.form.productName, 'editable')
assert.deepEqual(calls[1], calls[0])
} finally { harness.dispose() } } 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('customer confirms with current workflow version and double-click only sends once', async () => {
let resolve, calls = []
const harness = viewHarness({ detailPage: true, api: { confirmProcurement: (orderNo, payload) => {
calls.push({ orderNo, ...payload }); return new Promise(done => { resolve = done })
} } })
try {
await flush()
const first = harness.state.confirmReceived(); await flush(); await harness.state.confirmReceived()
assert.equal(calls.length, 1); assert.equal(calls[0].version, 1); assert.equal(calls[0].orderNo, 'PO-1')
assert.ok(calls[0].idempotencyKey)
resolve({ orderNo: 'PO-1', version: 2, status: 'CONFIRMED' }); await first
assert.equal(harness.state.workflow.value.status, 'CONFIRMED'); assert.equal(harness.state.canConfirm.value, false)
} finally { harness.dispose() }
})
test('failed customer confirmation preserves receipt context for recovery', async () => {
const harness = viewHarness({ detailPage: true, api: { confirmProcurement: async () => { throw new ApiError('版本已更新,请刷新', 'A0409') } } })
try {
await flush(); await harness.state.confirmReceived()
assert.equal(harness.state.workflow.value.status, 'WAIT_CUSTOMER_CONFIRM')
assert.equal(harness.state.confirming.value, false); assert.equal(harness.state.confirmError.value, '版本已更新,请刷新')
} finally { harness.dispose() }
})
test('unknown create and confirmation results reuse idempotency keys for unchanged retries', async () => {
const creates = [], confirms = []
const create = viewHarness({ createPage: true, api: { createProcurement: async payload => { creates.push(payload); throw new ApiError('timeout', 'TIMEOUT') } } })
const confirm = viewHarness({ detailPage: true, api: { confirmProcurement: async (_, payload) => { confirms.push(payload); throw new ApiError('timeout', 'TIMEOUT') } } })
try {
Object.assign(create.state.form, draft()); await create.state.submit(); await create.state.submit()
assert.equal(creates[0].idempotencyKey, creates[1].idempotencyKey)
await flush(); await confirm.state.confirmReceived(); await confirm.state.confirmReceived()
assert.equal(confirms[0].idempotencyKey, confirms[1].idempotencyKey)
} finally { create.dispose(); confirm.dispose() }
})
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('insufficient balance and credit blocks procurement creation and preserves the draft', async () => {
let creates = 0
const harness = viewHarness({ createPage: true, api: { requireOrderBudget: async () => { throw new Error('余额及授信不足') }, createProcurement: async () => { creates++ } } })
try {
Object.assign(harness.state.form, draft()); await harness.state.submit()
assert.equal(creates, 0); assert.equal(harness.state.submitError.value, '余额及授信不足')
assert.equal(harness.state.form.productName, draft().productName)
} finally { harness.dispose() }
})
test('customer rejection requires a reason and carries current order version', async () => {
const calls = []
const harness = viewHarness({ detailPage: true, api: { rejectProcurement: async (orderNo, command) => { calls.push({ orderNo, ...command }); return { orderNo, status: 'RECEIVING', version: 2, rejectionReason: command.reason } } } })
try {
await flush(); await harness.state.rejectReceived()
assert.equal(calls.length, 1); assert.equal(calls[0].orderNo, 'PO-1'); assert.equal(calls[0].version, 1)
assert.equal(calls[0].reason, '照片不清晰'); assert.equal(harness.state.workflow.value.status, 'RECEIVING')
} finally { harness.dispose() }
const blank = viewHarness({ detailPage: true, api: { rejectionReason: ' ', rejectProcurement: async () => { throw new Error('不得发送空原因') } } })
try { await flush(); await blank.state.rejectReceived(); assert.match(blank.state.confirmError.value, /请填写驳回原因/) }
finally { blank.dispose() }
})
@@ -1,21 +1,20 @@
import type { Amount, ProcurementCreate, ProcurementFee } from './api/procurement' import type { Amount, ProcurementCreate, ProcurementFee } from './api/procurement'
export const procurementStatuses: Record<string, string> = { export const procurementStatuses: Record<string, string> = {
PENDING_REVIEW: '待审核', WAIT_PURCHASE: '待购买', WAIT_OVERSEAS_RECEIPT: '待海外到仓', OVERSEAS_RECEIVING: '海外收货中', PENDING_REVIEW: '待审核', RECEIVING: '收货中', WAIT_CUSTOMER_CONFIRM: '待客户确认', CONFIRMED: '已确认',
WAIT_PACKING: '待装箱', WAIT_LABELS: '待面单及预估处理', WAIT_OVERSEAS_SHIPMENT: '待海外交寄', INTERNATIONAL_TRANSIT: '国际运输中', IN_TRANSIT: '运输中', DELIVERING: '派送中', COMPLETED: '签收完成',
DOMESTIC_RECEIVING: '国内收货中', WAIT_CHARGES: '待国内核费', WAIT_CUSTOMER_SHIPMENT: '待寄客户', SHIPPED_TO_CUSTOMER: '已寄客户', REJECTED: '已拒绝', CANCELLED: '已取消',
REJECTED: '已拒绝', CANCELLED: '已取消', EXCEPTION_CLOSED: '异常关闭',
} }
export const feePurposes: Record<string, string> = { export const feePurposes: Record<string, string> = {
SAMPLE_PAYMENT: '样品货款', INTERNATIONAL_ESTIMATE: '预估国际运费', INTERNATIONAL_FREIGHT: '实际国际运费', SAMPLE_PAYMENT: '样品货款', INTERNATIONAL_ESTIMATE: '预估国际运费', INTERNATIONAL_FREIGHT: '实际国际运费',
DUTY: '关税', DOMESTIC_FREIGHT: '国内运费', OTHER: '其他费用', ADJUSTMENT: '追加费用', REFUND: '退款', DUTY: '关税', DOMESTIC_FREIGHT: '国内运费', OTHER: '其他费用', ADJUSTMENT: '追加费用', REFUND: '退款',
} }
export function statusLabel(status: string | null | undefined) { return status ? procurementStatuses[status] || '待核对进度' : '—' } 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' { export function statusTone(status: string | null | undefined): 'success' | 'warning' | 'danger' | 'info' | 'primary' {
if (status === 'SHIPPED_TO_CUSTOMER') return 'success' if (status === 'COMPLETED' || status === 'CONFIRMED') return 'success'
if (status === 'REJECTED' || status === 'EXCEPTION_CLOSED') return 'danger' if (status === 'REJECTED') return 'danger'
if (status === 'CANCELLED') return 'info' if (status === 'CANCELLED') return 'info'
if (status === 'INTERNATIONAL_TRANSIT') return 'primary' if (status === 'IN_TRANSIT' || status === 'DELIVERING') return 'primary'
return 'warning' return 'warning'
} }
function cents(value: Amount | null | undefined): bigint | null { function cents(value: Amount | null | undefined): bigint | null {
@@ -46,6 +45,12 @@ export function productHref(value: string | null | undefined) {
try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) ? url.href : undefined } catch { 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) { 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') { if (fee.purpose === 'INTERNATIONAL_ESTIMATE') {
const label: Record<string, string> = { FROZEN: '已冻结,未扣款', ZERO: '零预估已确认', SETTLED: '原预估已结清', RELEASED: '预估已释放' } const label: Record<string, string> = { FROZEN: '已冻结,未扣款', ZERO: '零预估已确认', SETTLED: '原预估已结清', RELEASED: '预估已释放' }
if (fee.walletStatus && label[fee.walletStatus]) return label[fee.walletStatus] if (fee.walletStatus && label[fee.walletStatus]) return label[fee.walletStatus]
@@ -58,6 +63,8 @@ export function feeStatus(fee: ProcurementFee) {
return fee.walletStatus ? labels[fee.walletStatus] || '待核定' : '待核定' return fee.walletStatus ? labels[fee.walletStatus] || '待核定' : '待核定'
} }
export function feeTone(fee: ProcurementFee): 'success' | 'warning' | 'danger' | 'info' { 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 (fee.walletStatus?.endsWith('_FAILED')) return 'danger'
if (['SETTLED', 'REFUNDED', 'ZERO', 'NOT_APPLICABLE', 'RELEASED'].includes(fee.walletStatus || '')) return 'success' if (['SETTLED', 'REFUNDED', 'ZERO', 'NOT_APPLICABLE', 'RELEASED'].includes(fee.walletStatus || '')) return 'success'
if (fee.walletStatus === 'TERMINATED') return 'info' if (fee.walletStatus === 'TERMINATED') return 'info'
@@ -79,6 +86,7 @@ export function feeTotals(fees: ProcurementFee[]) {
return { paid: decimal(paid), refunded: decimal(refunded), net: decimal(paid - refunded), estimatedHold: decimal(estimatedHold) } return { paid: decimal(paid), refunded: decimal(refunded), net: decimal(paid - refunded), estimatedHold: decimal(estimatedHold) }
} }
export interface ProcurementDraft { export interface ProcurementDraft {
procurementDirection?: ProcurementDirection
purchaseCategory: string purchaseCategory: string
productName: string productName: string
productSpecification: string productSpecification: string
@@ -92,7 +100,7 @@ export interface ProcurementDraft {
remark: string remark: string
} }
export function emptyProcurementDraft(): ProcurementDraft { export function emptyProcurementDraft(): ProcurementDraft {
return { purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: '1', budgetUnitPrice: '', currency: 'USD', receivingAddress: '', contactName: '', contactPhone: '', remark: '' } return { procurementDirection: 'OVERSEAS_TO_DOMESTIC', purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: '1', budgetUnitPrice: '', currency: 'USD', receivingAddress: '', contactName: '', contactPhone: '', remark: '' }
} }
export function draftBudgetTotal(draft: ProcurementDraft) { export function draftBudgetTotal(draft: ProcurementDraft) {
const price = cents(draft.budgetUnitPrice) const price = cents(draft.budgetUnitPrice)
@@ -101,11 +109,12 @@ export function draftBudgetTotal(draft: ProcurementDraft) {
} }
export function buildProcurementCreate(draft: ProcurementDraft, customerName: string, key: string): ProcurementCreate { export function buildProcurementCreate(draft: ProcurementDraft, customerName: string, key: string): ProcurementCreate {
for (const [field, label, max] of [ for (const [field, label, max] of [
['purchaseCategory', '采购品类', 128], ['productName', '商品名称', 255], ['receivingAddress', '完整国内收货地址', 1000], ['productName', '商品名称', 255], ['receivingAddress', '完整目的地收货地址', 1000],
['contactName', '最终收件人', 128], ['contactPhone', '联系电话', 64], ['contactName', '最终收件人', 128], ['contactPhone', '联系电话', 64],
] as const) { ] as const) {
if (!draft[field].trim() || draft[field].trim().length > max) throw new Error(`请填写有效的${label}`) 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 (!customerName.trim()) throw new Error('当前企业信息尚未加载,请刷新登录信息后重试')
if (!/^\d+$/.test(draft.purchaseQuantity) || !Number.isSafeInteger(Number(draft.purchaseQuantity)) || Number(draft.purchaseQuantity) <= 0) 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) const price = cents(draft.budgetUnitPrice)
@@ -115,9 +124,20 @@ export function buildProcurementCreate(draft: ProcurementDraft, customerName: st
if (!/^[+0-9][0-9 ()-]{5,63}$/.test(draft.contactPhone.trim())) throw new Error('请填写快递可联系的电话号码,微信或邮箱不能代替电话') if (!/^[+0-9][0-9 ()-]{5,63}$/.test(draft.contactPhone.trim())) throw new Error('请填写快递可联系的电话号码,微信或邮箱不能代替电话')
if (draft.productUrl && (!productHref(draft.productUrl.trim()) || draft.productUrl.trim().length > 2000)) throw new Error('商品链接须为有效的 http 或 https 地址') if (draft.productUrl && (!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.productSpecification.length > 500 || draft.remark.length > 1000) throw new Error('商品规格或备注超过长度限制')
return { customerName: customerName.trim(), purchaseCategory: draft.purchaseCategory.trim(), productName: draft.productName.trim(), 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, productSpecification: draft.productSpecification.trim() || undefined, productUrl: draft.productUrl.trim() || undefined,
purchaseQuantity: Number(draft.purchaseQuantity), budgetUnitPrice: Number(decimal(price)), currency: draft.currency, purchaseQuantity: Number(draft.purchaseQuantity), budgetUnitPrice: Number(decimal(price)), currency: draft.currency,
receivingAddress: draft.receivingAddress.trim(), contactName: draft.contactName.trim(), contactPhone: draft.contactPhone.trim(), receivingAddress: draft.receivingAddress.trim(), contactName: draft.contactName.trim(), contactPhone: draft.contactPhone.trim(),
remark: draft.remark.trim() || undefined, idempotencyKey: key } 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
}
@@ -1,23 +1,3 @@
import type { ProcurementCreate } from './api/procurement'
import { buildProcurementCreate, emptyProcurementDraft } from './procurementPresentation'
/** Restore the exact request; an unknown result cannot become a new order. */
export function restoreProcurementSubmission(raw: string): ProcurementCreate {
const saved: unknown = JSON.parse(raw)
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) throw new Error('提交记录格式错误')
const value = saved as Record<string, unknown>
for (const key of ['customerName', 'purchaseCategory', 'productName', 'currency', 'receivingAddress', 'contactName', 'contactPhone', 'idempotencyKey']) if (typeof value[key] !== 'string') throw new Error('提交记录不完整')
if (typeof value.purchaseQuantity !== 'number' || typeof value.budgetUnitPrice !== 'number' || !String(value.idempotencyKey).trim() || String(value.idempotencyKey).length > 255) throw new Error('提交记录不完整')
for (const key of ['productSpecification', 'productUrl', 'remark']) if (value[key] !== undefined && typeof value[key] !== 'string') throw new Error('提交记录不完整')
if (value.currency !== 'CNY' && value.currency !== 'USD') throw new Error('提交记录币种无效')
return buildProcurementCreate({ ...emptyProcurementDraft(), purchaseCategory: String(value.purchaseCategory), productName: String(value.productName),
productSpecification: String(value.productSpecification || ''), productUrl: String(value.productUrl || ''), purchaseQuantity: String(value.purchaseQuantity),
budgetUnitPrice: String(value.budgetUnitPrice), currency: value.currency, receivingAddress: String(value.receivingAddress), contactName: String(value.contactName),
contactPhone: String(value.contactPhone), remark: String(value.remark || '') }, String(value.customerName), String(value.idempotencyKey))
}
export function definitelyRejected(error: { code?: string; status?: number }) {
return ['A0400', 'A0401', 'A0403', 'A0422'].includes(error.code || '') || [400, 401, 403, 422].includes(error.status || 0)
}
export function procurementRequestKey(provider: Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>> = globalThis.crypto) { export function procurementRequestKey(provider: Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>> = globalThis.crypto) {
if (provider.randomUUID) return provider.randomUUID() if (provider.randomUUID) return provider.randomUUID()
return `proc-${Array.from(provider.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('')}` return `proc-${Array.from(provider.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('')}`
@@ -0,0 +1,63 @@
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, transportDemandError, buildTransportDemand } = runInNewContext(`${code}\n({ createTransportDemandForm, transportDemandError, buildTransportDemand })`)
const valid = () => ({ ...createTransportDemandForm(), vehicleType: 'PALLET_15', estimatedPalletCount: 3, budgetAmount: 100, origin: ' LA ', 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('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)
})
@@ -0,0 +1,116 @@
import type { FormRules } from 'element-plus'
export type TransportDemandKind = 'truck' | 'looseboard'
export interface TransportDemandForm {
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 {
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) => ({
origin: kind === 'truck' ? '取货地' : '起运地',
destination: kind === 'truck' ? '送达地' : '目的地',
originContactName: kind === 'truck' ? '取货联系人' : '起运地联系人',
originContactPhone: 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)
for (const [field, label] of Object.entries(labels)) {
rules[field as keyof typeof labels] = [{ required: true, whitespace: true, message: `请输入${label}`, trigger: 'blur' }]
}
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 === 'truck' && !['PALLET_15', 'PALLET_30'].includes(form.vehicleType)) return '请选择车辆类型'
const labels = requiredText(kind)
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 & { 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) {
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, productName: form.productName.trim() || undefined, estimatedPalletCount: form.estimatedPalletCount }
}
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue' import { computed, onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus' import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ApiError } from '@/api/types' import { ApiError } from '@/api/types'
import { accessTokenIdentity } from '@/api/session' import { accessTokenIdentity } from '@/api/session'
import { useAuthStore } from '@/modules/auth/public' import { useAuthStore } from '@/modules/auth/public'
@@ -9,9 +9,10 @@ import DataTable, { type DataTableColumn } from '@/components/common/DataTable.v
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue' import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
import type { TableAction } from '@/components/common/tableActions' import type { TableAction } from '@/components/common/tableActions'
import ProcurementDetailPanel from '../components/ProcurementDetailPanel.vue' import ProcurementDetailPanel from '../components/ProcurementDetailPanel.vue'
import { createProcurement, getProcurement, listProcurements, type ProcurementCreate, type ProcurementDetail, type ProcurementSummary } from '../api/procurement' import { rejectProcurement, confirmProcurement, createProcurement, getProcurement, getProcurementWorkflow, listProcurements, type ProcurementDetail, type ProcurementSummary, type ProcurementWorkflow } from '../api/procurement'
import { buildProcurementCreate, dateTime, draftBudgetTotal, emptyProcurementDraft, money, procurementStatuses, statusLabel, statusTone } from '../procurementPresentation' import { procurementDirections, directionLabel, regionText, buildProcurementCreate, dateTime, draftBudgetTotal, emptyProcurementDraft, money, procurementStatuses, statusLabel, statusTone } from '../procurementPresentation'
import { definitelyRejected, procurementRequestKey, restoreProcurementSubmission } from '../procurementSubmission' import { requireOrderBudget } from '../api/orderBudgets'
import { procurementRequestKey } from '../procurementSubmission'
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false }) const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
const auth = useAuthStore(), route = useRoute(), router = useRouter() const auth = useAuthStore(), route = useRoute(), router = useRouter()
@@ -20,16 +21,34 @@ const orderNo = computed(() => typeof route.params.orderNo === 'string' ? route.
const canCreate = computed(() => auth.hasPermission('merchant:cross-border:procurement:create')) const canCreate = computed(() => auth.hasPermission('merchant:cross-border:procurement:create'))
const canList = computed(() => auth.hasPermission('merchant:cross-border:procurement:list')) const canList = computed(() => auth.hasPermission('merchant:cross-border:procurement:list'))
const identity = computed(() => auth.token ? accessTokenIdentity(auth.token) : null) const identity = computed(() => auth.token ? accessTokenIdentity(auth.token) : null)
const storageKey = computed(() => identity.value ? `cc-procurement-submit:${encodeURIComponent(identity.value)}` : null)
const companyName = computed(() => auth.profile.tenantName || (auth.user?.tenantName && !/^企业租户 \d+$/.test(auth.user.tenantName) ? auth.user.tenantName : '')) const companyName = computed(() => auth.profile.tenantName || (auth.user?.tenantName && !/^企业租户 \d+$/.test(auth.user.tenantName) ? auth.user.tenantName : ''))
const form = reactive(emptyProcurementDraft()) const form = reactive(emptyProcurementDraft())
const pending = shallowRef<ProcurementCreate | null>(null) const formRef = ref<FormInstance>()
const recoveryError = ref(''), submitError = ref(''), submittedOrder = ref('') const formRules: FormRules<typeof form> = {
procurementDirection: [{ required: true, message: '请选择采购方向', trigger: 'change' }],
productName: [{ 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 submitting = ref(false), loading = ref(false), error = ref('')
const detail = shallowRef<ProcurementDetail | null>(null) const detail = shallowRef<ProcurementDetail | null>(null)
const workflow = shallowRef<ProcurementWorkflow | null>(null)
const confirming = ref(false), confirmError = ref('')
const canConfirm = computed(() => canCreate.value && workflow.value?.status === 'WAIT_CUSTOMER_CONFIRM')
const rows = ref<ProcurementSummary[]>([]), total = ref(0) const rows = ref<ProcurementSummary[]>([]), total = ref(0)
const query = reactive({ page: 1, size: 20, orderNo: '', purchaseCategory: '', productName: '', status: '' }) const query = reactive({ page: 1, size: 20, orderNo: '', purchaseCategory: '', productName: '', status: '' })
let requestSequence = 0, active = true, inFlight = '' let requestSequence = 0, active = true, inFlight = ''
let createAttempt: { fingerprint: string; key: string } | null = null
let confirmAttempt: { fingerprint: string; key: string } | null = null
const queryModel = computed<QueryModel>({ const queryModel = computed<QueryModel>({
get: () => ({ orderNo: query.orderNo, purchaseCategory: query.purchaseCategory, productName: query.productName, status: query.status }), 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] || '') }, set: value => { for (const key of ['orderNo', 'purchaseCategory', 'productName', 'status'] as const) query[key] = String(value[key] || '') },
@@ -41,6 +60,7 @@ const queryFields: QueryField[] = [
] ]
const columns: DataTableColumn[] = [ const columns: DataTableColumn[] = [
{ key: 'actions', label: '操作', width: 90, fixed: 'left', slotName: 'actions' }, { key: 'actions', label: '操作', width: 90, fixed: 'left', slotName: 'actions' },
{ prop: 'procurementDirection', label: '采购方向', minWidth: 170, slotName: 'direction' },
{ prop: 'orderNo', label: '采购单号', minWidth: 250, slotName: 'orderNo' }, { prop: 'orderNo', label: '采购单号', minWidth: 250, slotName: 'orderNo' },
{ prop: 'purchaseCategory', label: '采购品类', width: 120 }, { prop: 'productName', label: '商品名称', minWidth: 200 }, { prop: 'purchaseCategory', label: '采购品类', width: 120 }, { prop: 'productName', label: '商品名称', minWidth: 200 },
{ prop: 'productSpecification', label: '商品规格', minWidth: 160 }, { prop: 'purchaseQuantity', label: '采购数量(件)', width: 135 }, { prop: 'productSpecification', label: '商品规格', minWidth: 160 }, { prop: 'purchaseQuantity', label: '采购数量(件)', width: 135 },
@@ -67,50 +87,73 @@ async function loadDetail() {
if (!orderNo.value) { error.value = '采购单号缺失'; return } if (!orderNo.value) { error.value = '采购单号缺失'; return }
const key = JSON.stringify([identity.value, orderNo.value]) const key = JSON.stringify([identity.value, orderNo.value])
if (inFlight === key) return if (inFlight === key) return
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''; detail.value = null const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''; detail.value = null; workflow.value = null
try { const result = await getProcurement(orderNo.value); if (sequence === requestSequence) detail.value = result } 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) } catch (cause) { if (sequence === requestSequence) error.value = message(cause) }
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } } finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
} }
async function confirmReceived() {
if (!canConfirm.value || confirming.value || !workflow.value) return
const owner = identity.value, targetOrder = orderNo.value, version = workflow.value.version
confirming.value = true; confirmError.value = ''
try {
await ElMessageBox.confirm('确认本单收货数量及照片,确认后平台将安排出库。', '确认采购结果', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' })
if (!active || owner !== identity.value || targetOrder !== orderNo.value) return
const fingerprint = JSON.stringify([owner, targetOrder, version])
if (confirmAttempt?.fingerprint !== fingerprint) confirmAttempt = { fingerprint, key: procurementRequestKey() }
const result = await confirmProcurement(targetOrder, { version, idempotencyKey: confirmAttempt.key })
if (!active || owner !== identity.value || targetOrder !== orderNo.value) return
workflow.value = result; confirmAttempt = null
if (detail.value) detail.value = { ...detail.value, order: { ...detail.value.order, status: result.status, version: result.version } }
ElMessage.success('采购结果已确认')
} catch (cause) {
if (cause !== 'cancel' && cause !== 'close' && active && owner === identity.value && targetOrder === orderNo.value) confirmError.value = message(cause)
} finally { confirming.value = false }
}
// 驳回携带当前版本和必填原因,失败保留当前采购详情。
async function rejectReceived() {
if (!canConfirm.value || confirming.value || !workflow.value) return
const owner = identity.value, targetOrder = orderNo.value
confirming.value = true; confirmError.value = ''
try {
const answer = await ElMessageBox.prompt('请说明采购结果不符合要求的原因,平台将重新上传照片。', '驳回采购结果', { inputType: 'textarea', inputValidator: value => !!value?.trim() && value.trim().length <= 1000 || '请填写驳回原因,最多1000字', confirmButtonText: '提交驳回', cancelButtonText: '取消' })
if (!active || owner !== identity.value || targetOrder !== orderNo.value || !workflow.value) return
const result = await rejectProcurement(targetOrder, { version: workflow.value.version, idempotencyKey: procurementRequestKey(), reason: answer.value.trim() })
if (!active || owner !== identity.value || targetOrder !== orderNo.value) return
workflow.value = result; ElMessage.success('已驳回,等待平台重新上传照片')
} catch (cause) {
if (cause !== 'cancel' && cause !== 'close' && active && owner === identity.value && targetOrder === orderNo.value) confirmError.value = message(cause)
} finally { confirming.value = false }
}
function search() { if (query.page === 1) void loadList(); else query.page = 1 } 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 resetQuery() { const reload = query.page === 1; Object.assign(query, { page: 1, orderNo: '', purchaseCategory: '', productName: '', status: '' }); if (reload) void loadList() }
function populate(payload: ProcurementCreate) { function resetForm() { submitError.value = ''; submittedOrder.value = ''; Object.assign(form, emptyProcurementDraft()); formRef.value?.clearValidate(); createAttempt = null }
Object.assign(form, { purchaseCategory: payload.purchaseCategory, productName: payload.productName, productSpecification: payload.productSpecification || '', productUrl: payload.productUrl || '',
purchaseQuantity: String(payload.purchaseQuantity), budgetUnitPrice: String(payload.budgetUnitPrice), currency: payload.currency, receivingAddress: payload.receivingAddress,
contactName: payload.contactName, contactPhone: payload.contactPhone, remark: payload.remark || '' })
}
function restorePending() {
pending.value = null; recoveryError.value = ''; submitError.value = ''; submittedOrder.value = ''; Object.assign(form, emptyProcurementDraft())
if (!storageKey.value) return
try { const saved = sessionStorage.getItem(storageKey.value); if (saved) { pending.value = Object.freeze(restoreProcurementSubmission(saved)); populate(pending.value) } }
catch { recoveryError.value = '上次提交记录暂无法恢复,请先在订单列表或通过客服核对提交结果,避免重复下单。' }
}
async function submit() { async function submit() {
if (submitting.value || !canCreate.value || recoveryError.value || !storageKey.value) return if (submitting.value || !canCreate.value || !identity.value || submittedOrder.value) return
submitError.value = ''; const owner = identity.value, key = storageKey.value; const resuming = Boolean(pending.value) const owner = identity.value; submitting.value = true; submitError.value = ''
let started = false
try { try {
if (!pending.value) { if (!formRef.value || !await formRef.value.validate().catch(() => false)) return
const payload = buildProcurementCreate(form, companyName.value, procurementRequestKey())
try { sessionStorage.setItem(key, JSON.stringify(payload)) } catch { throw new Error('浏览器暂无法保留提交信息,请允许会话存储后重试') }
pending.value = Object.freeze(payload)
}
submitting.value = true; started = true
const result = await createProcurement(pending.value)
sessionStorage.removeItem(key)
if (!active || owner !== identity.value) return if (!active || owner !== identity.value) return
pending.value = null; submittedOrder.value = result.order.orderNo; ElMessage.success('采购订单已提交') const payload = buildProcurementCreate(form, companyName.value, '')
const fingerprint = JSON.stringify([owner, payload])
if (createAttempt?.fingerprint !== fingerprint) createAttempt = { fingerprint, key: procurementRequestKey() }
await requireOrderBudget('procurement', createAttempt.key, Number((payload.budgetUnitPrice * payload.purchaseQuantity).toFixed(2)), payload.currency)
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('采购订单已提交')
if (canList.value) await router.push({ name: 'cross-border-procurement-detail', params: { orderNo: result.order.orderNo } }) if (canList.value) await router.push({ name: 'cross-border-procurement-detail', params: { orderNo: result.order.orderNo } })
} catch (cause) { } catch (cause) { if (/已释放|已过期/.test(message(cause))) createAttempt = null; if (active && owner === identity.value) submitError.value = message(cause) }
if (!active || owner !== identity.value) return finally { submitting.value = false }
if (!resuming && cause instanceof ApiError && definitelyRejected(cause)) { sessionStorage.removeItem(key); pending.value = null }
submitError.value = started && pending.value ? `${message(cause)}。提交结果尚未确认,请再次确认上次提交结果。` : message(cause)
} finally { submitting.value = false }
} }
watch(() => [mode.value, orderNo.value, query.page, query.size, identity.value], (values, previous) => { watch(() => [mode.value, orderNo.value, query.page, query.size, identity.value], (values, previous) => {
if (values[4] !== previous?.[4]) { rows.value = []; total.value = 0 } if (values[4] !== previous?.[4]) { rows.value = []; total.value = 0; createAttempt = null }
++requestSequence; inFlight = ''; loading.value = false; error.value = ''; detail.value = null if (values[4] !== previous?.[4] || values[1] !== previous?.[1]) confirmAttempt = null
if (mode.value === 'create') restorePending() ++requestSequence; inFlight = ''; loading.value = false; error.value = ''; detail.value = null; workflow.value = null; confirmError.value = ''
if (mode.value === 'create') resetForm()
else if (mode.value === 'detail') void loadDetail() else if (mode.value === 'detail') void loadDetail()
else void loadList() else void loadList()
}, { immediate: true }) }, { immediate: true })
@@ -118,7 +161,7 @@ onBeforeUnmount(() => { active = false; ++requestSequence })
</script> </script>
<template> <template>
<section class="procurement-page client-ui" :aria-busy="loading || submitting"> <section class="procurement-page client-ui" :class="{ 'procurement-page--create': mode === 'create' }" :aria-busy="loading || submitting">
<template v-if="mode === 'list'"> <template v-if="mode === 'list'">
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="采购订单查询条件" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetQuery" /> <QueryToolbar v-model="queryModel" layout="grid" ariaLabel="采购订单查询条件" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetQuery" />
<div class="procurement-table-card"> <div class="procurement-table-card">
@@ -127,43 +170,80 @@ onBeforeUnmount(() => { active = false; ++requestSequence })
<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 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 #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 #budget="{ row }">{{ money((row as ProcurementSummary).budgetUnitPrice, (row as ProcurementSummary).currency) }}</template>
<template #status="{ row }"><el-tag :type="statusTone((row as ProcurementSummary).status)" size="small">{{ statusLabel((row as ProcurementSummary).status) }}</el-tag></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 #createdAt="{ row }">{{ dateTime((row as ProcurementSummary).createdAt) }}</template> <template #createdAt="{ row }">{{ dateTime((row as ProcurementSummary).createdAt) }}</template>
</DataTable> </DataTable>
</div> </div>
</template> </template>
<section v-else-if="mode === 'detail'" v-loading="loading" class="procurement-detail" aria-label="采购订单详情"> <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(detail.order.status)">{{ statusLabel(detail.order.status) }}</el-tag><el-button :disabled="loading" @click="loadDetail">刷新</el-button></div></header> <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 v-if="canConfirm" type="danger" :disabled="confirming" @click="rejectReceived">驳回</el-button><el-button v-if="canConfirm" type="primary" :loading="confirming" @click="confirmReceived">确认采购结果</el-button><el-button :disabled="loading || confirming" @click="loadDetail">刷新</el-button></div></header>
<div v-if="error" class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadDetail">重新加载</el-button></div> <div v-if="error" class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadDetail">重新加载</el-button></div>
<ProcurementDetailPanel v-else-if="detail" :detail="detail" /><el-skeleton v-else :rows="8" animated /> <template v-else-if="detail && workflow"><el-alert v-if="confirmError" :title="confirmError" type="error" :closable="false" /><el-alert v-if="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>
<section v-else class="procurement-create" aria-label="采购下单"> <section v-else class="procurement-create" aria-label="采购下单">
<header class="procurement-heading"><div><h2>海外采购下单</h2><p>一单一个商品及规格;预算仅授权样品货款,运费及关税另行核定。</p></div><el-button v-if="canList" @click="returnToList">返回列表</el-button></header> <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-if="!canCreate" icon="warning" title="没有采购下单权限" sub-title="请联系企业管理员配置权限" />
<el-result v-else-if="submittedOrder" icon="success" title="采购订单已提交" :sub-title="submittedOrder"><template #extra><el-button @click="restorePending">新建另一单</el-button></template></el-result> <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> <template v-else>
<el-alert v-if="recoveryError" :title="recoveryError" type="error" :closable="false" />
<el-alert v-else-if="pending" title="已保留本次提交内容。请再次确认上次提交结果,确认前不修改订单信息。" type="warning" :closable="false" />
<el-alert v-if="submitError" class="submit-error" :title="submitError" type="error" :closable="false" /> <el-alert v-if="submitError" class="submit-error" :title="submitError" type="error" :closable="false" />
<el-form :model="form" label-position="top" :disabled="submitting || Boolean(pending) || Boolean(recoveryError)" @submit.prevent="submit"> <section class="procurement-summary" aria-label="采购预算概览">
<h3>商品与预算</h3><div class="procurement-form-grid"> <article class="procurement-summary-card">
<el-form-item label="采购品类" required><el-input v-model.trim="form.purchaseCategory" maxlength="128" placeholder="请输入采购品类" /></el-form-item> <div class="procurement-summary-title">
<el-form-item label="商品名称" required><el-input v-model.trim="form.productName" maxlength="255" placeholder="请输入商品名称" /></el-form-item> <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>
<el-form-item label="商品规格"><el-input v-model.trim="form.productSpecification" maxlength="500" placeholder="规格、型号" /></el-form-item> <h2>采购数量</h2>
<el-form-item label="采购数量(件)" required><el-input v-model.trim="form.purchaseQuantity" inputmode="numeric" maxlength="18" placeholder="正整数" /></el-form-item> </div>
<el-form-item label="预算单价" required><el-input v-model.trim="form.budgetUnitPrice" inputmode="decimal" maxlength="20" placeholder="请明确填写;免费样品填 0" /></el-form-item> <div class="procurement-summary-value">{{ summaryQuantity }}<small>件</small></div>
<el-form-item label="预算币种" required><el-select v-model="form.currency"><el-option label="美元 USD" value="USD" /><el-option label="人民币 CNY" value="CNY" /></el-select></el-form-item> </article>
<el-form-item class="full" label="商品链接"><el-input v-model.trim="form.productUrl" maxlength="2000" placeholder="https://…" /></el-form-item> <article class="procurement-summary-card">
</div><p class="procurement-hint">货款预算总上限:<strong>{{ money(draftBudgetTotal(form), form.currency) }}</strong>。零预算仅授权免费样品;实际货款按供应商实付核定。</p> <div class="procurement-summary-title">
<h3>最终国内收件资料</h3><div class="procurement-form-grid"> <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>
<el-form-item label="收件人" required><el-input v-model.trim="form.contactName" maxlength="128" placeholder="实际收件人姓名" /></el-form-item> <h2>预算单价</h2>
<el-form-item label="联系电话" required><el-input v-model.trim="form.contactPhone" maxlength="64" type="tel" placeholder="快递可联系的电话" /></el-form-item> </div>
<el-form-item label="下单企业"><el-input :model-value="companyName" disabled /></el-form-item> <div class="procurement-summary-value">{{ summaryUnitPrice }}</div>
<el-form-item class="full" label="完整国内地址" required><el-input v-model.trim="form.receivingAddress" maxlength="1000" placeholder="省、市、区县、街道及详细门牌" /></el-form-item> </article>
<el-form-item class="full" label="采购要求"><el-input v-model="form.remark" type="textarea" :rows="3" maxlength="1000" show-word-limit placeholder="其他采购要求(选填)" /></el-form-item> <article class="procurement-summary-card">
</div> <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"><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" 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> </el-form>
<footer class="procurement-form-actions"><el-button v-if="canList" :disabled="submitting" @click="returnToList">返回列表</el-button><el-button type="primary" :loading="submitting" :disabled="Boolean(recoveryError) || (!pending && !companyName) || !identity" @click="submit">{{ pending ? '确认上次提交结果' : '提交采购订单' }}</el-button></footer> <footer class="procurement-form-actions"><el-button v-if="canList" :disabled="submitting" @click="returnToList">返回列表</el-button><el-button type="primary" :loading="submitting" :disabled="!companyName || !identity" @click="submit">提交采购订单</el-button></footer>
</template> </template>
</section> </section>
</section> </section>
@@ -171,17 +251,72 @@ onBeforeUnmount(() => { active = false; ++requestSequence })
<style scoped> <style scoped>
.procurement-page { display: grid; gap: var(--client-section-gap); min-width: 0; } .procurement-page { display: grid; gap: var(--client-section-gap); min-width: 0; }
.procurement-table-card, .procurement-detail, .procurement-create { min-width: 0; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; } .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, .procurement-create { padding: 16px 20px 24px; } .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 { 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 > 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-create .procurement-heading > div { display: block; }.procurement-heading p { margin: 7px 0 0; font-size: 13px; color: var(--muted); } .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-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-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-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 24px; }.procurement-form-grid .full { grid-column: 1 / -1; }.procurement-form-grid :deep(.el-select) { width: 100%; } .procurement-page--create { width: 100%; background: #f4f7fc; }
.procurement-create h3 { margin: 22px 0 16px; color: var(--navy); font-size: 14px; }.procurement-hint { margin: 0 0 20px; line-height: 1.8; font-size: 13px; color: var(--muted); }.procurement-hint strong { color: var(--navy); } .procurement-create {
.procurement-form-actions { display: flex; justify-content: flex-end; gap: 12px; padding-top: 16px; border-top: 1px solid var(--border); }.submit-error { margin: 12px 0; } --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) { @media (max-width: 767px) {
.procurement-form-grid { grid-template-columns: 1fr; }.procurement-heading, .procurement-heading > div { flex-wrap: wrap; } .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> </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`。
@@ -13,8 +13,8 @@ const primaryActions = computed(() => [
{ title: '美本土散板', description: '拼车拼载 · 打盘服务 · 灵活派送', icon: Forklift, route: '/cross-border/pallet-shipping/create', permission: 'merchant:cross-border:pallet-shipping:create', tone: 'cyan', featured: false }, { title: '美本土散板', description: '拼车拼载 · 打盘服务 · 灵活派送', icon: Forklift, route: '/cross-border/pallet-shipping/create', permission: 'merchant:cross-border:pallet-shipping:create', tone: 'cyan', featured: false },
{ title: '海外采购', description: '采购代购 · 验货质检 · 集中发货', icon: ShoppingCart, route: '/cross-border/procurement/create', permission: 'merchant:cross-border:procurement:create', tone: 'orange', featured: false }, { title: '海外采购', description: '采购代购 · 验货质检 · 集中发货', icon: ShoppingCart, route: '/cross-border/procurement/create', permission: 'merchant:cross-border:procurement:create', tone: 'orange', featured: false },
{ title: '贴标申请', description: '产品建档 · 标签上传 · 批量贴标', icon: Tags, route: '/overseas-warehouse/labeling/create', permission: 'merchant:overseas-warehouse:relabel:create', tone: 'rose', featured: false }, { 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', permission: 'merchant:overseas-warehouse:transfer:list', tone: 'teal', featured: false, actionLabel: '开始办理' }, { 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', permission: 'merchant:overseas-warehouse:discard:list', tone: 'brown', featured: false, actionLabel: '开始办理' }, { title: '货物废弃', description: '废弃申请 · 处理进度', icon: PackageOpen, route: '/overseas-warehouse/cargo-disposal/create', permission: 'merchant:overseas-warehouse:discard:create', tone: 'brown', featured: false, actionLabel: '开始办理' },
].filter((action) => auth.hasPermission(action.permission))) ].filter((action) => auth.hasPermission(action.permission)))
</script> </script>
@@ -23,7 +23,7 @@ const primaryActions = computed(() => [
<div class="client-dashboard"> <div class="client-dashboard">
<header class="business-intro"> <header class="business-intro">
<h1>选择业务,快速下单</h1> <h1>选择业务,快速下单</h1>
<p>请选择您需要的业务类型,填写信息后提交订单,我们将尽快为您安排。</p>
</header> </header>
<section class="quick-actions" aria-label="业务选择"> <section class="quick-actions" aria-label="业务选择">
+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`。
+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
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
@@ -151,6 +151,7 @@ export interface MerchantTransportFragment {
} }
export interface MerchantUnifiedOrderDetail { export interface MerchantUnifiedOrderDetail {
progress: MerchantOrderProgress
transportFragments: MerchantTransportFragment[] transportFragments: MerchantTransportFragment[]
summary: MerchantUnifiedOrderRow summary: MerchantUnifiedOrderRow
order: MerchantFirstLegOrderDetail order: MerchantFirstLegOrderDetail
@@ -2,6 +2,7 @@
import { computed, nextTick, onBeforeUnmount, 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,
@@ -329,7 +330,7 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
<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
@@ -367,7 +368,7 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
<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="选择资料关联入仓码">
@@ -382,7 +383,7 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
<section class="customs-section clearance-results-section"> <section class="customs-section clearance-results-section">
<div class="customs-section-title"> <div class="customs-section-title">
<div><h3>海关申报结果</h3><p>平台完成正式申报后,客户可查看与本订单相关的查验、补充资料和放行结果。</p></div> <h3>海关申报结果</h3>
</div> </div>
<div v-if="clearanceError" class="customs-error" role="alert"> <div v-if="clearanceError" class="customs-error" role="alert">
<strong>海关申报结果加载失败</strong> <strong>海关申报结果加载失败</strong>
@@ -402,7 +403,7 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
<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> </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">
@@ -442,47 +443,52 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
</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; } :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), :global(.customs-documents-dialog .el-dialog__footer) { flex: 0 0 auto; } :global(.customs-documents-dialog .el-dialog__header) { flex: 0 0 auto; }
:global(.customs-documents-dialog .el-dialog__body) { min-height: 0; flex: 1 1 auto; overflow-y: auto; overscroll-behavior: contain; } :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 :deep(.el-empty) { padding: 20px 0; }
.clearance-result-list { display:grid; gap:10px; } .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 { 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 strong,.clearance-result-row span { display:block; }
.clearance-result-row span { margin-top:4px; color:var(--muted); font-size:11px; } .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; } .clearance-result-row p { grid-column:1 / -1; margin:0; color:var(--navy); font-size:12px; }
.customs-section-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 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-help-heading { display: flex; align-items: center; gap: 4px; }
.customs-inbound-options { display: flex; flex-wrap: wrap; gap: 8px 18px; padding: 13px 15px; border: 1px solid var(--border); } .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>
@@ -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,7 +51,7 @@ 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'\)"/)
}) })
@@ -30,32 +61,67 @@ test('shows the published merchant inbound, measurement details and customer con
} }
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, /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/)
assert.match(source, /latestFee\.ruleCode/) assert.doesNotMatch(source, /latestFee\.(feeVersion|ruleCode|rateCode|chargeRuleVersion|carrierRateVersion|sentAt)/)
assert.match(source, /latestFee\.rateCode/)
assert.match(source, /latestFee\.chargeRuleVersion/)
assert.match(source, /latestFee\.carrierRateVersion/)
assert.match(source, /箱规规则/) assert.match(source, /箱规规则/)
assert.match(source, /getCalculationRuleLabel\(row\.calculationRuleVersion\)/) assert.match(source, /getCalculationRuleLabel\(row\.calculationRuleVersion\)/)
}) })
test('matches the confirmed billing prototype summary, table, notice and footer', () => { test('keeps the billing summary, confirmation table, notice and footer', () => {
assert.match(source, /width="min\(1180px, calc\(100vw - 40px\)\)"/) assert.match(source, /width="min\(1180px, calc\(100vw - 40px\)\)"/)
assert.match(source, /class="fee-dialog-summary" aria-label="计费汇总"/) assert.match(source, /class="fee-dialog-summary" aria-label="计费汇总"/)
for (const label of ['计算重', '单价', '总金额', '箱规长(cm)', '箱规宽(cm)', '箱规高(cm)', '每箱体积', '总体积', '总材积重']) assert.ok(source.includes(label), `missing prototype label: ${label}`) for (const label of ['计算重', '单价', '总金额', '计费毛重', '计费体积', '计费方式', '最终计费量']) assert.ok(confirmationBody.includes(label), `missing billing label: ${label}`)
assert.match(source, /class="fee-confirm-notice"/) assert.match(source, /class="fee-confirm-notice"/)
assert.match(source, /请核对计算重、单价和总金额。确认后当前费用版本将锁定。/) assert.match(source, /请核对计费毛重、计费体积、计费量、单价和总金额。确认后当前费用版本将锁定。/)
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-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\)/) 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: 570.5, actualVolumeCbm: 3.6894,
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, /570\.5 kg/)
assert.match(html, /3\.6894 m³/)
assert.match(html, /616\.13 kg/)
assert.match(html, /8,379\.37/)
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,
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', () => {
assert.match(source, /@media \(max-width: 720px\)/) assert.match(source, /@media \(max-width: 720px\)/)
assert.match(source, /\.inbound-overview, \.inbound-measurements, \.fee-calculation-grid \{ grid-template-columns: 1fr;/) assert.match(source, /\.inbound-overview, \.inbound-measurements, \.fee-calculation-grid \{ grid-template-columns: 1fr;/)
@@ -77,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>
@@ -160,7 +160,7 @@ async function confirmFee() {
<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) }} · {{ getTaxModeLabel(props.data.latestFee.taxMode) }}</dd></div>
@@ -172,8 +172,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>
@@ -183,11 +183,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">
@@ -198,42 +196,36 @@ async function confirmFee() {
</section> </section>
<el-dialog v-model="feeDialogOpen" class="billing-confirm-dialog" title="确认测量与计费数据" width="min(1180px, calc(100vw - 40px))" 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="fee-dialog-summary" aria-label="计费汇总"> <dl class="fee-dialog-summary" aria-label="计费汇总">
<div><dt>计算重</dt><dd>{{ formatInboundMeasure(props.data.billingBasis.chargeableWeightKg, 'kg') }}</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>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit.toUpperCase() }}</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>{{ formatInboundMoney(props.data.latestFee.totalAmount, 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 class="measurement-detail-table fee-dialog-table" :data="props.data.measurementItems" border empty-text="暂无箱规测量明细"> <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) }}</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 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> </el-table>
<div class="fee-confirm-notice" :class="{ 'is-confirmed': props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' }" role="status"> <div class="fee-confirm-notice" :class="{ 'is-confirmed': props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' }" role="status">
<CircleAlert :size="21" aria-hidden="true" /> <CircleAlert :size="21" aria-hidden="true" />
<span v-if="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED'">客户已于 {{ formatInboundDateTime(props.data.latestFee.customerConfirmedAt) }} 确认,费用已锁定,不允许修改。</span> <span v-if="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED'">客户已于 {{ formatInboundDateTime(props.data.latestFee.customerConfirmedAt) }} 确认,费用已锁定,不允许修改。</span>
<span v-else>请核对计算重、单价和总金额。确认后当前费用版本将锁定。</span> <span v-else>请核对计费毛重、计费体积、计费量、单价和总金额。确认后当前费用版本将锁定。</span>
</div> </div>
</template> </template>
<template #footer> <template #footer>
@@ -283,7 +275,7 @@ async function confirmFee() {
.fee-dialog-table { margin-top:16px; overflow:hidden; border-radius:10px; box-shadow:0 5px 18px rgba(51,65,85,.04); } .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__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.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(7)), .fee-dialog-table :deep(.el-table__body td:nth-child(8)) { color:#34466b; font-weight:650; } .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-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 { 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 > svg { flex:0 0 auto; fill:#eda332; color:#fff; filter:drop-shadow(0 2px 3px rgba(233,154,37,.25)); }
@@ -305,9 +297,7 @@ 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; }
@@ -345,6 +335,5 @@ async function confirmFee() {
.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>
@@ -26,14 +26,14 @@ function stageState(index: number) {
</div> </div>
</div> </div>
<p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消,不再继续履约。</p> <p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消</p>
<ol v-else class="progress-stages" aria-label="订单主状态阶段"> <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> <div v-if="order.status !== 'CANCELLED'" class="progress-cabinet-detail"><slot name="cabinet" /></div>
</section> </section>
</template> </template>
@@ -21,7 +21,7 @@ function time(value: string | null) { return value ? value.replace('T', ' ') : '
<el-table-column prop="location" label="地点" min-width="130" /> <el-table-column prop="location" label="地点" min-width="130" />
<el-table-column prop="source" label="来源" width="105" /> <el-table-column prop="source" label="来源" width="105" />
</el-table> </el-table>
<p v-else>暂无实际装载片段的运输节点。预计时间不表示实际发生。</p> <p v-else>暂无运输节点</p>
</div> </div>
</template> </template>
@@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs'
import ts from 'typescript' import ts from 'typescript'
import * as vue from 'vue' import * as vue from 'vue'
import * as pinia from 'pinia' import * as pinia from 'pinia'
import { requireOrderProgress } from '../utils/orderProgress.ts'
function compile(path, dependencies) { function compile(path, dependencies) {
const source = readFileSync(new URL(path, import.meta.url), 'utf8') const source = readFileSync(new URL(path, import.meta.url), 'utf8')
@@ -31,10 +32,11 @@ function harness(t) {
vue, pinia, vue, pinia,
'@/modules/first-leg/api/firstLeg': api, '@/modules/first-leg/api/firstLeg': api,
'@/modules/first-leg/api/unifiedOrders': { '@/modules/first-leg/api/unifiedOrders': {
getMerchantUnifiedOrder: async () => ({ summary: { orderId: 'one', mainStatus: null }, order: { order: { id: 'one', status: behavior.status, version: behavior.version, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress } }, timeline: [] }), getMerchantUnifiedOrder: async () => ({ progress: { orderId: 'one', stage: 'none', partial: false }, summary: { orderId: 'one', mainStatus: null }, order: { order: { id: 'one', status: behavior.status, version: behavior.version, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress } }, timeline: [] }),
}, },
'@/modules/first-leg/utils/firstLegOrder': { canClientEditFirstLegOrder: status => status === 'DRAFT', getFirstLegStatusLabel: value => value }, '@/modules/first-leg/utils/firstLegOrder': { canClientEditFirstLegOrder: status => status === 'DRAFT', getFirstLegStatusLabel: value => value },
'@/modules/first-leg/utils/warehousePagination': {}, '@/modules/first-leg/utils/warehousePagination': {},
'@/modules/first-leg/utils/orderProgress': { requireOrderProgress },
}) })
const store = module.useFirstLegOrdersStore() const store = module.useFirstLegOrdersStore()
store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC' }] store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC' }]
@@ -126,41 +128,25 @@ test('cancelled detail summary has no pending overseas synchronization entries',
assert.deepEqual(summary, []) assert.deepEqual(summary, [])
}) })
test('edit freezes detail version rather than cached list version and replays same key/body after uncertain result', async t => { test('edit preserves the detail version but generates a fresh command after failure', async t => {
const h = harness(t) const h = harness(t), session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
const original = await h.store.loadDraftDetail('one') h.store.orders = [{ id: 'one', version: 0 }]; h.behavior.failWrite = true
const session = h.store.beginDraftEdit(original) await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /响应丢失/)
h.store.orders = [{ ...original, version: 0 }] h.behavior.failWrite = false; h.draft.customerRemark = '已修改'
h.behavior.failWrite = true await h.store.saveDraft(h.draft, '客户', 'one', session)
await assert.rejects(h.store.saveDraft(h.draft, '测试企业', 'one', session), /响应丢失/)
const first = h.calls.find(call => call.method === 'PUT')
assert.equal(first.data.expectedVersion, 9)
assert.equal(first.data.draft.customerRemark, '原草稿')
assert.ok(first.headers['Idempotency-Key'])
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT'], 'no pre-save version refresh')
h.behavior.failWrite = false; h.behavior.version = 10
const result = await h.store.saveDraft(h.draft, '测试企业', 'one', session)
const writes = h.calls.filter(call => call.method === 'PUT') const writes = h.calls.filter(call => call.method === 'PUT')
assert.deepEqual(writes[1], first) assert.equal(writes[0].data.expectedVersion, 9); assert.equal(writes[1].data.draft.customerRemark, '已修改')
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT', 'GET', 'PUT', 'GET']) assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
assert.equal(result.version, 10)
}) })
test('missing edit session is invalid while changed inputs after failure are accepted', async t => {
test('changed retry payload or missing edit session fails closed without issuing a new write', async t => { const h = harness(t); await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
const h = harness(t) const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one')); h.behavior.failWrite = true
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
assert.equal(h.calls.length, 0)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
h.behavior.failWrite = true
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session)) await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session))
h.draft.customerRemark = '不同内容' h.draft.customerRemark = '不同内容'; h.behavior.failWrite = false
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /重试原内容/) await h.store.saveDraft(h.draft, '客户', 'one', session)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1) assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
assert.equal(session.expectedVersion, 9)
assert.ok(Object.isFrozen(session))
}) })
test('read failure after edit does not retain a frozen request', async t => {
test('read failure after successful edit preserves the same command for retry', async t => {
const h = harness(t) const h = harness(t)
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one')) const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
h.behavior.failRead = true h.behavior.failRead = true
@@ -168,28 +154,17 @@ test('read failure after successful edit preserves the same command for retry',
h.behavior.failRead = false h.behavior.failRead = false
await h.store.saveDraft(h.draft, '客户', 'one', session) await h.store.saveDraft(h.draft, '客户', 'one', session)
const writes = h.calls.filter(call => call.method === 'PUT') const writes = h.calls.filter(call => call.method === 'PUT')
assert.deepEqual(writes[0], writes[1]) assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
}) })
test('cancel forwards version and reason without rejecting submitted orders locally; retry keeps key and body', async t => { test('cancel submits the current version and reason after a previous failure', async t => {
const h = harness(t) const h = harness(t); h.behavior.status = 'SUBMITTED'; h.behavior.failWrite = true
h.behavior.status = 'SUBMITTED'
h.store.orders = [{ id: 'one', status: 'PENDING_REVIEW', version: 0 }]
h.behavior.failWrite = true
await assert.rejects(h.store.cancelOrder('one', 12, '客户要求取消'), /响应丢失/) await assert.rejects(h.store.cancelOrder('one', 12, '客户要求取消'), /响应丢失/)
const first = h.calls[0] h.behavior.failWrite = false; await h.store.cancelOrder('one', 13, '其他原因')
assert.equal(first.method, 'POST') const writes = h.calls.filter(call => call.method === 'POST')
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/cancel') assert.equal(writes.length, 2); assert.deepEqual(writes[1].data, { expectedVersion: 13, reason: '其他原因' })
assert.deepEqual(first.data, { expectedVersion: 12, reason: '客户要求取消' }) assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
await assert.rejects(h.store.cancelOrder('one', 13, '其他原因'), /原版本和原因/)
assert.equal(h.calls.length, 1)
h.behavior.failWrite = false
await h.store.cancelOrder('one', 12, '客户要求取消')
assert.deepEqual(h.calls[2], first)
assert.equal(h.calls[1].method, 'GET')
assert.equal(h.store.orders.length, 0)
}) })
test('cancel requires a detail version and a nonempty reason', async t => { test('cancel requires a detail version and a nonempty reason', async t => {
const h = harness(t) const h = harness(t)
await assert.rejects(h.store.cancelOrder('one', undefined, '理由')) await assert.rejects(h.store.cancelOrder('one', undefined, '理由'))
@@ -250,24 +225,13 @@ test('cancel UI uses mandatory-reason centered prompt and refreshes after succes
assert.deepEqual(h.calls[1], ['cancel', 'one', 12, '客户申请取消']) assert.deepEqual(h.calls[1], ['cancel', 'one', 12, '客户申请取消'])
}) })
test('cancel UI keeps an uncertain command for explicit retry, but conflict requires a fresh decision', async () => { test('cancel UI releases failure and asks for a current cancellation decision on the next click', async () => {
const h = cancellationViewHarness() const h = cancellationViewHarness(), order = { id: 'one', status: 'DRAFT' }
const order = { id: 'one', status: 'DRAFT' } h.behavior.error = new Error('网络无响应'); await h.handler(order)
h.behavior.error = new Error('网络无响应') h.behavior.error = null; await h.handler(order)
await h.handler(order) assert.equal(h.prompts.length, 2); assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 2)
assert.equal(h.pendingCancellation.value.expectedVersion, 12) assert.equal(h.calls.filter(call => call[0] === 'cancel').length, 2)
h.behavior.error = null
await h.handler(order)
assert.equal(h.prompts.length, 1)
assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 1)
assert.equal(h.calls.filter(call => call[0] === 'confirm').length, 1)
assert.deepEqual(h.calls.filter(call => call[0] === 'cancel')[0], h.calls.filter(call => call[0] === 'cancel')[1])
h.behavior.error = new h.ApiError()
await h.handler(order)
assert.equal(h.pendingCancellation.value, undefined)
assert.match(h.messages.at(-1), /刷新订单后重新确认/)
}) })
test('cancel UI blocks unavailable permission and irreversible visible stages before reads or writes', async () => { test('cancel UI blocks unavailable permission and irreversible visible stages before reads or writes', async () => {
const h = cancellationViewHarness() const h = cancellationViewHarness()
h.canCancelOrder.value = false h.canCancelOrder.value = false
@@ -284,23 +248,14 @@ test('both editor entry points capture detail sessions and both save paths pass
assert.equal((view.match(/store\.saveDraft(?:ForSubmission)?\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2) assert.equal((view.match(/store\.saveDraft(?:ForSubmission)?\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2)
}) })
test('submit reads raw detail version rather than list zero and replays original key and version after timeout', async t => { test('submit uses the current raw version and a fresh key after timeout', async t => {
const h = harness(t) const h = harness(t); h.store.orders = [{id:'one',status:'DRAFT',version:0}]; h.behavior.failSubmit = true
h.store.orders = [{ id: 'one', status: 'DRAFT', version: 0 }]
h.behavior.failSubmit = true
await assert.rejects(h.store.submitSaved('one', 'ACTIVE'), /响应丢失/) await assert.rejects(h.store.submitSaved('one', 'ACTIVE'), /响应丢失/)
const first = h.calls[1] h.behavior.version = 10; h.behavior.failSubmit = false; await h.store.submitSaved('one', 'ACTIVE')
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/submit') const writes = h.calls.filter(call => call.url.endsWith('/submit'))
assert.deepEqual(first.data, { expectedVersion: 9 }) assert.deepEqual(writes.map(call => call.data.expectedVersion), [9,10]); assert.notEqual(writes[0].headers['Idempotency-Key'],writes[1].headers['Idempotency-Key'])
assert.ok(first.headers['Idempotency-Key'])
h.behavior.version = 10; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
await h.store.submitSaved('one', 'ACTIVE')
assert.deepEqual(h.calls[3], first)
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'POST', 'GET', 'POST', 'GET'])
assert.equal(h.store.hasPendingSubmission('one'), false)
}) })
test('submit validates current status and releases failure after readback', async t => {
test('submit refuses missing version or non-draft first decision and preserves command after failed readback', async t => {
const h = harness(t) const h = harness(t)
for (const version of [undefined, -1, 1.5]) { for (const version of [undefined, -1, 1.5]) {
h.behavior.version = version h.behavior.version = version
@@ -311,49 +266,25 @@ test('submit refuses missing version or non-draft first decision and preserves c
assert.ok(h.calls.every(call => call.method === 'GET')) assert.ok(h.calls.every(call => call.method === 'GET'))
h.behavior.status = 'DRAFT'; h.behavior.failSubmitRead = true h.behavior.status = 'DRAFT'; h.behavior.failSubmitRead = true
await assert.rejects(h.store.submitSaved('one'), /读取失败/) await assert.rejects(h.store.submitSaved('one'), /读取失败/)
assert.equal(h.store.hasPendingSubmission('one'), true)
h.behavior.failRead = false; h.behavior.failSubmitRead = false h.behavior.failRead = false; h.behavior.failSubmitRead = false
await h.store.submitSaved('one') await h.store.submitSaved('one')
const posts = h.calls.filter(call => call.method === 'POST') const posts = h.calls.filter(call => call.method === 'POST')
assert.deepEqual(posts[0], posts[1]) assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key'])
assert.deepEqual(posts[0].data, { expectedVersion: 0 }, 'raw detail zero is valid') assert.deepEqual(posts[0].data, { expectedVersion: 0 }, 'raw detail zero is valid')
}) })
test('save then submit retries without another save and changed form requires an explicit new decision', async t => { test('failed submit leaves the draft editable for a fresh save and submission', async t => {
const h = harness(t) const h = harness(t), session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one')) await h.store.saveDraft(h.draft, '客户', 'one', session); h.behavior.failSubmit = true
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session) await assert.rejects(h.store.submitSaved('one')); h.draft.customerRemark = '新内容'
h.behavior.failSubmit = true await h.store.saveDraft(h.draft, '客户', 'one', session); h.behavior.failSubmit = false
await assert.rejects(h.store.submitSaved('one')) await h.store.submitSaved('one'); assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
const first = h.calls.find(call => call.url.endsWith('/submit'))
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
h.draft.customerRemark = '新决定'
await assert.rejects(h.store.saveDraftForSubmission(h.draft, '客户', 'one', session), /重新编辑/)
h.behavior.status = 'SUBMITTED'
await assert.rejects(h.store.beginNewSubmissionEdit('one'), /不能重新编辑/)
assert.equal(h.store.hasPendingSubmission('one'), true)
h.behavior.status = 'DRAFT'; h.behavior.version = 12
const newSession = await h.store.beginNewSubmissionEdit('one')
assert.equal(newSession.expectedVersion, 12)
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', newSession)
h.behavior.version = 13; h.behavior.failSubmit = false
await h.store.submitSaved('one')
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.notEqual(posts[1].headers['Idempotency-Key'], first.headers['Idempotency-Key'])
assert.deepEqual(posts[1].data, { expectedVersion: 13 })
}) })
test('failed initial submit read releases the submission guard for the next click', async t => {
test('failed initial submit read does not resave the prepared draft on retry', async t => { const h = harness(t); h.behavior.failRead = true; await assert.rejects(h.store.submitSaved('one'))
const h = harness(t) h.behavior.failRead = false; await h.store.submitSaved('one')
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one')) assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 1)
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
h.behavior.failRead = true
await assert.rejects(h.store.submitSaved('one'))
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
}) })
async function submissionViewHarness(t) { async function submissionViewHarness(t) {
const h = harness(t) const h = harness(t)
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1] const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
@@ -375,56 +306,29 @@ async function submissionViewHarness(t) {
return { ...h, ...handlers, globals, messages, confirmations } return { ...h, ...handlers, globals, messages, confirmations }
} }
test('real editor submit handler retries original submission without PUT and requires confirmation for changed form', async t => { test('real editor releases failure and saves current edited input on another click', async t => {
const h = await submissionViewHarness(t) const h = await submissionViewHarness(t); h.behavior.failSubmit = true
h.behavior.failSubmit = true await h.submitOrder(); assert.equal(h.globals.saving.value, false)
await h.submitOrder() h.draft.customerRemark = '修改后的决定'; h.behavior.failSubmit = false; await h.submitOrder()
await h.submitOrder() const writes = h.calls.filter(call => call.method === 'PUT'), posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1) assert.equal(writes.length, 2); assert.equal(writes[1].data.draft.customerRemark, '修改后的决定')
const posts = h.calls.filter(call => call.url.endsWith('/submit')) assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key']); assert.equal(h.globals.saving.value, false)
assert.deepEqual(posts[0], posts[1])
h.draft.customerRemark = '修改后的决定'
h.behavior.cancelConfirm = true
await h.submitOrder()
assert.equal(h.confirmations.length, 1)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
h.behavior.cancelConfirm = false; h.behavior.failSubmit = false; h.behavior.version = 12
await h.submitOrder()
assert.equal(h.confirmations.length, 2)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
const last = h.calls.filter(call => call.url.endsWith('/submit')).at(-1)
assert.deepEqual(last.data, { expectedVersion: 12 })
assert.notEqual(last.headers['Idempotency-Key'], posts[0].headers['Idempotency-Key'])
assert.equal(h.globals.saving.value, false)
}) })
test('real batch handler uses only current selection after a failed batch', async t => {
test('real batch handler retains uncertain IDs across list refresh and retries original commands even if now submitted', async t => { const h = await submissionViewHarness(t); h.behavior.failSubmit = true
const h = await submissionViewHarness(t) await h.submitSelectedDraftOrders(); assert.equal(h.globals.batchSubmitting.value, false)
h.behavior.failSubmit = true h.behavior.failSubmit = false; await h.submitSelectedDraftOrders()
await h.submitSelectedDraftOrders() assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 1)
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, ['one']) h.globals.selectedDraftOrders.value = [{id:'one',version:9}]; await h.submitSelectedDraftOrders()
assert.deepEqual(h.globals.selectedDraftOrders.value, [])
h.behavior.failSubmit = false; h.behavior.status = 'SUBMITTED'; h.behavior.version = 10
await h.submitSelectedDraftOrders()
const posts = h.calls.filter(call => call.url.endsWith('/submit')) const posts = h.calls.filter(call => call.url.endsWith('/submit'))
assert.equal(posts.length, 2) assert.equal(posts.length, 2); assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key'])
assert.deepEqual(posts[1], posts[0])
assert.deepEqual(posts[0].data, { expectedVersion: 9 })
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, [])
assert.equal(h.globals.batchSubmitting.value, false)
}) })
test('real new-order handler retains the created order and saves current edits after submit failure', async t => {
test('real new-order handler creates once and retries the saved order submission with the original version', async t => { const h = await submissionViewHarness(t); h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined
const h = await submissionViewHarness(t) h.behavior.version = 0; h.behavior.failSubmit = true; await h.submitOrder()
h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined assert.equal(h.globals.editingId.value, 'one'); h.behavior.failSubmit = false; h.draft.customerRemark = '修改'
h.behavior.version = 0; h.behavior.failSubmit = true
await h.submitOrder()
assert.equal(h.globals.editingId.value, 'one')
h.behavior.version = 1; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
await h.submitOrder() await h.submitOrder()
assert.equal(h.calls.filter(call => call.method === 'POST' && call.url === '/merchant/v1/orders/first-leg').length, 1) assert.equal(h.calls.filter(call => call.method === 'POST' && call.url === '/merchant/v1/orders/first-leg').length, 1)
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 0) assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
const posts = h.calls.filter(call => call.url.endsWith('/submit')) assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 2)
assert.deepEqual(posts[0], posts[1]) })
assert.deepEqual(posts[0].data, { expectedVersion: 0 })
})
@@ -8,6 +8,47 @@ const storeSource = readFileSync(new URL('./firstLegOrders.ts', import.meta.url)
const apiSource = readFileSync(new URL('../api/firstLeg.ts', import.meta.url), 'utf8') const apiSource = readFileSync(new URL('../api/firstLeg.ts', import.meta.url), 'utf8')
const unifiedApiSource = readFileSync(new URL('../api/unifiedOrders.ts', import.meta.url), 'utf8') const unifiedApiSource = readFileSync(new URL('../api/unifiedOrders.ts', import.meta.url), 'utf8')
test('saves optional express tracking, trims it, and omits it for other pickup methods', () => {
const functions = storeSource.slice(storeSource.indexOf('function apiTransport('), storeSource.indexOf('function prepareDraftForSave('))
const javascript = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const save = runInNewContext(`${javascript}; savePayload`)
const draft = { pickupMethod: 'SELF_EXPRESS', trackingNumber: ' SF123456789 ', destinationCountryCode: 'US', destinationType: 'OVERSEAS', items: [] }
const warehouse = { id: '1', name: '收货仓' }
assert.equal(save(draft, warehouse, '客户').expressTrackingNo, 'SF123456789')
for (const trackingNumber of ['', ' ']) {
assert.equal(save({ ...draft, trackingNumber }, warehouse, '客户').expressTrackingNo, undefined)
}
for (const pickupMethod of ['SELF_TRUCK', 'PICKUP']) {
assert.equal(save({ ...draft, pickupMethod }, warehouse, '客户').expressTrackingNo, undefined)
}
})
test('detail fetches authoritative progress on direct entry and refresh, and clears stale progress on failure', async () => {
const functionSource = storeSource.slice(storeSource.indexOf(' async function loadDetail('), storeSource.indexOf(' async function loadWarehouseDetail('))
const progressSource = readFileSync(new URL('../utils/orderProgress.ts', import.meta.url), 'utf8')
const validationSource = progressSource.slice(progressSource.indexOf('export function requireOrderProgress(')).replace('export ', '')
const javascript = ts.transpileModule(`${validationSource}\n${functionSource}`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const id = '2110663764278312961'
const orderProgress = { value: {} }
let calls = 0
let response = { progress: { orderId: id, stage: 'scheduled', partial: true } }
const loadDetail = runInNewContext(`${javascript}; loadDetail`, {
orderProgress, warehouses: { value: [] },
getMerchantUnifiedOrder: async requested => { assert.equal(requested, id); calls++; return response },
mapUnifiedOrderDetail: detail => ({ id, detail }), upsertOrder: order => order,
})
await loadDetail(id)
assert.equal(orderProgress.value[id].stage, 'scheduled')
assert.equal(orderProgress.value[id].partial, true)
response = { progress: { orderId: id, stage: 'delivering', partial: false } }
await loadDetail(id)
assert.equal(calls, 2)
assert.equal(orderProgress.value[id].stage, 'delivering')
response = { progress: { orderId: 'another-order', stage: 'delivered', partial: false } }
await assert.rejects(loadDetail(id), /订单履约进度不完整/)
assert.equal(orderProgress.value[id], undefined)
})
test('renders estimated sailing from the current API without substituting actual departure', () => { test('renders estimated sailing from the current API without substituting actual departure', () => {
const mapper = storeSource.slice(storeSource.indexOf('function businessSummary('), storeSource.indexOf('\nconst unifiedActionLabels')) const mapper = storeSource.slice(storeSource.indexOf('function businessSummary('), storeSource.indexOf('\nconst unifiedActionLabels'))
const javascript = ts.transpileModule(mapper, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText const javascript = ts.transpileModule(mapper, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
@@ -179,7 +220,7 @@ test('only blocks submission when a known company audit status is not active', (
}) })
test('uses the versioned merchant cancellation contract', () => { test('uses the versioned merchant cancellation contract', () => {
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/) assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, payload, createIdempotencyKey\(/)
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/) assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
}) })
@@ -190,8 +231,8 @@ test('sends an idempotency key for create and submit writes', () => {
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/) assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/) assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/) assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
assert.match(storeSource, /pendingSubmissions\.get\(id\)/) assert.doesNotMatch(storeSource, /pendingSubmissions|pendingEdits|pendingCancellation/)
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/) assert.match(storeSource, /submitMerchantFirstLegOrder\(id, \{ expectedVersion: order\.version \}, createIdempotencyKey\(/)
}) })
test('does not expose the contradictory backend rejected state in the client model', () => { test('does not expose the contradictory backend rejected state in the client model', () => {
+14 -67
View File
@@ -32,6 +32,7 @@ import type { FirstLegPartySnapshot } from '@/modules/first-leg/data/firstLegPar
import type { FirstLegOrder, FirstLegOrderDraft, FirstLegOrderTimelineItem } from '@/modules/first-leg/types/firstLegOrder' import type { FirstLegOrder, FirstLegOrderDraft, FirstLegOrderTimelineItem } from '@/modules/first-leg/types/firstLegOrder'
import { canClientEditFirstLegOrder, getFirstLegStatusLabel } from '@/modules/first-leg/utils/firstLegOrder' import { canClientEditFirstLegOrder, getFirstLegStatusLabel } from '@/modules/first-leg/utils/firstLegOrder'
import { loadAllWarehouseRecords } from '@/modules/first-leg/utils/warehousePagination' import { loadAllWarehouseRecords } from '@/modules/first-leg/utils/warehousePagination'
import { requireOrderProgress } from '@/modules/first-leg/utils/orderProgress'
export type ClientWarehouseType = 'DOMESTIC' | 'FBA' | 'OVERSEAS' export type ClientWarehouseType = 'DOMESTIC' | 'FBA' | 'OVERSEAS'
export type ClientWarehouse = PlatformReceivingWarehouse & { export type ClientWarehouse = PlatformReceivingWarehouse & {
@@ -119,6 +120,7 @@ function savePayload(draft: FirstLegOrderDraft, warehouse: ClientWarehouse, cust
productImageFileId: item.productImageFileId || undefined, productImageFileId: item.productImageFileId || undefined,
})), })),
pickupMethod: draft.pickupMethod, pickupMethod: draft.pickupMethod,
expressTrackingNo: draft.pickupMethod === 'SELF_EXPRESS' ? draft.trackingNumber.trim() || undefined : undefined,
receivingWarehouseId: warehouse.id, receivingWarehouseId: warehouse.id,
receivingWarehouseName: warehouse.name, receivingWarehouseName: warehouse.name,
channelCode: draft.channelCode, channelCode: draft.channelCode,
@@ -402,11 +404,7 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
const orderProgress = ref<Record<string, MerchantOrderProgress>>({}) const orderProgress = ref<Record<string, MerchantOrderProgress>>({})
const queryChannelNames = ref<string[]>([]) const queryChannelNames = ref<string[]>([])
let listRequest = 0 let listRequest = 0
const pendingSubmissions = new Map<string, { key: string; payload: { expectedVersion: number } }>()
const submissionForms = new Map<string, { snapshot: string; order: FirstLegOrder }>()
const submittingIds = new Set<string>() const submittingIds = new Set<string>()
const pendingEdits = new WeakMap<DraftEditSession, { key: string; payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest } }>()
const pendingCancellations = new Map<string, { key: string; payload: { expectedVersion: number; reason: string } }>()
function beginDraftEdit(detail: FirstLegOrder): DraftEditSession { function beginDraftEdit(detail: FirstLegOrder): DraftEditSession {
if (!canClientEditFirstLegOrder(detail.status) || !Number.isSafeInteger(detail.version) || detail.version < 0) throw new Error('请重新打开草稿详情后编辑') if (!canClientEditFirstLegOrder(detail.status) || !Number.isSafeInteger(detail.version) || detail.version < 0) throw new Error('请重新打开草稿详情后编辑')
@@ -507,8 +505,12 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
} }
async function loadDetail(id: string) { async function loadDetail(id: string) {
delete orderProgress.value[id]
const detail = await getMerchantUnifiedOrder(id) const detail = await getMerchantUnifiedOrder(id)
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value)) const progress = requireOrderProgress(id, detail.progress)
const mapped = mapUnifiedOrderDetail(detail, warehouses.value)
orderProgress.value[id] = progress
return upsertOrder(mapped)
} }
async function loadWarehouseDetail(id: string) { async function loadWarehouseDetail(id: string) {
@@ -528,22 +530,12 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
} }
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) { async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
if (hasPendingSubmission(id)) throw new Error('上次提交结果未确认,请重试原提交,或确认重新编辑后再保存')
const warehouse = prepareDraftForSave(draft, warehouses.value) const warehouse = prepareDraftForSave(draft, warehouses.value)
if (id) { if (id) {
if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑') if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑')
const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) } const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) }
let pending = pendingEdits.get(editSession) await updateMerchantFirstLegOrder(id, payload, createIdempotencyKey(`first-leg-edit-${id}`))
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次保存结果未确认,请重试原内容,或重新打开详情后编辑')
// Observe an uncertain previous outcome without replacing its frozen version.
if (pending) await getMerchantFirstLegOrder(id)
if (!pending) {
pending = { key: createIdempotencyKey(`first-leg-edit-${id}`), payload: JSON.parse(JSON.stringify(payload)) }
pendingEdits.set(editSession, pending)
}
await updateMerchantFirstLegOrder(id, pending.payload, pending.key)
const saved = await loadOrderAggregate(id) const saved = await loadOrderAggregate(id)
pendingEdits.delete(editSession)
return saved return saved
} }
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName)) const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
@@ -553,15 +545,7 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
async function cancelOrder(id: string, expectedVersion: number, reason: string) { async function cancelOrder(id: string, expectedVersion: number, reason: string) {
if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0 || !reason.trim() || reason.trim().length > 500) throw new Error('取消订单需要详情版本及 1–500 字取消原因') if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0 || !reason.trim() || reason.trim().length > 500) throw new Error('取消订单需要详情版本及 1–500 字取消原因')
const payload = { expectedVersion, reason: reason.trim() } const payload = { expectedVersion, reason: reason.trim() }
let pending = pendingCancellations.get(id) await cancelMerchantFirstLegOrder(id, payload, createIdempotencyKey(`first-leg-cancel-${id}`))
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次取消结果未确认,请使用原版本和原因重试')
if (pending) await getMerchantFirstLegOrder(id)
if (!pending) {
pending = { key: createIdempotencyKey(`first-leg-cancel-${id}`), payload }
pendingCancellations.set(id, pending)
}
await cancelMerchantFirstLegOrder(id, pending.payload, pending.key)
pendingCancellations.delete(id)
orders.value = orders.value.filter(order => order.id !== id) orders.value = orders.value.filter(order => order.id !== id)
} }
@@ -570,7 +554,6 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '审核中', APPROVED: '已审核', ACCEPTED: '已接单', REJECTED: '已退回' } const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '审核中', APPROVED: '已审核', ACCEPTED: '已接单', REJECTED: '已退回' }
if (!Object.hasOwn(labels, order.status)) throw new Error('当前订单状态不允许取消,请刷新订单查看最新进度') if (!Object.hasOwn(labels, order.status)) throw new Error('当前订单状态不允许取消,请刷新订单查看最新进度')
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情') if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
pendingCancellations.delete(id)
return { id, expectedVersion: order.version, businessNo: order.orderNo || order.inboundCode || '—', statusLabel: labels[order.status] } return { id, expectedVersion: order.version, businessNo: order.orderNo || order.inboundCode || '—', statusLabel: labels[order.status] }
} }
@@ -591,55 +574,19 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候') if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
submittingIds.add(id) submittingIds.add(id)
try { try {
let pending = pendingSubmissions.get(id)
// Always observe the raw detail; a retry must retain the original command.
const { order } = await getMerchantFirstLegOrder(id) const { order } = await getMerchantFirstLegOrder(id)
if (!pending) { if (order.status !== 'DRAFT') throw new Error('当前订单不是草稿,请刷新订单查看最新状态')
if (order.status !== 'DRAFT') throw new Error('当前订单不是草稿,请刷新订单查看最新状态') if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情') await submitMerchantFirstLegOrder(id, { expectedVersion: order.version }, createIdempotencyKey(`first-leg-submit-${id}`))
pending = { key: createIdempotencyKey(`first-leg-submit-${id}`), payload: { expectedVersion: order.version } } return await loadOrderAggregate(id)
pendingSubmissions.set(id, pending)
}
await submitMerchantFirstLegOrder(id, pending.payload, pending.key)
const submitted = await loadOrderAggregate(id)
pendingSubmissions.delete(id)
submissionForms.delete(id)
return submitted
} finally { } finally {
submittingIds.delete(id) submittingIds.delete(id)
} }
} }
function hasPendingSubmission(id?: string) { return !!id && (pendingSubmissions.has(id) || submissionForms.has(id)) }
function isSubmissionRetry(id: string | undefined, draft: FirstLegOrderDraft) {
return !!id && hasPendingSubmission(id) && submissionForms.get(id)?.snapshot === JSON.stringify(draft)
}
async function beginNewSubmissionEdit(id: string) {
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
const detail = await getMerchantFirstLegOrder(id)
if (detail.order.status !== 'DRAFT') throw new Error('订单已不在草稿状态,不能重新编辑,请刷新订单查看最新状态')
if (!Number.isSafeInteger(detail.order.version) || detail.order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
const order = mapOrder(detail.order, warehouses.value, detail)
const session = beginDraftEdit(order)
pendingSubmissions.delete(id)
submissionForms.delete(id)
upsertOrder(order)
return session
}
async function saveDraftForSubmission(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
if (id && isSubmissionRetry(id, draft)) return submissionForms.get(id)!.order
const snapshot = JSON.stringify(draft)
const order = await saveDraft(JSON.parse(snapshot), customerName, id, editSession)
submissionForms.set(order.id, { snapshot, order })
return order
}
async function loadDraftDetail(id: string) { async function loadDraftDetail(id: string) {
return loadOrderAggregate(id) return loadOrderAggregate(id)
} }
return { orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved, hasPendingSubmission, isSubmissionRetry, beginNewSubmissionEdit, saveDraftForSubmission } return { orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved }
}) })
@@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs'
import ts from 'typescript' import ts from 'typescript'
import * as vue from 'vue' import * as vue from 'vue'
import * as pinia from 'pinia' import * as pinia from 'pinia'
import { requireOrderProgress } from '../utils/orderProgress.ts'
const source = readFileSync(new URL('./firstLegOrders.ts', import.meta.url), 'utf8') const source = readFileSync(new URL('./firstLegOrders.ts', import.meta.url), 'utf8')
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
@@ -27,11 +28,12 @@ function harness(t, read) {
getMerchantOrderWorkbench: query => { calls.push(structuredClone(query)); return read(query) }, getMerchantOrderWorkbench: query => { calls.push(structuredClone(query)); return read(query) },
getMerchantUnifiedOrder: async id => { getMerchantUnifiedOrder: async id => {
details.push(id) details.push(id)
return { summary: row(id, 'DRAFT'), order: { order: { id, status: 'DRAFT', version: 7 } }, timeline: [] } return { progress: { orderId: id, stage: 'none', partial: false }, summary: row(id, 'DRAFT'), order: { order: { id, status: 'DRAFT', version: 7 } }, timeline: [] }
}, },
}, },
'@/modules/first-leg/utils/firstLegOrder': { getFirstLegStatusLabel: value => value }, '@/modules/first-leg/utils/firstLegOrder': { getFirstLegStatusLabel: value => value },
'@/modules/first-leg/utils/warehousePagination': { loadAllWarehouseRecords: async type => { warehouseCalls.push(type); return [] } }, '@/modules/first-leg/utils/warehousePagination': { loadAllWarehouseRecords: async type => { warehouseCalls.push(type); return [] } },
'@/modules/first-leg/utils/orderProgress': { requireOrderProgress },
} }
const exports = {} const exports = {}
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports) new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
@@ -183,6 +183,7 @@ export type FirstLegOrderDraft = Omit<Pick<
| 'destinationWarehouseId' | 'destinationWarehouseId'
| 'destinationWarehouseName' | 'destinationWarehouseName'
| 'pickupMethod' | 'pickupMethod'
| 'trackingNumber'
| 'channelCode' | 'channelCode'
| 'channelName' | 'channelName'
| 'pricingTaxMode' | 'pricingTaxMode'
@@ -0,0 +1,134 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import ts from 'typescript'
import { computed, effectScope, ref, watch } from 'vue'
import { readOrderColumnPreferences, saveOrderColumnPreferences } from './orderColumnPreferences.ts'
const page = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
const columnSource = page.slice(page.indexOf('const fixedOrderColumns:'), page.indexOf('const tablePage ='))
const columnScript = ts.transpileModule(columnSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const createColumns = new Function('auth', 'ref', 'computed', 'watch', 'readOrderColumnPreferences', 'saveOrderColumnPreferences', `${columnScript}
return { visibleColumnKeys, orderedColumnKeys, visibleOrderColumns, draggedColumnKey, moveOrderColumn, dropOrderColumn, resetOrderColumns }
`)
function mockStorage(t) {
const original = Object.getOwnPropertyDescriptor(globalThis, 'localStorage')
const entries = new Map()
const storage = {
getItem: key => entries.get(key) ?? null,
setItem: (key, value) => entries.set(key, value),
}
Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: storage })
t.after(() => {
if (original) Object.defineProperty(globalThis, 'localStorage', original)
else delete globalThis.localStorage
})
return storage
}
function openColumns(t, ownerId = 'customer-one') {
const scope = effectScope()
const columns = scope.run(() => createColumns({ user: { id: ownerId } }, ref, computed, watch, readOrderColumnPreferences, saveOrderColumnPreferences))
t.after(() => scope.stop())
return { ...columns, close: () => scope.stop() }
}
test('restores checked fields and both arrow and drag ordering after a fresh page setup', t => {
mockStorage(t)
const columns = openColumns(t)
columns.visibleColumnKeys.value.push('destinationWarehouse', 'grossWeight', 'volume')
columns.visibleColumnKeys.value.splice(columns.visibleColumnKeys.value.indexOf('createdAt'), 1)
columns.moveOrderColumn('destinationWarehouse', -1)
columns.draggedColumnKey.value = 'grossWeight'
columns.dropOrderColumn('status')
const visibleKeys = [...columns.visibleColumnKeys.value]
const orderedKeys = [...columns.orderedColumnKeys.value]
const renderedKeys = columns.visibleOrderColumns.value.map(column => column.key)
columns.close()
const refreshed = openColumns(t)
assert.deepEqual(refreshed.visibleColumnKeys.value, visibleKeys)
assert.deepEqual(refreshed.orderedColumnKeys.value, orderedKeys)
assert.deepEqual(refreshed.visibleOrderColumns.value.map(column => column.key), renderedKeys)
assert.deepEqual(renderedKeys.slice(0, 3), ['selection', 'actions', 'inboundCode'])
assert.equal(renderedKeys[3], 'grossWeight')
})
test('persists restore-default and intentionally hiding every selectable field', t => {
mockStorage(t)
const columns = openColumns(t)
const defaults = [...columns.visibleColumnKeys.value]
const defaultOrder = [...columns.orderedColumnKeys.value]
columns.visibleColumnKeys.value = []
columns.close()
const refreshed = openColumns(t)
assert.deepEqual(refreshed.visibleColumnKeys.value, [])
assert.deepEqual(refreshed.visibleOrderColumns.value.map(column => column.key), ['selection', 'actions', 'inboundCode'])
refreshed.moveOrderColumn('grossWeight', -1)
refreshed.resetOrderColumns()
refreshed.close()
const reset = openColumns(t)
assert.deepEqual(reset.visibleColumnKeys.value, defaults)
assert.deepEqual(reset.orderedColumnKeys.value, defaultOrder)
})
test('keeps the field selection separate for each signed-in account', t => {
mockStorage(t)
const first = openColumns(t)
first.visibleColumnKeys.value = ['volume']
first.close()
const second = openColumns(t, 'customer-two')
assert.notDeepEqual(second.visibleColumnKeys.value, ['volume'])
second.visibleColumnKeys.value = ['grossWeight']
second.close()
assert.deepEqual(openColumns(t).visibleColumnKeys.value, ['volume'])
assert.deepEqual(openColumns(t, 'customer-two').visibleColumnKeys.value, ['grossWeight'])
})
test('discards unknown, duplicate and invalid keys and includes newly available fields in ordering', t => {
mockStorage(t)
saveOrderColumnPreferences('customer-one', {
visibleColumnKeys: ['volume', 'removed', 'volume', null, 3],
orderedColumnKeys: ['volume', 'removed', 'volume', false],
})
assert.deepEqual(readOrderColumnPreferences('customer-one', ['status', 'volume', 'newField'], ['status']), {
visibleColumnKeys: ['volume'],
orderedColumnKeys: ['volume', 'status', 'newField'],
})
})
test('uses the original defaults for missing or damaged saved preferences', t => {
const storage = mockStorage(t)
const defaults = { visibleColumnKeys: ['status'], orderedColumnKeys: ['status', 'volume'] }
assert.deepEqual(readOrderColumnPreferences('customer-one', ['status', 'volume'], ['status']), defaults)
saveOrderColumnPreferences('customer-one', defaults)
const realGetItem = storage.getItem
for (const saved of ['{invalid', 'null', '[]', '42', '{"visibleColumnKeys":"status","orderedColumnKeys":[]}']) {
storage.getItem = () => saved
assert.deepEqual(readOrderColumnPreferences('customer-one', ['status', 'volume'], ['status']), defaults)
}
storage.getItem = realGetItem
})
test('keeps column controls usable when browser storage is blocked', t => {
const storage = mockStorage(t)
storage.getItem = () => { throw new Error('Storage denied') }
storage.setItem = () => { throw new Error('Storage denied') }
const columns = openColumns(t)
assert.ok(columns.visibleColumnKeys.value.includes('status'))
assert.doesNotThrow(() => { columns.visibleColumnKeys.value.push('volume') })
assert.doesNotThrow(() => columns.resetOrderColumns())
})
test('does not read or save preferences without an account', t => {
const storage = mockStorage(t)
let storageCalls = 0
storage.getItem = () => { storageCalls++; return null }
storage.setItem = () => { storageCalls++ }
const columns = openColumns(t, '')
columns.visibleColumnKeys.value = ['volume']
assert.equal(openColumns(t, '').visibleColumnKeys.value.includes('status'), true)
assert.equal(storageCalls, 0)
})
@@ -0,0 +1,35 @@
interface OrderColumnPreferences {
visibleColumnKeys: string[]
orderedColumnKeys: string[]
}
function storageKey(ownerId: string) {
return `cc:client:first-leg:order-columns:${ownerId}`
}
export function readOrderColumnPreferences(ownerId: string, selectableKeys: string[], defaultVisibleKeys: string[]): OrderColumnPreferences {
const defaults = { visibleColumnKeys: [...defaultVisibleKeys], orderedColumnKeys: [...selectableKeys] }
if (!ownerId) return defaults
try {
const saved: unknown = JSON.parse(localStorage.getItem(storageKey(ownerId)) ?? 'null')
if (!saved || typeof saved !== 'object') return defaults
const preferences = saved as Partial<OrderColumnPreferences>
if (!Array.isArray(preferences.visibleColumnKeys) || !Array.isArray(preferences.orderedColumnKeys)) return defaults
const validKeys = (keys: unknown[]) => [...new Set(keys.filter((key): key is string => typeof key === 'string' && selectableKeys.includes(key)))]
return {
visibleColumnKeys: validKeys(preferences.visibleColumnKeys),
orderedColumnKeys: [...new Set([...validKeys(preferences.orderedColumnKeys), ...selectableKeys])],
}
} catch {
return defaults
}
}
export function saveOrderColumnPreferences(ownerId: string, preferences: OrderColumnPreferences) {
if (!ownerId) return
try {
localStorage.setItem(storageKey(ownerId), JSON.stringify(preferences))
} catch {
// Column selection remains usable when browser storage is unavailable.
}
}
@@ -0,0 +1,17 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { orderBillingMetric } from './orderDetailSummary.ts'
test('detail uses the published billing quantity without substituting physical gross weight', () => {
const billing = { inbound: { summary: { actualGrossWeightKg: 23, chargeableWeightKg: null } },
billingBasis: { chargeUnit: 'KG', chargeableQuantity: 17.0006, chargeableWeightKg: null } }
assert.deepEqual(orderBillingMetric(billing, null), { label: '计费重量', quantity: 17.0006, unit: 'kg' })
assert.equal(orderBillingMetric(billing, null).quantity.toLocaleString('zh-CN'), '17.001')
})
test('volume charging retains its real unit and missing billing does not invent a quantity', () => {
assert.deepEqual(orderBillingMetric({ billingBasis: { chargeUnit: 'CBM', chargeableQuantity: 0.102 } }, 23),
{ label: '计费体积', quantity: 0.102, unit: 'm³' })
assert.equal(orderBillingMetric(null, null).quantity, null)
assert.equal(orderBillingMetric(null, 0).quantity, 0)
})
@@ -0,0 +1,14 @@
import type { MerchantInboundBilling } from '../types/inboundBilling'
/** Published billing quantity and physical gross weight have different meanings. */
export function orderBillingMetric(billing: MerchantInboundBilling | null, measuredChargeableWeight: number | null) {
if (billing) {
const basis = billing.billingBasis
return basis.chargeUnit === 'KG'
? { label: '计费重量', quantity: basis.chargeableQuantity, unit: 'kg' }
: basis.chargeUnit === 'CBM'
? { label: '计费体积', quantity: basis.chargeableQuantity, unit: 'm³' }
: { label: '计费量', quantity: null, unit: '' }
}
return { label: '计费重量', quantity: measuredChargeableWeight, unit: 'kg' }
}
@@ -13,3 +13,13 @@ test('prototype queues preserve order and distinguish partial progress from comp
assert.equal(exports.orderProgressLabel({ stage: 'none', partial: false }), '—') assert.equal(exports.orderProgressLabel({ stage: 'none', partial: false }), '—')
assert.equal(exports.orderProgressLabel(), '—') assert.equal(exports.orderProgressLabel(), '—')
}) })
test('detail progress must belong to the requested order and retain partial fulfillment', () => {
const progress = { orderId: '2110663764278312961', stage: 'scheduled', partial: true }
assert.equal(exports.requireOrderProgress(progress.orderId, progress), progress)
assert.equal(exports.orderProgressLabel(exports.requireOrderProgress(progress.orderId, progress)), '部分已排车')
assert.throws(() => exports.requireOrderProgress('other-order', progress), /订单履约进度不完整/)
assert.throws(() => exports.requireOrderProgress(progress.orderId, undefined), /订单履约进度不完整/)
assert.throws(() => exports.requireOrderProgress(progress.orderId, { ...progress, stage: 'UNKNOWN' }), /订单履约进度不完整/)
assert.throws(() => exports.requireOrderProgress(progress.orderId, { ...progress, partial: null }), /订单履约进度不完整/)
})
@@ -18,3 +18,12 @@ export function orderProgressLabel(progress?: MerchantOrderProgress) {
const label = ORDER_QUEUES.find(q => q.key === progress.stage)?.label ?? '—' const label = ORDER_QUEUES.find(q => q.key === progress.stage)?.label ?? '—'
return `${progress.partial ? '部分' : ''}${label}` return `${progress.partial ? '部分' : ''}${label}`
} }
export function requireOrderProgress(orderId: string, progress: MerchantOrderProgress) {
if (!progress || String(progress.orderId) !== orderId
|| !['none', 'loaded', 'declared', 'cleared', 'scheduled', 'delivering', 'delivered'].includes(progress.stage)
|| typeof progress.partial !== 'boolean') {
throw new Error('订单履约进度不完整,请重新加载')
}
return progress
}
@@ -7,6 +7,7 @@ import type { TableAction } from '@/components/common/tableActions'
import { MERCHANT_CUSTOMS_STATUS_LABELS, type MerchantCustomsContainer } from '../api/customs' import { MERCHANT_CUSTOMS_STATUS_LABELS, type MerchantCustomsContainer } from '../api/customs'
import { readCustomsDocuments, type CustomsDocumentRow } from '../utils/customsDocumentsReader' import { readCustomsDocuments, type CustomsDocumentRow } from '../utils/customsDocumentsReader'
import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue' import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue'
import CustomsHelp from '../components/CustomsHelp.vue'
import { useCustomsPendingStore } from '../store/customsPending' import { useCustomsPendingStore } from '../store/customsPending'
@@ -98,7 +99,7 @@ onMounted(() => { void load() })
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" /> <QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" />
<section class="customs-card"> <section class="customs-card">
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRecords" :columns="columns" :loading="loading" :total="filteredRecords.length" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="order.id" :empty-text="emptyText"> <DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRecords" :columns="columns" :loading="loading" :total="filteredRecords.length" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="order.id" :empty-text="emptyText">
<template #toolbar><strong>资料列表</strong><span>统计为本客户同柜退税货物汇总,资料覆盖按入仓码计。</span></template> <template #toolbar><strong class="customs-list-heading">资料列表<CustomsHelp title="资料统计口径"><p>统计为本客户同柜退税货物汇总,资料覆盖按入仓码计。</p></CustomsHelp></strong></template>
<template #toolbar-actions><el-button :loading="loading" @click="load"><RefreshCcw :size="16" />刷新</el-button></template> <template #toolbar-actions><el-button :loading="loading" @click="load"><RefreshCcw :size="16" />刷新</el-button></template>
<template v-if="errorMessage" #error><div class="state-error" role="alert"><span>{{ errorMessage }}</span><el-button :loading="loading" @click="load">重新加载</el-button></div></template> <template v-if="errorMessage" #error><div class="state-error" role="alert"><span>{{ errorMessage }}</span><el-button :loading="loading" @click="load">重新加载</el-button></div></template>
<template #orderNo="{ row }">{{ row.order.orderNo || '—' }}</template> <template #orderNo="{ row }">{{ row.order.orderNo || '—' }}</template>
@@ -114,6 +115,7 @@ onMounted(() => { void load() })
<style scoped> <style scoped>
.customs-page { display: grid; gap: var(--client-section-gap); } .customs-page { display: grid; gap: var(--client-section-gap); }
.customs-list-heading { display: flex; align-items: center; gap: 4px; }
.customs-card { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; } .customs-card { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
.state-error { display: flex; min-height: 84px; align-items: center; justify-content: center; gap: 12px; padding: 14px; color: #b42318; } .state-error { display: flex; min-height: 84px; align-items: center; justify-content: center; gap: 12px; padding: 14px; color: #b42318; }
</style> </style>
@@ -223,7 +223,8 @@ test('shows one unified progress line and C02 business summaries without detail
assert.match(source, /progressSummaryItems/) assert.match(source, /progressSummaryItems/)
assert.match(source, /summary\.preloadStatus/) assert.match(source, /summary\.preloadStatus/)
assert.match(source, /summary\.expectedPickCount/) assert.match(source, /summary\.expectedPickCount/)
assert.match(source, /summary\.deliveryTrackingNo/) assert.match(source, /label: '后续履约', value: orderProgressLabel\(store\.orderProgress\[order\.id\]\)/)
assert.doesNotMatch(source, /待海外同步/)
assert.match(progressSource, /FIRST_LEG_PROGRESS_STAGES/) assert.match(progressSource, /FIRST_LEG_PROGRESS_STAGES/)
assert.match(progressSource, /订单主节点与关联柜次统一展示/) assert.match(progressSource, /订单主节点与关联柜次统一展示/)
assert.match(progressSource, /履约进度/) assert.match(progressSource, /履约进度/)
@@ -234,7 +235,7 @@ test('shows one unified progress line and C02 business summaries without detail
assert.match(source, /pickingStatusLabel: getFirstLegPickingStatusLabel\(summary\.loadingStatus\)/) assert.match(source, /pickingStatusLabel: getFirstLegPickingStatusLabel\(summary\.loadingStatus\)/)
assert.match(source, /prop="pickingStatusLabel" label="拣货状态"/) assert.match(source, /prop="pickingStatusLabel" label="拣货状态"/)
assert.doesNotMatch(source, /label="当前节点"/) assert.doesNotMatch(source, /label="当前节点"/)
assert.match(source, /尚未分配柜次,后续柜次节点将在这里同步。/) assert.match(source, /尚未分配柜次/)
assert.doesNotMatch(source, /暂无柜次分配信息/) assert.doesNotMatch(source, /暂无柜次分配信息/)
assert.doesNotMatch(source, /summary\.sealNo \|\|/) assert.doesNotMatch(source, /summary\.sealNo \|\|/)
assert.doesNotMatch(progressSource, /客户确认|差异处理中|派送中/) assert.doesNotMatch(progressSource, /客户确认|差异处理中|派送中/)
@@ -396,7 +397,7 @@ test('distills order creation into the confirmed prototype sections with server
assert.match(cargoToolbarSource, /isCreatePage && !routeDraftId && canCreateOrder/) assert.match(cargoToolbarSource, /isCreatePage && !routeDraftId && canCreateOrder/)
assert.match(cargoToolbarSource, /downloadBatchTemplate[\s\S]*下载 Excel 模板/) assert.match(cargoToolbarSource, /downloadBatchTemplate[\s\S]*下载 Excel 模板/)
assert.match(cargoToolbarSource, /openBatchImport[\s\S]*Excel 批量导入/) assert.match(cargoToolbarSource, /openBatchImport[\s\S]*Excel 批量导入/)
assert.match(cargoToolbarSource, /Excel 导入用于一次创建多条订单草稿/) assert.doesNotMatch(cargoToolbarSource, /Excel 导入用于一次创建多条订单草稿/)
assert.match(source, /导入成功的数据只创建草稿,不会直接提交审核/) assert.match(source, /导入成功的数据只创建草稿,不会直接提交审核/)
assert.match(source, /下载正式模板[\s\S]*选择 Excel/) assert.match(source, /下载正式模板[\s\S]*选择 Excel/)
assert.match(source, /仅支持 \.xlsx,文件不超过 5MB、最多 50 行/) assert.match(source, /仅支持 \.xlsx,文件不超过 5MB、最多 50 行/)
@@ -459,7 +460,7 @@ test('matches the prototype two-column create layout and reset action', () => {
test('shows an optional LX inbound order number for one-click dropship orders', () => { test('shows an optional LX inbound order number for one-click dropship orders', () => {
assert.match(source, /v-if="form\.fulfillmentType === 'ONE_CLICK_DROPSHIP'" label="LX入库单号" prop="lxCode"/) assert.match(source, /v-if="form\.fulfillmentType === 'ONE_CLICK_DROPSHIP'" label="LX入库单号" prop="lxCode"/)
assert.match(source, /v-model="form\.lxCode"[^>]*placeholder="请输入LX入库单号"/) assert.match(source, /v-model="form\.lxCode"[^>]*placeholder=""/)
assert.doesNotMatch(source, /label="LX入库单号"[^>]*required/) assert.doesNotMatch(source, /label="LX入库单号"[^>]*required/)
}) })
@@ -548,9 +549,19 @@ test('shows fulfillment courier information as read-only client detail', () => {
assert.match(source, /履约快递信息/) assert.match(source, /履约快递信息/)
assert.match(source, /detailOrder\.expressCompanyName/) assert.match(source, /detailOrder\.expressCompanyName/)
assert.match(source, /detailOrder\.trackingNumber/) assert.match(source, /detailOrder\.trackingNumber/)
assert.match(source, /客户端仅只读展示/) assert.match(source, /快递公司由平台维护/)
assert.doesNotMatch(source, /v-model="form\.expressCompanyName"/) assert.doesNotMatch(source, /v-model="form\.expressCompanyName"/)
assert.doesNotMatch(source, /v-model="form\.trackingNumber"/) })
test('orders pickup choices and offers an optional tracking number only for express pickup', () => {
const group = source.match(/<el-radio-group v-model="form\.pickupMethod"[\s\S]*?<\/el-radio-group>/)[0]
assert.deepEqual([...group.matchAll(/value="([A-Z_]+)"/g)].map(match => match[1]), ['SELF_TRUCK', 'PICKUP', 'SELF_EXPRESS'])
assert.match(group, /value="SELF_EXPRESS">快递自提/)
const field = source.match(/<el-form-item v-if="form\.pickupMethod === 'SELF_EXPRESS'"[^>]*label="快递单号"[\s\S]*?<\/el-form-item>/)[0]
assert.match(field, /v-model="form\.trackingNumber" maxlength="128"/)
assert.doesNotMatch(field, /\brequired\b|:rules=/)
assert.match(source, /trackingNumber: order\.pickupMethod === 'SELF_EXPRESS' \? order\.trackingNumber : ''/)
assert.match(source, /if \(form\.pickupMethod !== 'SELF_EXPRESS'\) form\.trackingNumber = ''/)
}) })
test('shows the full customer-safe order detail without platform-only controls', () => { test('shows the full customer-safe order detail without platform-only controls', () => {
@@ -612,7 +623,7 @@ test('loads merchant inbound billing as an isolated read-only detail section', (
assert.match(source, /error instanceof ApiError && error\.code === 'A0404'/) assert.match(source, /error instanceof ApiError && error\.code === 'A0404'/)
assert.match(source, /error\.message \|\| unavailableMessage/) assert.match(source, /error\.message \|\| unavailableMessage/)
assert.match(source, /order\.status === 'DRAFT'/) assert.match(source, /order\.status === 'DRAFT'/)
assert.match(source, /feeConfirmationOpen\.value[\s\S]*\? '未推送计费重'[\s\S]*: '订单提交后可查看入库结果'/) assert.match(source, /feeConfirmationOpen\.value[\s\S]*\? '未推送费用'[\s\S]*: '订单提交后可查看入库结果'/)
assert.match(source, /订单提交后可查看入库结果/) assert.match(source, /订单提交后可查看入库结果/)
assert.doesNotMatch(source, /confirmMerchantInbound|adjustMerchantInbound|sendMerchantInbound/) assert.doesNotMatch(source, /confirmMerchantInbound|adjustMerchantInbound|sendMerchantInbound/)
}) })
@@ -625,18 +636,47 @@ test('keeps platform enterprise scope and tenant terminology out of the customer
test('opens billing-weight confirmation independently from order details', () => { test('opens billing-weight confirmation independently from order details', () => {
const handler = source.slice(source.indexOf('function openFeeConfirmation'), source.indexOf('async function retryDetail')) const handler = source.slice(source.indexOf('function openFeeConfirmation'), source.indexOf('async function retryDetail'))
assert.match(handler, /feeConfirmationOpen\.value = true/) assert.match(handler, /feeConfirmationOpen\.value = true/)
assert.match(handler, /loadInboundBilling\(order, '未推送计费重'\)/) assert.match(handler, /loadInboundBilling\(order, '未推送费用'\)/)
assert.doesNotMatch(handler, /openDetail\(/) assert.doesNotMatch(handler, /openDetail\(/)
assert.match(source, /v-if="feeConfirmationOpen"[\s\S]*dialog-only[\s\S]*auto-open/) assert.match(source, /v-if="feeConfirmationOpen"[\s\S]*dialog-only[\s\S]*auto-open/)
assert.match(source, /unavailable-message="未推送计费重"/) assert.match(source, /unavailable-message="未推送费用"/)
}) })
test('shows billing-weight confirmation only when the backend marks it pending', () => { test('only offers published-fee confirmation for pending orders with confirmation permission', () => {
assert.match(source, /if \(canConfirmInboundFee\.value && order\.businessSummary\.customerFeeConfirmationRequired\) \{\s*actions\.push\(\{ key: 'fee'/) const actions = source.slice(source.indexOf('function getOrderRowActions'), source.indexOf('function getOrderRowActions') + 1800)
assert.match(actions, /actions\.push\(\{ key: 'fee', label: '确认计费重', run: \(\) => openFeeConfirmation\(order\) \}\)/)
assert.match(actions, /if \(canConfirmInboundFee\.value && order\.businessSummary\.customerFeeConfirmationRequired\) \{\s*actions\.push\(\{ key: 'fee'/)
assert.doesNotMatch(actions, /label: '确认费用'|key: 'weight'/)
assert.doesNotMatch(source, /ChargeableWeightDialog|weightConfirmationOrderId/)
assert.match(source, /:row-actions="getOrderRowActions"/) assert.match(source, /:row-actions="getOrderRowActions"/)
assert.match(orderStoreSource, /customerFeeConfirmationRequired: summary\?\.customerFeeConfirmationRequired \?\? false/) assert.match(orderStoreSource, /customerFeeConfirmationRequired: summary\?\.customerFeeConfirmationRequired \?\? false/)
}) })
test('hides confirmation for confirmed, unpushed and unauthorized orders and refreshes after confirmation', () => {
const start = source.indexOf('function getOrderRowActions')
const end = source.indexOf('\nasync function copyOrder', start)
const body = source.slice(start, end)
.replace('function getOrderRowActions(row: object): TableAction[]', 'function getOrderRowActions(row)')
.replace('const order = row as FirstLegOrder', 'const order = row')
.replace('const actions: TableAction[]', 'const actions')
const actionsFor = new Function('canConfirmInboundFee', 'canCreateOrder', 'canEditOrder',
'canOfferCancellation', 'eligibleCustomsDetail', 'openFeeConfirmation',
`${body}; return getOrderRowActions`)
for (const [permitted, pending] of [[true, true], [true, false], [false, true], [false, false]]) {
const opened = []
const order = { id: 'order-1', businessSummary: { customerFeeConfirmationRequired: pending } }
const getActions = actionsFor({ value: permitted }, { value: false }, { value: false },
() => false, () => false, row => opened.push(row.id))
const confirm = getActions(order).filter(action => action.key === 'fee')
assert.equal(confirm.length, permitted && pending ? 1 : 0)
if (confirm.length) {
confirm[0].run()
assert.deepEqual(opened, ['order-1'])
}
}
assert.match(source, /function handleInboundFeeConfirmed\(\) \{\s*if \(!isCreatePage\.value && !isDetailPage\.value\) void loadOrderPage\(\)/)
})
test('submits only selected draft orders in one batch action', () => { test('submits only selected draft orders in one batch action', () => {
assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/) assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/)
assert.match(source, /Promise\.allSettled\(ids\.map\(id => store\.submitSaved/) assert.match(source, /Promise\.allSettled\(ids\.map\(id => store\.submitSaved/)
@@ -60,9 +60,11 @@ import {
validateFirstLegOrderDraft, validateFirstLegOrderDraft,
} from '@/modules/first-leg/utils/firstLegOrder' } from '@/modules/first-leg/utils/firstLegOrder'
import { ORDER_QUEUES, orderProgressLabel } from '../utils/orderProgress' import { ORDER_QUEUES, orderProgressLabel } from '../utils/orderProgress'
import { orderBillingMetric } from '../utils/orderDetailSummary'
import type { OrderQueue } from '../api/unifiedOrders' import type { OrderQueue } from '../api/unifiedOrders'
import { validateProductImageFile } from '@/modules/first-leg/utils/productImage' import { validateProductImageFile } from '@/modules/first-leg/utils/productImage'
import { createPriceEstimateBreakdown } from '@/modules/first-leg/utils/priceEstimate' import { createPriceEstimateBreakdown } from '@/modules/first-leg/utils/priceEstimate'
import { readOrderColumnPreferences, saveOrderColumnPreferences } from '@/modules/first-leg/utils/orderColumnPreferences'
const store = useFirstLegOrdersStore() const store = useFirstLegOrdersStore()
const tenantStore = useTenantAdministrationStore() const tenantStore = useTenantAdministrationStore()
@@ -84,7 +86,6 @@ const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit')) const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel')) const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel'))
const cancellingOrderId = ref('') const cancellingOrderId = ref('')
const pendingCancellation = shallowRef<{ id: string; expectedVersion: number; reason: string; businessNo: string; statusLabel: string }>()
function canOfferCancellation(order: FirstLegOrder) { function canOfferCancellation(order: FirstLegOrder) {
return canCancelOrder.value && ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE'].includes(order.status) return canCancelOrder.value && ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE'].includes(order.status)
@@ -94,40 +95,20 @@ async function cancelOrder(order: FirstLegOrder) {
if (!canOfferCancellation(order) || cancellingOrderId.value) return if (!canOfferCancellation(order) || cancellingOrderId.value) return
cancellingOrderId.value = order.id cancellingOrderId.value = order.id
try { try {
let command = pendingCancellation.value const target = await store.prepareCancellation(order.id)
if (command && command.id !== order.id) { const { value } = await ElMessageBox.prompt(
ElMessage.warning(`请先处理订单 ${command.businessNo} 未确认的取消结果`) `订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
return
}
if (!command) {
const target = await store.prepareCancellation(order.id)
const { value } = await ElMessageBox.prompt(`订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
type: 'warning', inputType: 'textarea', confirmButtonText: '确认取消订单', cancelButtonText: '返回', type: 'warning', inputType: 'textarea', confirmButtonText: '确认取消订单', cancelButtonText: '返回',
inputValidator: value => Boolean(value?.trim()) && value.trim().length <= 500 || '请填写 1–500 字取消原因', inputValidator: value => Boolean(value?.trim()) && value.trim().length <= 500 || '请填写 1–500 字取消原因',
}) })
command = { ...target, reason: value.trim() } await store.cancelOrder(target.id, target.expectedVersion, value.trim())
pendingCancellation.value = command ElMessage.success('订单已取消'); await loadOrderPage()
} else {
await ElMessageBox.confirm(`订单:${command.businessNo};原状态:${command.statusLabel};原因:${command.reason}。将查询当前状态并重试原取消请求。`, '重试取消订单', {
type: 'warning', confirmButtonText: '重试原请求', cancelButtonText: '返回',
})
}
await store.cancelOrder(command.id, command.expectedVersion, command.reason)
pendingCancellation.value = undefined
ElMessage.success('订单已取消')
await loadOrderPage()
if (isDetailPage.value) await router.push({ name: 'first-leg-orders' }) if (isDetailPage.value) await router.push({ name: 'first-leg-orders' })
} catch (error) { } catch (error) {
if (error === 'cancel' || error === 'close') return if (error === 'cancel' || error === 'close') return
if (error instanceof ApiError && (error.code === 'A0409' || error.status === 409)) { ElMessage.error(error instanceof Error ? error.message : '取消失败,请重新操作')
pendingCancellation.value = undefined void loadOrderPage()
ElMessage.error(`${error.message}。请刷新订单后重新确认取消。`) } finally { cancellingOrderId.value = '' }
} else {
ElMessage.error(error instanceof Error ? error.message : '取消失败,请重试原请求')
}
} finally {
cancellingOrderId.value = ''
}
} }
const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit')) const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit')) const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
@@ -202,8 +183,13 @@ const selectableOrderColumns: DataTableColumn[] = [
] ]
const allSelectableColumnKeys = selectableOrderColumns.map((column) => String(column.key)) const allSelectableColumnKeys = selectableOrderColumns.map((column) => String(column.key))
const defaultVisibleColumnKeys = ['status', 'progress', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt'] const defaultVisibleColumnKeys = ['status', 'progress', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt']
const visibleColumnKeys = ref<string[]>([...defaultVisibleColumnKeys]) const columnPreferencesOwnerId = auth.user?.id ?? ''
const orderedColumnKeys = ref<string[]>([...allSelectableColumnKeys]) const savedColumnPreferences = readOrderColumnPreferences(columnPreferencesOwnerId, allSelectableColumnKeys, defaultVisibleColumnKeys)
const visibleColumnKeys = ref<string[]>(savedColumnPreferences.visibleColumnKeys)
const orderedColumnKeys = ref<string[]>(savedColumnPreferences.orderedColumnKeys)
watch([visibleColumnKeys, orderedColumnKeys], ([visibleKeys, orderedKeys]) => {
saveOrderColumnPreferences(columnPreferencesOwnerId, { visibleColumnKeys: visibleKeys, orderedColumnKeys: orderedKeys })
}, { deep: true, flush: 'sync' })
const draggedColumnKey = ref('') const draggedColumnKey = ref('')
const orderedSelectableColumns = computed(() => orderedColumnKeys.value const orderedSelectableColumns = computed(() => orderedColumnKeys.value
.map((key) => selectableOrderColumns.find((column) => String(column.key) === key)) .map((key) => selectableOrderColumns.find((column) => String(column.key) === key))
@@ -241,7 +227,6 @@ const tablePageSize = ref(10)
const downloadingMarks = ref(false) const downloadingMarks = ref(false)
const exportingOrders = ref(false) const exportingOrders = ref(false)
const batchSubmitting = ref(false) const batchSubmitting = ref(false)
const pendingBatchSubmissionIds = ref<string[]>([])
const selectedOrders = ref<FirstLegOrder[]>([]) const selectedOrders = ref<FirstLegOrder[]>([])
const selectedOrderCount = computed(() => selectedOrders.value.length) const selectedOrderCount = computed(() => selectedOrders.value.length)
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT')) const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
@@ -371,9 +356,9 @@ function formatExportDateTime(value: string | null | undefined) {
} }
const pickupMethodLabels: Record<FirstLegOrder['pickupMethod'], string> = { const pickupMethodLabels: Record<FirstLegOrder['pickupMethod'], string> = {
SELF_EXPRESS: '自行快递到仓', SELF_TRUCK: '卡车自送',
PICKUP: '平台上门提货', PICKUP: '我司提货',
SELF_TRUCK: '自行送货到仓', SELF_EXPRESS: '快递自提',
} }
const destinationTypeLabels: Record<FirstLegOrder['destinationType'], string> = { const destinationTypeLabels: Record<FirstLegOrder['destinationType'], string> = {
FBA: 'FBA 仓', FBA: 'FBA 仓',
@@ -422,7 +407,8 @@ function emptyDraft(): FirstLegOrderDraft {
destinationCountryCode: 'US', destinationCountryCode: 'US',
destinationWarehouseId: '', destinationWarehouseId: '',
destinationWarehouseName: '', destinationWarehouseName: '',
pickupMethod: 'SELF_EXPRESS', pickupMethod: 'SELF_TRUCK',
trackingNumber: '',
channelCode: '', channelCode: '',
channelName: '', channelName: '',
pricingTaxMode: 'TAX_INCLUDED', pricingTaxMode: 'TAX_INCLUDED',
@@ -603,8 +589,10 @@ const pagedDetailCargoItems = computed(() => {
const progressSummaryItems = computed(() => { const progressSummaryItems = computed(() => {
const order = detailOrder.value const order = detailOrder.value
if (!order || order.status === 'CANCELLED') return [] if (!order || order.status === 'CANCELLED') return []
const inbound = inboundBilling.value?.inbound.summary const billing = inboundBillingOrderId.value === order.id ? inboundBilling.value : null
const inbound = billing?.inbound.summary
const summary = order.businessSummary const summary = order.businessSummary
const billingMetric = orderBillingMetric(billing, summary.chargeableWeightKg)
const formatMetric = (value: number | null | undefined, unit = '') => value == null ? '待更新' : `${value.toLocaleString()}${unit ? ` ${unit}` : ''}` const formatMetric = (value: number | null | undefined, unit = '') => value == null ? '待更新' : `${value.toLocaleString()}${unit ? ` ${unit}` : ''}`
const preloadStatus = ({ PENDING: '待确认', CONFIRMING: '确认中', CONFIRMED: '已确认' } as Record<string, string>)[summary.preloadStatus] ?? summary.preloadStatus const preloadStatus = ({ PENDING: '待确认', CONFIRMING: '确认中', CONFIRMED: '已确认' } as Record<string, string>)[summary.preloadStatus] ?? summary.preloadStatus
const transportReference = [summary.vesselName, summary.voyageNo].filter(Boolean).join(' · ') const transportReference = [summary.vesselName, summary.voyageNo].filter(Boolean).join(' · ')
@@ -615,12 +603,12 @@ const progressSummaryItems = computed(() => {
{ label: '实际箱数', value: formatMetric(summary.totalPackageCount ?? inbound?.totalPackageCount, '箱') }, { label: '实际箱数', value: formatMetric(summary.totalPackageCount ?? inbound?.totalPackageCount, '箱') },
{ label: '实测毛重', value: formatMetric(summary.actualGrossWeightKg ?? inbound?.actualGrossWeightKg, 'kg') }, { label: '实测毛重', value: formatMetric(summary.actualGrossWeightKg ?? inbound?.actualGrossWeightKg, 'kg') },
{ label: '实测体积', value: formatMetric(summary.actualVolumeCbm ?? inbound?.actualVolumeCbm, 'm³') }, { label: '实测体积', value: formatMetric(summary.actualVolumeCbm ?? inbound?.actualVolumeCbm, 'm³') },
{ label: '预装清单', value: preloadStatus ? `${preloadStatus}${summary.preloadItemCount == null ? '' : ` · ${summary.preloadItemCount} 项`}` : '待更新' }, { label: '预装确认', value: preloadStatus || '待更新' },
{ label: '拣货进度', value: pickingProgress }, { label: '拣货进度', value: pickingProgress },
{ label: '关联柜次', value: summary.cabinetNo || summary.containerNo || '—' }, { label: '关联柜次', value: summary.cabinetNo || summary.containerNo || '—' },
{ label: '船期摘要', value: transportReference || '待更新' }, { label: '船期摘要', value: transportReference || '待更新' },
{ label: '计费重量', value: formatMetric(summary.chargeableWeightKg, 'kg') }, { label: billingMetric.label, value: formatMetric(billingMetric.quantity, billingMetric.unit) },
{ label: '后续履约', value: summary.deliveryTrackingNo || (summary.deliveryCompletedAt ? `海外回传于 ${formatDateTime(summary.deliveryCompletedAt)}` : '待海外同步') }, { label: '后续履约', value: orderProgressLabel(store.orderProgress[order.id]) },
] ]
}) })
const cabinetProgressItems = computed(() => { const cabinetProgressItems = computed(() => {
@@ -917,6 +905,7 @@ function draftFromOrder(order: FirstLegOrder): FirstLegOrderDraft {
destinationWarehouseId: order.destinationWarehouseId, destinationWarehouseId: order.destinationWarehouseId,
destinationWarehouseName: order.destinationWarehouseName, destinationWarehouseName: order.destinationWarehouseName,
pickupMethod: order.pickupMethod, pickupMethod: order.pickupMethod,
trackingNumber: order.pickupMethod === 'SELF_EXPRESS' ? order.trackingNumber : '',
channelCode: order.channelCode, channelCode: order.channelCode,
channelName: order.channelName, channelName: order.channelName,
pricingTaxMode: order.pricingTaxMode, pricingTaxMode: order.pricingTaxMode,
@@ -939,6 +928,7 @@ function copyDraftFromOrder(order: FirstLegOrder): FirstLegOrderDraft {
return { return {
...draft, ...draft,
inboundCode: '', inboundCode: '',
trackingNumber: '',
items: draft.items.map((item) => ({ items: draft.items.map((item) => ({
...item, ...item,
id: `copied-cargo-${++cargoSequence}`, id: `copied-cargo-${++cargoSequence}`,
@@ -1131,6 +1121,7 @@ async function changeDestinationType() {
} }
function changePickupMethod() { function changePickupMethod() {
if (form.pickupMethod !== 'SELF_EXPRESS') form.trackingNumber = ''
if (form.pickupMethod === 'PICKUP') { if (form.pickupMethod === 'PICKUP') {
form.shipperPartySnapshot ??= createPickupPartySnapshot() form.shipperPartySnapshot ??= createPickupPartySnapshot()
} else { } else {
@@ -1361,7 +1352,7 @@ function getOrderRowActions(row: object): TableAction[] {
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) }) actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
} }
if (canOfferCancellation(order)) { if (canOfferCancellation(order)) {
actions.push({ key: 'cancel', label: pendingCancellation.value?.id === order.id ? '重试取消' : '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) }) actions.push({ key: 'cancel', label: '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) })
} }
if (eligibleCustomsDetail(order)) { if (eligibleCustomsDetail(order)) {
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) }) actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
@@ -1464,9 +1455,9 @@ async function loadDetailPage(orderId: string) {
function openFeeConfirmation(order: FirstLegOrder) { function openFeeConfirmation(order: FirstLegOrder) {
resetInboundBillingState() resetInboundBillingState()
inboundBillingUnavailableMessage.value = '未推送计费重' inboundBillingUnavailableMessage.value = '未推送费用'
feeConfirmationOpen.value = true feeConfirmationOpen.value = true
void loadInboundBilling(order, '未推送计费重') void loadInboundBilling(order, '未推送费用')
} }
async function retryDetail() { async function retryDetail() {
@@ -1501,7 +1492,7 @@ async function loadInboundBilling(order: FirstLegOrder, unavailableMessage = '
if (order.status === 'DRAFT') { if (order.status === 'DRAFT') {
inboundBillingUnavailable.value = true inboundBillingUnavailable.value = true
inboundBillingUnavailableMessage.value = feeConfirmationOpen.value inboundBillingUnavailableMessage.value = feeConfirmationOpen.value
? '未推送计费重' ? '未推送费用'
: '订单提交后可查看入库结果' : '订单提交后可查看入库结果'
return return
} }
@@ -1516,7 +1507,7 @@ async function loadInboundBilling(order: FirstLegOrder, unavailableMessage = '
if (error instanceof ApiError && error.code === 'A0404') { if (error instanceof ApiError && error.code === 'A0404') {
inboundBillingUnavailable.value = true inboundBillingUnavailable.value = true
inboundBillingUnavailableMessage.value = feeConfirmationOpen.value inboundBillingUnavailableMessage.value = feeConfirmationOpen.value
? '未推送计费重' ? '未推送费用'
: error.message || unavailableMessage : error.message || unavailableMessage
} else { } else {
inboundBillingError.value = error instanceof Error ? error.message : '入库与费用加载失败' inboundBillingError.value = error instanceof Error ? error.message : '入库与费用加载失败'
@@ -1528,7 +1519,7 @@ async function loadInboundBilling(order: FirstLegOrder, unavailableMessage = '
async function retryInboundBilling() { async function retryInboundBilling() {
const order = inboundBillingOrderId.value ? store.getById(inboundBillingOrderId.value) : undefined const order = inboundBillingOrderId.value ? store.getById(inboundBillingOrderId.value) : undefined
if (order) await loadInboundBilling(order, feeConfirmationOpen.value ? '未推送计费重' : '还未测量推送') if (order) await loadInboundBilling(order, feeConfirmationOpen.value ? '未推送费用' : '还未测量推送')
} }
function handleInboundFeeConfirmed() { function handleInboundFeeConfirmed() {
@@ -1744,14 +1735,14 @@ function handleOrderSelectionChange(rows: FirstLegOrder[]) {
} }
async function submitSelectedDraftOrders() { async function submitSelectedDraftOrders() {
const ids = [...new Set([...pendingBatchSubmissionIds.value, ...selectedDraftOrders.value.map(order => order.id)])] const ids = [...new Set(selectedDraftOrders.value.map(order => order.id))]
if (batchSubmitting.value || !ids.length) return if (batchSubmitting.value || !ids.length) return
if (companySubmissionBlocked.value) { if (companySubmissionBlocked.value) {
ElMessage.warning('企业资料审核通过后才能提交订单') ElMessage.warning('企业资料审核通过后才能提交订单')
return return
} }
try { try {
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?${pendingBatchSubmissionIds.value.length ? '上次结果未确认的订单将使用原提交命令重试。' : ''}`, '批量提交订单', { await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?`, '批量提交订单', {
type: 'warning', type: 'warning',
confirmButtonText: '确认提交', confirmButtonText: '确认提交',
cancelButtonText: '取消', cancelButtonText: '取消',
@@ -1764,7 +1755,6 @@ async function submitSelectedDraftOrders() {
batchSubmitting.value = true batchSubmitting.value = true
try { try {
const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined))) const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined)))
pendingBatchSubmissionIds.value = ids.filter((id, index) => results[index]?.status === 'rejected' && store.hasPendingSubmission(id))
const successCount = results.filter((result) => result.status === 'fulfilled').length const successCount = results.filter((result) => result.status === 'fulfilled').length
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected') const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
await searchOrders(appliedFilters.value) await searchOrders(appliedFilters.value)
@@ -2017,7 +2007,6 @@ async function saveDraft() {
if (!await validateEditorForm()) return if (!await validateEditorForm()) return
saving.value = true saving.value = true
try { try {
if (!await confirmSubmissionEdit()) return
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value) const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
editingId.value = order.id editingId.value = order.id
editingSession.value = store.beginDraftEdit(order) editingSession.value = store.beginDraftEdit(order)
@@ -2032,20 +2021,6 @@ async function saveDraft() {
} }
} }
async function confirmSubmissionEdit() {
if (!editingId.value || !store.hasPendingSubmission(editingId.value)) return true
try {
await ElMessageBox.confirm('上次提交结果尚未确认。确认重新读取订单并按当前表单重新编辑吗?只有服务端仍为草稿时才能开始新的提交决定。', '重新编辑订单', {
type: 'warning', center: true, confirmButtonText: '确认重新编辑', cancelButtonText: '返回',
})
} catch (error) {
if (error === 'cancel' || error === 'close') return false
throw error
}
editingSession.value = await store.beginNewSubmissionEdit(editingId.value)
return true
}
async function submitOrder() { async function submitOrder() {
if (saving.value) return if (saving.value) return
if (companySubmissionBlocked.value) { if (companySubmissionBlocked.value) {
@@ -2064,14 +2039,12 @@ async function submitOrder() {
} }
return return
} }
const retry = store.isSubmissionRetry(editingId.value, cloneDraft(form)) if (!await validateEditorForm()) return
if (!retry && !await validateEditorForm()) return
try { try {
saving.value = true saving.value = true
if (!retry && !await confirmSubmissionEdit()) return
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
const savedOrder = await store.saveDraftForSubmission(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value) const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
editingId.value = savedOrder.id editingId.value = savedOrder.id
editingSession.value = store.beginDraftEdit(savedOrder) editingSession.value = store.beginDraftEdit(savedOrder)
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus) await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
@@ -2108,16 +2081,16 @@ async function searchOrders(model: QueryModel) {
<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" /> <QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" />
<div class="client-card order-table-card"> <div class="client-card order-table-card">
<nav class="order-queue-tabs" aria-label="订单事项分类">
<button v-for="queue in ORDER_QUEUES" :key="queue.key" type="button"
:class="{ active: activeOrderQueue === queue.key }" :aria-pressed="activeOrderQueue === queue.key"
@click="selectOrderQueue(queue.key)">
{{ queue.label }}<span v-if="queue.key !== 'all' && orderQueueCounts[queue.key]"
:class="queue.todo ? 'queue-count' : 'queue-stage-count'">{{ queue.todo ? orderQueueCounts[queue.key] : `(${orderQueueCounts[queue.key]})` }}</span>
</button>
</nav>
<DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="store.total" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange"> <DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="store.total" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange">
<template #toolbar> <template #toolbar>
<nav class="order-queue-tabs" aria-label="订单事项分类">
<button v-for="queue in ORDER_QUEUES" :key="queue.key" type="button"
:class="{ active: activeOrderQueue === queue.key }" :aria-pressed="activeOrderQueue === queue.key"
@click="selectOrderQueue(queue.key)">
{{ queue.label }}<span v-if="queue.key !== 'all' && orderQueueCounts[queue.key]"
:class="queue.todo ? 'queue-count' : 'queue-stage-count'">{{ queue.todo ? orderQueueCounts[queue.key] : `(${orderQueueCounts[queue.key]})` }}</span>
</button>
</nav>
<span v-if="selectedOrderCount">已选 {{ selectedOrderCount }} 条</span> <span v-if="selectedOrderCount">已选 {{ selectedOrderCount }} 条</span>
</template> </template>
<template #toolbar-actions> <template #toolbar-actions>
@@ -2126,7 +2099,7 @@ async function searchOrders(model: QueryModel) {
<el-button class="column-settings-trigger" aria-label="设置订单列表显示列" title="设置显示列"><SlidersHorizontal :size="18" />显示字段筛选</el-button> <el-button class="column-settings-trigger" aria-label="设置订单列表显示列" title="设置显示列"><SlidersHorizontal :size="18" />显示字段筛选</el-button>
</template> </template>
<div class="column-settings-panel"> <div class="column-settings-panel">
<p>拖动调整顺序,也可使用上下移动按钮。</p>
<el-checkbox-group v-model="visibleColumnKeys" aria-label="订单列表显示列"> <el-checkbox-group v-model="visibleColumnKeys" aria-label="订单列表显示列">
<div <div
v-for="(column, index) in orderedSelectableColumns" v-for="(column, index) in orderedSelectableColumns"
@@ -2149,7 +2122,7 @@ async function searchOrders(model: QueryModel) {
</el-popover> </el-popover>
<el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button> <el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button>
<el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button> <el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button>
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="(selectedDraftOrders.length === 0 && pendingBatchSubmissionIds.length === 0) || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />{{ pendingBatchSubmissionIds.length ? '重试批量提交' : '批量提交草稿' }}</el-button> <el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="selectedDraftOrders.length === 0 || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />批量提交草稿</el-button>
<el-button v-if="auth.hasPermission('order:first-leg:create')" @click="openBatchImport"><Upload :size="17" />批量导入订单</el-button> <el-button v-if="auth.hasPermission('order:first-leg:create')" @click="openBatchImport"><Upload :size="17" />批量导入订单</el-button>
<el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button> <el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button>
@@ -2237,17 +2210,18 @@ async function searchOrders(model: QueryModel) {
<div class="order-section-heading"><span class="order-step-badge">01</span><h3>客户下单</h3><span class="order-section-context">国内交货与运输信息</span></div> <div class="order-section-heading"><span class="order-step-badge">01</span><h3>客户下单</h3><span class="order-section-context">国内交货与运输信息</span></div>
<div class="prototype-form-flow shipping-form-flow"> <div class="prototype-form-flow shipping-form-flow">
<el-form-item label="履约类型" prop="fulfillmentType" required class="prototype-form-row prototype-form-row--tabs"><el-radio-group v-model="form.fulfillmentType" class="segmented-options" @change="changeFulfillmentType"><el-radio-button value="STANDARD">普通头程</el-radio-button><el-radio-button value="ONE_CLICK_DROPSHIP">一件代发</el-radio-button></el-radio-group><small v-if="form.fulfillmentType === 'ONE_CLICK_DROPSHIP'" class="field-guidance">测量完成后不办理国内库存入库,将直接推送 PDA 合托。</small></el-form-item> <el-form-item label="履约类型" prop="fulfillmentType" required class="prototype-form-row prototype-form-row--tabs"><el-radio-group v-model="form.fulfillmentType" class="segmented-options" @change="changeFulfillmentType"><el-radio-button value="STANDARD">普通头程</el-radio-button><el-radio-button value="ONE_CLICK_DROPSHIP">一件代发</el-radio-button></el-radio-group><small v-if="form.fulfillmentType === 'ONE_CLICK_DROPSHIP'" class="field-guidance">测量完成后不办理国内库存入库,将直接推送 PDA 合托。</small></el-form-item>
<el-form-item v-if="form.fulfillmentType === 'ONE_CLICK_DROPSHIP'" label="LX入库单号" prop="lxCode" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.lxCode" maxlength="128" placeholder="请输入LX入库单号" /><small class="field-guidance">用于绑定领星入库单,提交后可在尾程订单、入库单和出库单中查询。</small></el-form-item> <el-form-item v-if="form.fulfillmentType === 'ONE_CLICK_DROPSHIP'" label="LX入库单号" prop="lxCode" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.lxCode" maxlength="128" placeholder="" /></el-form-item>
<el-form-item label="取货方式" prop="pickupMethod" required class="prototype-form-row prototype-form-row--tabs"><el-radio-group v-model="form.pickupMethod" class="segmented-options" @change="changePickupMethod"><el-radio-button value="SELF_EXPRESS">快递自送</el-radio-button><el-radio-button value="PICKUP">我司提货</el-radio-button><el-radio-button value="SELF_TRUCK">卡车自送</el-radio-button></el-radio-group></el-form-item> <el-form-item label="取货方式" prop="pickupMethod" required class="prototype-form-row prototype-form-row--tabs"><el-radio-group v-model="form.pickupMethod" class="segmented-options" @change="changePickupMethod"><el-radio-button value="SELF_TRUCK">卡车自送</el-radio-button><el-radio-button value="PICKUP">我司提货</el-radio-button><el-radio-button value="SELF_EXPRESS">快递自提</el-radio-button></el-radio-group></el-form-item>
<el-form-item v-if="form.pickupMethod === 'SELF_EXPRESS'" label="快递单号" prop="trackingNumber" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.trackingNumber" maxlength="128" placeholder="" /></el-form-item>
<template v-if="form.pickupMethod === 'PICKUP' && form.shipperPartySnapshot"> <template v-if="form.pickupMethod === 'PICKUP' && form.shipperPartySnapshot">
<el-form-item label="企业提货地址簿" prop="senderAddressId" required :rules="requiredSelectRules('请选择企业提货地址')" class="prototype-form-row prototype-form-row--wide address-book-row"> <el-form-item label="企业提货地址簿" prop="senderAddressId" required :rules="requiredSelectRules('请选择企业提货地址')" class="prototype-form-row prototype-form-row--wide address-book-row">
<div class="address-book-control"><el-select v-model="form.senderAddressId" clearable filterable :loading="orderAddressesLoading" placeholder="选择企业保存的提货地址" @change="selectPickupAddress"><el-option v-for="address in pickupAddresses" :key="String(address.id)" :label="addressLabel(address)" :value="String(address.id)" /></el-select><el-button @click="savePickupAddress">保存当前地址</el-button><el-button v-if="form.senderAddressId" link type="danger" @click="removeOrderAddress('PICKUP')">停用</el-button></div> <div class="address-book-control"><el-select v-model="form.senderAddressId" clearable filterable :loading="orderAddressesLoading" placeholder="选择企业保存的提货地址" @change="selectPickupAddress"><el-option v-for="address in pickupAddresses" :key="String(address.id)" :label="addressLabel(address)" :value="String(address.id)" /></el-select><el-button @click="savePickupAddress">保存当前地址</el-button><el-button v-if="form.senderAddressId" link type="danger" @click="removeOrderAddress('PICKUP')">停用</el-button></div>
</el-form-item> </el-form-item>
<el-form-item label="提货联系人" prop="shipperPartySnapshot.contactName" required :rules="requiredTextRules('请输入提货联系人')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.contactName" maxlength="50" placeholder="请输入联系人姓名" /></el-form-item> <el-form-item label="提货联系人" prop="shipperPartySnapshot.contactName" required :rules="requiredTextRules('请输入提货联系人')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.contactName" maxlength="50" placeholder="" /></el-form-item>
<el-form-item label="联系电话" prop="shipperPartySnapshot.phone" required :rules="requiredTextRules('请输入提货联系电话')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.phone" maxlength="30" placeholder="请输入联系电话" /></el-form-item> <el-form-item label="联系电话" prop="shipperPartySnapshot.phone" required :rules="requiredTextRules('请输入提货联系电话')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.phone" maxlength="30" placeholder="" /></el-form-item>
<el-form-item label="州 / 省" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.province" maxlength="100" placeholder="请输入州或省" /></el-form-item> <el-form-item label="州 / 省" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.province" maxlength="100" placeholder="" /></el-form-item>
<el-form-item label="城市" prop="shipperPartySnapshot.city" required :rules="requiredTextRules('请输入提货城市')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.city" maxlength="100" placeholder="请输入城市" /></el-form-item> <el-form-item label="城市" prop="shipperPartySnapshot.city" required :rules="requiredTextRules('请输入提货城市')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.shipperPartySnapshot.city" maxlength="100" placeholder="" /></el-form-item>
<el-form-item label="提货地址" prop="shipperPartySnapshot.address" required :rules="requiredTextRules('请输入提货地址')" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.shipperPartySnapshot.address" maxlength="300" placeholder="请输入详细提货地址" /></el-form-item> <el-form-item label="提货地址" prop="shipperPartySnapshot.address" required :rules="requiredTextRules('请输入提货地址')" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.shipperPartySnapshot.address" maxlength="300" placeholder="" /></el-form-item>
</template> </template>
<el-form-item label="国内收货仓" prop="receivingWarehouseId" required class="prototype-form-row prototype-form-row--wide"><el-radio-group v-model="form.receivingWarehouseId" class="warehouse-options" @change="loadSelectedWarehouse"><el-radio v-for="warehouse in availableWarehouses" :key="warehouse.id" :value="warehouse.id">{{ warehouse.name }}</el-radio></el-radio-group></el-form-item> <el-form-item label="国内收货仓" prop="receivingWarehouseId" required class="prototype-form-row prototype-form-row--wide"><el-radio-group v-model="form.receivingWarehouseId" class="warehouse-options" @change="loadSelectedWarehouse"><el-radio v-for="warehouse in availableWarehouses" :key="warehouse.id" :value="warehouse.id">{{ warehouse.name }}</el-radio></el-radio-group></el-form-item>
</div> </div>
@@ -2267,8 +2241,8 @@ async function searchOrders(model: QueryModel) {
</el-form-item> </el-form-item>
<el-form-item label="买单 / 退税" prop="taxMode" required><el-radio-group v-model="form.taxMode"><el-radio value="BUY_DECLARATION">买单</el-radio><el-radio value="TAX_REFUND">退税</el-radio></el-radio-group></el-form-item> <el-form-item label="买单 / 退税" prop="taxMode" required><el-radio-group v-model="form.taxMode"><el-radio value="BUY_DECLARATION">买单</el-radio><el-radio value="TAX_REFUND">退税</el-radio></el-radio-group></el-form-item>
<el-form-item label="是否整柜" prop="transportMode" required><el-radio-group v-model="form.transportMode"><el-radio value="FCL">整柜</el-radio><el-radio value="LCL">散货</el-radio></el-radio-group></el-form-item> <el-form-item label="是否整柜" prop="transportMode" required><el-radio-group v-model="form.transportMode"><el-radio value="FCL">整柜</el-radio><el-radio value="LCL">散货</el-radio></el-radio-group></el-form-item>
<el-form-item label="期望出货日期"><el-date-picker v-model="form.expectedDepartureDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择期望出货日期" /></el-form-item> <el-form-item label="期望出货日期"><el-date-picker v-model="form.expectedDepartureDate" type="date" value-format="YYYY-MM-DD" placeholder="" /></el-form-item>
<el-form-item label="订单备注"><el-input v-model="form.customerRemark" type="textarea" :rows="3" resize="vertical" maxlength="300" show-word-limit placeholder="选填,例如:入仓前请电话联系" /></el-form-item> <el-form-item label="订单备注"><el-input v-model="form.customerRemark" type="textarea" :rows="3" resize="vertical" maxlength="300" show-word-limit placeholder="" /></el-form-item>
</div> </div>
</section> </section>
@@ -2281,17 +2255,17 @@ async function searchOrders(model: QueryModel) {
<div class="address-book-control"><el-select v-model="form.privateDestinationAddressId" clearable filterable :loading="orderAddressesLoading" placeholder="选择企业保存的私人仓地址" @change="selectPrivateAddress"><el-option v-for="address in privateAddresses" :key="String(address.id)" :label="addressLabel(address)" :value="String(address.id)" /></el-select><el-button @click="savePrivateAddress">保存当前地址</el-button><el-button v-if="form.privateDestinationAddressId" link type="danger" @click="removeOrderAddress('PRIVATE_DESTINATION')">停用</el-button></div> <div class="address-book-control"><el-select v-model="form.privateDestinationAddressId" clearable filterable :loading="orderAddressesLoading" placeholder="选择企业保存的私人仓地址" @change="selectPrivateAddress"><el-option v-for="address in privateAddresses" :key="String(address.id)" :label="addressLabel(address)" :value="String(address.id)" /></el-select><el-button @click="savePrivateAddress">保存当前地址</el-button><el-button v-if="form.privateDestinationAddressId" link type="danger" @click="removeOrderAddress('PRIVATE_DESTINATION')">停用</el-button></div>
</el-form-item> </el-form-item>
<el-form-item v-if="form.destinationType !== 'PRIVATE'" :label="form.destinationType === 'FBA' ? 'FBA 仓' : '海外仓'" prop="destinationWarehouseId" required :rules="requiredSelectRules('请选择平台维护的目的仓')" class="prototype-form-row"><el-select v-model="form.destinationWarehouseId" filterable :loading="destinationWarehousesLoading" placeholder="请选择当前可送达的目的仓" @change="selectDestinationWarehouse"><el-option v-for="warehouse in availableDestinationWarehouses" :key="warehouse.id" :label="form.destinationType === 'FBA' ? warehouse.code : `${warehouse.name} · ${warehouse.code}`" :value="warehouse.id" /></el-select><small v-if="!destinationWarehousesLoading && availableDestinationWarehouses.length === 0" class="field-guidance">平台暂未维护可用的{{ form.destinationType === 'FBA' ? ' FBA 仓' : '海外仓' }},请联系平台管理员。</small></el-form-item> <el-form-item v-if="form.destinationType !== 'PRIVATE'" :label="form.destinationType === 'FBA' ? 'FBA 仓' : '海外仓'" prop="destinationWarehouseId" required :rules="requiredSelectRules('请选择平台维护的目的仓')" class="prototype-form-row"><el-select v-model="form.destinationWarehouseId" filterable :loading="destinationWarehousesLoading" placeholder="" @change="selectDestinationWarehouse"><el-option v-for="warehouse in availableDestinationWarehouses" :key="warehouse.id" :label="form.destinationType === 'FBA' ? warehouse.code : `${warehouse.name} · ${warehouse.code}`" :value="warehouse.id" /></el-select><small v-if="!destinationWarehousesLoading && availableDestinationWarehouses.length === 0" class="field-guidance">平台暂未维护可用的{{ form.destinationType === 'FBA' ? ' FBA 仓' : '海外仓' }},请联系平台管理员。</small></el-form-item>
<div v-if="form.destinationType !== 'PRIVATE' && selectedDestinationWarehouse" class="selected-destination"><MapPin :size="17" /><div><span>{{ form.destinationType === 'FBA' ? selectedDestinationWarehouse.code : `${selectedDestinationWarehouse.name} · ${selectedDestinationWarehouse.code}` }} · {{ selectedDestinationWarehouse.countryCode }}</span><small v-if="selectedDestinationWarehouse.address">仓库地址:{{ selectedDestinationWarehouse.province }}{{ selectedDestinationWarehouse.city }} {{ selectedDestinationWarehouse.address }}</small><small v-if="selectedDestinationWarehouse.contactName || selectedDestinationWarehouse.contactPhone">联系人:{{ selectedDestinationWarehouse.contactName || '-' }} {{ selectedDestinationWarehouse.contactPhone }}</small></div></div> <div v-if="form.destinationType !== 'PRIVATE' && selectedDestinationWarehouse" class="selected-destination"><MapPin :size="17" /><div><span>{{ form.destinationType === 'FBA' ? selectedDestinationWarehouse.code : `${selectedDestinationWarehouse.name} · ${selectedDestinationWarehouse.code}` }} · {{ selectedDestinationWarehouse.countryCode }}</span><small v-if="selectedDestinationWarehouse.address">仓库地址:{{ selectedDestinationWarehouse.province }}{{ selectedDestinationWarehouse.city }} {{ selectedDestinationWarehouse.address }}</small><small v-if="selectedDestinationWarehouse.contactName || selectedDestinationWarehouse.contactPhone">联系人:{{ selectedDestinationWarehouse.contactName || '-' }} {{ selectedDestinationWarehouse.contactPhone }}</small></div></div>
<template v-if="form.destinationType === 'PRIVATE' && form.consigneePartySnapshot"> <template v-if="form.destinationType === 'PRIVATE' && form.consigneePartySnapshot">
<el-form-item label="私人地址名称" prop="destinationWarehouseName" required class="prototype-form-row"><el-input v-model="form.destinationWarehouseName" maxlength="128" placeholder="例如:洛杉矶客户自有仓" @input="syncPrivateDestinationName" /></el-form-item> <el-form-item label="私人地址名称" prop="destinationWarehouseName" required class="prototype-form-row"><el-input v-model="form.destinationWarehouseName" maxlength="128" placeholder="例如:洛杉矶客户自有仓" @input="syncPrivateDestinationName" /></el-form-item>
<el-form-item label="收件人姓名" prop="consigneePartySnapshot.contactName" required :rules="requiredTextRules('请输入收货联系人姓名')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.contactName" maxlength="50" placeholder="请输入收件人姓名" /></el-form-item> <el-form-item label="收件人姓名" prop="consigneePartySnapshot.contactName" required :rules="requiredTextRules('请输入收货联系人姓名')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.contactName" maxlength="50" placeholder="" /></el-form-item>
<el-form-item label="收件人电话" prop="consigneePartySnapshot.phone" required :rules="requiredTextRules('请输入收货联系电话')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.phone" maxlength="30" placeholder="请输入收件人电话" /></el-form-item> <el-form-item label="收件人电话" prop="consigneePartySnapshot.phone" required :rules="requiredTextRules('请输入收货联系电话')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.phone" maxlength="30" placeholder="" /></el-form-item>
<el-form-item label="收件国家代码" prop="destinationCountryCode" required class="prototype-form-row prototype-form-row--short"><el-input v-model="form.destinationCountryCode" maxlength="2" placeholder="例如:US" /></el-form-item> <el-form-item label="收件国家代码" prop="destinationCountryCode" required class="prototype-form-row prototype-form-row--short"><el-input v-model="form.destinationCountryCode" maxlength="2" placeholder="例如:US" /></el-form-item>
<el-form-item label="州 / 省" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.province" maxlength="100" placeholder="请输入州或省" /></el-form-item> <el-form-item label="州 / 省" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.province" maxlength="100" placeholder="" /></el-form-item>
<el-form-item label="城市" prop="consigneePartySnapshot.city" required :rules="requiredTextRules('请输入收件城市')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.city" maxlength="100" placeholder="请输入城市" /></el-form-item> <el-form-item label="城市" prop="consigneePartySnapshot.city" required :rules="requiredTextRules('请输入收件城市')" class="prototype-form-row prototype-form-row--compact"><el-input v-model="form.consigneePartySnapshot.city" maxlength="100" placeholder="" /></el-form-item>
<el-form-item label="收件地址" prop="consigneePartySnapshot.address" required :rules="requiredTextRules('请输入本单实际收货地址')" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.consigneePartySnapshot.address" maxlength="300" placeholder="请输入收件详细地址" /></el-form-item> <el-form-item label="收件地址" prop="consigneePartySnapshot.address" required :rules="requiredTextRules('请输入本单实际收货地址')" class="prototype-form-row prototype-form-row--wide"><el-input v-model="form.consigneePartySnapshot.address" maxlength="300" placeholder="" /></el-form-item>
<el-form-item label="邮编" class="prototype-form-row prototype-form-row--short"><el-input v-model="form.consigneePartySnapshot.postalCode" maxlength="20" placeholder="请输入邮编" /></el-form-item> <el-form-item label="邮编" class="prototype-form-row prototype-form-row--short"><el-input v-model="form.consigneePartySnapshot.postalCode" maxlength="20" placeholder="" /></el-form-item>
</template> </template>
</div> </div>
</section> </section>
@@ -2302,9 +2276,9 @@ async function searchOrders(model: QueryModel) {
<div v-if="isCreatePage && !routeDraftId && canCreateOrder" class="cargo-import-actions"> <div v-if="isCreatePage && !routeDraftId && canCreateOrder" class="cargo-import-actions">
<el-button class="cargo-download-button" :loading="batchTemplateDownloading" @click="downloadBatchTemplate"><Download :size="16" />下载 Excel 模板</el-button> <el-button class="cargo-download-button" :loading="batchTemplateDownloading" @click="downloadBatchTemplate"><Download :size="16" />下载 Excel 模板</el-button>
<el-button class="cargo-upload-button" type="primary" plain @click="openBatchImport"><Upload :size="16" />Excel 批量导入</el-button> <el-button class="cargo-upload-button" type="primary" plain @click="openBatchImport"><Upload :size="16" />Excel 批量导入</el-button>
<span class="cargo-table-hint">Excel 导入用于一次创建多条订单草稿。</span>
</div> </div>
<span v-else class="cargo-table-hint">可逐行维护货物明细。</span>
<div class="cargo-table-actions"><el-button @click="addCargoItem"><Plus :size="16" />添加行</el-button><el-button type="danger" plain :disabled="!selectedCargoIds.length" @click="removeSelectedCargoItems"><Trash2 :size="15" />删除所选行</el-button></div> <div class="cargo-table-actions"><el-button @click="addCargoItem"><Plus :size="16" />添加行</el-button><el-button type="danger" plain :disabled="!selectedCargoIds.length" @click="removeSelectedCargoItems"><Trash2 :size="15" />删除所选行</el-button></div>
</div> </div>
<div class="cargo-table-wrap" :class="{ 'is-dropship': form.fulfillmentType === 'ONE_CLICK_DROPSHIP' }"> <div class="cargo-table-wrap" :class="{ 'is-dropship': form.fulfillmentType === 'ONE_CLICK_DROPSHIP' }">
@@ -2327,7 +2301,7 @@ async function searchOrders(model: QueryModel) {
<td><el-form-item :prop="`items.${index}.unitsPerPackage`" required :rules="positiveNumberRules('每箱数量必须大于 0', true)"><el-input-number v-model="item.unitsPerPackage" :min="1" :controls="false" placeholder="每箱数量" @change="syncSkuQuantity(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-form-item v-else :prop="`items.${index}.packageCount`" required :rules="positiveNumberRules('箱数必须大于 0', true)"><el-input-number v-model="item.packageCount" :min="1" :controls="false" placeholder="箱数" @change="syncPackingGroupFields(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-form-item v-else :prop="`items.${index}.grossWeightKg`" required :rules="positiveNumberRules('总毛重必须大于 0')"><el-input-number v-model="item.grossWeightKg" :min="0" :precision="3" :controls="false" placeholder="总毛重" @change="syncPackingGroupFields(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-form-item v-else :prop="`items.${index}.volumeCbm`" required :rules="positiveNumberRules('总体积必须大于 0')"><el-input-number v-model="item.volumeCbm" :min="0" :precision="4" :controls="false" placeholder="总体积" @change="syncPackingGroupFields(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="derived-sku-value">{{ item.pieces }}</span><el-form-item v-else :prop="`items.${index}.pieces`" required :rules="positiveNumberRules('总数量必须大于 0', true)"><el-input-number v-model="item.pieces" :min="1" :controls="false" placeholder="总数量" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-input-number v-else v-model="item.netWeightKg" :min="0" :precision="3" :controls="false" placeholder="净重" @change="syncPackingGroupFields(item)" /></td> <td><el-form-item :prop="`items.${index}.unitsPerPackage`" required :rules="positiveNumberRules('每箱数量必须大于 0', true)"><el-input-number v-model="item.unitsPerPackage" :min="1" :controls="false" placeholder="每箱数量" @change="syncSkuQuantity(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-form-item v-else :prop="`items.${index}.packageCount`" required :rules="positiveNumberRules('箱数必须大于 0', true)"><el-input-number v-model="item.packageCount" :min="1" :controls="false" placeholder="箱数" @change="syncPackingGroupFields(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-form-item v-else :prop="`items.${index}.grossWeightKg`" required :rules="positiveNumberRules('总毛重必须大于 0')"><el-input-number v-model="item.grossWeightKg" :min="0" :precision="3" :controls="false" placeholder="总毛重" @change="syncPackingGroupFields(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-form-item v-else :prop="`items.${index}.volumeCbm`" required :rules="positiveNumberRules('总体积必须大于 0')"><el-input-number v-model="item.volumeCbm" :min="0" :precision="4" :controls="false" placeholder="总体积" @change="syncPackingGroupFields(item)" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="derived-sku-value">{{ item.pieces }}</span><el-form-item v-else :prop="`items.${index}.pieces`" required :rules="positiveNumberRules('总数量必须大于 0', true)"><el-input-number v-model="item.pieces" :min="1" :controls="false" placeholder="总数量" /></el-form-item></td><td><span v-if="isAdditionalMixedSku(item, index)" class="shared-carton-value">同箱</span><el-input-number v-else v-model="item.netWeightKg" :min="0" :precision="3" :controls="false" placeholder="净重" @change="syncPackingGroupFields(item)" /></td>
<td><el-input-number v-model="item.unitDeclaredValue" :min="0" :precision="2" :controls="false" placeholder="申报单价" /></td><td><el-input-number v-model="item.declaredValue" :min="0" :precision="2" :controls="false" placeholder="申报总价" /></td><td><el-input v-model="item.usage" maxlength="128" placeholder="用途" /></td><td><el-input v-model="item.model" maxlength="64" placeholder="型号" /></td><td><el-input v-model="item.brand" maxlength="64" placeholder="品牌" /></td> <td><el-input-number v-model="item.unitDeclaredValue" :min="0" :precision="2" :controls="false" placeholder="申报单价" /></td><td><el-input-number v-model="item.declaredValue" :min="0" :precision="2" :controls="false" placeholder="申报总价" /></td><td><el-input v-model="item.usage" maxlength="128" placeholder="用途" /></td><td><el-input v-model="item.model" maxlength="64" placeholder="型号" /></td><td><el-input v-model="item.brand" maxlength="64" placeholder="品牌" /></td>
<td class="cargo-dimensions-column"><div class="cargo-table-dimensions"><el-input-number v-model="item.productLengthCm" :min="0" :precision="2" :controls="false" placeholder="长" /><span>×</span><el-input-number v-model="item.productWidthCm" :min="0" :precision="2" :controls="false" placeholder="宽" /><span>×</span><el-input-number v-model="item.productHeightCm" :min="0" :precision="2" :controls="false" placeholder="高" /></div></td> <td class="cargo-dimensions-column"><div class="cargo-table-dimensions"><el-input-number v-model="item.productLengthCm" :min="0" :precision="2" :controls="false" placeholder="长" /><span>×</span><el-input-number v-model="item.productWidthCm" :min="0" :precision="2" :controls="false" placeholder="宽" /><span>×</span><el-input-number v-model="item.productHeightCm" :min="0" :precision="2" :controls="false" placeholder="高" /></div></td>
<td><el-form-item :prop="`items.${index}.shipmentId`" :required="form.destinationType === 'FBA'" :rules="form.destinationType === 'FBA' ? requiredTextRules('FBA 货物请输入货件编号') : undefined"><el-input v-model="item.shipmentId" maxlength="64" placeholder="货件编号" /></el-form-item></td><td><el-form-item :prop="`items.${index}.referenceId`" :required="form.destinationType === 'FBA'" :rules="form.destinationType === 'FBA' ? requiredTextRules('FBA 货物请输入跟踪编号') : undefined"><el-input v-model="item.referenceId" maxlength="64" placeholder="跟踪编号" /></el-form-item></td><td><el-form-item :prop="`items.${index}.upc`"><el-input v-model="item.upc" maxlength="64" placeholder="UPC NO.(选填)" /></el-form-item></td><td><el-input v-model="item.remark" maxlength="500" placeholder="备注" /></td><td class="cargo-operation-column"><el-button v-if="form.fulfillmentType === 'ONE_CLICK_DROPSHIP'" link type="primary" :aria-label="`为货物 ${index + 1} 添加同箱 SKU`" @click="addSkuToPackingGroup(index)"><Plus :size="15" />添加 SKU</el-button><el-button link type="danger" :aria-label="`删除货物 ${index + 1}`" @click="removeCargoItem(index)"><Trash2 :size="15" />删除</el-button></td> <td><el-form-item :prop="`items.${index}.shipmentId`" :required="form.destinationType === 'FBA'" :rules="form.destinationType === 'FBA' ? requiredTextRules('FBA 货物请输入货件编号') : undefined"><el-input v-model="item.shipmentId" maxlength="64" placeholder="货件编号" /></el-form-item></td><td><el-form-item :prop="`items.${index}.referenceId`" :required="form.destinationType === 'FBA'" :rules="form.destinationType === 'FBA' ? requiredTextRules('FBA 货物请输入跟踪编号') : undefined"><el-input v-model="item.referenceId" maxlength="64" placeholder="跟踪编号" /></el-form-item></td><td><el-form-item :prop="`items.${index}.upc`"><el-input v-model="item.upc" maxlength="64" placeholder="UPC NO.(选填)" /></el-form-item></td><td><el-input v-model="item.remark" maxlength="500" placeholder="" /></td><td class="cargo-operation-column"><el-button v-if="form.fulfillmentType === 'ONE_CLICK_DROPSHIP'" link type="primary" :aria-label="`为货物 ${index + 1} 添加同箱 SKU`" @click="addSkuToPackingGroup(index)"><Plus :size="15" />添加 SKU</el-button><el-button link type="danger" :aria-label="`删除货物 ${index + 1}`" @click="removeCargoItem(index)"><Trash2 :size="15" />删除</el-button></td>
</tr></tbody> </tr></tbody>
</table> </table>
</div> </div>
@@ -2335,7 +2309,7 @@ async function searchOrders(model: QueryModel) {
</section> </section>
<section class="order-form-section prototype-section cost-estimate-section" aria-label="费用预估"> <section class="order-form-section prototype-section cost-estimate-section" aria-label="费用预估">
<div class="order-section-heading"><div><h3>参考运费</h3><p>根据当前价格表、渠道、目的仓以及货物重量和体积实时试算。</p></div></div> <div class="order-section-heading"><div><h3>参考运费</h3></div></div>
<div class="price-estimate" :class="{ 'is-loading': priceEstimateLoading }" aria-live="polite"> <div class="price-estimate" :class="{ 'is-loading': priceEstimateLoading }" aria-live="polite">
<div v-if="priceEstimateLoading" class="price-estimate__state" v-loading="true">正在获取实时参考报价</div> <div v-if="priceEstimateLoading" class="price-estimate__state" v-loading="true">正在获取实时参考报价</div>
<div v-else-if="priceEstimateError" class="price-estimate__state is-error" role="alert"> <div v-else-if="priceEstimateError" class="price-estimate__state is-error" role="alert">
@@ -2413,9 +2387,9 @@ async function searchOrders(model: QueryModel) {
<div class="order-detail-heading"> <div class="order-detail-heading">
<div class="detail-heading-main"> <div class="detail-heading-main">
<el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button> <el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button>
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'CANCELLED' ? (detailOrder.orderNo || '—') : detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p v-if="detailOrder.status === 'CANCELLED'">订单已取消。</p><p v-else>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div> <div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'CANCELLED' ? (detailOrder.orderNo || '—') : detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2></div>
</div> </div>
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button><el-button v-if="canOfferCancellation(detailOrder)" type="danger" plain :loading="cancellingOrderId === detailOrder.id" :disabled="!!cancellingOrderId" @click="cancelOrder(detailOrder)">{{ pendingCancellation?.id === detailOrder.id ? '重试取消' : '取消订单' }}</el-button></div> <div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button><el-button v-if="canOfferCancellation(detailOrder)" type="danger" plain :loading="cancellingOrderId === detailOrder.id" :disabled="!!cancellingOrderId" @click="cancelOrder(detailOrder)">取消订单</el-button></div>
</div> </div>
<section class="detail-section"> <section class="detail-section">
<h3>订单与运输</h3> <h3>订单与运输</h3>
@@ -2463,7 +2437,7 @@ async function searchOrders(model: QueryModel) {
<el-table-column label="预计船期" width="170"><template #default="{ row }">{{ row.estimatedSailingAt ? formatDateTime(row.estimatedSailingAt) : '待更新' }}</template></el-table-column> <el-table-column label="预计船期" width="170"><template #default="{ row }">{{ row.estimatedSailingAt ? formatDateTime(row.estimatedSailingAt) : '待更新' }}</template></el-table-column>
<el-table-column prop="pickingStatusLabel" label="拣货状态" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.pickingStatusLabel }}</el-tag></template></el-table-column> <el-table-column prop="pickingStatusLabel" label="拣货状态" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.pickingStatusLabel }}</el-tag></template></el-table-column>
</el-table> </el-table>
<p v-else class="detail-inline-empty">尚未分配柜次,后续柜次节点将在这里同步。</p> <p v-else class="detail-inline-empty">尚未分配柜次</p>
<TransportFactsTable :fragments="detailOrder.businessSummary.transportFragments" /> <TransportFactsTable :fragments="detailOrder.businessSummary.transportFragments" />
</div> </div>
</template> </template>
@@ -2471,7 +2445,7 @@ async function searchOrders(model: QueryModel) {
<section v-if="detailOrder.status !== 'CANCELLED' || detailOrder.expressCompanyName || detailOrder.trackingNumber" class="detail-section"> <section v-if="detailOrder.status !== 'CANCELLED' || detailOrder.expressCompanyName || detailOrder.trackingNumber" class="detail-section">
<h3>履约快递信息</h3> <h3>履约快递信息</h3>
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div></dl> <dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div></dl>
<div v-else class="express-empty"><PackageCheck :size="20" /><div><strong>平台尚未维护快递信息</strong><span>快递公司和快递单号由平台后台维护,客户端仅只读展示。</span></div></div> <div v-else class="express-empty"><PackageCheck :size="20" /><div><strong>暂无快递信息</strong><span>快递自提可在下单或编辑草稿时选填快递单号,快递公司由平台维护。</span></div></div>
</section> </section>
<section class="detail-section"> <section class="detail-section">
<h3>货物明细</h3> <h3>货物明细</h3>
@@ -2540,7 +2514,7 @@ async function searchOrders(model: QueryModel) {
:data="inboundBilling" :data="inboundBilling"
:loading="inboundBillingLoading" :loading="inboundBillingLoading"
:unavailable="inboundBillingUnavailable" :unavailable="inboundBillingUnavailable"
unavailable-message="未推送计费重" unavailable-message="未推送费用"
:error="inboundBillingError" :error="inboundBillingError"
:can-confirm="canConfirmInboundFee" :can-confirm="canConfirmInboundFee"
@retry="retryInboundBilling" @retry="retryInboundBilling"
@@ -2578,10 +2552,7 @@ async function searchOrders(model: QueryModel) {
.supporting-data-error span { overflow-wrap: anywhere; color: var(--muted); font-size: 11px; line-height: 1.55; } .supporting-data-error span { overflow-wrap: anywhere; color: var(--muted); font-size: 11px; line-height: 1.55; }
.order-row-actions, .editor-actions { display: flex; justify-content: flex-end; gap: 8px; } .order-row-actions, .editor-actions { display: flex; justify-content: flex-end; gap: 8px; }
.order-table-card { padding: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); box-shadow: none; } .order-table-card { padding: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); box-shadow: none; }
.prototype-order-table :deep(.data-table__toolbar) { flex-wrap: nowrap; } .order-queue-tabs { display: flex; min-width: 0; align-items: center; gap: 4px; overflow-x: auto; padding: 14px 16px 10px; border-bottom: 1px solid var(--client-border); scrollbar-width: thin; }
.prototype-order-table :deep(.data-table__toolbar-heading) { min-width: 0; flex: 1; flex-wrap: nowrap; }
.prototype-order-table :deep(.data-table__toolbar-actions) { flex-shrink: 0; }
.order-queue-tabs { display: flex; min-width: 0; align-items: center; gap: 4px; overflow-x: auto; padding: 7px 0 10px; scrollbar-width: thin; }
.order-queue-tabs button { flex-shrink: 0; white-space: nowrap; } .order-queue-tabs button { flex-shrink: 0; white-space: nowrap; }
.queue-stage-count { margin-left: 3px; } .queue-stage-count { margin-left: 3px; }
.order-queue-tabs button { position: relative; min-height: 34px; padding: 0 12px; border: 1px solid transparent; border-radius: 7px; background: transparent; color: #667085; cursor: pointer; font: inherit; font-weight: 600; } .order-queue-tabs button { position: relative; min-height: 34px; padding: 0 12px; border: 1px solid transparent; border-radius: 7px; background: transparent; color: #667085; cursor: pointer; font: inherit; font-weight: 600; }
@@ -2829,7 +2800,6 @@ async function searchOrders(model: QueryModel) {
.detail-heading-main > div { min-width: 0; } .detail-heading-main > div { min-width: 0; }
.detail-back-action, .detail-heading-actions { flex: 0 0 auto; } .detail-back-action, .detail-heading-actions { flex: 0 0 auto; }
.order-detail-heading h2 { margin: 0; overflow: hidden; color: var(--navy); font-size: 18px; text-overflow: ellipsis; white-space: nowrap; } .order-detail-heading h2 { margin: 0; overflow: hidden; color: var(--navy); font-size: 18px; text-overflow: ellipsis; white-space: nowrap; }
.order-detail-heading p { margin: 3px 0 0; overflow: hidden; color: var(--muted); font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.order-detail-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0; margin: 0; border-top: 1px solid var(--border); border-left: 1px solid var(--border); } .order-detail-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0; margin: 0; border-top: 1px solid var(--border); border-left: 1px solid var(--border); }
.order-detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 78px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); } .order-detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 78px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
.order-detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; } .order-detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
@@ -201,7 +201,8 @@ function buildOrderDraft(row: QuickOrderRow, channel: QuickChannelOption): First
destinationCountryCode: row.destinationCountryCode, destinationCountryCode: row.destinationCountryCode,
destinationWarehouseId: row.destinationWarehouseId, destinationWarehouseId: row.destinationWarehouseId,
destinationWarehouseName: row.destinationWarehouseName, destinationWarehouseName: row.destinationWarehouseName,
pickupMethod: 'SELF_EXPRESS', pickupMethod: 'SELF_TRUCK',
trackingNumber: '',
channelCode: channel.channelCode, channelCode: channel.channelCode,
channelName: channel.channelName, channelName: channel.channelName,
pricingTaxMode, pricingTaxMode,
@@ -421,7 +422,7 @@ onMounted(loadChannels)
<section class="quick-order-page" aria-labelledby="quick-order-heading"> <section class="quick-order-page" aria-labelledby="quick-order-heading">
<header class="quick-order-intro"> <header class="quick-order-intro">
<h2 id="quick-order-heading">客户下单</h2> <h2 id="quick-order-heading">客户下单</h2>
<p>只需输入渠道、目的仓、产品 SKU 和箱数,即可快速填写订单。</p>
<small v-if="manualInboundCodeRequired">当前全局使用旧系统入仓码,每张草稿都需要填写旧系统生成的入仓码。</small> <small v-if="manualInboundCodeRequired">当前全局使用旧系统入仓码,每张草稿都需要填写旧系统生成的入仓码。</small>
<small>每一行会直接生成一张独立草稿单,其他明细可进入草稿后继续编辑并提交。</small> <small>每一行会直接生成一张独立草稿单,其他明细可进入草稿后继续编辑并提交。</small>
</header> </header>
@@ -482,7 +483,7 @@ onMounted(loadChannels)
<td class="products-cell"> <td class="products-cell">
<div v-for="(product, productIndex) in row.products" :key="product.id" class="product-fields"> <div v-for="(product, productIndex) in row.products" :key="product.id" class="product-fields">
<el-input v-model="product.sku" maxlength="64" placeholder="产品 SKU" /> <el-input v-model="product.sku" maxlength="64" placeholder="产品 SKU" />
<el-input-number v-model="product.packageCount" :min="1" :max="99999" :precision="0" controls-position="right" aria-label="箱数" placeholder="请输入箱数" /> <el-input-number v-model="product.packageCount" :min="1" :max="99999" :precision="0" controls-position="right" aria-label="箱数" placeholder="" />
<el-button v-if="row.products.length > 1" text type="danger" aria-label="删除产品" @click="removeProduct(row, productIndex)"><Trash2 :size="15" /></el-button> <el-button v-if="row.products.length > 1" text type="danger" aria-label="删除产品" @click="removeProduct(row, productIndex)"><Trash2 :size="15" /></el-button>
</div> </div>
</td> </td>
@@ -76,7 +76,7 @@ watch(originWarehouseId, (value, previous) => { if (!value || previous === '') r
<template> <template>
<div class="pricing-page"><section class="pricing-inquiry"><div class="inquiry-copy"><span>SAILING PRICE INQUIRY</span><h2>船期价格查询</h2><p>重量或体积填写一项即可,系统会按计价规则自动换算</p></div><el-form class="pricing-form" label-position="top"><el-form-item label="起运仓"><el-select v-model="originWarehouseId" filterable :loading="loading" placeholder="选择起运仓"><el-option v-for="item in warehouses" :key="String(item.id)" :label="`${item.warehouseName} · ${item.warehouseCode}`" :value="item.id" /></el-select></el-form-item><el-form-item label="货物重量"><div class="unit-input"><el-input v-model.number="weight" type="number" min="0" placeholder="可选,输入重量" /><span>KG</span></div></el-form-item><el-form-item label="货物立方数"><div class="unit-input"><el-input v-model.number="volume" type="number" min="0" placeholder="可选,输入体积" /><span>CBM</span></div></el-form-item><el-form-item label="目的 FBA 仓"><el-select v-model="destinationWarehouseId" filterable :loading="loading" placeholder="输入或选择仓库代码"><el-option v-for="item in destinationWarehouses" :key="String(item.id)" :label="item.warehouseCode" :value="item.id" /></el-select></el-form-item><el-form-item label="报价方式"><el-radio-group v-model="taxMode"><el-radio-button value="TAX_INCLUDED" label="包税" /><el-radio-button value="TAX_EXCLUDED" label="不包税" /></el-radio-group></el-form-item><el-form-item class="query-item"><el-button type="primary" :loading="querying" @click="query"><Search :size="16" />立即查询</el-button></el-form-item></el-form> <div class="pricing-page"><section class="pricing-inquiry"><div class="inquiry-copy"><span>SAILING PRICE INQUIRY</span><h2>船期价格查询</h2><p>重量或体积填写一项即可,系统会按计价规则自动换算</p></div><el-form class="pricing-form" label-position="top"><el-form-item label="起运仓"><el-select v-model="originWarehouseId" filterable :loading="loading" placeholder="选择起运仓"><el-option v-for="item in warehouses" :key="String(item.id)" :label="`${item.warehouseName} · ${item.warehouseCode}`" :value="item.id" /></el-select></el-form-item><el-form-item label="货物重量"><div class="unit-input"><el-input v-model.number="weight" type="number" min="0" placeholder="可选,输入重量" /><span>KG</span></div></el-form-item><el-form-item label="货物立方数"><div class="unit-input"><el-input v-model.number="volume" type="number" min="0" placeholder="可选,输入体积" /><span>CBM</span></div></el-form-item><el-form-item label="目的 FBA 仓"><el-select v-model="destinationWarehouseId" filterable :loading="loading" placeholder="输入或选择仓库代码"><el-option v-for="item in destinationWarehouses" :key="String(item.id)" :label="item.warehouseCode" :value="item.id" /></el-select></el-form-item><el-form-item label="报价方式"><el-radio-group v-model="taxMode"><el-radio-button value="TAX_INCLUDED" label="包税" /><el-radio-button value="TAX_EXCLUDED" label="不包税" /></el-radio-group></el-form-item><el-form-item class="query-item"><el-button type="primary" :loading="querying" @click="query"><Search :size="16" />立即查询</el-button></el-form-item></el-form>
<el-dialog v-model="quoteDialogOpen" class="quote-dialog" :show-close="false" :lock-scroll="false" width="min(1080px, calc(100vw - 48px))" top="6vh"><template #header><div class="quote-dialog-head"><div><h3>查询结果</h3><span>{{ resultSummary }}</span></div><button type="button" class="quote-close" aria-label="关闭" @click="quoteDialogOpen = false">×</button></div></template><div class="quote-grid"><article v-for="item in quoteCards" :key="item.quote.channelCode" class="quote-card" :class="recommendation(item)?.className"><div v-if="recommendation(item)" class="quote-ribbon">{{ recommendation(item)?.label }}</div><div class="quote-card-title"><strong>{{ item.channel.channelName }}</strong><span>{{ item.quote.pricingTaxMode === 'TAX_INCLUDED' ? '包税' : '不包税' }} / {{ item.quote.chargeUnit || 'CBM' }}</span></div><div class="quote-price"><b>{{ formatMoney(item.quote) }}</b><small>预估运费</small></div><div class="quote-meta"><div><span>单价</span><strong>{{ formatUnitPrice(item.quote) }}</strong></div><div><span>参考时效</span><strong>{{ item.channel.referenceTransit || '待更新' }}</strong></div><div><span>最晚进仓</span><strong>{{ item.channel.latestWarehouseEntry || '—' }}</strong></div><div><span>船期</span><strong>{{ item.channel.estimatedDepartureText || item.channel.estimatedDepartureDate || '待更新' }}</strong></div></div><el-button type="primary" plain class="quote-order" @click="placeOrder(item.quote.channelCode, item.channel.channelName)">下单</el-button></article></div></el-dialog></section> <el-dialog v-model="quoteDialogOpen" class="quote-dialog" :show-close="false" :lock-scroll="false" width="min(1080px, calc(100vw - 48px))" top="6vh"><template #header><div class="quote-dialog-head"><div><h3>查询结果</h3><span>{{ resultSummary }}</span></div><button type="button" class="quote-close" aria-label="关闭" @click="quoteDialogOpen = false">×</button></div></template><div class="quote-grid"><article v-for="item in quoteCards" :key="item.quote.channelCode" class="quote-card" :class="recommendation(item)?.className"><div v-if="recommendation(item)" class="quote-ribbon">{{ recommendation(item)?.label }}</div><div class="quote-card-title"><strong>{{ item.channel.channelName }}</strong><span>{{ item.quote.pricingTaxMode === 'TAX_INCLUDED' ? '包税' : '不包税' }} / {{ item.quote.chargeUnit || 'CBM' }}</span></div><div class="quote-price"><b>{{ formatMoney(item.quote) }}</b><small>预估运费</small></div><div class="quote-meta"><div><span>单价</span><strong>{{ formatUnitPrice(item.quote) }}</strong></div><div><span>参考时效</span><strong>{{ item.channel.referenceTransit || '待更新' }}</strong></div><div><span>最晚进仓</span><strong>{{ item.channel.latestWarehouseEntry || '—' }}</strong></div><div><span>船期</span><strong>{{ item.channel.estimatedDepartureText || item.channel.estimatedDepartureDate || '待更新' }}</strong></div></div><el-button type="primary" plain class="quote-order" @click="placeOrder(item.quote.channelCode, item.channel.channelName)">下单</el-button></article></div></el-dialog></section>
<section class="pricing-results"><div class="section-title"><div><h2>匹配渠道</h2><span>{{ channels.length }} 个渠道 · 参考价格以服务端估价为准</span></div><Calculator :size="20" /></div><el-skeleton v-if="loading || querying" :rows="4" animated /><el-alert v-else-if="errorMessage" :title="errorMessage" type="error" show-icon /><el-empty v-else-if="!channels.length" description="暂无可用船期价格" /><el-table v-else :data="channels" stripe><el-table-column label="渠道" min-width="160"><template #default="{ row }"><strong>{{ row.channelName }}</strong><small>{{ row.channelCode }}</small></template></el-table-column><el-table-column label="参考船期" min-width="150"><template #default="{ row }">{{ row.estimatedDepartureText || row.estimatedDepartureDate || '待更新' }}</template></el-table-column><el-table-column label="最晚进仓" min-width="130"><template #default="{ row }">{{ row.latestWarehouseEntry || '—' }}</template></el-table-column><el-table-column label="参考时效" width="120"><template #default="{ row }">{{ row.referenceTransit || '—' }}</template></el-table-column><el-table-column label="预估运费" width="150"><template #default="{ row }"><span v-if="quotes.find((quote) => quote.channelCode === row.channelCode)">{{ formatMoney(quotes.find((quote) => quote.channelCode === row.channelCode)!) }}</span><span v-else class="muted">查询后显示</span></template></el-table-column><el-table-column label="附加费说明" min-width="180" prop="surchargeDescription" /><el-table-column label="操作" width="100" fixed="right"><template #default="{ row }"><el-button link type="primary" :disabled="!quotes.some((quote) => quote.channelCode === row.channelCode)" @click="placeOrder(row.channelCode, row.channelName)">下单</el-button></template></el-table-column></el-table></section> <section class="pricing-results"><div class="section-title"><div><h2>匹配渠道</h2><span>{{ channels.length }} 个渠道 · 参考价格以服务端估价为准</span></div><Calculator :size="20" /></div><el-skeleton v-if="loading || querying" :rows="4" animated /><el-alert v-else-if="errorMessage" :title="errorMessage" type="error" show-icon /><el-empty v-else-if="!channels.length" description="暂无可用船期价格" /><el-table v-else :data="channels" stripe><el-table-column label="渠道" min-width="160"><template #default="{ row }"><strong>{{ row.channelName }}</strong><small>{{ row.channelCode }}</small></template></el-table-column><el-table-column label="参考船期" min-width="150"><template #default="{ row }">{{ row.estimatedDepartureText || row.estimatedDepartureDate || '待更新' }}</template></el-table-column><el-table-column label="最晚进仓" min-width="130"><template #default="{ row }">{{ row.latestWarehouseEntry || '—' }}</template></el-table-column><el-table-column label="参考时效" width="120"><template #default="{ row }">{{ row.referenceTransit || '—' }}</template></el-table-column><el-table-column label="预估运费" width="150"><template #default="{ row }"><span v-if="quotes.find((quote) => quote.channelCode === row.channelCode)">{{ formatMoney(quotes.find((quote) => quote.channelCode === row.channelCode)!) }}</span><span v-else class="muted">查询后显示</span></template></el-table-column><el-table-column label="附加费说明" min-width="180" prop="surchargeDescription" /></el-table></section>
</div> </div>
</template> </template>
+28
View File
@@ -0,0 +1,28 @@
# Client 消息中心模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/notifications/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
- 页面:`views/NotificationsView.vue`(收件箱)、`views/NotificationDetailView.vue`(详情);状态在 `store/notifications.ts`,请求在 `api/notifications.ts`。
- 后端归 `iam/` 的 `notification/` 子域;契约见 `notification-v1.yaml`。
## 页面与入口
| 目标 | 页面/入口 | API 与后端 |
|---|---|---|
| 消息收件箱、未读与分页 | `views/NotificationsView.vue` | `api/notifications.ts`、`store/notifications.ts`;`iam/notification/` |
| 消息详情与业务跳转 | `views/NotificationDetailView.vue` | `api/notifications.ts` |
| 文案与类型映射 | `presentation.ts`、`contracts.ts` | 服务端模板字段 |
| 对外导出 | `public.ts` | — |
## 关键边界
- 未读计数与已读状态以服务端为准;本地乐观更新后必须回读,不长期保留本地计数。
- 消息跳转只带业务编号(订单号、入仓码、派送号等),不用内部 ID 作参数或标题。
- 只展示当前企业范围内的消息;模板变量由服务端填充,前端不补默认值。
- 消息列表失败要可重试,不清空已有内容。
## 验证
- 定向:`pnpm test src/modules/notifications/<目标测试>`;字段变化同时核对 `notification-v1.yaml`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+30
View File
@@ -0,0 +1,30 @@
# Client 订单管理模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/order-management/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,订单与入仓计划细则见 `../../../docs/business-index.md`。
- 本模块承载客户可见的**统一订单、海外仓入仓计划与派送单**;头程下单与费用确认归 `../first-leg/`。
- 后端只查 `lastleg-service/` 的 `inboundplan/`、`delivery/`;头程订单事实由 `../first-leg/` 与 `order/` 提供。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 我的订单(统一列表) | `views/MyOrdersView.vue`;`orders/my` | 复用 `../first-leg/api/unifiedOrders.ts`;`order/` |
| 海外仓入库订单列表与详情 | `views/InboundOrdersView.vue`;`orders/inbound`、`orders/inbound/:planNo/detail` | `api/inboundPlans.ts`、`inboundPlanDisplay.ts`;`lastleg-service/inboundplan/` |
| 派送单列表 | `views/DeliveryOrdersView.vue`、`views/deliveryOrders.css`;`orders/delivery` | `api/deliveryOrders.ts`;`lastleg-service/delivery/` |
| 派送单详情与签收结果 | `views/DeliveryOrderDetailView.vue`;`orders/delivery/:deliveryNo` | `api/deliveryOrders.ts` |
| 浏览器读屏验收脚本 | `receiptBrowserAcceptance.mjs` | 仅本地验收,不写业务数据 |
## 关键边界
- 入仓计划与派送单对客户只读;任何状态推进由海外仓作业侧完成,客户端不提供完成/发车类动作。
- 派送单按目的 FBA 仓拆分,列表与详情必须显示目的 FBA 仓;不得用单个出库号覆盖整批派送。
- 业务标识用计划号、入仓码、派送号等正式编号;缺失显示“—”,不用内部 ID 回退。
- 客户与仓库范围只取服务端当前租户上下文,不从前端参数推断。
- 分页、筛选与导出只消费服务端结果,不在浏览器重排或本地累计。
## 验证
- 定向:`pnpm test src/modules/order-management/<目标测试>`;接口或类型变化同时运行 `pnpm typecheck`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
@@ -104,17 +104,6 @@ interface DeliveryOrderDetailResponse {
}> }>
} }
export interface DeliveryTransferResult {
dispatchNo: string
outboundNo: string
outboundStatus: string
deliveryNo: string
deliveryStatus: string
palletCount: number
packageCount: number
replayed: boolean
}
export interface DeliveryQuery { export interface DeliveryQuery {
page: number page: number
size: number size: number
@@ -140,26 +129,6 @@ export function normalizeDeliveryPage(data: PageResult<DeliveryRow>): PageResult
} }
} }
export interface DeliveryTransferPayload {
dispatchNo: string
idempotencyKey: string
plannedDeliveryAt: string
deliveryMethod: string
pickupMethod: string
loadingType: string
waybillNo?: string
carrierName?: string
vehicleType?: string
vehicleSize?: string
driverName?: string
driverPhone?: string
vehiclePlate?: string
appointmentAccount?: string
sellerName?: string
remark?: string
fees: DeliveryOrderFee[]
}
export function listDeliveryOrders(params: DeliveryQuery) { export function listDeliveryOrders(params: DeliveryQuery) {
return apiRequest<PageResult<DeliveryRow>>({ return apiRequest<PageResult<DeliveryRow>>({
method: 'GET', method: 'GET',
@@ -179,13 +148,3 @@ export function getDeliveryOrder(deliveryNo: string) {
items: skus, items: skus,
})) }))
} }
export function createDeliveryOrder(payload: DeliveryTransferPayload) {
const { dispatchNo, ...request } = payload
return apiRequest<DeliveryTransferResult>({
method: 'POST',
url: '/merchant/v1/last-leg/delivery-orders',
params: { dispatchNo },
data: request,
})
}
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs' import { existsSync, readFileSync } from 'node:fs'
import test from 'node:test' import test from 'node:test'
import ts from 'typescript' import ts from 'typescript'
@@ -8,7 +8,6 @@ const routesSource = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8
const listSource = readFileSync(new URL('./views/DeliveryOrdersView.vue', import.meta.url), 'utf8') const listSource = readFileSync(new URL('./views/DeliveryOrdersView.vue', import.meta.url), 'utf8')
const detailSource = readFileSync(new URL('./views/DeliveryOrderDetailView.vue', import.meta.url), 'utf8') const detailSource = readFileSync(new URL('./views/DeliveryOrderDetailView.vue', import.meta.url), 'utf8')
const deliveryStyles = readFileSync(new URL('./views/deliveryOrders.css', import.meta.url), 'utf8') const deliveryStyles = readFileSync(new URL('./views/deliveryOrders.css', import.meta.url), 'utf8')
const createSource = readFileSync(new URL('./views/DeliveryOrderCreateView.vue', 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')
async function importTypeScriptModule(source) { async function importTypeScriptModule(source) {
@@ -33,22 +32,18 @@ for (const signedPackages of [null, 0, 3]) test(`preserves actual signed quantit
test('uses only authenticated merchant delivery endpoints without customer scope or mock fallback', () => { test('uses only authenticated merchant delivery endpoints without customer scope or mock fallback', () => {
assert.match(apiSource, /method: 'GET'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/) assert.match(apiSource, /method: 'GET'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/)
assert.match(apiSource, /delivery-orders\/\$\{encodeURIComponent\(deliveryNo\)\}/) assert.match(apiSource, /delivery-orders\/\$\{encodeURIComponent\(deliveryNo\)\}/)
assert.match(apiSource, /method: 'POST'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/) assert.doesNotMatch(apiSource, /method: '(?:POST|PUT|PATCH|DELETE)'|createDeliveryOrder|DeliveryTransferPayload|DeliveryTransferResult/)
assert.match(apiSource, /const \{ dispatchNo, \.\.\.request \} = payload/)
assert.match(apiSource, /params: \{ dispatchNo \}/)
assert.match(apiSource, /apiRequest<DeliveryOrderDetailResponse>/) assert.match(apiSource, /apiRequest<DeliveryOrderDetailResponse>/)
assert.match(apiSource, /\.then\(\(\{ order, skus, fees \}\) => \(\{[\s\S]*\.\.\.order,[\s\S]*fees,[\s\S]*items: skus/) assert.match(apiSource, /\.then\(\(\{ order, skus, fees \}\) => \(\{[\s\S]*\.\.\.order,[\s\S]*fees,[\s\S]*items: skus/)
assert.match(apiSource, /apiRequest<DeliveryTransferResult>/)
assert.doesNotMatch(apiSource, /customerId|tenantId|Record<string, unknown>|mock|fallback/i) assert.doesNotMatch(apiSource, /customerId|tenantId|Record<string, unknown>|mock|fallback/i)
}) })
test('keeps list, read-only detail and create permissions independent in active routes', () => { test('keeps customer delivery list and read-only detail active without a creation route', () => {
const listRoute = routesSource.match(/path: 'orders\/delivery',[\s\S]*?\n\s*},/)?.[0] ?? '' const listRoute = routesSource.match(/path: 'orders\/delivery',[\s\S]*?\n\s*},/)?.[0] ?? ''
assert.match(listRoute, /permission: 'merchant:warehouse:delivery:list'/) assert.match(listRoute, /permission: 'merchant:warehouse:delivery:list'/)
assert.match(listRoute, /navigation: \{ key: 'orders-delivery', icon: Truck \}/) assert.match(listRoute, /navigation: \{ key: 'orders-delivery', icon: Truck \}/)
assert.match(routesSource, /path: 'orders\/delivery\/create'[\s\S]*DeliveryOrderCreateView\.vue[\s\S]*permission: 'merchant:warehouse:delivery:create'/) assert.doesNotMatch(routesSource, /orders\/delivery\/create|orders-delivery-create|DeliveryOrderCreateView/)
assert.match(routesSource, /path: 'orders\/delivery\/:deliveryNo'[\s\S]*DeliveryOrderDetailView\.vue[\s\S]*props: true[\s\S]*permission: 'merchant:warehouse:delivery:list'/) assert.match(routesSource, /path: 'orders\/delivery\/:deliveryNo'[\s\S]*DeliveryOrderDetailView\.vue[\s\S]*props: true[\s\S]*permission: 'merchant:warehouse:delivery:list'/)
assert.match(routesSource, /orders-delivery-create[\s\S]*keepAlive: false/)
assert.match(routesSource, /orders-delivery-detail[\s\S]*keepAlive: false/) assert.match(routesSource, /orders-delivery-detail[\s\S]*keepAlive: false/)
}) })
@@ -70,10 +65,9 @@ test('renders the operation column first and covers loading, empty, error and pa
assert.doesNotMatch(listSource, /row\.id[^a-zA-Z]|deliveryNo \|\| row\.id|customerId|tenantId/) assert.doesNotMatch(listSource, /row\.id[^a-zA-Z]|deliveryNo \|\| row\.id|customerId|tenantId/)
}) })
test('shows the create button only with the independent create permission', () => { test('does not expose customer delivery creation even to an account retaining an old permission snapshot', () => {
assert.match(listSource, /auth\.hasPermission\('merchant:warehouse:delivery:create'\)/) assert.doesNotMatch(listSource, /delivery:create|canCreate|openCreate|orders-delivery-create|创建派送单/)
assert.match(listSource, /<el-button v-if="canCreate" type="primary" @click="openCreate"/) assert.equal(existsSync(new URL('./views/DeliveryOrderCreateView.vue', import.meta.url)), false)
assert.doesNotMatch(listSource, /hasPermission\('merchant:warehouse:delivery:list'\)[\s\S]{0,120}创建派送单/)
}) })
test('loads a typed detail route by delivery number and never exposes an internal id fallback', () => { test('loads a typed detail route by delivery number and never exposes an internal id fallback', () => {
@@ -126,33 +120,12 @@ test('renders a compact customer-readable delivery detail surface', () => {
assert.match(deliveryStyles, /delivery-detail-surface \.delivery-detail-grid div\{display:grid;min-height:42px;/) assert.match(deliveryStyles, /delivery-detail-surface \.delivery-detail-grid div\{display:grid;min-height:42px;/)
}) })
test('submits the complete create contract with stable retry idempotency and recoverable failures', () => { test('keeps merchant delivery reads and removes creation from the advertised permission map', async () => {
for (const model of ['dispatchNo', 'plannedDeliveryAt', 'deliveryMethod', 'pickupMethod', 'loadingType', 'waybillNo', 'carrierName', 'vehicleType', 'vehicleSize', 'driverName', 'driverPhone', 'vehiclePlate', 'appointmentAccount', 'sellerName', 'remark']) {
assert.match(createSource, new RegExp(`v-model="form\\.${model}"`))
}
assert.match(createSource, /if \(!pendingIdempotencyKey\) pendingIdempotencyKey = createIdempotencyKey\(\)/)
assert.match(createSource, /createDeliveryOrder\(requestPayload\(\)\)/)
assert.match(createSource, /fees: form\.fees\.map/)
assert.match(createSource, /if \(form\.fees\.length === 0\)/)
assert.match(createSource, /请至少添加一条费用明细/)
for (const value of ['FBA_PICKUP', 'CUSTOMER_PICKUP', 'TRUCK_PALLET', 'TRUCK_FLOOR', 'EXPRESS', 'OUTSOURCED', 'DEDICATED_TRUCK', 'LTL']) {
assert.match(createSource, new RegExp(`value="${value}"`))
}
for (const value of ['ONE_PICKUP_ONE_DROP', 'ONE_PICKUP_MULTI_DROP', 'MULTI_PICKUP_ONE_DROP', 'MULTI_PICKUP_MULTI_DROP', 'WAREHOUSE_PICKUP', 'PALLET', 'FLOOR', 'MIXED']) {
assert.match(createSource, new RegExp(`value="${value}"`))
}
assert.doesNotMatch(createSource, /value="(?:TRUCK|COURIER|SELF_PICKUP|DOOR_PICKUP|LOOSE_CARTON)"/)
assert.match(createSource, /submitError\.value = error instanceof Error/)
assert.match(createSource, /useUnsavedWorkRegistration/)
assert.doesNotMatch(createSource, /customerId|tenantId|mock|fallback/i)
})
test('maps both merchant delivery permissions independently', async () => {
assert.match(permissionSource, /'merchant:warehouse:delivery:list': \['merchant:warehouse:delivery:list'\]/) assert.match(permissionSource, /'merchant:warehouse:delivery:list': \['merchant:warehouse:delivery:list'\]/)
assert.match(permissionSource, /'merchant:warehouse:delivery:create': \['merchant:warehouse:delivery:create'\]/) assert.doesNotMatch(permissionSource, /merchant:warehouse:delivery:create/)
const contracts = await importTypeScriptModule(permissionSource) const contracts = await importTypeScriptModule(permissionSource)
assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:list', new Set(['merchant:warehouse:delivery:list'])), true) assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:list', new Set(['merchant:warehouse:delivery:list'])), true)
assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:list', new Set(['merchant:warehouse:delivery:create'])), false) assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:list', new Set(['merchant:warehouse:delivery:create'])), false)
assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:create', new Set(['merchant:warehouse:delivery:create'])), true) assert.equal(Object.hasOwn(contracts.FRONTEND_TO_MERCHANT_PERMISSION_CODES, 'merchant:warehouse:delivery:create'), false)
assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:create', new Set(['merchant:warehouse:delivery:list'])), false) assert.equal(contracts.hasMappedMerchantPermission('merchant:warehouse:delivery:create', new Set(['merchant:warehouse:delivery:list'])), false)
}) })
-7
View File
@@ -37,13 +37,6 @@ export const orderManagementModule = {
meta: { title: '派送订单列表', description: '查询海外仓派送订单', permission: 'merchant:warehouse:delivery:list' }, meta: { title: '派送订单列表', description: '查询海外仓派送订单', permission: 'merchant:warehouse:delivery:list' },
navigation: { key: 'orders-delivery', icon: Truck }, navigation: { key: 'orders-delivery', icon: Truck },
}, },
{
path: 'orders/delivery/create',
name: 'orders-delivery-create',
component: () => import('./views/DeliveryOrderCreateView.vue'),
release: 'active',
meta: { title: '创建派送单', workspaceTitle: '派送订单 · 新建', description: '从排车单创建海外仓派送单', permission: 'merchant:warehouse:delivery:create', keepAlive: false },
},
{ {
path: 'orders/delivery/:deliveryNo', path: 'orders/delivery/:deliveryNo',
name: 'orders-delivery-detail', name: 'orders-delivery-detail',
@@ -1,201 +0,0 @@
<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowLeft, Plus, Trash2 } from '@lucide/vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useAuthStore } from '@/modules/auth/public'
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
import { createIdempotencyKey } from '@/utils/idempotencyKey'
import { createDeliveryOrder, type DeliveryOrderFee, type DeliveryTransferPayload } from '../api/deliveryOrders'
type DeliveryCreateForm = Omit<DeliveryTransferPayload, 'idempotencyKey'>
const router = useRouter()
const auth = useAuthStore()
const formRef = ref<FormInstance>()
const submitting = ref(false)
const submitError = ref('')
const submitted = ref(false)
let pendingIdempotencyKey = ''
const form = reactive<DeliveryCreateForm>({
dispatchNo: '',
plannedDeliveryAt: '',
deliveryMethod: '',
pickupMethod: '',
loadingType: '',
waybillNo: '',
carrierName: '',
vehicleType: '',
vehicleSize: '',
driverName: '',
driverPhone: '',
vehiclePlate: '',
appointmentAccount: '',
sellerName: '',
remark: '',
fees: [],
})
const rules: FormRules<DeliveryCreateForm> = {
dispatchNo: [{ required: true, message: '请输入排车单号', trigger: 'blur' }],
plannedDeliveryAt: [{ required: true, message: '请选择计划派送时间', trigger: 'change' }],
deliveryMethod: [{ required: true, message: '请选择派送方式', trigger: 'change' }],
pickupMethod: [{ required: true, message: '请选择提货方式', trigger: 'change' }],
loadingType: [{ required: true, message: '请选择装载类型', trigger: 'change' }],
}
const dirty = computed(() => !submitted.value && Boolean(
form.dispatchNo || form.plannedDeliveryAt || form.deliveryMethod || form.pickupMethod || form.loadingType
|| form.waybillNo || form.carrierName || form.vehicleType || form.vehicleSize || form.driverName
|| form.driverPhone || form.vehiclePlate || form.appointmentAccount || form.sellerName || form.remark || form.fees.length,
))
useUnsavedWorkRegistration({
key: 'delivery-order-create-form',
routeKey: 'orders-delivery-create',
label: '创建派送单',
dirty,
})
function optional(value: string | undefined) {
const normalized = value?.trim()
return normalized || undefined
}
function addFee() {
form.fees.push({ feeType: '', currency: 'USD', amount: 0, remark: '' })
}
function removeFee(index: number) {
form.fees.splice(index, 1)
}
function validateFees() {
if (form.fees.length === 0) {
ElMessage.warning('请至少添加一条费用明细')
return false
}
const invalidIndex = form.fees.findIndex((fee) => !fee.feeType.trim() || !fee.currency.trim() || fee.amount <= 0)
if (invalidIndex < 0) return true
ElMessage.warning(`请完整填写第 ${invalidIndex + 1} 条费用的类型、币种和大于 0 的金额`)
return false
}
function requestPayload(): DeliveryTransferPayload {
return {
dispatchNo: form.dispatchNo.trim(),
idempotencyKey: pendingIdempotencyKey,
plannedDeliveryAt: form.plannedDeliveryAt,
deliveryMethod: form.deliveryMethod,
pickupMethod: form.pickupMethod,
loadingType: form.loadingType,
waybillNo: optional(form.waybillNo),
carrierName: optional(form.carrierName),
vehicleType: optional(form.vehicleType),
vehicleSize: optional(form.vehicleSize),
driverName: optional(form.driverName),
driverPhone: optional(form.driverPhone),
vehiclePlate: optional(form.vehiclePlate),
appointmentAccount: optional(form.appointmentAccount),
sellerName: optional(form.sellerName),
remark: optional(form.remark),
fees: form.fees.map((fee): DeliveryOrderFee => ({
feeType: fee.feeType.trim(),
currency: fee.currency.trim().toUpperCase(),
amount: fee.amount,
remark: optional(fee.remark ?? ''),
})),
}
}
async function submit() {
submitError.value = ''
const valid = await formRef.value?.validate().catch(() => false)
if (!valid || !validateFees()) return
if (!pendingIdempotencyKey) pendingIdempotencyKey = createIdempotencyKey()
submitting.value = true
try {
const created = await createDeliveryOrder(requestPayload())
submitted.value = true
pendingIdempotencyKey = ''
ElMessage.success('派送单创建成功')
if (auth.hasPermission('merchant:warehouse:delivery:list')) {
await router.replace({ name: 'orders-delivery-detail', params: { deliveryNo: created.deliveryNo } })
} else {
await router.replace('/')
}
} catch (error) {
submitError.value = error instanceof Error ? error.message : '派送单创建失败,请检查后重试'
} finally {
submitting.value = false
}
}
async function cancel() {
if (dirty.value) {
try {
await ElMessageBox.confirm('当前派送单尚未提交,离开后填写内容将丢失。', '放弃创建?', { type: 'warning', confirmButtonText: '放弃', cancelButtonText: '继续填写' })
} catch (error) {
if (error === 'cancel' || error === 'close') return
throw error
}
}
submitted.value = true
await router.push({ name: 'orders-delivery' })
}
</script>
<template>
<section class="delivery-page" aria-labelledby="delivery-create-title">
<button type="button" class="delivery-back" @click="cancel"><ArrowLeft :size="16" />返回派送单列表</button>
<div class="delivery-heading"><div><h2 id="delivery-create-title">创建派送单</h2><p>从已确认的排车单创建本企业海外仓派送任务。</p></div></div>
<div v-if="submitError" class="delivery-card delivery-state delivery-state--error" role="alert"><p>{{ submitError }}</p></div>
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="delivery-card delivery-form" @submit.prevent="submit">
<section>
<h3>基础信息</h3>
<div class="delivery-form-grid">
<el-form-item label="排车单号" prop="dispatchNo" required><el-input v-model="form.dispatchNo" maxlength="64" placeholder="请输入排车单号" /></el-form-item>
<el-form-item label="计划派送时间" prop="plannedDeliveryAt" required><el-date-picker v-model="form.plannedDeliveryAt" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="请选择计划派送时间" /></el-form-item>
<el-form-item label="派送方式" prop="deliveryMethod" required><el-select v-model="form.deliveryMethod" placeholder="请选择派送方式"><el-option label="FBA自提" value="FBA_PICKUP" /><el-option label="客户自提" value="CUSTOMER_PICKUP" /><el-option label="卡派打托" value="TRUCK_PALLET" /><el-option label="卡派地板" value="TRUCK_FLOOR" /><el-option label="快递" value="EXPRESS" /><el-option label="外配" value="OUTSOURCED" /><el-option label="专车直送" value="DEDICATED_TRUCK" /><el-option label="零担派送" value="LTL" /></el-select></el-form-item>
<el-form-item label="提货方式" prop="pickupMethod" required><el-select v-model="form.pickupMethod" placeholder="请选择提货方式"><el-option label="一提一卸" value="ONE_PICKUP_ONE_DROP" /><el-option label="一提多卸" value="ONE_PICKUP_MULTI_DROP" /><el-option label="多提一卸" value="MULTI_PICKUP_ONE_DROP" /><el-option label="多提多卸" value="MULTI_PICKUP_MULTI_DROP" /><el-option label="仓库自提" value="WAREHOUSE_PICKUP" /></el-select></el-form-item>
<el-form-item label="装载类型" prop="loadingType" required><el-select v-model="form.loadingType" placeholder="请选择装载类型"><el-option label="托盘" value="PALLET" /><el-option label="地板" value="FLOOR" /><el-option label="混装" value="MIXED" /></el-select></el-form-item>
<el-form-item label="运单号"><el-input v-model="form.waybillNo" maxlength="64" placeholder="选填" /></el-form-item>
</div>
</section>
<section>
<h3>承运与车辆</h3>
<div class="delivery-form-grid">
<el-form-item label="承运商"><el-input v-model="form.carrierName" maxlength="128" placeholder="选填" /></el-form-item>
<el-form-item label="车型"><el-input v-model="form.vehicleType" maxlength="64" placeholder="选填" /></el-form-item>
<el-form-item label="车辆尺寸"><el-input v-model="form.vehicleSize" maxlength="64" placeholder="选填" /></el-form-item>
<el-form-item label="车牌号"><el-input v-model="form.vehiclePlate" maxlength="32" placeholder="选填" /></el-form-item>
<el-form-item label="司机姓名"><el-input v-model="form.driverName" maxlength="64" placeholder="选填" /></el-form-item>
<el-form-item label="司机电话"><el-input v-model="form.driverPhone" maxlength="32" placeholder="选填" /></el-form-item>
<el-form-item label="预约账号"><el-input v-model="form.appointmentAccount" maxlength="128" placeholder="选填" /></el-form-item>
<el-form-item label="卖家名称"><el-input v-model="form.sellerName" maxlength="128" placeholder="选填" /></el-form-item>
<el-form-item label="备注" class="delivery-span-3"><el-input v-model="form.remark" type="textarea" :rows="3" maxlength="500" show-word-limit placeholder="选填" /></el-form-item>
</div>
</section>
<section>
<div class="delivery-fee-heading"><h3>费用明细</h3><el-button @click="addFee"><Plus :size="16" />添加费用</el-button></div>
<el-table v-if="form.fees.length" :data="form.fees" table-layout="fixed">
<el-table-column label="操作" width="88"><template #default="{ $index }"><el-button link type="danger" aria-label="删除费用" @click="removeFee($index)"><Trash2 :size="16" />删除</el-button></template></el-table-column>
<el-table-column label="费用类型" min-width="180"><template #default="{ row }"><el-input v-model="row.feeType" maxlength="64" placeholder="请输入费用类型" /></template></el-table-column>
<el-table-column label="币种" width="140"><template #default="{ row }"><el-input v-model="row.currency" maxlength="3" placeholder="USD" /></template></el-table-column>
<el-table-column label="金额" width="180"><template #default="{ row }"><el-input-number v-model="row.amount" :min="0" :precision="2" :step="1" controls-position="right" placeholder="请输入金额" /></template></el-table-column>
<el-table-column label="备注" min-width="220"><template #default="{ row }"><el-input v-model="row.remark" maxlength="200" placeholder="选填" /></template></el-table-column>
</el-table>
<div v-else class="delivery-fee-empty">请至少添加一条费用明细后再提交。</div>
</section>
<div class="delivery-form-actions"><el-button :disabled="submitting" @click="cancel">取消</el-button><el-button type="primary" native-type="submit" :loading="submitting">提交创建</el-button></div>
</el-form>
</section>
</template>
<style scoped src="./deliveryOrders.css"></style>
@@ -1,16 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { Plus } from '@lucide/vue'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { useAuthStore } from '@/modules/auth/public'
import { listDeliveryOrders, type DeliveryQuery, type DeliveryRow } from '../api/deliveryOrders' import { listDeliveryOrders, type DeliveryQuery, type DeliveryRow } from '../api/deliveryOrders'
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue' import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue' import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
import type { TableAction } from '@/components/common/tableActions' import type { TableAction } from '@/components/common/tableActions'
const router = useRouter() const router = useRouter()
const auth = useAuthStore()
const loading = ref(false) const loading = ref(false)
const errorMessage = ref('') const errorMessage = ref('')
const records = ref<DeliveryRow[]>([]) const records = ref<DeliveryRow[]>([])
@@ -18,7 +15,6 @@ const total = ref(0)
const page = ref(1) const page = ref(1)
const pageSize = ref(20) const pageSize = ref(20)
const filters = reactive({ documentNo: '', dispatchNo: '', waybillNo: '', status: '', deliveryMethod: '', plannedRange: [] as string[] }) const filters = reactive({ documentNo: '', dispatchNo: '', waybillNo: '', status: '', deliveryMethod: '', plannedRange: [] as string[] })
const canCreate = computed(() => auth.hasPermission('merchant:warehouse:delivery:create'))
let requestSequence = 0 let requestSequence = 0
const deliveryMethodOptions = [ const deliveryMethodOptions = [
@@ -142,9 +138,6 @@ function openDetail(row: DeliveryRow) {
void router.push({ name: 'orders-delivery-detail', params: { deliveryNo: row.deliveryNo } }) void router.push({ name: 'orders-delivery-detail', params: { deliveryNo: row.deliveryNo } })
} }
function openCreate() {
void router.push({ name: 'orders-delivery-create' })
}
function rowActions(candidate: object): TableAction[] { function rowActions(candidate: object): TableAction[] {
const row = candidate as DeliveryRow const row = candidate as DeliveryRow
return [{ key: 'detail', label: '详情', disabled: !row.deliveryNo, run: () => openDetail(row) }] return [{ key: 'detail', label: '详情', disabled: !row.deliveryNo, run: () => openDetail(row) }]
@@ -163,7 +156,6 @@ watch([page, pageSize], ([nextPage, nextSize], [previousPage, previousSize]) =>
<div class="delivery-card delivery-table-card"> <div class="delivery-card delivery-table-card">
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="records" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="deliveryNo" empty-text="暂无派送单"> <DataTable v-model:page="page" v-model:page-size="pageSize" :data="records" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="deliveryNo" empty-text="暂无派送单">
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />创建派送单</el-button></template>
<template v-if="errorMessage" #error><div class="delivery-state delivery-state--error" role="alert"><p>{{ errorMessage }}</p><el-button @click="loadOrders">重试</el-button></div></template> <template v-if="errorMessage" #error><div class="delivery-state delivery-state--error" role="alert"><p>{{ errorMessage }}</p><el-button @click="loadOrders">重试</el-button></div></template>
<template #status="{ row }"><el-tag :type="statusType(row.status)" effect="light">{{ statusLabel(row.status) }}</el-tag></template> <template #status="{ row }"><el-tag :type="statusType(row.status)" effect="light">{{ statusLabel(row.status) }}</el-tag></template>
<template #planned="{ row }">{{ formatDateTime(row.plannedDeliveryAt) }}</template> <template #planned="{ row }">{{ formatDateTime(row.plannedDeliveryAt) }}</template>
+34
View File
@@ -0,0 +1,34 @@
# Client 海外仓模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/overseas-warehouse/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,页面与字段细则见 `../../../docs/business-index.md`。
- 五类自助业务共用三个页面文件:`WarehouseServiceView.vue`(贴标、仓储转运、货物废弃)、`ReturnOrdersView.vue`(退货预报与签收)、`ReturnInventoryView.vue`(退货库存与箱号);按路由区分模式。
- 后端只查 `lastleg-service/` 的 `relabel/`、`transfer/`、`discard/`、`returnreceipt/`;资源与库位归 `warehouse-overseas-service/`;纯页面与文案不读后端。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 贴标申请列表、新建、详情 | `views/WarehouseServiceView.vue`;`overseas-warehouse/labeling`、`.../create`、`.../:detailNo/detail` | `api/warehouseServices.ts`;`lastleg-service/relabel/` |
| 仓储转运列表、详情与入库测量 | `views/WarehouseServiceView.vue`;`overseas-warehouse/storage-transfer`、`.../:detailNo/detail` | `api/warehouseServices.ts`、`api/transferPickups.ts`;`components/TransferPickupProgressPanel.vue`;`lastleg-service/transfer/` |
| 货物废弃列表、新建与详情 | `views/WarehouseServiceView.vue`;`overseas-warehouse/cargo-disposal`、`.../:detailNo/detail` | `api/warehouseServices.ts`、`utils/discardDocuments.ts`;`lastleg-service/discard/` |
| 退货预报、新建与签收详情 | `views/ReturnOrdersView.vue`;`overseas-warehouse/return-relabel`、`.../create`、`.../:returnNo/detail` | `api/returnOrders.ts`、`utils/returnReceiptDisplay.ts`;`lastleg-service/returnreceipt/` |
| 退货库存查询 | `views/ReturnInventoryView.vue`;`overseas-warehouse/return-inventory` | `api/returnInventory.ts` |
| 退货箱号与箱内明细 | `views/ReturnInventoryView.vue`;`overseas-warehouse/return-cartons`、`.../:cartonMark/detail` | `api/returnInventory.ts`、`utils/returnReceiptDisplay.ts` |
| 换标完工确认与驳回提示 | `components/CompletionConfirmationDialog.vue`、`components/ReviewRejectionNotice.vue`、`components/RelabelDocumentsPanel.vue` | `api/warehouseServices.ts`、`utils/relabelSkuDisplay.ts` |
`views/LabelingView.vue`、`views/ReturnInboundView.vue`、`views/ReturnOutboundView.vue` 当前未在 `routes.ts` 注册;改动前先确认是否已废弃或仅被内嵌,不要据此认定页面开放。
## 关键边界
- 换标申请必须提交正数 CNY `chargeAmount`;金额与资金状态以服务端返回为准,不在客户端模拟冻结成功。
- 退货预报与签收只消费服务端状态与箱号;退货库存按箱号和 SKU 查询,箱内明细以服务端实收为准,不按预报箱数推算。
- 仓储转运的测量与打托由仓库侧完成,客户端只读展示与确认;转运进度以 `TransferPickupProgressPanel.vue` 消费的服务端事实为准。
- 货物废弃在待审锁定与实际确认扣减之间不可回退,前端只按服务端允许动作开放按钮。
- 页面承载方式按已确认原型:贴标、转运、废弃为独立路由页面,退货预报为独立页面,不擅自改为弹框或抽屉。
## 验证
- 定向:`pnpm test src/modules/overseas-warehouse/<目标测试>`;接口或类型变化同时运行 `pnpm typecheck`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
@@ -0,0 +1,28 @@
import { apiRequest } from '@/api/http'
export interface RelabelQuantity {
sourcePalletCount?: number | string | null
targetPalletCount?: number | string | null
sourceUnitCounts?: Record<string, number | string> | null
labelPieceCount: number | string | null
cartonCount: number | string | null
skuCount: number | string
duplicateCarton: boolean
}
export interface RelabelQuantityTotals {
knownSourcePalletCount?: number | string
unknownSourcePalletOrders?: number | string
knownTargetPalletCount?: number | string
unknownTargetPalletOrders?: number | string
orderCount: number | string
skuCount: number | string
knownLabelPieceCount: number | string
unknownPieceOrders: number | string
knownCartonCount: number | string
unknownCartonOrders: number | string
orders: Record<string, RelabelQuantity>
}
/** 客户范围来自会话,数量汇总覆盖全部筛选结果。 */
export function getRelabelQuantities(params: Record<string, unknown>) {
return apiRequest<RelabelQuantityTotals>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications/quantity-summary', params })
}
@@ -2,6 +2,10 @@ import { apiRequest, apiBlobRequest } from '@/api/http'
import type { PageResult } from './warehouseServices' import type { PageResult } from './warehouseServices'
export interface ReturnOrderSummary { export interface ReturnOrderSummary {
remainingQuantity?: number
receivedBoxCount?: number
receivedParcelCount?: number
receivedPalletCount?: number
relabelApplications?: Array<{ relabelNo: string; status: string; quantity: number; quantityUnit?: string; createdAt: string }> relabelApplications?: Array<{ relabelNo: string; status: string; quantity: number; quantityUnit?: string; createdAt: string }>
returnNo: string; overseasWarehouseId: string; warehouseContactName?: string; warehouseContactPhone?: string; customerReferenceNo?: string; status: string returnNo: string; overseasWarehouseId: string; warehouseContactName?: string; warehouseContactPhone?: string; customerReferenceNo?: string; status: string
skuTypes: number; expectedQuantity: number; receivedQuantity: number; needRelabel: boolean; relabelNo?: string; relabelStatus?: string; createdAt: string skuTypes: number; expectedQuantity: number; receivedQuantity: number; needRelabel: boolean; relabelNo?: string; relabelStatus?: string; createdAt: string
@@ -30,6 +34,13 @@ export interface ReturnOrderCreate {
export function listReturnOrders(params: Record<string, unknown>) { export function listReturnOrders(params: Record<string, unknown>) {
return apiRequest<PageResult<ReturnOrderSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/return-orders', params }) return apiRequest<PageResult<ReturnOrderSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/return-orders', params })
} }
export interface ReturnOrderStatistics {
totals: { orderCount: number; skuTypes: number; expectedQuantity: number; receivedQuantity: number; remainingQuantity: number; receivedBoxCount: number; receivedParcelCount: number; receivedPalletCount: number }
pageDimensions: Array<{ returnNo: string; remainingQuantity: number; receivedBoxCount: number; receivedParcelCount: number; receivedPalletCount: number }>
}
export function getReturnOrderStatistics(params: Record<string, unknown>) {
return apiRequest<ReturnOrderStatistics>({ method: 'GET', url: '/merchant/v1/last-leg/return-orders/statistics', params })
}
export function getReturnOrder(returnNo: string) { export function getReturnOrder(returnNo: string) {
return apiRequest<ReturnOrderDetail>({ method: 'GET', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}` }) return apiRequest<ReturnOrderDetail>({ method: 'GET', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}` })
} }
@@ -0,0 +1,15 @@
import { apiRequest, apiBlobRequest } from '@/api/http'
export interface PickupProgress {
status: string; tripNo: string | null; vehiclePlate: string | null; driverName: string | null; driverPhone: string | null
plannedDepartureAt: string | null; actualPackages: number | null; pickedAt: string | null; arrivedAt: string | null; remark: string | null
evidence: { fileId: string; fileName: string }[]
}
/** 客户范围由统一会话确定,不允许调用方传入其他客户。 */
export function getTransferPickupProgress(transferNo: string) {
return apiRequest<PickupProgress | null>({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/pickup-progress` })
}
/** 只下载本票已经确认的凭证。 */
export function downloadTransferPickupEvidence(transferNo: string, fileId: string) {
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/pickup-evidence/${encodeURIComponent(fileId)}` })
}
@@ -1,7 +1,7 @@
import { apiRequest, apiBlobRequest } from '@/api/http' import { apiRequest, apiBlobRequest } from '@/api/http'
import { createIdempotencyKey } from '@/utils/idempotencyKey' import { createIdempotencyKey } from '@/utils/idempotencyKey'
export type RelabelDeliveryMethod = 'TRUCK' | 'EXPRESS' | 'TRUCK_PICKUP' | 'EXPRESS_PICKUP' export type RelabelDeliveryMethod = 'TRUCK' | 'EXPRESS' | 'AMAZON_PICKUP' | 'CUSTOMER_PICKUP'
export interface PageResult<T> { records: T[]; page: number; size: number; total: number; pages: number } export interface PageResult<T> { records: T[]; page: number; size: number; total: number; pages: number }
export interface LastlegOrderSummary { id: string; orderNo: string; inboundCode: string; orderType: string; packageCount: number; overseasWarehouseId?: string } export interface LastlegOrderSummary { id: string; orderNo: string; inboundCode: string; orderType: string; packageCount: number; overseasWarehouseId?: string }
@@ -23,10 +23,11 @@ export interface RelabelDetail {
remark?: string; items: RelabelItemDetail[] remark?: string; items: RelabelItemDetail[]
history: Array<{ fromStatus?: string; toStatus?: string; operatorId?: string; remark?: string; createdAt: string }> history: Array<{ fromStatus?: string; toStatus?: string; operatorId?: string; remark?: string; createdAt: string }>
tailOrders?: Array<{ id: string; orderNo: string; overseasWarehouseId: string; packageCount: number; status: string }> tailOrders?: Array<{ id: string; orderNo: string; overseasWarehouseId: string; packageCount: number; status: string }>
completionEvidence?: { taskId: string; photoFileIds: string[]; completionRemark?: string; reviewerName?: string; reviewRemark?: string; completedAt?: string } completionEvidence?: { taskId: string; photoFileIds: string[]; completionRemark?: string; reviewerName?: string; reviewRemark?: string; completedAt?: string; customerConfirmedAt?: string }
} }
export interface DiscardSummary { id: string; discardNo: string; outboundNo?: string; inboundCodes: string; overseasWarehouseId: string; overseasWarehouseName: string; totalPackages: number; totalFee: number; currency: string; status: string; createdAt: string; completedAt?: string } export interface DiscardSummary { id: string; discardNo: string; outboundNo?: string; inboundCodes: string; overseasWarehouseId: string; overseasWarehouseName: string; totalPackages: number; totalFee: number; currency: string; status: string; createdAt: string; completedAt?: string; customerConfirmedAt?: string; skuCodes: string[]; skuCount: number; requestedPackages: number; actualPackages: number | null }
export interface DiscardCandidate { orderId: string; sourceType?: 'DROPSHIP' | 'RETURN_CARTON'; returnCartonId?: string; cartonMark?: string; inboundCode: string; inboundOrderNo: string; overseasWarehouseId: string; overseasWarehouseName: string; availablePackages: number; skus: Array<{ skuCode: string; productName: string; availablePackages: number }> } export interface DiscardBox { cartonId: string; cartonMark: string; palletNo?: string; skus: Array<{ skuCode: string; productName: string; availablePackages: number; availablePieces?: number | null }> }
export interface DiscardCandidate { cartons?: DiscardBox[]; cartonSelectionSupported?: boolean; cartonSelectionBlockReason?: string; orderId: string; sourceType?: 'DROPSHIP' | 'RETURN_CARTON' | 'INVENTORY'; inventoryPositionId?: string; palletNo?: string; returnCartonId?: string; cartonMark?: string; inboundCode: string; inboundOrderNo: string; overseasWarehouseId: string; overseasWarehouseName: string; availablePackages: number; skus: Array<{ skuCode: string; productName: string; availablePackages: number }> }
export interface RelabelInventoryCandidate { export interface RelabelInventoryCandidate {
cartonSkuItems: Array<{ skuCode: string; quantity: number }>; cartonAvailablePackages: number | string cartonSkuItems: Array<{ skuCode: string; quantity: number }>; cartonAvailablePackages: number | string
skuConversions?: import('./returnInventory').ReturnSkuConversion[] skuConversions?: import('./returnInventory').ReturnSkuConversion[]
@@ -44,10 +45,10 @@ export interface TransferCreate {
inboundCode?: string; sourceLastlegOrderIds?: string[]; operatingWarehouseId: string; fbaWarehouseCode?: string; destinationType?: 'NONE' | 'FBA' | 'PRIVATE' inboundCode?: string; sourceLastlegOrderIds?: string[]; operatingWarehouseId: string; fbaWarehouseCode?: string; destinationType?: 'NONE' | 'FBA' | 'PRIVATE'
destinationWarehouseId?: string; destinationWarehouseCode?: string; destinationWarehouseName?: string destinationWarehouseId?: string; destinationWarehouseCode?: string; destinationWarehouseName?: string
privateDestinationAddress?: string; privateDestinationPostalCode?: string; privateDestinationContactName?: string; privateDestinationContactPhone?: string privateDestinationAddress?: string; privateDestinationPostalCode?: string; privateDestinationContactName?: string; privateDestinationContactPhone?: string
deliveryAddress: string; packageCount: number; volumeCbm: number; deliveryMethod: string; estimatedArrivalAt: string; estimatedShipAt?: string deliveryAddress?: string; packageCount: number; volumeCbm: number; deliveryMethod?: string; estimatedArrivalAt?: string; estimatedShipAt?: string
fbaShipmentNo?: string; trackingNo?: string; fbaBoxNos?: string; remark?: string; needRelabel: boolean; idempotencyKey: string fbaShipmentNo?: string; trackingNo?: string; fbaBoxNos?: string; remark?: string; needRelabel: boolean; idempotencyKey: string
labelDeadline?: string; pickupContactName?: string; pickupContactPhone?: string; relabelContactName?: string; relabelContactPhone?: string; relabelChargeAmount?: number; relabelDeliveryMethod?: RelabelDeliveryMethod labelDeadline?: string; pickupContactName?: string; pickupContactPhone?: string; relabelContactName?: string; relabelContactPhone?: string; relabelChargeAmount?: number; relabelDeliveryMethod?: RelabelDeliveryMethod
items: Array<{ skuCode?: string; productNameZh?: string; packageCount: number; shippingMark?: string }> items: Array<{ skuCode?: string; productNameZh?: string; quantity: number; packageCount: number; shippingMark?: string; cartonMarks?: string[] }>
relabelItems?: Array<{ operationType: 'CARTON_LABEL' | 'SKU_LABEL' | 'CARTON_AND_SKU'; customerCartonMarks: string[]; originalSku?: string; newSku?: string; quantity: number; fbaCartonMark?: string; destinationWarehouseCode?: string; remark?: string }> relabelItems?: Array<{ operationType: 'CARTON_LABEL' | 'SKU_LABEL' | 'CARTON_AND_SKU'; customerCartonMarks: string[]; originalSku?: string; newSku?: string; quantity: number; fbaCartonMark?: string; destinationWarehouseCode?: string; remark?: string }>
} }
export interface RelabelCreate { export interface RelabelCreate {
@@ -75,6 +76,10 @@ export function updateTransfer(transferNo: string, payload: TransferCreate) {
export function submitTransfer(transferNo: string) { export function submitTransfer(transferNo: string) {
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/submit` }) return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/submit` })
} }
/** 补充既有SKU的预报箱数,原箱数快照用于并发核对与安全重试。 */
export function increaseTransferForecastCartons(transferNo: string, payload: { expectedPackageCount: number; packageCount: number }) {
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/increase-forecast-cartons`, data: payload })
}
export function listRelabels(params: Record<string, unknown>) { export function listRelabels(params: Record<string, unknown>) {
return apiRequest<PageResult<RelabelSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications', params }) return apiRequest<PageResult<RelabelSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications', params })
} }
@@ -127,14 +132,28 @@ export function getDiscard(discardNo: string) {
export function listDiscardCandidates(inboundCode?: string) { export function listDiscardCandidates(inboundCode?: string) {
return apiRequest<DiscardCandidate[]>({ method: 'GET', url: '/merchant/v1/last-leg/cargo-discards/inventory-candidates', params: { inboundCode: inboundCode || undefined } }) return apiRequest<DiscardCandidate[]>({ method: 'GET', url: '/merchant/v1/last-leg/cargo-discards/inventory-candidates', params: { inboundCode: inboundCode || undefined } })
} }
export function createDiscard(payload: { items: Array<{ orderId?: string; returnCartonId?: string; skuCode: string; discardPackages: number }>; idempotencyKey: string; remark?: string }) { export function createDiscard(payload: { items: Array<{ orderId?: string; returnCartonId?: string; inventoryPositionId?: string; cartonIds?: string[]; skuCode: string; discardPackages: number }>; idempotencyKey: string; remark?: string; requestedPackages?: number }) {
return apiRequest<Record<string, unknown>>({ method: 'POST', url: '/merchant/v1/last-leg/cargo-discards', data: payload }) return apiRequest<Record<string, unknown>>({ method: 'POST', url: '/merchant/v1/last-leg/cargo-discards', data: payload })
} }
export function cancelDiscard(discardNo: string) { export function cancelDiscard(discardNo: string) {
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/cancel` }) return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/cancel` })
} }
export function confirmDiscardCompletion(discardNo: string) {
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/confirm-completion` })
}
export interface DiscardPhoto { fileId: string; palletNo: string; fileName: string; createdAt: string; submittedAt: string } export interface DiscardPhoto { fileId: string; palletNo: string; fileName: string; createdAt: string; submittedAt: string }
export function downloadDiscardPhoto(discardNo: string, fileId: string) { export function downloadDiscardPhoto(discardNo: string, fileId: string) {
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/photos/files/${encodeURIComponent(fileId)}/download` }) return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/photos/files/${encodeURIComponent(fileId)}/download` })
} }
export interface TransferSourceCarton { cartonMark: string; productNameZh?: string; quantity?: number; destinationWarehouseCode?: string; destinationWarehouseName?: string; items: Array<{skuCode?: string; quantity?: number}> }
export function getTransferSourceCartons(operatingWarehouseId: string, inboundCode: string) {
return apiRequest<TransferSourceCarton[]>({method:'GET',url:'/merchant/v1/last-leg/warehouse-transfers/inventory-source-cartons',params:{operatingWarehouseId,inboundCode}})
}
/** 通过客户授权入口读取申请绑定的资料,不使用平台文件地址。 */
export function downloadRelabelDocument(relabelNo: string, fileId: string, scope: string, itemId?: string) {
const base = '/merchant/v1/last-leg/relabel-applications/' + encodeURIComponent(relabelNo)
return apiBlobRequest({ method: 'GET', url: scope === 'SHIPPING' ? base + '/shipping-label/' + encodeURIComponent(fileId) + '/download' : base + '/files/' + encodeURIComponent(fileId) + '/download', params: scope === 'SHIPPING' ? undefined : { scope, itemId } })
}
@@ -0,0 +1,113 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
const source = readFileSync(new URL('./CompletionConfirmationDialog.vue', import.meta.url), 'utf8')
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
const js = ts.transpileModule(script, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText
.replace(/^import .*$/gm, '').replace(/^export \{\};?$/gm, '')
function harness(kind = 'disposal', overrides = {}) {
const props = { modelValue: true, kind, documentNo: 'CD/1' }
const calls = []; const events = []; const revoked = []
const api = {
getDiscard: async () => ({ summary: { status: 'PDA_COMPLETED' }, photos: [{ fileId: '101' }] }),
getRelabel: async () => ({ application: { status: 'CUSTOMER_CONFIRM_PENDING' }, completionEvidence: { photoFileIds: ['101'] } }),
getTransfer: async () => ({ status: 'WAIT_CUSTOMER_CONFIRMATION', measurementPhotos: [{ fileId: '101' }], cartons: [{ cartonMark: 'BOX-1', status: 'COUNTED', weight: 5 }], pallets: [{ palletNo: 'PLT-1', grossWeightKg: 5 }] }),
downloadTransferMeasurementPhoto: async () => ({}),
confirmTransferMeasurement: async no => calls.push(['transfer', no]),
downloadDiscardPhoto: async () => ({}), downloadRelabelCompletionPhoto: async () => ({}),
confirmDiscardCompletion: async no => calls.push(['discard', no]),
confirmRelabelCompletion: async no => calls.push(['relabel', no]), ...overrides,
}
const env = {
computed: fn => ({ get value() { return fn() } }), ref: value => ({ value }), watch: () => {}, onBeforeUnmount: () => {},
defineProps: () => props, defineEmits: () => (...args) => events.push(args),
useAuthStore: () => ({ hasPermission: () => true }), ElMessage: { success() {}, error() {} },
URL: { createObjectURL: () => 'blob:photo', revokeObjectURL: url => revoked.push(url) }, ...api,
}
const state = new Function(...Object.keys(env), js + '\nreturn { loadEvidence, loadPhoto, submit, clear, checked, canConfirm, urls, failed, error, busy, measurement };')(...Object.values(env))
return { ...state, props, calls, events, revoked }
}
test('仓储转运客户确认测量弹窗不展示箱子明细和托盘尺寸', () => {
assert.doesNotMatch(source, /<el-table :data="measurement\.cartons\?\.filter\(carton => carton\.status === 'COUNTED'\)/)
assert.doesNotMatch(source, /<el-table-column label="尺寸\(cm\)"/)
assert.doesNotMatch(source, /箱数、尺寸、重量/)
assert.match(source, /<el-table-column prop="grossWeightKg" label="毛重\(kg\)"/)
assert.match(source, /<el-table-column prop="volumeCbm" label="体积\(m³\)"/)
})
for (const kind of ['disposal', 'labeling', 'transfer']) {
test(`${kind}: opening loads photos without confirming; only reviewed evidence can be submitted`, async () => {
const state = harness(kind)
await state.loadEvidence()
assert.deepEqual(state.calls, [])
await state.submit(); assert.deepEqual(state.calls, [])
state.checked.value = true
assert.equal(state.canConfirm.value, true)
await state.submit()
assert.deepEqual(state.calls, [[kind === 'transfer' ? 'transfer' : kind === 'disposal' ? 'discard' : 'relabel', 'CD/1']])
assert.deepEqual(state.events, [['confirmed', 'CD/1'], ['update:modelValue', false]])
state.clear(); assert.deepEqual(state.revoked, ['blob:photo'])
})
}
test('transfer confirmation reads current measurements and blocks missing, failed or outdated evidence', async () => {
const state = harness('transfer', { downloadTransferMeasurementPhoto: async () => { throw Error('offline') } })
await state.loadEvidence()
assert.equal(state.measurement.value.pallets[0].grossWeightKg, 5)
assert.equal(state.measurement.value.cartons[0].cartonMark, 'BOX-1')
state.checked.value = true
await state.submit()
assert.equal(state.canConfirm.value, false)
assert.deepEqual(state.calls, [])
for (const detail of [
{ status: 'WAIT_CUSTOMER_CONFIRMATION', measurementPhotos: [] },
{ status: 'COMPLETED', measurementPhotos: [{ fileId: '101' }] },
{ status: 'WAIT_CUSTOMER_CONFIRMATION', customerConfirmedAt: '2026-10-16', measurementPhotos: [{ fileId: '101' }] },
]) {
const invalid = harness('transfer', { getTransfer: async () => detail })
await invalid.loadEvidence(); invalid.checked.value = true; await invalid.submit()
assert.equal(invalid.canConfirm.value, false)
assert.deepEqual(invalid.calls, [])
}
})
test('photo failure blocks confirmation and supports retry', async () => {
let reject = true
const state = harness('disposal', { downloadDiscardPhoto: async () => { if (reject) throw Error('offline'); return {} } })
await state.loadEvidence(); state.checked.value = true
assert.equal(state.failed.value['101'], true); assert.equal(state.canConfirm.value, false)
reject = false; await state.loadPhoto('101')
assert.equal(state.canConfirm.value, true)
})
test('closing while photos load prevents stale preview URLs', async () => {
let resolve
const state = harness('disposal', { downloadDiscardPhoto: () => new Promise(done => { resolve = done }) })
const pending = state.loadEvidence()
await Promise.resolve()
state.props.modelValue = false; state.clear(); resolve({}); await pending
assert.deepEqual(state.urls.value, {})
})
test('completed orders and missing evidence cannot be confirmed', async () => {
for (const detail of [{ summary: { status: 'COMPLETED' }, photos: [{ fileId: '101' }] }, { summary: { status: 'PDA_COMPLETED' }, photos: [] }]) {
const state = harness('disposal', { getDiscard: async () => detail })
await state.loadEvidence(); state.checked.value = true; await state.submit()
assert.equal(state.canConfirm.value, false); assert.deepEqual(state.calls, [])
}
})
test('failed submission preserves dialog and a pending submission is not sent twice', async () => {
let reject
const state = harness('disposal', { confirmDiscardCompletion: () => new Promise((_, fail) => { reject = fail }) })
await state.loadEvidence(); state.checked.value = true
const pending = state.submit()
assert.equal(state.busy.value, true); await state.submit()
reject(Error('offline')); await pending
assert.deepEqual(state.events, []); assert.equal(state.busy.value, false)
assert.equal(state.canConfirm.value, true)
})
@@ -0,0 +1,130 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/modules/auth/public'
import { confirmDiscardCompletion, confirmRelabelCompletion, confirmTransferMeasurement, downloadDiscardPhoto, downloadRelabelCompletionPhoto, downloadTransferMeasurementPhoto, getDiscard, getRelabel, getTransfer, type DiscardPhoto } from '../api/warehouseServices'
const props = defineProps<{ modelValue: boolean; kind: 'disposal' | 'labeling' | 'transfer'; documentNo: string }>()
const emit = defineEmits<{ 'update:modelValue': [value: boolean]; confirmed: [documentNo: string] }>()
const auth = useAuthStore()
const title = computed(() => props.kind === 'transfer' ? '确认测量数据' : props.kind === 'disposal' ? '废弃确认' : '贴标完成确认')
interface MeasurementEvidence {
status?: string
customerConfirmedAt?: string
cartons?: Array<{ cartonMark: string; status: string; length?: number; width?: number; height?: number; weight?: number }>
pallets?: Array<{ palletNo?: string; sequenceNo?: number; cartonCount?: number; lengthCm?: number; widthCm?: number; heightCm?: number; grossWeightKg?: number; volumeCbm?: number }>
measurementPhotos?: Array<{ fileId: string | number }>
}
const measurement = ref<MeasurementEvidence | null>(null)
const loading = ref(false)
const busy = ref(false)
const error = ref('')
const fileIds = ref<string[]>([])
const urls = ref<Record<string, string>>({})
const failed = ref<Record<string, boolean>>({})
const photoLoading = ref<Record<string, boolean>>({})
const checked = ref(false)
const eligible = ref(false)
let generation = 0
const previewUrls = computed(() => fileIds.value.map(id => urls.value[id]).filter(Boolean))
const canConfirm = computed(() => eligible.value && checked.value && !loading.value && !busy.value && !error.value
&& fileIds.value.length > 0 && fileIds.value.every(id => Boolean(urls.value[id]))
&& auth.hasPermission(`merchant:overseas-warehouse:${props.kind === 'transfer' ? 'transfer' : props.kind === 'disposal' ? 'discard' : 'relabel'}:confirm`))
function clear() {
generation++
Object.values(urls.value).forEach(URL.revokeObjectURL)
urls.value = {}; failed.value = {}; photoLoading.value = {}; fileIds.value = []; checked.value = false; eligible.value = false
measurement.value = null
}
async function loadPhoto(fileId: string) {
if (photoLoading.value[fileId]) return
const currentGeneration = generation; const no = props.documentNo; const kind = props.kind
photoLoading.value[fileId] = true; failed.value[fileId] = false
try {
const blob = kind === 'transfer' ? await downloadTransferMeasurementPhoto(no, fileId) : kind === 'disposal' ? await downloadDiscardPhoto(no, fileId) : await downloadRelabelCompletionPhoto(no, fileId)
if (generation !== currentGeneration || !props.modelValue) return
if (urls.value[fileId]) URL.revokeObjectURL(urls.value[fileId])
urls.value[fileId] = URL.createObjectURL(blob)
} catch { if (generation === currentGeneration) failed.value[fileId] = true }
finally { if (generation === currentGeneration) photoLoading.value[fileId] = false }
}
async function loadEvidence() {
clear(); error.value = ''; loading.value = true
const currentGeneration = generation
try {
if (props.kind === 'transfer') {
const detail = await getTransfer(props.documentNo) as MeasurementEvidence
if (generation !== currentGeneration) return
measurement.value = detail
eligible.value = detail.status === 'WAIT_CUSTOMER_CONFIRMATION' && !detail.customerConfirmedAt
fileIds.value = (detail.measurementPhotos || []).map(photo => String(photo.fileId))
} else if (props.kind === 'disposal') {
const detail = await getDiscard(props.documentNo) as { summary?: { status?: string }; photos?: DiscardPhoto[] }
if (generation !== currentGeneration) return
eligible.value = detail.summary?.status === 'PDA_COMPLETED'
fileIds.value = (detail.photos || []).map(photo => String(photo.fileId))
} else {
const detail = await getRelabel(props.documentNo)
if (generation !== currentGeneration) return
eligible.value = detail.application.status === 'CUSTOMER_CONFIRM_PENDING' && !detail.application.customerConfirmedAt
fileIds.value = (detail.completionEvidence?.photoFileIds || []).map(String)
}
fileIds.value = [...new Set(fileIds.value)]
if (!eligible.value) error.value = '当前单据已确认或尚未完成 PDA 作业,请刷新列表核对。'
else if (!fileIds.value.length) error.value = props.kind === 'transfer' ? '暂无 PDA 测量打托照片,暂不能确认。' : '暂无 PDA 完工作业照片,暂不能确认。'
await Promise.all(fileIds.value.map(loadPhoto))
} catch (e) { if (generation === currentGeneration) error.value = e instanceof Error ? e.message : '作业照片加载失败' }
finally { if (generation === currentGeneration) loading.value = false }
}
async function submit() {
if (!canConfirm.value) return
busy.value = true
try {
if (props.kind === 'transfer') await confirmTransferMeasurement(props.documentNo)
else if (props.kind === 'disposal') await confirmDiscardCompletion(props.documentNo)
else await confirmRelabelCompletion(props.documentNo)
ElMessage.success(props.kind === 'transfer' ? '仓库实测数据已确认' : props.kind === 'disposal' ? '废弃已确认,单据已完结' : '贴标已确认,订单进入后续出库流程')
emit('confirmed', props.documentNo)
emit('update:modelValue', false)
} catch (e) { ElMessage.error(e instanceof Error ? e.message : '确认失败,请重试') }
finally { busy.value = false }
}
watch(() => [props.modelValue, props.kind, props.documentNo], () => { if (props.modelValue) void loadEvidence(); else clear() }, { immediate: true })
onBeforeUnmount(clear)
</script>
<template>
<el-dialog :model-value="modelValue" :title="title" width="760px" :close-on-click-modal="false" :close-on-press-escape="!busy" :show-close="!busy" @update:model-value="!busy && emit('update:modelValue', $event)">
<p>单号:{{ documentNo }}</p>
<p>{{ kind === 'transfer' ? '请核对 PDA 回传的箱数、重量、打托数据及现场照片,确认无误后再提交。' : '请核对以下 PDA 作业照片,确认作业结果无误后再提交。' }}</p>
<template v-if="kind === 'transfer' && measurement">
<p>实际签收箱数:{{ measurement.cartons?.filter(carton => carton.status === 'COUNTED').length ?? 0 }} 箱;托盘数:{{ measurement.pallets?.length ?? 0 }} 托</p>
<el-table :data="measurement.pallets || []" max-height="220" size="small" border empty-text="暂无 PDA 打托测量数据">
<el-table-column label="托盘号" min-width="180"><template #default="{ row }">{{ row.palletNo || `第${row.sequenceNo || '—'}托` }}</template></el-table-column>
<el-table-column prop="cartonCount" label="箱数" width="65" />
<el-table-column prop="grossWeightKg" label="毛重(kg)" width="95" />
<el-table-column prop="volumeCbm" label="体积(m³)" width="95" />
</el-table>
</template>
<p v-if="loading">正在读取作业照片…</p>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<el-button v-if="error" :disabled="loading || busy" @click="loadEvidence">重新读取</el-button>
<div class="completion-photo-grid">
<div v-for="(fileId, index) in fileIds" :key="fileId">
<el-image v-if="urls[fileId]" :src="urls[fileId]" :preview-src-list="previewUrls" :initial-index="previewUrls.indexOf(urls[fileId])" fit="contain" preview-teleported />
<span v-else-if="photoLoading[fileId]">照片 {{ index + 1 }} 加载中…</span>
<el-button v-else :disabled="busy" @click="loadPhoto(fileId)">{{ failed[fileId] ? '照片加载失败,点击重试' : '加载照片' }}</el-button>
</div>
</div>
<el-checkbox v-model="checked" :disabled="loading || busy || !!error || previewUrls.length !== fileIds.length">{{ kind === 'transfer' ? '我已核对 PDA 实测数据及现场照片,确认无误' : '我已核对 PDA 作业照片,确认作业结果无误' }}</el-checkbox>
<template #footer>
<el-button :disabled="busy" @click="emit('update:modelValue', false)">取消</el-button>
<el-button type="primary" :loading="busy" :disabled="!canConfirm" @click="submit">{{ kind === 'transfer' ? '确认数据' : kind === 'disposal' ? '确认废弃完结' : '确认贴标完成' }}</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.completion-photo-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 16px 0; }
.completion-photo-grid .el-image { width: 100%; height: 180px; }
</style>
@@ -0,0 +1,78 @@
<script setup lang="ts">
import { computed, ref, watch, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { getRelabel, downloadRelabelDocument, type RelabelDetail } from '../api/warehouseServices'
const props = defineProps<{ relabelNo: string; detail?: RelabelDetail | null; inline?: boolean }>()
const loaded = ref<RelabelDetail | null>(null)
const loading = ref(false)
const error = ref('')
const busy = ref(false)
let generation = 0
const current = computed(() => props.detail || loaded.value)
/** 各申请分别加载,失败只影响资料区,不阻断订单详情。 */
async function load() {
const ticket = ++generation
loaded.value = null; error.value = ''
if (props.detail || !props.relabelNo) { loading.value = false; return }
loading.value = true
try { const result = await getRelabel(props.relabelNo); if (ticket === generation) loaded.value = result }
catch (cause) { if (ticket === generation) error.value = cause instanceof Error ? cause.message : '贴标资料加载失败' }
finally { if (ticket === generation) loading.value = false }
}
watch(() => [props.relabelNo, props.detail], () => { void load() }, { immediate: true })
interface DocumentRow { key: string; kind: string; fileId: string; fileName: string; scope: string; itemId?: string }
const documents = computed<DocumentRow[]>(() => {
const result: DocumentRow[] = []
const application = current.value?.application
if (!application) return result
// 旧总文件仅作为兼容回显,避免与已分类型的总文件重复展示。
const add = (kind: string, id: string | null | undefined, name: string | null | undefined, scope: string, itemId?: string) => {
if (id) result.push({ key: scope + ':' + (itemId || '') + ':' + id, kind, fileId: id, fileName: name || '未命名文件', scope, itemId })
}
add('箱唛贴标文件', application.cartonTotalFileId, application.cartonTotalFileName, 'CARTON_TOTAL')
add('SKU 贴标文件', application.skuTotalFileId, application.skuTotalFileName, 'SKU_TOTAL')
if (application.totalFileId !== application.cartonTotalFileId && application.totalFileId !== application.skuTotalFileId)
add('贴标总文件', application.totalFileId, application.totalFileName, 'TOTAL')
add('面单文件', application.shippingLabelFileId, application.shippingLabelFileName, 'SHIPPING')
for (const item of current.value?.items || []) add('明细文件', item.relabelFileId, item.relabelFileName, 'ITEM', String(item.id))
return result
})
/** 使用带身份认证的下载接口,保留文件归属校验和原始文件名。 */
async function downloadFile(key: string) {
const row = documents.value.find(document => document.key === key)
if (!row || busy.value) return
busy.value = true
const ticket = generation
try {
const blob = await downloadRelabelDocument(props.relabelNo, row.fileId, row.scope, row.itemId)
if (ticket !== generation) return
const url = URL.createObjectURL(blob); const link = document.createElement('a')
link.href = url; link.download = row.fileName; link.click(); window.setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (cause) { ElMessage.error(cause instanceof Error ? cause.message : '文件读取失败,请重试') }
finally { busy.value = false }
}
onBeforeUnmount(() => { ++generation })
</script>
<template>
<section class="relabel-documents" :class="{ 'relabel-documents--inline': inline }" aria-label="客户上传的贴标文件">
<h3>贴标文件</h3>
<p v-if="loading">资料加载中…</p>
<p v-else-if="error" role="alert">{{ error }} <el-button link type="primary" @click="load">重试</el-button></p>
<div v-else-if="inline" class="relabel-document-links">
<div v-for="row in documents" :key="row.key" class="relabel-document-link"><span>{{ row.kind }}</span><el-button link type="primary" :disabled="busy" @click="downloadFile(row.key)">下载</el-button></div>
<span v-if="!documents.length">暂无上传的贴标文件</span>
</div>
<el-table v-else :data="documents" row-key="key" border empty-text="暂无上传的贴标文件">
<el-table-column prop="kind" label="文件类型" min-width="150" />
<el-table-column label="操作" width="90"><template #default="{ row }"><el-button link type="primary" :disabled="busy" @click="downloadFile(String(row.key))">下载</el-button></template></el-table-column>
</el-table>
</section>
</template>
<style scoped>
.relabel-documents { margin: 16px 0; }
.relabel-documents h3 { margin: 0 0 12px; font-size: 14px; }
.relabel-documents--inline { display: flex; align-items: center; gap: 12px; margin: 0; min-width: 0; }
.relabel-documents--inline h3 { flex-shrink: 0; margin: 0; color: var(--muted); font-size: 12px; font-weight: 400; }
.relabel-document-links { display: flex; flex-wrap: wrap; gap: 4px 12px; }
.relabel-document-link { display: flex; align-items: center; gap: 8px; }
</style>
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
import { getRelabelQuantities, type RelabelQuantityTotals } from '../api/relabelQuantities'
const props = defineProps<{ query?: Record<string, unknown>; relabelNo?: string }>()
const data = ref<RelabelQuantityTotals | null>(null)
const error = ref('')
let generation = 0
function dimension(known: number, unknown: number, unit: string) {
if (unknown > 0 && known === 0) return `—(${unknown} 票)`
return `已知 ${known} ${unit}${unknown > 0 ? `(${unknown} 票 —)` : ''}`
}
watch(() => [props.query, props.relabelNo], async () => {
const current = ++generation
data.value = null; error.value = ''
try {
const result = await getRelabelQuantities({ ...props.query, ...(props.relabelNo ? { relabelNo: props.relabelNo } : {}) })
if (current === generation) data.value = result
} catch { if (current === generation) error.value = '数量汇总加载失败,请刷新重试' }
}, { immediate: true, deep: true })
</script>
<template>
<section class="relabel-quantity-panel" aria-label="贴标数量维度">
<p v-if="error" role="alert">{{ error }}</p>
<template v-else-if="data">
<strong>{{ relabelNo ? '本单数量' : '全部筛选结果' }}</strong>
<span>{{ data.orderCount }} 票</span><span>{{ data.skuCount }} 种 SKU</span>
<span>贴标件数:{{ dimension(Number(data.knownLabelPieceCount), Number(data.unknownPieceOrders), '件') }}</span>
<span>箱数:{{ dimension(Number(data.knownCartonCount), Number(data.unknownCartonOrders), '箱') }}</span>
<span>原托盘:{{ dimension(Number(data.knownSourcePalletCount ?? 0), Number(data.unknownSourcePalletOrders ?? data.orderCount), '托') }}</span>
<span>本轮目标托盘:{{ dimension(Number(data.knownTargetPalletCount ?? 0), Number(data.unknownTargetPalletOrders ?? data.orderCount), '托') }}</span>
<p v-if="relabelNo && data.orders[relabelNo]?.duplicateCarton" role="status">存在重复箱唛关联,箱数已去重,贴标件数待核查。</p>
</template>
<span v-else>数量加载中…</span>
</section>
</template>
<style scoped>
.relabel-quantity-panel { display: flex; gap: 12px; flex-wrap: wrap; padding: 12px 16px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface, white); margin-bottom: 12px; }
.relabel-quantity-panel p { margin: 0; }
</style>
@@ -0,0 +1,29 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { parse } from 'vue/compiler-sfc'
const source = readFileSync(new URL('./ReviewRejectionNotice.vue', import.meta.url), 'utf8')
const template = parse(source).descriptor.template.content
const render = (status, reason) => renderToString(createSSRApp({ template, props: ['status', 'reason'] }, { status, reason }))
test('rejected documents display the actual reason safely', async () => {
const html = await render('REJECTED', '箱数不符\n请核对 <SKU>')
assert.match(html, /驳回原因/)
assert.match(html, /箱数不符\n请核对 &lt;SKU&gt;/)
assert.match(html, /role="alert"/)
})
test('non-rejected documents do not show an old rejection reason', async () => {
for (const status of ['PENDING_REVIEW', 'APPROVED', 'COMPLETED', undefined]) {
assert.doesNotMatch(await render(status, '旧审核原因'), /旧审核原因|驳回原因/)
}
})
test('legacy rejection without a reason has an explicit fallback', async () => {
for (const reason of [undefined, '', ' ']) {
assert.match(await render('REJECTED', reason), /暂未记录驳回原因/)
}
})
@@ -0,0 +1,16 @@
<script setup lang="ts">
defineProps<{ status?: string; reason?: string }>()
</script>
<template>
<div v-if="status === 'REJECTED'" class="review-rejection-notice" role="alert">
<strong>驳回原因</strong>
<span>{{ reason?.trim() || '暂未记录驳回原因,请联系平台确认' }}</span>
</div>
</template>
<style scoped>
.review-rejection-notice{display:flex;align-items:flex-start;gap:12px;margin:12px 16px;padding:10px 12px;border:1px solid var(--el-color-danger-light-7);border-radius:4px;background:var(--el-color-danger-light-9);color:var(--el-color-danger);font-size:13px;line-height:1.7}
.review-rejection-notice strong{flex-shrink:0;font-weight:600}
.review-rejection-notice span{min-width:0;white-space:pre-wrap;overflow-wrap:anywhere}
</style>
@@ -0,0 +1,52 @@
<script setup lang="ts">
const props = defineProps<{ modelValue: number }>()
const emit = defineEmits<{ 'update:modelValue': [value: number] }>()
let drag: { pointerId: number; startX: number; startValue: number; width: number } | null = null
function resize(value: number) {
emit('update:modelValue', Math.min(65, Math.max(35, value)))
}
function startDrag(event: PointerEvent) {
if (event.button !== 0 || !event.isPrimary) return
const handle = event.currentTarget as HTMLElement
const width = (handle.parentElement?.getBoundingClientRect().width ?? 0) - 16
if (width <= 0) return
event.preventDefault()
handle.focus()
drag = { pointerId: event.pointerId, startX: event.clientX, startValue: props.modelValue, width }
handle.setPointerCapture(event.pointerId)
}
function moveDrag(event: PointerEvent) {
if (!drag || drag.pointerId !== event.pointerId) return
resize(drag.startValue + (event.clientX - drag.startX) / drag.width * 100)
}
function endDrag(event: PointerEvent) {
if (drag?.pointerId !== event.pointerId) return
drag = null
const handle = event.currentTarget as HTMLElement
if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId)
}
function keyResize(event: KeyboardEvent) {
const value = { ArrowLeft: props.modelValue - 2, ArrowRight: props.modelValue + 2, Home: 35, End: 65, Enter: 43 }[event.key]
if (value === undefined) return
event.preventDefault()
resize(value)
}
</script>
<template>
<div class="transfer-pane-divider" role="separator" tabindex="0" aria-label="调整转运信息和换标申请宽度"
aria-orientation="vertical" :aria-valuenow="Math.round(modelValue)" :aria-valuemin="35" :aria-valuemax="65"
aria-controls="transfer-main-pane transfer-relabel-pane" title="左右拖动调整宽度,双击恢复"
@pointerdown="startDrag" @pointermove="moveDrag" @pointerup="endDrag" @pointercancel="endDrag"
@lostpointercapture="drag = null" @keydown="keyResize" @dblclick="resize(43)">
<span aria-hidden="true" />
</div>
</template>
<style scoped>
.transfer-pane-divider { display:flex; width:16px; align-items:center; justify-content:center; align-self:stretch; cursor:col-resize; touch-action:none; user-select:none; outline:none; }
.transfer-pane-divider span { width:4px; height:64px; border-radius:4px; background:#c5d1e1; transition:background .15s; }
.transfer-pane-divider:hover, .transfer-pane-divider:focus-visible { background:#e9f1ff; border-radius:6px; }
.transfer-pane-divider:hover span, .transfer-pane-divider:focus-visible span { background:#3478c8; }
</style>
@@ -0,0 +1,38 @@
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { getTransferPickupProgress, downloadTransferPickupEvidence, type PickupProgress } from '../api/transferPickups'
const props = defineProps<{ transferNo: string }>()
const progress = ref<PickupProgress | null>(null), error = ref(''), loading = ref(false)
const labels: Record<string, string> = { PENDING_REVIEW: '待审核', WAITING: '待安排取货', ASSIGNED: '已安排取货', PICKED: '已取货', ARRIVED: '已送仓' }
const time = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—'
let sequence = 0
/** 业务号变化后忽略旧响应,客户之间不复用取货数据。 */
async function load() {
const current = ++sequence; progress.value = null; error.value = ''; loading.value = true
try { const value = await getTransferPickupProgress(props.transferNo); if (current === sequence) progress.value = value }
catch (cause) { if (current === sequence) error.value = cause instanceof Error ? cause.message : '取货进度加载失败' }
finally { if (current === sequence) loading.value = false }
}
/** 凭证读取必须经过原单鉴权。 */
async function download(file: { fileId: string; fileName: string }) {
try { const blob = await downloadTransferPickupEvidence(props.transferNo, file.fileId); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = file.fileName; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000) }
catch (cause) { error.value = cause instanceof Error ? cause.message : '取货凭证下载失败' }
}
watch(() => props.transferNo, load, { immediate: true }); onBeforeUnmount(() => { sequence++ })
</script>
<template>
<section v-if="loading || progress || error" v-loading="loading" class="pickup-progress" aria-label="取货安排">
<div class="pickup-heading"><h3>取货安排</h3><el-button size="small" :disabled="loading" @click="load">刷新进度</el-button></div>
<el-alert v-if="error" :title="error" type="error" :closable="false" />
<dl v-if="progress" class="pickup-fields">
<div><dt>取货进度</dt><dd>{{ labels[progress.status] || progress.status }}</dd></div><div><dt>车次号</dt><dd>{{ progress.tripNo || '待安排' }}</dd></div>
<div><dt>车牌</dt><dd>{{ progress.vehiclePlate || '待分配' }}</dd></div><div><dt>司机</dt><dd>{{ progress.driverName || '待分配' }}</dd></div>
<div><dt>司机电话</dt><dd>{{ progress.driverPhone || '—' }}</dd></div><div><dt>计划取货发车</dt><dd>{{ time(progress.plannedDepartureAt) }}</dd></div>
<div><dt>实际取货数量(箱)</dt><dd>{{ progress.actualPackages ?? '待取货' }}</dd></div><div><dt>取货时间</dt><dd>{{ time(progress.pickedAt) }}</dd></div>
<div><dt>送仓时间</dt><dd>{{ time(progress.arrivedAt) }}</dd></div><div v-if="progress.remark"><dt>取货备注</dt><dd>{{ progress.remark }}</dd></div>
</dl>
<div v-if="progress?.evidence.length" class="pickup-files"><span>取货凭证</span><el-button v-for="file in progress.evidence" :key="file.fileId" link type="primary" @click="download(file)">{{ file.fileName }}</el-button></div>
</section>
</template>
<style scoped>.pickup-progress{padding:0 16px 10px;border:1px solid var(--border,#e5e7eb);border-radius:6px;margin:16px 0}.pickup-heading{display:flex;min-height:40px;justify-content:space-between;align-items:center}.pickup-heading h3{margin:0;font-size:14px}.pickup-fields{display:grid;max-width:1408px;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px 18px;margin:8px 0 0}.pickup-fields>div{display:flex;min-height:24px;align-items:center;gap:8px;padding:1px 0}.pickup-fields dt{flex:0 0 84px;min-width:0;color:#8a95a5;font-size:12px}.pickup-fields dd{min-width:0;margin:0;overflow-wrap:anywhere;color:#334157;font-size:13px;font-weight:700}.pickup-files{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:8px}.pickup-files>span{color:#8a95a5;font-size:12px}@media(max-width:1100px){.pickup-fields{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.pickup-fields{grid-template-columns:1fr;gap:2px}}</style>
@@ -1,6 +1,7 @@
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 routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8') const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8')
const services = readFileSync(new URL('./views/WarehouseServiceView.vue', import.meta.url), 'utf8') const services = readFileSync(new URL('./views/WarehouseServiceView.vue', import.meta.url), 'utf8')
@@ -41,13 +42,31 @@ test('opens warehouse service and return receipt details as dedicated protected
}) })
test('returns to the labeling list after a labeling application is submitted', () => { test('returns to the labeling list after a labeling application is submitted', () => {
assert.match(services, /ElMessage\.success\(`\$\{config\.value\.title\}提交成功`\)[\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/) assert.match(services, /ElMessage\.success\(`\$\{config\.value\.title\}提交成功`\)[\s\S]*?await goToServiceList\(\)/)
// Return-carton sources use the unified relabel application and its file endpoint. // Return-carton sources use the unified relabel application and its file endpoint.
assert.match(services, /returnCartonId: item\.returnCartonId/) assert.match(services, /returnCartonId: item\.returnCartonId/)
assert.match(services, /uploadRelabelFile\(created\.application\.relabelNo,[\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/) assert.match(services, /uploadRelabelFile\(created\.application\.relabelNo,[\s\S]*?await goToServiceList\(\)/)
assert.match(services, /申请已创建,附件待补传/) assert.match(services, /申请已创建,附件待补传/)
}) })
test('service list return navigates standalone pages and refreshes embedded lists', async () => {
const source = services.slice(services.indexOf('function serviceListRouteName('), services.indexOf('async function openEdit('))
const javascript = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
for (const props of [
{ service: 'labeling', createPage: true, detailPage: false },
{ service: 'labeling', createPage: false, detailPage: true },
{ service: 'labeling', createPage: false, detailPage: false },
]) {
const calls = [], mode = { value: 'create' }
const goToServiceList = new Function('props', 'router', 'mode', 'loadPage', `${javascript}; return goToServiceList`)(
props, { push: async route => calls.push(route) }, mode, async () => calls.push('refresh'),
)
await goToServiceList()
assert.deepEqual(calls, props.createPage || props.detailPage ? [{ name: 'overseas-labeling' }] : ['refresh'])
if (!props.createPage && !props.detailPage) assert.equal(mode.value, 'list')
}
})
test('keeps overseas warehouse writes behind operation-specific button permissions', () => { test('keeps overseas warehouse writes behind operation-specific button permissions', () => {
for (const permission of [ for (const permission of [
'merchant:overseas-warehouse:relabel:create', 'merchant:overseas-warehouse:relabel:create',
+11
View File
@@ -5,6 +5,17 @@ export const overseasWarehouseModule = {
key: 'overseas-warehouse', key: 'overseas-warehouse',
navigationGroup: { title: '海外仓', icon: Warehouse }, navigationGroup: { title: '海外仓', icon: Warehouse },
routes: [ routes: [
{
path: 'overseas-warehouse/storage-transfer/create', name: 'overseas-storage-transfer-create',
component: () => import('./views/WarehouseServiceView.vue'), props: { service: 'transfer', createPage: true }, release: 'active',
meta: { title: '新增仓储转运单', workspaceTitle: '仓储转运 · 新建', description: '填写并提交仓储转运申请', permission: 'merchant:overseas-warehouse:transfer:create', keepAlive: false },
},
{
path: 'overseas-warehouse/cargo-disposal/create', name: 'overseas-cargo-disposal-create',
component: () => import('./views/WarehouseServiceView.vue'), props: { service: 'disposal', createPage: true }, release: 'active',
meta: { title: '新增货物废弃申请', workspaceTitle: '货物废弃 · 新建', description: '填写并提交货物废弃申请', permission: 'merchant:overseas-warehouse:discard:create', keepAlive: false },
},
{ {
path: 'overseas-warehouse/labeling/create', name: 'overseas-labeling-create', path: 'overseas-warehouse/labeling/create', name: 'overseas-labeling-create',
component: () => import('./views/WarehouseServiceView.vue'), props: { service: 'labeling', createPage: true }, release: 'active', component: () => import('./views/WarehouseServiceView.vue'), props: { service: 'labeling', createPage: true }, release: 'active',
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
import ts from 'typescript'
const compiled = ts.transpileModule(readFileSync(new URL('./discardDocuments.ts', import.meta.url), 'utf8'), { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText
const { groupDiscardDocuments } = await import(`data:text/javascript;base64,${Buffer.from(compiled).toString('base64')}`)
const returned = (id, warehouse = 'WH', document = 'TT-BYWL-261019152551') => ({
orderId: `return:${id}`, returnCartonId: id, sourceType: 'RETURN_CARTON', overseasWarehouseId: warehouse,
inboundCode: document, inboundOrderNo: document, availablePackages: 5, cartonSelectionSupported: true,
cartons: [{ cartonId: id, cartonMark: `BOX-${id}`, skus: [{ skuCode: 'A', availablePackages: 5 }] }], skus: [{ skuCode: 'A', availablePackages: 5 }],
})
test('同单两箱合并成一个选项,可用量为两箱而非十件,保留原始提交身份', () => {
const sources = [returned('1'), returned('2')]
const result = groupDiscardDocuments(sources)
assert.equal(result.length, 1)
assert.equal(result[0].availablePackages, 2)
assert.deepEqual(result[0].sources, sources)
assert.equal(result[0].cartonSelectionSupported, true)
})
test('不同单据或操作仓独立展示,混装SKU不重复计算物理箱', () => {
assert.equal(groupDiscardDocuments([returned('1'), returned('2', 'OTHER'), returned('3', 'WH', 'TT-OTHER')]).length, 3)
const source = { ...returned('1'), sourceType: 'INVENTORY', orderId: 'inventory:1', inventoryPositionId: '1', availablePackages: 10 }
const second = { ...source, orderId: 'inventory:2', inventoryPositionId: '2', cartons: source.cartons }
assert.equal(groupDiscardDocuments([source, second])[0].availablePackages, 1)
})
test('缺少箱级记录时合并仓位可用箱数并保持全部废弃明细', () => {
const first = { ...returned('1'), sourceType: 'INVENTORY', orderId: 'inventory:1', cartonSelectionSupported: false, availablePackages: 3 }
const second = { ...first, orderId: 'inventory:2', availablePackages: 4 }
const result = groupDiscardDocuments([first, second])[0]
assert.equal(result.availablePackages, 7)
assert.equal(result.cartonSelectionSupported, false)
assert.equal(result.sources.length, 2)
})
test('接口 Long 字符串按数值相加,不串联数字', () => {
const source = { ...returned('1'), sourceType: 'INVENTORY', cartonSelectionSupported: false }
const sources = ['50', '100', '97'].map((availablePackages, index) => ({ ...source, orderId: `inventory:${index}`, returnCartonId: undefined, availablePackages }))
assert.equal(groupDiscardDocuments(sources)[0].availablePackages, 247)
assert.equal(groupDiscardDocuments([{ ...source, orderId: 'i:1', returnCartonId: undefined, availablePackages: '125' }, { ...source, orderId: 'i:2', returnCartonId: undefined, availablePackages: '125' }])[0].availablePackages, 250)
})
test('相同仓位重复关联只计一次,零值与未知可用量不进入可选来源', () => {
const source = { ...returned('1'), returnCartonId: undefined, sourceType: 'INVENTORY', inventoryPositionId: 'position:1', cartonSelectionSupported: false, availablePackages: 2 }
assert.equal(groupDiscardDocuments([source, source])[0].availablePackages, 2)
for (const availablePackages of [0, null, undefined, 'invalid']) assert.equal(groupDiscardDocuments([{ ...source, availablePackages }]).length, 0)
})
test('相同来源的混箱分片保留全部SKU和实箱,且不修改接口原始对象', () => {
const a = { ...returned('1'), sourceType: 'INVENTORY', inventoryPositionId: 'P', skus: [{ skuCode: 'A', availablePackages: 1 }] }
const b = { ...a, skus: [{ skuCode: 'B', availablePackages: 1 }], cartons: [{ ...a.cartons[0], skus: [{ skuCode: 'B', availablePackages: 1 }] }] }
const doc = groupDiscardDocuments([a, b])[0]
assert.equal(doc.availablePackages, 1)
assert.equal(doc.sources.length, 1)
assert.deepEqual(doc.sources[0].skus.map(sku => sku.skuCode), ['A', 'B'])
assert.deepEqual(doc.sources[0].cartons[0].skus.map(sku => sku.skuCode), ['A', 'B'])
assert.equal(a.skus.length, 1)
})
@@ -0,0 +1,61 @@
import type { DiscardCandidate } from '../api/warehouseServices'
export interface DiscardDocument extends DiscardCandidate {
sources: DiscardCandidate[]
}
/** 下拉按来源单据和操作仓汇总;原始库存身份保留给选箱与提交。 */
export function groupDiscardDocuments(candidates: DiscardCandidate[]): DiscardDocument[] {
const groups = new Map<string, DiscardDocument>()
const identities = new Map<string, DiscardCandidate>()
for (const candidate of candidates) {
const available = Number(candidate.availablePackages)
if (candidate.availablePackages == null || !Number.isFinite(available) || available <= 0) continue
// 按真实来源身份去重;缺身份的旧接口行仍独立保留,不合并不同库存。
const identity = candidate.sourceType === 'RETURN_CARTON' ? candidate.returnCartonId : candidate.inventoryPositionId || candidate.orderId
const sourceKey = identity ? JSON.stringify([candidate.overseasWarehouseId, candidate.sourceType, identity]) : null
const existing = sourceKey ? identities.get(sourceKey) : undefined
if (existing) {
// 同一仓位的分片响应合并 SKU 和箱,重复关联不会丢掉箱内商品。
existing.skus = [...new Map([...existing.skus, ...candidate.skus].map(sku => [sku.skuCode, sku])).values()]
const cartons = new Map((existing.cartons || []).map(box => [box.cartonId, box]))
for (const box of candidate.cartons || []) {
const old = cartons.get(box.cartonId)
cartons.set(box.cartonId, old ? { ...old, skus: [...new Map([...old.skus, ...box.skus].map(sku => [sku.skuCode, sku])).values()] } : { ...box })
}
existing.cartons = [...cartons.values()]
existing.availablePackages = Math.max(Number(existing.availablePackages), available)
continue
}
const source = { ...candidate, skus: [...candidate.skus], cartons: candidate.cartons?.map(box => ({ ...box, skus: [...box.skus] })) }
if (sourceKey) identities.set(sourceKey, source)
const documentNo = candidate.inboundOrderNo || candidate.inboundCode
const key = JSON.stringify([candidate.overseasWarehouseId, candidate.sourceType, documentNo || candidate.orderId])
let document = groups.get(key)
if (!document) {
document = { ...candidate, orderId: key, sources: [], availablePackages: 0 }
groups.set(key, document)
}
document.sources.push(source)
}
for (const document of groups.values()) {
const boxes = new Set<string>()
let untrackedPackages = 0
for (const source of document.sources) {
if (source.sourceType === 'RETURN_CARTON' && source.returnCartonId) {
// 退货候选的 availablePackages 是箱内 SKU 件数,一条退货箱只计一箱。
boxes.add(`RETURN_CARTON:${source.returnCartonId}`)
} else if (source.cartonSelectionSupported && source.cartons?.length) {
for (const box of source.cartons) boxes.add(`${source.sourceType}:${box.cartonId}`)
} else {
// Long 序列化可能返回字符串,必须先转数值再汇总,避免拼成 005010097。
const packages = Number(source.availablePackages)
untrackedPackages += Number.isFinite(packages) && packages > 0 ? packages : 0
}
}
document.availablePackages = boxes.size + untrackedPackages
document.cartonSelectionSupported = document.sources.every(source => source.cartonSelectionSupported)
document.cartonSelectionBlockReason = document.sources.find(source => !source.cartonSelectionSupported)?.cartonSelectionBlockReason
}
return [...groups.values()]
}
@@ -20,6 +20,14 @@ test('签收箱号只包含箱子和托盘签收,包裹实物记录不重复
assert.deepEqual(exports.receiptBoxDetails(receipts.slice(0, 1), cartons), []) assert.deepEqual(exports.receiptBoxDetails(receipts.slice(0, 1), cartons), [])
}) })
test('零箱、未记录箱数和包裹不补造一箱,缺少箱数时可使用真实标签', () => {
assert.equal(exports.receiptPrintableBoxCount([{ unitType: 'BOX', boxCount: 0, labels: [] }]), 0)
assert.equal(exports.receiptPrintableBoxCount([{ unitType: 'PALLET', boxCount: null, labels: [] }]), 0)
assert.equal(exports.receiptPrintableBoxCount([{ unitType: 'PARCEL', boxCount: 1, labels: [{}] }]), 0)
assert.equal(exports.receiptPrintableBoxCount([{ unitType: 'PALLET', boxCount: null, labels: [{}, {}] }]), 2)
assert.equal(exports.receiptPrintableBoxCount([{ boxCount: -1 }, { boxCount: 'bad' }]), 0)
})
test('volume rounds upward to exactly three decimal places without increasing exact thousandths', () => { test('volume rounds upward to exactly three decimal places without increasing exact thousandths', () => {
for (const [input, expected] of [[0.186624, '0.187'], [0.15, '0.150'], [1.001, '1.001'], [1.00100001, '1.002'], [0.0000001, '0.001'], [0, '0.000'], [null, '—'], [NaN, '—']]) { for (const [input, expected] of [[0.186624, '0.187'], [0.15, '0.150'], [1.001, '1.001'], [1.00100001, '1.002'], [0.0000001, '0.001'], [0, '0.000'], [null, '—'], [NaN, '—']]) {
assert.equal(exports.formatReturnVolume(input), expected) assert.equal(exports.formatReturnVolume(input), expected)
@@ -39,6 +47,8 @@ test('箱子在签收箱号明细展示一次,真实托盘和缺少箱号明
test('parcel waybills appear as tracking numbers while generated parcel codes remain physical codes', () => { test('parcel waybills appear as tracking numbers while generated parcel codes remain physical codes', () => {
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'sf561626' }), 'sf561626') assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'sf561626' }), 'sf561626')
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK0123456789ABCDEF' }), '') assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK0123456789ABCDEF' }), '')
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK-FUW3Q9N0B8RL' }), '')
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK-FUW3Q9N0B8RL', trackingNo: ' SF123 ' }), 'SF123')
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK0123456789ABCDEF', trackingNo: ' SF123 ' }), 'SF123') assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK0123456789ABCDEF', trackingNo: ' SF123 ' }), 'SF123')
assert.equal(exports.receiptTrackingNo({ unitType: 'PALLET', unitCode: 'PLT123' }), '') assert.equal(exports.receiptTrackingNo({ unitType: 'PALLET', unitCode: 'PLT123' }), '')
}) })
@@ -1,7 +1,12 @@
import type { ReturnPallet, ReturnReceipt, ReturnReceiptCarton } from '../api/returnOrders' import type { ReturnPallet, ReturnReceipt, ReturnReceiptCarton } from '../api/returnOrders'
export function receiptPrintableBoxCount(receipts: ReturnReceipt[]) { export function receiptPrintableBoxCount(receipts: ReturnReceipt[]) {
return receipts.reduce((total, receipt) => total + Number(receipt.labels?.length || receipt.boxCount || 1), 0) // 只累计真实箱数;缺少箱数时使用已生成标签,不凭空补一箱。
return receipts.reduce((total, receipt) => {
if (receipt.unitType === 'PARCEL') return total
const count = Number(receipt.boxCount ?? receipt.labels?.length ?? 0)
return total + (Number.isSafeInteger(count) && count >= 0 ? count : 0)
}, 0)
} }
export function receiptPhysicalDetails(pallets: ReturnPallet[], boxes: ReturnReceiptCarton[]) { export function receiptPhysicalDetails(pallets: ReturnPallet[], boxes: ReturnReceiptCarton[]) {
@@ -18,7 +23,7 @@ export function receiptTrackingNo(receipt: Pick<ReturnReceipt, 'trackingNo' | 'u
const trackingNo = typeof receipt.trackingNo === 'string' ? receipt.trackingNo.trim() : '' const trackingNo = typeof receipt.trackingNo === 'string' ? receipt.trackingNo.trim() : ''
if (trackingNo) return trackingNo if (trackingNo) return trackingNo
const code = typeof receipt.unitCode === 'string' ? receipt.unitCode.trim() : '' const code = typeof receipt.unitCode === 'string' ? receipt.unitCode.trim() : ''
return receipt.unitType === 'PARCEL' && code && !/^PK[0-9A-F]{16}$/.test(code) ? code : '' return receipt.unitType === 'PARCEL' && code && !/^(?:PK[0-9A-F]{16}|PK-[0-9A-Z]+)$/.test(code) ? code : ''
} }
export function formatReturnVolume(value?: number | null) { export function formatReturnVolume(value?: number | null) {
@@ -0,0 +1,47 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
const source = readFileSync(new URL('./transferCartonPrinting.ts', import.meta.url), 'utf8')
const js = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
const exports = {}
new Function('exports', js)(exports)
const prepare = exports.prepareTransferCartonLabels
test('prints forecast counts independently of quantities or order fields and escapes cargo', () => {
const rows = [{ sku: 'A<script>', name: '货物 & 品名', expectedPackageCount: 12 }]
let next = 0
const html = prepare(rows, () => `BX-${++next}`)
assert.equal((html.match(/<section /g) || []).length, 12)
assert.match(html, /12 \/ 12/)
assert.match(html, /A&lt;script&gt;/)
assert.equal(rows[0].generatedCartonMarks.length, 12)
assert.equal(prepare(rows, () => { throw new Error('must retain labels') }), html)
})
test('adding boxes or rows keeps previously printed identities', () => {
const rows = [{ sku: 'A', name: '', expectedPackageCount: 2 }]
let next = 0
prepare(rows, () => `BX-${++next}`)
rows[0].expectedPackageCount = 3
rows.push({ sku: 'B', name: '', expectedPackageCount: 1 })
const html = prepare(rows, () => `BX-${++next}`)
assert.deepEqual(rows[0].generatedCartonMarks, ['BX-1', 'BX-2', 'BX-3'])
assert.match(html, /BX-4/)
})
test('invalid or excessive forecasts do not generate any labels', () => {
for (const count of [0, -1, 1.5, undefined, 5001]) {
const row = { sku: '', name: '', expectedPackageCount: count }
assert.throws(() => prepare([row]), /预计箱数/)
assert.equal(row.generatedCartonMarks, undefined)
}
})
test('print button cannot create, update or submit an order', () => {
const view = readFileSync(new URL('../views/WarehouseServiceView.vue', import.meta.url), 'utf8')
const handler = view.slice(view.indexOf('function printForecastCartons()'), view.indexOf('async function submit('))
assert.match(handler, /prepareTransferCartonLabels\(cargoRows.value\)/)
assert.doesNotMatch(handler, /createTransfer|updateTransfer|submitTransfer|getTransferCartonLabel|form\./)
assert.match(view, /cartonMarks: item.generatedCartonMarks/)
})
@@ -0,0 +1,28 @@
export interface PrintableCargoRow {
sku: string
name: string
expectedPackageCount?: number
generatedCartonMarks?: string[]
}
const escapeHtml = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]!)
/** Generate labels in memory only. The later order request carries these same identities. */
export function prepareTransferCartonLabels(rows: PrintableCargoRow[], newMark: () => string = () => {
// 采用短箱码,业务前缀保留 BX,SKU/品名等业务信息继续单独打印,避免把业务字段拼进唯一箱码。
const bytes = crypto.getRandomValues(new Uint8Array(6))
return `BX-${Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('').toUpperCase()}`
}) {
const total = rows.reduce((sum, row) => sum + Number(row.expectedPackageCount || 0), 0)
if (!rows.length || rows.some(row => !Number.isSafeInteger(row.expectedPackageCount) || Number(row.expectedPackageCount) < 1) || total > 5000) {
throw new Error('请填写货物的预计箱数(正整数),单次最多打印 5000 箱')
}
let index = 0
const labels = rows.flatMap(row => {
const count = Number(row.expectedPackageCount)
const marks = row.generatedCartonMarks ||= []
while (marks.length < count) marks.push(newMark())
return marks.slice(0, count).map(mark => `<section class="label"><div class="title">仓储转运箱唛</div><div class="mark">${escapeHtml(mark)}</div><div>${++index} / ${total}</div><div>SKU:${escapeHtml(row.sku)}</div><div>${escapeHtml(row.name)}</div></section>`)
})
return `<!doctype html><html><head><meta charset="utf-8"><title>仓储转运箱唛</title><style>@page{size:100mm 100mm;margin:0}body{margin:0;font-family:Arial,sans-serif}.label{box-sizing:border-box;width:100mm;height:100mm;padding:10mm;break-after:page;display:flex;flex-direction:column;justify-content:center;gap:6mm;text-align:center;overflow-wrap:anywhere}.label:last-child{break-after:auto}.title{font-size:22px;font-weight:bold}.mark{font-size:23px;font-weight:bold}</style></head><body>${labels.join('')}</body></html>`
}
@@ -285,11 +285,11 @@ onMounted(() => { if (props.detailPage) void Promise.all([loadCartonDetail(), lo
<template #time="{ row }"><span class="inventory-time">{{ formatInventoryTime(row.updatedAt || row.createdAt || row.receivedAt) }}</span></template> <template #time="{ row }"><span class="inventory-time">{{ formatInventoryTime(row.updatedAt || row.createdAt || row.receivedAt) }}</span></template>
</DataTable> </DataTable>
</div> </div>
<el-dialog v-model="showPackingCreate" title="创建合箱计划" width="720px" destroy-on-close><el-form label-width="110px"><el-form-item label="已完成退货单"><el-input v-model="packingForm.returnNos" type="textarea" :rows="2" placeholder="输入退货单号,多个用空格或逗号分隔" /></el-form-item><el-form-item label="合箱 SKU"><div class="packing-sku-grid"><div v-for="item in summaryRows" :key="item.skuCode" class="packing-sku-row"><el-checkbox :model-value="packingForm.selectedSkus[item.skuCode] !== undefined" @change="togglePackingSku(item.skuCode, Boolean($event))">{{ item.skuCode }}</el-checkbox><span>可用 {{ item.availableQuantity }}</span><el-input-number v-if="packingForm.selectedSkus[item.skuCode] !== undefined" v-model="packingForm.selectedSkus[item.skuCode]" :min="1" :max="item.availableQuantity" :controls="false" placeholder="数量" /></div></div></el-form-item><el-form-item label="箱规"><div class="packing-dimensions"><el-input-number v-model="packingForm.length" :min="1" placeholder="长 cm" /><el-input-number v-model="packingForm.width" :min="1" placeholder="宽 cm" /><el-input-number v-model="packingForm.height" :min="1" placeholder="高 cm" /><el-input-number v-model="packingForm.weight" :min="1" placeholder="重量 kg" /></div></el-form-item><el-form-item label="备注"><el-input v-model="packingForm.remark" placeholder="可填写合箱说明" /></el-form-item></el-form><template #footer><el-button @click="showPackingCreate = false">取消</el-button><el-button type="primary" :loading="packingSaving" @click="submitPackingPlan">提交审核</el-button></template></el-dialog> <el-dialog v-model="showPackingCreate" title="创建合箱计划" width="720px" destroy-on-close><el-form label-width="110px"><el-form-item label="已完成退货单"><el-input v-model="packingForm.returnNos" type="textarea" :rows="2" placeholder="输入退货单号,多个用空格或逗号分隔" /></el-form-item><el-form-item label="合箱 SKU"><div class="packing-sku-grid"><div v-for="item in summaryRows" :key="item.skuCode" class="packing-sku-row"><el-checkbox :model-value="packingForm.selectedSkus[item.skuCode] !== undefined" @change="togglePackingSku(item.skuCode, Boolean($event))">{{ item.skuCode }}</el-checkbox><span>可用 {{ item.availableQuantity }}</span><el-input-number v-if="packingForm.selectedSkus[item.skuCode] !== undefined" v-model="packingForm.selectedSkus[item.skuCode]" :min="1" :max="item.availableQuantity" :controls="false" placeholder="数量" /></div></div></el-form-item><el-form-item label="箱规"><div class="packing-dimensions"><el-input-number v-model="packingForm.length" :min="1" placeholder="长 cm" /><el-input-number v-model="packingForm.width" :min="1" placeholder="宽 cm" /><el-input-number v-model="packingForm.height" :min="1" placeholder="高 cm" /><el-input-number v-model="packingForm.weight" :min="1" placeholder="重量 kg" /></div></el-form-item><el-form-item label="备注"><el-input v-model="packingForm.remark" placeholder="" /></el-form-item></el-form><template #footer><el-button @click="showPackingCreate = false">取消</el-button><el-button type="primary" :loading="packingSaving" @click="submitPackingPlan">提交审核</el-button></template></el-dialog>
</template> </template>
<article v-else v-loading="loading" class="carton-detail-surface"> <article v-else v-loading="loading" class="carton-detail-surface">
<template v-if="cartonDetail"> <template v-if="cartonDetail">
<header class="carton-detail-header"><button type="button" class="carton-detail-back" @click="returnToCartons"><ArrowLeft :size="16" />返回列表</button><div><strong>{{ cartonDetail.cartonMark }}</strong><span>{{ warehouseLabel(cartonDetail.overseasWarehouseId) }} · 退货箱明细</span></div><div class="carton-detail-actions"><el-tag effect="light">{{ cartonStatusLabel(cartonDetail.status) }}</el-tag><el-button type="primary" @click="printLabel(cartonDetail.cartonMark)"><Printer :size="16" />打印箱唛</el-button></div></header> <header class="carton-detail-header"><button type="button" class="carton-detail-back" @click="returnToCartons"><ArrowLeft :size="16" />返回列表</button><div><strong>{{ cartonDetail.cartonMark }}</strong><span>{{ warehouseLabel(cartonDetail.overseasWarehouseId) }}</span></div><div class="carton-detail-actions"><el-tag effect="light">{{ cartonStatusLabel(cartonDetail.status) }}</el-tag><el-button type="primary" @click="printLabel(cartonDetail.cartonMark)"><Printer :size="16" />打印箱唛</el-button></div></header>
<section class="carton-detail-section"><h3>箱号概览</h3><dl class="carton-detail-grid"><div><dt>来源退货单</dt><dd>{{ cartonDetail.sourceReturnNo || '—' }}</dd></div><div><dt>签收批次</dt><dd>{{ cartonDetail.sourceBatchNo || '—' }}</dd></div><div><dt>SKU 种类</dt><dd>{{ cartonDetail.skuTypes }}</dd></div><div><dt>箱内总件数</dt><dd>{{ cartonDetail.totalQuantity }}</dd></div><div><dt>箱规</dt><dd>{{ cartonDetail.length && cartonDetail.width && cartonDetail.height ? `${cartonDetail.length} × ${cartonDetail.width} × ${cartonDetail.height} cm` : '—' }}</dd></div><div><dt>重量</dt><dd>{{ cartonDetail.weight ? `${cartonDetail.weight} kg` : '—' }}</dd></div><div><dt>换标进度</dt><dd>{{ returnRelabelStatusLabel(cartonDetail.relabelStatus) }}</dd></div><div><dt>实际完成(件)</dt><dd>{{ cartonDetail.relabelledQuantity ?? '—' }}</dd></div><div><dt>处理中占用(件)</dt><dd>{{ cartonDetail.relabelReservedQuantity ?? '—' }}</dd></div><div><dt>签收时间</dt><dd>{{ formatInventoryTime(cartonDetail.receivedAt) }}</dd></div></dl></section> <section class="carton-detail-section"><h3>箱号概览</h3><dl class="carton-detail-grid"><div><dt>来源退货单</dt><dd>{{ cartonDetail.sourceReturnNo || '—' }}</dd></div><div><dt>签收批次</dt><dd>{{ cartonDetail.sourceBatchNo || '—' }}</dd></div><div><dt>SKU 种类</dt><dd>{{ cartonDetail.skuTypes }}</dd></div><div><dt>箱内总件数</dt><dd>{{ cartonDetail.totalQuantity }}</dd></div><div><dt>箱规</dt><dd>{{ cartonDetail.length && cartonDetail.width && cartonDetail.height ? `${cartonDetail.length} × ${cartonDetail.width} × ${cartonDetail.height} cm` : '—' }}</dd></div><div><dt>重量</dt><dd>{{ cartonDetail.weight ? `${cartonDetail.weight} kg` : '—' }}</dd></div><div><dt>换标进度</dt><dd>{{ returnRelabelStatusLabel(cartonDetail.relabelStatus) }}</dd></div><div><dt>实际完成(件)</dt><dd>{{ cartonDetail.relabelledQuantity ?? '—' }}</dd></div><div><dt>处理中占用(件)</dt><dd>{{ cartonDetail.relabelReservedQuantity ?? '—' }}</dd></div><div><dt>签收时间</dt><dd>{{ formatInventoryTime(cartonDetail.receivedAt) }}</dd></div></dl></section>
<section class="carton-detail-section"><h3>箱内 SKU</h3><DataTable :data="cartonDetail.items" :columns="cartonItemColumns" row-key="skuCode" empty-text="暂无箱内 SKU" /></section> <section class="carton-detail-section"><h3>箱内 SKU</h3><DataTable :data="cartonDetail.items" :columns="cartonItemColumns" row-key="skuCode" empty-text="暂无箱内 SKU" /></section>
<section class="carton-detail-section"><h3>SKU 换标明细</h3><DataTable :data="cartonDetail.skuConversions" :columns="conversionColumns" empty-text="暂无 SKU 换标记录"><template #conversionStatus="{ row }">{{ conversionStatusLabel(row.status) }}</template></DataTable></section> <section class="carton-detail-section"><h3>SKU 换标明细</h3><DataTable :data="cartonDetail.skuConversions" :columns="conversionColumns" empty-text="暂无 SKU 换标记录"><template #conversionStatus="{ row }">{{ conversionStatusLabel(row.status) }}</template></DataTable></section>
@@ -1,10 +1,51 @@
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 { createRequire } from 'node:module'
const view = readFileSync(new URL('./ReturnOrdersView.vue', import.meta.url), 'utf8') const view = readFileSync(new URL('./ReturnOrdersView.vue', import.meta.url), 'utf8')
const api = readFileSync(new URL('../api/returnOrders.ts', import.meta.url), 'utf8') const api = readFileSync(new URL('../api/returnOrders.ts', import.meta.url), 'utf8')
function listHarness(list, summary) {
const state = { query: { page: 1, size: 1, skuCode: 'FILTER' }, loading: { value: false }, listError: { value: '' }, rows: { value: [] }, total: { value: 0 } }
const source = view.slice(view.indexOf('async function load()'), view.indexOf('\nfunction changePage('))
const js = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const load = new Function(...Object.keys(state), 'listReturnOrders', 'getReturnOrderStatistics', `let listRequest=0; ${js}; return load`)(...Object.values(state), list, summary)
return { ...state, load }
}
test('分页行按服务器单号映射载体,不展示全筛选汇总', async () => {
const calls = []
const totals = { orderCount: 3, skuTypes: 3, expectedQuantity: 19, receivedQuantity: 14, remainingQuantity: 5 }
const h = listHarness(async p => { calls.push(p); return { total: '3', records: [{ returnNo: 'RT-1', receivedQuantity: 8 }] } }, async p => { calls.push(p); return { totals, pageDimensions: [{ returnNo: 'RT-1', receivedParcelCount: 1, receivedBoxCount: 1 }] } })
await h.load()
assert.equal(h.total.value, 3)
assert.doesNotMatch(view, /return-filter-summary|预报箱\/包裹\/托数/)
assert.equal(h.rows.value[0].receivedParcelCount, 1)
h.query.page = 2
await h.load()
assert.equal(h.rows.value[0].receivedBoxCount, 1)
assert.deepEqual(calls[2], calls[3])
assert.equal(calls[3].page, 2)
})
test('维度查询失败清空旧列表,并忽略较旧查询的迟到结果', async () => {
let fail = false, finish
const h = listHarness(async () => ({ total: 1, records: [{ returnNo: 'RT-1' }] }), async p => {
if (fail) throw Error('统计服务不可用')
if (p.page === 1) return new Promise(resolve => { finish = resolve })
return { totals: { orderCount: 2 }, pageDimensions: [{ returnNo: 'RT-1', receivedBoxCount: 2 }] }
})
const old = h.load(); h.query.page = 2; await h.load()
finish({ totals: { orderCount: 999 }, pageDimensions: [] }); await old
assert.equal(h.rows.value[0].receivedBoxCount, 2)
fail = true; await h.load()
assert.deepEqual(h.rows.value, [])
assert.equal(h.listError.value, '统计服务不可用')
assert.equal(h.loading.value, false)
})
function submitHarness(failure) { function submitHarness(failure) {
const source = view.slice(view.indexOf('async function submit()'), view.indexOf('\nfunction statusType(')) const source = view.slice(view.indexOf('async function submit()'), view.indexOf('\nfunction statusType('))
const state = { requests: [], loads: 0, routes: [], errors: [], successes: [] } const state = { requests: [], loads: 0, routes: [], errors: [], successes: [] }
@@ -61,7 +102,6 @@ test('新建退货预报选择海外仓后带出联系人和电话', () => {
assert.match(view, /label="海外仓联系电话"/) assert.match(view, /label="海外仓联系电话"/)
assert.match(view, /:readonly="Boolean\(selectedOperationWarehouse\?\.contactName\)"/) assert.match(view, /:readonly="Boolean\(selectedOperationWarehouse\?\.contactName\)"/)
assert.match(view, /:readonly="Boolean\(selectedOperationWarehouse\?\.contactPhone\)"/) assert.match(view, /:readonly="Boolean\(selectedOperationWarehouse\?\.contactPhone\)"/)
assert.match(view, /该海外仓未维护,请手动填写/)
assert.match(view, /warehouseContactName: form\.warehouseContactName\.trim\(\)/) assert.match(view, /warehouseContactName: form\.warehouseContactName\.trim\(\)/)
assert.match(view, /warehouseContactPhone: form\.warehouseContactPhone\.trim\(\)/) assert.match(view, /warehouseContactPhone: form\.warehouseContactPhone\.trim\(\)/)
}) })
@@ -77,11 +117,10 @@ test('新建退货预报使用独立路由页面,编辑仍保留加宽弹框',
assert.match(view, /class="return-create-actions"[\s\S]*?<el-button type="primary" :loading="creating" @click="submit">提交预报<\/el-button>/) assert.match(view, /class="return-create-actions"[\s\S]*?<el-button type="primary" :loading="creating" @click="submit">提交预报<\/el-button>/)
}) })
test('新建预报居左限宽,联系字段与数量输入保持紧凑', () => { test('新建预报铺满工作区,基础字段等宽对齐且数量输入保持紧凑', () => {
assert.match(view, /return-create-surface \{ width:calc\(100% - 24px\);[^}]*max-width:1120px;[^}]*margin:0 0 0 24px; justify-self:start;/) assert.match(view, /return-create-surface \{ width:100%; min-width:0;[^}]*margin:0;/)
assert.match(view, /<el-form label-width="130px" class="return-create-form">/) assert.match(view, /<el-form ref="createFormRef"[^>]*:model="form"[^>]*:rules="createFormRules"[^>]*label-position="top"/)
assert.match(view, /return-create-form :deep\(\.el-input\) \{ max-width:320px;/) assert.match(view, /return-create-form :deep\(\.el-input\), \.return-create-body \.return-create-form :deep\(\.el-select\) \{ width:100%; max-width:none;/)
assert.match(view, /return-create-form :deep\(\.el-select\) \{ max-width:520px;/)
assert.match(view, /:deep\(\.el-table \.el-input-number\) \{ width:120px;/) assert.match(view, /:deep\(\.el-table \.el-input-number\) \{ width:120px;/)
assert.match(view, /<el-table class="return-forecast-table"[^>]*>/) assert.match(view, /<el-table class="return-forecast-table"[^>]*>/)
assert.match(view, /return-forecast-table \{[^}]*border-radius:8px;/) assert.match(view, /return-forecast-table \{[^}]*border-radius:8px;/)
@@ -254,7 +293,59 @@ test('待审核退货可编辑,完成入库后从独立新增页发起贴标',
assert.match(view, /name: 'overseas-labeling-create'/) assert.match(view, /name: 'overseas-labeling-create'/)
assert.match(view, /query: \{ returnNo: order\.returnNo, warehouseId: String\(order\.overseasWarehouseId\)/) assert.match(view, /query: \{ returnNo: order\.returnNo, warehouseId: String\(order\.overseasWarehouseId\)/)
assert.match(view, /cartonMark \? \{ cartonMark \}/) assert.match(view, /cartonMark \? \{ cartonMark \}/)
assert.match(view, /openRelabel\(selected\.order, current\.carton\.cartonMark\)/) assert.match(view, /v-if="canCreateRelabel && canApplyRelabel\(selected\.order\)"[^>]*@click="openRelabel\(selected\.order\)">贴标申请/)
assert.match(view, /v-for="application in row\.relabelApplications \|\| \[\]"/) assert.match(view, /v-for="application in row\.relabelApplications \|\| \[\]"/)
assert.match(view, /relabelStatusLabel\(application\.status\)/) assert.match(view, /relabelStatusLabel\(application\.status\)/)
}) })
test('贴标入口保留完成入库门禁与退货来源,箱号只作为目标页库存筛选', () => {
const source = view.slice(view.indexOf('function canApplyRelabel('), view.indexOf('async function submit()'))
const javascript = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const routes = []
const { canApplyRelabel, openRelabel } = new Function('router', `${javascript}; return { canApplyRelabel, openRelabel }`)({ push: route => routes.push(route) })
const order = { returnNo: 'RT-TEST', overseasWarehouseId: 'WH-TEST', status: 'COMPLETED', needRelabel: true }
assert.equal(canApplyRelabel(order), true)
assert.equal(canApplyRelabel({ ...order, status: 'PENDING_RECEIPT' }), false)
assert.equal(canApplyRelabel({ ...order, needRelabel: false }), false)
assert.equal(canApplyRelabel({ ...order, relabelNo: 'RL-EXISTS' }), false)
openRelabel(order)
openRelabel(order, 'RC-TEST')
assert.deepEqual(routes, [
{ name: 'overseas-labeling-create', query: { returnNo: 'RT-TEST', warehouseId: 'WH-TEST' } },
{ name: 'overseas-labeling-create', query: { returnNo: 'RT-TEST', warehouseId: 'WH-TEST', cartonMark: 'RC-TEST' } },
])
})
test('新增退货校验海外仓与联系人,空白联系人无效,客户参考号可选', async () => {
const { default: Schema } = createRequire(import.meta.resolve('element-plus'))('async-validator')
const source = view.slice(view.indexOf('const createFormRules:'), view.indexOf('const selectedOperationWarehouse ='))
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const rules = new Function(code + '\nreturn createFormRules')()
const validator = new Schema(rules)
await assert.rejects(validator.validate({ overseasWarehouseId: '', warehouseContactName: ' ', warehouseContactPhone: '' }), error => {
assert.deepEqual(Object.keys(error.fields).sort(), ['overseasWarehouseId', 'warehouseContactName', 'warehouseContactPhone'])
return true
})
await validator.validate({ overseasWarehouseId: 'WH', warehouseContactName: 'Contact', warehouseContactPhone: '123456', customerReferenceNo: '' })
})
test('新增校验失败或正在提交时不继续创建,编辑保持既有校验路径', async () => {
const start = view.indexOf('async function submit()')
const end = view.indexOf(' const items =', start)
const code = view.slice(start, end) + '\nreturn "continue"\n}'
const creating = { value: false }, props = { createPage: true }
let validations = 0
const formRef = { value: { validate: async () => { validations++; throw new Error('required') } } }
const submit = new Function('creating', 'props', 'createFormRef', code + '\nreturn submit')(creating, props, formRef)
assert.equal(await submit(), undefined)
assert.equal(validations, 1)
creating.value = true
assert.equal(await submit(), undefined)
assert.equal(validations, 1)
creating.value = false
props.createPage = false
assert.equal(await submit(), 'continue')
props.createPage = true
formRef.value.validate = async () => true
assert.equal(await submit(), 'continue')
})
@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue' import { computed, onActivated, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft, ChevronDown, Plus } from '@lucide/vue' import { ArrowLeft, ChevronDown, Plus } from '@lucide/vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue' import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
@@ -10,6 +10,8 @@ import { useAuthStore } from '@/modules/auth/public'
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public' import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public'
import { createIdempotencyKey } from '@/utils/idempotencyKey' import { createIdempotencyKey } from '@/utils/idempotencyKey'
import { createReturnOrder, downloadReturnPhoto, getReturnOrder, listReturnOrders, updateReturnOrder, type ReturnOrderDetail, type ReturnOrderSummary, type ReturnReceipt } from '../api/returnOrders' import { createReturnOrder, downloadReturnPhoto, getReturnOrder, listReturnOrders, updateReturnOrder, type ReturnOrderDetail, type ReturnOrderSummary, type ReturnReceipt } from '../api/returnOrders'
import ReviewRejectionNotice from '../components/ReviewRejectionNotice.vue'
import { getReturnOrderStatistics } from '../api/returnOrders'
import { getReturnInventoryLabel } from '../api/returnInventory' import { getReturnInventoryLabel } from '../api/returnInventory'
import { formatReturnVolume, receiptBoxDetails, receiptPhysicalDetails, receiptPrintableBoxCount, receiptTrackingNo } from '../utils/returnReceiptDisplay' import { formatReturnVolume, receiptBoxDetails, receiptPhysicalDetails, receiptPrintableBoxCount, receiptTrackingNo } from '../utils/returnReceiptDisplay'
@@ -39,6 +41,8 @@ const printableBoxCount = computed(() => receiptPrintableBoxCount(printableRecei
const photoUrls = reactive<Record<string, string>>({}) const photoUrls = reactive<Record<string, string>>({})
const rows = ref<ReturnOrderSummary[]>([]) const rows = ref<ReturnOrderSummary[]>([])
const total = ref(0) const total = ref(0)
const listError = ref('')
let listRequest = 0
const operationWarehouses = ref<MerchantWarehouse[]>([]) const operationWarehouses = ref<MerchantWarehouse[]>([])
const operationWarehousesLoading = ref(false) const operationWarehousesLoading = ref(false)
const operationWarehousesError = ref('') const operationWarehousesError = ref('')
@@ -61,8 +65,13 @@ const tableColumns: DataTableColumn[] = [
{ key: 'actions', label: '操作', slotName: 'actions', width: 220, fixed: 'left' }, { key: 'actions', label: '操作', slotName: 'actions', width: 220, fixed: 'left' },
{ prop: 'returnNo', label: '退货单号', minWidth: 190 }, { prop: 'customerReferenceNo', label: '客户参考号', minWidth: 160 }, { prop: 'returnNo', label: '退货单号', minWidth: 190 }, { prop: 'customerReferenceNo', label: '客户参考号', minWidth: 160 },
{ key: 'warehouse', label: '操作仓', slotName: 'warehouse', minWidth: 200 }, { key: 'relabel', label: '换标', slotName: 'relabel', width: 100 }, { key: 'warehouse', label: '操作仓', slotName: 'warehouse', minWidth: 200 }, { key: 'relabel', label: '换标', slotName: 'relabel', width: 100 },
{ prop: 'skuTypes', label: 'SKU 种类', width: 105 }, { prop: 'expectedQuantity', label: '预报数量', width: 110 }, { prop: 'skuTypes', label: 'SKU 种类', width: 105 }, { prop: 'expectedQuantity', label: '预报(件)', width: 110 },
{ prop: 'receivedQuantity', label: '实收数量', width: 110 }, { key: 'status', label: '状态', slotName: 'status', width: 150 }, { prop: 'receivedQuantity', label: '实收(件)', width: 110 },
{ prop: 'remainingQuantity', label: '待收(件)', width: 110 },
{ prop: 'receivedBoxCount', label: '签收箱数', width: 110 },
{ prop: 'receivedParcelCount', label: '签收包裹数', width: 115 },
{ prop: 'receivedPalletCount', label: '签收托数', width: 110 },
{ key: 'status', label: '状态', slotName: 'status', width: 150 },
{ key: 'relabelApplications', label: '换标子单', slotName: 'relabelApplications', minWidth: 340 }, { key: 'relabelApplications', label: '换标子单', slotName: 'relabelApplications', minWidth: 340 },
{ key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 180 }, { key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 180 },
] ]
@@ -88,6 +97,12 @@ interface SkuDraft { id: number; skuCode: string; productNameZh: string; expecte
let skuSequence = 0 let skuSequence = 0
function emptySku(): SkuDraft { return { id: ++skuSequence, skuCode: '', productNameZh: '', expectedQuantity: 1 } } function emptySku(): SkuDraft { return { id: ++skuSequence, skuCode: '', productNameZh: '', expectedQuantity: 1 } }
const form = reactive({ overseasWarehouseId: '', warehouseContactName: '', warehouseContactPhone: '', customerReferenceNo: '', remark: '', needRelabel: false, items: [emptySku()] }) const form = reactive({ overseasWarehouseId: '', warehouseContactName: '', warehouseContactPhone: '', customerReferenceNo: '', remark: '', needRelabel: false, items: [emptySku()] })
const createFormRef = ref<FormInstance>()
const createFormRules: FormRules = {
overseasWarehouseId: [{ required: true, message: '请选择海外仓', trigger: 'change' }],
warehouseContactName: [{ required: true, whitespace: true, message: '请输入联系人', trigger: 'blur' }],
warehouseContactPhone: [{ required: true, whitespace: true, message: '请输入联系电话', trigger: 'blur' }],
}
const selectedOperationWarehouse = computed(() => operationWarehouses.value.find(item => String(item.id) === form.overseasWarehouseId)) const selectedOperationWarehouse = computed(() => operationWarehouses.value.find(item => String(item.id) === form.overseasWarehouseId))
function normalizedSku(value: string) { return value.trim().toUpperCase() } function normalizedSku(value: string) { return value.trim().toUpperCase() }
const duplicateSkuIds = computed(() => { const duplicateSkuIds = computed(() => {
@@ -98,7 +113,7 @@ const duplicateSkuIds = computed(() => {
} }
return new Set([...grouped.values()].filter(ids => ids.length > 1).flat()) return new Set([...grouped.values()].filter(ids => ids.length > 1).flat())
}) })
function resetForm() { Object.assign(form, { overseasWarehouseId: '', warehouseContactName: '', warehouseContactPhone: '', customerReferenceNo: '', remark: '', needRelabel: false, items: [emptySku()] }) } function resetForm() { createFormRef.value?.clearValidate(); Object.assign(form, { overseasWarehouseId: '', warehouseContactName: '', warehouseContactPhone: '', customerReferenceNo: '', remark: '', needRelabel: false, items: [emptySku()] }) }
function warehouseLabel(warehouse: MerchantWarehouse) { return `${warehouse.warehouseName} · ${warehouse.warehouseCode}` } function warehouseLabel(warehouse: MerchantWarehouse) { return `${warehouse.warehouseName} · ${warehouse.warehouseCode}` }
function operationWarehouseLabel(warehouseId: string) { function operationWarehouseLabel(warehouseId: string) {
const warehouse = operationWarehouses.value.find(item => String(item.id) === String(warehouseId)) const warehouse = operationWarehouses.value.find(item => String(item.id) === String(warehouseId))
@@ -108,6 +123,7 @@ function selectOperationWarehouse() {
const warehouse = operationWarehouses.value.find(item => String(item.id) === form.overseasWarehouseId) const warehouse = operationWarehouses.value.find(item => String(item.id) === form.overseasWarehouseId)
form.warehouseContactName = warehouse?.contactName || '' form.warehouseContactName = warehouse?.contactName || ''
form.warehouseContactPhone = warehouse?.contactPhone || '' form.warehouseContactPhone = warehouse?.contactPhone || ''
if (props.createPage) createFormRef.value?.clearValidate(['warehouseContactName', 'warehouseContactPhone'])
} }
async function loadOperationWarehouses() { async function loadOperationWarehouses() {
operationWarehousesLoading.value = true operationWarehousesLoading.value = true
@@ -146,9 +162,21 @@ async function openEdit(returnNo: string) {
function addItem() { form.items.push(emptySku()) } function addItem() { form.items.push(emptySku()) }
function removeItem(index: number) { if (form.items.length > 1) form.items.splice(index, 1) } function removeItem(index: number) { if (form.items.length > 1) form.items.splice(index, 1) }
async function load() { async function load() {
const request = ++listRequest
loading.value = true loading.value = true
try { const response = await listReturnOrders({ ...query, returnNo: query.returnNo || undefined, trackingNo: query.trackingNo || undefined, skuCode: query.skuCode || undefined, status: query.status || undefined }); rows.value = response.records; total.value = Number(response.total); if (!Number.isFinite(total.value)) total.value = response.records.length } listError.value = ''
finally { loading.value = false } try {
const params = { ...query, returnNo: query.returnNo || undefined, trackingNo: query.trackingNo || undefined, skuCode: query.skuCode || undefined, status: query.status || undefined }
const [response, summary] = await Promise.all([listReturnOrders(params), getReturnOrderStatistics(params)])
if (request !== listRequest) return
const dimensions = new Map(summary.pageDimensions.map(row => [row.returnNo, row]))
rows.value = response.records.map(row => ({ ...row, ...dimensions.get(row.returnNo) }))
total.value = Number(response.total)
} catch (error) {
if (request !== listRequest) return
rows.value = []; total.value = 0
listError.value = error instanceof Error ? error.message : '退货列表加载失败'
} finally { if (request === listRequest) loading.value = false }
} }
function changePage(page: number) { function changePage(page: number) {
if (page === query.page) return if (page === query.page) return
@@ -230,6 +258,8 @@ function openRelabel(order: Pick<ReturnOrderSummary, 'returnNo' | 'overseasWareh
void router.push({ name: 'overseas-labeling-create', query: { returnNo: order.returnNo, warehouseId: String(order.overseasWarehouseId), ...(cartonMark ? { cartonMark } : {}) } }) void router.push({ name: 'overseas-labeling-create', query: { returnNo: order.returnNo, warehouseId: String(order.overseasWarehouseId), ...(cartonMark ? { cartonMark } : {}) } })
} }
async function submit() { async function submit() {
if (creating.value) return
if (props.createPage && !await createFormRef.value?.validate().catch(() => false)) return
const items = form.items.map(({ skuCode, productNameZh, expectedQuantity }) => ({ skuCode: skuCode.trim(), productNameZh: productNameZh.trim(), expectedQuantity })) const items = form.items.map(({ skuCode, productNameZh, expectedQuantity }) => ({ skuCode: skuCode.trim(), productNameZh: productNameZh.trim(), expectedQuantity }))
if (!form.overseasWarehouseId || items.some(item => !item.skuCode || item.expectedQuantity <= 0)) { ElMessage.warning('请填写操作仓、SKU 和预报数量'); return } if (!form.overseasWarehouseId || items.some(item => !item.skuCode || item.expectedQuantity <= 0)) { ElMessage.warning('请填写操作仓、SKU 和预报数量'); return }
if (!form.warehouseContactName.trim() || !form.warehouseContactPhone.trim()) { ElMessage.warning('请填写海外仓联系人和联系电话'); return } if (!form.warehouseContactName.trim() || !form.warehouseContactPhone.trim()) { ElMessage.warning('请填写海外仓联系人和联系电话'); return }
@@ -280,6 +310,11 @@ onMounted(() => {
else if (props.detailPage) void Promise.all([loadDetail(), loadOperationWarehouses()]) else if (props.detailPage) void Promise.all([loadDetail(), loadOperationWarehouses()])
else void Promise.all([load(), loadOperationWarehouses()]) else void Promise.all([load(), loadOperationWarehouses()])
}) })
let activatedOnce = false
onActivated(() => {
if (activatedOnce && !props.createPage && !props.detailPage) void load()
activatedOnce = true
})
watch(() => [query.page, query.size] as const, ([nextPage, nextSize], [previousPage, previousSize]) => { watch(() => [query.page, query.size] as const, ([nextPage, nextSize], [previousPage, previousSize]) => {
if (nextSize !== previousSize && nextPage !== 1) { query.page = 1; return } if (nextSize !== previousSize && nextPage !== 1) { query.page = 1; return }
if (!props.createPage && !props.detailPage) void load() if (!props.createPage && !props.detailPage) void load()
@@ -288,37 +323,44 @@ onBeforeUnmount(clearPhotoUrls)
</script> </script>
<template> <template>
<section class="return-orders-page"> <section class="return-orders-page" :class="{ 'return-orders-create client-ui': props.createPage }">
<template v-if="props.createPage"> <template v-if="props.createPage">
<article class="return-create-surface"> <article class="return-create-surface">
<header class="return-create-header"> <header class="return-create-header">
<div><h2>新建退货预报</h2><p>填写预计退回的 SKU 和数量,仓库签收后将自动更新实收结果。</p></div> <div><h2>新建退货预报</h2></div>
<el-button @click="returnToList"><ArrowLeft :size="16" />返回列表</el-button> <el-button @click="returnToList"><ArrowLeft :size="16" />返回列表</el-button>
</header> </header>
<div class="return-create-body"> <el-form ref="createFormRef" class="return-create-body" :model="form" :rules="createFormRules" label-position="top" :disabled="creating" scroll-to-error @submit.prevent="submit">
<el-form label-width="130px" class="return-create-form"> <section class="return-create-section">
<el-form-item label="海外仓" required><el-select v-model="form.overseasWarehouseId" filterable clearable :loading="operationWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" @change="selectOperationWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><div v-if="operationWarehousesError" class="warehouse-error">{{ operationWarehousesError }}</div></el-form-item> <h3>基础信息</h3>
<el-form-item label="客户参考号"><el-input v-model="form.customerReferenceNo" placeholder="可填写客户侧参考号" /></el-form-item> <div class="return-create-form">
<el-form-item label="海外仓联系人" required><el-input v-model="form.warehouseContactName" :readonly="Boolean(selectedOperationWarehouse?.contactName)" :placeholder="selectedOperationWarehouse?.contactName ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item> <el-form-item label="海外仓" prop="overseasWarehouseId"><el-select v-model="form.overseasWarehouseId" filterable clearable :loading="operationWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" popper-class="return-create-popper" @change="selectOperationWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><div v-if="operationWarehousesError" class="warehouse-error">{{ operationWarehousesError }}</div></el-form-item>
<el-form-item label="海外仓联系电话" required><el-input v-model="form.warehouseContactPhone" :readonly="Boolean(selectedOperationWarehouse?.contactPhone)" :placeholder="selectedOperationWarehouse?.contactPhone ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item> <el-form-item label="海外仓联系人" prop="warehouseContactName"><el-input v-model="form.warehouseContactName" :readonly="Boolean(selectedOperationWarehouse?.contactName)" placeholder="请输入海外仓联系人" /></el-form-item>
<el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" :rows="2" placeholder="填写退货说明(选填)" /></el-form-item> <el-form-item label="海外仓联系电话" prop="warehouseContactPhone"><el-input v-model="form.warehouseContactPhone" type="tel" :readonly="Boolean(selectedOperationWarehouse?.contactPhone)" placeholder="请输入海外仓联系电话" /></el-form-item>
</el-form> <el-form-item label="客户参考号"><el-input v-model="form.customerReferenceNo" placeholder="请输入客户参考号(选填)" /></el-form-item>
<div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div> <el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" :rows="3" resize="vertical" placeholder="请输入退货要求或其他补充信息(选填)" /></el-form-item>
<div class="return-relabel-option"><span>是否换标</span><el-radio-group v-model="form.needRelabel" aria-label="是否换标"><el-radio-button :value="false">不换标</el-radio-button><el-radio-button :value="true">需要换标</el-radio-button></el-radio-group></div> </div>
<div class="items-hint">客户只需填写预计退回的 SKU 和数量;快递单号由仓库签收时按实际包裹扫描绑定。</div> </section>
<el-table class="return-forecast-table" :data="form.items" row-key="id" size="small"> <section class="return-create-section">
<el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column> <div class="items-title"><h3>SKU 预报明细</h3><el-button type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div>
<el-table-column label="SKU" width="300"><template #default="{ row }"><div><el-input v-model="row.skuCode" :class="{ 'duplicate-sku-input': duplicateSkuIds.has(row.id) }" placeholder="填写 SKU" @blur="row.skuCode = row.skuCode.trim()" /><div v-if="duplicateSkuIds.has(row.id)" class="duplicate-sku-error">该 SKU 已在明细中填写</div></div></template></el-table-column> <div class="return-create-card">
<el-table-column label="中文品名" min-width="320"><template #default="{ row }"><el-input v-model="row.productNameZh" placeholder="填写中文品名(选填)" /></template></el-table-column> <div class="return-relabel-option"><span>是否换标</span><el-radio-group v-model="form.needRelabel" aria-label="是否换标"><el-radio-button :value="false">不换标</el-radio-button><el-radio-button :value="true">需要换标</el-radio-button></el-radio-group></div>
<el-table-column label="预报数量" width="150"><template #default="{ row }"><el-input-number v-model="row.expectedQuantity" :min="1" controls-position="right" placeholder="数量" /></template></el-table-column> <el-table class="return-forecast-table" :data="form.items" row-key="id" size="small">
</el-table> <el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column>
</div> <el-table-column label="SKU" width="300"><template #default="{ row }"><div><el-input v-model="row.skuCode" :class="{ 'duplicate-sku-input': duplicateSkuIds.has(row.id) }" placeholder="请输入 SKU" @blur="row.skuCode = row.skuCode.trim()" /><div v-if="duplicateSkuIds.has(row.id)" class="duplicate-sku-error">该 SKU 已在明细中填写</div></div></template></el-table-column>
<footer class="return-create-actions"><el-button @click="cancelCreate">取消</el-button><el-button type="primary" :loading="creating" @click="submit">提交预报</el-button></footer> <el-table-column label="中文品名" min-width="320"><template #default="{ row }"><el-input v-model="row.productNameZh" placeholder="请输入中文品名(选填)" /></template></el-table-column>
<el-table-column label="预报数量" width="150"><template #default="{ row }"><el-input-number v-model="row.expectedQuantity" :min="1" controls-position="right" placeholder="请输入数量" /></template></el-table-column>
</el-table>
</div>
</section>
</el-form>
<footer class="return-create-actions"><el-button :disabled="creating" @click="cancelCreate">返回列表</el-button><el-button type="primary" :loading="creating" @click="submit">提交预报</el-button></footer>
</article> </article>
</template> </template>
<template v-else-if="!props.detailPage"> <template v-else-if="!props.detailPage">
<QueryToolbar v-model="queryModel" class="return-query" layout="grid" ariaLabel="退货签收筛选" :fields="queryFields" @search="search" /> <QueryToolbar v-model="queryModel" class="return-query" layout="grid" ariaLabel="退货签收筛选" :fields="queryFields" @search="search" />
<el-alert v-if="listError" type="error" :closable="false" :title="listError"><el-button @click="load">重新加载</el-button></el-alert>
<div class="return-table-card"> <div class="return-table-card">
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[15, 30, 50, 100]" :row-actions="rowActions" row-key="returnNo" empty-text="暂无退货预报"> <DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[15, 30, 50, 100]" :row-actions="rowActions" row-key="returnNo" empty-text="暂无退货预报">
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新建退货预报</el-button></template> <template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新建退货预报</el-button></template>
@@ -332,20 +374,18 @@ onBeforeUnmount(clearPhotoUrls)
<el-dialog v-model="showCreate" :title="editingReturnNo ? '编辑退货预报' : '新建退货预报'" width="1120px" destroy-on-close> <el-dialog v-model="showCreate" :title="editingReturnNo ? '编辑退货预报' : '新建退货预报'" width="1120px" destroy-on-close>
<el-form label-width="190px" class="return-create-form"> <el-form label-width="190px" class="return-create-form">
<el-form-item label="海外仓" required class="return-form-wide"><el-select v-model="form.overseasWarehouseId" filterable clearable :loading="operationWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" @change="selectOperationWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><div v-if="operationWarehousesError" class="warehouse-error">{{ operationWarehousesError }}</div></el-form-item> <el-form-item label="海外仓" required class="return-form-wide"><el-select v-model="form.overseasWarehouseId" filterable clearable :loading="operationWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="" @change="selectOperationWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><div v-if="operationWarehousesError" class="warehouse-error">{{ operationWarehousesError }}</div></el-form-item>
<el-form-item label="海外仓联系人" required><el-input v-model="form.warehouseContactName" :readonly="Boolean(selectedOperationWarehouse?.contactName)" :placeholder="selectedOperationWarehouse?.contactName ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item> <el-form-item label="海外仓联系人" required><el-input v-model="form.warehouseContactName" :readonly="Boolean(selectedOperationWarehouse?.contactName)" placeholder="" /></el-form-item>
<el-form-item label="海外仓联系电话" required><el-input v-model="form.warehouseContactPhone" :readonly="Boolean(selectedOperationWarehouse?.contactPhone)" :placeholder="selectedOperationWarehouse?.contactPhone ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item> <el-form-item label="海外仓联系电话" required><el-input v-model="form.warehouseContactPhone" :readonly="Boolean(selectedOperationWarehouse?.contactPhone)" placeholder="" /></el-form-item>
<el-form-item label="客户参考号" class="return-form-wide"><el-input v-model="form.customerReferenceNo" placeholder="可填写客户侧参考号" /></el-form-item> <el-form-item label="客户参考号" class="return-form-wide"><el-input v-model="form.customerReferenceNo" placeholder="" /></el-form-item>
<el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" placeholder="填写退货说明(选填)" /></el-form-item> <el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" placeholder="" /></el-form-item>
</el-form> </el-form>
<div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div> <div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div>
<div class="return-relabel-option"><span>是否换标</span><el-radio-group v-model="form.needRelabel" aria-label="是否换标"><el-radio-button :value="false">不换标</el-radio-button><el-radio-button :value="true">需要换标</el-radio-button></el-radio-group></div> <div class="return-relabel-option"><span>是否换标</span><el-radio-group v-model="form.needRelabel" aria-label="是否换标"><el-radio-button :value="false">不换标</el-radio-button><el-radio-button :value="true">需要换标</el-radio-button></el-radio-group></div> <el-table :data="form.items" row-key="id" size="small">
<div class="items-hint">客户只需填写预计退回的 SKU 和数量;快递单号由仓库签收时按实际包裹扫描绑定。</div>
<el-table :data="form.items" row-key="id" size="small">
<el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column> <el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column>
<el-table-column label="SKU" min-width="200"><template #default="{ row }"><div><el-input v-model="row.skuCode" :class="{ 'duplicate-sku-input': duplicateSkuIds.has(row.id) }" placeholder="填写 SKU" @blur="row.skuCode = row.skuCode.trim()" /><div v-if="duplicateSkuIds.has(row.id)" class="duplicate-sku-error">该 SKU 已在明细中填写</div></div></template></el-table-column> <el-table-column label="SKU" min-width="200"><template #default="{ row }"><div><el-input v-model="row.skuCode" :class="{ 'duplicate-sku-input': duplicateSkuIds.has(row.id) }" placeholder="" @blur="row.skuCode = row.skuCode.trim()" /><div v-if="duplicateSkuIds.has(row.id)" class="duplicate-sku-error">该 SKU 已在明细中填写</div></div></template></el-table-column>
<el-table-column label="中文品名" min-width="260"><template #default="{ row }"><el-input v-model="row.productNameZh" placeholder="填写中文品名(选填)" /></template></el-table-column> <el-table-column label="中文品名" min-width="260"><template #default="{ row }"><el-input v-model="row.productNameZh" placeholder="" /></template></el-table-column>
<el-table-column label="预报数量" width="160"><template #default="{ row }"><el-input-number v-model="row.expectedQuantity" :min="1" controls-position="right" placeholder="数量" /></template></el-table-column> <el-table-column label="预报数量" width="160"><template #default="{ row }"><el-input-number v-model="row.expectedQuantity" :min="1" controls-position="right" placeholder="" /></template></el-table-column>
</el-table> </el-table>
<template #footer><el-button @click="showCreate=false; editingReturnNo=''">取消</el-button><el-button v-if="canCreate" type="primary" :loading="creating" @click="submit">{{ editingReturnNo ? '保存修改' : '提交预报' }}</el-button></template> <template #footer><el-button @click="showCreate=false; editingReturnNo=''">取消</el-button><el-button v-if="canCreate" type="primary" :loading="creating" @click="submit">{{ editingReturnNo ? '保存修改' : '提交预报' }}</el-button></template>
</el-dialog> </el-dialog>
@@ -355,13 +395,14 @@ onBeforeUnmount(clearPhotoUrls)
<template v-if="selected"> <template v-if="selected">
<header class="return-detail-header"> <header class="return-detail-header">
<button type="button" class="return-back" @click="returnToList"><ArrowLeft :size="16" />返回列表</button> <button type="button" class="return-back" @click="returnToList"><ArrowLeft :size="16" />返回列表</button>
<div class="return-detail-title"><strong>{{ selected.order.returnNo }}</strong><span>{{ operationWarehouseLabel(selected.order.overseasWarehouseId) }} · 退货签收</span></div> <div class="return-detail-title"><strong>{{ selected.order.returnNo }}</strong><span>{{ operationWarehouseLabel(selected.order.overseasWarehouseId) }}</span></div>
<div class="return-detail-actions"><el-button v-if="canCreateRelabel && canApplyRelabel(selected.order)" type="primary" plain @click="openRelabel(selected.order)">贴标申请</el-button><el-tag :type="statusType(selected.order.status, selected.order.needRelabel)" :class="statusClass(selected.order.status, selected.order.needRelabel)" effect="light">{{ statusLabel(selected.order.status, selected.order.needRelabel) }}</el-tag></div> <div class="return-detail-actions"><el-button v-if="canCreateRelabel && canApplyRelabel(selected.order)" type="primary" plain @click="openRelabel(selected.order)">贴标申请</el-button><el-tag :type="statusType(selected.order.status, selected.order.needRelabel)" :class="statusClass(selected.order.status, selected.order.needRelabel)" effect="light">{{ statusLabel(selected.order.status, selected.order.needRelabel) }}</el-tag></div>
</header> </header>
<ReviewRejectionNotice :status="selected.order.status" :reason="selected.remark" />
<section class="return-detail-section"> <section class="return-detail-section">
<h3>签收概览</h3> <h3>签收概览</h3>
<div class="return-detail-grid"> <div class="return-detail-grid">
<div><span>实收 / 预报</span><strong>{{ selected.order.receivedQuantity }} / {{ selected.order.expectedQuantity }}</strong></div> <div><span>预报(件)</span><strong>{{ selected.order.expectedQuantity }}</strong></div><div><span>实收(件)</span><strong>{{ selected.order.receivedQuantity }}</strong></div><div><span>待收(件)</span><strong>{{ Math.max(selected.order.expectedQuantity - selected.order.receivedQuantity, 0) }}</strong></div>
<div><span>SKU 种类</span><strong>{{ selected.order.skuTypes }}</strong></div> <div><span>SKU 种类</span><strong>{{ selected.order.skuTypes }}</strong></div>
<div><span>是否换标</span><strong>{{ selected.order.needRelabel ? '需要换标' : '否' }}</strong></div> <div><span>是否换标</span><strong>{{ selected.order.needRelabel ? '需要换标' : '否' }}</strong></div>
<div><span>客户参考号</span><strong>{{ selected.order.customerReferenceNo || '—' }}</strong></div> <div><span>客户参考号</span><strong>{{ selected.order.customerReferenceNo || '—' }}</strong></div>
@@ -369,7 +410,7 @@ onBeforeUnmount(clearPhotoUrls)
<div><span>联系电话</span><strong>{{ selected.order.warehouseContactPhone || '—' }}</strong></div> <div><span>联系电话</span><strong>{{ selected.order.warehouseContactPhone || '—' }}</strong></div>
<div><span>创建时间</span><strong>{{ formatDateTime(selected.order.createdAt) }}</strong></div> <div><span>创建时间</span><strong>{{ formatDateTime(selected.order.createdAt) }}</strong></div>
</div> </div>
<div v-if="selected.remark" class="return-detail-remark"><span>备注</span><strong>{{ selected.remark }}</strong></div> <div v-if="selected.remark && selected.order.status !== 'REJECTED'" class="return-detail-remark"><span>备注</span><strong>{{ selected.remark }}</strong></div>
</section> </section>
<section v-if="selected.order.relabelApplications?.length" class="return-detail-section"> <section v-if="selected.order.relabelApplications?.length" class="return-detail-section">
<h3>换标子单({{ selected.order.relabelApplications?.length || 0 }})</h3> <h3>换标子单({{ selected.order.relabelApplications?.length || 0 }})</h3>
@@ -443,24 +484,6 @@ onBeforeUnmount(clearPhotoUrls)
<template #footer><el-button @click="showCartons = false">关闭</el-button></template> <template #footer><el-button @click="showCartons = false">关闭</el-button></template>
</el-dialog> </el-dialog>
</section> </section>
<section class="return-detail-section">
<h3>当前关联实物箱</h3>
<el-collapse v-if="selected.currentCartons?.length">
<el-collapse-item v-for="current in selected.currentCartons" :key="current.carton.cartonMark" :name="current.carton.cartonMark">
<template #title>{{ current.carton.cartonMark }} · 整箱 {{ current.carton.totalQuantity }} 件 · 本单 {{ current.orderQuantity }} 件 · {{ current.carton.sourceReturnNo?.includes(',') ? '跨来源单合箱' : '单一来源' }}</template>
<p>来源退货单:{{ current.carton.sourceReturnNo }} · 我方箱唛:{{ current.labelStatus === 'CONFIRMED' ? '已确认贴标' : '待贴标确认' }}</p>
<el-table :data="current.ownership" border>
<el-table-column prop="returnNo" label="来源退货单" min-width="200" />
<el-table-column prop="skuCode" label="SKU" min-width="180" />
<el-table-column prop="quantity" label="来源贡献数量" width="130" />
</el-table>
<p>换箱唛以当前实物箱为单位;跨来源单同 SKU 的部分贴标须先现场分拣确认。</p>
<el-button v-if="canCreateRelabel" :disabled="!current.canRelabel" @click="openRelabel(selected.order, current.carton.cartonMark)">选择此箱贴标</el-button>
<p v-if="!current.canRelabel">{{ current.blockReason }}</p>
</el-collapse-item>
</el-collapse>
<el-empty v-else description="暂无当前关联实物箱" :image-size="64" />
</section>
<section v-if="selected.photos?.length" class="return-detail-section"> <section v-if="selected.photos?.length" class="return-detail-section">
<h3>退货打托照片({{ selected.photos?.length || 0 }} 张)</h3> <h3>退货打托照片({{ selected.photos?.length || 0 }} 张)</h3>
<div v-if="selected.photos?.length" class="return-photo-grid"> <div v-if="selected.photos?.length" class="return-photo-grid">
@@ -497,18 +520,17 @@ onBeforeUnmount(clearPhotoUrls)
.return-query :deep(.query-toolbar__actions) { margin:0; padding:0; border:0; align-self:end; } .return-query :deep(.query-toolbar__actions) { margin:0; padding:0; border:0; align-self:end; }
@media(max-width:1200px) { .return-query.query-toolbar--grid { grid-template-columns:repeat(2,minmax(0,320px)); } } @media(max-width:1200px) { .return-query.query-toolbar--grid { grid-template-columns:repeat(2,minmax(0,320px)); } }
.relabel-suborder { display: flex; align-items: center; gap: 8px; min-height: 30px; white-space: nowrap; } .relabel-suborder { display: flex; align-items: center; gap: 8px; min-height: 30px; white-space: nowrap; }
.return-orders-page { display:grid; gap:12px; } .return-create-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); column-gap:20px; } .return-form-wide { grid-column:1 / -1; } .items-title { display:flex; justify-content:space-between; align-items:center; margin:16px 0 4px; font-weight:600; } .items-hint { margin-bottom:10px; color:var(--el-text-color-secondary); font-size:12px; } h3 { margin:24px 0 10px; font-size:16px; } h4 { margin:16px 0 8px; font-size:14px; } .remark { white-space:pre-wrap; } .warehouse-error, .duplicate-sku-error { margin-top:6px; color:var(--el-color-danger); font-size:12px; } :deep(.duplicate-sku-input .el-input__wrapper) { box-shadow:0 0 0 1px var(--el-color-danger) inset; } :deep(.el-dialog .el-select) { width:100%; } .return-orders-page { display:grid; gap:12px; } .return-create-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); column-gap:20px; } .return-form-wide { grid-column:1 / -1; } .items-title { display:flex; justify-content:space-between; align-items:center; margin:16px 0 4px; font-weight:600; } h3 { margin:24px 0 10px; font-size:16px; } h4 { margin:16px 0 8px; font-size:14px; } .remark { white-space:pre-wrap; } .warehouse-error, .duplicate-sku-error { margin-top:6px; color:var(--el-color-danger); font-size:12px; } :deep(.duplicate-sku-input .el-input__wrapper) { box-shadow:0 0 0 1px var(--el-color-danger) inset; } :deep(.el-dialog .el-select) { width:100%; }
.return-create-surface { width:calc(100% - 24px); max-width:1120px; min-width:0; margin:0 0 0 24px; justify-self:start; box-sizing:border-box; overflow:hidden; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; } .return-create-surface { width:100%; min-width:0; min-height:calc(100dvh - 198px); margin:0; box-sizing:border-box; overflow:hidden; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; }
.return-create-header, .return-create-body, .return-create-actions { width:100%; min-width:0; box-sizing:border-box; }
.return-create-header { display:flex; min-height:68px; align-items:center; justify-content:space-between; gap:20px; padding:12px 20px; border-bottom:1px solid var(--client-border); } .return-create-header { display:flex; min-height:68px; align-items:center; justify-content:space-between; gap:20px; padding:12px 20px; border-bottom:1px solid var(--client-border); }
.return-create-header h2 { margin:0; color:#1f2d45; font-size:20px; } .return-create-header h2 { margin:0; color:#1f2d45; font-size:20px; }
.return-create-header p { margin:4px 0 0; color:#7c899c; font-size:12px; }
.return-create-body { padding:18px 20px 14px; } .return-create-body { padding:18px 20px 14px; }
.return-create-body :deep(.el-select), .return-create-body :deep(.el-input-number) { width:100%; } .return-create-body :deep(.el-select), .return-create-body :deep(.el-input-number) { width:100%; }
.return-create-body .return-create-form { max-width:900px; column-gap:24px; } .return-create-body .return-create-form { width:100%; column-gap:24px; }
.return-create-body .return-create-form :deep(.el-form-item) { margin-bottom:16px; } .return-create-body .return-create-form :deep(.el-form-item) { margin-bottom:16px; }
.return-create-body .return-create-form :deep(.el-form-item__content) { min-width:0; } .return-create-body .return-create-form :deep(.el-form-item__content) { min-width:0; }
.return-create-body .return-create-form :deep(.el-input) { max-width:320px; } .return-create-body .return-create-form :deep(.el-input), .return-create-body .return-create-form :deep(.el-select) { width:100%; max-width:none; }
.return-create-body .return-create-form :deep(.el-select) { max-width:520px; }
.return-create-body .return-create-form :deep(.el-textarea) { max-width:100%; } .return-create-body .return-create-form :deep(.el-textarea) { max-width:100%; }
.return-create-body :deep(.el-table .el-input-number) { width:120px; } .return-create-body :deep(.el-table .el-input-number) { width:120px; }
.return-forecast-table { overflow:hidden; border:1px solid var(--client-border); border-radius:8px; --el-table-header-bg-color:#f5f7fb; --el-table-header-text-color:#526176; --el-table-border-color:#edf1f5; --el-table-row-hover-bg-color:#f8faff; } .return-forecast-table { overflow:hidden; border:1px solid var(--client-border); border-radius:8px; --el-table-header-bg-color:#f5f7fb; --el-table-header-text-color:#526176; --el-table-border-color:#edf1f5; --el-table-row-hover-bg-color:#f8faff; }
@@ -595,3 +617,50 @@ onBeforeUnmount(clearPhotoUrls)
@media (max-width: 900px) { .return-photo-grid { grid-template-columns:repeat(3,minmax(0,1fr)); } } @media (max-width: 900px) { .return-photo-grid { grid-template-columns:repeat(3,minmax(0,1fr)); } }
@media (max-width: 720px) { .return-detail-header { grid-template-columns:1fr auto; } .return-back { grid-column:1/-1; } .return-pagination { padding:12px; } .return-photo-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } } @media (max-width: 720px) { .return-detail-header { grid-template-columns:1fr auto; } .return-back { grid-column:1/-1; } .return-pagination { padding:12px; } .return-photo-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
</style> </style>
<style scoped>
.return-orders-create { --el-color-primary: #2f7bff; --el-text-color-regular: #1f2937; --el-text-color-placeholder: #b0b7c3; width: 100%; min-width: 0; background: #f4f7fc; color: #1f2937; font: 14px/1.5 "PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif; }
.return-orders-create .return-create-surface { min-height: 0; overflow: visible; border: 0; border-radius: 0; background: transparent; }
.return-orders-create .return-create-header { min-height: 44px; margin-bottom: 12px; padding: 0; border: 0; }
.return-orders-create .return-create-header h2 { color: #1f2937; font-size: 26px; font-weight: 700; }
.return-orders-create .return-create-body { padding: 0; }
.return-orders-create .return-create-section { margin-bottom: 12px; }
.return-orders-create .return-create-section h3 { display: flex; align-items: center; gap: 10px; margin: 0 0 10px; color: #1f2937; font-size: 18px; font-weight: 700; }
.return-orders-create .return-create-section h3::before { content: ''; width: 9px; height: 9px; flex: 0 0 9px; border-radius: 50%; background: #2f7bff; }
.return-orders-create .return-create-section:nth-of-type(2) h3::before { background: #0ea5a4; }
.return-orders-create .return-create-form,
.return-orders-create .return-create-card { min-width: 0; padding: 16px; box-sizing: border-box; border: 1px solid #e3e8f0; border-radius: 10px; background: #fff; }
.return-orders-create .return-create-form { --el-component-size: 44px; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px 20px; }
.return-orders-create .return-create-form :deep(.el-form-item) { min-width: 0; margin: 0; }
.return-orders-create .return-create-form :deep(.el-form-item__label) { height: auto; margin: 0 0 6px; padding: 0; color: #374151; font-size: 14px; font-weight: 600; line-height: 20px; }
.return-orders-create .return-create-form :deep(.el-form-item.is-required .el-form-item__label::before) { color: #e5484d; }
.return-orders-create .return-create-form :deep(.el-form-item__content) { min-width: 0; line-height: 20px; }
.return-orders-create .return-create-form :deep(.el-form-item__error) { position: absolute; top: auto; bottom: calc(100% + 6px); right: 0; left: auto; width: auto; max-width: calc(100% - 140px); padding: 0; font-size: 12px; line-height: 20px; text-align: right; }
.return-orders-create :deep(.el-input__wrapper),
.return-orders-create :deep(.el-select__wrapper),
.return-orders-create :deep(.el-textarea__inner) { border: 1px solid #d5dce8; border-radius: 6px; box-shadow: none; }
.return-orders-create .return-create-form :deep(.el-input__wrapper),
.return-orders-create .return-create-form :deep(.el-select__wrapper) { min-height: 44px; box-sizing: border-box; padding: 10px 14px; }
.return-orders-create .return-create-form :deep(.el-input__inner) { height: 22px; color: #1f2937; font-size: 14px; line-height: 22px; }
.return-orders-create .return-create-form :deep(.el-textarea__inner) { min-height: 110px !important; padding: 11px 14px; color: #1f2937; font-size: 14px; line-height: 20px; }
.return-orders-create :deep(.el-input__inner::placeholder),
.return-orders-create :deep(.el-textarea__inner::placeholder),
.return-orders-create :deep(.el-select__placeholder.is-transparent) { color: #b0b7c3; opacity: 1; }
.return-orders-create :deep(.el-input__wrapper.is-focus),
.return-orders-create :deep(.el-select__wrapper.is-focused),
.return-orders-create :deep(.el-textarea__inner:focus) { outline: 2px solid #2f7bff; outline-offset: 0; }
.return-orders-create :deep(.is-error .el-input__wrapper),
.return-orders-create :deep(.is-error .el-select__wrapper),
.return-orders-create :deep(.duplicate-sku-input .el-input__wrapper) { border-color: #e5484d; box-shadow: none; }
.return-orders-create .items-title { margin: 0 0 10px; }
.return-orders-create .items-title h3 { margin: 0; }
.return-orders-create .return-relabel-option { margin: 0 0 12px; color: #374151; }
.return-orders-create .return-relabel-option :deep(.el-radio-button__inner) { box-shadow: none; }
.return-orders-create .return-create-actions { gap: 12px; padding: 0; border: 0; background: transparent; }
.return-orders-create :deep(.el-button) { box-shadow: none; }
.return-orders-create .return-create-header :deep(.el-button),
.return-orders-create .return-create-actions :deep(.el-button) { min-height: 44px; margin-left: 0; padding: 10px 18px; border: 1px solid #d5dce8; border-radius: 6px; background: #fff; color: #1d5fe0; font-size: 14px; font-weight: 600; }
.return-orders-create .return-create-actions :deep(.el-button--primary) { padding: 12px 28px; border-color: #2f7bff; background: #2f7bff; color: #fff; }
.return-orders-create .return-create-actions :deep(.el-button.is-disabled) { opacity: .55; }
:global(.return-create-popper.el-popper) { border: 1px solid #e3e8f0; border-radius: 6px; box-shadow: none; }
</style>
File diff suppressed because one or more lines are too long
@@ -0,0 +1,117 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { transpileModule, ScriptTarget } from 'typescript'
import { computed, ref, reactive, watch } from 'vue'
const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
test('退货箱明细与来源下拉使用同一份逐箱库存,不请求普通入仓箱接口', async () => {
const body = view.slice(view.indexOf('async function loadTransferSourceCartons('), view.indexOf('// Snowflake IDs'))
const code = transpileModule(body, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText
const ctx = { transferSourceCartons: { value: [] }, transferSourceError: { value: '' },
transferSourceLoading: { value: false }, inventoryTransfer: { value: true },
selectedTransferInventory: { value: 'RETURN_ORDER:RET-1' }, form: { warehouse: 'WH' },
transferInventoryCandidates: { value: [
{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'RET-1', cartonMark: 'BOX-1', cartonAvailablePackages: 1,
cartonSkuItems: [{ skuCode: 'A', quantity: 3 }, { skuCode: 'B', quantity: 2 }] },
{ sourceType: 'RETURN_PARCEL', inboundOrderNo: 'RET-1', cartonMark: 'BOX-2', cartonAvailablePackages: 1,
cartonSkuItems: [{ skuCode: 'A', quantity: 1 }] },
{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'OTHER', cartonMark: 'FOREIGN', cartonAvailablePackages: 1 },
{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'RET-1', cartonMark: 'OCCUPIED', cartonAvailablePackages: 0 },
{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'RET-1', cartonMark: 'LABELLED', cartonAvailablePackages: 1, relabelStatus: 'COMPLETED' },
{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'RET-1', cartonMark: 'PARTIAL', cartonAvailablePackages: 1, relabelledQuantity: 2 },
] }, getTransferSourceCartons: () => { throw Error('不应调用普通来源箱查询') } }
const load = new Function(...Object.keys(ctx), 'let transferSourceRequest=0;' + code + ';return loadTransferSourceCartons')(...Object.values(ctx))
await load()
assert.deepEqual(ctx.transferSourceCartons.value.map(box => box.cartonMark), ['BOX-1', 'BOX-2'])
assert.equal(ctx.transferSourceCartons.value[0].quantity, 5)
assert.equal(ctx.transferSourceCartons.value[0].items.length, 2)
assert.equal(ctx.transferSourceError.value, '')
assert.equal(ctx.transferSourceLoading.value, false)
})
test('选择库存来源时隐藏保存草稿并阻止草稿动作', () => {
assert.match(view, /props\.service === 'transfer' && !inventoryTransfer/)
assert.match(view, /保存草稿/)
assert.match(view, /props\.service === 'transfer' && inventoryTransfer\.value && action === 'draft'/)
assert.match(view, /选择库存来源后不能保存草稿,请直接提交订单/)
})
test('来源库存发往FBA默认开启贴标,清除来源或切换私人仓后恢复选项', () => {
const source = ref(''), destination = ref('NONE'), form = reactive({ relabel: false })
const inventoryTransfer = computed(() => Boolean(source.value))
const body = view.slice(view.indexOf('const transferRelabelRequired ='), view.indexOf('const transferSourceCartons ='))
const required = new Function('computed', 'watch', 'inventoryTransfer', 'transferDestinationType', 'form', body + ';return transferRelabelRequired')(
computed, watch, inventoryTransfer, destination, form)
destination.value = 'FBA'
assert.equal(form.relabel, false)
source.value = 'IN-1'
assert.equal(required.value, true)
assert.equal(form.relabel, true)
destination.value = 'PRIVATE'
assert.equal(required.value, false)
form.relabel = false
destination.value = 'FBA'
assert.equal(form.relabel, true)
source.value = ''
assert.equal(required.value, false)
assert.match(view, /<el-radio-button v-if="!transferRelabelRequired" :value="false">不需要贴标/)
})
function setup() {
const body = view.slice(view.indexOf('async function selectTransferInventory('), view.indexOf('function selectTransferInboundMethod('))
const code = transpileModule(body, { compilerOptions: { target: ScriptTarget.ES2022 } }).outputText
const ctx = { selectedTransferInventory: {value:''}, selectedTransferSourceOrderIds:{value:[]},
transferSourceCartons:{value:[{cartonMark:'OLD'}]}, transferSourceError:{value:'OLD'}, transferSourceLoading:{value:true},
transferDestinationType:{value:'NONE'}, form:{warehouse:'WH',inboundNo:''},
transferInventoryCandidates:{value:[{inboundCode:'IN',skuCode:'SKU',productNameZh:'货品',availablePackages:2},
{inboundCode:'IN',skuCode:'SKU',availablePackages:3},{inboundCode:'OTHER',skuCode:'OTHER',availablePackages:99}]},
cargoRows:{value:[]}, inventoryQuantity:Number, createCargoRow:()=>({expectedPackageCount:1}),
loadTransferSourceCartons:async()=>{}, listRelabelHistoricalOrders:async()=>[{id:'1234567890123456789'}],
ElMessage:{error(message){throw Error(message)}} }
const select = new Function(...Object.keys(ctx), 'let transferSourceRequest=0;'+code+'; return selectTransferInventory')(...Object.values(ctx))
return {ctx,select}
}
test('inventory source populates full immutable cargo counts without mixing other inbound orders',async()=>{
const {ctx,select}=setup(); await select('IN')
assert.equal(ctx.transferDestinationType.value,'FBA')
assert.equal(ctx.cargoRows.value.length,1)
assert.equal(ctx.cargoRows.value[0].expectedPackageCount,5)
assert.equal(ctx.cargoRows.value[0].quantity,5)
assert.deepEqual(ctx.selectedTransferSourceOrderIds.value,['1234567890123456789'])
await select('')
assert.equal(ctx.form.inboundNo,'')
assert.deepEqual(ctx.selectedTransferSourceOrderIds.value,[])
assert.deepEqual(ctx.transferSourceCartons.value,[])
})
test('inventory view hides inbound fields and editing actions and shows original carton destination',()=>{
assert.match(view,/v-if="props.service === 'transfer' && !inventoryTransfer"[^>]*><span><i>\*<\/i>入仓方式/)
assert.match(view,/<el-radio-button v-if="!inventoryTransfer" value="NONE">/)
const panel=view.slice(view.indexOf('<section v-if="inventoryTransfer"'),view.indexOf('</section>',view.indexOf('<section v-if="inventoryTransfer"')))
assert.match(panel,/box.cartonMark/); assert.match(panel,/box.destinationWarehouseCode/)
assert.doesNotMatch(panel,/v-model|addCargoRow|removeCargoRow|清空/)
assert.match(view,/!inventoryTransfer\.value && \(!form.warehouse/)
assert.match(view,/estimatedArrivalAt: inventoryTransfer.value \? undefined : form.estimatedArrivalAt/)
})
test('仓储转运来源下拉包含退货单并使用独立来源编码', () => {
assert.match(view, /RETURN_ORDER:\$\{returnNo\}/)
assert.match(view, /退货单|\$\{returnNo\}/)
assert.match(view, /item\.sourceType === 'RETURN_CARTON' \|\| item\.sourceType === 'RETURN_PARCEL'/)
assert.match(view, /isReturnSource[\s\S]*item\.sourceType === 'RETURN_CARTON'/)
})
test('退货来源带出实物 SKU 数量并跳过普通历史订单查询', async () => {
const { ctx, select } = setup()
ctx.transferInventoryCandidates.value = [{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'RET-1',
cartonAvailablePackages: 1, skuItems: [{ skuCode: 'SKU', quantity: 1 }],
cartonSkuItems: [{ skuCode: 'SKU', quantity: 6 }] },
{ sourceType: 'RETURN_CARTON', inboundOrderNo: 'OTHER', cartonAvailablePackages: 1,
cartonSkuItems: [{ skuCode: 'FOREIGN', quantity: 99 }] }]
await select('RETURN_ORDER:RET-1')
assert.equal(ctx.cargoRows.value.length, 1)
assert.equal(ctx.cargoRows.value[0].quantity, 6)
assert.equal(ctx.cargoRows.value[0].expectedPackageCount, 1)
assert.deepEqual(ctx.selectedTransferSourceOrderIds.value, [])
})
@@ -0,0 +1,67 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { computed, reactive, ref } from 'vue'
import ts from 'typescript'
const source = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const { default: Schema } = createRequire(import.meta.resolve('element-plus'))('async-validator')
const rulesSource = source.slice(source.indexOf('const labelingFormRules ='), source.indexOf('const orderInfoCollapsed ='))
const rulesCode = ts.transpileModule(rulesSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
function harness(mode = 'carton', patch = {}) {
const labelingMode = ref(mode)
const form = reactive({ warehouse: 'warehouse-a', sourceOrder: 'source-a', contact: '联系人', phone: '12345678', labelDeadline: '2026-11-10T12:00:00', destination: 'FBA-A', deliveryMethod: 'TRUCK', relabel: false, ...patch })
const rules = new Function('computed', 'labelingMode', 'form', `${rulesCode}\nreturn labelingFormRules`)(computed, labelingMode, form)
return { form, labelingMode, validate: () => new Schema(rules.value).validate(form) }
}
test('order information reports every missing required field and rejects whitespace contacts', async () => {
const state = harness('carton', { warehouse: '', sourceOrder: '', contact: ' ', phone: ' ', labelDeadline: '', destination: '', deliveryMethod: '' })
await assert.rejects(state.validate(), error => {
assert.deepEqual(Object.keys(error.fields).sort(), ['warehouse', 'sourceOrder', 'contact', 'phone', 'labelDeadline', 'destination', 'deliveryMethod'].sort())
return true
})
})
test('SKU-only labeling excludes hidden destination and delivery requirements', async () => {
const state = harness('sku', { destination: '', deliveryMethod: '' })
await state.validate()
state.labelingMode.value = 'carton_and_sku'
await assert.rejects(state.validate(), error => Object.keys(error.fields).sort().join(',') === 'deliveryMethod,destination')
})
test('shipping label file is required only when express printing is selected', async () => {
const state = harness('carton', { deliveryMethod: 'EXPRESS', relabel: true })
await assert.rejects(state.validate(), error => Boolean(error.fields.shippingLabelFile))
state.form.shippingLabelFile = new File(['label'], 'label.pdf', { type: 'application/pdf' })
await state.validate()
state.form.shippingLabelFile = null
state.form.relabel = false
await state.validate()
state.form.relabel = true
state.form.deliveryMethod = 'TRUCK'
await state.validate()
state.form.deliveryMethod = 'EXPRESS'
state.labelingMode.value = 'sku'
await state.validate()
})
test('invalid create fields expand the order section and stop before submission logic', async () => {
const start = source.indexOf("async function submit(action:")
const end = source.indexOf(" if (props.service === 'transfer' && inventoryTransfer.value", start)
const preamble = source.slice(start, end) + '\nreturn "continue"\n}'
const code = ts.transpileModule(preamble, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const collapsed = ref(true), saving = ref(false), isLabelingCreate = ref(true)
let validations = 0
const formRef = ref({ validate: async () => { validations++; throw new Error('invalid') } })
const submit = new Function('saving', 'isLabelingCreate', 'orderInfoCollapsed', 'nextTick', 'labelingFormRef', `${code}\nreturn submit`)(saving, isLabelingCreate, collapsed, async () => {}, formRef)
assert.equal(await submit(), undefined)
assert.equal(collapsed.value, false)
assert.equal(validations, 1)
isLabelingCreate.value = false
assert.equal(await submit(), 'continue')
assert.equal(validations, 1)
saving.value = true
assert.equal(await submit(), undefined)
})
@@ -57,19 +57,16 @@ test('客户贴标表单不展示客户单号、托盘和内部库存来源列',
assert.doesNotMatch(view, /已选托盘组成/) assert.doesNotMatch(view, /已选托盘组成/)
}) })
test('贴标申请保留关联模板下载和上传入口', () => { test('贴标申请使用统一明细模板下载和上传入口', () => {
assert.match(view, /downloadRelabelTemplate/) assert.match(view, /downloadRelabelTemplate/)
assert.match(view, /<strong>SKU 关联<\/strong>/) assert.match(view, /<strong>统一贴标明细<\/strong>/)
assert.match(view, /<strong>箱号关联<\/strong>/)
assert.match(view, /<strong>SKU 混箱<\/strong>/)
assert.match(view, />下载模板<\/el-button>/) assert.match(view, />下载模板<\/el-button>/)
assert.match(view, />上传文件<\/el-button>/) assert.match(view, />上传文件<\/el-button>/)
assert.match(view, /skuTemplateInput\?\.click\(\)/) assert.match(view, /unifiedTemplateInput\?\.click\(\)/)
assert.match(view, /cartonTemplateInput\?\.click\(\)/)
assert.match(view, /importRelabelTemplate/) assert.match(view, /importRelabelTemplate/)
assert.match(view, /明细行标识/) assert.match(view, /明细行标识/)
assert.match(view, /'明细行标识', '旧箱唛', '旧SKU标签', '新SKU标签'/) assert.match(view, /'明细行标识', '贴标类型'/)
assert.match(view, /const includeDestination = false/) assert.doesNotMatch(view.slice(view.indexOf('function downloadRelabelTemplate'), view.indexOf('function parseCsvLine')), /FBA目的仓/)
assert.doesNotMatch(view, /const includeDestination = props\.service !== 'transfer'/) assert.doesNotMatch(view, /const includeDestination = props\.service !== 'transfer'/)
assert.match(view, /<strong>绑定明细<\/strong>/) assert.match(view, /<strong>绑定明细<\/strong>/)
assert.match(view, /<th>仓库唛头 \*<\/th>/) assert.match(view, /<th>仓库唛头 \*<\/th>/)
@@ -129,9 +126,9 @@ test('贴标货物明细通过单一换标类型选择三种模式', () => {
test('箱唛相关换标必须选择四选一派送方式', () => { test('箱唛相关换标必须选择四选一派送方式', () => {
assert.match(view, /label="卡车派送" value="TRUCK"/) assert.match(view, /label="卡车派送" value="TRUCK"/)
assert.match(view, /label="快递派送" value="EXPRESS"/) assert.match(view, /label="快递派送" value="EXPRESS"/)
assert.match(view, /label="卡车自提" value="TRUCK_PICKUP"/) assert.match(view, /label="亚马逊自提" value="AMAZON_PICKUP"/)
assert.match(view, /label="快递自提" value="EXPRESS_PICKUP"/) assert.match(view, /label="客户自提" value="CUSTOMER_PICKUP"/)
assert.match(api, /RelabelDeliveryMethod = 'TRUCK' \| 'EXPRESS' \| 'TRUCK_PICKUP' \| 'EXPRESS_PICKUP'/) assert.match(api, /RelabelDeliveryMethod = 'TRUCK' \| 'EXPRESS' \| 'AMAZON_PICKUP' \| 'CUSTOMER_PICKUP'/)
assert.match(view, /labelingMode\.value !== 'sku' && !form\.deliveryMethod/) assert.match(view, /labelingMode\.value !== 'sku' && !form\.deliveryMethod/)
}) })
@@ -174,7 +171,7 @@ test('海外操作仓和FBA目的仓使用独立字段', () => {
assert.match(api, /destinationFbaWarehouseCode\?: string/) assert.match(api, /destinationFbaWarehouseCode\?: string/)
assert.match(view, /operationWarehouseId: form\.warehouse/) assert.match(view, /operationWarehouseId: form\.warehouse/)
assert.match(view, /destinationFbaWarehouseCode: form\.destination/) assert.match(view, /destinationFbaWarehouseCode: form\.destination/)
assert.match(view, /<el-select v-model="form\.destination"[^\n]+FBA 目的仓/) assert.match(view, /FBA 目的仓<\/span><el-select v-model="form\.destination"/)
assert.doesNotMatch(view, /v-model="row\.destinationWarehouseId"[^\n]+请选择 FBA 目的仓/) assert.doesNotMatch(view, /v-model="row\.destinationWarehouseId"[^\n]+请选择 FBA 目的仓/)
}) })
@@ -230,7 +227,7 @@ test('进入复核后客户订单回显换标完成状态', () => {
test('审核驳回后展示原因并允许替换资料后重新提交', () => { test('审核驳回后展示原因并允许替换资料后重新提交', () => {
assert.match(api, /export function resubmitRelabel\(/) assert.match(api, /export function resubmitRelabel\(/)
assert.match(view, /贴标单审核已驳回/) assert.match(view, /<ReviewRejectionNotice/)
assert.match(view, /application\.reviewRemark/) assert.match(view, /application\.reviewRemark/)
assert.match(view, /修改后重新提交/) assert.match(view, /修改后重新提交/)
assert.match(view, /await resubmitRelabel\(/) assert.match(view, /await resubmitRelabel\(/)
@@ -5,6 +5,26 @@ import ts from 'typescript'
const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8') const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const source = view.slice(view.indexOf('function returnSourceNos'), view.indexOf('const relabelInboundOptions')) const source = view.slice(view.indexOf('function returnSourceNos'), view.indexOf('const relabelInboundOptions'))
const compiled = ts.transpileModule(source + '\nexports.sourceNos = returnSourceNos; exports.progress = returnRelabelProgress', { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText const compiled = ts.transpileModule(source + '\nexports.sourceNos = returnSourceNos; exports.progress = returnRelabelProgress', { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
test('carton validation ignores unselected stock after SKU relabel and consolidation', () => {
const start = view.indexOf('async function submit(')
const validation = view.slice(view.indexOf(' const invalidCargo =', start), view.indexOf(" if ((props.service === 'relabel'", start))
const compiledValidation = ts.transpileModule(validation, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const validate = new Function('props', 'labelingMode', 'relabelRows', 'cartonDetailRows', 'cargoRows', 'skuRelabelRows', compiledValidation + '; return invalidCargo')
const stockRows = [
{ included: false, name: '', sku: 'OLD-SKU', quantity: 1 },
{ included: false, name: '', sku: 'OLD-SKU,NEW-SKU', quantity: 1 },
]
const selected = { included: true, name: 'Product', sku: 'OLD-SKU,NEW-SKU', quantity: 1 }
function invalid(details) {
return validate({ service: 'labeling' }, { value: 'carton' }, details,
{ value: details }, { value: [...stockRows, ...details] }, { value: [] })
}
assert.equal(invalid([selected]), false)
assert.equal(invalid([{ ...selected, name: '' }]), true)
assert.equal(invalid([]), true)
assert.equal(invalid([{ ...selected, sku: '' }]), false, 'SKU is optional for carton labels')
})
const exports = {} const exports = {}
new Function('exports', compiled)(exports) new Function('exports', compiled)(exports)
test('合箱来源按单号集合精确匹配并去重,不能用子串匹配', () => { test('合箱来源按单号集合精确匹配并去重,不能用子串匹配', () => {
@@ -22,7 +42,6 @@ test('退货 SKU 申请按实物箱选择,来源标识只读,部分数量转
assert.match(view, /item.id === rows\[0\].sourceRowId/) assert.match(view, /item.id === rows\[0\].sourceRowId/)
assert.match(view, /row.sourceRowId !== source\?\.id/) assert.match(view, /row.sourceRowId !== source\?\.id/)
assert.match(view, /:readonly="isReturnRelabelSource"/) assert.match(view, /:readonly="isReturnRelabelSource"/)
assert.match(view, /SKU 换标完成后扣减旧 SKU、增加新 SKU/)
assert.match(view, /labelingMode.value === 'sku' \? !skuTotalFile.value : !cartonTotalFile.value/) assert.match(view, /labelingMode.value === 'sku' \? !skuTotalFile.value : !cartonTotalFile.value/)
}) })
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { computed, reactive, ref } from 'vue'
import ts from 'typescript'
const source = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const { default: Schema } = createRequire(import.meta.resolve('element-plus'))('async-validator')
const ruleSource = source.slice(source.indexOf('const transferFormRules ='), source.indexOf('watch([inventoryTransfer,'))
const code = ts.transpileModule(ruleSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
function harness(patch = {}) {
const form = reactive({ warehouse: 'WH', deliveryMethod: 'WAREHOUSE_PICKUP', address: 'Street 1', pickupContact: 'Contact', pickupPhone: '123456', estimatedArrivalAt: '2026-11-01T12:00:00', relabel: false, ...patch })
const inventoryTransfer = ref(false), transferDestinationType = ref('NONE'), labelingMode = ref('carton')
const rules = new Function('computed', 'inventoryTransfer', 'transferDestinationType', 'labelingMode', 'form', code + '\nreturn transferFormRules')(computed, inventoryTransfer, transferDestinationType, labelingMode, form)
return { form, inventoryTransfer, transferDestinationType, labelingMode, validate: () => new Schema(rules.value).validate(form) }
}
const hasFields = (...fields) => error => {
assert.deepEqual(Object.keys(error.fields).sort(), fields.sort())
return true
}
test('pickup requires contact and phone; customer delivery hides those requirements', async () => {
const state = harness({ pickupContact: ' ', pickupPhone: '' })
await assert.rejects(state.validate(), hasFields('pickupContact', 'pickupPhone'))
state.form.deliveryMethod = 'CUSTOMER_DELIVERY'
await state.validate()
state.form.address = ''
await assert.rejects(state.validate(), hasFields('address'))
})
test('inventory transfer excludes inbound address, arrival and pickup fields', async () => {
const state = harness({ deliveryMethod: '', address: '', estimatedArrivalAt: '', pickupContact: '', pickupPhone: '' })
state.inventoryTransfer.value = true
await state.validate()
state.form.warehouse = ''
await assert.rejects(state.validate(), hasFields('warehouse'))
})
test('destination switch validates only FBA or private warehouse fields currently visible', async () => {
const state = harness()
await state.validate()
state.transferDestinationType.value = 'FBA'
await assert.rejects(state.validate(), hasFields('destination'))
state.transferDestinationType.value = 'PRIVATE'
await assert.rejects(state.validate(), hasFields('privateDestinationAddress', 'privateDestinationPostalCode', 'privateDestinationContact', 'privateDestinationPhone'))
Object.assign(state.form, { privateDestinationAddress: 'Private street', privateDestinationPostalCode: '10000', privateDestinationContact: 'Person', privateDestinationPhone: '123456' })
await state.validate()
state.transferDestinationType.value = 'NONE'
await state.validate()
})
test('relabeling requires its visible fields, with no delivery method for SKU-only mode', async () => {
const state = harness({ relabel: true })
await assert.rejects(state.validate(), hasFields('labelDeadline', 'relabelContact', 'relabelPhone', 'relabelDeliveryMethod', 'relabelDestination'))
Object.assign(state.form, { labelDeadline: '2026-11-01T12:00:00', relabelContact: 'Contact', relabelPhone: '123456', relabelDestination: 'FBA-A' })
state.labelingMode.value = 'sku'
await state.validate()
state.labelingMode.value = 'carton_and_sku'
await assert.rejects(state.validate(), hasFields('relabelDeliveryMethod'))
state.form.relabel = false
await state.validate()
})
test('draft and submit stop before business requests when create validation fails; edit remains unchanged', async () => {
const start = source.indexOf(' if (isTransferCreate.value) {', source.indexOf('async function submit('))
const end = source.indexOf(' const primaryWarehouse =', start)
const code = 'return async function submit(action) {' + source.slice(start, end) + '\nreturn action\n}'
const isTransferCreate = ref(true)
const labelingFormRef = ref({ validate: async () => { throw new Error('required') } })
const submit = new Function('isTransferCreate', 'labelingFormRef', 'nextTick', code)(isTransferCreate, labelingFormRef, async () => {})
assert.equal(await submit('draft'), undefined)
assert.equal(await submit('submit'), undefined)
isTransferCreate.value = false
assert.equal(await submit('draft'), 'draft')
assert.equal(await submit('submit'), 'submit')
})
@@ -0,0 +1,87 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
const source = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const csvCell = source.slice(source.indexOf('function csvCell('), source.indexOf('function transferCustomerMarks'))
const buildItems = source.slice(source.indexOf('function buildSkuRelabelItems('), source.indexOf('function addRelabelCargoRow('))
const submitStart = source.indexOf('const sourceInboundOrders =', source.indexOf('async function submit('))
const submitBody = source.slice(submitStart, source.indexOf(' try {', submitStart))
const code = ts.transpileModule(csvCell + buildItems + source.slice(source.indexOf('function relabelTemplateTypeForMode'), source.indexOf('function selectDiscardInbound')) + '\nasync function submitImported() { const idempotencyKey = "test-key"; ' + submitBody + '\nreturn created; }', { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
function harness(service = 'labeling') {
const state = { props: { service }, cargoRows: { value: [{ id: 1, sku: 'OLD', name: '货物', included: false, cartonMark: 'BOX-1', customerCartonMarks: 'CUSTOMER-1', shipmentNo: '', remark: '' }] }, labelingMode: { value: 'carton' }, importedRelabelBindings: { value: [] }, skuRelabelRows: { value: [] }, transferRelabelRows: { value: [] }, form: { destination: 'ONT8' }, ElMessage: { error: message => errors.push(message), warning: message => errors.push(message), success: () => {} }, createCargoRow: () => ({}), transferCustomerMarks: row => row.customerCartonMarks.split(',') }
const requests = []
Object.assign(state, { isReturnRelabelSource: { value: false }, selectedReturnCandidates: { value: [] }, cartonDetailRows: { get value() { return state.cargoRows.value.filter(row => row.included) } }, createRelabel: async request => { requests.push(request); return { application: { relabelNo: 'TEST-RELABEL' } } } })
Object.assign(state.cargoRows.value[0], { availableQuantity: 1, sourceInventoryBalanceId: '101', sourceInventoryPositionId: '102', sourceInboundOrderId: '103' })
const errors = [], downloads = []
const URL = { createObjectURL: blob => { downloads.push(blob); return 'blob:test' }, revokeObjectURL: () => {} }
const document = { createElement: () => ({ click() {} }) }
const result = new Function(...Object.keys(state), 'URL', 'document', 'let skuRelabelSequence = 0;\n' + code + '\nreturn { downloadRelabelTemplate, importRelabelTemplate, importSelectedBindingsToDetails, buildSkuRelabelItems, submitImported };')(...Object.values(state), URL, document)
async function upload(rows) {
const csv = [['明细行标识', '贴标类型', '仓库唛头', '旧SKU标签', '新SKU标签', '换标数量(件)', '新FBA箱唛', 'FBA货件编号', '备注'], ...rows].map(row => row.join(',')).join('\r\n')
await result.importRelabelTemplate({ target: { files: [new File([csv], '统一模板.csv')], value: 'file' } })
}
return { ...state, ...result, upload, errors, downloads, requests }
}
for (const [type, mode, expected] of [['只换箱唛', 'carton', 'carton'], ['只换 SKU 标签', 'sku', 'sku'], ['SKU 和箱唛都换', 'carton_and_sku', 'mixed']]) {
test(`${type}:统一模板导入并生成对应类型明细`, async () => {
const state = harness()
await state.upload([[1, type, 'BOX-1', 'OLD', mode === 'carton' ? '' : 'NEW', 3, mode === 'sku' ? '' : 'FBA-1', mode === 'sku' ? '' : 'SHIP-1', '']])
assert.deepEqual(state.errors, [])
assert.equal(state.importedRelabelBindings.value[0].templateType, expected)
state.importSelectedBindingsToDetails()
assert.equal(state.labelingMode.value, mode)
if (mode === 'carton') { assert.equal(state.cargoRows.value[0].included, true); assert.equal(state.cargoRows.value[0].quantity, 1) }
else {
assert.equal(state.skuRelabelRows.value[0].newSku, 'NEW')
const [item] = state.buildSkuRelabelItems()
assert.equal(item.operationType, mode === 'sku' ? 'SKU_LABEL' : 'CARTON_AND_SKU')
assert.equal(item.totalPackageCount, 1)
assert.equal(item.skuItems[0].quantity, 3)
assert.equal(item.destinationFbaWarehouseCode, mode === 'sku' ? undefined : 'ONT8')
}
state.form.deliveryMethod = 'TRUCK'
await state.submitImported()
assert.equal(state.requests.length, 1)
assert.equal(state.requests[0].items[0].operationType, mode === 'carton' ? 'CARTON_LABEL' : mode === 'sku' ? 'SKU_LABEL' : 'CARTON_AND_SKU')
assert.equal(state.requests[0].deliveryMethod, mode === 'sku' ? undefined : 'TRUCK')
})
}
test('三种类型下载同一列结构,并带出当前换标类型', async () => {
const state = harness()
const headers = []
for (const mode of ['carton', 'sku', 'carton_and_sku']) {
state.labelingMode.value = mode
state.downloadRelabelTemplate()
const csv = await state.downloads.at(-1).text()
const lines = csv.split('\r\n')
assert.equal(lines.length, 3)
headers.push(lines[0])
assert.match(lines[1], /只换箱唛|只换 SKU 标签|SKU 和箱唛都换/)
}
assert.equal(new Set(headers).size, 1)
})
test('组合换标同箱多 SKU 生成一条箱任务并保留全部 SKU 子项', async () => {
const state = harness()
await state.upload([[1, 'SKU 和箱唛都换', 'BOX-1', 'OLD', 'NEW', 3, 'FBA-1', 'SHIP-1', ''], [1, 'SKU 和箱唛都换', 'BOX-1', 'OLD2', 'NEW2', 2, 'FBA-1', 'SHIP-1', '']])
assert.deepEqual(state.errors, [])
state.importSelectedBindingsToDetails()
await state.submitImported()
assert.equal(state.requests[0].items.length, 1)
assert.equal(state.requests[0].items[0].totalPackageCount, 1)
assert.deepEqual(state.requests[0].items[0].skuItems.map(item => item.quantity), [3, 2])
})
test('混合类型、缺字段、无效数量、重复关系和未知库存均不导入', async () => {
const valid = [1, 'SKU 和箱唛都换', 'BOX-1', 'OLD', 'NEW', 3, 'FBA-1', 'SHIP-1', '']
for (const rows of [[valid, [1, '只换箱唛', 'BOX-2', '', '', 1, 'FBA-2', 'SHIP-2', '']], [[...valid.slice(0, 4), '', ...valid.slice(5)]], [[...valid.slice(0, 5), 0, ...valid.slice(6)]], [valid, valid], [[999, ...valid.slice(1)]], [valid, [1, 'SKU 和箱唛都换', 'BOX-1', 'OTHER', 'NEW2', 1, 'FBA-OTHER', 'SHIP-1', '']]]) {
const state = harness()
await state.upload(rows)
assert.equal(state.errors.length, 1)
assert.equal(state.importedRelabelBindings.value.length, 0)
}
})
@@ -1,12 +1,96 @@
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 { createRequire } from 'node:module'
import ts from 'typescript'
const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8') const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const { default: Schema } = createRequire(import.meta.resolve('element-plus'))('async-validator')
test('新增废弃逐字段校验仓库、来源单和原因,备注不影响提交资格', async () => {
const source = view.slice(view.indexOf('const disposalFormRules:'), view.indexOf('const labelingFormRef ='))
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const rules = new Function(code + '\nreturn disposalFormRules')()
const validator = new Schema(rules)
await assert.rejects(validator.validate({ warehouse: '', sourceOrder: '', reason: '' }), error => {
assert.deepEqual(Object.keys(error.fields).sort(), ['reason', 'sourceOrder', 'warehouse'])
return true
})
const form = { warehouse: 'WH-A', sourceOrder: 'document:IN-A', reason: '其他', remark: '' }
await validator.validate(form)
await assert.rejects(validator.validate({ ...form, sourceOrder: '' }), error => Boolean(error.fields.sourceOrder))
await assert.rejects(validator.validate({ ...form, reason: ' ' }), error => Boolean(error.fields.reason))
})
test('新增废弃校验失败不进入库存提交判断,其他页面不调用废弃表单校验', async () => {
const guard = view.match(/ if \(isDisposalCreate\.value && !await labelingFormRef[^\n]+/)[0]
let validations = 0
const submit = new Function('isDisposalCreate', 'labelingFormRef', 'return async () => {' + guard + '\nreturn "continue"\n}')
const formRef = { value: { validate: async () => { validations++; throw new Error('required') } } }
assert.equal(await submit({ value: true }, formRef)(), undefined)
assert.equal(validations, 1)
assert.equal(await submit({ value: false }, formRef)(), 'continue')
assert.equal(validations, 1)
formRef.value.validate = async () => true
assert.equal(await submit({ value: true }, formRef)(), 'continue')
})
test('货物废弃先选择海外操作仓,再加载并选择该仓入库单', () => { test('货物废弃先选择海外操作仓,再加载并选择该仓入库单', () => {
assert.match(view, /props\.service === 'disposal'.*操作仓.*v-model="form\.warehouse".*请选择海外仓.*@change="selectDiscardWarehouse"/s) assert.match(view, /props\.service === 'disposal'.*操作仓.*v-model="form\.warehouse".*@change="selectDiscardWarehouse"/s)
assert.match(view, /props\.service === 'disposal'.*选择入库单.*:disabled="!form\.warehouse".*请先选择操作仓/s) assert.match(view, /props\.service === 'disposal'.*选择入库单.*:disabled="!form\.warehouse".*@change="selectDiscardInbound"/s)
assert.match(view, /async function selectDiscardWarehouse\(\).*selectedDiscardOrderId\.value = ''.*cargoRows\.value = \[\].*listRelabelInventoryCandidates\(form\.warehouse\).*grouped/s) assert.match(view, /async function selectDiscardWarehouse\(\).*selectedDiscardOrderId\.value = ''.*cargoRows\.value = \[\].*listDiscardCandidates\(\)/s)
assert.match(view, /\|\| !primaryWarehouse \|\| invalidCargo/) assert.match(view, /\|\| !primaryWarehouse \|\| invalidCargo/)
}) })
test('无箱唛按数量废弃时备注必填,选择箱唛废弃时备注可选', () => {
assert.match(view, /props\.service === 'disposal' && discardQuantityMode\.value && !form\.remark\.trim\(\)/)
assert.match(view, /请填写废弃备注/)
assert.match(view, /props\.service === 'disposal' && discardQuantityMode \? '备注 \*' : '备注'/)
})
test('废弃来源包含通用仓位,选择后带出全部库存且不把选择键提交为订单ID', () => {
const body = view.match(/function selectDiscardInbound\(orderId: string\) \{([\s\S]*?)\n\}/)[1]
const select = new Function('discardRequestedPackages', 'discardSelectedBoxKeys', 'discardBoxSearch', 'selectAllDiscardBoxes', 'discardDocuments', 'cargoRows', 'form', 'cargoSequence', 'orderId', body)
const cargoRows = { value: [] }; const form = {}
const source = { orderId: 'inventory:42', sourceType: 'INVENTORY', inventoryPositionId: '42', overseasWarehouseId: '99', inboundCode: 'WT-1', skus: [{ skuCode: 'A', productName: '商品', availablePackages: 100 }] }
select({ value: 9 }, { value: [] }, { value: '' }, () => {}, { value: [{ ...source, orderId: 'document:WT-1', sources: [source] }] }, cargoRows, form, 0, 'document:WT-1')
assert.equal(cargoRows.value[0].quantity, 100)
assert.equal(cargoRows.value[0].sourceInventoryPositionId, '42')
assert.equal(form.inboundNo, 'WT-1')
assert.match(view, /orderId: item.sourceType === 'DROPSHIP' \? item.sourceOrderId : undefined/)
assert.match(view, /inventoryPositionId: item.sourceType === 'INVENTORY'/)
})
function selectionRows(boxes, selectedKeys) {
const body = view.match(/function syncDiscardSelection\(\) \{([\s\S]*?)\n\}/)[1].replace('new Map<string, CargoRow>()', 'new Map()')
const rows = { value: [] }
new Function('discardSourceBoxes', 'discardSelectedBoxKeys', 'cargoRows', 'createCargoRow', body)({ value: boxes }, { value: selectedKeys }, rows, () => ({}))
return rows.value
}
test('部分废弃只提交勾选的箱子,数量由箱子汇总,清空后无明细', () => {
const source = { orderId: 'inventory:42', inventoryPositionId: '42', sourceType: 'INVENTORY', availablePackages: 3, skus: [{ skuCode: 'SKU', productName: '商品' }] }
const boxes = ['1', '2', '3'].map(id => ({ key: `INVENTORY:${id}`, cartonId: id, cartonMark: `BOX-${id}`, source, skus: source.skus }))
const rows = selectionRows(boxes, ['INVENTORY:2'])
assert.equal(rows.length, 1); assert.equal(rows[0].quantity, 1)
assert.deepEqual(rows[0].discardCartonIds, ['2']); assert.equal(rows[0].sourceInventoryPositionId, '42')
assert.equal(selectionRows(boxes, []).length, 0)
})
test('混合SKU箱按实物箱只计一次,退货箱仍整箱携带全部SKU', () => {
const skus = [{ skuCode: 'A', availablePackages: 2 }, { skuCode: 'B', availablePackages: 3 }]
const dropship = { orderId: '42', sourceType: 'DROPSHIP', availablePackages: 1, skus }
const rows = selectionRows([{ key: 'DROPSHIP:1', cartonId: '1', source: dropship, skus }], ['DROPSHIP:1'])
assert.equal(rows.length, 1); assert.equal(rows[0].quantity, 1); assert.deepEqual(rows[0].discardCartonIds, ['1'])
const returned = { orderId: 'return:2', returnCartonId: '2', sourceType: 'RETURN_CARTON', availablePackages: 5, skus }
const returnRows = selectionRows([{ key: 'RETURN_CARTON:2', cartonId: '2', source: returned, skus }], ['RETURN_CARTON:2'])
assert.deepEqual(returnRows.map(row => row.quantity), [2, 3]); assert.ok(returnRows.every(row => row.returnCartonId === '2' && row.discardCartonIds === undefined))
})
test('通用混箱同仓位保留全部SKU,跨仓位相同SKU保持独立来源', () => {
const skus = [{ skuCode: 'A', availablePackages: 1 }, { skuCode: 'B', availablePackages: 1 }]
const source = { orderId: null, inventoryPositionId: '42', sourceType: 'INVENTORY', availablePackages: 1, skus }
const boxes = [{ key: 'INVENTORY:1', cartonId: '1', source, skus }, { key: 'INVENTORY:2', cartonId: '2', source: { ...source, inventoryPositionId: '43' }, skus: [skus[0]] }]
const rows = selectionRows(boxes, ['INVENTORY:1', 'INVENTORY:2'])
assert.equal(rows.length, 3)
assert.deepEqual(rows.map(row => [row.sourceInventoryPositionId, row.sku, row.quantity, row.discardCartonIds]), [['42', 'A', 1, ['1']], ['42', 'B', 1, ['1']], ['43', 'A', 1, ['2']]])
})
@@ -0,0 +1,49 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { computed, effectScope, nextTick, reactive, ref, watch } from 'vue'
import ts from 'typescript'
const source = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const detailNumber = source.match(/^const detailNumber = .*$/m)[0]
const routeWatcher = source.slice(source.indexOf('watch(() => [props.service,'), source.indexOf('watch(mode,'))
const activation = source.slice(source.indexOf('let activatedOnce = false'), source.indexOf('onBeforeUnmount(() =>'))
const code = ts.transpileModule([detailNumber, routeWatcher, activation].join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
function harness(detailPage = false) {
const scope = effectScope(), props = reactive({ service: 'transfer', createPage: false, detailPage, detailNo: '' })
const route = reactive({ params: { detailNo: detailPage ? 'TRANSFER-A' : undefined } })
const mode = ref(detailPage ? 'detail' : 'list'), page = ref(3), filters = reactive({ number: 'TRANSFER-FILTER', warehouse: 'warehouse-1', status: 'RECEIVED' })
const calls = [], activationCallbacks = []
const resetFilters = () => { calls.push('resetFilters'); Object.assign(filters, { number: '', warehouse: '', status: '' }) }
const loadPage = () => { calls.push({ kind: 'list', page: page.value, ...filters }) }
scope.run(() => new Function('computed', 'watch', 'props', 'route', 'mode', 'page', 'resetFilters', 'resetForm', 'openCreate', 'loadDetailPage', 'loadPage', 'onActivated', code)(computed, watch, props, route, mode, page, resetFilters, () => calls.push('resetForm'), () => calls.push('create'), () => calls.push('detail'), loadPage, callback => activationCallbacks.push(callback)))
return { scope, props, route, mode, page, filters, calls, activate: () => activationCallbacks.forEach(callback => callback()) }
}
test('cached transfer list ignores detail navigation and refreshes once on return with its original filters and page', async () => {
const state = harness()
try {
state.activate()
state.route.params.detailNo = 'TRANSFER-A'
await nextTick()
assert.deepEqual(state.calls, [])
assert.equal(state.page.value, 3)
assert.equal(state.filters.number, 'TRANSFER-FILTER')
state.route.params.detailNo = 'TRANSFER-B'
await nextTick()
assert.deepEqual(state.calls, [])
state.route.params.detailNo = undefined
await nextTick()
state.activate()
assert.deepEqual(state.calls, [{ kind: 'list', page: 3, number: 'TRANSFER-FILTER', warehouse: 'warehouse-1', status: 'RECEIVED' }])
} finally { state.scope.stop() }
})
test('real detail pages still react to another detail number without loading a background list', async () => {
const state = harness(true)
try {
state.route.params.detailNo = 'TRANSFER-B'
await nextTick()
assert.deepEqual(state.calls, ['resetFilters', 'resetForm', 'detail'])
} finally { state.scope.stop() }
})
@@ -0,0 +1,29 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
const source = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
const functions = source.slice(source.indexOf('function transferCartonItem('), source.indexOf("const detailError = ref('')"))
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
const load = selectedDetail => new Function('selectedDetail', `${code}; return { transferCartonLines, palletSkuRows, palletQuantity, receivedItemCartons, receivedItemQuantity };`)(selectedDetail)
test('mixed carton detail and pallet summaries preserve every SKU without duplicating boxes', () => {
const mixed = { status: 'COUNTED', transferItemId: '1', transferPalletId: '9', quantity: 10, items: [{ transferItemId: '1', skuCode: 'A', quantity: 3 }, { transferItemId: '2', skuCode: 'B', quantity: 7 }] }
const display = load({ value: { items: [{ id: '1', skuCode: 'A', productNameZh: '产品A' }, { id: '2', skuCode: 'B', productNameZh: '产品B' }], cartons: [mixed, { ...mixed, status: 'NOT_RECEIVED', quantity: 999 }] } })
assert.equal(display.transferCartonLines(mixed).length, 2)
assert.equal(display.transferCartonLines(mixed)[1].productNameZh, '产品B')
assert.deepEqual(display.palletSkuRows({ id: '9' }), [{ sku: 'A', quantity: 3 }, { sku: 'B', quantity: 7 }])
assert.equal(display.palletQuantity({ id: '9' }), 10)
assert.equal(display.receivedItemQuantity('1'), 3)
assert.equal(display.receivedItemQuantity('2'), 7)
assert.equal(display.receivedItemCartons('2').length, 1)
})
test('discard and shipment lifecycle keeps historical receipt quantities', () => {
const detail = { value: { items: [{ id: '1', skuCode: 'A' }], cartons: ['COUNTED', 'DISCARD_PENDING', 'DISCARDED', 'SHIPPED'].map((status, i) => ({ status, transferItemId: '1', transferPalletId: '9', quantity: i + 1 })) } }
const display = load(detail)
assert.equal(display.receivedItemCartons('1').length, 4)
assert.equal(display.receivedItemQuantity('1'), 10)
assert.equal(display.palletQuantity({ id: '9' }), 10)
})
@@ -30,7 +30,6 @@ test('仓储转运支持无目的地、FBA 仓和私人仓并显式选择是否
assert.match(view, />是否贴标</) assert.match(view, />是否贴标</)
assert.match(view, /:value="false">不需要贴标/) assert.match(view, /:value="false">不需要贴标/)
assert.match(view, /:value="true">需要贴标/) assert.match(view, /:value="true">需要贴标/)
assert.match(view, /FBA 仓和私人仓均可选择是否贴标/)
assert.doesNotMatch(view, /v-model="form\.relabel" disabled/) assert.doesNotMatch(view, /v-model="form\.relabel" disabled/)
assert.doesNotMatch(view, /value === 'FBA'\) form\.relabel = true/) assert.doesNotMatch(view, /value === 'FBA'\) form\.relabel = true/)
assert.doesNotMatch(view, /value === 'PRIVATE'.*form\.relabel = false/) assert.doesNotMatch(view, /value === 'PRIVATE'.*form\.relabel = false/)
@@ -44,7 +43,8 @@ test('仓储转运支持无目的地、FBA 仓和私人仓并显式选择是否
test('换标详情待客户确认时提供确认入口并刷新详情', () => { test('换标详情待客户确认时提供确认入口并刷新详情', () => {
assert.match(view, /application\.status === 'CUSTOMER_CONFIRM_PENDING'[\s\S]*@click="confirmSelectedRelabel">确认换标完成/) assert.match(view, /application\.status === 'CUSTOMER_CONFIRM_PENDING'[\s\S]*@click="confirmSelectedRelabel">确认换标完成/)
assert.match(view, /async function confirmSelectedRelabel\(\)[\s\S]*await confirmRelabelCompletion\(relabelNo\)[\s\S]*await openDetail\(\{ '0': relabelNo \}\)/) assert.match(view, /async function confirmSelectedRelabel\(\)[\s\S]*openCompletionConfirmation\(relabelNo, 'labeling'\)/)
assert.match(view, /async function refreshAfterCompletion\(no: string\)[\s\S]*await openDetail\(\{ '0': no \}\)/)
}) })
test('仓储转运换标绑定明细自动同步只读的旧 SKU', () => { test('仓储转运换标绑定明细自动同步只读的旧 SKU', () => {
@@ -55,7 +55,7 @@ test('仓储转运换标绑定明细自动同步只读的旧 SKU', () => {
test('仓储转运换标整票只允许一个目的仓', () => { test('仓储转运换标整票只允许一个目的仓', () => {
assert.match(view, /props\.service === 'transfer' && transferDestinationType === 'FBA'[^\n]+FBA 目的仓/) assert.match(view, /props\.service === 'transfer' && transferDestinationType === 'FBA'[^\n]+FBA 目的仓/)
assert.match(view, /FBA 货件编号<\/span><el-input v-model="form\.fbaShipmentNo" placeholder="选填,可后续补充"/) assert.match(view, /FBA 货件编号<\/span><el-input v-model="form\.fbaShipmentNo" placeholder=""/)
assert.match(view, /transferDestinationType\.value === 'FBA' && !form\.destination/) assert.match(view, /transferDestinationType\.value === 'FBA' && !form\.destination/)
assert.match(view, /transferDestinationType\.value === 'PRIVATE'.*!form\.privateDestinationPostalCode/) assert.match(view, /transferDestinationType\.value === 'PRIVATE'.*!form\.privateDestinationPostalCode/)
assert.match(view, /整票换标货物目的 FBA 仓/) assert.match(view, /整票换标货物目的 FBA 仓/)
@@ -69,7 +69,7 @@ test('仓储转运换标整票只允许一个目的仓', () => {
assert.match(view, /props\.service === 'transfer' \? '客户箱唛号' : '仓库唛头'/) assert.match(view, /props\.service === 'transfer' \? '客户箱唛号' : '仓库唛头'/)
assert.match(view, /已导入 \$\{importedRows\.length\} 条仓储转运换标明细/) assert.match(view, /已导入 \$\{importedRows\.length\} 条仓储转运换标明细/)
assert.doesNotMatch(transferRelabelSection, /新 FBA 箱唛<\/th><th>FBA 目的仓<\/th>/) assert.doesNotMatch(transferRelabelSection, /新 FBA 箱唛<\/th><th>FBA 目的仓<\/th>/)
assert.match(view, /const includeDestination = false/) assert.doesNotMatch(view.slice(view.indexOf('function downloadRelabelTemplate'), view.indexOf('function parseCsvLine')), /FBA目的仓/)
}) })
test('仓储转运不要求客户填写内部入仓号和我方箱唛,但换标时填写客户箱唛', () => { test('仓储转运不要求客户填写内部入仓号和我方箱唛,但换标时填写客户箱唛', () => {
@@ -78,12 +78,10 @@ test('仓储转运不要求客户填写内部入仓号和我方箱唛,但换
assert.doesNotMatch(transferConfig, /进仓编号/) assert.doesNotMatch(transferConfig, /进仓编号/)
assert.doesNotMatch(transferSubmit, /inboundCode|sourceLastlegOrderIds/) assert.doesNotMatch(transferSubmit, /inboundCode|sourceLastlegOrderIds/)
assert.match(view, /货物明细/) assert.match(view, /货物明细/)
assert.match(view, /客户箱唛号 \*/) assert.match(view, /仓库唛头 \*/)
assert.match(view, /downloadTransferCartonMarkTemplate/) assert.match(view, /downloadTransferCartonMarkTemplate/)
assert.match(view, /importTransferCartonMarks/) assert.match(view, /importTransferCartonMarks/)
assert.match(view, /<strong>SKU 关联<\/strong>/) assert.match(view, /<strong>统一贴标明细<\/strong>/)
assert.match(view, /<strong>箱号关联<\/strong>/)
assert.match(view, /<strong>SKU 混箱<\/strong>/)
assert.match(view, />下载模板<\/el-button>/) assert.match(view, />下载模板<\/el-button>/)
assert.match(view, />上传文件<\/el-button>/) assert.match(view, />上传文件<\/el-button>/)
assert.match(view, /换标类型/) assert.match(view, /换标类型/)
@@ -101,15 +99,12 @@ test('仓储转运不要求客户填写内部入仓号和我方箱唛,但换
assert.doesNotMatch(view, /<th v-if="props\.service === 'transfer'">FNSKU \/ 箱唛<\/th>/) assert.doesNotMatch(view, /<th v-if="props\.service === 'transfer'">FNSKU \/ 箱唛<\/th>/)
}) })
test('仓储转运货物明细可按 SKU 和箱数打印客户预贴箱唛', () => { test('仓储转运填写货物即可打印,保存或提交保留已打印箱号', () => {
assert.match(view, /printTransferDraftCartonMarks/) assert.doesNotMatch(view, /printTransferDraftCartonMarks|CT-\$\{batch\}/)
assert.match(view, /请先填写商品 SKU 和对应的整数箱数/) assert.match(view, /getTransferCartonLabel\(transferNo\)/)
assert.match(view, /Array\.from\(\{ length: Number\(row\.quantity\) \}/) assert.match(view, /打印预报箱唛/)
assert.match(view, /row\.customerCartonMarks = marks\.join\('\\n'\)/) assert.match(view, /@click="printForecastCartons"/)
assert.match(view, /仓储转运客户箱唛/) assert.match(view, /cartonMarks: item.generatedCartonMarks/)
assert.match(view, /@click="printTransferDraftCartonMarks"/)
assert.match(view, /打印唛头/)
assert.match(view, /单次最多打印 500 张箱唛/)
}) })
test('仓储转运换标资料按步骤分组展示', () => { test('仓储转运换标资料按步骤分组展示', () => {
@@ -145,7 +140,7 @@ test('仓储转运换标总文件与明细模板在桌面端左右排列', () =>
}) })
test('上门提货不提交物流号,需要换标时随转运单登记申请', () => { test('上门提货不提交物流号,需要换标时随转运单登记申请', () => {
assert.match(view, /trackingNo:\s*form\.deliveryMethod === 'CUSTOMER_DELIVERY'\s*\?[^:]+:\s*undefined/) assert.match(view, /trackingNo:\s*!inventoryTransfer\.value && form\.deliveryMethod === 'CUSTOMER_DELIVERY'\s*\?[^:]+:\s*undefined/)
assert.match(view, /relabelItems: form\.relabel/) assert.match(view, /relabelItems: form\.relabel/)
assert.match(view, /form\.deliveryMethod === 'CUSTOMER_DELIVERY'.*物流跟踪号/s) assert.match(view, /form\.deliveryMethod === 'CUSTOMER_DELIVERY'.*物流跟踪号/s)
assert.match(view, /提货联系人/) assert.match(view, /提货联系人/)
@@ -155,9 +150,8 @@ test('上门提货不提交物流号,需要换标时随转运单登记申请',
assert.match(view, /form\.pickupPhone/) assert.match(view, /form\.pickupPhone/)
assert.match(view, /form\.relabelContact/) assert.match(view, /form\.relabelContact/)
assert.match(view, /form\.relabelPhone/) assert.match(view, /form\.relabelPhone/)
assert.match(view, /选择海外仓后自动带出,也可手动填写/) assert.match(view, /pickupContactName: !inventoryTransfer\.value && form\.deliveryMethod === 'WAREHOUSE_PICKUP' \? form\.pickupContact : undefined/)
assert.match(view, /pickupContactName: form\.deliveryMethod === 'WAREHOUSE_PICKUP' \? form\.pickupContact : undefined/) assert.match(view, /pickupContactPhone: !inventoryTransfer\.value && form\.deliveryMethod === 'WAREHOUSE_PICKUP' \? form\.pickupPhone : undefined/)
assert.match(view, /pickupContactPhone: form\.deliveryMethod === 'WAREHOUSE_PICKUP' \? form\.pickupPhone : undefined/)
assert.match(view, /relabelContactName: form\.relabel \? form\.relabelContact/) assert.match(view, /relabelContactName: form\.relabel \? form\.relabelContact/)
assert.match(api, /pickupContactName\?: string; pickupContactPhone\?: string/) assert.match(api, /pickupContactName\?: string; pickupContactPhone\?: string/)
}) })
@@ -174,7 +168,7 @@ test('仓储转运期望发货时间可选并在订单概览回填发货时间',
assert.doesNotMatch(view, /预计发货时间/) assert.doesNotMatch(view, /预计发货时间/)
assert.match(view, /期望发货时间/) assert.match(view, /期望发货时间/)
assert.match(view, /v-model="form\.estimatedShipAt"/) assert.match(view, /v-model="form\.estimatedShipAt"/)
assert.match(view, /v-model="form\.estimatedShipAt"[^>]+placeholder="选填"/) assert.match(view, /v-model="form\.estimatedShipAt"[^>]+placeholder=""/)
assert.doesNotMatch(view, /!form\.estimatedShipAt/) assert.doesNotMatch(view, /!form\.estimatedShipAt/)
assert.match(view, /estimatedShipAt: form\.estimatedShipAt/) assert.match(view, /estimatedShipAt: form\.estimatedShipAt/)
assert.match(view, /<span>期望发货时间<\/span><strong>\{\{ formatDateTime\(selectedDetail\?\.estimatedShipAt\) \}\}<\/strong>/) assert.match(view, /<span>期望发货时间<\/span><strong>\{\{ formatDateTime\(selectedDetail\?\.estimatedShipAt\) \}\}<\/strong>/)
@@ -210,7 +204,7 @@ test('仓储转运列表展示换标单号、换标状态并为两类状态着
test('仓储转运详情订单概览使用详情接口命名字段回填', () => { test('仓储转运详情订单概览使用详情接口命名字段回填', () => {
assert.match(view, /v-else-if="props\.service === 'transfer'" class="warehouse-detail-grid warehouse-transfer-overview-grid"/) assert.match(view, /v-else-if="props\.service === 'transfer'" class="warehouse-detail-grid warehouse-transfer-overview-grid"/)
assert.doesNotMatch(view, /入库箱数/) assert.doesNotMatch(view, /入库箱数/)
assert.match(view, /'转运单号', '箱数', '海外仓'/) assert.match(view, /'转运单号', '预计箱数', '海外仓'/)
for (const field of ['transferNo', 'packageCount', 'operatingWarehouseId', 'deliveryMethod', 'needRelabel', 'relabelNo', 'status', 'createdAt']) { for (const field of ['transferNo', 'packageCount', 'operatingWarehouseId', 'deliveryMethod', 'needRelabel', 'relabelNo', 'status', 'createdAt']) {
assert.match(view, new RegExp(`selectedDetail\\?\\.${field}`)) assert.match(view, new RegExp(`selectedDetail\\?\\.${field}`))
} }
@@ -258,7 +252,8 @@ test('贴标申请详情使用紧凑订单概览并中文展示换标状态', ()
test('仓储转运详情按接口具名字段展示订单概览', () => { test('仓储转运详情按接口具名字段展示订单概览', () => {
const overview = view.split('<h3>订单概览</h3>')[1]?.split('warehouse-transfer-cargo-card')[0] || '' const overview = view.split('<h3>订单概览</h3>')[1]?.split('warehouse-transfer-cargo-card')[0] || ''
assert.match(overview, /v-if="props\.service === 'transfer'"/) assert.match(overview, /v-if="props\.service === 'transfer'"/)
assert.match(overview, /selectedDetail\?\.transferNo/) assert.doesNotMatch(overview, /<span>转运单号<\/span>/)
assert.match(view.split('<header class="warehouse-detail-header">')[1]?.split('</header>')[0] || '', /selectedDetail\?\.transferNo/)
assert.match(overview, /selectedDetail\?\.packageCount \?\? '—'/) assert.match(overview, /selectedDetail\?\.packageCount \?\? '—'/)
assert.match(overview, /warehouseDisplay\(selectedDetail\?\.operatingWarehouseId\)/) assert.match(overview, /warehouseDisplay\(selectedDetail\?\.operatingWarehouseId\)/)
assert.match(overview, /selectedDetail\?\.destinationWarehouseName \|\| warehouseDisplay\(selectedDetail\?\.destinationWarehouseCode \|\| selectedDetail\?\.fbaWarehouseCode\)/) assert.match(overview, /selectedDetail\?\.destinationWarehouseName \|\| warehouseDisplay\(selectedDetail\?\.destinationWarehouseCode \|\| selectedDetail\?\.fbaWarehouseCode\)/)
@@ -271,27 +266,27 @@ test('PDA 打托完成后客户可从列表或详情确认并查看实测数据'
assert.match(view, /item\.__status === 'WAIT_CUSTOMER_CONFIRMATION'/) assert.match(view, /item\.__status === 'WAIT_CUSTOMER_CONFIRMATION'/)
assert.match(view, /confirmTransferFromList\(item\['0'\]\)/) assert.match(view, /confirmTransferFromList\(item\['0'\]\)/)
assert.match(view, /selectedDetail\?\.status === 'WAIT_CUSTOMER_CONFIRMATION'/) assert.match(view, /selectedDetail\?\.status === 'WAIT_CUSTOMER_CONFIRMATION'/)
assert.match(view, /PDA 打托实测数据/) assert.match(view, /托盘实测数据/)
for (const label of ['托盘号', '库位', '箱数', '长 × 宽 × 高(cm)', '毛重(kg)', '体积(m³)', '完成时间']) assert.equal(view.includes(label), true) for (const label of ['托盘号', '库位', '箱数', 'SKU 汇总', '毛重(kg)', '体积(m³)', '完成时间']) assert.equal(view.includes(label), true)
assert.match(view, /pallet\.warehouseLocationCode/) assert.match(view, /pallet\.warehouseLocationCode/)
assert.match(view, /pallet\.cartonCount/) assert.match(view, /palletCartons\(pallet\)\.length/)
assert.match(view, /pallet\.grossWeightKg/) assert.match(view, /pallet\.grossWeightKg/)
assert.match(view, /pallet\.volumeCbm/) assert.match(view, /pallet\.volumeCbm/)
assert.doesNotMatch(view, /pallet\.items/) assert.doesNotMatch(view, /pallet\.items/)
}) })
test('仓储转运详情按订单概览、PDA 实测数据、货物明细排序并放大测量照片', () => { test('仓储转运详情按订单概览、货物预报、PDA 实测数据排序并放大测量照片', () => {
const detailStart = view.indexOf('<header class="warehouse-detail-header">') const detailStart = view.indexOf('<header class="warehouse-detail-header">')
const detailSource = view.slice(detailStart) const detailSource = view.slice(detailStart)
const overviewIndex = detailSource.indexOf('<h3>订单概览</h3>') const overviewIndex = detailSource.indexOf('<h3>订单概览</h3>')
const measurementIndex = detailSource.indexOf('<h3>PDA 打托实测数据</h3>') const measurementIndex = detailSource.indexOf('<h3>托盘实测数据</h3>')
const cargoIndex = detailSource.indexOf('<h3>货物明细</h3>') const cargoIndex = detailSource.indexOf('<h3>预报与实际签收</h3>')
assert.ok(overviewIndex >= 0 && overviewIndex < measurementIndex) assert.ok(overviewIndex >= 0 && overviewIndex < measurementIndex)
assert.ok(measurementIndex < cargoIndex) assert.ok(cargoIndex < measurementIndex)
assert.match(view, /class="warehouse-photo-grid warehouse-measurement-photo-grid"/) assert.match(view, /class="warehouse-photo-grid warehouse-measurement-photo-grid"/)
assert.match(view, /class="warehouse-photo-item warehouse-measurement-photo-item"/) assert.match(view, /class="warehouse-photo-item warehouse-measurement-photo-item"/)
assert.match(view, /warehouse-measurement-photo-grid\{flex:1;grid-template-columns:repeat\(auto-fill,minmax\(240px,1fr\)\)\}/) assert.match(view, /warehouse-measurement-photo-grid\{flex:1;grid-template-columns:repeat\(auto-fill,minmax\(240px,1fr\)\)\}/)
assert.match(view, /warehouse-measurement-photo-item\{width:100%;height:180px\}/) assert.match(view, /warehouse-measurement-photo-item\{width:100%;height:120px\}/)
}) })
test('仓储转运详情自动加载 PDA 测量照片并释放 Blob URL', () => { test('仓储转运详情自动加载 PDA 测量照片并释放 Blob URL', () => {
@@ -300,7 +295,7 @@ test('仓储转运详情自动加载 PDA 测量照片并释放 Blob URL', () =>
assert.match(view, /measurementPhotos\?: TransferMeasurementPhoto\[\]/) assert.match(view, /measurementPhotos\?: TransferMeasurementPhoto\[\]/)
assert.match(view, /fileId: string \| number/) assert.match(view, /fileId: string \| number/)
assert.match(view, /if \(props\.service === 'transfer'\) void loadMeasurementPhotos\(\)/) assert.match(view, /if \(props\.service === 'transfer'\) void loadMeasurementPhotos\(\)/)
assert.match(view, /测量打托现场照片/) assert.match(view, /v-if="selectedDetail\?\.measurementPhotos\?\.length" class="warehouse-evidence warehouse-measurement-evidence"/)
assert.match(view, /:preview-src-list="measurementPhotoPreviewUrls"/) assert.match(view, /:preview-src-list="measurementPhotoPreviewUrls"/)
assert.match(view, /加载失败,点击重试/) assert.match(view, /加载失败,点击重试/)
assert.match(view, /URL\.createObjectURL\(blob\)/) assert.match(view, /URL\.createObjectURL\(blob\)/)
@@ -327,8 +322,9 @@ test('仓储转运可在新建页直接提交,也可保存草稿后编辑提
assert.match(view, /v-if="props\.service === 'transfer'"[^>]*type="primary"[^>]*native-type="submit"[^>]*>提交订单/) assert.match(view, /v-if="props\.service === 'transfer'"[^>]*type="primary"[^>]*native-type="submit"[^>]*>提交订单/)
assert.match(view, /await updateTransfer\(editingTransferNo\.value, payload\)/) assert.match(view, /await updateTransfer\(editingTransferNo\.value, payload\)/)
assert.match(view, /await submitTransfer\(transferNo\)/) assert.match(view, /await submitTransfer\(transferNo\)/)
assert.match(view, /<form [^>]*@submit\.prevent="submit\('submit'\)"/) assert.match(view, /const isLabelingCreate = computed\(\(\) => props.service === 'labeling' && mode.value === 'create'\)/)
assert.match(view, /selectedDetail\?\.status !== 'DRAFT'[^>]*[\s\S]*?printTransferCartons[^>]*[\s\S]*?打印箱唛/) assert.match(view, /<component :is="isServiceCreate \? ElForm : 'form'"[^>]*@submit\.prevent="submit\('submit'\)"/)
assert.match(view, /selectedDetail\?\.status !== 'DRAFT'[^>]*[\s\S]*?printTransferCartons[^>]*[\s\S]*?打印预报箱唛/)
assert.doesNotMatch(view, /row\.__status !== 'DRAFT'.*printTransferCartons\(row\['0'\]\)/s) assert.doesNotMatch(view, /row\.__status !== 'DRAFT'.*printTransferCartons\(row\['0'\]\)/s)
assert.doesNotMatch(view, /selectedDetail\?\.status === 'DRAFT'[^>]*[\s\S]*?>提交订单/) assert.doesNotMatch(view, /selectedDetail\?\.status === 'DRAFT'[^>]*[\s\S]*?>提交订单/)
assert.match(view, /native-type="button"[^>]*:loading="saving"[^>]*@click="submit\('draft'\)"/) assert.match(view, /native-type="button"[^>]*:loading="saving"[^>]*@click="submit\('draft'\)"/)
@@ -339,7 +335,7 @@ test('仓储转运可在新建页直接提交,也可保存草稿后编辑提
test('编辑仓储转运时加载库存转运来源候选', () => { test('编辑仓储转运时加载库存转运来源候选', () => {
assert.match(view, /async function loadTransferInventoryCandidates\(warehouseId: string\)/) assert.match(view, /async function loadTransferInventoryCandidates\(warehouseId: string\)/)
assert.match(view, /if \(props\.service === 'transfer' && form\.warehouse\) \{[\s\S]*await loadTransferInventoryCandidates\(form\.warehouse\)/) assert.match(view, /if \(props\.service === 'transfer' && form\.warehouse\) \{[\s\S]*await loadTransferInventoryCandidates\(form\.warehouse\)/)
assert.match(view, /transferInventoryCandidates\.value = await listRelabelInventoryCandidates\(warehouseId\)/) assert.match(view, /transferInventoryCandidates\.value = \(await listRelabelInventoryCandidates\(warehouseId\)\)\.filter/)
assert.match(view, /transferInventoryOptions\.value\.some\(\(option\) => option\.value === sourceInboundCode\)/) assert.match(view, /transferInventoryOptions\.value\.some\(\(option\) => option\.value === sourceInboundCode\)/)
assert.match(view, /selectedTransferInventory\.value = sourceInboundCode/) assert.match(view, /selectedTransferInventory\.value = sourceInboundCode/)
assert.match(view, /detail\.sourceOrders \|\| \[\]/) assert.match(view, /detail\.sourceOrders \|\| \[\]/)
@@ -361,9 +357,51 @@ test('转运贴标单在PDA确认库存前不误报附件上传失败', () => {
test('仓储转运基础货物不强制 SKU 和中文品名,只换箱唛不强制旧 SKU', () => { test('仓储转运基础货物不强制 SKU 和中文品名,只换箱唛不强制旧 SKU', () => {
assert.match(view, /商品 SKU\{\{ props\.service === 'transfer' \? '' : ' \*' \}\}/) assert.match(view, /商品 SKU\{\{ props\.service === 'transfer' \? '' : ' \*' \}\}/)
assert.match(view, /中文品名\{\{ props\.service === 'transfer' \? '' : ' \*' \}\}/) assert.match(view, /中文品名\{\{ props\.service === 'transfer' \? '' : ' \*' \}\}/)
assert.match(view, /props\.service === 'transfer' \? '选填' : '请输入商品 SKU'/) assert.match(view, /props\.service === 'relabel' \? '请输入商品 SKU' : ''/)
assert.match(view, /v-if="labelingMode === 'carton'"[^\n]+<th>旧 SKU<\/th>/) assert.match(view, /v-if="labelingMode === 'carton'"[^\n]+<th>旧 SKU<\/th>/)
assert.match(view, /labelingMode\.value !== 'carton' && \(!row\.sku\.trim\(\) \|\| !row\.newSkuCode\.trim\(\)\)/) assert.match(view, /labelingMode\.value !== 'carton' && \(!row\.sku\.trim\(\) \|\| !row\.newSkuCode\.trim\(\)\)/)
assert.match(api, /skuCode\?: string; productNameZh\?: string/) assert.match(api, /skuCode\?: string; productNameZh\?: string/)
assert.match(api, /originalSku\?: string/) assert.match(api, /originalSku\?: string/)
}) })
test('SKU 件数和预计箱数独立提交,签收展示实际清点箱数', () => {
assert.match(view, /quantity: item.quantity, packageCount: Number\(item.expectedPackageCount\)/)
assert.match(view, /sum \+ Number\(item.expectedPackageCount \|\| 0\)/)
assert.match(view, /v-model="row.expectedPackageCount"/)
assert.match(view, /Number.isSafeInteger\(row.quantity\)/)
assert.match(view, /Number.isSafeInteger\(row.expectedPackageCount\)/)
assert.match(view, /\['COUNTED', 'DISCARD_PENDING', 'DISCARDED', 'SHIPPED'\]\.includes\(carton.status\)/)
assert.match(view, /实际签收箱数/)
})
test('转运客户详情保留预报并显示实际签收箱内明细和托盘汇总', () => {
for (const label of ['预报数量(件)', '预报 SKU 种数', '签收箱号明细', '查看箱号明细', 'SKU 汇总', '毛重(kg)', '体积(m³)']) assert.ok(view.includes(label), label)
assert.match(view, /countedTransferCartons\(\)\.filter\(\(carton\) => pallet.id != null/)
assert.match(view, /String\(carton.transferPalletId\) === String\(pallet.id\)/)
assert.match(view, /carton.transferItemId != null && String\(item.id\) === String\(carton.transferItemId\)/)
assert.match(view, /@click="showTransferCartons = true"/)
assert.match(view, /<el-dialog v-model="showTransferCartons"[\s\S]*?<el-collapse-item v-for="carton in countedTransferCartons\(\)"/)
assert.doesNotMatch(view, /warehouse-transfer-receipt-summary|expandedTransferCartons/)
const receiptSection = view.slice(view.indexOf('warehouse-transfer-received-card', view.indexOf('<header class="warehouse-detail-header">')), view.indexOf('v-if="props.service === \'transfer\' && selectedDetail?.needRelabel"'))
assert.doesNotMatch(receiptSection.split('<el-dialog')[0], /<table|<el-table|<el-collapse/)
assert.match(view, /暂无签收箱号/)
assert.doesNotMatch(view, /<td>\{\{ \[pallet.lengthCm/)
})
test('预报实收同区对照、托盘卡片换行、签收按钮紧邻标题', () => {
const start = view.indexOf('class="warehouse-card warehouse-form-section warehouse-transfer-cargo-card"', view.indexOf('<header class="warehouse-detail-header">'))
const section = view.slice(start, view.indexOf('warehouse-transfer-received-card', start))
assert.ok(section.includes('预报与实际签收'))
assert.ok(section.includes('托盘实测数据'))
assert.ok(section.includes('receivedItemQuantity(item.id)'))
assert.ok(section.includes('receivedItemCartons(item.id).length'))
assert.ok(section.includes('class="warehouse-transfer-pallet-card"'))
assert.ok(section.includes('class="warehouse-transfer-pallet-sku"'))
assert.doesNotMatch(section, /打印箱唛/)
const receipt = view.slice(view.indexOf('warehouse-transfer-received-card', start)).split('<el-dialog')[0]
assert.ok(view.includes('打印预报箱唛')); assert.ok(view.includes('增加预报箱数'))
assert.ok(receipt.includes('查看箱号明细'))
assert.match(view, /warehouse-section-heading h3\{flex:0 0 auto/)
})
+24
View File
@@ -0,0 +1,24 @@
# Client 系统页模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/system/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`。
- 只有 `views/ForbiddenView.vue`(403 无权限页)与 `routes.ts`;不承载业务。
## 页面与入口
| 目标 | 页面/入口 | 说明 |
|---|---|---|
| 无权限提示页 | `views/ForbiddenView.vue` | 路由守卫或接口 403 后跳转 |
| 系统页路由 | `routes.ts` | 由 `../../router/index.ts` 装配 |
## 关键边界
- 403 页只做提示与返回入口,不暴露权限码、内部角色或接口细节。
- 不在此模块新增业务页面或全局状态。
- 权限判断仍在服务端与 `core/access`,页面不补前端鉴权分支。
## 验证
- 定向:`pnpm test src/modules/system/<目标测试>`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+30
View File
@@ -0,0 +1,30 @@
# Client 企业设置模块指引
## 路径基准与读取顺序
- 本文件适用于 `src/modules/tenant-management/`,代码路径相对本目录;应用公共规则见 `../../../AGENTS.md`,层级与权限语义见 `../../../docs/平台客户层级与权限契约.md`。
- 本模块承载企业资料、成员、角色与权限(`company/profile`、`organization/*`);账号与登录标识归 `backend auth/`,接入侧实现归 `backend iam/`。
- 模块对外只暴露 `public.ts` 与 `contracts.ts`,其他模块不得穿透内部 `views/`、`store/`。
## 页面与入口
| 目标 | 页面/路由 | API 与后端 |
|---|---|---|
| 企业资料、资质上传与状态 | `views/CompanyProfileView.vue`、`utils/qualificationFile.ts`、`utils/qualificationStatus.ts`;`company/profile` | `api/merchantIam.ts`;`iam/`、`file/` |
| 企业成员管理 | `views/MembersView.vue`;`organization/members` | 页面经 `store/tenantAdministration.ts` → `api/merchantIam.ts`;`iam/`、`auth/` |
| 企业角色 | `views/RolesView.vue`;`organization/roles` | 页面经 `store/tenantAdministration.ts` → `api/merchantIam.ts`;`iam/` |
| 角色权限分配 | `views/PermissionsView.vue`;`organization/permissions` | 页面经 `store/tenantAdministration.ts` → `api/merchantIam.ts`;权限码常量见 `contracts.ts` |
| 跨页状态与稳定契约 | `store/tenantAdministration.ts`、`contracts.ts`、`public.ts` | 服务端 DTO |
## 关键边界
- 企业资料只修改 `contactPhone` 等企业联系信息,不提交或回填成员登录手机号;两者独立维护。
- 成员登录手机号可选;修改时由 IAM/Auth 同步并撤销该账号现有会话,前端不互相回填或联动提交。
- 审核必填资质仅营业执照与统一社会信用代码;法人身份证选填,可在已有营业执照后单独补传或替换。
- 企业成员、角色与权限只能管理当前企业范围;前端隐藏不是安全控制,服务端必须重复校验租户与权限。
- 认证与会话统一经 `../../api/http.ts`、`../../api/session.ts`;页面不读写 Token,不自行处理 401 刷新。
## 验证
- 定向:`pnpm test src/modules/tenant-management/<目标测试>`;成员或权限字段变化同时运行 `pnpm typecheck`。
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
+2 -2
View File
@@ -57,7 +57,6 @@ export const TENANT_PERMISSION_GROUPS: readonly TenantPermissionGroup[] = [
{ code: 'order:first-leg:submit', label: '提交订单', description: '提交草稿进入平台审核' }, { code: 'order:first-leg:submit', label: '提交订单', description: '提交草稿进入平台审核' },
{ code: 'order:first-leg:cancel', label: '取消订单', description: '在允许的状态下取消订单' }, { code: 'order:first-leg:cancel', label: '取消订单', description: '在允许的状态下取消订单' },
{ code: 'merchant:warehouse:delivery:list', label: '查看派送单', description: '分页查询本企业海外仓派送单' }, { code: 'merchant:warehouse:delivery:list', label: '查看派送单', description: '分页查询本企业海外仓派送单' },
{ code: 'merchant:warehouse:delivery:create', label: '创建派送单', description: '从排车单创建海外仓派送单' },
], ],
}, },
{ {
@@ -75,6 +74,7 @@ export const TENANT_PERMISSION_GROUPS: readonly TenantPermissionGroup[] = [
{ code: 'merchant:overseas-warehouse:transfer:confirm', label: '确认转运实测', description: '确认仓库回传的箱数、尺寸、重量和打托数据' }, { code: 'merchant:overseas-warehouse:transfer:confirm', label: '确认转运实测', description: '确认仓库回传的箱数、尺寸、重量和打托数据' },
{ code: 'merchant:overseas-warehouse:discard:list', label: '查看货物废弃', description: '查看本企业货物废弃申请列表和详情' }, { code: 'merchant:overseas-warehouse:discard:list', label: '查看货物废弃', description: '查看本企业货物废弃申请列表和详情' },
{ code: 'merchant:overseas-warehouse:discard:create', label: '创建货物废弃', description: '使用本企业可用库存创建废弃申请' }, { code: 'merchant:overseas-warehouse:discard:create', label: '创建货物废弃', description: '使用本企业可用库存创建废弃申请' },
{ code: 'merchant:overseas-warehouse:discard:confirm', label: '确认废弃完成', description: '核对本企业废弃现场照片并确认完结' },
{ code: 'merchant:overseas-warehouse:discard:cancel', label: '取消货物废弃', description: '取消本企业尚未审核的废弃申请' }, { code: 'merchant:overseas-warehouse:discard:cancel', label: '取消货物废弃', description: '取消本企业尚未审核的废弃申请' },
{ code: 'merchant:overseas-warehouse:return-order:list', label: '查看退货预报', description: '查看本企业退货预报和仓库签收结果' }, { code: 'merchant:overseas-warehouse:return-order:list', label: '查看退货预报', description: '查看本企业退货预报和仓库签收结果' },
{ code: 'merchant:overseas-warehouse:return-order:create', label: '创建退货预报', description: '创建本企业退货 SKU 和数量预报' }, { code: 'merchant:overseas-warehouse:return-order:create', label: '创建退货预报', description: '创建本企业退货 SKU 和数量预报' },
@@ -144,7 +144,6 @@ export const FRONTEND_TO_MERCHANT_PERMISSION_CODES: Readonly<Record<string, read
'order:first-leg:submit': ['merchant:order:submit'], 'order:first-leg:submit': ['merchant:order:submit'],
'order:first-leg:cancel': ['merchant:order:cancel'], 'order:first-leg:cancel': ['merchant:order:cancel'],
'merchant:warehouse:delivery:list': ['merchant:warehouse:delivery:list'], 'merchant:warehouse:delivery:list': ['merchant:warehouse:delivery:list'],
'merchant:warehouse:delivery:create': ['merchant:warehouse:delivery:create'],
'merchant:warehouse:inbound:list': ['merchant:warehouse:inbound:list'], 'merchant:warehouse:inbound:list': ['merchant:warehouse:inbound:list'],
'merchant:overseas-warehouse:return-inventory:list': ['merchant:overseas-warehouse:return-inventory:list'], 'merchant:overseas-warehouse:return-inventory:list': ['merchant:overseas-warehouse:return-inventory:list'],
'merchant:overseas-warehouse:last-mile-order:list': ['merchant:overseas-warehouse:last-mile-order:list'], 'merchant:overseas-warehouse:last-mile-order:list': ['merchant:overseas-warehouse:last-mile-order:list'],
@@ -157,6 +156,7 @@ export const FRONTEND_TO_MERCHANT_PERMISSION_CODES: Readonly<Record<string, read
'merchant:overseas-warehouse:transfer:confirm': ['merchant:overseas-warehouse:transfer:confirm'], 'merchant:overseas-warehouse:transfer:confirm': ['merchant:overseas-warehouse:transfer:confirm'],
'merchant:overseas-warehouse:discard:list': ['merchant:overseas-warehouse:discard:list'], 'merchant:overseas-warehouse:discard:list': ['merchant:overseas-warehouse:discard:list'],
'merchant:overseas-warehouse:discard:create': ['merchant:overseas-warehouse:discard:create'], 'merchant:overseas-warehouse:discard:create': ['merchant:overseas-warehouse:discard:create'],
'merchant:overseas-warehouse:discard:confirm': ['merchant:overseas-warehouse:discard:confirm'],
'merchant:overseas-warehouse:discard:cancel': ['merchant:overseas-warehouse:discard:cancel'], 'merchant:overseas-warehouse:discard:cancel': ['merchant:overseas-warehouse:discard:cancel'],
'merchant:overseas-warehouse:return-order:list': ['merchant:overseas-warehouse:return-order:list'], 'merchant:overseas-warehouse:return-order:list': ['merchant:overseas-warehouse:return-order:list'],
'merchant:overseas-warehouse:return-order:create': ['merchant:overseas-warehouse:return-order:create'], 'merchant:overseas-warehouse:return-order:create': ['merchant:overseas-warehouse:return-order:create'],
+7 -19
View File
@@ -52,7 +52,7 @@ test('keeps standalone business pages at the client sidebar root', () => {
{ title: '首页', children: undefined }, { title: '首页', children: undefined },
{ {
title: '订单中心', title: '订单中心',
children: ['头程订单', '入库订单', '派送订单', '海外采购', '美国本土卡', '美本土散板'], children: ['头程订单', '海外采购', '美国本土卡', '美本土散板'],
}, },
{ title: '报关资料', children: undefined }, { title: '报关资料', children: undefined },
{ title: '船期价格', children: undefined }, { title: '船期价格', children: undefined },
@@ -88,8 +88,6 @@ test('flattens visible leaves with unique paths', () => {
assert.deepEqual(paths, [ assert.deepEqual(paths, [
'/', '/',
'/orders/first-leg', '/orders/first-leg',
'/orders/inbound',
'/orders/delivery',
'/cross-border/procurement', '/cross-border/procurement',
'/cross-border/domestic-trucking', '/cross-border/domestic-trucking',
'/cross-border/pallet-shipping', '/cross-border/pallet-shipping',
@@ -121,22 +119,10 @@ test('filters inaccessible leaves and empty navigation groups', () => {
assert.equal(getFirstAccessiblePath([]), '/forbidden') assert.equal(getFirstAccessiblePath([]), '/forbidden')
}) })
test('exposes active inbound and delivery queries only with their existing read permissions', () => { test('omits inbound and delivery entries from the customer sidebar', () => {
const deliveryOnly = ['merchant:warehouse:delivery:list'] const permissions = ['merchant:warehouse:delivery:list', 'merchant:warehouse:inbound:list']
const inboundOnly = ['merchant:warehouse:inbound:list'] assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation, permissions)), [])
assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation, deliveryOnly)) assert.equal(getFirstAccessiblePath(permissions), '/forbidden')
.map(({ title, path }) => ({ title, path })), [{ title: '派送订单', path: '/orders/delivery' }])
assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation, inboundOnly))
.map(({ title, path }) => ({ title, path })), [{ title: '入库订单', path: '/orders/inbound' }])
assert.equal(getFirstAccessiblePath(deliveryOnly), '/orders/delivery')
assert.equal(getFirstAccessiblePath(inboundOnly), '/orders/inbound')
assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation,
['merchant:warehouse:delivery:create'])), [])
assert.deepEqual(getRouteBreadcrumbs('/orders/delivery/DL-1', '派送单详情'), [
{ title: '首页', path: '/' }, { title: '订单中心' },
{ title: '派送订单', path: '/orders/delivery' }, { title: '派送单详情' },
])
assert.deepEqual(getNavigationParentKeys(clientNavigation, '/orders/delivery'), ['order-center'])
}) })
test('excludes entries marked for manual hiding without affecting other visible items', () => { test('excludes entries marked for manual hiding without affecting other visible items', () => {
@@ -383,6 +369,8 @@ test('exposes customer business lists and keeps utility routes outside navigatio
] ]
const hiddenActivePaths = new Set([ const hiddenActivePaths = new Set([
'orders/inbound',
'orders/delivery',
'first-leg/quick-order', 'first-leg/quick-order',
'overseas-warehouse/return-inventory', 'overseas-warehouse/return-inventory',
'overseas-warehouse/return-cartons', 'overseas-warehouse/return-cartons',
-2
View File
@@ -52,8 +52,6 @@ export const clientNavigation: ClientNavigationNode[] = [
icon: ClipboardList, icon: ClipboardList,
children: [ children: [
requireLeaf('first-leg-orders', '头程订单'), requireLeaf('first-leg-orders', '头程订单'),
requireLeaf('orders-inbound', '入库订单'),
requireLeaf('orders-delivery', '派送订单'),
requireLeaf('cross-border-procurement'), requireLeaf('cross-border-procurement'),
requireLeaf('cross-border-domestic-trucking'), requireLeaf('cross-border-domestic-trucking'),
requireLeaf('cross-border-pallet-shipping'), requireLeaf('cross-border-pallet-shipping'),