Compare commits
190
Commits
0fa80874bc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b5525ce49 | ||
|
|
2c98d121ca | ||
|
|
d1eeaab067 | ||
|
|
3ffa706b89 | ||
|
|
22baa5b5c0 | ||
|
|
9f47b1b276 | ||
|
|
7adb97d145 | ||
|
|
24439b15a3 | ||
|
|
7842791c10 | ||
|
|
78893f1144 | ||
|
|
20858dbe33 | ||
|
|
99922bbc34 | ||
|
|
c38a7384aa | ||
|
|
5594e8fa02 | ||
|
|
f851f5667d | ||
|
|
9b1dec75dd | ||
|
|
b52ad0c3e3 | ||
|
|
64697276ec | ||
|
|
1e26ddad4b | ||
|
|
8abc058a65 | ||
|
|
5036593195 | ||
|
|
de31c14695 | ||
|
|
513bbe2bb0 | ||
|
|
d910b24755 | ||
|
|
666be8a80d | ||
|
|
33db45f1c6 | ||
|
|
dcdaf1438c | ||
|
|
17580fb0a2 | ||
|
|
34650b06df | ||
|
|
04a06668a1 | ||
|
|
f1436f2889 | ||
|
|
82dcc5a14d | ||
|
|
9a24e0c83d | ||
|
|
07590dd4d3 | ||
|
|
88c9ff2cb5 | ||
|
|
f7dd39c7ed | ||
|
|
7e68d978dd | ||
|
|
4b5113a690 | ||
|
|
e0726444cc | ||
|
|
fbaa48337d | ||
|
|
af3cacd2db | ||
|
|
a674ec2435 | ||
|
|
8c064cfb0d | ||
|
|
d1e9002bef | ||
|
|
ded625f2a1 | ||
|
|
3d3ca053a6 | ||
|
|
3d73f1c82d | ||
|
|
bb674eb3a0 | ||
|
|
c79b5492c6 | ||
|
|
9b58c12012 | ||
|
|
d89830fe41 | ||
|
|
4d7b6eb6dc | ||
|
|
5b320a3293 | ||
|
|
63e169b051 | ||
|
|
f5a6c7fd88 | ||
|
|
d67da9af82 | ||
|
|
d28408f678 | ||
|
|
90ef9893f3 | ||
|
|
aa68e93b08 | ||
|
|
c168afa1e1 | ||
|
|
6355bb69df | ||
|
|
15015d8bfc | ||
|
|
bd8f9433ed | ||
|
|
4db8700817 | ||
|
|
c72c819f95 | ||
|
|
a0e9ad808b | ||
|
|
cd06e264ff | ||
|
|
aaab5041f9 | ||
|
|
700074e983 | ||
|
|
06f91c8b91 | ||
|
|
6cb9b91435 | ||
|
|
6d0eb2a5f3 | ||
|
|
15b51b6139 | ||
|
|
db44d24eb4 | ||
|
|
3692f9d27f | ||
|
|
90e1e646ec | ||
|
|
5751973c83 | ||
|
|
d7f8365ecc | ||
|
|
3cdd14a521 | ||
|
|
509dc677cb | ||
|
|
c0b151bc15 | ||
|
|
639b1ae22c | ||
|
|
33d86d2a64 | ||
|
|
9891ac3e29 | ||
|
|
d2bbd5024b | ||
|
|
07ba9fcb7c | ||
|
|
985cab06b0 | ||
|
|
2aa20b7172 | ||
|
|
c63fb704a2 | ||
|
|
d39c1f4ea7 | ||
|
|
bc84686658 | ||
|
|
62cf7829d3 | ||
|
|
0be4088fa9 | ||
|
|
8b0decbaca | ||
|
|
7759c7e9f3 | ||
|
|
19f060727b | ||
|
|
47385d46f2 | ||
|
|
a853b1e0c2 | ||
|
|
ffa2b82c73 | ||
|
|
b7fcc14e59 | ||
|
|
b3f78207b8 | ||
|
|
3703d0a677 | ||
|
|
e139c5c87b | ||
|
|
f0777ba2db | ||
|
|
a0736239e4 | ||
|
|
40f6753cca | ||
|
|
78315873d7 | ||
|
|
fc32d0b390 | ||
|
|
1fe2cada15 | ||
|
|
8e5fa0bebc | ||
|
|
5c53eba31b | ||
|
|
b1f538b3ac | ||
|
|
81a2e6473d | ||
|
|
5f963f326e | ||
|
|
e564353a80 | ||
|
|
187deb5047 | ||
|
|
dae119a1e8 | ||
|
|
c06c105836 | ||
|
|
c3a213d039 | ||
|
|
2f1babae45 | ||
|
|
1bd1664e9c | ||
|
|
1e707f613c | ||
|
|
605388e666 | ||
|
|
c115f1c504 | ||
|
|
162e9a2336 | ||
|
|
d19b1b2f8c | ||
|
|
3c36c55809 | ||
|
|
ff0754810a | ||
|
|
fce1356cb6 | ||
|
|
706e3e871e | ||
|
|
6564d41285 | ||
|
|
6abb8b7388 | ||
|
|
151106250f | ||
|
|
d45cd19361 | ||
|
|
fa9bfd5f97 | ||
|
|
a427aca5c3 | ||
|
|
ffbe3480a8 | ||
|
|
32c5241a01 | ||
|
|
9e133779ab | ||
|
|
214fe4ff50 | ||
|
|
225e3b0e71 | ||
|
|
f24674dddc | ||
|
|
b03cb1dd3d | ||
|
|
e681eadfcd | ||
|
|
21be160668 | ||
|
|
8fd406331a | ||
|
|
8acfbb1074 | ||
|
|
bea42ccca3 | ||
|
|
3e2847814a | ||
|
|
5ebfa71248 | ||
|
|
983df11081 | ||
|
|
8c8fdbc2ab | ||
|
|
a2934aad9d | ||
|
|
146dee0587 | ||
|
|
23fd82632b | ||
|
|
20ea6adc6f | ||
|
|
34cdf4fc4f | ||
|
|
7eda66bc4d | ||
|
|
8aed079d02 | ||
|
|
58c4be7fc0 | ||
|
|
682d75f201 | ||
|
|
b0d4e6ed33 | ||
|
|
b1c2d2cc15 | ||
|
|
c71a9945df | ||
|
|
92e0586089 | ||
|
|
5feb44abff | ||
|
|
df1ea86278 | ||
|
|
806c9f393b | ||
|
|
78d94c3cbc | ||
|
|
2923b545d1 | ||
|
|
e62278e1c9 | ||
|
|
fc008886fc | ||
|
|
aa189146a0 | ||
|
|
671351fa7c | ||
|
|
6926e99bd2 | ||
|
|
5bfe284e22 | ||
|
|
bc5c56d0e4 | ||
|
|
06e0598e39 | ||
|
|
25db3c1777 | ||
|
|
5de5f30b20 | ||
|
|
eb884c2790 | ||
|
|
da0f306d9b | ||
|
|
8048279465 | ||
|
|
524cf79952 | ||
|
|
ca7021a145 | ||
|
|
1dcb93c69d | ||
|
|
3f39264141 | ||
|
|
138d4a64dd | ||
|
|
0303168c26 | ||
|
|
cee2818944 |
+3
-1
@@ -4,6 +4,8 @@
|
||||
dist
|
||||
node_modules
|
||||
node_modules.broken-by-path
|
||||
.env.local
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
+7
-2
@@ -1,5 +1,10 @@
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_OVERSEAS_API_BASE_URL=/overseas-api
|
||||
OVERSEAS_API_PROXY_TARGET=http://127.0.0.1:9300
|
||||
API_PROXY_TARGET=http://127.0.0.1:9000
|
||||
VITE_ADMIN_WEB_ORIGIN=http://localhost:5173
|
||||
|
||||
# Test container deployment (Jenkins environment or untracked .env).
|
||||
# API_UPSTREAM: unified Gateway origin, no /api suffix.
|
||||
# TEST_NETWORK: shared test Docker network.
|
||||
API_UPSTREAM=http://gateway:9000
|
||||
TEST_NETWORK=firstleg-test-network
|
||||
IMAGE_TAG=
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
|
||||
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。
|
||||
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及海外 API、海外 Token 或跨区域事件时读取 `../../docs/跨区域认证与服务通信契约.md`。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
||||
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及统一 API、Token、会话撤销或可靠事件时按需读取 `../../docs/统一认证与服务通信契约.md` 对应章节。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
||||
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
|
||||
|
||||
## 技术基线
|
||||
@@ -26,37 +26,38 @@
|
||||
- 模块内 `store/`:该业务跨页面状态;局部表单状态仍留在页面或组件内。跨模块使用 store 时只能导入其公开 store 文件,不得读取模块内部页面或组件实现。
|
||||
- `src/api/`:只保留 HTTP、会话令牌、响应类型等全局请求基础设施;业务接口放入对应模块的 `api/`。页面不得直接创建独立 Axios 客户端。
|
||||
- 模块之间不得通过相对路径或内部目录穿透;确需协作时只能从目标模块的 `public.ts` 导入。模块内稳定契约放在 `contracts.ts`,稳定的跨应用模型仍应上移到 `@chongchong/shared`。
|
||||
- `VITE_API_BASE_URL`、`VITE_OVERSEAS_API_BASE_URL` 分别控制国内和海外浏览器前缀;`API_PROXY_TARGET`、`OVERSEAS_API_PROXY_TARGET` 只由 Vite 开发代理读取,不进入客户端构建。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
|
||||
- `VITE_API_BASE_URL` 控制唯一浏览器 API 前缀;全部业务共用 `src/api/http.ts` 和同一 Access/Refresh Token。`API_PROXY_TARGET` 仅供本地 Vite 代理连接测试入口,不进入客户端构建。独立海外 HTTP 客户端与代理已移除。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
|
||||
- `src/styles/`:全局设计令牌和布局;优先复用现有 `--primary`、`--navy`、`--border`、`--muted`。
|
||||
- 本应用多个模块稳定复用的前端模型放到应用内 `shared/`,客户工作台专属类型保留在对应业务模块。不要链接应用目录之外的 TypeScript 包,服务端契约以 `baiyue-firstleg` Controller/OpenAPI 为准。
|
||||
|
||||
## 开发环境样式验收
|
||||
## 测试环境样式验收
|
||||
|
||||
- 开发环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。
|
||||
- 测试环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。
|
||||
- 账号与密码不写入仓库;从本机未提交环境变量或 `C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env` 读取。若显式验收凭据不存在,再向用户索取。
|
||||
- 该身份仅适用于开发环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;开发环境变更时只更新本机凭据。
|
||||
- 当前只有一个测试环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;测试环境变更时只更新本机凭据。
|
||||
- 由人工使用该身份进入真实页面,按 `1920×1080` 视口和 `100%` 浏览器缩放完成操作与截图,再把截图发送给 AI 核对加载、空态、错误态、权限态和桌面布局;AI 默认不主动调用截图或视觉类技能取证。
|
||||
|
||||
## 模块快速查询
|
||||
|
||||
退货预报与签收结果:`src/modules/overseas-warehouse/views/ReturnOrdersView.vue`、`api/returnOrders.ts`;菜单仍名为“退货换标”,正式路由 `return-relabel` 已使用独立页面,不再由 `WarehouseServiceView.vue` 承载。客户退货库存/箱号共用 `views/ReturnInventoryView.vue`、`api/returnInventory.ts`,`return-cartons` 传 `cartonOnly=true`。Backend 为 Lastleg `returnreceipt/`,退货单签收完成不等于换标或退货出库完成;后续换标、出库须按各自业务状态核对。
|
||||
本表只保留首个入口;完整 API、字段、状态与恢复规则见 [按需业务索引](docs/business-index.md)。从本应用根执行 `rg -n -F '任务词或文件名' docs/business-index.md` 读取命中条款;涉及业务行为变更时必须核对对应细则,纯定位不全文加载。保留所有适用的最近模块指引。
|
||||
|
||||
先从 `src/modules/registry.ts` 确认模块,再按目标模块的 `routes.ts → views/ → api/、store/、contracts.ts 或 public.ts` 查询。页面是否正式开放以 `routes.ts` 的 `release` 为准,不从任务或进度文档推断。
|
||||
表中路径均相对本应用根目录。模块指引中的后端类名以服务名起算,如 `firstleg/service/X.java` 即 `baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/service/X.java`。
|
||||
|
||||
| 业务 | 模块入口 | 联查模块或服务端 |
|
||||
|---|---|---|
|
||||
| 登录、注册与会话 | `src/modules/auth/`、`src/api/session.ts`、`src/api/http.ts` | Backend `auth/`、`iam/`;正常旋转的国内/海外 Token 会话统一持久化,“记住账号”只记登录标识;访问令牌失效但刷新令牌仍在时先恢复会话,公开认证接口不得携带旧 Token |
|
||||
| 企业资料、成员与角色 | `src/modules/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`。所有订单行均可进入计费重弹框,尚未推送时展示明确空态;只有具备编辑权限且服务端返回当前 `SENT` 费用时才可二次确认并提交 `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`、`components/BusinessOrdersView.vue`、`api/businessOrders.ts` | 三个路由均为 `active`,客户范围只取 Token;采购创建的 `customerName` 只取当前认证会话企业名称,不允许自由输入或冒用其他客户。Backend `lastleg-service/` 的 `procurement/`、`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 |
|
||||
| 业务 | 首个入口 |
|
||||
|---|---|
|
||||
| 登录、注册与会话 | `src/modules/auth/AGENTS.md`、`src/api/session.ts`、`src/api/http.ts` |
|
||||
| 企业资料、成员与角色 | `src/modules/tenant-management/AGENTS.md`、`src/modules/account/AGENTS.md` |
|
||||
| 工作台与系统入口 | `src/modules/dashboard/AGENTS.md`、`src/modules/system/AGENTS.md` |
|
||||
| 企业成员消息收件箱 | `src/modules/notifications/AGENTS.md` |
|
||||
| 头程下单、中文批量导入、入仓码关系、箱唛、履约进度与入库费用确认 | `src/modules/first-leg/AGENTS.md` |
|
||||
| 装柜完成后的退税报关资料 | `src/modules/first-leg/AGENTS.md`、`src/modules/first-leg/components/CustomsDocumentsDialog.vue` |
|
||||
| 统一订单展示 | `src/modules/order-management/AGENTS.md` |
|
||||
| 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `src/modules/finance/AGENTS.md` |
|
||||
| 客户资金账户、授信与充值申请 | `src/modules/finance/AGENTS.md` |
|
||||
| 海外采购 | `src/modules/cross-border/AGENTS.md` |
|
||||
| 美国本土卡与美本土散板 | `src/modules/cross-border/AGENTS.md` |
|
||||
| 海外仓入库订单 | `src/modules/order-management/AGENTS.md` |
|
||||
| 海外仓贴标、仓储转运、货物废弃 | `src/modules/overseas-warehouse/AGENTS.md` |
|
||||
|
||||
## 租户、认证与数据安全
|
||||
|
||||
@@ -65,14 +66,14 @@
|
||||
- 任何查询和变更都必须以服务端确认的当前租户为边界;绝不从可篡改的前端参数推断授权租户。
|
||||
- 企业成员、角色和权限只能管理当前企业范围。前端隐藏不是安全控制,服务端必须重复校验租户与权限。
|
||||
- 注册时登录手机号同时初始化公司联系电话;注册完成后两者独立维护。企业资料只修改 `contactPhone`,个人资料或成员管理中的登录手机号由 IAM/Auth 同步并撤销该账号现有会话,不得在前端互相回填或联动提交。
|
||||
- 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;国内请求使用国内 Access Token,海外请求统一由 `src/api/overseasHttp.ts` 读取短时海外 Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。
|
||||
- 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;全部请求共用统一 Access Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。
|
||||
- 当前认证仍包含模拟数据。接入真实 API 后移除对应模拟分支,生产环境不得回退为模拟成功。
|
||||
- 头程订单统一使用当前正式读写契约;不得继续扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API、历史部分响应兼容或其他新旧并跑逻辑。触及该链路时按根无兼容规则同步删除生产分支、类型、文案、Mock 和测试,不以现有代码或测试仍覆盖旧路径作为保留依据。
|
||||
- 注册、上传资质、成员邀请和订单操作必须提供明确校验、幂等保护、提交中状态和可恢复的失败反馈。
|
||||
|
||||
## UI 与交互
|
||||
|
||||
- 修改已有 Client 原型页面前先读 `../../docs/Admin-Client前端原型还原验收规则.md`,按页面和操作形成原型核对矩阵;本节维护 Client 的实现约束,不复制跨前端验收文档全文。
|
||||
- 视觉还原、布局/交互承载方式变更或真实页面验收时读取 `../../docs/Admin-Client前端原型还原验收规则.md`,只为受影响操作形成原型核对矩阵;纯文案、逻辑或测试修改不自动读取。自动检查与人工视觉验收分开报告,无视觉变化时标记“无需视觉验收”。
|
||||
- 已向客户讲解或确认过的产品原型是页面视觉与布局实现的直接事实来源。字段顺序、字段分组、字段摆放、列宽、控件宽高、对齐方式、换行方式、区块层级、上下左右边距、内边距、间隙、留白、圆角、边框、阴影、背景色、文字颜色和字号均必须按原型还原,不得只参考大致风格后自行重新排版。
|
||||
- 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。
|
||||
- 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。
|
||||
@@ -96,8 +97,8 @@ pnpm typecheck
|
||||
pnpm build
|
||||
```
|
||||
|
||||
- 日常变更至少运行 `pnpm typecheck`;交付前运行 `pnpm build`。
|
||||
- 当前测试使用 Node.js 内置测试运行器,执行 `pnpm test`;项目仍未声明 lint 脚本,不得声称 lint 已通过。
|
||||
- 按 `../../docs/AI工程执行与协作约束.md` 的“验证范围选择”执行;命令表不是每轮清单。文案/纯展示核对差异,小逻辑跑定向测试;类型/签名变化加最小类型检查,公共能力覆盖实际消费者。不因源码修改或交付自动 typecheck、全量测试或构建;构建和全量测试分别说明触发原因,相同编译不重复跑。纯文档/索引只检查路径、链接及索引合同。
|
||||
- 当前测试使用 Node.js 内置测试运行器,局部改动指定受影响测试文件,`pnpm test` 是全量入口;项目未声明 lint 脚本,不得声称 lint 已通过。
|
||||
- 不手工修改 `dist/` 或 `node_modules/`;依赖变更必须同步当前项目依赖清单和锁文件。
|
||||
|
||||
## 全量验收脚本
|
||||
@@ -109,11 +110,4 @@ pnpm build
|
||||
|
||||
## 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` 定位。
|
||||
全量验收的两类客户可见范围按需查 `docs/business-index.md` 同名节;平台/PDA 操作与内部证据不得因此暴露给客户。普通修改保持最小模块范围,不自动加载验收资料。
|
||||
|
||||
Vendored
+26
-216
@@ -1,250 +1,60 @@
|
||||
def sendProductionWeComNotification(String title, String status, String color, String detail) {
|
||||
withCredentials([string(credentialsId: 'wecom-prod-webhook', variable: 'WECOM_WEBHOOK')]) {
|
||||
String sourceVersion = env.SOURCE_TAG ?: env.GIT_COMMIT ?: '未解析'
|
||||
String duration = currentBuild.durationString?.replace(' and counting', '') ?: '—'
|
||||
String content = """## ${title}
|
||||
> 应用:客户工作台
|
||||
> Job:${env.JOB_NAME}
|
||||
> 构建:[#${env.BUILD_NUMBER}](${env.BUILD_URL})
|
||||
> 提交:${sourceVersion}
|
||||
> 状态:<font color="${color}">${status}</font>
|
||||
${detail}
|
||||
> 耗时:${duration}
|
||||
> 时间:${new Date().format('yyyy-MM-dd HH:mm:ss', TimeZone.getTimeZone('Asia/Shanghai'))}
|
||||
"""
|
||||
String payloadFile = 'wecom-production-notification.json'
|
||||
writeFile(
|
||||
file: payloadFile,
|
||||
text: groovy.json.JsonOutput.toJson([
|
||||
msgtype: 'markdown',
|
||||
markdown: [content: content]
|
||||
]),
|
||||
encoding: 'UTF-8'
|
||||
)
|
||||
sh '''
|
||||
set -eu
|
||||
payload_file='wecom-production-notification.json'
|
||||
trap 'rm -f "$payload_file"' EXIT HUP INT TERM
|
||||
response="$(curl --fail --silent --show-error \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-binary @"$payload_file" \
|
||||
"$WECOM_WEBHOOK")"
|
||||
printf '%s\n' "$response"
|
||||
printf '%s' "$response" | grep -Eq '"errcode"[[:space:]]*:[[:space:]]*0([[:space:]]*[,}])'
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
pipeline {
|
||||
agent {
|
||||
label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : (env.JOB_BASE_NAME?.endsWith('-dev') ? 'java-dev' : 'java-test')}"
|
||||
}
|
||||
|
||||
environment {
|
||||
DEVELOPMENT_COMPOSE_FILE = 'docker-compose.development.yml'
|
||||
DEVELOPMENT_COMPOSE_PROJECT = 'client-web'
|
||||
REGISTRY_HOST = '172.31.198.7:10082'
|
||||
REGISTRY_CREDENTIALS = 'gitea-registry-token'
|
||||
NODE_BASE_IMAGE = '172.31.198.7:10082/java-project/node:22-alpine'
|
||||
NGINX_BASE_IMAGE = '172.31.198.7:10082/java-project/nginx:1.27-alpine'
|
||||
PRODUCTION_IMAGE_REPOSITORY = 'git.buggoglobal.com/html/client-web'
|
||||
}
|
||||
|
||||
agent { label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : 'java-test'}" }
|
||||
options {
|
||||
timestamps()
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('确认提交版本') {
|
||||
stage('检查测试发布参数') {
|
||||
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||
steps {
|
||||
script {
|
||||
env.IS_DEVELOPMENT = env.JOB_BASE_NAME?.endsWith('-dev') ? 'true' : 'false'
|
||||
env.IS_PRODUCTION = env.JOB_BASE_NAME?.endsWith('-prod') ? 'true' : 'false'
|
||||
if (env.IS_PRODUCTION == 'true') {
|
||||
sh '''
|
||||
set -eu
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)" || {
|
||||
echo "生产部署只允许 origin/main 当前提交;请先合并代码到 main" >&2
|
||||
exit 1
|
||||
}
|
||||
'''
|
||||
if (env.JOB_BASE_NAME?.endsWith('-dev')) {
|
||||
error('此流水线仅支持 test 和本轮授权的 prod 灰度')
|
||||
}
|
||||
env.SOURCE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||
env.IMAGE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||
}
|
||||
sh 'git log -1 --oneline'
|
||||
sh '''set -eu
|
||||
export API_UPSTREAM="${API_UPSTREAM:-http://gateway:9000}"
|
||||
export TEST_NETWORK="${TEST_NETWORK:-firstleg-test-network}"
|
||||
: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN 未设置}"
|
||||
docker network inspect "$TEST_NETWORK" >/dev/null
|
||||
docker compose -f docker-compose.test.yml config --quiet
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('构建并部署测试前端') {
|
||||
when { expression { env.IS_DEVELOPMENT != 'true' && env.IS_PRODUCTION != 'true' } }
|
||||
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
|
||||
sh '''
|
||||
set -eu
|
||||
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
mkdir -p "$DOCKER_CONFIG"
|
||||
cleanup_registry() {
|
||||
docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
}
|
||||
trap cleanup_registry EXIT HUP INT TERM
|
||||
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
|
||||
docker compose -f docker-compose.test.yml build --pull=false
|
||||
docker compose -f docker-compose.test.yml up -d --remove-orphans
|
||||
'''
|
||||
}
|
||||
sh '''set -eu
|
||||
docker compose -f docker-compose.test.yml build --pull=false
|
||||
docker compose -f docker-compose.test.yml up -d --wait --wait-timeout 120
|
||||
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('构建并发布生产镜像') {
|
||||
when { expression { env.IS_PRODUCTION == 'true' } }
|
||||
stage('发布临时生产灰度') {
|
||||
when { expression { env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
|
||||
sh '''
|
||||
set -eu
|
||||
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
mkdir -p "$DOCKER_CONFIG"
|
||||
cleanup_registry() {
|
||||
docker logout git.buggoglobal.com >/dev/null 2>&1 || true
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
}
|
||||
trap cleanup_registry EXIT HUP INT TERM
|
||||
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin git.buggoglobal.com
|
||||
image="$PRODUCTION_IMAGE_REPOSITORY:$SOURCE_TAG"
|
||||
docker build \
|
||||
--build-arg NODE_IMAGE="$NODE_BASE_IMAGE" \
|
||||
--build-arg NGINX_IMAGE="$NGINX_BASE_IMAGE" \
|
||||
--build-arg VITE_ADMIN_WEB_ORIGIN=https://admin.buggoglobal.com \
|
||||
-t "$image" .
|
||||
docker push "$image"
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('部署生产前端') {
|
||||
when { expression { env.IS_PRODUCTION == 'true' } }
|
||||
steps {
|
||||
lock(resource: 'firstleg-production-client-web-deploy', inversePrecedence: true) {
|
||||
lock(resource: 'firstleg-production-client-web-deploy') {
|
||||
withCredentials([
|
||||
usernamePassword(credentialsId: 'gitea-registry-token', usernameVariable: 'BUILD_REGISTRY_USER', passwordVariable: 'BUILD_REGISTRY_PASSWORD'),
|
||||
usernamePassword(credentialsId: 'gitea-production-pull-token', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD'),
|
||||
sshUserPrivateKey(credentialsId: 'firstleg-production-ssh', keyFileVariable: 'TARGET_SSH_KEY', usernameVariable: 'TARGET_SSH_USER'),
|
||||
string(credentialsId: 'firstleg-production-host', variable: 'TARGET_SSH_HOST'),
|
||||
file(credentialsId: 'firstleg-production-known-hosts', variable: 'TARGET_SSH_KNOWN_HOSTS')
|
||||
]) {
|
||||
withEnv([
|
||||
'TARGET_DEPLOY_DIR=/data/firstleg/deploy/frontend',
|
||||
'TARGET_SSH_TARGET=' + env.TARGET_SSH_USER + '@' + env.TARGET_SSH_HOST
|
||||
]) {
|
||||
sh "sh scripts/deploy-production.sh client-web '${env.PRODUCTION_IMAGE_REPOSITORY}' '${env.SOURCE_TAG}' docker-compose.production.yml"
|
||||
}
|
||||
sh 'sh scripts/deploy-production.sh'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('构建并部署开发前端') {
|
||||
when { expression { env.IS_DEVELOPMENT == 'true' } }
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
|
||||
sh '''
|
||||
set -eu
|
||||
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
mkdir -p "$DOCKER_CONFIG"
|
||||
cleanup_registry() {
|
||||
docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
}
|
||||
trap cleanup_registry EXIT HUP INT TERM
|
||||
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
|
||||
image="client-web-development:${SOURCE_TAG}"
|
||||
|
||||
docker build \
|
||||
--build-arg NODE_IMAGE="$NODE_BASE_IMAGE" \
|
||||
--build-arg NGINX_IMAGE="$NGINX_BASE_IMAGE" \
|
||||
--build-arg VITE_ADMIN_WEB_ORIGIN=http://8.163.49.32:9001 \
|
||||
-t "$image" .
|
||||
export IMAGE_TAG="$SOURCE_TAG"
|
||||
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" up -d --remove-orphans --pull never
|
||||
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" ps
|
||||
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('部署检查') {
|
||||
when { expression { env.IS_DEVELOPMENT != 'true' && env.IS_PRODUCTION != 'true' } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
docker compose -f docker-compose.test.yml ps
|
||||
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
if (env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
try {
|
||||
sendProductionWeComNotification(
|
||||
'✅ 生产部署成功',
|
||||
'成功',
|
||||
'info',
|
||||
'> 结果:Client 生产前端已完成发布和部署流程'
|
||||
)
|
||||
} catch (Exception error) {
|
||||
echo "企业微信通知失败,不影响原构建结果:${error.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
failure {
|
||||
sh '''
|
||||
if [ "${IS_PRODUCTION:-false}" = "true" ]; then
|
||||
echo "生产部署失败,请查看上方远程部署日志"
|
||||
elif [ "${IS_DEVELOPMENT:-false}" = "true" ]; then
|
||||
docker logs --tail=100 client-web-development || true
|
||||
else
|
||||
docker compose -f docker-compose.test.yml logs --tail=100 || true
|
||||
fi
|
||||
'''
|
||||
script {
|
||||
if (env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
try {
|
||||
sendProductionWeComNotification(
|
||||
'❌ 生产发布失败',
|
||||
'失败',
|
||||
'warning',
|
||||
'> 说明:请打开 Jenkins 构建日志查看失败阶段'
|
||||
)
|
||||
} catch (Exception error) {
|
||||
echo "企业微信通知失败,不影响原构建结果:${error.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
if (env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
try {
|
||||
sendProductionWeComNotification(
|
||||
'⏹ 生产部署已取消',
|
||||
'已取消',
|
||||
'comment',
|
||||
'> 说明:生产部署流程被人工取消或中止'
|
||||
)
|
||||
} catch (Exception error) {
|
||||
echo "企业微信通知失败,不影响原构建结果:${error.message}"
|
||||
}
|
||||
if (!env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
sh 'docker compose -f docker-compose.test.yml logs --tail=100 || true'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
生产构建:
|
||||
发布资源构建:
|
||||
|
||||
```bash
|
||||
pnpm typecheck
|
||||
@@ -35,7 +35,7 @@ pnpm test
|
||||
|
||||
依赖和 `pnpm-lock.yaml` 均保存在当前前端项目中,不需要在仓库根目录安装 Node 依赖。
|
||||
|
||||
订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经海外 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。开发代理通过 `API_PROXY_TARGET` 与 `OVERSEAS_API_PROXY_TARGET` 分别配置国内、海外 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
|
||||
订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经统一 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。本地代理仅通过 `API_PROXY_TARGET` 配置统一 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
|
||||
|
||||
认证会话保存 Access Token 和轮换后的 Refresh Token,并对并发 401 请求执行单次刷新。刷新或会话上下文加载遇到临时网络故障、超时等非认证错误时保留当前有效 Token,只有服务端明确返回 401/会话失效才清理登录状态。客户端只接受 `app_code` 为 `MERCHANT` 的 JWT;页面权限通过当前用户授权接口实时加载,不从 JWT 携带或解析角色权限。前端权限仅用于导航和交互控制,服务端仍须按用户、客户和权限编码完成最终授权。
|
||||
|
||||
@@ -47,4 +47,10 @@ pnpm test
|
||||
|
||||
头程订单列表、详情、仓库查询、创建/编辑草稿和提交已经接入真实 API,并显式映射后端 `transportMode`、`containerMode` 和订单状态。创建与提交请求携带幂等键,`merchant:order:create`、`merchant:order:edit`、`merchant:order:submit` 分别映射到独立前端操作权限。页面补齐渠道、提货方式、报关模式、目的仓类型、包装类型等后端必填字段;API 模式先清空本地记录,请求失败不会回退模拟成功。FBA 和海外仓按公共仓类型筛选,选择后由仓库主数据生成目的仓字段,不再要求客户重复选择收货单位;私人仓才填写并按当前用户缓存收件资料。只有“我司提货”需要填写提货联系人和地址,其他送货方式不发送发货方快照,订单也不再依赖往来单位 `customerId`。快递信息仍由平台维护、客户只读。订单取消不属于本轮本地订单与客户验收,客户端不暴露取消写操作。订单产品状态仍按已确认的七状态执行,不设置“已驳回”;若兼容旧接口数据收到 `REJECTED`,只按待审核展示且不开放编辑。
|
||||
|
||||
联调远端 Gateway 时,进程环境变量优先于 `.env` 文件。浏览器国内业务统一请求同源 `/api`,海外业务请求同源 `/overseas-api`,由代理分别转发并确保最终路径只有一个 `/api` 前缀。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。
|
||||
联调远端 Gateway 时,进程环境变量优先于 `.env` 文件。浏览器全部业务统一请求同源 `/api`,由同一代理转发并确保最终路径只有一个 `/api` 前缀。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。
|
||||
|
||||
## 唯一测试部署入口
|
||||
|
||||
仅保留 `docker-compose.test.yml` 与 test Jenkins Job。发布前注入 `API_UPSTREAM`(统一 Gateway origin,不含 `/api`)、`TEST_NETWORK`(后端共享测试网络)、`VITE_ADMIN_WEB_ORIGIN`(管理后台 origin,构建时用于安全代登录)与 `IMAGE_TAG`(Jenkins 从当前提交生成)。`HOST_PORT` 默认 9002 且仅绑定 loopback;宿主机反向代理负责外部入口。可选 `NODE_BASE_IMAGE`/`NGINX_BASE_IMAGE`,私有镜像认证由构建节点管理。不得把本地构建结果描述为测试环境已发布。
|
||||
|
||||
同机目标默认值:`API_UPSTREAM=http://gateway:9000`、`TEST_NETWORK=firstleg-test-network`;必须与后端同批 test Compose 配置一致。
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
services:
|
||||
client-web:
|
||||
image: client-web-development:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||
container_name: client-web-development
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:9002:80"
|
||||
environment:
|
||||
API_UPSTREAM: "http://firstleg-development-gateway:9000"
|
||||
OVERSEAS_API_UPSTREAM: "http://firstleg-development-gateway-overseas:9300"
|
||||
networks:
|
||||
- development-backend
|
||||
- development-overseas-backend
|
||||
|
||||
networks:
|
||||
development-backend:
|
||||
external: true
|
||||
name: firstleg-development-network
|
||||
development-overseas-backend:
|
||||
external: true
|
||||
name: firstleg-development-overseas-network
|
||||
@@ -1,23 +1,22 @@
|
||||
name: firstleg-prod-client-web
|
||||
|
||||
services:
|
||||
client-web:
|
||||
image: ${IMAGE_REPOSITORY:?IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||
image: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required}"
|
||||
container_name: firstleg-prod-client-web
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-9002}:80"
|
||||
- "127.0.0.1:${HOST_PORT:-29012}:80"
|
||||
environment:
|
||||
API_UPSTREAM: "http://gateway-active:9000"
|
||||
OVERSEAS_API_UPSTREAM: "http://gateway-overseas-active:9300"
|
||||
API_UPSTREAM: "http://gateway:9000"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
networks:
|
||||
- infra-network
|
||||
- routing-network
|
||||
|
||||
- backend
|
||||
networks:
|
||||
infra-network:
|
||||
backend:
|
||||
external: true
|
||||
name: firstleg-prod-infra-network
|
||||
routing-network:
|
||||
external: true
|
||||
name: firstleg-production-routing
|
||||
name: firstleg-production-network
|
||||
|
||||
+17
-7
@@ -1,19 +1,29 @@
|
||||
name: firstleg-test-client-web
|
||||
services:
|
||||
client-web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:-https://test-admin.buggoglobal.com}"
|
||||
NODE_IMAGE: "${NODE_BASE_IMAGE:-node:22-alpine}"
|
||||
NGINX_IMAGE: "${NGINX_BASE_IMAGE:-nginx:1.27-alpine}"
|
||||
image: client-web-test:local
|
||||
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN is required}"
|
||||
image: client-web-test:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||
container_name: client-web-test
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
ports:
|
||||
- "${HOST_PORT:-9002}:80"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
- "127.0.0.1:${HOST_PORT:-9002}:80"
|
||||
environment:
|
||||
API_UPSTREAM: "${API_UPSTREAM:-http://host.docker.internal:9000}"
|
||||
OVERSEAS_API_UPSTREAM: "${OVERSEAS_API_UPSTREAM:-http://host.docker.internal:9300}"
|
||||
API_UPSTREAM: "${API_UPSTREAM:-http://gateway:9000}"
|
||||
networks:
|
||||
- test-backend
|
||||
networks:
|
||||
test-backend:
|
||||
external: true
|
||||
name: "${TEST_NETWORK:-firstleg-test-network}"
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# 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/` |
|
||||
| 美国本土卡与美本土散板 | `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` 定位。
|
||||
@@ -35,17 +35,6 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 海外业务使用独立 Gateway;浏览器前缀只在此处改写一次为 /api。
|
||||
location /overseas-api/ {
|
||||
client_max_body_size 55m;
|
||||
rewrite ^/overseas-api/(.*)$ /api/$1 break;
|
||||
proxy_pass ${OVERSEAS_API_UPSTREAM};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $proxy_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 支持 Vue Router history 路由直接刷新。
|
||||
location / {
|
||||
|
||||
+52
-144
@@ -1,150 +1,58 @@
|
||||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
if [ "$#" -ne 4 ]; then
|
||||
echo "用法: $0 <服务名> <镜像仓库> <镜像标签> <Compose 文件>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
SERVICE="$1"
|
||||
IMAGE_REPOSITORY="$2"
|
||||
IMAGE_TAG="$3"
|
||||
COMPOSE_FILE="$4"
|
||||
IMAGE="$IMAGE_REPOSITORY:$IMAGE_TAG"
|
||||
REGISTRY_HOST="${IMAGE_REPOSITORY%%/*}"
|
||||
SSH_TARGET="${TARGET_SSH_TARGET:?TARGET_SSH_TARGET 未设置}"
|
||||
SSH_KEY="${TARGET_SSH_KEY:?TARGET_SSH_KEY 未设置}"
|
||||
SSH_KNOWN_HOSTS="${TARGET_SSH_KNOWN_HOSTS:?TARGET_SSH_KNOWN_HOSTS 未设置}"
|
||||
REMOTE_DIR="${TARGET_DEPLOY_DIR:?TARGET_DEPLOY_DIR 未设置}"
|
||||
: "${REGISTRY_USER:?REGISTRY_USER 未设置}"
|
||||
: "${REGISTRY_PASSWORD:?REGISTRY_PASSWORD 未设置}"
|
||||
|
||||
set +x
|
||||
: "${PUBLIC_WEB_ORIGIN:?PUBLIC_WEB_ORIGIN is required}"
|
||||
: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}"
|
||||
: "${TARGET_SSH_KEY:?}"
|
||||
: "${TARGET_SSH_USER:?}"
|
||||
: "${TARGET_SSH_HOST:?}"
|
||||
: "${TARGET_SSH_KNOWN_HOSTS:?}"
|
||||
: "${BUILD_REGISTRY_USER:?}"
|
||||
: "${BUILD_REGISTRY_PASSWORD:?}"
|
||||
: "${REGISTRY_USER:?}"
|
||||
: "${REGISTRY_PASSWORD:?}"
|
||||
case "$PUBLIC_WEB_ORIGIN" in https://*) ;; *) echo 'prod requires HTTPS web origin' >&2; exit 2 ;; esac
|
||||
# Only an origin (optionally a trailing slash) is accepted; no shell/env-file metacharacters.
|
||||
printf '%s' "$PUBLIC_WEB_ORIGIN" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]+)?/?$'
|
||||
printf '%s' "$PRODUCTION_IMAGE_REPOSITORY" | grep -Eq '^[A-Za-z0-9.-]+(:[0-9]+)?/[a-z0-9._/-]+$'
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)"
|
||||
IMAGE_TAG=$(git rev-parse --short=12 HEAD)
|
||||
registry=${PRODUCTION_IMAGE_REPOSITORY%%/*}
|
||||
image="$PRODUCTION_IMAGE_REPOSITORY:$IMAGE_TAG"
|
||||
TARGET_SSH_TARGET="$TARGET_SSH_USER@$TARGET_SSH_HOST"
|
||||
remote_dir=/data/firstleg/deploy/gray-client-web
|
||||
run_ssh() {
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$SSH_TARGET" "$@"
|
||||
ssh -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$TARGET_SSH_TARGET" "$@"
|
||||
}
|
||||
|
||||
run_scp() {
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$@"
|
||||
scp -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$@"
|
||||
}
|
||||
|
||||
run_ssh install -d -m 750 "$REMOTE_DIR"
|
||||
REMOTE_COMPOSE="$REMOTE_DIR/docker-compose.$SERVICE.yml"
|
||||
run_scp "$COMPOSE_FILE" "$SSH_TARGET:$REMOTE_COMPOSE.tmp"
|
||||
run_ssh sh -s -- "$REMOTE_COMPOSE.tmp" "$REMOTE_COMPOSE" <<'REMOTE_PREPARE'
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
|
||||
trap cleanup EXIT HUP INT TERM
|
||||
printf '%s' "$BUILD_REGISTRY_PASSWORD" | docker login -u "$BUILD_REGISTRY_USER" --password-stdin "$registry"
|
||||
docker build --build-arg NODE_IMAGE="${NODE_BASE_IMAGE:-node:22-alpine}" \
|
||||
--build-arg NGINX_IMAGE="${NGINX_BASE_IMAGE:-nginx:1.27-alpine}" \
|
||||
--build-arg VITE_ADMIN_WEB_ORIGIN="$PUBLIC_WEB_ORIGIN" -t "$image" .
|
||||
docker push "$image"
|
||||
run_ssh install -d -m 750 "$remote_dir"
|
||||
run_scp docker-compose.production.yml "$TARGET_SSH_TARGET:$remote_dir/compose.yml"
|
||||
# The remote env file contains only image coordinates and public web origin, never credentials.
|
||||
printf 'PRODUCTION_IMAGE_REPOSITORY=%s\nIMAGE_TAG=%s\nPUBLIC_WEB_ORIGIN=%s\n' \
|
||||
"$PRODUCTION_IMAGE_REPOSITORY" "$IMAGE_TAG" "$PUBLIC_WEB_ORIGIN" | run_ssh sh -c "'umask 077; cat > $remote_dir/release.env'"
|
||||
# Registry credentials exist only in an isolated temporary Docker config, removed after pull.
|
||||
printf '%s' "$REGISTRY_USER" | grep -Eq '^[A-Za-z0-9_.@-]+$'
|
||||
run_scp scripts/pull-production-image.sh "$TARGET_SSH_TARGET:$remote_dir/pull-image.sh"
|
||||
printf '%s' "$REGISTRY_PASSWORD" | run_ssh sh "$remote_dir/pull-image.sh" "$REGISTRY_USER" "$registry" "$image"
|
||||
run_ssh sh -s -- "$remote_dir" <<'REMOTE'
|
||||
set -eu
|
||||
compose_tmp="$1"
|
||||
compose_target="$2"
|
||||
chmod 644 "$compose_tmp"
|
||||
mv -f "$compose_tmp" "$compose_target"
|
||||
REMOTE_PREPARE
|
||||
|
||||
printf '%s' "$REGISTRY_PASSWORD" | run_ssh docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
|
||||
trap 'run_ssh docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true' EXIT HUP INT TERM
|
||||
run_ssh docker pull "$IMAGE"
|
||||
|
||||
run_ssh sh -s -- "$REMOTE_DIR" "$SERVICE" "$IMAGE_REPOSITORY" "$IMAGE_TAG" <<'REMOTE_DEPLOY'
|
||||
set -eu
|
||||
remote_dir="$1"
|
||||
service="$2"
|
||||
image_repository="$3"
|
||||
image_tag="$4"
|
||||
compose_file="docker-compose.$service.yml"
|
||||
project_name="firstleg-prod-$service"
|
||||
cd "$remote_dir"
|
||||
export IMAGE_REPOSITORY="$image_repository" IMAGE_TAG="$image_tag"
|
||||
|
||||
compose() {
|
||||
docker compose --project-name "$project_name" -f "$compose_file" "$@"
|
||||
}
|
||||
|
||||
case "$service" in
|
||||
admin-web)
|
||||
base_port=9001
|
||||
nginx_config=/www/server/panel/vhost/nginx/00-blue-green-admin-web.conf
|
||||
legacy_container=firstleg-prod-admin-web
|
||||
;;
|
||||
client-web)
|
||||
base_port=9002
|
||||
nginx_config=/www/server/panel/vhost/nginx/00-blue-green-client-web.conf
|
||||
legacy_container=firstleg-prod-client-web
|
||||
;;
|
||||
*) echo "不支持蓝绿部署的前端服务: $service" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
state_root=/data/firstleg/deploy/blue-green-state
|
||||
state_file="$state_root/frontend-$service.active"
|
||||
routing_network=firstleg-production-routing
|
||||
mkdir -p "$state_root"
|
||||
chmod 750 "$state_root"
|
||||
docker network inspect "$routing_network" >/dev/null 2>&1 || docker network create "$routing_network" >/dev/null
|
||||
|
||||
for pair in gateway-active:firstleg-production-gateway gateway-overseas-active:firstleg-production-gateway-overseas; do
|
||||
alias_name="${pair%%:*}"
|
||||
container="${pair#*:}"
|
||||
if docker inspect "$container" >/dev/null 2>&1; then
|
||||
docker network inspect "$routing_network" --format '{{json .Containers}}' | grep -q "\"$container\"" \
|
||||
|| docker network connect --alias "$alias_name" "$routing_network" "$container"
|
||||
fi
|
||||
done
|
||||
|
||||
active_slot=""
|
||||
active_container=""
|
||||
active_port=""
|
||||
if [ -s "$state_file" ]; then
|
||||
IFS='|' read -r active_slot active_container active_port active_image < "$state_file"
|
||||
elif docker inspect "$legacy_container" >/dev/null 2>&1; then
|
||||
active_slot=legacy
|
||||
active_container="$legacy_container"
|
||||
active_port="$base_port"
|
||||
fi
|
||||
|
||||
if [ "$active_slot" = blue ]; then target_slot=green; else target_slot=blue; fi
|
||||
[ "$active_slot" = legacy ] && target_slot=green
|
||||
if [ "$target_slot" = blue ]; then target_port=$((base_port + 20000)); else target_port=$((base_port + 10000)); fi
|
||||
candidate="${legacy_container}-${target_slot}"
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
|
||||
if ! compose run -d --no-deps --name "$candidate" \
|
||||
-p "127.0.0.1:$target_port:80" "$service" >/dev/null; then
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
healthy=false
|
||||
elapsed=0
|
||||
while [ "$elapsed" -lt 120 ]; do
|
||||
if docker exec "$candidate" wget -qO- http://127.0.0.1/healthz >/dev/null 2>&1; then
|
||||
healthy=true
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
elapsed=$((elapsed + 2))
|
||||
done
|
||||
if [ "$healthy" != true ]; then
|
||||
docker logs --tail 100 "$candidate" >&2 || true
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
backup="$nginx_config.blue-green-backup"
|
||||
cp -f "$nginx_config" "$backup"
|
||||
if ! sed -i "s#127\.0\.0\.1:${active_port:-$base_port}#127.0.0.1:$target_port#g" "$nginx_config" \
|
||||
|| cmp -s "$nginx_config" "$backup" || ! nginx -t || ! nginx -s reload; then
|
||||
cp -f "$backup" "$nginx_config"
|
||||
nginx -t && nginx -s reload || true
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
rm -f "$backup"
|
||||
|
||||
if [ -n "$active_container" ] && docker inspect "$active_container" >/dev/null 2>&1; then
|
||||
docker stop --time 30 "$active_container" >/dev/null
|
||||
docker rm "$active_container" >/dev/null
|
||||
fi
|
||||
printf '%s|%s|%s|%s\n' "$target_slot" "$candidate" "$target_port" "$image_repository:$image_tag" > "$state_file.tmp"
|
||||
chmod 640 "$state_file.tmp"
|
||||
mv -f "$state_file.tmp" "$state_file"
|
||||
echo "生产前端蓝绿部署成功: service=$service slot=$target_slot port=$target_port image=$image_repository:$image_tag"
|
||||
REMOTE_DEPLOY
|
||||
cd "$1"
|
||||
docker network inspect firstleg-production-network >/dev/null
|
||||
docker compose --env-file release.env -f compose.yml config --quiet
|
||||
docker compose --env-file release.env -f compose.yml up -d --wait --wait-timeout 120
|
||||
docker compose --env-file release.env -f compose.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
REMOTE
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
set +x
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
|
||||
trap cleanup EXIT HUP INT TERM
|
||||
docker login -u "$1" --password-stdin "$2"
|
||||
docker pull "$3"
|
||||
@@ -92,6 +92,7 @@ export const FIRST_LEG_ORDER_STATUSES = [
|
||||
{ code: 'LOADED', label: '装柜完成' },
|
||||
{ code: 'DELIVERED', label: '派送完成' },
|
||||
{ code: 'COMPLETED', label: '已完成' },
|
||||
{ code: 'CANCELLED', label: '已取消' },
|
||||
] as const
|
||||
|
||||
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
|
||||
|
||||
+95
-12
@@ -1,8 +1,8 @@
|
||||
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||
import { accessTokenIdentity, clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
||||
import { ApiError, isApiEnvelope, type ApiEnvelope } from '@/api/types'
|
||||
import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
|
||||
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
|
||||
|
||||
const transport = axios.create({
|
||||
@@ -13,9 +13,18 @@ const transport = axios.create({
|
||||
|
||||
interface RetryableRequest extends InternalAxiosRequestConfig {
|
||||
_retriedAfterRefresh?: boolean
|
||||
_sessionIdentity?: string | null
|
||||
_logoutGeneration?: number
|
||||
}
|
||||
|
||||
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
||||
if (!isApiEnvelope(envelope)) {
|
||||
const invalid: unknown = envelope
|
||||
if (isApiFailure(invalid)) {
|
||||
throw new ApiError(invalid.message, invalid.code, undefined, undefined, invalid.traceId, invalid.requestId)
|
||||
}
|
||||
throw new ApiError('接口响应格式错误', 'INVALID_RESPONSE')
|
||||
}
|
||||
if (envelope.code !== '200') {
|
||||
const fieldErrors = asFieldErrors(envelope.data)
|
||||
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId, envelope.requestId)
|
||||
@@ -28,8 +37,8 @@ function mapError(error: unknown) {
|
||||
if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败')
|
||||
|
||||
const body = error.response?.data
|
||||
if (isApiEnvelope(body)) {
|
||||
const fieldErrors = asFieldErrors(body.data)
|
||||
if (isApiEnvelope(body) || isApiFailure(body)) {
|
||||
const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
|
||||
return new ApiError(
|
||||
apiErrorMessage(body.message, fieldErrors),
|
||||
body.code,
|
||||
@@ -44,9 +53,12 @@ function mapError(error: unknown) {
|
||||
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
|
||||
let refreshExchange: { identity: string; refreshToken: string; promise: Promise<TokenPair> } | null = null
|
||||
let logoutGeneration = 0
|
||||
let refreshPromise: Promise<string> | null = null
|
||||
let refreshIdentity: string | null = null
|
||||
let redirectingToLogin = false
|
||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/impersonations/exchange']
|
||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout', '/auth/impersonations/exchange']
|
||||
|
||||
function isPublicAuthRequest(url?: string) {
|
||||
return publicAuthPaths.some((path) => url?.endsWith(path))
|
||||
@@ -63,29 +75,46 @@ function redirectToLoginAfterSessionExpiry() {
|
||||
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
||||
}
|
||||
|
||||
function requireCurrentIdentity(identity: string | null | undefined, accessToken = getAccessToken()) {
|
||||
if (!identity || accessTokenIdentity(accessToken) !== identity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
}
|
||||
|
||||
export async function refreshAuthenticatedSession() {
|
||||
const observedIdentity = accessTokenIdentity(getAccessToken())
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const observedRefreshToken = getRefreshToken()
|
||||
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||
if (!refreshPromise) {
|
||||
refreshIdentity = observedIdentity
|
||||
refreshPromise = coordinateCrossTabRefresh({
|
||||
lockName: 'cc-client-auth-refresh',
|
||||
observedRefreshToken,
|
||||
currentRefreshToken: getRefreshToken,
|
||||
reuseCurrentSession: async () => {
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const currentAccessToken = getAccessToken()
|
||||
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||
return currentAccessToken
|
||||
},
|
||||
refresh: async (currentRefreshToken) => {
|
||||
const response = await transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken })
|
||||
const tokens = unwrap(response.data)
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const exchange = { identity: observedIdentity!, refreshToken: currentRefreshToken, promise: transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }).then(response => unwrap(response.data)) }
|
||||
refreshExchange = exchange
|
||||
let tokens: TokenPair
|
||||
try { tokens = await exchange.promise } finally { if (refreshExchange === exchange) refreshExchange = null }
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
requireCurrentIdentity(observedIdentity, tokens.accessToken)
|
||||
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
||||
if (getRefreshToken() !== currentRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||
persistTokenPair(tokens)
|
||||
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('cc-client-session-updated'))
|
||||
return tokens.accessToken
|
||||
},
|
||||
})
|
||||
.catch((error) => {
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
if (error instanceof CrossTabRefreshTimeoutError) {
|
||||
if (getRefreshToken() && getRefreshToken() !== observedRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||
const expiredError = new ApiError(error.message, 'A0401', 401)
|
||||
clearSessionTokens()
|
||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||
@@ -96,33 +125,60 @@ export async function refreshAuthenticatedSession() {
|
||||
})
|
||||
.finally(() => {
|
||||
refreshPromise = null
|
||||
refreshIdentity = null
|
||||
})
|
||||
}
|
||||
return refreshPromise
|
||||
if (refreshIdentity !== observedIdentity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
const refreshed = await refreshPromise
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
return refreshed
|
||||
}
|
||||
|
||||
transport.interceptors.request.use((config) => {
|
||||
const token = getAccessToken()
|
||||
if (token && !isPublicAuthRequest(config.url)) config.headers.Authorization = `Bearer ${token}`
|
||||
const request = config as RetryableRequest
|
||||
if (request._retriedAfterRefresh && !isPublicAuthRequest(config.url)) requireCurrentIdentity(request._sessionIdentity, token)
|
||||
if (token && !isPublicAuthRequest(config.url)) {
|
||||
if (!request._retriedAfterRefresh) {
|
||||
request._sessionIdentity = accessTokenIdentity(token)
|
||||
request._logoutGeneration = logoutGeneration
|
||||
}
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
transport.interceptors.response.use(
|
||||
(response) => response,
|
||||
(response) => {
|
||||
const request = response.config as RetryableRequest
|
||||
if (request._sessionIdentity) {
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
}
|
||||
return response
|
||||
},
|
||||
async (error: AxiosError) => {
|
||||
const request = error.config as RetryableRequest | undefined
|
||||
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
|
||||
throw mapError(error)
|
||||
}
|
||||
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
request._retriedAfterRefresh = true
|
||||
const refreshTokenBeforeRetry = getRefreshToken()
|
||||
try {
|
||||
const accessToken = await refreshAuthenticatedSession()
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
request.headers.Authorization = `Bearer ${accessToken}`
|
||||
return await transport.request(request)
|
||||
} catch (refreshError) {
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
const mappedError = mapError(refreshError)
|
||||
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
||||
if (getRefreshToken() && getRefreshToken() !== refreshTokenBeforeRetry) throw mappedError
|
||||
clearSessionTokens()
|
||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||
redirectToLoginAfterSessionExpiry()
|
||||
@@ -132,6 +188,33 @@ transport.interceptors.response.use(
|
||||
},
|
||||
)
|
||||
|
||||
// Captured revocation never persists credentials or restores local login state.
|
||||
export async function revokeCapturedSession(accessToken: string, refreshToken: string) {
|
||||
logoutGeneration++
|
||||
const identity = accessTokenIdentity(accessToken)
|
||||
if (!identity || !refreshToken) throw new ApiError('服务器会话注销未确认', 'SESSION_CHANGED')
|
||||
const pending = refreshExchange?.identity === identity && refreshExchange.refreshToken === refreshToken ? refreshExchange.promise : null
|
||||
const revoke = (pair: Pick<TokenPair, 'accessToken' | 'refreshToken'>) => apiRequest<void>({
|
||||
method: 'POST', url: '/auth/logout', data: { refreshToken: pair.refreshToken },
|
||||
headers: { Authorization: `Bearer ${pair.accessToken}` },
|
||||
})
|
||||
const validate = (pair: TokenPair) => {
|
||||
if (accessTokenIdentity(pair.accessToken) !== identity || !pair.refreshToken) throw new ApiError('刷新身份不一致,服务器会话注销未确认', 'SESSION_CHANGED')
|
||||
return pair
|
||||
}
|
||||
// An already sent refresh can rotate the pair. Consume its actual result
|
||||
// without issuing a competing refresh or restoring it to local storage.
|
||||
if (pending) {
|
||||
await revoke(validate(await pending))
|
||||
return
|
||||
}
|
||||
try { await revoke({ accessToken, refreshToken }) } catch (error) {
|
||||
if (!(error instanceof ApiError) || error.status !== 401) throw error
|
||||
const pair = await apiRequest<TokenPair>({ method: 'POST', url: '/auth/refresh', data: { refreshToken } })
|
||||
await revoke(validate(pair))
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<ApiEnvelope<T>>(config)
|
||||
@@ -170,8 +253,8 @@ async function throwBlobApiError(error: unknown, responseStatus?: number) {
|
||||
if (!blob || !blob.type.toLowerCase().includes('json')) return
|
||||
try {
|
||||
const body = JSON.parse(await blob.text()) as unknown
|
||||
if (!isApiEnvelope(body)) return
|
||||
const fieldErrors = asFieldErrors(body.data)
|
||||
if (!isApiEnvelope(body) && !isApiFailure(body)) return
|
||||
const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
|
||||
throw new ApiError(
|
||||
apiErrorMessage(body.message, fieldErrors),
|
||||
body.code,
|
||||
|
||||
@@ -26,8 +26,8 @@ test('does not accept malformed or data-less successful responses', () => {
|
||||
assert.equal(isApiEnvelope({ code: '200', message: 'OK', data: [] }), true)
|
||||
})
|
||||
|
||||
test('overseas transport handles business-code and HTTP security failures', async () => {
|
||||
const transport = await readFile(new URL('./overseasHttp.ts', import.meta.url), 'utf8')
|
||||
assert.match(transport, /if \(isApiFailure\(response.data\)\)/)
|
||||
test('unified transport handles business-code and HTTP security failures', async () => {
|
||||
const transport = await readFile(new URL('./http.ts', import.meta.url), 'utf8')
|
||||
assert.match(transport, /if \(isApiFailure\(invalid\)\)/)
|
||||
assert.match(transport, /isApiEnvelope\(body\) \|\| isApiFailure\(body\)/)
|
||||
})
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import axios, { type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||
import { ApiError, isApiEnvelope, isApiFailure } from '@/api/types'
|
||||
import { getOverseasAccessToken } from '@/api/session'
|
||||
import { refreshAuthenticatedSession } from '@/api/http'
|
||||
|
||||
interface RetryableRequest extends InternalAxiosRequestConfig { _retriedOverseasAuth?: boolean }
|
||||
|
||||
const transport = axios.create({
|
||||
baseURL: import.meta.env.VITE_OVERSEAS_API_BASE_URL || '/overseas-api',
|
||||
timeout: 15_000,
|
||||
transformResponse: [(data: unknown) => parseApiJsonResponse(data)],
|
||||
})
|
||||
|
||||
async function requireToken() {
|
||||
const current = getOverseasAccessToken()
|
||||
if (current) return current
|
||||
await refreshAuthenticatedSession()
|
||||
const refreshed = getOverseasAccessToken()
|
||||
if (!refreshed) throw new ApiError('当前环境未签发海外访问令牌', 'OVERSEAS_TOKEN_UNAVAILABLE')
|
||||
return refreshed
|
||||
}
|
||||
|
||||
transport.interceptors.request.use(async (config) => {
|
||||
config.headers.Authorization = `Bearer ${await requireToken()}`
|
||||
return config
|
||||
})
|
||||
|
||||
transport.interceptors.response.use((response) => response, async (error) => {
|
||||
const request = error.config as RetryableRequest | undefined
|
||||
if (error.response?.status !== 401 || !request || request._retriedOverseasAuth) throw error
|
||||
request._retriedOverseasAuth = true
|
||||
await refreshAuthenticatedSession()
|
||||
request.headers.Authorization = `Bearer ${await requireToken()}`
|
||||
return transport.request(request)
|
||||
})
|
||||
|
||||
export async function overseasApiRequest<T>(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<unknown>(config)
|
||||
if (isApiFailure(response.data)) {
|
||||
throw new ApiError(response.data.message, response.data.code, response.status, undefined,
|
||||
response.data.traceId, response.data.requestId)
|
||||
}
|
||||
if (!isApiEnvelope(response.data) || response.data.code !== '200') {
|
||||
throw new ApiError(
|
||||
isApiEnvelope(response.data) ? response.data.message : '海外接口响应格式错误',
|
||||
isApiEnvelope(response.data) ? response.data.code : 'INVALID_RESPONSE',
|
||||
undefined,
|
||||
undefined,
|
||||
isApiEnvelope(response.data) ? response.data.traceId : null,
|
||||
isApiEnvelope(response.data) ? response.data.requestId : null,
|
||||
)
|
||||
}
|
||||
return response.data.data as T
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error
|
||||
if (axios.isAxiosError(error)) {
|
||||
const body = error.response?.data
|
||||
if (isApiEnvelope(body) || isApiFailure(body)) {
|
||||
throw new ApiError(body.message, body.code, error.response?.status, undefined, body.traceId, body.requestId)
|
||||
}
|
||||
throw new ApiError(error.code === 'ERR_NETWORK' ? '无法连接海外服务' : error.message, error.code || 'OVERSEAS_HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
throw new ApiError(error instanceof Error ? error.message : '海外接口请求失败')
|
||||
}
|
||||
}
|
||||
|
||||
export async function overseasBlobRequest(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error
|
||||
if (axios.isAxiosError(error)) {
|
||||
const body = error.response?.data
|
||||
if (body instanceof Blob && body.type.includes('json')) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await body.text())
|
||||
if (isApiEnvelope(parsed) || isApiFailure(parsed)) {
|
||||
throw new ApiError(parsed.message, parsed.code, error.response?.status, undefined, parsed.traceId, parsed.requestId)
|
||||
}
|
||||
} catch (parseError) {
|
||||
if (parseError instanceof ApiError) throw parseError
|
||||
}
|
||||
}
|
||||
throw new ApiError(error.code === 'ERR_NETWORK' ? '无法连接海外服务' : error.message, error.code || 'OVERSEAS_HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
throw new ApiError(error instanceof Error ? error.message : '海外文件下载失败')
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
accessTokenIdentity,
|
||||
ACCESS_TOKEN_KEY,
|
||||
REFRESH_TOKEN_KEY,
|
||||
REMEMBERED_LOGIN_ID_KEY,
|
||||
@@ -56,3 +57,34 @@ test('remembers only the login id and keeps it when session tokens are cleared',
|
||||
persistRememberedLoginId('merchant-user', false)
|
||||
assert.equal(getRememberedLoginId(), '')
|
||||
})
|
||||
|
||||
test('normal token rotation never removes either shared token between writes', () => {
|
||||
installStorage()
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, 'old-access')
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, 'old-refresh')
|
||||
const removed = []
|
||||
const remove = localStorage.removeItem
|
||||
localStorage.removeItem = key => { removed.push(key); remove(key) }
|
||||
persistTokenPair({ accessToken: 'new-access', refreshToken: 'new-refresh' })
|
||||
assert.ok(!removed.includes(ACCESS_TOKEN_KEY))
|
||||
assert.ok(!removed.includes(REFRESH_TOKEN_KEY))
|
||||
})
|
||||
|
||||
function rawIdentity(overrides = '') {
|
||||
return `test.${Buffer.from(`{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"${overrides}}`).toString('base64url')}.test`
|
||||
}
|
||||
test('identity preserves low digits of numeric 19 digit user customer and membership',()=>{
|
||||
const original=rawIdentity();const json=Buffer.from(original.split('.')[1],'base64url').toString();
|
||||
for(const field of ['user_id','tenant_id','membership_id']){
|
||||
const changed=json.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`)
|
||||
assert.notEqual(accessTokenIdentity(original),accessTokenIdentity(`test.${Buffer.from(changed).toString('base64url')}.test`))
|
||||
}
|
||||
})
|
||||
test('identity string and numeric integers are equivalent without changing other strings',()=>{
|
||||
const a=rawIdentity();const raw=Buffer.from(a.split('.')[1],'base64url').toString();
|
||||
const b=`test.${Buffer.from(raw.replaceAll(':2107003446494334978',':"2107003446494334978"')).toString('base64url')}.test`
|
||||
assert.equal(accessTokenIdentity(a),accessTokenIdentity(b))
|
||||
const decorated=rawIdentity(',"username":'+JSON.stringify('number 2107003446494334979 and "tenant_id":2107003446494334979')+',"note":"1234567890123456789"')
|
||||
assert.equal(accessTokenIdentity(a),accessTokenIdentity(decorated))
|
||||
assert.ok(accessTokenIdentity(a).includes('2107003446494334978'))
|
||||
})
|
||||
|
||||
+29
-20
@@ -1,7 +1,5 @@
|
||||
export const ACCESS_TOKEN_KEY = 'cc-client-access-token'
|
||||
export const REFRESH_TOKEN_KEY = 'cc-client-refresh-token'
|
||||
export const OVERSEAS_ACCESS_TOKEN_KEY = 'cc-client-overseas-access-token'
|
||||
export const OVERSEAS_EXPIRES_AT_KEY = 'cc-client-overseas-expires-at'
|
||||
export const REMEMBERED_LOGIN_ID_KEY = 'cc-client-remembered-login-id'
|
||||
|
||||
export interface TokenPair {
|
||||
@@ -10,14 +8,8 @@ export interface TokenPair {
|
||||
expiresIn: number
|
||||
refreshToken: string
|
||||
refreshExpiresIn: number
|
||||
overseasAccessToken?: string | null
|
||||
overseasExpiresIn?: number
|
||||
}
|
||||
|
||||
function activeStorage() {
|
||||
if (localStorage.getItem(ACCESS_TOKEN_KEY)) return localStorage
|
||||
return sessionStorage
|
||||
}
|
||||
|
||||
export function getAccessToken() {
|
||||
return localStorage.getItem(ACCESS_TOKEN_KEY) || sessionStorage.getItem(ACCESS_TOKEN_KEY) || ''
|
||||
@@ -27,21 +19,40 @@ export function getRefreshToken() {
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
export function getOverseasAccessToken() {
|
||||
const storage = activeStorage()
|
||||
const expiresAt = Number(storage.getItem(OVERSEAS_EXPIRES_AT_KEY) || 0)
|
||||
if (expiresAt <= Date.now() + 30_000) return ''
|
||||
return storage.getItem(OVERSEAS_ACCESS_TOKEN_KEY) || ''
|
||||
// Only binds a retry to its original identity; never grants permissions. Expired
|
||||
// access tokens remain readable here because they are the normal refresh trigger.
|
||||
export function accessTokenIdentity(token: string): string | null {
|
||||
try {
|
||||
const encoded = token.split('.')[1]
|
||||
if (!encoded) return null
|
||||
const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const bytes = Uint8Array.from(atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')), character => character.charCodeAt(0))
|
||||
const json = new TextDecoder().decode(bytes)
|
||||
// Match whole JSON strings first so digits inside arbitrary string values
|
||||
// are never rewritten. Preserve integer identity claims before JSON.parse
|
||||
// can round them; number/string representations then share one identity.
|
||||
const exactIdentityJson = json.replace(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (part, offset: number) => {
|
||||
if (!/^-?\d+$/.test(part)) return part
|
||||
const key = json.slice(0, offset).match(/"(user_id|tenant_id|membership_id|operator_tenant_id)"\s*:\s*$/)
|
||||
return key ? JSON.stringify(part) : part
|
||||
})
|
||||
const value = JSON.parse(exactIdentityJson)
|
||||
if (!value?.user_id || !value.tenant_id || !value.membership_id || value.app_code !== 'MERCHANT') return null
|
||||
return JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type].map(item => item == null ? null : String(item)))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function persistTokenPair(tokens: TokenPair) {
|
||||
clearSessionTokens()
|
||||
// Replace the pair without publishing a transient logout to other tabs.
|
||||
sessionStorage.removeItem(ACCESS_TOKEN_KEY)
|
||||
sessionStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
sessionStorage.removeItem('cc-client-token')
|
||||
localStorage.removeItem('cc-client-token')
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
|
||||
if (tokens.overseasAccessToken && Number(tokens.overseasExpiresIn) > 0) {
|
||||
localStorage.setItem(OVERSEAS_ACCESS_TOKEN_KEY, tokens.overseasAccessToken)
|
||||
localStorage.setItem(OVERSEAS_EXPIRES_AT_KEY, String(Date.now() + Number(tokens.overseasExpiresIn) * 1000))
|
||||
}
|
||||
}
|
||||
|
||||
export function getRememberedLoginId() {
|
||||
@@ -62,8 +73,6 @@ export function clearSessionTokens() {
|
||||
for (const storage of [localStorage, sessionStorage]) {
|
||||
storage.removeItem(ACCESS_TOKEN_KEY)
|
||||
storage.removeItem(REFRESH_TOKEN_KEY)
|
||||
storage.removeItem(OVERSEAS_ACCESS_TOKEN_KEY)
|
||||
storage.removeItem(OVERSEAS_EXPIRES_AT_KEY)
|
||||
storage.removeItem('cc-client-token')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import axios from 'axios'
|
||||
|
||||
function compile(name, dependencies = {}) {
|
||||
const source = readFileSync(new URL(name, import.meta.url), 'utf8')
|
||||
.replace('import.meta.env.VITE_API_BASE_URL', "'/api'")
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)((id) => {
|
||||
assert.ok(id in dependencies, `unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports)
|
||||
return exports
|
||||
}
|
||||
|
||||
function access(user, tenant = 1, membership = 1, nonce = 'original') {
|
||||
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, app_code: 'MERCHANT', nonce })).toString('base64url')}.test`
|
||||
}
|
||||
const oldAccess = access(1)
|
||||
const newAccess = access(1, 1, 1, 'rotated')
|
||||
const otherAccess = access(2, 2, 2)
|
||||
|
||||
function harness(adapter) {
|
||||
let token = oldAccess
|
||||
let refreshToken = 'old-refresh'
|
||||
const http = compile('./http.ts', {
|
||||
axios: { ...axios, create: (config) => axios.create({ ...config, adapter }) },
|
||||
'@chongchong/shared': { parseApiJsonResponse: (data) => data },
|
||||
'@/api/session': {
|
||||
accessTokenIdentity: compile('./session.ts').accessTokenIdentity,
|
||||
getAccessToken: () => token, getRefreshToken: () => refreshToken,
|
||||
persistTokenPair: (tokens) => { token = tokens.accessToken; refreshToken = tokens.refreshToken },
|
||||
clearSessionTokens: () => { token = ''; refreshToken = '' },
|
||||
},
|
||||
'@/api/errorDetails': compile('./errorDetails.ts'),
|
||||
'@/api/types': compile('./types.ts'),
|
||||
'@/api/crossTabRefresh': compile('./crossTabRefresh.ts'),
|
||||
})
|
||||
return { ...http, setSession: (access, refresh) => { token = access; refreshToken = refresh }, session: () => ({ token, refreshToken }) }
|
||||
}
|
||||
|
||||
test('order and lastleg 401s share one refresh and replay the unified access token', async () => {
|
||||
let refreshes = 0
|
||||
const calls = []
|
||||
const http = harness(async (config) => {
|
||||
calls.push({ url: config.url, base: config.baseURL, token: config.headers.Authorization })
|
||||
if (config.url === '/auth/refresh') {
|
||||
refreshes++
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||
}
|
||||
if (config.headers.Authorization === `Bearer ${oldAccess}`) {
|
||||
throw new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||
}
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: config.url } }
|
||||
})
|
||||
const urls = ['/merchant/v1/orders', '/merchant/v1/last-leg/inbound-plans']
|
||||
assert.deepEqual(await Promise.all(urls.map((url) => http.apiRequest({ url }))), urls)
|
||||
assert.equal(refreshes, 1)
|
||||
assert.ok(calls.every((call) => call.base === '/api'))
|
||||
assert.equal(calls.find((call) => call.url === '/auth/refresh').token, undefined)
|
||||
assert.equal(calls.filter((call) => call.token === `Bearer ${newAccess}`).length, 2)
|
||||
})
|
||||
|
||||
test('successful order submit with explicit null data is accepted', async () => {
|
||||
const http = harness(async (config) => ({
|
||||
config, status: 200, headers: {}, data: { code: '200', message: 'success', data: null },
|
||||
}))
|
||||
assert.equal(await http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/order-1/submit' }), null)
|
||||
})
|
||||
|
||||
test('data-less security failures preserve diagnostics and malformed success is rejected', async () => {
|
||||
for (const data of [{ code: 'A0403', message: 'Denied', traceId: 'trace-1', requestId: 'request-1' }, { code: '200', message: 'OK' }]) {
|
||||
const http = harness(async (config) => ({ config, status: 200, headers: {}, data }))
|
||||
await assert.rejects(http.apiRequest({ url: '/merchant/v1/last-leg/inbound-plans' }), (error) => {
|
||||
assert.equal(error.code, data.code === '200' ? 'INVALID_RESPONSE' : 'A0403')
|
||||
if (data.code !== '200') { assert.equal(error.traceId, 'trace-1'); assert.equal(error.requestId, 'request-1') }
|
||||
return true
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test('late refresh response cannot overwrite a session changed in another tab', async () => {
|
||||
let complete, started
|
||||
const ready = new Promise(resolve => { started = resolve })
|
||||
const response = new Promise(resolve => { complete = resolve })
|
||||
const http = harness(async config => { started(); await response; return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: oldAccess, refreshToken: 'stale-refresh' } } } })
|
||||
const pending = http.refreshAuthenticatedSession()
|
||||
await ready
|
||||
http.setSession(otherAccess, 'other-refresh')
|
||||
complete()
|
||||
await pending.catch(error => assert.equal(error.code, 'SESSION_CHANGED'))
|
||||
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'other-refresh' })
|
||||
})
|
||||
|
||||
function deferred() { let resolve; const promise = new Promise(yes => { resolve = yes }); return { promise, resolve } }
|
||||
|
||||
function unauthorized(config) {
|
||||
return new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||
}
|
||||
|
||||
test('late A write 401 after user, customer or membership switch never refreshes or replays under B', async () => {
|
||||
for (const next of [access(2), access(1, 2), access(1, 1, 2)]) {
|
||||
const sent = deferred(), release = deferred(), calls = []
|
||||
const http = harness(async config => {
|
||||
calls.push(config.url); sent.resolve(); await release.promise
|
||||
throw unauthorized(config)
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit', data: { expectedVersion: 1 } })
|
||||
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||
await sent.promise; http.setSession(next, 'refresh-b'); release.resolve(); await rejected
|
||||
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit'])
|
||||
assert.deepEqual(http.session(), { token: next, refreshToken: 'refresh-b' })
|
||||
}
|
||||
})
|
||||
|
||||
test('switch during in-flight refresh cannot reuse B token to replay an A write', async () => {
|
||||
const refreshing = deferred(), release = deferred(), calls = []
|
||||
const http = harness(async config => {
|
||||
calls.push(config.url)
|
||||
if (config.url === '/auth/refresh') {
|
||||
refreshing.resolve(); await release.promise
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||
}
|
||||
throw unauthorized(config)
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||
await refreshing.promise; http.setSession(otherAccess, 'refresh-b'); release.resolve(); await rejected
|
||||
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit', '/auth/refresh'])
|
||||
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'refresh-b' })
|
||||
})
|
||||
|
||||
test('refresh lock wait reuses same-identity rotation but rejects changed-identity reuse', async t => {
|
||||
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
|
||||
t.after(() => { if (originalNavigator) Object.defineProperty(globalThis, 'navigator', originalNavigator); else delete globalThis.navigator })
|
||||
for (const next of [newAccess, otherAccess]) {
|
||||
const waiting = deferred(), release = deferred(), calls = []
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: { request: async (_name, _options, run) => {
|
||||
waiting.resolve(); await release.promise; return run()
|
||||
} } } })
|
||||
const http = harness(async config => {
|
||||
calls.push({ url: config.url, authorization: config.headers.Authorization })
|
||||
if (config.headers.Authorization === `Bearer ${oldAccess}`) throw unauthorized(config)
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: null } }
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||
const outcome = next === otherAccess ? assert.rejects(pending, error => error.code === 'SESSION_CHANGED') : pending
|
||||
await waiting.promise; http.setSession(next, 'rotated-refresh'); release.resolve(); await outcome
|
||||
assert.equal(calls.some(call => call.url === '/auth/refresh'), false)
|
||||
assert.equal(calls.length, next === otherAccess ? 1 : 2)
|
||||
assert.deepEqual(http.session(), { token: next, refreshToken: 'rotated-refresh' })
|
||||
}
|
||||
})
|
||||
|
||||
function authApi(http) { return compile('../modules/auth/api/auth.ts', { '@/api/http': http }) }
|
||||
function ok(config, data = null) { return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data } } }
|
||||
test('logout after immediate local clear revokes captured Bearer and Refresh', async () => {
|
||||
const calls=[]; const http=harness(async c=>{calls.push(c);return ok(c)})
|
||||
http.setSession('', '');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||
assert.equal(calls.length,1);assert.equal(calls[0].headers.Authorization,`Bearer ${oldAccess}`)
|
||||
assert.deepEqual(JSON.parse(calls[0].data),{refreshToken:'old-refresh'});assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('only explicit logout401 refreshes once and revokes same-identity replacement without storing it', async () => {
|
||||
const calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'});if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||
http.setSession('','');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||
assert.deepEqual(calls.map(x=>x.url),['/auth/logout','/auth/refresh','/auth/logout']);assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[2].data).refreshToken,'new-refresh');assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('unknown logout failure never refreshes; changed identity cannot be revoked as replacement', async () => {
|
||||
for(const mode of ['network','wrongIdentity','second401']){const calls=[];const http=harness(async c=>{calls.push(c);if(mode==='network')throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c);if(c.url==='/auth/refresh')return ok(c,{accessToken:mode==='wrongIdentity'?otherAccess:newAccess,refreshToken:'replacement'});throw unauthorized(c)})
|
||||
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(oldAccess,'old-refresh'));assert.equal(calls.length,mode==='network'?1:mode==='wrongIdentity'?2:3);assert.deepEqual(http.session(),{token:'',refreshToken:''})}
|
||||
})
|
||||
test('logout consumes already inflight refresh once while old business caller cannot revive session',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}return ok(c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');release.resolve();await leaving;await rejected
|
||||
assert.deepEqual(calls.map(x=>x.url),['/auth/refresh','/auth/logout']);assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('late successful business response after logout rejects even after same-identity new login',async()=>{
|
||||
const started=deferred(),release=deferred();const http=harness(async c=>{if(c.url==='/merchant/v1/orders'){started.resolve();await release.promise}return ok(c,'old-data')})
|
||||
const pending=http.apiRequest({url:'/merchant/v1/orders'});const rejected=assert.rejects(pending,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||
await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected;assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||
})
|
||||
|
||||
test('inflight refresh unknown outcome stops logout without competing retry and preserves later login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);started.resolve();await release.promise;throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');const failure=assert.rejects(leaving,e=>e.code==='NETWORK_ERROR');http.setSession(otherAccess,'other-refresh');release.resolve();await failure;await rejected
|
||||
assert.equal(calls.length,1);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||
})
|
||||
test('logout401 refresh and replacement revocation cannot overwrite later login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');await started.promise;http.setSession(otherAccess,'other-refresh');release.resolve();await leaving
|
||||
assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||
})
|
||||
test('late old business401 after logout does not refresh or replay under same-identity new login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/merchant/v1/orders/first-leg/one/submit'){started.resolve();await release.promise;throw unauthorized(c)}return ok(c)})
|
||||
const request=http.apiRequest({method:'POST',url:'/merchant/v1/orders/first-leg/one/submit'});const rejected=assert.rejects(request,e=>e.code==='SESSION_CHANGED');await started.promise;await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected
|
||||
assert.deepEqual(calls.map(x=>x.url),['/merchant/v1/orders/first-leg/one/submit','/auth/logout']);assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||
})
|
||||
|
||||
test('same identity new pair logout does not adopt another session inflight refresh',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'old-session-rotated'})}return ok(c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise;http.setSession(newAccess,'new-login-refresh')
|
||||
const leaving=authApi(http).logoutMerchant(newAccess,'new-login-refresh');http.setSession('','');await leaving
|
||||
assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[1].data).refreshToken,'new-login-refresh');release.resolve();await rejected;assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
|
||||
test('logout rejects refreshed 19 digit identity differing only in low digit',async()=>{
|
||||
const raw='{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"}'
|
||||
const original=`test.${Buffer.from(raw).toString('base64url')}.test`
|
||||
for(const field of ['user_id','tenant_id','membership_id']){
|
||||
const changed=raw.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`),calls=[]
|
||||
const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:`test.${Buffer.from(changed).toString('base64url')}.test`,refreshToken:'replacement'});throw unauthorized(c)})
|
||||
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(original,'original-refresh'),e=>e.code==='SESSION_CHANGED');assert.equal(calls.length,2)
|
||||
}
|
||||
})
|
||||
Vendored
+1
@@ -42,6 +42,7 @@ declare module 'vue' {
|
||||
ElRadio: typeof import('element-plus/es')['ElRadio']
|
||||
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
||||
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
||||
ElResult: typeof import('element-plus/es')['ElResult']
|
||||
ElSelect: typeof import('element-plus/es')['ElSelect']
|
||||
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
|
||||
ElSwitch: typeof import('element-plus/es')['ElSwitch']
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue'
|
||||
import {
|
||||
clientNavigation,
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getNavigationParentKeys,
|
||||
} from '@/navigation/clientNavigation'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import { useCustomsPendingStore } from '@/modules/first-leg/public'
|
||||
|
||||
const props = defineProps<{
|
||||
activePath: string
|
||||
@@ -16,10 +17,34 @@ const emit = defineEmits<{
|
||||
navigate: [path: string]
|
||||
}>()
|
||||
const auth = useAuthStore()
|
||||
const customsPending = useCustomsPendingStore()
|
||||
const badges = computed(() => ({ 'first-leg-customs-documents': { count: customsPending.count, error: customsPending.error } }))
|
||||
watch(() => auth.isAuthenticated && auth.hasPermission('order:first-leg:customs-list') ? auth.user?.id ?? '' : '', scope => {
|
||||
customsPending.setScope(scope)
|
||||
if (scope) void customsPending.refresh()
|
||||
}, { immediate: true, flush: 'sync' })
|
||||
function refreshCustomsPending() {
|
||||
if (document.visibilityState === 'visible') void customsPending.refresh()
|
||||
}
|
||||
let refreshTimer: ReturnType<typeof setInterval> | undefined
|
||||
onMounted(() => {
|
||||
refreshTimer = setInterval(refreshCustomsPending, 60_000)
|
||||
window.addEventListener('focus', refreshCustomsPending)
|
||||
document.addEventListener('visibilitychange', refreshCustomsPending)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
clearInterval(refreshTimer)
|
||||
window.removeEventListener('focus', refreshCustomsPending)
|
||||
document.removeEventListener('visibilitychange', refreshCustomsPending)
|
||||
customsPending.setScope('')
|
||||
})
|
||||
|
||||
const visibleNavigation = computed(() => filterNavigationByPermissions(clientNavigation, auth.permissionCodes))
|
||||
|
||||
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath)))
|
||||
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) {
|
||||
const next = new Set(openedKeys.value)
|
||||
@@ -47,6 +72,7 @@ function handleSelect(path: string) {
|
||||
v-for="node in visibleNavigation"
|
||||
:key="node.key"
|
||||
:node="node"
|
||||
:badges="badges"
|
||||
:active-path="activePath"
|
||||
:opened-keys="openedKeys"
|
||||
:active-parent-keys="activeParentKeys"
|
||||
|
||||
@@ -8,6 +8,7 @@ const props = defineProps<{
|
||||
activePath: string
|
||||
openedKeys: ReadonlySet<string>
|
||||
activeParentKeys: ReadonlySet<string>
|
||||
badges?: Readonly<Record<string, { count: number | null; error: string }>>
|
||||
level?: number
|
||||
}>()
|
||||
|
||||
@@ -16,6 +17,9 @@ const emit = defineEmits<{
|
||||
toggle: [key: string]
|
||||
}>()
|
||||
|
||||
const badge = computed(() => props.badges?.[props.node.key])
|
||||
const badgeTitle = computed(() => badge.value?.error || `${badge.value?.count ?? 0} 个柜次待上传资料或确认回执`)
|
||||
|
||||
const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
||||
</script>
|
||||
|
||||
@@ -54,6 +58,7 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
||||
v-for="child in node.children"
|
||||
:key="child.key"
|
||||
:node="child"
|
||||
:badges="badges"
|
||||
:active-path="activePath"
|
||||
:opened-keys="openedKeys"
|
||||
:active-parent-keys="activeParentKeys"
|
||||
@@ -78,6 +83,14 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span>{{ node.title }}</span>
|
||||
<span v-if="badge?.error || (badge?.count != null && badge.count > 0)" class="client-nav-badge"
|
||||
:title="badgeTitle" :aria-label="badgeTitle" role="status">
|
||||
{{ badge?.error ? '!' : badge!.count! > 99 ? '99+' : badge?.count }}
|
||||
</span>
|
||||
</RouterLink>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.client-sidebar-link .client-nav-badge { display: inline-flex; flex: 0 0 auto; min-width: 23px; height: 23px; align-items: center; justify-content: center; margin-left: auto; padding: 0 5px; border: 2px solid #fff; border-radius: 999px; background: #ef4444; color: #fff; box-shadow: 0 3px 9px rgb(239 68 68 / 24%); font-size: 12px; font-weight: 700; line-height: 1; }
|
||||
</style>
|
||||
|
||||
@@ -1,9 +1,76 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { parse, compileScript } from 'vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./DataTable.vue', import.meta.url), 'utf8')
|
||||
|
||||
function paginationHarness(t) {
|
||||
const descriptor = parse(source).descriptor
|
||||
const compiled = compileScript(descriptor, { id: 'data-table-pagination-test' })
|
||||
const code = ts.transpileModule(compiled.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
const deps = { vue, '@lucide/vue': { ChevronLeft: {}, ChevronRight: {} }, './tableActions': {} }
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||
const component = exports.default
|
||||
component.render = () => null
|
||||
const state = vue.reactive({ page: 5, total: 5542, loading: false, error: false })
|
||||
const emitted = []
|
||||
const renderer = vue.createRenderer({
|
||||
createElement: tag => ({ tag }), createText: text => ({ text }), createComment: text => ({ text }),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const app = renderer.createApp({ render: () => vue.h(component, {
|
||||
data: [], columns: [], page: state.page, pageSize: 50, total: state.total, loading: state.loading,
|
||||
'onUpdate:page': value => { emitted.push(value); state.page = value },
|
||||
}, state.error ? { error: () => vue.h('div', 'Request failed') } : {}) })
|
||||
app.mount({})
|
||||
t.after(() => app.unmount())
|
||||
return { state, emitted }
|
||||
}
|
||||
|
||||
test('server-page loading must not reset the requested page when total temporarily clears', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.loading = true; state.total = 0
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
state.total = 5542; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
})
|
||||
|
||||
test('failed server page retains its page for explicit retry and emits no automatic fallback request', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.loading = true; state.total = 0
|
||||
await vue.nextTick()
|
||||
state.error = true; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
state.error = false; state.loading = true
|
||||
await vue.nextTick()
|
||||
state.total = 5542; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
})
|
||||
|
||||
test('settled successful totals still clamp out-of-range and empty pages', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.total = 120
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 3)
|
||||
state.total = 0
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 1)
|
||||
assert.deepEqual(emitted, [3, 1])
|
||||
})
|
||||
|
||||
test('keeps action-only table toolbars on the left', () => {
|
||||
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
|
||||
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
|
||||
|
||||
@@ -88,7 +88,9 @@ watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
|
||||
page.value = 1
|
||||
}, { immediate: true })
|
||||
|
||||
watch([page, pageCount], ([value, count]) => {
|
||||
watch([page, pageCount, () => props.loading, () => Boolean(slots.error)], ([value, count, loading, hasError]) => {
|
||||
// A cleared total is not an authoritative page count while loading or showing a request error.
|
||||
if (loading || hasError) return
|
||||
const nextValue = normalizePage(value, count)
|
||||
if (value !== nextValue) page.value = nextValue
|
||||
}, { immediate: true })
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import test from 'node:test'
|
||||
|
||||
const script = (await readFile(new URL('../../scripts/deploy-production.sh', import.meta.url), 'utf8'))
|
||||
.replaceAll('\r\n', '\n')
|
||||
const compose = (await readFile(new URL('../../docker-compose.production.yml', import.meta.url), 'utf8'))
|
||||
.replaceAll('\r\n', '\n')
|
||||
|
||||
test('client production deployment switches healthy blue-green slots atomically', () => {
|
||||
const start = script.indexOf('compose run -d --no-deps --name "$candidate"')
|
||||
const health = script.indexOf('docker exec "$candidate" wget')
|
||||
const nginx = script.indexOf('nginx -t || ! nginx -s reload')
|
||||
const stop = script.indexOf('docker stop --time 30 "$active_container"')
|
||||
assert.ok(start >= 0 && start < health && health < nginx && nginx < stop)
|
||||
assert.match(script, /target_port=\$\(\(base_port \+ 20000\)\)/)
|
||||
assert.match(script, /target_port=\$\(\(base_port \+ 10000\)\)/)
|
||||
assert.match(script, /00-blue-green-admin-web\.conf/)
|
||||
assert.match(script, /00-blue-green-client-web\.conf/)
|
||||
assert.doesNotMatch(script, /nginx_config=\/www\/server\/panel\/vhost\/nginx\/(?:admin|app)\.buggoglobal\.com\.conf/)
|
||||
assert.match(script, /cp -f "\$backup" "\$nginx_config"/)
|
||||
})
|
||||
|
||||
test('client uses stable active gateway aliases on the routing network', () => {
|
||||
assert.match(compose, /API_UPSTREAM: "http:\/\/gateway-active:9000"/)
|
||||
assert.match(compose, /OVERSEAS_API_UPSTREAM: "http:\/\/gateway-overseas-active:9300"/)
|
||||
assert.match(compose, /name: firstleg-production-routing/)
|
||||
})
|
||||
@@ -1,67 +1,63 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { readFileSync, existsSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const config = readFileSync(new URL('../../nginx/default.conf.template', import.meta.url), 'utf8')
|
||||
const testCompose = readFileSync(new URL('../../docker-compose.test.yml', import.meta.url), 'utf8')
|
||||
const developmentCompose = readFileSync(new URL('../../docker-compose.development.yml', import.meta.url), 'utf8')
|
||||
const productionCompose = readFileSync(new URL('../../docker-compose.production.yml', import.meta.url), 'utf8')
|
||||
const jenkinsfile = readFileSync(new URL('../../Jenkinsfile', import.meta.url), 'utf8')
|
||||
const dockerfile = readFileSync(new URL('../../Dockerfile', import.meta.url), 'utf8')
|
||||
const root = new URL('../../', import.meta.url)
|
||||
const config = readFileSync(new URL('nginx/default.conf.template', root), 'utf8')
|
||||
const compose = readFileSync(new URL('docker-compose.test.yml', root), 'utf8')
|
||||
const jenkins = readFileSync(new URL('Jenkinsfile', root), 'utf8')
|
||||
const vite = readFileSync(new URL('vite.config.ts', root), 'utf8')
|
||||
|
||||
test('allows 50 MiB uploads with multipart overhead through both API proxies', () => {
|
||||
assert.match(config, /location \/api\/ \{[\s\S]*?client_max_body_size 55m;/)
|
||||
assert.match(config, /location \/overseas-api\/ \{[\s\S]*?client_max_body_size 55m;/)
|
||||
assert.equal(config.match(/client_max_body_size 55m;/g)?.length, 2)
|
||||
})
|
||||
|
||||
test('does not cache the SPA entry while keeping hashed assets immutable', () => {
|
||||
assert.match(config, /location = \/index\.html[\s\S]*no-store, no-cache, must-revalidate/)
|
||||
assert.match(config, /location \/assets\/[\s\S]*max-age=31536000, immutable/)
|
||||
assert.match(config, /location \/ \{[\s\S]*no-store, no-cache, must-revalidate[\s\S]*try_files \$uri \$uri\/ \/index\.html/)
|
||||
})
|
||||
|
||||
test('routes domestic and overseas browser APIs to their test gateways without duplicate api prefixes', () => {
|
||||
assert.match(testCompose, /- "host\.docker\.internal:host-gateway"/)
|
||||
assert.match(testCompose, /API_UPSTREAM: "\$\{API_UPSTREAM:-http:\/\/host\.docker\.internal:9000\}"/)
|
||||
assert.match(testCompose, /OVERSEAS_API_UPSTREAM: "\$\{OVERSEAS_API_UPSTREAM:-http:\/\/host\.docker\.internal:9300\}"/)
|
||||
assert.doesNotMatch(testCompose, /http:\/\/test-api-(?:cn|global)\.buggoglobal\.com/)
|
||||
assert.match(testCompose, /VITE_ADMIN_WEB_ORIGIN: "\$\{VITE_ADMIN_WEB_ORIGIN:-https:\/\/test-admin\.buggoglobal\.com\}"/)
|
||||
assert.match(config, /location \/overseas-api\/ \{[\s\S]*?rewrite \^\/overseas-api\/\(\.\*\)\$ \/api\/\$1 break;[\s\S]*?proxy_pass \$\{OVERSEAS_API_UPSTREAM\};/)
|
||||
test('all business traffic uses one Gateway without rewriting API paths', () => {
|
||||
assert.match(config, /location \/api\//)
|
||||
assert.match(config, /proxy_pass \$\{API_UPSTREAM\};/)
|
||||
assert.doesNotMatch(config, /overseas-api|OVERSEAS_API_UPSTREAM|rewrite/)
|
||||
assert.match(config, /client_max_body_size 55m;/)
|
||||
assert.match(config, /proxy_set_header Host \$proxy_host;/)
|
||||
assert.doesNotMatch(config, /\/api\/api/)
|
||||
assert.doesNotMatch(vite, /OVERSEAS_API|AUTH_API_PROXY_TARGET|IAM_API_PROXY_TARGET|WAREHOUSE_API_PROXY_TARGET/)
|
||||
})
|
||||
|
||||
test('connects the development client proxy to both development gateways', () => {
|
||||
assert.match(developmentCompose, /API_UPSTREAM: "http:\/\/firstleg-development-gateway:9000"/)
|
||||
assert.match(developmentCompose, /OVERSEAS_API_UPSTREAM: "http:\/\/firstleg-development-gateway-overseas:9300"/)
|
||||
assert.match(developmentCompose, /- development-backend/)
|
||||
assert.match(developmentCompose, /- development-overseas-backend/)
|
||||
assert.match(developmentCompose, /development-overseas-backend:[\s\S]*?external: true[\s\S]*?name: firstleg-development-overseas-network/)
|
||||
assert.doesNotMatch(developmentCompose, /test-api|prod(?:uction)?/i)
|
||||
test('test deployment requires an explicit shared network, Gateway and version', () => {
|
||||
for (const key of ['IMAGE_TAG']) {
|
||||
assert.ok(compose.includes('${' + key + ':?'))
|
||||
}
|
||||
assert.ok(compose.includes('${API_UPSTREAM:-http://gateway:9000}'))
|
||||
assert.ok(compose.includes('${TEST_NETWORK:-firstleg-test-network}'))
|
||||
assert.match(compose, /external: true/)
|
||||
assert.match(compose, /127\.0\.0\.1:/)
|
||||
assert.doesNotMatch(compose, /overseas|host\.docker\.internal|production|development/)
|
||||
assert.match(jenkins, /'java-builder' : 'java-test'/)
|
||||
assert.match(jenkins, /docker compose -f docker-compose\.test\.yml config --quiet/)
|
||||
assert.match(jenkins, /docker network inspect/)
|
||||
assert.match(jenkins, /scripts\/deploy-production\.sh/)
|
||||
assert.match(jenkins, /firstleg-production-ssh/)
|
||||
|
||||
})
|
||||
|
||||
test('keeps local environments on target nodes and uses credential-managed SSH for production', () => {
|
||||
assert.match(jenkinsfile, /env\.JOB_BASE_NAME\?\.endsWith\('-prod'\) \? 'java-builder'/)
|
||||
assert.match(jenkinsfile, /DEVELOPMENT_COMPOSE_PROJECT = 'client-web'/)
|
||||
assert.match(jenkinsfile, /docker compose -p "\$DEVELOPMENT_COMPOSE_PROJECT" -f "\$DEVELOPMENT_COMPOSE_FILE" up -d/)
|
||||
assert.doesNotMatch(jenkinsfile, /\/var\/jenkins_home\/\.ssh|docker save/)
|
||||
assert.match(jenkinsfile, /credentialsId: 'firstleg-production-ssh'/)
|
||||
assert.match(jenkinsfile, /git rev-parse origin\/main/)
|
||||
assert.match(productionCompose, /127\.0\.0\.1:\$\{HOST_PORT:-9002\}:80/)
|
||||
assert.match(productionCompose, /API_UPSTREAM: "http:\/\/gateway-active:9000"/)
|
||||
assert.match(productionCompose, /OVERSEAS_API_UPSTREAM: "http:\/\/gateway-overseas-active:9300"/)
|
||||
assert.match(productionCompose, /name: firstleg-production-routing/)
|
||||
assert.match(productionCompose, /name: firstleg-prod-infra-network/)
|
||||
test('application shell is revalidated and missing chunks remain 404', () => {
|
||||
assert.match(config, /location = \/index\.html/)
|
||||
assert.match(config, /no-store/)
|
||||
assert.match(config, /max-age=31536000, immutable/)
|
||||
assert.match(config, /try_files \$uri =404;/)
|
||||
assert.match(config, /try_files \$uri \$uri\/ \/index\.html;/)
|
||||
})
|
||||
|
||||
test('uses authenticated internal base images in CI', () => {
|
||||
assert.match(dockerfile, /ARG NODE_IMAGE=node:22-alpine/)
|
||||
assert.match(dockerfile, /ARG NGINX_IMAGE=nginx:1\.27-alpine/)
|
||||
assert.match(dockerfile, /FROM \$\{NODE_IMAGE\} AS build/)
|
||||
assert.match(dockerfile, /FROM \$\{NGINX_IMAGE\}/)
|
||||
assert.match(jenkinsfile, /NODE_BASE_IMAGE = '172\.31\.198\.7:10082\/java-project\/node:22-alpine'/)
|
||||
assert.match(jenkinsfile, /NGINX_BASE_IMAGE = '172\.31\.198\.7:10082\/java-project\/nginx:1\.27-alpine'/)
|
||||
assert.match(jenkinsfile, /withCredentials\(\[usernamePassword\(/)
|
||||
assert.match(jenkinsfile, /export DOCKER_CONFIG="\$\{WORKSPACE\}@tmp\/docker-auth"/)
|
||||
|
||||
test('container build excludes local environment values and waits for Nginx health', () => {
|
||||
const ignore = readFileSync(new URL('.dockerignore', root), 'utf8')
|
||||
assert.match(ignore, /^\.env$/m)
|
||||
assert.match(ignore, /^\.env\.\*$/m)
|
||||
assert.match(compose, /healthcheck:/)
|
||||
assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
|
||||
assert.match(jenkins, /up -d --wait --wait-timeout 120/)
|
||||
})
|
||||
|
||||
test('gray production is isolated from TEST and routes to the single Gateway', () => {
|
||||
const production = readFileSync(new URL('docker-compose.production.yml', root), 'utf8')
|
||||
assert.match(production, /name: firstleg-production-network/)
|
||||
assert.match(production, /API_UPSTREAM: "http:\/\/gateway:9000"/)
|
||||
assert.match(production, /127\.0\.0\.1:/)
|
||||
assert.match(production, /healthcheck:/)
|
||||
assert.doesNotMatch(production, /test-network|gateway-overseas|gateway-active|routing-network/)
|
||||
assert.doesNotMatch(jenkins, /wecom|sendProductionWeComNotification/)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
||||
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
||||
@@ -108,7 +110,7 @@ test('source contract: locks body scrolling while open and restores it on close
|
||||
})
|
||||
|
||||
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
|
||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*try \{/)
|
||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*const logoutToken = auth.token\s*try \{/)
|
||||
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
||||
})
|
||||
|
||||
@@ -148,3 +150,49 @@ test('source contract: routes denied pages to an explicit 403 state', () => {
|
||||
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
||||
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
||||
})
|
||||
|
||||
function logoutHarness(t) {
|
||||
const script = layoutSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('layout.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const nodes = ast.statements.filter(node => (ts.isFunctionDeclaration(node) && node.name?.text === 'handleLogout') || (ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes('() => auth.isAuthenticated')))
|
||||
const code = ts.transpileModule(nodes.map(node => node.getText(ast)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
let rejectLogout, confirm
|
||||
const remote = new Promise((_, no) => { rejectLogout = no })
|
||||
const confirmation = new Promise(yes => { confirm = yes })
|
||||
const calls = [], warnings = []
|
||||
const auth = vue.reactive({ token: 'A', isAuthenticated: true, logout: () => { calls.push('logout'); auth.token = ''; auth.isAuthenticated = false; return remote } })
|
||||
const scope = vue.effectScope(); t.after(() => scope.stop())
|
||||
const handler = scope.run(() => new Function('watch', 'auth', 'workspace', 'unsaved', 'router', 'ElMessageBox', 'ElMessage', code + ';return handleLogout')(vue.watch, auth, { clear: () => calls.push('workspace') }, { hasDirty: false, clear: () => calls.push('unsaved') }, { replace: path => { calls.push(path); return Promise.resolve() } }, { confirm: () => confirmation }, { warning: value => warnings.push(value) }))
|
||||
return { auth, handler, confirm, rejectLogout, calls, warnings }
|
||||
}
|
||||
|
||||
test('logout navigates before remote completion and late failure cannot affect a new login', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||
assert.deepEqual(h.calls, ['logout', 'workspace', 'unsaved', '/login'])
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
h.auth.token = 'B'; h.auth.isAuthenticated = true; await vue.nextTick()
|
||||
h.rejectLogout(new Error('SESSION_CHANGED')); await Promise.resolve(); await vue.nextTick()
|
||||
assert.equal(h.auth.token, 'B'); assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.calls.filter(item => item === '/login').length, 1)
|
||||
assert.equal(h.warnings.length, 0)
|
||||
})
|
||||
|
||||
test('cross-tab logout leaves protected route and stale confirmation never logs out a new identity', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler()
|
||||
h.auth.token = 'B'; h.confirm(); await clicked
|
||||
assert.equal(h.calls.length, 0)
|
||||
h.auth.token = ''; h.auth.isAuthenticated = false; await vue.nextTick()
|
||||
assert.deepEqual(h.calls, ['workspace', 'unsaved', '/login'])
|
||||
assert.match(layoutSource, /<div v-if="auth.isAuthenticated" class="client-shell"/)
|
||||
})
|
||||
|
||||
test('remote logout failure reports incomplete server revocation without leaving protected content visible', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||
h.rejectLogout(new Error('offline')); await Promise.resolve()
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.ok(h.calls.includes('/login'))
|
||||
assert.deepEqual(h.warnings, ['已退出本页,服务器会话注销未完成'])
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
||||
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
||||
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
||||
@@ -108,6 +108,7 @@ watch(
|
||||
watch(
|
||||
() => auth.permissionCodes.join('|'),
|
||||
() => {
|
||||
if (!auth.isAuthenticated) return
|
||||
const result = workspace.reconcile(isAllowedTab)
|
||||
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
||||
},
|
||||
@@ -119,6 +120,7 @@ watch(
|
||||
if (authenticated) return
|
||||
workspace.clear()
|
||||
unsaved.clear()
|
||||
void router.replace('/login')
|
||||
},
|
||||
)
|
||||
|
||||
@@ -163,6 +165,7 @@ function handleBeforeUnload(event: BeforeUnloadEvent) {
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
const logoutToken = auth.token
|
||||
try {
|
||||
await ElMessageBox.confirm(unsaved.hasDirty
|
||||
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
||||
@@ -176,15 +179,16 @@ async function handleLogout() {
|
||||
throw error
|
||||
}
|
||||
|
||||
workspace.clear()
|
||||
unsaved.clear()
|
||||
await auth.logout()
|
||||
await router.replace('/login')
|
||||
if (auth.token !== logoutToken) return
|
||||
void auth.logout().catch(() => {
|
||||
if (!auth.isAuthenticated) ElMessage.warning('已退出本页,服务器会话注销未完成')
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||
<div v-if="auth.isAuthenticated" class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
|
||||
<button
|
||||
ref="menuButtonRef"
|
||||
|
||||
@@ -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`。
|
||||
@@ -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`。
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiRequest } from '@/api/http'
|
||||
import { apiRequest, revokeCapturedSession } from '@/api/http'
|
||||
import type { TokenPair } from '@/api/session'
|
||||
|
||||
export interface RegisterMerchantRequest {
|
||||
@@ -35,8 +35,8 @@ export function registerMerchant(payload: RegisterMerchantRequest) {
|
||||
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
||||
}
|
||||
|
||||
export function logoutMerchant(refreshToken: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: '/auth/logout', data: { refreshToken } })
|
||||
export function logoutMerchant(accessToken: string, refreshToken: string) {
|
||||
return revokeCapturedSession(accessToken, refreshToken)
|
||||
}
|
||||
|
||||
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
||||
|
||||
+105
-99
@@ -61,18 +61,34 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
const permissionCodes = ref<string[]>([])
|
||||
const sessionRestored = ref(false)
|
||||
|
||||
let logoutRequest: { accessToken: string; refreshToken: string; promise: Promise<void> } | undefined
|
||||
let generation = 0
|
||||
let contextRequest: { generation: number; promise: Promise<void> } | undefined
|
||||
let restoreTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function identity(value: MerchantJwtPayload | null) {
|
||||
return value ? JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type]) : ''
|
||||
}
|
||||
|
||||
function applyToken(accessToken: string) {
|
||||
const decoded = decodeMerchantToken(accessToken)
|
||||
const changedIdentity = identity(decoded) !== identity(payload.value)
|
||||
if (accessToken === token.value && payload.value && !changedIdentity) return
|
||||
generation++
|
||||
if (changedIdentity) {
|
||||
user.value = null
|
||||
profile.value = { ...emptyProfile }
|
||||
permissionCodes.value = mapPermissions()
|
||||
}
|
||||
payload.value = decoded
|
||||
token.value = accessToken
|
||||
user.value = currentUser(decoded, user.value?.tenantName)
|
||||
profile.value.username = decoded.username
|
||||
profile.value.realName = decoded.username
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
clearSessionTokens()
|
||||
function resetLocalSession() {
|
||||
generation++
|
||||
token.value = ''
|
||||
payload.value = null
|
||||
user.value = null
|
||||
@@ -81,137 +97,123 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
sessionRestored.value = true
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
clearSessionTokens()
|
||||
resetLocalSession()
|
||||
}
|
||||
|
||||
function applyStoredSession() {
|
||||
const storedToken = getAccessToken()
|
||||
if (!storedToken) {
|
||||
token.value = ''
|
||||
payload.value = null
|
||||
user.value = null
|
||||
permissionCodes.value = []
|
||||
profile.value = { ...emptyProfile }
|
||||
sessionRestored.value = true
|
||||
resetLocalSession()
|
||||
return
|
||||
}
|
||||
try {
|
||||
applyToken(storedToken)
|
||||
sessionRestored.value = false
|
||||
} catch {
|
||||
clearSession()
|
||||
}
|
||||
}
|
||||
|
||||
if (token.value) {
|
||||
try {
|
||||
applyToken(token.value)
|
||||
} catch (error) {
|
||||
if (!(error instanceof MerchantTokenExpiredError && getRefreshToken())) clearSession()
|
||||
resetLocalSession()
|
||||
if (error instanceof MerchantTokenExpiredError && getRefreshToken()) sessionRestored.value = false
|
||||
}
|
||||
}
|
||||
|
||||
applyStoredSession()
|
||||
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
||||
|
||||
async function loadSessionContext() {
|
||||
if (!payload.value) return
|
||||
const currentPermissionCodes = await getCurrentMerchantPermissionCodes()
|
||||
const currentAccessToken = getAccessToken()
|
||||
if (currentAccessToken && currentAccessToken !== token.value) applyToken(currentAccessToken)
|
||||
permissionCodes.value = mapPermissions(currentPermissionCodes)
|
||||
const [tenant, personalProfile] = await Promise.all([
|
||||
getTenantProfile(),
|
||||
getMerchantPersonalProfile(),
|
||||
])
|
||||
user.value = currentUser(payload.value, tenant.tenantName)
|
||||
profile.value = {
|
||||
...profile.value,
|
||||
realName: personalProfile.displayName || payload.value.username,
|
||||
phone: personalProfile.phone || '',
|
||||
email: personalProfile.email || '',
|
||||
tenantName: tenant.tenantName,
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreSession() {
|
||||
if (sessionRestored.value) return
|
||||
if (!isAuthenticated.value) {
|
||||
if (!getRefreshToken()) {
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
if (contextRequest?.generation === generation) return contextRequest.promise
|
||||
let requestGeneration = generation
|
||||
let requestAccessToken = getAccessToken()
|
||||
const isCurrent = () => requestGeneration === generation && getAccessToken() === requestAccessToken
|
||||
const promise = (async () => {
|
||||
try {
|
||||
applyToken(await refreshAuthenticatedSession())
|
||||
if (!isAuthenticated.value) {
|
||||
if (!getRefreshToken()) return
|
||||
const refreshedToken = await refreshAuthenticatedSession()
|
||||
if (requestGeneration !== generation) return restoreSession()
|
||||
applyToken(refreshedToken)
|
||||
requestAccessToken = refreshedToken
|
||||
requestGeneration = generation
|
||||
if (contextRequest) contextRequest.generation = generation
|
||||
}
|
||||
const requestPayload = payload.value
|
||||
if (!requestPayload) return
|
||||
const [codes, tenant, personalProfile] = await Promise.all([
|
||||
getCurrentMerchantPermissionCodes(), getTenantProfile(), getMerchantPersonalProfile(),
|
||||
])
|
||||
if (!isCurrent()) {
|
||||
applyStoredSession()
|
||||
return restoreSession()
|
||||
}
|
||||
permissionCodes.value = mapPermissions(codes)
|
||||
user.value = currentUser(requestPayload, tenant.tenantName)
|
||||
profile.value = {
|
||||
username: requestPayload.username,
|
||||
realName: personalProfile.displayName || requestPayload.username,
|
||||
phone: personalProfile.phone || '', email: personalProfile.email || '', tenantName: tenant.tenantName,
|
||||
}
|
||||
sessionRestored.value = true
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
sessionRestored.value = false
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
})()
|
||||
contextRequest = { generation: requestGeneration, promise }
|
||||
try { await promise } finally {
|
||||
if (contextRequest?.promise === promise) contextRequest = undefined
|
||||
}
|
||||
try {
|
||||
await loadSessionContext()
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
sessionRestored.value = true
|
||||
}
|
||||
|
||||
function synchronizeSession() {
|
||||
// Identity changes and logout revoke local rights immediately. Coalesce pair writes
|
||||
// before loading the new context; same-identity rotation retains confirmed rights.
|
||||
applyStoredSession()
|
||||
if (restoreTimer) clearTimeout(restoreTimer)
|
||||
restoreTimer = setTimeout(() => {
|
||||
restoreTimer = undefined
|
||||
void restoreSession().catch(() => {})
|
||||
}, 0)
|
||||
}
|
||||
|
||||
async function login(loginId: string, password: string, remember = false) {
|
||||
const attempt = ++generation
|
||||
const tokens = await loginMerchant(loginId, password)
|
||||
const decoded = decodeMerchantToken(tokens.accessToken)
|
||||
if (attempt !== generation) return
|
||||
decodeMerchantToken(tokens.accessToken)
|
||||
persistTokenPair(tokens)
|
||||
persistRememberedLoginId(loginId, remember)
|
||||
token.value = tokens.accessToken
|
||||
payload.value = decoded
|
||||
user.value = currentUser(decoded)
|
||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
try {
|
||||
await loadSessionContext()
|
||||
sessionRestored.value = true
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
}
|
||||
applyToken(tokens.accessToken)
|
||||
await restoreSession()
|
||||
}
|
||||
|
||||
async function acceptImpersonationCode(code: string) {
|
||||
const attempt = ++generation
|
||||
const exchanged = await exchangeImpersonationCode(code)
|
||||
const decoded = decodeMerchantToken(exchanged.accessToken)
|
||||
if (attempt !== generation) return
|
||||
decodeMerchantToken(exchanged.accessToken)
|
||||
persistTemporaryAccessToken(exchanged.accessToken)
|
||||
token.value = exchanged.accessToken
|
||||
payload.value = decoded
|
||||
user.value = currentUser(decoded)
|
||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
try {
|
||||
await loadSessionContext()
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
sessionRestored.value = true
|
||||
applyToken(exchanged.accessToken)
|
||||
await restoreSession()
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
function logout() {
|
||||
const accessToken = getAccessToken()
|
||||
const refreshToken = getRefreshToken()
|
||||
try {
|
||||
if (refreshToken) await logoutMerchant(refreshToken)
|
||||
} finally {
|
||||
clearSession()
|
||||
}
|
||||
if (logoutRequest && ((!accessToken && !refreshToken)
|
||||
|| (logoutRequest.accessToken === accessToken && logoutRequest.refreshToken === refreshToken))) return logoutRequest.promise
|
||||
const pending = accessToken || refreshToken
|
||||
? logoutMerchant(accessToken, refreshToken)
|
||||
: Promise.resolve()
|
||||
clearSession()
|
||||
const request = { accessToken, refreshToken, promise: pending.finally(() => {
|
||||
if (logoutRequest === request) logoutRequest = undefined
|
||||
}) }
|
||||
logoutRequest = request
|
||||
return request.promise
|
||||
}
|
||||
|
||||
function hasPermission(permission?: string) {
|
||||
@@ -224,10 +226,13 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
}
|
||||
|
||||
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
|
||||
const requestGeneration = generation
|
||||
const requestToken = getAccessToken()
|
||||
const updated = await updateMerchantPersonalProfile({
|
||||
displayName: next.realName.trim(),
|
||||
email: next.email.trim(),
|
||||
})
|
||||
if (requestGeneration !== generation || requestToken !== getAccessToken()) return
|
||||
updateProfile({
|
||||
realName: updated.displayName,
|
||||
phone: updated.phone || '',
|
||||
@@ -236,8 +241,9 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
}
|
||||
|
||||
window.addEventListener('cc-client-session-expired', clearSession)
|
||||
window.addEventListener('cc-client-session-updated', synchronizeSession)
|
||||
window.addEventListener('storage', (event) => {
|
||||
if (event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token') applyStoredSession()
|
||||
if (event.storageArea === localStorage && (event.key === null || event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token')) synchronizeSession()
|
||||
})
|
||||
|
||||
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
function compile(path, dependencies = {}) {
|
||||
const code = ts.transpileModule(readFileSync(new URL(path, import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function storage() {
|
||||
const values = new Map()
|
||||
return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key) }
|
||||
}
|
||||
function token(user = 1, tenant = 1, membership = 1, nonce = 'a') {
|
||||
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, username: `user-${user}`, app_code: 'MERCHANT', exp: 4102444800, nonce })).toString('base64url')}.test`
|
||||
}
|
||||
const flush = () => new Promise(resolve => setTimeout(resolve, 10))
|
||||
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
|
||||
function harness(t, expired = false) {
|
||||
globalThis.localStorage = storage(); globalThis.sessionStorage = storage()
|
||||
const listeners = new Map()
|
||||
globalThis.window = { addEventListener: (name, fn) => listeners.set(name, fn) }
|
||||
const session = compile('../../../api/session.ts')
|
||||
const initial = expired ? `test.${Buffer.from(JSON.stringify({ user_id: 1, tenant_id: 1, membership_id: 1, username: 'user-1', app_code: 'MERCHANT', exp: 1 })).toString('base64url')}.test` : token()
|
||||
session.persistTokenPair({ accessToken: initial, refreshToken: 'refresh-a' })
|
||||
let reads = 0
|
||||
const behavior = { permissions: async () => ['edit'], tenant: async () => ({ tenantName: 'company' }) }
|
||||
class ApiError extends Error { constructor(status) { super('failed'); this.status = status } }
|
||||
const module = compile('./auth.ts', {
|
||||
vue, pinia, '@/api/session': session,
|
||||
'@/modules/auth/api/auth': { logoutMerchant: async (access, refresh) => behavior.logout?.(refresh, access) },
|
||||
'@/modules/auth/utils/jwt': compile('../utils/jwt.ts'),
|
||||
'@/api/http': { ApiError, refreshAuthenticatedSession: async () => {
|
||||
session.persistTokenPair({ accessToken: token(1, 1, 1, 'refreshed'), refreshToken: 'refresh-new' })
|
||||
listeners.get('cc-client-session-updated')()
|
||||
return session.getAccessToken()
|
||||
} },
|
||||
'@/modules/tenant-management/public': {
|
||||
FRONTEND_TO_MERCHANT_PERMISSION_CODES: { 'order:first-leg:edit': 'edit' },
|
||||
hasMappedMerchantPermission: (_, codes) => codes.has('edit'),
|
||||
getCurrentMerchantPermissionCodes: () => { reads++; return behavior.permissions() },
|
||||
getTenantProfile: () => behavior.tenant(), getMerchantPersonalProfile: async () => ({}),
|
||||
},
|
||||
})
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(async () => { await flush(); pinia.disposePinia(context) })
|
||||
const auth = module.useAuthStore()
|
||||
const event = key => listeners.get('storage')({ key, storageArea: localStorage })
|
||||
function rotate(nextToken = token(1, 1, 1, 'b')) {
|
||||
session.persistTokenPair({ accessToken: nextToken, refreshToken: 'refresh-b' })
|
||||
event(session.ACCESS_TOKEN_KEY); event(session.REFRESH_TOKEN_KEY)
|
||||
}
|
||||
return { auth, session, event, rotate, behavior, listeners, ApiError, reads: () => reads }
|
||||
}
|
||||
|
||||
test('pair storage rotation retains same-identity rights and automatically reloads once without navigation', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
assert.equal(h.auth.sessionRestored, false)
|
||||
await flush()
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false, 'new server rights replace the retained snapshot')
|
||||
assert.equal(h.reads(), 2)
|
||||
h.listeners.get('cc-client-session-updated')()
|
||||
await flush()
|
||||
assert.equal(h.reads(), 2, 'already applied token does not reload twice')
|
||||
})
|
||||
|
||||
test('startup expired-token refresh waits for restored rights even when local rotation emits an event', async t => {
|
||||
const h = harness(t, true)
|
||||
await h.auth.restoreSession()
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.reads(), 1)
|
||||
})
|
||||
|
||||
test('logout storage event immediately clears rights and late context cannot restore them', async t => {
|
||||
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
const pending = h.auth.restoreSession()
|
||||
h.session.clearSessionTokens(); h.event(h.session.ACCESS_TOKEN_KEY)
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.deepEqual(h.auth.permissionCodes, [])
|
||||
old.resolve(['edit']); await pending; await flush()
|
||||
assert.equal(h.auth.user, null)
|
||||
assert.deepEqual(h.auth.permissionCodes, [])
|
||||
})
|
||||
|
||||
test('account, customer and membership switches revoke rights immediately and reject stale request results', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
h.rotate(); await flush()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate(token(2, 2, 2, 'new'))
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
await flush(); old.resolve(['edit']); await flush()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
h.behavior.permissions = async () => ['edit']; h.rotate(token(2, 3, 3, 'next')); await flush()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
h.rotate(token(2, 3, 4, 'membership'))
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
})
|
||||
|
||||
test('context failure is not marked restored and explicit retry coalesces concurrent callers', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.permissions = async () => { throw new Error('offline') }
|
||||
await h.auth.restoreSession()
|
||||
assert.equal(h.auth.sessionRestored, false)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
const pending = deferred(); h.behavior.permissions = () => pending.promise
|
||||
const first = h.auth.restoreSession(), second = h.auth.restoreSession()
|
||||
assert.equal(h.reads(), 2)
|
||||
pending.resolve(['edit']); await Promise.all([first, second])
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
})
|
||||
|
||||
test('stale unauthorized context response cannot clear a newer account', async t => {
|
||||
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
const pending = h.auth.restoreSession()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate(token(2, 2, 2)); await flush()
|
||||
old.reject(new h.ApiError(401)); await pending
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
})
|
||||
|
||||
test('store logout clears immediately and late revocation failure preserves a later cross-tab login', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
const remote = deferred(); let sentRefresh
|
||||
h.behavior.logout = refresh => { sentRefresh = refresh; return remote.promise }
|
||||
const pending = h.auth.logout()
|
||||
const rejected = assert.rejects(pending, /offline/)
|
||||
assert.equal(sentRefresh, 'refresh-a')
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.equal(h.session.getAccessToken(), '')
|
||||
h.rotate(token(2, 2, 2)); await flush()
|
||||
remote.reject(new Error('offline')); await rejected
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.session.getRefreshToken(), 'refresh-b')
|
||||
})
|
||||
|
||||
test('duplicate logout joins captured pair revocation and does not send again',async t=>{
|
||||
const h=harness(t);const remote=deferred();let count=0,sent
|
||||
h.behavior.logout=(refresh,access)=>{count++;sent={refresh,access};return remote.promise}
|
||||
const a=h.auth.logout(),b=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(sent.access,token());assert.equal(sent.refresh,'refresh-a');assert.equal(count,1);remote.resolve();await Promise.all([a,b])
|
||||
})
|
||||
|
||||
test('B logout during A pending revokes B; A finally cannot release B deduplication',async t=>{
|
||||
const h=harness(t);const a=deferred(),b=deferred(),calls=[]
|
||||
h.behavior.logout=(refresh,access)=>{calls.push({refresh,access});return calls.length===1?a.promise:b.promise}
|
||||
const leavingA=h.auth.logout();h.rotate(token(2,2,2));await flush();assert.equal(h.auth.isAuthenticated,true)
|
||||
const leavingB=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(h.session.getAccessToken(),'');assert.equal(calls.length,2);assert.equal(calls[1].access,token(2,2,2))
|
||||
a.resolve();await leavingA;const duplicateB=h.auth.logout();assert.equal(calls.length,2);let duplicateFinished=false;void duplicateB.then(()=>{duplicateFinished=true});await flush();assert.equal(duplicateFinished,false);b.resolve();await Promise.all([leavingB,duplicateB])
|
||||
})
|
||||
@@ -102,7 +102,8 @@ test('opens complete service and privacy documents from registration', () => {
|
||||
test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||
assert.match(authApiSource, /\/auth\/login/)
|
||||
assert.match(authApiSource, /\/auth\/register/)
|
||||
assert.match(authApiSource, /\/auth\/logout/)
|
||||
assert.match(authApiSource, /revokeCapturedSession\(accessToken, refreshToken\)/)
|
||||
assert.match(httpSource, /\/auth\/logout/)
|
||||
assert.match(httpSource, /refreshPromise/)
|
||||
assert.match(httpSource, /\/auth\/refresh/)
|
||||
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
||||
@@ -117,7 +118,8 @@ test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
||||
assert.match(authStoreSource, /decodeMerchantToken/)
|
||||
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
|
||||
assert.match(authStoreSource, /applyToken\(await refreshAuthenticatedSession\(\)\)/)
|
||||
assert.match(authStoreSource, /const refreshedToken = await refreshAuthenticatedSession\(\)/)
|
||||
assert.match(authStoreSource, /applyToken\(refreshedToken\)/)
|
||||
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
||||
})
|
||||
|
||||
@@ -152,7 +154,7 @@ test('shows a forced re-login notice after login identifiers change', () => {
|
||||
test('keeps a valid local session during temporary context and refresh outages', () => {
|
||||
assert.match(authStoreSource, /function isExpiredSessionError/)
|
||||
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
||||
assert.match(authStoreSource, /sessionRestored\.value = true\s+return/)
|
||||
assert.match(authStoreSource, /if \(!isCurrent\(\)\) return\s+sessionRestored\.value = false/)
|
||||
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
||||
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
||||
})
|
||||
|
||||
@@ -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` | 本地换算,服务端复核 |
|
||||
|
||||
## 关键边界
|
||||
|
||||
- 三条线都是客户自助下单,提交后由平台审核;客户侧不提供审核、改价或内部作业动作。
|
||||
- 客户与仓库范围只取服务端当前租户上下文,不从前端参数推断;跨客户查询一律拒绝。
|
||||
- 提交需要幂等键、提交中状态与可恢复失败反馈;失败保留已填内容。
|
||||
- 海外采购的购买、装箱、面单、交寄与国内核费是一条独立链路,改节点前先读 `docs/海外仓业务/采购订单样品履约流程变更需求.md`(工作区路径)。
|
||||
- 页面承载方式按已确认原型:列表 + 独立建单/详情路由,不改为弹框或抽屉。
|
||||
|
||||
## 验证
|
||||
|
||||
- 定向:`pnpm test src/modules/cross-border/<目标测试>`;接口或类型变化同时运行 `pnpm typecheck`。
|
||||
- 本文件或索引变更后,从后端根运行 `./scripts/agents-index-contract.ps1`。
|
||||
@@ -0,0 +1,34 @@
|
||||
# 本土卡车字段调整核对
|
||||
|
||||
依据:用户提供的下单页截图 `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 由认证会话确定客户。
|
||||
@@ -1,4 +1,4 @@
|
||||
import { overseasApiRequest } from '@/api/overseasHttp'
|
||||
import { apiRequest } from '@/api/http'
|
||||
|
||||
export interface PageResult<T> {
|
||||
records: T[]
|
||||
@@ -8,7 +8,7 @@ export interface PageResult<T> {
|
||||
pages: number
|
||||
}
|
||||
|
||||
export type CrossBorderBusinessKind = 'procurement' | 'trucking' | 'looseboard'
|
||||
export type CrossBorderBusinessKind = 'trucking' | 'looseboard'
|
||||
|
||||
export interface BusinessOrderQuery {
|
||||
page: number
|
||||
@@ -16,81 +16,38 @@ export interface BusinessOrderQuery {
|
||||
orderNo?: string
|
||||
status?: string
|
||||
routeKeyword?: string
|
||||
productName?: string
|
||||
purchaseCategory?: string
|
||||
transportType?: string
|
||||
transportMode?: string
|
||||
vehicleType?: 'PALLET_15' | 'PALLET_30'
|
||||
pickupFrom?: string
|
||||
pickupTo?: string
|
||||
requestedFrom?: string
|
||||
requestedTo?: string
|
||||
createdFrom?: string
|
||||
createdTo?: string
|
||||
}
|
||||
|
||||
export interface ProcurementSummary {
|
||||
orderNo: string
|
||||
purchaseCategory: string
|
||||
productName: string
|
||||
productSpecification: string | null
|
||||
purchaseQuantity: number
|
||||
budgetUnitPrice: number | null
|
||||
currency: string | null
|
||||
inboundQuantity: number
|
||||
outboundQuantity: number
|
||||
inventoryQuantity: number
|
||||
status: string
|
||||
version: number
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
export interface ProcurementDetail {
|
||||
summary: ProcurementSummary
|
||||
productUrl: string | null
|
||||
receivingAddress: string | null
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
domesticCarrier: string | null
|
||||
domesticTrackingNo: string | null
|
||||
overseasCarrier: string | null
|
||||
overseasTrackingNo: string | null
|
||||
estimatedArrivalAt: string | null
|
||||
remark: string | null
|
||||
reviewRemark: string | null
|
||||
}
|
||||
|
||||
export interface ProcurementCreate {
|
||||
customerName: string
|
||||
purchaseCategory: string
|
||||
productName: string
|
||||
productSpecification?: string
|
||||
productUrl?: string
|
||||
purchaseQuantity: number
|
||||
budgetUnitPrice?: number
|
||||
currency?: string
|
||||
receivingAddress?: string
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
remark?: string
|
||||
idempotencyKey: string
|
||||
}
|
||||
|
||||
export interface TransportSummary {
|
||||
fleetArrangement: import('../fleetArrangement').FleetArrangement | null
|
||||
orderNo: string
|
||||
transportType: string
|
||||
transportMode?: string
|
||||
palletRequired?: string
|
||||
transportType?: string
|
||||
palletRequired?: string | null
|
||||
origin: string
|
||||
destination: string
|
||||
containerType: string | null
|
||||
palletCount?: number
|
||||
packageCount: number
|
||||
totalWeightKg: number
|
||||
totalVolumeCbm: number
|
||||
budgetAmount: number | null
|
||||
currency: string | null
|
||||
contactName: string | null
|
||||
contactInfo: string | null
|
||||
requestedDate: string | null
|
||||
productName?: string | null
|
||||
estimatedPalletCount?: number | 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
|
||||
version: number
|
||||
createdAt: string
|
||||
@@ -105,23 +62,44 @@ export interface TransportDetail {
|
||||
}
|
||||
|
||||
export interface TransportCreate {
|
||||
transportType: string
|
||||
transportMode?: string
|
||||
palletRequired?: string
|
||||
productName?: string
|
||||
estimatedPalletCount: number
|
||||
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
|
||||
originContactName: string
|
||||
originContactPhone: 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
|
||||
packageCount: number
|
||||
totalWeightKg: number
|
||||
totalVolumeCbm: number
|
||||
budgetAmount?: number
|
||||
currency?: string
|
||||
remark?: string
|
||||
idempotencyKey: string
|
||||
}
|
||||
@@ -130,8 +108,11 @@ export interface TransportUpdate extends Omit<TransportCreate, 'idempotencyKey'>
|
||||
version: number
|
||||
}
|
||||
|
||||
export interface TruckUpdate extends Omit<TruckCreate, 'idempotencyKey'> {
|
||||
version: number
|
||||
}
|
||||
|
||||
const endpointByKind: Record<CrossBorderBusinessKind, string> = {
|
||||
procurement: '/merchant/v1/last-leg/overseas-procurements',
|
||||
trucking: '/merchant/v1/last-leg/us-truck-orders',
|
||||
looseboard: '/merchant/v1/last-leg/local-looseboard-orders',
|
||||
}
|
||||
@@ -141,23 +122,23 @@ function normalizePage<T>(data: PageResult<T>): PageResult<T> {
|
||||
}
|
||||
|
||||
export function listBusinessOrders<T>(kind: CrossBorderBusinessKind, params: BusinessOrderQuery) {
|
||||
return overseasApiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage)
|
||||
return apiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage)
|
||||
}
|
||||
|
||||
export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: string) {
|
||||
return overseasApiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
||||
return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
||||
}
|
||||
|
||||
export function createProcurement(payload: ProcurementCreate) {
|
||||
return overseasApiRequest<ProcurementDetail>({ method: 'POST', url: endpointByKind.procurement, data: payload })
|
||||
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 })
|
||||
}
|
||||
|
||||
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) {
|
||||
return overseasApiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
|
||||
}
|
||||
|
||||
export function updateTransport(kind: 'trucking' | 'looseboard', orderNo: string, payload: TransportUpdate) {
|
||||
return overseasApiRequest<TransportDetail>({
|
||||
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>({
|
||||
method: kind === 'trucking' ? 'PATCH' : 'PUT',
|
||||
url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}`,
|
||||
data: payload,
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { apiRequest } from '@/api/http'
|
||||
import type { PageResult } from './businessOrders'
|
||||
|
||||
export type Amount = number | string
|
||||
export interface ProcurementSummary {
|
||||
orderNo: string
|
||||
purchaseCategory: string
|
||||
productName: string
|
||||
productSpecification: string | null
|
||||
purchaseQuantity: number
|
||||
budgetUnitPrice: Amount | null
|
||||
currency: string | null
|
||||
status: string
|
||||
version: number
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
}
|
||||
export interface ProcurementOrder extends ProcurementSummary {
|
||||
productUrl: string | null
|
||||
receivingAddress: string
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
estimatedArrivalAt: string | null
|
||||
plannedWarehouseName: string | null
|
||||
actualWarehouseCode: string | null
|
||||
actualWarehouseName: string | null
|
||||
}
|
||||
export interface ProcurementFee {
|
||||
feeNo: string
|
||||
purpose: string
|
||||
name: string
|
||||
version: number | null
|
||||
active: boolean
|
||||
determination: string
|
||||
amount: Amount
|
||||
currency: string
|
||||
originalAmount: Amount | null
|
||||
originalCurrency: string | null
|
||||
exchangeRate: Amount | null
|
||||
exchangeRateMonth: string | null
|
||||
businessDate: string | null
|
||||
parentFeeNo: string | null
|
||||
walletStatus: string | null
|
||||
sourceLinked: boolean
|
||||
}
|
||||
export interface ProcurementBox {
|
||||
cartonNo: string
|
||||
quantity: number
|
||||
lengthCm: Amount
|
||||
widthCm: Amount
|
||||
heightCm: Amount
|
||||
grossWeightKg: Amount
|
||||
}
|
||||
export interface ProcurementShipment {
|
||||
shipmentNo: string
|
||||
leg: 'OVERSEAS' | 'DOMESTIC'
|
||||
shippedAt: string
|
||||
cartonNo: string
|
||||
quantity: number
|
||||
carrier: string
|
||||
trackingNo: string
|
||||
}
|
||||
export interface ProcurementDetail {
|
||||
order: ProcurementOrder
|
||||
budget: { totalAmount: Amount | null; currency: string; authorizedAt: string | null }
|
||||
purchased: boolean
|
||||
purchaseConfirmed: boolean
|
||||
purchaseNeedsAttention: boolean
|
||||
progress: { key: string; title: string; completedAt: string | null }[]
|
||||
boxes: ProcurementBox[]
|
||||
shipments: ProcurementShipment[]
|
||||
fees: ProcurementFee[]
|
||||
exceptionSummaries: string[]
|
||||
}
|
||||
export interface ProcurementCreate {
|
||||
customerName: string
|
||||
purchaseCategory: string
|
||||
productName: string
|
||||
productSpecification?: string
|
||||
productUrl?: string
|
||||
purchaseQuantity: number
|
||||
budgetUnitPrice: number
|
||||
currency: 'CNY' | 'USD'
|
||||
receivingAddress: string
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
remark?: string
|
||||
idempotencyKey: string
|
||||
}
|
||||
export interface ProcurementQuery {
|
||||
page: number
|
||||
size: number
|
||||
orderNo?: string
|
||||
productName?: string
|
||||
purchaseCategory?: string
|
||||
status?: string
|
||||
}
|
||||
const endpoint = '/merchant/v1/last-leg/overseas-procurements'
|
||||
export async function listProcurements(params: ProcurementQuery) {
|
||||
const result = await apiRequest<PageResult<ProcurementSummary>>({ method: 'GET', url: endpoint, params })
|
||||
return { ...result, page: Number(result.page), size: Number(result.size), total: Number(result.total), pages: Number(result.pages) }
|
||||
}
|
||||
export function getProcurement(orderNo: string) {
|
||||
return apiRequest<ProcurementDetail>({ method: 'GET', url: `${endpoint}/${encodeURIComponent(orderNo)}` })
|
||||
}
|
||||
export function createProcurement(data: ProcurementCreate) {
|
||||
return apiRequest<ProcurementDetail>({ method: 'POST', url: endpoint, data })
|
||||
}
|
||||
@@ -1,10 +1,42 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
|
||||
const api = readFileSync(new URL('./api/businessOrders.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 demandComponent = readFileSync(new URL('./components/TransportDemandForm.vue', import.meta.url), 'utf8')
|
||||
const demandLogic = ts.transpileModule(readFileSync(new URL('./transportDemandForm.ts', import.meta.url), 'utf8'), { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText.replace(/^export /gm, '')
|
||||
const demandHelpers = runInNewContext(`${demandLogic}\n({ createTransportDemandForm, transportDemandRules, transportDemandError, buildTransportDemand })`)
|
||||
const procurementApi = readFileSync(new URL('./api/procurement.ts', import.meta.url), 'utf8')
|
||||
const procurementView = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
|
||||
|
||||
test('renders unknown pallet service and container type as dashes while preserving explicit values', () => {
|
||||
const helpers = view.slice(view.indexOf('function read('), view.indexOf('function idempotencyKey('))
|
||||
const compiled = ts.transpileModule(helpers, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const { displayCell, yesNo, text } = runInNewContext(`${compiled}\n({ displayCell, yesNo, text })`)
|
||||
assert.equal(displayCell({ palletRequired: null }, 'palletRequired'), '—')
|
||||
assert.equal(displayCell({ palletRequired: 'NO' }, 'palletRequired'), '否')
|
||||
assert.equal(displayCell({ palletRequired: 'YES' }, 'palletRequired'), '是')
|
||||
assert.equal(displayCell({ containerType: null }, 'containerType'), '—')
|
||||
assert.equal(displayCell({ containerType: '40HQ' }, 'containerType'), '40HQ')
|
||||
assert.equal(yesNo(null), '—')
|
||||
assert.equal(text(null), '—')
|
||||
assert.match(api, /palletRequired\?: string \| null/)
|
||||
const create = api.slice(api.indexOf('export interface TransportCreate'), api.indexOf('export interface TransportUpdate'))
|
||||
assert.doesNotMatch(create, /palletRequired\?: string \| null/)
|
||||
})
|
||||
|
||||
test('shows merchant-owned arrangement facts without a pool request or editable status control', () => {
|
||||
assert.match(api, /fleetArrangement: import\('\.\.\/fleetArrangement'\)\.FleetArrangement \| null/)
|
||||
assert.match(view, /aria-label="承运安排"/)
|
||||
for (const field of ['signedPackages', 'unsignedPackages', 'returnedPackages', 'readOnlyReason']) assert.ok(view.includes(`fleetArrangement.${field}`))
|
||||
assert.doesNotMatch(api, /capacity-offers|fleet\/trips/)
|
||||
assert.match(view, /if \(query\.page !== 1\) query\.page = 1\s+else void load\(\)/)
|
||||
assert.match(view, /if \(reloadDirectly\) void load\(\)/)
|
||||
})
|
||||
|
||||
test('activates all three customer cross-border pages with frozen permissions', () => {
|
||||
for (const [path, permission] of [
|
||||
@@ -15,14 +47,15 @@ test('activates all three customer cross-border pages with frozen permissions',
|
||||
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?release: 'active'[\\s\\S]*?permission: '${permission}'`))
|
||||
}
|
||||
assert.doesNotMatch(view, /PrototypeFeatureView|mock|customerId|tenantId/i)
|
||||
assert.match(view, /merchant:cross-border:procurement:create/)
|
||||
assert.match(procurementView, /merchant:cross-border:procurement:create/)
|
||||
assert.match(view, /merchant:cross-border:domestic-trucking:create/)
|
||||
assert.match(view, /merchant:cross-border:pallet-shipping:create/)
|
||||
assert.match(view, /v-if="canCreate"[^>]*type="primary"/)
|
||||
})
|
||||
|
||||
test('uses only merchant overseas endpoints and keeps retry idempotency stable', () => {
|
||||
assert.match(api, /overseas-procurements/)
|
||||
assert.match(procurementApi, /overseas-procurements/)
|
||||
assert.doesNotMatch(api, /overseas-procurements|ProcurementSummary|ProcurementDetail/)
|
||||
assert.match(api, /us-truck-orders/)
|
||||
assert.match(api, /local-looseboard-orders/)
|
||||
assert.doesNotMatch(api, /\/platform\/|\/internal\/|customerId|tenantId/)
|
||||
@@ -42,11 +75,9 @@ test('covers list detail create loading error empty pagination and actions-first
|
||||
assert.match(view, /<DataTable[^>]*:row-actions="getRowActions"/)
|
||||
assert.match(view, /key: 'actions', label: '操作', width: 90, fixed: 'left'/)
|
||||
assert.match(view, /class="business-table-card"/)
|
||||
assert.match(view, /PENDING_OUTBOUND: '待出库'/)
|
||||
assert.match(view, /PARTIALLY_OUTBOUND: '部分出库'/)
|
||||
assert.match(view, /OUTBOUNDED: '全部出库'/)
|
||||
assert.match(view, /\['入库量', read\(summary, 'inboundQuantity'\)\]/)
|
||||
assert.match(view, /\['审核备注', current\.reviewRemark\]/)
|
||||
assert.doesNotMatch(procurementView, /inventoryQuantity|outboundQuantity|reviewRemark/)
|
||||
assert.match(procurementView, /procurementStatuses/)
|
||||
assert.match(procurementView, /ProcurementDetailPanel/)
|
||||
})
|
||||
|
||||
test('opens every dashboard cross-border action on a dedicated protected create page', () => {
|
||||
@@ -73,12 +104,12 @@ test('opens all cross-border details on dedicated protected routes', () => {
|
||||
assert.match(view, /class="business-detail-error"/)
|
||||
})
|
||||
|
||||
test('keeps procurement filters, details and forms readable at PDA width', () => {
|
||||
test('preserves the existing transport responsive rules without adding a narrow-screen procurement acceptance gate', () => {
|
||||
assert.match(view, /@media \(max-width: 767px\)/)
|
||||
assert.match(view, /queryFields/)
|
||||
assert.match(view, /\.detail-grid \{ grid-template-columns: 1fr; \}/)
|
||||
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', () => {
|
||||
@@ -87,3 +118,93 @@ 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 div \{[^}]*min-height: 34px;[^}]*grid-template-columns: 76px minmax\(0, 1fr\)/)
|
||||
})
|
||||
|
||||
function transportHarness(kind = 'trucking', failFirst = false) {
|
||||
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: {},
|
||||
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', 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.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', 'palletCount', '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)
|
||||
})
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
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 { createTransportDemandForm, transportDemandError, buildTransportDemand, type TransportDemandForm as DemandFormModel } from '../transportDemandForm'
|
||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||
import type { TableAction } from '@/components/common/tableActions'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import {
|
||||
createProcurement,
|
||||
createTransport,
|
||||
getBusinessOrder,
|
||||
listBusinessOrders,
|
||||
type CrossBorderBusinessKind,
|
||||
type ProcurementDetail,
|
||||
type ProcurementSummary,
|
||||
type TransportDetail,
|
||||
type TransportSummary,
|
||||
} from '../api/businessOrders'
|
||||
import { CONTAINER_SPECIFICATIONS, DEFAULT_CONTAINER_TYPE } from '../containerSpecifications'
|
||||
import { poolOrderStatusLabels } from '../fleetArrangement'
|
||||
|
||||
const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
|
||||
const auth = useAuthStore()
|
||||
@@ -25,62 +24,19 @@ const router = useRouter()
|
||||
const route = useRoute()
|
||||
const detailOrderNo = computed(() => String(route.params.orderNo || ''))
|
||||
const canCreate = computed(() => auth.hasPermission(({
|
||||
procurement: 'merchant:cross-border:procurement:create',
|
||||
trucking: 'merchant:cross-border:domestic-trucking:create',
|
||||
looseboard: 'merchant:cross-border:pallet-shipping:create',
|
||||
} as Record<CrossBorderBusinessKind, string>)[props.kind]))
|
||||
|
||||
type BusinessRow = ProcurementSummary | TransportSummary
|
||||
type BusinessDetail = ProcurementDetail | TransportDetail
|
||||
type BusinessRow = TransportSummary
|
||||
type BusinessDetail = TransportDetail
|
||||
type PageMode = 'list' | 'create' | 'detail'
|
||||
|
||||
interface ColumnDefinition { key: string; label: string; width?: number }
|
||||
|
||||
interface BusinessForm {
|
||||
purchaseCategory: string
|
||||
productName: string
|
||||
productSpecification: string
|
||||
productUrl: string
|
||||
purchaseQuantity: number
|
||||
transportMode: string
|
||||
palletRequired: string
|
||||
transportType: string
|
||||
origin: string
|
||||
originAddress: string
|
||||
destination: string
|
||||
destinationAddress: string
|
||||
containerType: string
|
||||
palletCount: number
|
||||
packageCount: number
|
||||
totalWeightKg: number
|
||||
totalVolumeCbm: number
|
||||
budgetAmount?: number
|
||||
currency: string
|
||||
contactName: string
|
||||
contactInfo: string
|
||||
requestedDate: string
|
||||
receivingAddress: string
|
||||
remark: string
|
||||
}
|
||||
type BusinessForm = DemandFormModel
|
||||
|
||||
const configuration = computed(() => ({
|
||||
procurement: {
|
||||
title: '海外采购',
|
||||
description: '查询并管理海外采购订单',
|
||||
columns: [
|
||||
{ key: 'orderNo', label: '订单号', width: 180 },
|
||||
{ key: 'purchaseCategory', label: '采购品类', width: 130 },
|
||||
{ key: 'productName', label: '商品名称', width: 160 },
|
||||
{ key: 'productSpecification', label: '商品规格', width: 160 },
|
||||
{ key: 'purchaseQuantity', label: '采购数量', width: 100 },
|
||||
{ key: 'budgetUnitPrice', label: '预算单价', width: 110 },
|
||||
{ key: 'inboundQuantity', label: '入库量', width: 90 },
|
||||
{ key: 'outboundQuantity', label: '出库量', width: 90 },
|
||||
{ key: 'inventoryQuantity', label: '库存量', width: 90 },
|
||||
{ key: 'status', label: '状态', width: 120 },
|
||||
{ key: 'createdAt', label: '创建时间', width: 170 },
|
||||
] satisfies ColumnDefinition[],
|
||||
},
|
||||
trucking: {
|
||||
title: '美国本土卡',
|
||||
description: '查询并管理美国本土卡订单',
|
||||
@@ -96,15 +52,17 @@ const configuration = computed(() => ({
|
||||
function transportColumns(looseboard: boolean): ColumnDefinition[] {
|
||||
return [
|
||||
{ key: 'orderNo', label: '订单编号', width: 180 },
|
||||
...(looseboard ? [{ key: 'transportMode', label: '运输方式', width: 120 }, { key: 'palletRequired', label: '是否打盘', width: 100 }] : []),
|
||||
{ key: 'transportType', label: '运输类型', width: 130 },
|
||||
...(!looseboard ? [{ key: 'vehicleType', label: '车辆类型', width: 110 }] : []),
|
||||
{ key: 'origin', label: '起运地', width: 150 },
|
||||
{ key: 'destination', label: '目的地', width: 150 },
|
||||
{ key: 'containerType', label: '柜型', width: 100 },
|
||||
...(looseboard ? [{ key: 'productName', label: '商品名称', width: 150 }, { key: 'estimatedPalletCount', label: '预计托数', width: 100 }] : []),
|
||||
{ key: 'totalWeightKg', label: '总重量(kg)', width: 120 },
|
||||
{ key: 'budgetAmount', label: '预算总价', width: 110 },
|
||||
{ key: 'requestedDate', label: '要求时间', width: 120 },
|
||||
...([
|
||||
{ key: 'pickupAt', label: '取货时间', width: 165 }, { key: 'deliveryAt', label: '送货时间', width: 165 },
|
||||
]),
|
||||
{ key: 'status', label: '状态', width: 130 },
|
||||
{ key: 'fleetArrangement', label: '承运安排', width: 190 },
|
||||
]
|
||||
}
|
||||
|
||||
@@ -115,22 +73,19 @@ const submitKey = ref('')
|
||||
const error = ref('')
|
||||
const rows = ref<BusinessRow[]>([])
|
||||
const detail = ref<BusinessDetail | null>(null)
|
||||
const fleetArrangement = computed(() => detail.value ? (detail.value as TransportDetail).summary.fleetArrangement : null)
|
||||
const formRef = ref<FormInstance>()
|
||||
const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' })
|
||||
const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '' })
|
||||
const total = ref(0)
|
||||
|
||||
const queryModel = computed<QueryModel>({
|
||||
get: () => ({
|
||||
orderNo: query.orderNo,
|
||||
purchaseCategory: query.purchaseCategory,
|
||||
productName: query.productName,
|
||||
routeKeyword: query.routeKeyword,
|
||||
status: query.status,
|
||||
}),
|
||||
set: (value) => {
|
||||
query.orderNo = String(value.orderNo || '')
|
||||
query.purchaseCategory = String(value.purchaseCategory || '')
|
||||
query.productName = String(value.productName || '')
|
||||
query.routeKeyword = String(value.routeKeyword || '')
|
||||
query.status = String(value.status || '')
|
||||
},
|
||||
@@ -138,12 +93,7 @@ const queryModel = computed<QueryModel>({
|
||||
|
||||
const queryFields = computed<QueryField[]>(() => [
|
||||
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||
...(props.kind === 'procurement'
|
||||
? [
|
||||
{ key: 'purchaseCategory', label: '采购品类', type: 'input', placeholder: '请输入采购品类' } as QueryField,
|
||||
{ key: 'productName', label: '商品名称', type: 'input', placeholder: '请输入商品名称' } as QueryField,
|
||||
]
|
||||
: [{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: '请输入起运地或目的地' } as QueryField]),
|
||||
{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: '请输入起运地或目的地' },
|
||||
{
|
||||
key: 'status',
|
||||
label: '状态',
|
||||
@@ -153,10 +103,8 @@ const queryFields = computed<QueryField[]>(() => [
|
||||
{ label: '待审核', value: 'PENDING_REVIEW' },
|
||||
{ label: '已通过', value: 'APPROVED' },
|
||||
{ label: '已拒绝', value: 'REJECTED' },
|
||||
{ label: '待出库', value: 'PENDING_OUTBOUND' },
|
||||
{ label: '部分出库', value: 'PARTIALLY_OUTBOUND' },
|
||||
{ label: '全部出库', value: 'OUTBOUNDED' },
|
||||
{ label: '待接单', value: 'PENDING_ACCEPTANCE' },
|
||||
...Object.entries(poolOrderStatusLabels).filter(([value]) => !['IN_TRANSIT', 'COMPLETED', 'CANCELLED'].includes(value)).map(([value, label]) => ({ value, label })),
|
||||
{ label: '处理中', value: 'PROCESSING' },
|
||||
{ label: '运输中', value: 'IN_TRANSIT' },
|
||||
{ label: '已完成', value: 'COMPLETED' },
|
||||
@@ -166,47 +114,22 @@ const queryFields = computed<QueryField[]>(() => [
|
||||
])
|
||||
|
||||
const form = reactive<BusinessForm>(emptyForm())
|
||||
const rules: FormRules<BusinessForm> = {
|
||||
purchaseCategory: [{ required: true, message: '请输入采购品类', trigger: 'blur' }],
|
||||
productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
|
||||
purchaseQuantity: [{ required: true, type: 'number', min: 1, message: '采购数量至少为 1', trigger: 'change' }],
|
||||
origin: [{ required: true, message: '请输入起运地', trigger: 'blur' }],
|
||||
destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
|
||||
palletCount: [{ required: true, type: 'number', min: 1, message: '托盘数至少为 1', trigger: 'change' }],
|
||||
contactName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
|
||||
contactInfo: [{ required: true, message: '请输入联系电话或联系方式', trigger: 'blur' }],
|
||||
requestedDate: [{ required: true, message: '请选择要求时间', trigger: 'change' }],
|
||||
}
|
||||
|
||||
const detailFields = computed(() => {
|
||||
if (!detail.value) return []
|
||||
const summary = detail.value.summary
|
||||
if (props.kind === 'procurement') {
|
||||
const current = detail.value as ProcurementDetail
|
||||
return [
|
||||
['采购品类', read(summary, 'purchaseCategory')],
|
||||
['商品名称', read(summary, 'productName')], ['商品规格', read(summary, 'productSpecification')],
|
||||
['采购数量', read(summary, 'purchaseQuantity')], ['预算单价', money(read(summary, 'budgetUnitPrice'), read(summary, 'currency'))],
|
||||
['入库量', read(summary, 'inboundQuantity')], ['出库量', read(summary, 'outboundQuantity')],
|
||||
['库存量', read(summary, 'inventoryQuantity')], ['预计到达时间', dateTime(current.estimatedArrivalAt)],
|
||||
['联系人', current.contactName], ['联系电话', current.contactPhone],
|
||||
['收货地址', current.receivingAddress], ['商品链接', current.productUrl],
|
||||
['国内运单', joinText(current.domesticCarrier, current.domesticTrackingNo)],
|
||||
['海外运单', joinText(current.overseasCarrier, current.overseasTrackingNo)],
|
||||
['审核备注', current.reviewRemark], ['备注', current.remark],
|
||||
]
|
||||
}
|
||||
const current = detail.value as TransportDetail
|
||||
return [
|
||||
['运输方式', read(summary, 'transportMode')],
|
||||
['是否打盘', yesNo(read(summary, 'palletRequired'))], ['运输类型', transportTypeLabel(read(summary, 'transportType'))],
|
||||
...(props.kind === 'looseboard' ? [
|
||||
['商品名称', summary.productName], ['预计托数', summary.estimatedPalletCount],
|
||||
] : [['车辆类型', vehicleTypeLabel(summary.vehicleType)]]),
|
||||
['起运地', read(summary, 'origin')], ['起运地址', current.originAddress],
|
||||
['目的地', read(summary, 'destination')], ['目的地址', current.destinationAddress],
|
||||
['柜型', read(summary, 'containerType')], ['托盘数', read(summary, 'palletCount')],
|
||||
['件数', read(summary, 'packageCount')], ['总重量(kg)', read(summary, 'totalWeightKg')],
|
||||
['总体积(m³)', read(summary, 'totalVolumeCbm')], ['预算总价', money(read(summary, 'budgetAmount'), read(summary, 'currency'))],
|
||||
['联系人', read(summary, 'contactName')], ['联系方式', read(summary, 'contactInfo')],
|
||||
['要求时间', read(summary, 'requestedDate')], ['备注', current.remark],
|
||||
['起运地联系人', summary.originContactName], ['起运地联系电话', summary.originContactPhone],
|
||||
['目的地联系人', summary.destinationContactName], ['目的地联系电话', summary.destinationContactPhone],
|
||||
['取货时间', localMinute(summary.pickupAt)], ['送货时间', localMinute(summary.deliveryAt)], ['备注', current.remark],
|
||||
]
|
||||
})
|
||||
|
||||
@@ -215,47 +138,41 @@ const tableColumns = computed<DataTableColumn[]>(() => [
|
||||
...configuration.value.columns.map((column) => ({
|
||||
...column,
|
||||
prop: column.key,
|
||||
slotName: ['orderNo', 'status'].includes(column.key) ? column.key : undefined,
|
||||
slotName: ['orderNo', 'status', 'fleetArrangement'].includes(column.key) ? column.key : undefined,
|
||||
formatter: (row: object) => displayCell(row, column.key),
|
||||
})),
|
||||
])
|
||||
|
||||
const detailStatus = computed(() => detail.value ? statusLabel(detail.value.summary.status) : '—')
|
||||
|
||||
function emptyForm(): BusinessForm {
|
||||
return {
|
||||
purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: 1,
|
||||
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: '',
|
||||
receivingAddress: '', remark: '',
|
||||
}
|
||||
}
|
||||
function emptyForm(): BusinessForm { return createTransportDemandForm() }
|
||||
|
||||
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 text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
|
||||
function joinText(...values: unknown[]) { const result = values.filter(Boolean).join(' / '); return result || '—' }
|
||||
function money(amount: unknown, currency: unknown) { return amount === null || amount === undefined ? '—' : `${text(currency)} ${Number(amount).toFixed(2)}` }
|
||||
function 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 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 transportModeLabel(value: unknown) { return ({ SHARED_TRUCK: '拼车', PRIORITY_CONSOLIDATION: '优先拼载' } as Record<string, string>)[String(value)] || text(value) }
|
||||
function statusLabel(value: unknown) {
|
||||
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_OUTBOUND: '待出库', PARTIALLY_OUTBOUND: '部分出库', OUTBOUNDED: '全部出库', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
|
||||
if (poolOrderStatusLabels[String(value)]) return poolOrderStatusLabels[String(value)]
|
||||
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
|
||||
}
|
||||
function statusTone(value: unknown) {
|
||||
return ({ APPROVED: 'success', COMPLETED: 'success', OUTBOUNDED: 'success', REJECTED: 'danger', CANCELLED: 'info', PENDING_REVIEW: 'warning', PENDING_ACCEPTANCE: 'warning', PROCESSING: 'primary', IN_TRANSIT: 'primary' } as Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'>)[String(value)] || 'info'
|
||||
return ({ APPROVED: 'success', COMPLETED: 'success', REJECTED: 'danger', CANCELLED: 'info', PENDING_REVIEW: 'warning', PENDING_ACCEPTANCE: 'warning', PROCESSING: 'primary', IN_TRANSIT: 'primary' } as Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'>)[String(value)] || 'info'
|
||||
}
|
||||
function displayCell(candidate: unknown, key: string) {
|
||||
const row = candidate as BusinessRow
|
||||
const value = read(row, key)
|
||||
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 === 'transportMode') return transportModeLabel(value)
|
||||
if (key === 'palletRequired') return yesNo(value)
|
||||
if (key === 'createdAt') return dateTime(value)
|
||||
if (key === 'budgetUnitPrice' || key === 'budgetAmount') return money(value, read(row, 'currency'))
|
||||
if (key === 'budgetAmount') return money(value, read(row, 'currency'))
|
||||
return text(value)
|
||||
}
|
||||
function idempotencyKey() { return globalThis.crypto?.randomUUID?.() || `client-${Date.now()}-${Math.random().toString(16).slice(2)}` }
|
||||
@@ -267,12 +184,9 @@ async function load() {
|
||||
try {
|
||||
const params = {
|
||||
page: query.page, size: query.size, orderNo: query.orderNo || undefined, status: query.status || undefined,
|
||||
routeKeyword: query.routeKeyword || undefined, productName: query.productName || undefined,
|
||||
purchaseCategory: query.purchaseCategory || undefined,
|
||||
routeKeyword: query.routeKeyword || undefined,
|
||||
}
|
||||
const result = props.kind === 'procurement'
|
||||
? await listBusinessOrders<ProcurementSummary>('procurement', params)
|
||||
: await listBusinessOrders<TransportSummary>(props.kind, params)
|
||||
const result = await listBusinessOrders<TransportSummary>(props.kind, params)
|
||||
rows.value = result.records
|
||||
total.value = result.total
|
||||
} catch (cause) {
|
||||
@@ -283,13 +197,14 @@ async function load() {
|
||||
}
|
||||
|
||||
function resetQuery() {
|
||||
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' })
|
||||
void load()
|
||||
const reloadDirectly = query.page === 1
|
||||
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '' })
|
||||
if (reloadDirectly) void load()
|
||||
}
|
||||
|
||||
function searchOrders() {
|
||||
query.page = 1
|
||||
void load()
|
||||
if (query.page !== 1) query.page = 1
|
||||
else void load()
|
||||
}
|
||||
|
||||
function getRowActions(candidate: object): TableAction[] {
|
||||
@@ -297,16 +212,14 @@ function getRowActions(candidate: object): TableAction[] {
|
||||
}
|
||||
|
||||
function detailFieldClass(label: unknown) {
|
||||
return ['收货地址', '商品链接', '国内运单', '海外运单', '审核备注', '备注', '起运地址', '目的地址'].includes(String(label)) ? 'is-wide' : ''
|
||||
return ['备注', '起运地址', '目的地址'].includes(String(label)) ? 'is-wide' : ''
|
||||
}
|
||||
|
||||
const listRouteName = computed(() => ({
|
||||
procurement: 'cross-border-procurement',
|
||||
trucking: 'cross-border-domestic-trucking',
|
||||
looseboard: 'cross-border-pallet-shipping',
|
||||
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
||||
const detailRouteName = computed(() => ({
|
||||
procurement: 'cross-border-procurement-detail',
|
||||
trucking: 'cross-border-domestic-trucking-detail',
|
||||
looseboard: 'cross-border-pallet-shipping-detail',
|
||||
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
||||
@@ -328,45 +241,22 @@ async function loadDetail() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
detail.value = props.kind === 'procurement'
|
||||
? await getBusinessOrder<ProcurementDetail>('procurement', detailOrderNo.value)
|
||||
: await getBusinessOrder<TransportDetail>(props.kind, detailOrderNo.value)
|
||||
detail.value = await getBusinessOrder<TransportDetail>(props.kind, detailOrderNo.value)
|
||||
mode.value = 'detail'
|
||||
} catch (cause) { detail.value = null; error.value = errorMessage(cause); ElMessage.error(error.value) }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const failure = transportDemandError(props.kind === 'trucking' ? 'truck' : 'looseboard', form)
|
||||
if (failure) { ElMessage.error(failure); return }
|
||||
if (!await formRef.value?.validate().catch(() => false)) return
|
||||
submitting.value = true
|
||||
const stableSubmitKey = submitKey.value || idempotencyKey()
|
||||
submitKey.value = stableSubmitKey
|
||||
try {
|
||||
if (props.kind === 'procurement') {
|
||||
await createProcurement({
|
||||
customerName: auth.user?.tenantName || '',
|
||||
purchaseCategory: form.purchaseCategory, productName: form.productName,
|
||||
productSpecification: form.productSpecification || undefined, productUrl: form.productUrl || undefined,
|
||||
purchaseQuantity: form.purchaseQuantity, budgetUnitPrice: form.budgetAmount,
|
||||
currency: form.currency || undefined, receivingAddress: form.receivingAddress || undefined,
|
||||
contactName: form.contactName, contactPhone: form.contactInfo, remark: form.remark || undefined,
|
||||
idempotencyKey: stableSubmitKey,
|
||||
})
|
||||
} else {
|
||||
const base = {
|
||||
transportType: form.transportType, origin: form.origin, originAddress: form.originAddress || undefined,
|
||||
destination: form.destination, destinationAddress: form.destinationAddress || undefined,
|
||||
containerType: form.containerType || undefined, packageCount: form.packageCount,
|
||||
totalWeightKg: form.totalWeightKg, totalVolumeCbm: form.totalVolumeCbm,
|
||||
budgetAmount: form.budgetAmount, currency: form.currency || undefined,
|
||||
contactName: form.contactName || undefined, contactInfo: form.contactInfo || undefined,
|
||||
requestedDate: form.requestedDate || undefined, remark: form.remark || undefined,
|
||||
idempotencyKey: stableSubmitKey,
|
||||
}
|
||||
await createTransport(props.kind, props.kind === 'trucking'
|
||||
? { ...base, palletCount: form.palletCount }
|
||||
: { ...base, transportMode: form.transportMode, palletRequired: form.palletRequired })
|
||||
}
|
||||
if (props.kind === 'trucking') await createTransport('trucking', { ...buildTransportDemand('truck', form), idempotencyKey: stableSubmitKey })
|
||||
else await createTransport('looseboard', { ...buildTransportDemand('looseboard', form), idempotencyKey: stableSubmitKey })
|
||||
ElMessage.success('订单提交成功')
|
||||
resetForm()
|
||||
if (props.createPage) await router.push({ name: listRouteName.value })
|
||||
@@ -381,10 +271,10 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
|
||||
<template>
|
||||
<section v-loading="loading" class="business-orders client-ui" :aria-busy="loading">
|
||||
<header v-if="mode === 'create'" class="page-head">
|
||||
<header v-if="mode === 'create'" class="page-head" :class="{ 'looseboard-page-head': props.kind === 'looseboard' }">
|
||||
<div>
|
||||
<h2>{{ configuration.title }}下单</h2>
|
||||
<p>请填写订单信息,带 * 项为必填项</p>
|
||||
|
||||
</div>
|
||||
<el-button @click="returnToList">返回列表</el-button>
|
||||
</header>
|
||||
@@ -397,6 +287,7 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
<template v-if="error" #error><div class="business-load-error" role="alert"><span>{{ error }}</span><el-button size="small" @click="load">重新加载</el-button></div></template>
|
||||
<template #orderNo="{ row }"><button class="business-order-link" type="button" @click="openDetail(row)">{{ (row as BusinessRow).orderNo }}</button></template>
|
||||
<template #status="{ row }"><el-tag :type="statusTone((row as BusinessRow).status)" effect="light" size="small">{{ statusLabel((row as BusinessRow).status) }}</el-tag></template>
|
||||
<template #fleetArrangement="{ row }"><template v-if="(row as TransportSummary).fleetArrangement"><div>{{ poolOrderStatusLabels[(row as TransportSummary).fleetArrangement!.fulfillmentStage] || '待核对履约进度' }}</div><small>{{ dateTime((row as TransportSummary).fleetArrangement!.plannedDepartureAt) }}</small></template><span v-else>—</span></template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
@@ -409,43 +300,32 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
<div v-if="error" class="business-detail-error" role="alert"><strong>{{ error }}</strong><el-button size="small" @click="loadDetail">重新加载</el-button></div>
|
||||
<section v-else class="business-detail-section">
|
||||
<h3>订单信息</h3>
|
||||
<dl class="detail-grid">
|
||||
<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>
|
||||
</dl>
|
||||
</section>
|
||||
<section v-if="!error && fleetArrangement" class="business-detail-section" aria-label="承运安排">
|
||||
<h3>承运安排</h3><p>{{ fleetArrangement.readOnlyReason }}</p>
|
||||
<dl class="detail-grid arrangement-grid">
|
||||
<div><dt>预订号</dt><dd>{{ fleetArrangement.bookingNo }}</dd></div>
|
||||
<div><dt>计划发车</dt><dd>{{ dateTime(fleetArrangement.plannedDepartureAt) }}</dd></div>
|
||||
<div><dt>起运仓</dt><dd>{{ text(fleetArrangement.originWarehouseName) }}</dd></div>
|
||||
<div><dt>目的地</dt><dd>{{ text(fleetArrangement.destinationLabel) }}</dd></div>
|
||||
<div><dt>交货方式</dt><dd>{{ fleetArrangement.deliveryMode === 'SELF_DELIVERY' ? '自行送至起运仓' : '线下安排提货至起运仓' }}</dd></div>
|
||||
<div><dt>履约进度</dt><dd>{{ poolOrderStatusLabels[fleetArrangement.fulfillmentStage] || '待核对履约进度' }}</dd></div>
|
||||
<div><dt>更新时间</dt><dd>{{ dateTime(fleetArrangement.stageOccurredAt) }}</dd></div>
|
||||
<div><dt>约定运费(非实收)</dt><dd>{{ money(fleetArrangement.agreedFreightAmount, fleetArrangement.currency) }}</dd></div>
|
||||
<div><dt>来货单号</dt><dd>{{ text(fleetArrangement.incomingNo) }}</dd></div>
|
||||
<div><dt>派送单号</dt><dd>{{ text(fleetArrangement.deliveryNo) }}</dd></div>
|
||||
<div><dt>已签 / 未签 / 退回箱数</dt><dd>{{ fleetArrangement.signedPackages ?? '—' }} / {{ fleetArrangement.unsignedPackages ?? '—' }} / {{ fleetArrangement.returnedPackages ?? '—' }}</dd></div>
|
||||
<div class="is-wide"><dt>交货说明</dt><dd>{{ text(fleetArrangement.deliveryInstructions) }}</dd></div>
|
||||
<div v-if="fleetArrangement.exceptionSummary" class="is-wide"><dt>履约说明</dt><dd>{{ fleetArrangement.exceptionSummary }}</dd></div>
|
||||
</dl>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<el-card v-else shadow="never" class="form-card">
|
||||
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
|
||||
<template v-if="kind === 'procurement'">
|
||||
<el-form-item label="采购品类" prop="purchaseCategory"><el-input v-model.trim="form.purchaseCategory" maxlength="128" placeholder="请输入采购品类" /></el-form-item>
|
||||
<el-form-item label="商品名称" prop="productName"><el-input v-model.trim="form.productName" maxlength="255" placeholder="请输入商品名称" /></el-form-item>
|
||||
<el-form-item label="商品规格"><el-input v-model.trim="form.productSpecification" maxlength="500" placeholder="请输入规格、型号等信息" /></el-form-item>
|
||||
<el-form-item label="商品链接"><el-input v-model.trim="form.productUrl" maxlength="2000" placeholder="请输入商品链接" /></el-form-item>
|
||||
<el-form-item label="采购数量" prop="purchaseQuantity"><el-input-number v-model="form.purchaseQuantity" :min="1" placeholder="请输入数量" /></el-form-item>
|
||||
<el-form-item label="收货地址"><el-input v-model.trim="form.receivingAddress" maxlength="1000" placeholder="请输入收货地址" /></el-form-item>
|
||||
</template>
|
||||
<template v-else>
|
||||
<el-form-item v-if="kind === 'looseboard'" label="运输方式"><el-radio-group v-model="form.transportMode"><el-radio-button value="SHARED_TRUCK">拼车</el-radio-button><el-radio-button value="PRIORITY_CONSOLIDATION">优先拼载</el-radio-button></el-radio-group></el-form-item>
|
||||
<el-form-item v-if="kind === 'looseboard'" label="是否打盘"><el-radio-group v-model="form.palletRequired"><el-radio-button value="NO">否</el-radio-button><el-radio-button value="YES">是</el-radio-button></el-radio-group></el-form-item>
|
||||
<el-form-item label="运输类型"><el-select v-model="form.transportType"><el-option label="港口提柜" value="PORT_PICKUP" /><el-option label="仓到仓" value="WAREHOUSE_TO_WAREHOUSE" /><el-option label="仓到门" value="WAREHOUSE_TO_DOOR" /></el-select></el-form-item>
|
||||
<el-form-item label="起运地" prop="origin"><el-input v-model.trim="form.origin" maxlength="255" placeholder="请输入起运地" /></el-form-item>
|
||||
<el-form-item label="起运地址"><el-input v-model.trim="form.originAddress" maxlength="500" placeholder="请输入详细起运地址" /></el-form-item>
|
||||
<el-form-item label="目的地" prop="destination"><el-input v-model.trim="form.destination" maxlength="255" placeholder="请输入目的地" /></el-form-item>
|
||||
<el-form-item label="目的地址"><el-input v-model.trim="form.destinationAddress" maxlength="500" placeholder="请输入详细目的地址" /></el-form-item>
|
||||
<el-form-item label="柜型"><el-select v-model="form.containerType"><el-option v-for="item in CONTAINER_SPECIFICATIONS" :key="item.type" :label="item.type" :value="item.type" /></el-select></el-form-item>
|
||||
<el-form-item v-if="kind === 'trucking'" label="托盘数" prop="palletCount"><el-input-number v-model="form.palletCount" :min="1" placeholder="请输入托盘数" /></el-form-item>
|
||||
<el-form-item label="件数"><el-input-number v-model="form.packageCount" :min="0" placeholder="请输入件数" /></el-form-item>
|
||||
<el-form-item label="总重量(kg)"><el-input-number v-model="form.totalWeightKg" :min="0" :precision="2" placeholder="请输入总重量" /></el-form-item>
|
||||
<el-form-item label="总体积(m³)"><el-input-number v-model="form.totalVolumeCbm" :min="0" :precision="3" placeholder="请输入总体积" /></el-form-item>
|
||||
<el-form-item label="要求时间" :prop="kind === 'trucking' ? 'requestedDate' : undefined"><el-date-picker v-model="form.requestedDate" type="date" value-format="YYYY-MM-DD" /></el-form-item>
|
||||
</template>
|
||||
<el-form-item class="budget-form-item" :label="kind === 'procurement' ? '预算单价' : '预算金额'"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2" placeholder="请输入预算金额" /><el-select v-model="form.currency" class="currency"><el-option label="USD" value="USD" /><el-option label="CNY" value="CNY" /></el-select></el-form-item>
|
||||
<el-form-item label="联系人" prop="contactName"><el-input v-model.trim="form.contactName" maxlength="128" placeholder="请输入联系人" /></el-form-item>
|
||||
<el-form-item label="联系方式" prop="contactInfo"><el-input v-model.trim="form.contactInfo" maxlength="128" placeholder="请输入电话、微信或邮箱" /></el-form-item>
|
||||
<el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请输入其他要求" /></el-form-item>
|
||||
<el-form-item><el-button @click="returnToList">取消</el-button><el-button v-if="canCreate" type="primary" :loading="submitting" @click="submit">提交订单</el-button></el-form-item>
|
||||
</el-form>
|
||||
<TransportDemandForm ref="formRef" :model="form" :kind="kind === 'trucking' ? 'truck' : 'looseboard'" :submitting="submitting" :can-submit="canCreate" @submit="submit" @cancel="returnToList" />
|
||||
</el-card>
|
||||
</section>
|
||||
</template>
|
||||
@@ -453,6 +333,7 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
||||
<style scoped>
|
||||
.business-orders { display: grid; gap: var(--client-section-gap); }
|
||||
.page-head { display: flex; align-items: center; justify-content: space-between; gap: 24px; }
|
||||
.looseboard-page-head { max-width: 1180px; padding-right: 30px; box-sizing: border-box; }
|
||||
.page-head h2 { margin: 0; color: #111827; font-size: 26px; }
|
||||
.page-head p { margin: 7px 0 0; color: #64748b; font-size: 14px; }
|
||||
.business-table-card { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
|
||||
@@ -470,12 +351,13 @@ 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; }
|
||||
.detail-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin: 0; border-top: 1px solid var(--border); border-left: 1px solid var(--border); }
|
||||
.detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 76px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||
.trucking-detail-grid div { grid-template-columns: 112px minmax(0, 1fr); }
|
||||
.detail-grid div.is-wide { grid-column: span 2; }
|
||||
.detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
|
||||
.arrangement-grid div { grid-template-columns: 124px minmax(0, 1fr); }
|
||||
.arrangement-grid dt { white-space: normal; overflow-wrap: anywhere; }
|
||||
.detail-grid dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--navy); font-size: 12px; font-weight: 600; line-height: 1.4; }
|
||||
.form-card :deep(.el-form) { max-width: 860px; }
|
||||
.form-card :deep(.el-input), .form-card :deep(.el-textarea), .form-card :deep(.el-select) { width: 100%; }
|
||||
.form-card .currency { width: 110px; margin-left: 12px; }
|
||||
.form-card :deep(.el-card__body) { padding: 0; }
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.business-orders { gap: 14px; }
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { ProcurementDetail, ProcurementFee } from '../api/procurement'
|
||||
import { dateTime, feePurposes, feeStatus, feeTone, feeTotals, measurement, money, productHref, text } from '../procurementPresentation'
|
||||
|
||||
const props = defineProps<{ detail: ProcurementDetail }>()
|
||||
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>
|
||||
|
||||
<template>
|
||||
<section class="procurement-section" aria-label="采购履约进度">
|
||||
<h3>履约进度</h3>
|
||||
<ol class="procurement-progress">
|
||||
<li v-for="step in progress" :key="step.key" :class="{ 'is-complete': step.completedAt }">
|
||||
<strong>{{ step.title }}</strong><span>{{ step.completedAt ? dateTime(step.completedAt) : ended ? '未执行' : '待处理' }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
<p v-if="detail.purchaseNeedsAttention" class="procurement-note">购买资料正在核对,客服将协助处理。已发生的收货与费用结果仍保留在本单。</p>
|
||||
</section>
|
||||
<section class="procurement-section" aria-label="商品与收件信息">
|
||||
<h3>商品与收件信息</h3>
|
||||
<dl class="procurement-grid">
|
||||
<div><dt>采购品类</dt><dd>{{ detail.order.purchaseCategory }}</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>{{ detail.order.purchaseQuantity }} 件</dd></div>
|
||||
<div><dt>下单预算单价</dt><dd>{{ money(detail.order.budgetUnitPrice, detail.order.currency) }}</dd></div>
|
||||
<div><dt>货款预算总上限</dt><dd>{{ money(detail.budget.totalAmount, detail.budget.currency) }}</dd></div>
|
||||
<div><dt>预算核验时间</dt><dd>{{ dateTime(detail.budget.authorizedAt) }}</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.contactPhone }}</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 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>
|
||||
</section>
|
||||
<section class="procurement-section" aria-label="已确认海外装箱清单">
|
||||
<h3>已确认海外装箱清单</h3>
|
||||
<el-table :data="detail.boxes" border stripe empty-text="尚无已确认的装箱清单" row-key="cartonNo">
|
||||
<el-table-column prop="cartonNo" label="箱号" min-width="170" />
|
||||
<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>
|
||||
|
||||
</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>
|
||||
|
||||
<style scoped>
|
||||
.procurement-section { margin-top: 18px; min-width: 0; }
|
||||
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 > div { display: grid; grid-template-columns: 110px minmax(0, 1fr); align-items: center; gap: 8px; padding: 9px 12px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); min-width: 0; }
|
||||
.procurement-grid dt { font-size: 12px; color: var(--muted); }.procurement-grid dd { margin: 0; font-size: 13px; line-height: 1.6; color: var(--navy); overflow-wrap: anywhere; }
|
||||
.procurement-grid .wide { grid-column: span 2; }.money-grid > div { grid-template-columns: minmax(0, 1fr); }.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; }
|
||||
.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; }
|
||||
@media (max-width: 767px) {
|
||||
.procurement-progress, .procurement-grid { grid-template-columns: 1fr; }.procurement-grid .wide { grid-column: auto; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,87 @@
|
||||
<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))
|
||||
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" :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">
|
||||
<el-form-item v-if="kind === 'truck'" class="transport-demand-wide" label="车辆类型" prop="vehicleType">
|
||||
<el-select v-model="model.vehicleType" placeholder=""><el-option label="15拖" value="PALLET_15" /><el-option label="30拖" value="PALLET_30" /></el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="起运地" prop="origin"><el-input v-model.trim="model.origin" maxlength="255" placeholder="城市 / 港口 / 州" /></el-form-item>
|
||||
<el-form-item label="目的地" prop="destination"><el-input v-model.trim="model.destination" maxlength="255" placeholder="城市 / 州" /></el-form-item>
|
||||
<el-form-item label="起运地联系人" prop="originContactName"><el-input v-model.trim="model.originContactName" maxlength="128" placeholder="" /></el-form-item>
|
||||
<el-form-item label="目的地联系人" prop="destinationContactName"><el-input v-model.trim="model.destinationContactName" maxlength="128" placeholder="" /></el-form-item>
|
||||
<el-form-item label="起运地联系电话" prop="originContactPhone"><el-input v-model.trim="model.originContactPhone" type="tel" maxlength="128" placeholder="" /></el-form-item>
|
||||
<el-form-item label="目的地联系电话" prop="destinationContactPhone"><el-input v-model.trim="model.destinationContactPhone" type="tel" maxlength="128" placeholder="" /></el-form-item>
|
||||
<el-form-item label="起运详细地址"><el-input v-model.trim="model.originAddress" maxlength="500" placeholder="街道 / 门牌等补充信息(选填)" /></el-form-item>
|
||||
<el-form-item label="目的详细地址"><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' ? '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="" /></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="" /></el-form-item>
|
||||
<el-form-item v-if="kind === 'truck'" label="件数" prop="packageCount"><el-input-number v-model="model.packageCount" :min="0" :precision="0" controls-position="right" placeholder="" /></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="" /></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="" /></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="" /></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="" />
|
||||
<el-select v-model="model.currency" 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="取货时间" prop="pickupAt"><el-date-picker v-model="model.pickupAt" type="datetime" format="YYYY-MM-DD HH:mm" time-format="HH:mm" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="" @change="formRef?.validateField('deliveryAt').catch(() => undefined)" /></el-form-item>
|
||||
<el-form-item label="送货时间" prop="deliveryAt"><el-date-picker v-model="model.deliveryAt" type="datetime" format="YYYY-MM-DD HH:mm" time-format="HH:mm" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="" /></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 placeholder="" /></el-form-item>
|
||||
</div>
|
||||
</section>
|
||||
<footer class="transport-demand-actions">
|
||||
<el-button :disabled="submitting" @click="emit('cancel')">取消</el-button>
|
||||
<el-button v-if="canSubmit" type="primary" :loading="submitting" :disabled="disabled" @click="emit('submit')">{{ editing ? '保存修改' : '提交订单' }}</el-button>
|
||||
</footer>
|
||||
</el-form>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.transport-demand-form { --el-component-size: 36px; width: 100%; max-width: 1180px; margin: 0; background: #fff; }
|
||||
.transport-demand-section { padding: 20px 24px 0; border-bottom: 1px solid #e7ebf1; }
|
||||
.transport-demand-section h3 { margin: 0 0 16px; color: #27364d; font-size: 14px; font-weight: 600; }
|
||||
.transport-demand-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 24px; }
|
||||
.transport-demand-cargo-three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.transport-demand-cargo-four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.transport-demand-wide { grid-column: 1 / -1; }
|
||||
.transport-demand-form :deep(.el-form-item) { min-width: 0; margin-bottom: 18px; }
|
||||
.transport-demand-form :deep(.el-form-item__label) { height: auto; padding-bottom: 6px; font-size: 13px; line-height: 20px; }
|
||||
.transport-demand-form :deep(.el-input), .transport-demand-form :deep(.el-input-number), .transport-demand-form :deep(.el-select), .transport-demand-form :deep(.el-date-editor) { width: 100%; }
|
||||
.transport-demand-budget { display: grid; width: 100%; grid-template-columns: minmax(0, 1fr) 100px; gap: 10px; }
|
||||
.transport-demand-actions { display: flex; justify-content: flex-end; gap: 10px; padding: 18px 24px; }
|
||||
.transport-demand-actions :deep(.el-button + .el-button) { margin-left: 0; }
|
||||
</style>
|
||||
@@ -0,0 +1,28 @@
|
||||
export interface FleetArrangement {
|
||||
sourceType: 'FLEET_CAPACITY_OFFER'
|
||||
businessType: 'LOCAL_LOOSEBOARD' | 'US_TRUCK'
|
||||
businessOrderNo: string
|
||||
bookingNo: string
|
||||
tripNo: string
|
||||
plannedDepartureAt: string | null
|
||||
originWarehouseName: string
|
||||
destinationLabel: string
|
||||
deliveryMode: 'SELF_DELIVERY' | 'MANUAL_PICKUP_TO_WAREHOUSE'
|
||||
deliveryInstructions: string | null
|
||||
fulfillmentStage: string
|
||||
stageOccurredAt: string | null
|
||||
agreedFreightAmount: number | null
|
||||
currency: string | null
|
||||
incomingNo: string | null
|
||||
dispatchNo: string | null
|
||||
deliveryNo: string | null
|
||||
signedPackages: number | null
|
||||
unsignedPackages: number | null
|
||||
returnedPackages: number | null
|
||||
exceptionSummary: string | null
|
||||
readOnlyReason: string
|
||||
}
|
||||
export const poolOrderStatusLabels: Record<string, string> = {
|
||||
WAITING_INBOUND: '待入仓', RECEIVING: '收货中', WAITING_CONSOLIDATION: '待合托',
|
||||
PENDING_DISPATCH: '待派车', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消',
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import { parse, compileScript } from 'vue/compiler-sfc'
|
||||
|
||||
let nextKey = 0
|
||||
const crypto = { randomUUID: () => `test-key-${++nextKey}` }
|
||||
function moduleFrom(source, require = () => { throw new Error('unexpected import') }) {
|
||||
const context = { exports: {}, require, URL, Error, crypto }
|
||||
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||
runInNewContext(code, context)
|
||||
return context.exports
|
||||
}
|
||||
const presentation = moduleFrom(readFileSync(new URL('./procurementPresentation.ts', import.meta.url), 'utf8'))
|
||||
const submission = moduleFrom(readFileSync(new URL('./procurementSubmission.ts', import.meta.url), 'utf8'), name => {
|
||||
if (name === './procurementPresentation') return presentation
|
||||
throw new Error(`unexpected import ${name}`)
|
||||
})
|
||||
const normalized = value => JSON.parse(JSON.stringify(value))
|
||||
const draft = () => ({ ...presentation.emptyProcurementDraft(), purchaseCategory: 'Sample', productName: 'Test product', productSpecification: 'A',
|
||||
purchaseQuantity: '3', budgetUnitPrice: '0.29', receivingAddress: '测试省测试市测试街 1 号', contactName: '测试收件人', contactPhone: '13800000000' })
|
||||
const fee = (purpose, walletStatus, amount) => ({ purpose, walletStatus, amount, currency: 'CNY' })
|
||||
|
||||
test('budget distinguishes unknown from zero, preserves cents, and requires a real telephone/address', () => {
|
||||
assert.equal(presentation.draftBudgetTotal(draft()), '0.87')
|
||||
const valid = presentation.buildProcurementCreate(draft(), 'Authenticated Company', 'same-key')
|
||||
assert.equal(valid.customerName, 'Authenticated Company')
|
||||
assert.equal(valid.budgetUnitPrice, 0.29)
|
||||
for (const value of ['', '-1', '1.001', '90071992547409.91']) assert.throws(() => presentation.buildProcurementCreate({ ...draft(), budgetUnitPrice: value }, 'Company', 'key'), /预算/)
|
||||
assert.equal(presentation.buildProcurementCreate({ ...draft(), budgetUnitPrice: '0' }, 'Company', 'key').budgetUnitPrice, 0)
|
||||
for (const patch of [{ contactPhone: 'wechat-name' }, { contactPhone: 'a@test.invalid' }, { receivingAddress: '' }, { purchaseQuantity: '1.5' }]) {
|
||||
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), ...patch }, 'Company', 'key'))
|
||||
}
|
||||
assert.equal(presentation.measurement(20, 2), '20.00')
|
||||
assert.equal(presentation.measurement('5.125', 3), '5.125')
|
||||
assert.equal(presentation.measurement('1.234', 2), '待核对')
|
||||
assert.equal(presentation.money(null), '—')
|
||||
assert.equal(presentation.money(0), 'CNY 0.00')
|
||||
assert.equal(presentation.productHref('javascript:alert(1)'), undefined)
|
||||
assert.equal(presentation.productHref('https://example.com/item'), 'https://example.com/item')
|
||||
})
|
||||
|
||||
test('successful net debit excludes the original estimate and counts only successful refunds and differences', () => {
|
||||
const result = presentation.feeTotals([fee('INTERNATIONAL_ESTIMATE', 'SETTLED', '100'), fee('INTERNATIONAL_FREIGHT', 'SETTLED', '100'),
|
||||
fee('ADJUSTMENT', 'SETTLED', '20'), fee('ADJUSTMENT', 'SETTLED', '10'), fee('REFUND', 'REFUNDED', '20'), fee('REFUND', 'REFUND_PENDING', '5')])
|
||||
assert.deepEqual(normalized(result), { paid: '130.00', refunded: '20.00', net: '110.00', estimatedHold: '0.00' })
|
||||
assert.equal(presentation.feeTotals([fee('INTERNATIONAL_ESTIMATE', 'RELEASE_PENDING', '100')]).estimatedHold, '100.00')
|
||||
assert.equal(presentation.feeTotals([fee('DUTY', 'SETTLED', 'unknown')]), null)
|
||||
assert.equal(presentation.feeStatus(fee('INTERNATIONAL_ESTIMATE', 'FROZEN', 100)), '已冻结,未扣款')
|
||||
assert.equal(presentation.feeStatus(fee('INTERNATIONAL_ESTIMATE', 'SETTLED', 100)), '原预估已结清')
|
||||
assert.equal(presentation.feeStatus(fee('DUTY', null, 100)), '待核定')
|
||||
})
|
||||
|
||||
test('new requests get unique keys without restoring stored submissions', () => {
|
||||
assert.notEqual(submission.procurementRequestKey(crypto), submission.procurementRequestKey(crypto))
|
||||
})
|
||||
|
||||
class ApiError extends Error { constructor(message, code, status) { super(message); this.code = code; this.status = status } }
|
||||
const flush = async () => { await vue.nextTick(); await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
|
||||
function viewHarness({ createPage = false, detailPage = false, api = {}, storage = new Map() } = {}) {
|
||||
const props = vue.reactive({ createPage, detailPage })
|
||||
const route = vue.reactive({ params: { orderNo: detailPage ? 'PO-1' : '' } })
|
||||
const auth = vue.reactive({ token: 'identity-A', user: { tenantName: 'Company' }, profile: { tenantName: 'Company' }, hasPermission: () => true })
|
||||
const pushes = [], dispose = []
|
||||
const defaults = { listProcurements: async () => ({ records: [], total: 0 }), getProcurement: async orderNo => ({ order: { orderNo } }), createProcurement: async () => ({ order: { orderNo: 'PO-CREATED' } }) }
|
||||
const { descriptor } = parse(readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8'))
|
||||
const source = compileScript(descriptor, { id: 'procurement-test' }).content
|
||||
const context = { exports: {}, Error, crypto, sessionStorage: { getItem: key => storage.get(key) || null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) },
|
||||
require(name) {
|
||||
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => dispose.push(callback), watch: (...args) => { const stop = vue.watch(...args); dispose.push(stop); return stop } }
|
||||
if (name === 'vue-router') return { useRoute: () => route, useRouter: () => ({ push: async target => pushes.push(target) }) }
|
||||
if (name === 'element-plus') return { ElMessage: { success: () => {} } }
|
||||
if (name === '@/api/types') return { ApiError }
|
||||
if (name === '@/api/session') return { accessTokenIdentity: token => token }
|
||||
if (name === '@/modules/auth/public') return { useAuthStore: () => auth }
|
||||
if (name === '../api/procurement') return { ...defaults, ...api }
|
||||
if (name === '../procurementPresentation') return presentation
|
||||
if (name === '../procurementSubmission') return submission
|
||||
if (name.endsWith('.vue')) return { default: {} }
|
||||
throw new Error(`unexpected view import ${name}`)
|
||||
},
|
||||
}
|
||||
runInNewContext(ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText, context)
|
||||
const state = context.exports.default.setup(props, { expose: () => {} })
|
||||
return { state, props, route, auth, pushes, storage, dispose: () => dispose.forEach(callback => callback()) }
|
||||
}
|
||||
|
||||
test('detail has one in-flight request and an older response cannot overwrite another order', async () => {
|
||||
const calls = [], pending = new Map()
|
||||
const harness = viewHarness({ detailPage: true, api: { getProcurement: orderNo => { calls.push(orderNo); return new Promise(resolve => pending.set(orderNo, resolve)) } } })
|
||||
try {
|
||||
assert.deepEqual(calls, ['PO-1'])
|
||||
await harness.state.loadDetail(); assert.equal(calls.length, 1)
|
||||
harness.route.params.orderNo = 'PO-2'; await flush(); assert.deepEqual(calls, ['PO-1', 'PO-2'])
|
||||
pending.get('PO-1')({ order: { orderNo: 'PO-1' } }); await flush(); assert.equal(harness.state.detail.value, null)
|
||||
pending.get('PO-2')({ order: { orderNo: 'PO-2' } }); await flush(); assert.equal(harness.state.detail.value.order.orderNo, 'PO-2')
|
||||
assert.equal(harness.state.loading.value, false)
|
||||
} finally { harness.dispose() }
|
||||
})
|
||||
|
||||
test('timeout releases the form and another click submits the edited current values', async () => {
|
||||
const calls = []
|
||||
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => { calls.push(normalized(payload)); throw new ApiError('timeout', 'TIMEOUT') } } })
|
||||
try {
|
||||
Object.assign(harness.state.form, draft()); await harness.state.submit()
|
||||
assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
|
||||
harness.state.form.productName = 'changed'; await harness.state.submit()
|
||||
assert.equal(calls[1].productName, 'changed'); assert.notEqual(calls[0].idempotencyKey, calls[1].idempotencyKey)
|
||||
assert.equal(harness.state.submitting.value, false)
|
||||
} finally { harness.dispose() }
|
||||
})
|
||||
|
||||
test('submission double-click sends once and definitive validation rejection permits correction', async () => {
|
||||
let reject, calls = 0
|
||||
const harness = viewHarness({ createPage: true, api: { createProcurement: () => { calls++; return new Promise((_, failure) => { reject = failure }) } } })
|
||||
try {
|
||||
Object.assign(harness.state.form, draft()); const first = harness.state.submit(); await harness.state.submit(); assert.equal(calls, 1)
|
||||
reject(new ApiError('invalid', 'A0422')); await first
|
||||
assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
|
||||
} finally { harness.dispose() }
|
||||
})
|
||||
|
||||
test('pagination batches one request and switching account clears old rows before the new response', async () => {
|
||||
const calls = []; let resolveSecond
|
||||
const harness = viewHarness({ api: { listProcurements: async params => {
|
||||
calls.push(normalized(params)); if (calls.length < 3) return { records: [{ orderNo: 'PO-A' }], total: 100 }
|
||||
return new Promise(resolve => { resolveSecond = resolve })
|
||||
} } })
|
||||
try {
|
||||
await flush(); assert.equal(calls.length, 1)
|
||||
harness.state.query.page = 2; harness.state.query.size = 50; await flush(); assert.equal(calls.length, 2)
|
||||
harness.auth.token = 'identity-B'; await vue.nextTick(); assert.equal(harness.state.rows.value.length, 0); assert.equal(harness.state.total.value, 0)
|
||||
resolveSecond({ records: [{ orderNo: 'PO-B' }], total: 1 }); await flush(); assert.equal(harness.state.rows.value[0].orderNo, 'PO-B')
|
||||
assert.ok(calls.every(params => !('customerId' in params) && !('tenantId' in params)))
|
||||
} finally { harness.dispose() }
|
||||
})
|
||||
|
||||
|
||||
test('consecutive timeout and permission failures never persist or freeze a submission', async () => {
|
||||
let attempt = 0
|
||||
const harness = viewHarness({ createPage: true, api: { createProcurement: async () => { throw new ApiError('failed', ++attempt === 1 ? 'TIMEOUT' : 'A0403') } } })
|
||||
try {
|
||||
Object.assign(harness.state.form, draft()); await harness.state.submit(); await harness.state.submit()
|
||||
assert.equal(attempt, 2); assert.equal(harness.state.submitting.value, false); assert.equal(harness.storage.size, 0)
|
||||
harness.state.form.productName = 'editable'; assert.equal(harness.state.form.productName, 'editable')
|
||||
} finally { harness.dispose() }
|
||||
})
|
||||
|
||||
test('purchase category is optional while its length remains bounded', () => {
|
||||
const payload = presentation.buildProcurementCreate({ ...draft(), purchaseCategory: ' ' }, 'Company', 'key')
|
||||
assert.equal(payload.purchaseCategory, '')
|
||||
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), purchaseCategory: 'x'.repeat(129) }, 'Company', 'key'), /品类/)
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { Amount, ProcurementCreate, ProcurementFee } from './api/procurement'
|
||||
|
||||
export const procurementStatuses: Record<string, string> = {
|
||||
PENDING_REVIEW: '待审核', WAIT_PURCHASE: '待购买', WAIT_OVERSEAS_RECEIPT: '待海外到仓', OVERSEAS_RECEIVING: '海外收货中',
|
||||
WAIT_PACKING: '待装箱', WAIT_LABELS: '待面单及预估处理', WAIT_OVERSEAS_SHIPMENT: '待海外交寄', INTERNATIONAL_TRANSIT: '国际运输中',
|
||||
DOMESTIC_RECEIVING: '国内收货中', WAIT_CHARGES: '待国内核费', WAIT_CUSTOMER_SHIPMENT: '待寄客户', SHIPPED_TO_CUSTOMER: '已寄客户',
|
||||
REJECTED: '已拒绝', CANCELLED: '已取消', EXCEPTION_CLOSED: '异常关闭',
|
||||
}
|
||||
export const feePurposes: Record<string, string> = {
|
||||
SAMPLE_PAYMENT: '样品货款', INTERNATIONAL_ESTIMATE: '预估国际运费', INTERNATIONAL_FREIGHT: '实际国际运费',
|
||||
DUTY: '关税', DOMESTIC_FREIGHT: '国内运费', OTHER: '其他费用', ADJUSTMENT: '追加费用', REFUND: '退款',
|
||||
}
|
||||
export function statusLabel(status: string | null | undefined) { return status ? procurementStatuses[status] || '待核对进度' : '—' }
|
||||
export function statusTone(status: string | null | undefined): 'success' | 'warning' | 'danger' | 'info' | 'primary' {
|
||||
if (status === 'SHIPPED_TO_CUSTOMER') return 'success'
|
||||
if (status === 'REJECTED' || status === 'EXCEPTION_CLOSED') return 'danger'
|
||||
if (status === 'CANCELLED') return 'info'
|
||||
if (status === 'INTERNATIONAL_TRANSIT') return 'primary'
|
||||
return 'warning'
|
||||
}
|
||||
function cents(value: Amount | null | undefined): bigint | null {
|
||||
if (value === null || value === undefined) return null
|
||||
const match = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(String(value).trim())
|
||||
if (!match) return null
|
||||
const result = BigInt(match[2]) * 100n + BigInt((match[3] || '').padEnd(2, '0'))
|
||||
return match[1] ? -result : result
|
||||
}
|
||||
function decimal(value: bigint) {
|
||||
const absolute = value < 0n ? -value : value
|
||||
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`
|
||||
}
|
||||
export function money(value: Amount | null | undefined, currency: string | null | undefined = 'CNY') {
|
||||
const amount = cents(value)
|
||||
return amount === null ? '—' : `${currency || '—'} ${decimal(amount)}`
|
||||
}
|
||||
export function dateTime(value: string | null | undefined) { return value ? value.replace('T', ' ').replace(/\.\d+$/, '') : '—' }
|
||||
export function measurement(value: Amount | null | undefined, scale: number) {
|
||||
if (value === null || value === undefined) return '—'
|
||||
const parts = /^(\d+)(?:\.(\d+))?$/.exec(String(value))
|
||||
if (!parts || (parts[2] || '').length > scale) return '待核对'
|
||||
return `${parts[1]}.${(parts[2] || '').padEnd(scale, '0')}`
|
||||
}
|
||||
export function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
|
||||
export function productHref(value: string | null | undefined) {
|
||||
if (!value) return undefined
|
||||
try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) ? url.href : undefined } catch { return undefined }
|
||||
}
|
||||
export function feeStatus(fee: ProcurementFee) {
|
||||
if (fee.purpose === 'INTERNATIONAL_ESTIMATE') {
|
||||
const label: Record<string, string> = { FROZEN: '已冻结,未扣款', ZERO: '零预估已确认', SETTLED: '原预估已结清', RELEASED: '预估已释放' }
|
||||
if (fee.walletStatus && label[fee.walletStatus]) return label[fee.walletStatus]
|
||||
}
|
||||
const labels: Record<string, string> = {
|
||||
FREEZE_PENDING: '冻结处理中', FREEZE_FAILED: '冻结未成功', FROZEN: '等待扣款', SETTLE_PENDING: '扣款处理中', SETTLE_ACTUAL_PENDING: '实际费用结算中',
|
||||
SETTLE_FAILED: '扣款未成功', SETTLE_ACTUAL_FAILED: '实际费用未结清', SETTLED: '已扣款', RELEASE_PENDING: '释放处理中', RELEASE_FAILED: '释放未成功',
|
||||
RELEASED: '已释放冻结', REFUND_PENDING: '退款处理中', REFUND_FAILED: '退款未成功', REFUNDED: '已退款', ZERO: '已确认零元', NOT_APPLICABLE: '不适用', TERMINATED: '已终止',
|
||||
}
|
||||
return fee.walletStatus ? labels[fee.walletStatus] || '待核定' : '待核定'
|
||||
}
|
||||
export function feeTone(fee: ProcurementFee): 'success' | 'warning' | 'danger' | 'info' {
|
||||
if (fee.walletStatus?.endsWith('_FAILED')) return 'danger'
|
||||
if (['SETTLED', 'REFUNDED', 'ZERO', 'NOT_APPLICABLE', 'RELEASED'].includes(fee.walletStatus || '')) return 'success'
|
||||
if (fee.walletStatus === 'TERMINATED') return 'info'
|
||||
return 'warning'
|
||||
}
|
||||
export function feeTotals(fees: ProcurementFee[]) {
|
||||
let paid = 0n, refunded = 0n, estimatedHold = 0n
|
||||
for (const fee of fees) {
|
||||
const estimate = fee.purpose === 'INTERNATIONAL_ESTIMATE'
|
||||
const include = (!estimate && fee.walletStatus === 'SETTLED') || fee.walletStatus === 'REFUNDED'
|
||||
|| (estimate && ['FROZEN', 'RELEASE_PENDING', 'RELEASE_FAILED'].includes(fee.walletStatus || ''))
|
||||
if (!include) continue
|
||||
const amount = cents(fee.amount)
|
||||
if (amount === null || amount < 0n || fee.currency !== 'CNY') return null
|
||||
if (estimate) estimatedHold += amount
|
||||
else if (fee.walletStatus === 'REFUNDED') refunded += amount
|
||||
else paid += amount
|
||||
}
|
||||
return { paid: decimal(paid), refunded: decimal(refunded), net: decimal(paid - refunded), estimatedHold: decimal(estimatedHold) }
|
||||
}
|
||||
export interface ProcurementDraft {
|
||||
purchaseCategory: string
|
||||
productName: string
|
||||
productSpecification: string
|
||||
productUrl: string
|
||||
purchaseQuantity: string
|
||||
budgetUnitPrice: string
|
||||
currency: 'CNY' | 'USD'
|
||||
receivingAddress: string
|
||||
contactName: string
|
||||
contactPhone: string
|
||||
remark: string
|
||||
}
|
||||
export function emptyProcurementDraft(): ProcurementDraft {
|
||||
return { purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: '1', budgetUnitPrice: '', currency: 'USD', receivingAddress: '', contactName: '', contactPhone: '', remark: '' }
|
||||
}
|
||||
export function draftBudgetTotal(draft: ProcurementDraft) {
|
||||
const price = cents(draft.budgetUnitPrice)
|
||||
if (price === null || price < 0n || !/^\d+$/.test(draft.purchaseQuantity)) return null
|
||||
return decimal(price * BigInt(draft.purchaseQuantity))
|
||||
}
|
||||
export function buildProcurementCreate(draft: ProcurementDraft, customerName: string, key: string): ProcurementCreate {
|
||||
for (const [field, label, max] of [
|
||||
['productName', '商品名称', 255], ['receivingAddress', '完整国内收货地址', 1000],
|
||||
['contactName', '最终收件人', 128], ['contactPhone', '联系电话', 64],
|
||||
] as const) {
|
||||
if (!draft[field].trim() || draft[field].trim().length > max) throw new Error(`请填写有效的${label}`)
|
||||
}
|
||||
if (draft.purchaseCategory.trim().length > 128) throw new Error('采购品类超过长度限制')
|
||||
if (!customerName.trim()) throw new Error('当前企业信息尚未加载,请刷新登录信息后重试')
|
||||
if (!/^\d+$/.test(draft.purchaseQuantity) || !Number.isSafeInteger(Number(draft.purchaseQuantity)) || Number(draft.purchaseQuantity) <= 0) throw new Error('采购数量必须为正整数')
|
||||
const price = cents(draft.budgetUnitPrice)
|
||||
if (price === null || price < 0n) throw new Error('请明确填写非负预算单价,最多两位小数;免费样品填写 0')
|
||||
if (price > BigInt(Number.MAX_SAFE_INTEGER) || cents(Number(decimal(price))) !== price) throw new Error('预算金额过大,无法准确表示,请核对金额')
|
||||
if (!['CNY', 'USD'].includes(draft.currency)) throw new Error('预算币种只支持 CNY 或 USD')
|
||||
if (!/^[+0-9][0-9 ()-]{5,63}$/.test(draft.contactPhone.trim())) throw new Error('请填写快递可联系的电话号码,微信或邮箱不能代替电话')
|
||||
if (draft.productUrl && (!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('商品规格或备注超过长度限制')
|
||||
return { customerName: customerName.trim(), purchaseCategory: draft.purchaseCategory.trim(), productName: draft.productName.trim(),
|
||||
productSpecification: draft.productSpecification.trim() || undefined, productUrl: draft.productUrl.trim() || undefined,
|
||||
purchaseQuantity: Number(draft.purchaseQuantity), budgetUnitPrice: Number(decimal(price)), currency: draft.currency,
|
||||
receivingAddress: draft.receivingAddress.trim(), contactName: draft.contactName.trim(), contactPhone: draft.contactPhone.trim(),
|
||||
remark: draft.remark.trim() || undefined, idempotencyKey: key }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export function procurementRequestKey(provider: Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>> = globalThis.crypto) {
|
||||
if (provider.randomUUID) return provider.randomUUID()
|
||||
return `proc-${Array.from(provider.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('')}`
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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', 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.equal(buildTransportDemand('truck', valid()).budgetAmount, undefined)
|
||||
assert.equal(buildTransportDemand('truck', { ...valid(), budgetAmount: 0 }).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)
|
||||
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,106 @@
|
||||
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 = {
|
||||
origin: '起运地', destination: '目的地', originContactName: '起运地联系人',
|
||||
originContactPhone: '起运地联系电话', destinationContactName: '目的地联系人', destinationContactPhone: '目的地联系电话',
|
||||
} 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> = {}
|
||||
for (const [field, label] of Object.entries(requiredText)) {
|
||||
rules[field as keyof typeof requiredText] = [{ 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 === 'estimatedPalletCount' && kind !== 'looseboard') continue
|
||||
rules[field] = [{ required: true, type: 'number', min: 0, message: `${label}须为不小于 0 的数字`, trigger: 'change' }]
|
||||
}
|
||||
rules.budgetAmount = [{ type: 'number', min: 0, message: '预算总价不能小于 0', trigger: 'change' }]
|
||||
rules.pickupAt = [{ required: true, message: '请选择取货时间', trigger: 'change' }]
|
||||
rules.deliveryAt = [{ required: true, message: '请选择送货时间', trigger: 'change' }, {
|
||||
validator: (_rule, value, callback) => callback(value && form.pickupAt && localMinuteInput(value) < localMinuteInput(form.pickupAt) ? new Error('送货时间不能早于取货时间') : 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 '请选择车辆类型'
|
||||
for (const [field, label] of Object.entries(requiredText)) {
|
||||
if (!String(form[field as keyof typeof requiredText] || '').trim()) return `请输入${label}`
|
||||
}
|
||||
for (const [field, label] of [['pickupAt', '取货时间'], ['deliveryAt', '送货时间']] 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 '送货时间不能早于取货时间'
|
||||
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 (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 = CommonPayload & { 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'
|
||||
? { ...common, vehicleType: form.vehicleType as 'PALLET_15' | 'PALLET_30' }
|
||||
: { ...common, productName: form.productName.trim() || undefined, estimatedPalletCount: form.estimatedPalletCount }
|
||||
}
|
||||
@@ -1,6 +1,161 @@
|
||||
<script setup lang="ts">
|
||||
import BusinessOrdersView from '../components/BusinessOrdersView.vue'
|
||||
defineProps<{ createPage?: boolean; detailPage?: boolean }>()
|
||||
import { computed, onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ApiError } from '@/api/types'
|
||||
import { accessTokenIdentity } from '@/api/session'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||
import type { TableAction } from '@/components/common/tableActions'
|
||||
import ProcurementDetailPanel from '../components/ProcurementDetailPanel.vue'
|
||||
import { createProcurement, getProcurement, listProcurements, type ProcurementDetail, type ProcurementSummary } from '../api/procurement'
|
||||
import { buildProcurementCreate, dateTime, draftBudgetTotal, emptyProcurementDraft, money, procurementStatuses, statusLabel, statusTone } from '../procurementPresentation'
|
||||
import { procurementRequestKey } from '../procurementSubmission'
|
||||
|
||||
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
|
||||
const auth = useAuthStore(), route = useRoute(), router = useRouter()
|
||||
const mode = computed(() => props.detailPage ? 'detail' : props.createPage ? 'create' : 'list')
|
||||
const orderNo = computed(() => typeof route.params.orderNo === 'string' ? route.params.orderNo : '')
|
||||
const canCreate = computed(() => auth.hasPermission('merchant:cross-border:procurement:create'))
|
||||
const canList = computed(() => auth.hasPermission('merchant:cross-border:procurement:list'))
|
||||
const identity = computed(() => auth.token ? accessTokenIdentity(auth.token) : null)
|
||||
const companyName = computed(() => auth.profile.tenantName || (auth.user?.tenantName && !/^企业租户 \d+$/.test(auth.user.tenantName) ? auth.user.tenantName : ''))
|
||||
const form = reactive(emptyProcurementDraft())
|
||||
const submitError = ref(''), submittedOrder = ref('')
|
||||
const submitting = ref(false), loading = ref(false), error = ref('')
|
||||
const detail = shallowRef<ProcurementDetail | null>(null)
|
||||
const rows = ref<ProcurementSummary[]>([]), total = ref(0)
|
||||
const query = reactive({ page: 1, size: 20, orderNo: '', purchaseCategory: '', productName: '', status: '' })
|
||||
let requestSequence = 0, active = true, inFlight = ''
|
||||
const queryModel = computed<QueryModel>({
|
||||
get: () => ({ orderNo: query.orderNo, purchaseCategory: query.purchaseCategory, productName: query.productName, status: query.status }),
|
||||
set: value => { for (const key of ['orderNo', 'purchaseCategory', 'productName', 'status'] as const) query[key] = String(value[key] || '') },
|
||||
})
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'orderNo', label: '采购单号', type: 'input' }, { key: 'purchaseCategory', label: '采购品类', type: 'input' },
|
||||
{ key: 'productName', label: '商品名称', type: 'input' },
|
||||
{ key: 'status', label: '履约进度', type: 'select', options: Object.entries(procurementStatuses).map(([value, label]) => ({ value, label })) },
|
||||
]
|
||||
const columns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', width: 90, fixed: 'left', slotName: 'actions' },
|
||||
{ prop: 'orderNo', label: '采购单号', minWidth: 250, slotName: 'orderNo' },
|
||||
{ prop: 'purchaseCategory', label: '采购品类', width: 120 }, { prop: 'productName', label: '商品名称', minWidth: 200 },
|
||||
{ prop: 'productSpecification', label: '商品规格', minWidth: 160 }, { prop: 'purchaseQuantity', label: '采购数量(件)', width: 135 },
|
||||
{ prop: 'budgetUnitPrice', label: '预算单价', width: 155, slotName: 'budget' },
|
||||
{ prop: 'status', label: '履约进度', width: 180, slotName: 'status' }, { prop: 'createdAt', label: '下单时间', width: 185, slotName: 'createdAt' },
|
||||
]
|
||||
function rowActions(row: object): TableAction[] { return [{ key: 'detail', label: '详情', run: () => openDetail(row as ProcurementSummary) }] }
|
||||
function openDetail(row: ProcurementSummary) { if (row.orderNo) void router.push({ name: 'cross-border-procurement-detail', params: { orderNo: row.orderNo } }) }
|
||||
function returnToList() { if (canList.value) void router.push({ name: 'cross-border-procurement' }) }
|
||||
function message(cause: unknown) {
|
||||
if (cause instanceof ApiError && ((cause.status || 0) >= 500 || cause.code.startsWith('B'))) return '服务暂不可用,请稍后重试'
|
||||
return cause instanceof Error ? cause.message : '请求失败,请稍后重试'
|
||||
}
|
||||
async function loadList() {
|
||||
const params = { page: query.page, size: query.size, orderNo: query.orderNo || undefined, productName: query.productName || undefined, purchaseCategory: query.purchaseCategory || undefined, status: query.status || undefined }
|
||||
const key = JSON.stringify([identity.value, params])
|
||||
if (inFlight === key) return
|
||||
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''
|
||||
try { const result = await listProcurements(params); if (sequence === requestSequence) { rows.value = result.records; total.value = result.total } }
|
||||
catch (cause) { if (sequence === requestSequence) { rows.value = []; total.value = 0; error.value = message(cause) } }
|
||||
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
|
||||
}
|
||||
async function loadDetail() {
|
||||
if (!orderNo.value) { error.value = '采购单号缺失'; return }
|
||||
const key = JSON.stringify([identity.value, orderNo.value])
|
||||
if (inFlight === key) return
|
||||
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''; detail.value = null
|
||||
try { const result = await getProcurement(orderNo.value); if (sequence === requestSequence) detail.value = result }
|
||||
catch (cause) { if (sequence === requestSequence) error.value = message(cause) }
|
||||
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
|
||||
}
|
||||
function search() { if (query.page === 1) void loadList(); else query.page = 1 }
|
||||
function resetQuery() { const reload = query.page === 1; Object.assign(query, { page: 1, orderNo: '', purchaseCategory: '', productName: '', status: '' }); if (reload) void loadList() }
|
||||
function resetForm() { submitError.value = ''; submittedOrder.value = ''; Object.assign(form, emptyProcurementDraft()) }
|
||||
async function submit() {
|
||||
if (submitting.value || !canCreate.value || !identity.value || submittedOrder.value) return
|
||||
const owner = identity.value; submitting.value = true; submitError.value = ''
|
||||
try {
|
||||
const result = await createProcurement(buildProcurementCreate(form, companyName.value, procurementRequestKey()))
|
||||
if (!active || owner !== identity.value) return
|
||||
submittedOrder.value = result.order.orderNo; ElMessage.success('采购订单已提交')
|
||||
if (canList.value) await router.push({ name: 'cross-border-procurement-detail', params: { orderNo: result.order.orderNo } })
|
||||
} catch (cause) { if (active && owner === identity.value) submitError.value = message(cause) }
|
||||
finally { submitting.value = false }
|
||||
}
|
||||
watch(() => [mode.value, orderNo.value, query.page, query.size, identity.value], (values, previous) => {
|
||||
if (values[4] !== previous?.[4]) { rows.value = []; total.value = 0 }
|
||||
++requestSequence; inFlight = ''; loading.value = false; error.value = ''; detail.value = null
|
||||
if (mode.value === 'create') resetForm()
|
||||
else if (mode.value === 'detail') void loadDetail()
|
||||
else void loadList()
|
||||
}, { immediate: true })
|
||||
onBeforeUnmount(() => { active = false; ++requestSequence })
|
||||
</script>
|
||||
|
||||
<template><BusinessOrdersView kind="procurement" :create-page="createPage" :detail-page="detailPage" /></template>
|
||||
<template>
|
||||
<section class="procurement-page client-ui" :aria-busy="loading || submitting">
|
||||
<template v-if="mode === 'list'">
|
||||
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="采购订单查询条件" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetQuery" />
|
||||
<div class="procurement-table-card">
|
||||
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="columns" :row-actions="rowActions" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" row-key="orderNo" empty-text="暂无采购订单">
|
||||
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="router.push({ name: 'cross-border-procurement-create' })">新增下单</el-button></template>
|
||||
<template v-if="error" #error><div class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadList">重新加载</el-button></div></template>
|
||||
<template #orderNo="{ row }"><button class="procurement-link" type="button" @click="openDetail(row as ProcurementSummary)">{{ (row as ProcurementSummary).orderNo || '—' }}</button></template>
|
||||
<template #budget="{ row }">{{ money((row as ProcurementSummary).budgetUnitPrice, (row as ProcurementSummary).currency) }}</template>
|
||||
<template #status="{ row }"><el-tag :type="statusTone((row as ProcurementSummary).status)" size="small">{{ statusLabel((row as ProcurementSummary).status) }}</el-tag></template>
|
||||
<template #createdAt="{ row }">{{ dateTime((row as ProcurementSummary).createdAt) }}</template>
|
||||
</DataTable>
|
||||
</div>
|
||||
</template>
|
||||
<section v-else-if="mode === 'detail'" v-loading="loading" class="procurement-detail" aria-label="采购订单详情">
|
||||
<header class="procurement-heading"><div><el-button link type="primary" @click="returnToList">← 返回列表</el-button><h2>{{ detail?.order.orderNo || '采购订单详情' }}</h2></div><div><el-tag v-if="detail" :type="statusTone(detail.order.status)">{{ statusLabel(detail.order.status) }}</el-tag><el-button :disabled="loading" @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>
|
||||
<ProcurementDetailPanel v-else-if="detail" :detail="detail" /><el-skeleton v-else :rows="8" animated />
|
||||
</section>
|
||||
<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>
|
||||
<el-result v-if="!canCreate" icon="warning" title="没有采购下单权限" sub-title="请联系企业管理员配置权限" />
|
||||
<el-result v-else-if="submittedOrder" icon="success" title="采购订单已提交" :sub-title="submittedOrder"><template #extra><el-button @click="resetForm">新建另一单</el-button></template></el-result>
|
||||
<template v-else>
|
||||
<el-alert v-if="submitError" class="submit-error" :title="submitError" type="error" :closable="false" />
|
||||
<el-form :model="form" label-position="top" :disabled="submitting" @submit.prevent="submit">
|
||||
<h3>商品与预算</h3><div class="procurement-form-grid">
|
||||
<el-form-item label="采购品类"><el-input v-model.trim="form.purchaseCategory" maxlength="128" placeholder="" /></el-form-item>
|
||||
<el-form-item label="商品名称" required><el-input v-model.trim="form.productName" maxlength="255" placeholder="" /></el-form-item>
|
||||
<el-form-item label="商品规格"><el-input v-model.trim="form.productSpecification" maxlength="500" placeholder="规格、型号" /></el-form-item>
|
||||
<el-form-item label="采购数量(件)" required><el-input v-model.trim="form.purchaseQuantity" inputmode="numeric" maxlength="18" placeholder="正整数" /></el-form-item>
|
||||
<el-form-item label="预算单价" required><el-input v-model.trim="form.budgetUnitPrice" inputmode="decimal" maxlength="20" placeholder="请明确填写;免费样品填 0" /></el-form-item>
|
||||
<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>
|
||||
<el-form-item class="full" label="商品链接"><el-input v-model.trim="form.productUrl" maxlength="2000" placeholder="https://…" /></el-form-item>
|
||||
</div><p class="procurement-hint">货款预算总上限:<strong>{{ money(draftBudgetTotal(form), form.currency) }}</strong>。零预算仅授权免费样品;实际货款按供应商实付核定。</p>
|
||||
<h3>最终国内收件资料</h3><div class="procurement-form-grid">
|
||||
<el-form-item label="收件人" required><el-input v-model.trim="form.contactName" maxlength="128" placeholder="实际收件人姓名" /></el-form-item>
|
||||
<el-form-item label="联系电话" required><el-input v-model.trim="form.contactPhone" maxlength="64" type="tel" placeholder="快递可联系的电话" /></el-form-item>
|
||||
<el-form-item class="full" label="完整国内地址" required><el-input v-model.trim="form.receivingAddress" maxlength="1000" placeholder="省、市、区县、街道及详细门牌" /></el-form-item>
|
||||
<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>
|
||||
</div>
|
||||
</el-form>
|
||||
<footer class="procurement-form-actions"><el-button type="primary" :loading="submitting" :disabled="!companyName || !identity" @click="submit">提交采购订单</el-button></footer>
|
||||
</template>
|
||||
</section>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.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 { overflow: hidden; }.procurement-detail, .procurement-create { padding: 16px 20px 24px; }
|
||||
.procurement-heading { display: flex; justify-content: space-between; align-items: center; gap: 20px; min-height: 54px; border-bottom: 1px solid var(--border); padding-bottom: 12px; }
|
||||
.procurement-heading > div { display: flex; align-items: center; gap: 14px; min-width: 0; }.procurement-heading h2 { margin: 0; color: var(--navy); font-size: 18px; overflow-wrap: anywhere; }
|
||||
.procurement-create .procurement-heading > div { display: block; }.procurement-heading p { margin: 7px 0 0; font-size: 13px; color: var(--muted); }
|
||||
.procurement-link { padding: 0; border: 0; background: transparent; color: var(--client-action); font: inherit; cursor: pointer; text-align: left; }.procurement-link:hover { text-decoration: underline; }
|
||||
.procurement-error { min-height: 160px; display: flex; justify-content: center; align-items: center; gap: 16px; color: #b42318; }.procurement-error span { max-width: 900px; overflow-wrap: anywhere; }
|
||||
.procurement-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-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-form-actions { display: flex; justify-content: flex-end; gap: 12px; padding-top: 16px; border-top: 1px solid var(--border); }.submit-error { margin: 12px 0; }
|
||||
@media (max-width: 767px) {
|
||||
.procurement-form-grid { grid-template-columns: 1fr; }.procurement-heading, .procurement-heading > div { flex-wrap: wrap; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -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`。
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { ArrowRight, Forklift, RefreshCcw, Ship, ShoppingCart, Tags, Truck } from '@lucide/vue'
|
||||
import { ArrowRight, Forklift, PackageOpen, RefreshCcw, Ship, ShoppingCart, Tags, Truck, Warehouse } from '@lucide/vue'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import { FirstLegOrdersView } from '@/modules/first-leg/public'
|
||||
|
||||
@@ -13,6 +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: 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: Warehouse, route: '/overseas-warehouse/storage-transfer/create', permission: 'merchant:overseas-warehouse:transfer:create', tone: 'teal', featured: false, actionLabel: '开始办理' },
|
||||
{ title: '货物废弃', description: '废弃申请 · 处理进度', icon: PackageOpen, route: '/overseas-warehouse/cargo-disposal/create', permission: 'merchant:overseas-warehouse:discard:create', tone: 'brown', featured: false, actionLabel: '开始办理' },
|
||||
].filter((action) => auth.hasPermission(action.permission)))
|
||||
|
||||
</script>
|
||||
@@ -21,14 +23,14 @@ const primaryActions = computed(() => [
|
||||
<div class="client-dashboard">
|
||||
<header class="business-intro">
|
||||
<h1>选择业务,快速下单</h1>
|
||||
<p>请选择您需要的业务类型,填写信息后提交订单,我们将尽快为您安排。</p>
|
||||
|
||||
</header>
|
||||
|
||||
<section class="quick-actions" aria-label="业务选择">
|
||||
<RouterLink v-for="(action, index) in primaryActions" :key="action.route" :to="action.route" class="quick-action" :class="[`quick-action--${action.tone}`, { 'quick-action--featured': action.featured }]" :style="{ '--entry-index': index }">
|
||||
<span class="action-icon"><component :is="action.icon" :size="25" :stroke-width="2.2" aria-hidden="true" /></span>
|
||||
<span class="action-copy"><strong>{{ action.title }}</strong><small>{{ action.description }}</small></span>
|
||||
<span class="action-enter"><span>开始下单</span><ArrowRight :size="15" aria-hidden="true" /></span>
|
||||
<span class="action-enter"><span>{{ action.actionLabel ?? '开始下单' }}</span><ArrowRight :size="15" aria-hidden="true" /></span>
|
||||
</RouterLink>
|
||||
<p v-if="!primaryActions.length" class="no-actions">当前账号暂无常用业务权限,请通过已授权菜单办理业务,或联系企业管理员。</p>
|
||||
</section>
|
||||
@@ -46,7 +48,7 @@ const primaryActions = computed(() => [
|
||||
.business-intro { padding-top: 0; }
|
||||
.business-intro h1 { margin: 0; color: #172033; font-size: 27px; font-weight: 750; letter-spacing: -.5px; line-height: 1.3; }
|
||||
.business-intro p { margin: 5px 0 0; color: #7a8495; font-size: 13px; line-height: 1.55; }
|
||||
.quick-actions { display: grid; grid-template-columns: repeat(6, minmax(188px, 1fr)); gap: 10px; overflow-x: auto; padding: 0 0 6px; scroll-snap-type: x proximity; scrollbar-color: #bdc9dc transparent; scrollbar-width: thin; }
|
||||
.quick-actions { display: grid; grid-template-columns: repeat(8, minmax(150px, 1fr)); gap: 10px; overflow-x: auto; padding: 0 0 6px; scroll-snap-type: x proximity; scrollbar-color: #bdc9dc transparent; scrollbar-width: thin; }
|
||||
.quick-actions::-webkit-scrollbar { height: 7px; }
|
||||
.quick-actions::-webkit-scrollbar-thumb { border-radius: 999px; background: #bdc9dc; }
|
||||
.quick-actions::-webkit-scrollbar-track { background: transparent; }
|
||||
@@ -60,6 +62,8 @@ const primaryActions = computed(() => [
|
||||
.quick-action--cyan { --action-a: #0891b2; --action-b: #0e7490; --action-soft: rgba(8, 145, 178, .18); }
|
||||
.quick-action--orange { --action-a: #f59e0b; --action-b: #dc6b12; --action-soft: rgba(245, 158, 11, .2); }
|
||||
.quick-action--rose { --action-a: #e11d48; --action-b: #be185d; --action-soft: rgba(225, 29, 72, .17); }
|
||||
.quick-action--teal { --action-a: #0f766e; --action-b: #0e7490; --action-soft: rgba(15, 118, 110, .18); }
|
||||
.quick-action--brown { --action-a: #b45309; --action-b: #c2410c; --action-soft: rgba(180, 83, 9, .18); }
|
||||
.quick-action:hover { border-color: color-mix(in srgb, var(--action-a) 35%, transparent); box-shadow: 0 24px 54px rgba(15, 23, 42, .14), 0 0 0 1px color-mix(in srgb, var(--action-a) 16%, transparent); transform: translateY(-9px); }
|
||||
.quick-action:hover::before { transform: scale(1.25); }
|
||||
.quick-action:hover::after { right: 12%; left: 12%; opacity: 1; transform: scaleX(1); }
|
||||
@@ -93,8 +97,8 @@ const primaryActions = computed(() => [
|
||||
@keyframes action-enter { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: translateY(0); } }
|
||||
@keyframes featured-aura { 0%, 100% { opacity: .86; transform: translate3d(0, 0, 0) scale(1); } 50% { opacity: 1; transform: translate3d(-10px, 9px, 0) scale(1.08); } }
|
||||
@keyframes featured-shine { 0%, 55% { left: -55%; opacity: 0; } 65% { opacity: 1; } 88%, 100% { left: 125%; opacity: 0; } }
|
||||
@container dashboard-content (max-width: 1180px) { .quick-actions { grid-template-columns: repeat(6, minmax(178px, 1fr)); } }
|
||||
@container dashboard-content (max-width: 1180px) { .quick-actions { grid-template-columns: repeat(8, minmax(178px, 1fr)); } }
|
||||
@media (max-width: 720px) { .client-dashboard { padding: 0; gap: 16px; } .business-intro h1 { font-size: 25px; } .quick-actions { grid-template-columns: repeat(2, minmax(150px, 1fr)); } }
|
||||
@media (max-width: 420px) { .quick-actions { grid-template-columns: repeat(6, minmax(168px, 1fr)); } }
|
||||
@media (max-width: 420px) { .quick-actions { grid-template-columns: repeat(8, minmax(168px, 1fr)); } }
|
||||
@media (prefers-reduced-motion: reduce) { .client-dashboard, .quick-action, .quick-action--featured::before, .quick-action--featured .action-enter::before { animation: none; } .quick-action, .quick-action::before, .quick-action::after, .action-icon, .action-enter svg { transition: none; } }
|
||||
</style>
|
||||
|
||||
@@ -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`。
|
||||
@@ -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`。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 头程下单交货方式调整
|
||||
|
||||
依据:当前对话 2026-10-19 用户确认“卡车自送排第一,我司提货排第二,快递自提排第三;快递自提增加非必填快递单号”。该确认优先于历史原型对应字段。
|
||||
|
||||
2026-10-20 补充确认:新建、重置头程订单默认选择“卡车自送”;快速下单生成的草稿同步使用该默认值,编辑已有草稿保留原取货方式。
|
||||
|
||||
| 页面 | 操作 | 承载方式 | 布局 | 当前实现 | 结论 |
|
||||
|---|---|---|---|---|---|
|
||||
| 头程下单 | 新增 | 现有独立页面 | 保持现有国内交货区布局 | 快递自送、我司提货、卡车自送;无快递单号输入 | 按确认顺序排列;第三项改为快递自提,下方条件显示选填快递单号 |
|
||||
| 头程订单 | 编辑草稿 | 现有居中弹框 | 复用新增表单 | 无快递单号输入 | 同步新增规则,回显已保存单号 |
|
||||
| 头程订单 | 详情 | 现有独立页面 | 保持现有信息区 | 已有快递单号只读展示 | 复用当前展示;说明客户可在快递自提草稿填写单号 |
|
||||
|
||||
自动检查与人工视觉验收分别记录;1920×1080、100% 缩放的页面效果待人工截图确认。
|
||||
@@ -22,7 +22,7 @@ test('sends multi-inbound scope, optimistic versions and idempotency for every w
|
||||
assert.match(source, /params\.append\('inboundIds', id\)/)
|
||||
assert.match(source, /expectedVersion: document\.source\.version/)
|
||||
assert.match(source, /params: \{ expectedVersion: document\.source\.version \}/)
|
||||
assert.equal(source.match(/'Idempotency-Key'/g)?.length, 4)
|
||||
assert.equal(source.match(/'Idempotency-Key'/g)?.length, 6)
|
||||
assert.match(source, /data\.append\('file', file\)/)
|
||||
assert.match(source, /file\.size > MAX_CUSTOMS_FILE_SIZE/)
|
||||
})
|
||||
|
||||
@@ -14,6 +14,24 @@ export interface MerchantCustomsFile {
|
||||
uploadedAt: string
|
||||
}
|
||||
|
||||
export interface MerchantCustomsReceiptVersion {
|
||||
version: number
|
||||
file: MerchantCustomsFile
|
||||
operatorName: string | null
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export type MerchantCustomsConfirmationAction = 'CONFIRM' | 'REJECT'
|
||||
|
||||
export interface MerchantCustomsConfirmationHistory {
|
||||
id: string
|
||||
receiptVersion: number
|
||||
action: MerchantCustomsConfirmationAction
|
||||
reason: string | null
|
||||
operatorName: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface MerchantCustomsInbound {
|
||||
inboundId: string
|
||||
orderId: string
|
||||
@@ -32,7 +50,12 @@ export interface MerchantCustomsDocument {
|
||||
inboundIds: string[]
|
||||
inboundCodes: string[]
|
||||
frozen: boolean
|
||||
completion: MerchantCustomsFile | null
|
||||
receipt: MerchantCustomsFile | null
|
||||
receiptStatus: 'PENDING' | 'CONFIRMED' | 'REJECTED' | null
|
||||
receiptRejectReason: string | null
|
||||
finalDocument: MerchantCustomsFile | null
|
||||
receiptHistory?: MerchantCustomsReceiptVersion[]
|
||||
confirmationHistory: MerchantCustomsConfirmationHistory[]
|
||||
}
|
||||
|
||||
export interface MerchantCustomsContainer {
|
||||
@@ -47,12 +70,32 @@ export interface MerchantCustomsContainer {
|
||||
version: number
|
||||
taxRefundCount: number
|
||||
coveredTaxRefundCount: number
|
||||
actualBoxCount: number
|
||||
inbounds: MerchantCustomsInbound[]
|
||||
documents: MerchantCustomsDocument[]
|
||||
startedAt?: string | null
|
||||
brokerSubmittedAt?: string | null
|
||||
completedAt?: string | null
|
||||
}
|
||||
|
||||
export type MerchantClearanceResultType = 'INSPECTION' | 'SUPPLEMENT_REQUIRED' | 'RELEASED' | 'DETAINED' | 'OTHER'
|
||||
export type MerchantClearanceResultStatus = 'OPEN' | 'RESOLVED' | 'CANCELLED'
|
||||
|
||||
export interface MerchantClearanceResult {
|
||||
id: string
|
||||
declarationBatchId: string
|
||||
customsContainerId: string
|
||||
resultType: MerchantClearanceResultType
|
||||
resultStatus: MerchantClearanceResultStatus
|
||||
customsEntryNo: string | null
|
||||
occurredAt: string
|
||||
resolution: string | null
|
||||
evidenceFileId: string | null
|
||||
recordedByName: string
|
||||
recordedAt: string
|
||||
previousResultId: string | null
|
||||
}
|
||||
|
||||
export interface ApiErrorMeta {
|
||||
code: string
|
||||
requestId: string | null
|
||||
@@ -100,6 +143,13 @@ export function getMerchantCustomsForOrder(orderId: string) {
|
||||
})
|
||||
}
|
||||
|
||||
export function getMerchantClearanceResults(orderId: string) {
|
||||
return apiRequest<MerchantClearanceResult[]>({
|
||||
method: 'GET',
|
||||
url: `/merchant/v1/customs/orders/${encodedId(orderId)}/clearance-results`,
|
||||
})
|
||||
}
|
||||
|
||||
export function uploadMerchantCustomsDocument(planId: string, inboundIds: string[], file: File) {
|
||||
validateMerchantCustomsFile(file)
|
||||
return apiRequest<MerchantCustomsDocument>({
|
||||
@@ -183,13 +233,38 @@ export function downloadMerchantCustomsSource(document: MerchantCustomsDocument)
|
||||
return download(`/merchant/v1/customs/documents/${encodedId(document.documentId)}/download`, document.source.fileName)
|
||||
}
|
||||
|
||||
export function downloadMerchantCustomsCompletion(document: MerchantCustomsDocument) {
|
||||
export function downloadMerchantCustomsReceipt(document: MerchantCustomsDocument) {
|
||||
return download(
|
||||
`/merchant/v1/customs/documents/${encodedId(document.documentId)}/completion/download`,
|
||||
document.completion?.fileName || `customs-completion-${document.documentId}`,
|
||||
`/merchant/v1/customs/documents/${encodedId(document.documentId)}/receipt/download`,
|
||||
document.receipt?.fileName || `customs-receipt-${document.documentId}`,
|
||||
)
|
||||
}
|
||||
|
||||
export function downloadMerchantCustomsFinal(document: MerchantCustomsDocument) {
|
||||
return download(
|
||||
`/merchant/v1/customs/documents/${encodedId(document.documentId)}/final/download`,
|
||||
document.finalDocument?.fileName || `customs-final-${document.documentId}`,
|
||||
)
|
||||
}
|
||||
|
||||
export function confirmMerchantCustomsReceipt(document: MerchantCustomsDocument) {
|
||||
return apiRequest<MerchantCustomsContainer>({
|
||||
method: 'POST',
|
||||
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}/receipt/confirm`,
|
||||
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-receipt-confirm-${document.documentId}`) },
|
||||
data: { expectedVersion: document.receipt?.version ?? 0, confirm: true, remark: null },
|
||||
})
|
||||
}
|
||||
|
||||
export function rejectMerchantCustomsReceipt(document: MerchantCustomsDocument, reason: string) {
|
||||
return apiRequest<MerchantCustomsContainer>({
|
||||
method: 'POST',
|
||||
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}/receipt/reject`,
|
||||
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-receipt-reject-${document.documentId}`) },
|
||||
data: { expectedVersion: document.receipt?.version ?? 0, confirm: false, remark: reason },
|
||||
})
|
||||
}
|
||||
|
||||
export function merchantCustomsErrorMeta(error: unknown): ApiErrorMeta | null {
|
||||
if (!(error instanceof ApiError)) return null
|
||||
return { code: error.code, requestId: error.requestId ?? null, traceId: error.traceId ?? null }
|
||||
@@ -208,3 +283,11 @@ export function merchantCustomsErrorMessage(error: unknown, fallback: string) {
|
||||
export function isMerchantCustomsUnavailable(error: unknown) {
|
||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
||||
}
|
||||
|
||||
|
||||
export async function getMerchantCustomsPendingCount() {
|
||||
const result = await apiRequest<{ pendingCount: string | number }>({ method: 'GET', url: '/merchant/v1/customs/pending-summary' })
|
||||
const count = Number(result.pendingCount)
|
||||
if (result.pendingCount == null || result.pendingCount === '' || !Number.isSafeInteger(count) || count < 0) throw new Error('报关待办数量返回不完整')
|
||||
return count
|
||||
}
|
||||
|
||||
@@ -139,6 +139,7 @@ export interface FirstLegOrderSaveRequest {
|
||||
privateDestinationAddressId?: number | string
|
||||
cargoes: FirstLegOrderCargoPayload[]
|
||||
pickupMethod: ApiPickupMethod
|
||||
expressTrackingNo?: string
|
||||
receivingWarehouseId: number | string
|
||||
receivingWarehouseName: string
|
||||
receivingWarehouseAddress?: string | null
|
||||
@@ -441,6 +442,7 @@ export interface MerchantPriceEstimateRequest {
|
||||
destinationWarehouseId?: number | string
|
||||
destinationName?: string
|
||||
pricingTaxMode: ApiPricingTaxMode
|
||||
chargeMode?: 'KG' | 'CBM'
|
||||
actualWeightKg: number
|
||||
actualVolumeCbm: number
|
||||
}
|
||||
@@ -565,14 +567,19 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
|
||||
})
|
||||
}
|
||||
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload })
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) {
|
||||
export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number }, idempotencyKey: string) {
|
||||
return apiRequest<void>({
|
||||
method: 'POST',
|
||||
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
||||
data: payload,
|
||||
headers: { 'Idempotency-Key': idempotencyKey },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('forwards optional tax mode and pagination through the current GET endpoint', async () => {
|
||||
const calls = []
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||
const api = {}
|
||||
new Function('require', 'exports', code)(id => {
|
||||
assert.equal(id, '@/api/http')
|
||||
return { apiRequest: async config => { calls.push(config); return { records: [] } } }
|
||||
}, api)
|
||||
await api.getMerchantUnifiedOrders({ page: 2, size: 200, taxMode: 'TAX_REFUND' })
|
||||
await api.getMerchantUnifiedOrders({ taxMode: 'BUY_DECLARATION' })
|
||||
await api.getMerchantUnifiedOrders()
|
||||
assert.deepEqual(calls, [
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 2, size: 200, taxMode: 'TAX_REFUND' } },
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200, taxMode: 'BUY_DECLARATION' } },
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200 } },
|
||||
])
|
||||
})
|
||||
|
||||
test('keeps the merchant unified-order boundary and one-click palletization status', () => {
|
||||
assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
|
||||
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiError, apiRequest } from '@/api/http'
|
||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||
import { apiRequest } from '@/api/http'
|
||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||
|
||||
export type ApiUnifiedOrderMainStatus =
|
||||
| 'PENDING_REVIEW'
|
||||
@@ -48,17 +48,24 @@ export interface MerchantUnifiedTransportSummary {
|
||||
cabinetNo: string | null
|
||||
vesselName: string | null
|
||||
voyageNo: string | null
|
||||
sailingAt: string | null
|
||||
portArrivalAt: string | null
|
||||
estimatedSailingAt: string | null
|
||||
actualSailingAt: string | null
|
||||
effectiveSailingAt: string | null
|
||||
effectiveSailingAtEstimated: boolean | null
|
||||
estimatedPortArrivalAt: string | null
|
||||
actualPortArrivalAt: string | null
|
||||
effectivePortArrivalAt: string | null
|
||||
effectivePortArrivalAtEstimated: boolean | null
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderRow {
|
||||
orderId: number | string
|
||||
orderVersion: number
|
||||
tenantId: number | string
|
||||
orderNo: string | null
|
||||
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||
lxCode?: string | null
|
||||
mainStatus: ApiUnifiedOrderMainStatus
|
||||
mainStatus: ApiUnifiedOrderMainStatus | 'DRAFT' | 'CANCELLED'
|
||||
nextAction: string | null
|
||||
customerFeeConfirmationRequired: boolean
|
||||
internalOrderStatus: ApiFirstLegStatus | null
|
||||
@@ -77,6 +84,8 @@ export interface MerchantUnifiedOrderRow {
|
||||
actualGrossWeightKg: number | null
|
||||
actualVolumeCbm: number | null
|
||||
pickupMethod: ApiPickupMethod | null
|
||||
taxMode: ApiTaxMode | null
|
||||
customsInspection: boolean | null
|
||||
requestedPickupAt: string | null
|
||||
containerMode: ApiContainerMode | null
|
||||
destinationType: ApiDestinationType | null
|
||||
@@ -124,7 +133,26 @@ export interface MerchantUnifiedCustomNode {
|
||||
attachmentIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface MerchantTransportNode {
|
||||
standardNode: string
|
||||
nodeSequence: number
|
||||
providerCode: string | null
|
||||
estimatedAt: string | null
|
||||
actualAt: string | null
|
||||
locationCode: string | null
|
||||
locationName: string | null
|
||||
}
|
||||
|
||||
export interface MerchantTransportFragment {
|
||||
inboundCode: string | null
|
||||
cabinetNo: string | null
|
||||
containerNo: string | null
|
||||
nodes: MerchantTransportNode[]
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderDetail {
|
||||
progress: MerchantOrderProgress
|
||||
transportFragments: MerchantTransportFragment[]
|
||||
summary: MerchantUnifiedOrderRow
|
||||
order: MerchantFirstLegOrderDetail
|
||||
timeline: MerchantUnifiedTimelineEvent[]
|
||||
@@ -133,6 +161,8 @@ export interface MerchantUnifiedOrderDetail {
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderQuery {
|
||||
taxMode?: ApiTaxMode
|
||||
loaded?: boolean
|
||||
keyword?: string
|
||||
fbaCode?: string
|
||||
orderNo?: string
|
||||
@@ -148,6 +178,37 @@ export interface MerchantUnifiedOrderQuery {
|
||||
|
||||
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
||||
|
||||
export type OrderQueue = 'all' | 'fee' | 'customs' | 'draft' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
|
||||
export type OrderProgressStage = 'none' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
|
||||
export interface MerchantOrderProgress { orderId: string | number; stage: OrderProgressStage; partial: boolean }
|
||||
export type OrderQueueCounts = Record<OrderQueue, number>
|
||||
|
||||
export interface MerchantOrderWorkbenchQuery {
|
||||
cargoKeyword?: string
|
||||
receivingWarehouseId?: string
|
||||
channelName?: string
|
||||
destinationType?: string
|
||||
trackingNumber?: string
|
||||
mainStatus?: string
|
||||
createdFrom?: string
|
||||
createdTo?: string
|
||||
queue?: OrderQueue
|
||||
page?: number
|
||||
size?: number
|
||||
}
|
||||
|
||||
export interface MerchantOrderWorkbench {
|
||||
page: PageResult<MerchantUnifiedOrderRow>
|
||||
queues: OrderQueueCounts
|
||||
progress: MerchantOrderProgress[]
|
||||
channelNames: string[]
|
||||
}
|
||||
|
||||
export function getMerchantOrderWorkbench(params: MerchantOrderWorkbenchQuery = {}) {
|
||||
return apiRequest<MerchantOrderWorkbench>({ method: 'GET', url: `${unifiedOrderBaseUrl}/workbench`,
|
||||
params: { ...params, page: params.page ?? 1, size: params.size ?? 10 } })
|
||||
}
|
||||
|
||||
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
||||
const { page, size, ...filters } = params
|
||||
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
||||
@@ -163,7 +224,3 @@ export function getMerchantUnifiedOrder(orderId: number | string) {
|
||||
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
||||
})
|
||||
}
|
||||
|
||||
export function isUnifiedOrderQueryUnavailable(error: unknown) {
|
||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
function harness(t) {
|
||||
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const code = ts.transpileModule(source + '\nexport { loadDetail, detail, clearanceResults, loading, errorMessage, selectedInboundIds, clearanceError, clearanceLoading, retryClearanceResults, close }', { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const props = vue.reactive({ modelValue: false, orderId: 'A', canEdit: true }), requests = [], clearances = [], updates = [], view = {}
|
||||
const unmounts = []
|
||||
const dependencies = { '../store/customsPending': { useCustomsPendingStore: () => ({ refresh: async () => {} }) }, vue: { ...vue, onBeforeUnmount: fn => unmounts.push(fn) }, 'element-plus': { ElMessage: {} }, '@/modules/first-leg/api/customs': {
|
||||
getMerchantCustomsForOrder: id => { const pending = deferred(); requests.push({ id, ...pending }); return pending.promise },
|
||||
getMerchantClearanceResults: id => { const pending = deferred(); clearances.push({ id, ...pending }); return pending.promise },
|
||||
merchantCustomsErrorMessage: error => error.message,
|
||||
} }
|
||||
const scope = vue.effectScope()
|
||||
scope.run(() => new Function('require', 'exports', 'defineProps', 'defineEmits', code)(id => {
|
||||
assert.ok(id in dependencies, id); return dependencies[id]
|
||||
}, view, () => props, () => (...args) => updates.push(args)))
|
||||
t.after(() => scope.stop())
|
||||
return { props, requests, clearances, updates, view, unmount: () => unmounts.forEach(fn => fn()) }
|
||||
}
|
||||
const detail = id => ({ loadingPlanId: id, inbounds: [{ orderId: id, inboundId: `IN-${id}`, taxMode: 'TAX_REFUND' }] })
|
||||
const tick = async () => { await Promise.resolve(); await vue.nextTick(); await Promise.resolve() }
|
||||
|
||||
test('result section stays pending while the refreshed detail is still loading', async t => {
|
||||
const h = harness(t)
|
||||
h.props.initialDetail = detail('A')
|
||||
h.props.modelValue = true
|
||||
await tick()
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'A')
|
||||
assert.equal(h.view.loading.value, true)
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
assert.equal(h.clearances.length, 0)
|
||||
const template = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||
assert.match(template, /v-else-if="loading \|\| clearanceLoading"/)
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.clearanceLoading.value, true)
|
||||
h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.view.loading.value, false)
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||
})
|
||||
|
||||
test('switching orders while open starts the new request and ignores stale detail', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.orderId = 'B'; await tick()
|
||||
assert.deepEqual(h.requests.map(r => r.id), ['A', 'B'])
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||
assert.deepEqual(h.view.selectedInboundIds.value, ['IN-B'])
|
||||
assert.deepEqual(h.clearances.map(r => r.id), ['B'])
|
||||
assert.equal(h.updates.length, 1)
|
||||
})
|
||||
|
||||
test('closing before detail response prevents stale data and events', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.modelValue = false; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.detail.value, null); assert.equal(h.view.loading.value, false)
|
||||
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0)
|
||||
})
|
||||
|
||||
test('closing and reopening ignores the previous clearance response', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
h.props.modelValue = false; await tick(); h.props.orderId = 'B'; h.props.modelValue = true; await tick()
|
||||
h.requests[1].resolve(detail('B')); await tick()
|
||||
h.clearances[1].resolve([{ kind: 'B' }]); await tick()
|
||||
h.clearances[0].resolve([{ kind: 'A' }]); await tick()
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ kind: 'B' }])
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'B'); assert.equal(h.updates.length, 1)
|
||||
})
|
||||
|
||||
test('stale detail failure cannot clear the next request loading or show an error', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.orderId = 'B'; await tick(); h.requests[0].reject(new Error('old failure')); await tick()
|
||||
assert.equal(h.view.loading.value, true); assert.equal(h.view.errorMessage.value, '')
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.view.loading.value, false); assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||
})
|
||||
|
||||
test('unmount invalidates pending detail requests', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick(); h.unmount()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0); assert.equal(h.view.detail.value, null)
|
||||
})
|
||||
|
||||
test('result failure retains documents and exposes error; retry queries only results and deduplicates clicks', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve({ ...detail('A'), documents: [{ documentId: 'document-A' }] }); await tick()
|
||||
h.clearances[0].reject(new Error('结果服务暂不可用')); await tick()
|
||||
assert.equal(h.view.errorMessage.value, '')
|
||||
assert.equal(h.view.clearanceError.value, '结果服务暂不可用')
|
||||
assert.equal(h.view.detail.value.documents[0].documentId, 'document-A')
|
||||
assert.equal(h.view.loading.value, false)
|
||||
const retry = h.view.retryClearanceResults()
|
||||
await h.view.retryClearanceResults()
|
||||
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 2)
|
||||
assert.equal(h.view.clearanceLoading.value, true)
|
||||
h.clearances[1].resolve([{ id: 'result-A' }]); await retry
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'result-A' }])
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
})
|
||||
|
||||
test('normal open requests detail and results exactly once and distinguishes successful empty results', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 1)
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
})
|
||||
|
||||
for (const transition of ['switch', 'close', 'unmount']) {
|
||||
for (const outcome of ['resolve', 'reject']) {
|
||||
test(`${transition} ignores stale result retry ${outcome}`, async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].reject(new Error('first failure')); await tick()
|
||||
const retry = h.view.retryClearanceResults()
|
||||
if (transition === 'switch') { h.props.orderId = 'B'; await tick() }
|
||||
else if (transition === 'close') { h.view.close(); h.props.modelValue = false; await tick() }
|
||||
else h.unmount()
|
||||
if (outcome === 'resolve') h.clearances[1].resolve([{ id: 'old-A' }])
|
||||
else h.clearances[1].reject(new Error('old retry failure'))
|
||||
await retry
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||
if (transition === 'switch') {
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[2].resolve([{ id: 'B' }]); await tick()
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'B' }])
|
||||
} else {
|
||||
await h.view.retryClearanceResults()
|
||||
assert.equal(h.clearances.length, 2)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
test('result error and retry reuse existing section error styling before the empty state', () => {
|
||||
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||
assert.match(source, /v-if="clearanceError" class="customs-error" role="alert"/)
|
||||
assert.match(source, /@click="retryClearanceResults"/)
|
||||
assert.match(source, /v-else-if="loading \|\| clearanceLoading"/)
|
||||
assert.match(source, /v-else-if="!clearanceResults.length"/)
|
||||
})
|
||||
@@ -1,22 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue'
|
||||
import CustomsHelp from './CustomsHelp.vue'
|
||||
import {
|
||||
MERCHANT_CUSTOMS_STATUS_LABELS,
|
||||
deleteMerchantCustomsDocument,
|
||||
downloadMerchantCustomsCompletion,
|
||||
confirmMerchantCustomsReceipt,
|
||||
downloadMerchantCustomsReceipt,
|
||||
downloadMerchantCustomsFinal,
|
||||
downloadMerchantCustomsSource,
|
||||
getMerchantCustomsForOrder,
|
||||
getMerchantClearanceResults,
|
||||
merchantCustomsErrorMessage,
|
||||
replaceMerchantCustomsDocument,
|
||||
rejectMerchantCustomsReceipt,
|
||||
updateMerchantCustomsDocumentInbounds,
|
||||
uploadMerchantCustomsDocument,
|
||||
validateMerchantCustomsFile,
|
||||
type MerchantCustomsContainer,
|
||||
type MerchantCustomsDocument,
|
||||
type MerchantClearanceResult,
|
||||
} from '@/modules/first-leg/api/customs'
|
||||
|
||||
import { useCustomsPendingStore } from '../store/customsPending'
|
||||
|
||||
const customsPending = useCustomsPendingStore()
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
orderId: string
|
||||
@@ -40,6 +49,13 @@ const uploadInput = ref<HTMLInputElement>()
|
||||
const replaceInput = ref<HTMLInputElement>()
|
||||
const mutating = ref(false)
|
||||
const downloadingKey = ref('')
|
||||
const clearanceResults = ref<MerchantClearanceResult[]>([])
|
||||
const clearanceError = ref('')
|
||||
const clearanceLoading = ref(false)
|
||||
let clearanceRequest = 0
|
||||
let disposed = false
|
||||
let detailRequest = 0
|
||||
onBeforeUnmount(() => { disposed = true; detailRequest += 1; resetClearanceResults() })
|
||||
|
||||
const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? [])
|
||||
const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED')
|
||||
@@ -60,31 +76,81 @@ function initializeSelection(value: MerchantCustomsContainer) {
|
||||
selectedInboundIds.value = currentOrderIds
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
if (!props.orderId) return
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
function resetClearanceResults() {
|
||||
clearanceRequest += 1
|
||||
clearanceResults.value = []
|
||||
clearanceError.value = ''
|
||||
clearanceLoading.value = false
|
||||
}
|
||||
|
||||
async function loadClearanceResults() {
|
||||
if (disposed || !props.modelValue || !props.orderId || !detail.value || clearanceLoading.value) return
|
||||
const request = ++clearanceRequest
|
||||
const parentRequest = detailRequest
|
||||
const orderId = props.orderId
|
||||
const isCurrent = () => !disposed && request === clearanceRequest && parentRequest === detailRequest && props.modelValue && props.orderId === orderId
|
||||
clearanceLoading.value = true
|
||||
clearanceError.value = ''
|
||||
try {
|
||||
const result = await getMerchantCustomsForOrder(props.orderId)
|
||||
detail.value = result
|
||||
initializeSelection(result)
|
||||
emit('updated', result)
|
||||
const results = await getMerchantClearanceResults(orderId)
|
||||
if (isCurrent()) clearanceResults.value = results
|
||||
} catch (error) {
|
||||
detail.value = null
|
||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||
if (isCurrent()) clearanceError.value = merchantCustomsErrorMessage(error, '海关申报结果加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (isCurrent()) clearanceLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (open) => {
|
||||
async function retryClearanceResults() {
|
||||
if (loading.value) return
|
||||
await loadClearanceResults()
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
if (disposed || !props.modelValue || !props.orderId) return
|
||||
void customsPending.refresh(true)
|
||||
const request = ++detailRequest
|
||||
resetClearanceResults()
|
||||
const orderId = props.orderId
|
||||
const isCurrent = () => request === detailRequest && props.modelValue && props.orderId === orderId
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const result = await getMerchantCustomsForOrder(orderId)
|
||||
if (!isCurrent()) return
|
||||
detail.value = result
|
||||
initializeSelection(result)
|
||||
await loadClearanceResults()
|
||||
if (!isCurrent()) return
|
||||
emit('updated', result)
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
detail.value = null
|
||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||
} finally {
|
||||
if (isCurrent()) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.modelValue, props.orderId] as const, ([open]) => {
|
||||
detailRequest += 1
|
||||
detail.value = null
|
||||
resetClearanceResults()
|
||||
selectedInboundIds.value = []
|
||||
editingDocument.value = null
|
||||
replacingDocument.value = null
|
||||
errorMessage.value = ''
|
||||
loading.value = false
|
||||
if (!open) return
|
||||
detail.value = props.initialDetail ?? null
|
||||
const initial = props.initialDetail
|
||||
detail.value = initial?.inbounds.some((item) => item.orderId === props.orderId) ? initial : null
|
||||
if (detail.value) initializeSelection(detail.value)
|
||||
void loadDetail()
|
||||
})
|
||||
}, { immediate: true })
|
||||
|
||||
function close() {
|
||||
detailRequest += 1
|
||||
resetClearanceResults()
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
@@ -192,13 +258,13 @@ function saveDownload(blob: Blob, fileName: string) {
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
async function downloadFile(document: MerchantCustomsDocument, kind: 'source' | 'completion') {
|
||||
async function downloadFile(document: MerchantCustomsDocument, kind: 'source' | 'receipt' | 'final') {
|
||||
const key = `${document.documentId}:${kind}`
|
||||
downloadingKey.value = key
|
||||
try {
|
||||
const result = kind === 'source'
|
||||
? await downloadMerchantCustomsSource(document)
|
||||
: await downloadMerchantCustomsCompletion(document)
|
||||
: kind === 'receipt' ? await downloadMerchantCustomsReceipt(document) : await downloadMerchantCustomsFinal(document)
|
||||
saveDownload(result.blob, result.fileName)
|
||||
} catch (error) {
|
||||
ElMessage.error(merchantCustomsErrorMessage(error, '文件下载失败'))
|
||||
@@ -207,23 +273,64 @@ async function downloadFile(document: MerchantCustomsDocument, kind: 'source' |
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmReceipt(document: MerchantCustomsDocument) {
|
||||
try {
|
||||
await ElMessageBox.confirm('确认已核对整份报关行回执吗?确认后平台会把确认结果发送给报关行执行。', '确认报关行回执', { type: 'warning' })
|
||||
mutating.value = true
|
||||
await confirmMerchantCustomsReceipt(document)
|
||||
ElMessage.success('回执确认成功')
|
||||
await loadDetail()
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(merchantCustomsErrorMessage(error, '回执确认失败'))
|
||||
} finally { mutating.value = false }
|
||||
}
|
||||
|
||||
async function rejectReceipt(document: MerchantCustomsDocument) {
|
||||
try {
|
||||
const reason = await ElMessageBox.prompt('请填写打回原因', '打回报关行回执', { inputValidator: (value) => value.trim() ? true : '请输入打回原因' })
|
||||
mutating.value = true
|
||||
await rejectMerchantCustomsReceipt(document, reason.value)
|
||||
ElMessage.success('回执已打回')
|
||||
await loadDetail()
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(merchantCustomsErrorMessage(error, '回执打回失败'))
|
||||
} finally { mutating.value = false }
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined) {
|
||||
if (!value) return '-'
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
|
||||
}
|
||||
|
||||
function receiptHistoryLabel(document: MerchantCustomsDocument) {
|
||||
return (document.receiptHistory || []).map((item) => `V${item.version}`).join('、') || '—'
|
||||
}
|
||||
function confirmationActionLabel(action: MerchantCustomsDocument['confirmationHistory'][number]['action']) {
|
||||
return action === 'CONFIRM' ? '确认' : '打回'
|
||||
}
|
||||
|
||||
function formatSize(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function clearanceResultLabel(value: MerchantClearanceResult) {
|
||||
return ({ INSPECTION: '查验', SUPPLEMENT_REQUIRED: '补充资料', RELEASED: '放行', DETAINED: '扣留', OTHER: '其他' } as Record<string, string>)[value.resultType] || value.resultType
|
||||
}
|
||||
|
||||
function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
||||
return value.resultStatus === 'RESOLVED' ? '已处理' : value.resultStatus === 'CANCELLED' ? '已取消' : '待处理'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
class="customs-documents-dialog"
|
||||
class="customs-documents-dialog client-ui"
|
||||
title="退税报关资料"
|
||||
width="920px"
|
||||
append-to-body
|
||||
@@ -246,17 +353,22 @@ function formatSize(bytes: number) {
|
||||
<span>资料覆盖</span>
|
||||
<strong>{{ detail.coveredTaxRefundCount }} / {{ detail.taxRefundCount }} 票</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>实际箱数</span>
|
||||
<strong>{{ detail.actualBoxCount }}</strong>
|
||||
</div>
|
||||
<el-tag :type="statusTagType" effect="light">{{ merchantStatusLabel }}</el-tag>
|
||||
</header>
|
||||
|
||||
<div v-if="locked" class="customs-locked" role="status">
|
||||
<LockKeyhole :size="18" />
|
||||
<div><strong>报关资料已锁定</strong><span>报关开始后仅可查看和下载,不提供退回或解锁。</span></div>
|
||||
<div v-if="detail.status === 'COMPLETED'"><strong>报关已完成</strong><span>真实报关完税文件已齐全,可查看和下载资料、回执及完税文件。</span></div>
|
||||
<div v-else><strong>{{ detail.brokerSubmittedAt ? '已发送报关行执行' : '报关资料已锁定' }}</strong><span>{{ detail.brokerSubmittedAt ? '平台已将客户确认后的回执发送给报关行,等待真实报关完税文件。' : '客户原始资料已冻结,仍可确认或打回待确认的报关行回执。' }}</span></div>
|
||||
</div>
|
||||
|
||||
<section class="customs-section">
|
||||
<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>
|
||||
</div>
|
||||
<el-checkbox-group v-model="selectedInboundIds" class="customs-inbound-options" :disabled="!canEdit || locked" aria-label="选择资料关联入仓码">
|
||||
@@ -269,9 +381,29 @@ function formatSize(bytes: number) {
|
||||
<input ref="replaceInput" class="customs-hidden-input" type="file" @change="handleReplacementFile">
|
||||
</section>
|
||||
|
||||
<section class="customs-section clearance-results-section">
|
||||
<div class="customs-section-title">
|
||||
<h3>海关申报结果</h3>
|
||||
</div>
|
||||
<div v-if="clearanceError" class="customs-error" role="alert">
|
||||
<strong>海关申报结果加载失败</strong>
|
||||
<span>{{ clearanceError }}</span>
|
||||
<el-button :loading="clearanceLoading" @click="retryClearanceResults">重新加载</el-button>
|
||||
</div>
|
||||
<el-skeleton v-else-if="loading || clearanceLoading" :rows="2" animated />
|
||||
<el-empty v-else-if="!clearanceResults.length" description="暂无海关结果" :image-size="48" />
|
||||
<div v-else class="clearance-result-list">
|
||||
<div v-for="item in clearanceResults" :key="item.id" class="clearance-result-row">
|
||||
<div><strong>{{ clearanceResultLabel(item) }}</strong><span>{{ formatDateTime(item.occurredAt) }} · 报关单号 {{ item.customsEntryNo || '—' }}</span></div>
|
||||
<el-tag size="small" :type="item.resultStatus === 'RESOLVED' ? 'success' : 'warning'">{{ clearanceResultStatusLabel(item) }}</el-tag>
|
||||
<p v-if="item.resolution">{{ item.resolution }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="customs-section">
|
||||
<div class="customs-section-title">
|
||||
<div><h3>资料版本历史</h3><p>每份当前资料展示服务端版本、关联票和上传时间;覆盖及删除操作由服务端保留不可变历史。</p></div>
|
||||
<h3>资料版本历史</h3>
|
||||
</div>
|
||||
<el-empty v-if="!detail.documents.length" description="尚未上传退税报关资料" :image-size="54" />
|
||||
<div v-else class="customs-document-list">
|
||||
@@ -281,12 +413,20 @@ function formatSize(bytes: number) {
|
||||
<div>
|
||||
<strong>{{ item.source.fileName }}</strong>
|
||||
<span>版本 V{{ item.source.version }} · {{ formatSize(item.source.sizeBytes) }} · {{ formatDateTime(item.source.uploadedAt) }}</span>
|
||||
<small v-if="item.receiptHistory?.length">报关行回执历史:{{ receiptHistoryLabel(item) }}</small>
|
||||
<small v-for="history in item.confirmationHistory" :key="history.id">{{ confirmationActionLabel(history.action) }} · {{ formatDateTime(history.createdAt) }} · {{ history.operatorName || '—' }}<span v-if="history.reason"> · {{ history.reason }}</span></small>
|
||||
<small>关联入仓码:{{ item.inboundCodes.join('、') || '—' }}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="customs-document-actions">
|
||||
<el-button link type="primary" :loading="downloadingKey === `${item.documentId}:source`" @click="downloadFile(item, 'source')"><Download :size="15" />源文件</el-button>
|
||||
<el-button v-if="detail.status === 'COMPLETED' && item.completion" link type="success" :loading="downloadingKey === `${item.documentId}:completion`" @click="downloadFile(item, 'completion')"><Download :size="15" />完成文件</el-button>
|
||||
<el-button v-if="item.receipt" link type="success" :loading="downloadingKey === `${item.documentId}:receipt`" @click="downloadFile(item, 'receipt')"><Download :size="15" />报关行回执</el-button>
|
||||
<el-button v-if="item.finalDocument" link type="success" :loading="downloadingKey === `${item.documentId}:final`" @click="downloadFile(item, 'final')"><Download :size="15" />报关完税文件</el-button>
|
||||
<template v-if="item.receipt && item.receiptStatus !== 'CONFIRMED' && detail.status === 'DECLARING'">
|
||||
<el-button link type="success" :disabled="mutating" @click="confirmReceipt(item)">确认整份回执</el-button>
|
||||
<el-button link type="danger" :disabled="mutating" @click="rejectReceipt(item)">打回回执</el-button>
|
||||
</template>
|
||||
<el-tag v-if="item.receipt" size="small" :type="item.receiptStatus === 'CONFIRMED' ? 'success' : item.receiptStatus === 'REJECTED' ? 'danger' : 'warning'">{{ item.receiptStatus === 'CONFIRMED' ? '已确认' : item.receiptStatus === 'REJECTED' ? `已打回:${item.receiptRejectReason || '待补充'}` : '待确认' }}</el-tag>
|
||||
<template v-if="canEdit && !locked && !item.frozen">
|
||||
<el-button link type="primary" :disabled="mutating" @click="beginEditInbounds(item)"><Pencil :size="15" />改关联</el-button>
|
||||
<el-button link type="primary" :disabled="mutating" @click="chooseReplacement(item)"><Upload :size="15" />覆盖</el-button>
|
||||
@@ -308,34 +448,49 @@ function formatSize(bytes: number) {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:global(.customs-documents-dialog.el-dialog) { display: flex; max-height: 70vh; flex-direction: column; overflow: hidden; padding: 0; border: 1px solid var(--client-border); border-radius: var(--client-radius); }
|
||||
:global(.customs-documents-dialog .el-dialog__header), :global(.customs-documents-dialog .el-dialog__footer) { flex: 0 0 auto; }
|
||||
:global(.customs-documents-dialog .el-dialog__header) { margin: 0; padding: 18px 48px 18px 20px; border-bottom: 1px solid var(--client-border); }
|
||||
:global(.customs-documents-dialog .el-dialog__title) { color: var(--client-text); font-size: 16px; font-weight: 600; line-height: 24px; }
|
||||
:global(.customs-documents-dialog .el-dialog__headerbtn) { top: 8px; right: 8px; }
|
||||
:global(.customs-documents-dialog .el-dialog__body) { min-height: 0; flex: 1 1 auto; overflow-y: auto; padding: 20px; color: var(--client-text); line-height: 1.6; overscroll-behavior: contain; }
|
||||
:global(.customs-documents-dialog .el-dialog__footer) { padding: 14px 20px; border-top: 1px solid var(--client-border); background: var(--client-header-bg); }
|
||||
.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-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 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-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 { color: var(--navy); font-size: 12px; }
|
||||
.customs-locked span { margin-top: 3px; font-size: 11px; }
|
||||
.customs-section { margin-top: 18px; }
|
||||
.customs-section-title { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 12px; }
|
||||
.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-row { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:6px 14px; padding:12px 14px; border:1px solid var(--border); background:#fbfcfe; }
|
||||
.clearance-result-row strong,.clearance-result-row span { display:block; }
|
||||
.clearance-result-row span { margin-top:4px; color:var(--muted); font-size:11px; }
|
||||
.clearance-result-row p { grid-column:1 / -1; margin:0; color:var(--navy); font-size:12px; }
|
||||
.customs-section-title { display: flex; align-items: center; justify-content: space-between; gap: 18px; margin-bottom: 14px; }
|
||||
.customs-section-title h3 { margin: 0; color: var(--navy); font-size: 14px; }
|
||||
.customs-section-title p { margin: 5px 0 0; color: var(--muted); font-size: 11px; line-height: 1.55; }
|
||||
.customs-inbound-options { display: flex; flex-wrap: wrap; gap: 8px 18px; padding: 13px 15px; border: 1px solid var(--border); }
|
||||
.customs-help-heading { display: flex; align-items: center; gap: 4px; }
|
||||
.customs-inbound-options { display: flex; flex-wrap: wrap; gap: 8px 18px; padding: 12px 14px; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: var(--client-header-bg); }
|
||||
.customs-inbound-options :deep(.el-checkbox) { margin-right: 0; }
|
||||
.customs-inbound-options :deep(.el-checkbox__label) { white-space: normal; overflow-wrap: anywhere; }
|
||||
.customs-inbound-code { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
|
||||
.customs-inbound-options small { margin-left: 7px; color: var(--muted); }
|
||||
.customs-hidden-input { display: none; }
|
||||
.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 > svg { flex: 0 0 20px; color: var(--primary); }
|
||||
.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 { 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-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 :deep(.el-checkbox) { margin-right: 16px; }
|
||||
</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>
|
||||
@@ -20,19 +20,18 @@ test('supports a standalone dialog and keeps the unpushed billing-weight state v
|
||||
assert.match(source, /watch\(\(\) => props\.autoOpen/)
|
||||
assert.match(source, /if \(autoOpen\) feeDialogOpen\.value = true/)
|
||||
assert.match(source, /v-else-if="props\.unavailable \|\| !props\.data"/)
|
||||
assert.match(source, /平台推送计费重后,可在这里核对并确认/)
|
||||
assert.match(source, /平台推送费用后,可在这里核对并确认/)
|
||||
assert.match(source, /@closed="emit\('closed'\)"/)
|
||||
})
|
||||
|
||||
test('shows the published merchant inbound, measurement details and customer confirmation entry', () => {
|
||||
for (const label of ['入仓码', '平台收货仓', '实际毛重', '实测体积', '托盘与库位', '换算与精度', '最终计费量', '对客单价', '基础费用', '附加费用', '费用合计', '平台备注']) {
|
||||
assert.match(source, new RegExp(label))
|
||||
for (const label of ['入仓码', '平台收货仓', '实际毛重', '实测体积', '托盘与库位', '换算与精度', '最终计费量', '单价', '基础费用', '附加费用', '费用合计', '平台备注']) {
|
||||
assert.ok(source.includes(label), `missing label: ${label}`)
|
||||
}
|
||||
assert.match(source, /formatInboundMoney\(props\.data\.latestFee\.totalAmount/)
|
||||
assert.match(source, /formatConversionPrecision\(/)
|
||||
assert.match(source, /确认费用/)
|
||||
assert.match(source, /二次确认费用/)
|
||||
assert.match(source, /确认后该费用将锁定,平台不能再修改/)
|
||||
assert.match(source, /title="确认计费重"/)
|
||||
assert.match(source, /确认后当前费用版本将锁定/)
|
||||
assert.match(source, /customerConfirmationStatus === 'CONFIRMED'/)
|
||||
assert.match(source, /confirmMerchantInboundFee/)
|
||||
assert.match(source, /measurementItems/)
|
||||
@@ -46,6 +45,17 @@ test('shows the published merchant inbound, measurement details and customer con
|
||||
assert.match(source, /getCalculationRuleLabel\(row\.calculationRuleVersion\)/)
|
||||
})
|
||||
|
||||
test('matches the confirmed billing prototype summary, table, notice and footer', () => {
|
||||
assert.match(source, /width="min\(1180px, calc\(100vw - 40px\)\)"/)
|
||||
assert.match(source, /class="fee-dialog-summary" aria-label="计费汇总"/)
|
||||
for (const label of ['计算重', '单价', '总金额', '箱规长(cm)', '箱规宽(cm)', '箱规高(cm)', '每箱体积', '总体积', '总材积重']) assert.ok(source.includes(label), `missing prototype label: ${label}`)
|
||||
assert.match(source, /class="fee-confirm-notice"/)
|
||||
assert.match(source, /请核对计算重、单价和总金额。确认后当前费用版本将锁定。/)
|
||||
assert.match(source, /确认计费量和费用/)
|
||||
assert.match(source, /\.fee-dialog-summary \{ display:grid; grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/)
|
||||
assert.match(source, /\.fee-dialog-table :deep\(\.el-table__body td\.el-table__cell\)/)
|
||||
})
|
||||
|
||||
test('stacks core information for 720 and 360 pixel layouts', () => {
|
||||
assert.match(source, /@media \(max-width: 720px\)/)
|
||||
assert.match(source, /\.inbound-overview, \.inbound-measurements, \.fee-calculation-grid \{ grid-template-columns: 1fr;/)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Clock3, PackageCheck, RefreshCw, TriangleAlert } from '@lucide/vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { CircleAlert, Clock3, PackageCheck, RefreshCw, TriangleAlert } from '@lucide/vue'
|
||||
import { confirmMerchantInboundFee } from '@/modules/first-leg/api/inboundBilling'
|
||||
import type { MerchantInboundBilling } from '@/modules/first-leg/types/inboundBilling'
|
||||
import {
|
||||
@@ -55,15 +55,6 @@ async function confirmFee() {
|
||||
ElMessage.info('当前费用已经确认,无需重复操作')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`请再次确认费用单 ${fee.feeNo},合计 ${formatInboundMoney(fee.totalAmount, fee.currency)}。确认后该费用将锁定,平台不能再修改。`,
|
||||
'二次确认费用',
|
||||
{ type: 'warning', confirmButtonText: '确认费用无误', cancelButtonText: '返回核对' },
|
||||
)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
confirming.value = true
|
||||
try {
|
||||
await confirmMerchantInboundFee(orderId, fee.feeVersion)
|
||||
@@ -86,7 +77,7 @@ async function confirmFee() {
|
||||
<el-tag :type="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' ? 'success' : 'warning'" effect="light">
|
||||
{{ props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' ? '客户已确认 · 费用已锁定' : '费用已发布 · 待确认' }}
|
||||
</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>
|
||||
</div>
|
||||
</header>
|
||||
@@ -207,34 +198,27 @@ async function confirmFee() {
|
||||
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="feeDialogOpen" title="确认测量与计费数据" width="min(980px, 94vw)" append-to-body @closed="emit('closed')">
|
||||
<el-dialog v-model="feeDialogOpen" class="billing-confirm-dialog" title="确认计费重" width="min(1180px, calc(100vw - 40px))" append-to-body @closed="emit('closed')">
|
||||
<div v-if="props.loading" class="inbound-billing-loading" aria-live="polite" aria-busy="true">
|
||||
<el-skeleton :rows="4" animated />
|
||||
<span class="sr-only">正在加载计费重</span>
|
||||
<span class="sr-only">正在加载费用</span>
|
||||
</div>
|
||||
<div v-else-if="props.error" class="inbound-billing-state is-error" role="alert">
|
||||
<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>
|
||||
</div>
|
||||
<div v-else-if="props.unavailable || !props.data" class="inbound-billing-state is-pending" role="status">
|
||||
<Clock3 :size="22" />
|
||||
<div><strong>{{ props.unavailableMessage }}</strong><span>平台推送计费重后,可在这里核对并确认。</span></div>
|
||||
<div><strong>{{ props.unavailableMessage }}</strong><span>平台推送费用后,可在这里核对并确认。</span></div>
|
||||
</div>
|
||||
<template v-else>
|
||||
<dl class="inbound-measurements fee-dialog-summary">
|
||||
<div><dt>计费总箱数</dt><dd>{{ formatInboundNumber(props.data.measurementSummary.actualPackageCount, 0) }}</dd></div>
|
||||
<div><dt>计费总毛重</dt><dd>{{ formatInboundMeasure(props.data.measurementSummary.actualGrossWeightKg, 'kg') }}</dd></div>
|
||||
<div><dt>外箱规总体积</dt><dd>{{ formatInboundMeasure(props.data.measurementSummary.actualVolumeCbm, 'm³') }}</dd></div>
|
||||
<div><dt>外箱规总材积重</dt><dd>{{ formatInboundMeasure(props.data.measurementSummary.volumeWeightKg, 'kg') }}</dd></div>
|
||||
<div><dt>计费体积</dt><dd>{{ formatInboundMeasure(props.data.billingBasis.chargeableVolumeCbm, 'm³') }}</dd></div>
|
||||
<div><dt>计费重量</dt><dd>{{ formatInboundMeasure(props.data.billingBasis.chargeableWeightKg, 'kg') }}</dd></div>
|
||||
<div><dt>对客单价</dt><dd>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit }}</dd></div>
|
||||
<div><dt>基础费用</dt><dd>{{ formatInboundMoney(props.data.latestFee.subtotalAmount, props.data.latestFee.currency) }}</dd></div>
|
||||
<div><dt>附加费用</dt><dd>{{ formatInboundMoney(props.data.latestFee.additionalAmount, props.data.latestFee.currency) }}</dd></div>
|
||||
<div><dt>费用合计</dt><dd>{{ formatInboundMoney(props.data.latestFee.totalAmount, props.data.latestFee.currency) }}</dd></div>
|
||||
<dl class="fee-dialog-summary" aria-label="计费汇总">
|
||||
<div><dt>计算重</dt><dd>{{ formatInboundMeasure(props.data.billingBasis.chargeableWeightKg, 'kg') }}</dd></div>
|
||||
<div><dt>单价</dt><dd>{{ formatInboundMoney(props.data.latestFee.unitPrice, props.data.latestFee.currency) }} / {{ props.data.latestFee.chargeUnit.toUpperCase() }}</dd></div>
|
||||
<div><dt>总金额</dt><dd>{{ formatInboundMoney(props.data.latestFee.totalAmount, props.data.latestFee.currency) }}</dd></div>
|
||||
</dl>
|
||||
<el-table v-if="props.data?.measurementItems.length" class="measurement-detail-table" :data="props.data.measurementItems" border size="small">
|
||||
<el-table class="measurement-detail-table fee-dialog-table" :data="props.data.measurementItems" border empty-text="暂无箱规测量明细">
|
||||
<el-table-column type="index" label="#" width="54" />
|
||||
<el-table-column prop="lengthCm" label="箱规长(cm)" min-width="105" />
|
||||
<el-table-column prop="widthCm" label="箱规宽(cm)" min-width="105" />
|
||||
@@ -246,15 +230,11 @@ async function confirmFee() {
|
||||
<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-alert
|
||||
v-if="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED'"
|
||||
class="fee-confirmed-alert"
|
||||
:title="`客户已于 ${formatInboundDateTime(props.data.latestFee.customerConfirmedAt)} 确认,费用已锁定,不允许修改。`"
|
||||
type="success"
|
||||
:closable="false"
|
||||
show-icon
|
||||
/>
|
||||
<el-alert v-else class="fee-confirmed-alert" title="请核对计费量、对客单价和费用合计。确认后当前费用版本将锁定。" type="warning" :closable="false" show-icon />
|
||||
<div class="fee-confirm-notice" :class="{ 'is-confirmed': props.data.latestFee.customerConfirmationStatus === 'CONFIRMED' }" role="status">
|
||||
<CircleAlert :size="21" aria-hidden="true" />
|
||||
<span v-if="props.data.latestFee.customerConfirmationStatus === 'CONFIRMED'">客户已于 {{ formatInboundDateTime(props.data.latestFee.customerConfirmedAt) }} 确认,费用已锁定,不允许修改。</span>
|
||||
<span v-else>请核对计算重、单价和总金额。确认后当前费用版本将锁定。</span>
|
||||
</div>
|
||||
</template>
|
||||
<template #footer>
|
||||
<el-button @click="feeDialogOpen = false">关闭</el-button>
|
||||
@@ -290,8 +270,25 @@ async function confirmFee() {
|
||||
.inbound-measurements { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); margin: 10px 0 0; background: #f6f8f8; }
|
||||
.inbound-measurements > div { min-width: 0; padding: 12px; }
|
||||
.measurement-detail-table { margin-top: 12px; }
|
||||
.fee-dialog-summary { margin-top: 0; }
|
||||
.fee-confirmed-alert { margin-top: 14px; }
|
||||
.fee-dialog-summary { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; margin:0; }
|
||||
.fee-dialog-summary > div { position:relative; min-width:0; overflow:hidden; padding:13px 17px; border:1px solid #e4e8f2; border-radius:11px; background:linear-gradient(145deg,#fff,#f8f9fc); box-shadow:0 5px 16px rgba(51,65,85,.04); }
|
||||
.fee-dialog-summary > div::before { position:absolute; inset:0 auto 0 0; width:4px; background:#a7b4ef; content:''; }
|
||||
.fee-dialog-summary > div:nth-child(2)::before { background:#7d91eb; }
|
||||
.fee-dialog-summary > div:nth-child(3) { border-color:#cdd7ff; background:linear-gradient(145deg,#f8faff,#eef2ff); box-shadow:0 8px 22px rgba(82,110,232,.09); }
|
||||
.fee-dialog-summary > div:nth-child(3)::before { background:#526ee8; }
|
||||
.fee-dialog-summary dt { margin:0 0 3px; color:#7b8494; font-size:13px; font-weight:500; }
|
||||
.fee-dialog-summary dd { margin:0; overflow-wrap:anywhere; color:#283246; font-size:20px; font-weight:700; font-variant-numeric:tabular-nums; letter-spacing:0; }
|
||||
.fee-dialog-summary > div:nth-child(3) dt { color:#6578c5; }
|
||||
.fee-dialog-summary > div:nth-child(3) dd { color:#405fd8; font-size:22px; }
|
||||
.fee-dialog-table { margin-top:16px; overflow:hidden; border-radius:10px; box-shadow:0 5px 18px rgba(51,65,85,.04); }
|
||||
.fee-dialog-table :deep(.el-table__header th.el-table__cell) { height:42px; padding:9px 0; background:linear-gradient(180deg,#f8f9fc,#f3f5f9); color:#697386; font-size:13px; font-weight:650; }
|
||||
.fee-dialog-table :deep(.el-table__body td.el-table__cell) { height:82px; padding:9px 0; color:#515a6c; font-size:14px; font-variant-numeric:tabular-nums; }
|
||||
.fee-dialog-table :deep(.el-table__body td:nth-child(7)), .fee-dialog-table :deep(.el-table__body td:nth-child(8)) { color:#34466b; font-weight:650; }
|
||||
.fee-dialog-table :deep(.cell) { line-height:1.6; }
|
||||
.fee-confirm-notice { display:flex; align-items:center; gap:10px; margin-top:14px; padding:10px 14px; border:1px solid #f5dfba; border-radius:9px; background:linear-gradient(90deg,#fff9ef,#fffaf2); color:#c6790c; font-size:14px; font-weight:500; }
|
||||
.fee-confirm-notice > svg { flex:0 0 auto; fill:#eda332; color:#fff; filter:drop-shadow(0 2px 3px rgba(233,154,37,.25)); }
|
||||
.fee-confirm-notice.is-confirmed { border-color:#b7dfc2; background:#f1faf3; color:#2d8a46; }
|
||||
.fee-confirm-notice.is-confirmed > svg { fill:#4eae67; }
|
||||
.pallet-location-list { margin-top: 9px; border-top: 1px solid var(--border); }
|
||||
.pallet-location-list article { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 11px; padding: 12px 0; border-bottom: 1px solid var(--border); }
|
||||
.pallet-location-list article > svg { color: var(--primary); }
|
||||
@@ -315,7 +312,26 @@ async function confirmFee() {
|
||||
.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; }
|
||||
|
||||
:global(.billing-confirm-dialog) { max-height:calc(100vh - 40px); overflow:hidden; border-radius:14px; box-shadow:0 28px 90px rgba(17,24,39,.33); }
|
||||
:global(.billing-confirm-dialog .el-dialog__header) { display:flex; align-items:center; min-height:66px; margin:0; padding:16px 22px 14px; border-bottom:1px solid #edf0f5; }
|
||||
:global(.billing-confirm-dialog .el-dialog__title) { color:#252b38; font-size:22px; font-weight:700; line-height:1.4; letter-spacing:0; }
|
||||
:global(.billing-confirm-dialog .el-dialog__headerbtn) { top:14px; right:20px; width:36px; height:36px; border-radius:50%; background:#f5f6f9; }
|
||||
:global(.billing-confirm-dialog .el-dialog__headerbtn:hover) { background:#e9edfa; }
|
||||
:global(.billing-confirm-dialog .el-dialog__headerbtn .el-dialog__close) { color:#8b92a0; font-size:22px; }
|
||||
:global(.billing-confirm-dialog .el-dialog__body) { max-height:calc(100vh - 174px); overflow:auto; padding:18px 22px; }
|
||||
:global(.billing-confirm-dialog .el-dialog__footer) { padding:14px 22px 16px; border-top:1px solid #edf0f5; }
|
||||
:global(.billing-confirm-dialog .el-dialog__footer .el-button) { min-height:40px; padding:0 20px; border-radius:8px; font-size:14px; font-weight:650; }
|
||||
:global(.billing-confirm-dialog .el-dialog__footer .el-button--primary) { min-width:168px; border-color:#526ee8; background:linear-gradient(135deg,#647fec,#526ee8); box-shadow:0 7px 16px rgba(82,110,232,.17); }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.fee-dialog-summary { grid-template-columns: 1fr; gap: 8px; }
|
||||
.fee-dialog-summary dd, .fee-dialog-summary > div:nth-child(3) dd { font-size: 18px; }
|
||||
:global(.billing-confirm-dialog) { width:calc(100vw - 16px) !important; max-height:calc(100vh - 16px); }
|
||||
:global(.billing-confirm-dialog .el-dialog__header) { padding:14px 16px 11px; }
|
||||
:global(.billing-confirm-dialog .el-dialog__title) { font-size:19px; }
|
||||
:global(.billing-confirm-dialog .el-dialog__body) { max-height:calc(100vh - 145px); padding:14px 16px; }
|
||||
:global(.billing-confirm-dialog .el-dialog__footer) { padding:12px 16px; }
|
||||
:global(.billing-confirm-dialog .el-dialog__footer .el-button) { min-height:38px; padding:0 14px; font-size:13px; }
|
||||
.inbound-billing-state { grid-template-columns: auto minmax(0, 1fr); }
|
||||
.inbound-billing-state .el-button { grid-column: 1 / -1; width: 100%; min-height: 44px; }
|
||||
.inbound-overview, .inbound-measurements, .fee-calculation-grid { grid-template-columns: 1fr; }
|
||||
|
||||
@@ -26,14 +26,15 @@ function stageState(index: number) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ol class="progress-stages" aria-label="订单主状态阶段">
|
||||
<p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消</p>
|
||||
<ol v-else class="progress-stages" aria-label="订单主状态阶段">
|
||||
<li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined">
|
||||
<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>
|
||||
</li>
|
||||
</ol>
|
||||
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">订单提交后开始记录主状态进度。</p>
|
||||
<div class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">待提交</p>
|
||||
<div v-if="order.status !== 'CANCELLED'" class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
import { customerTransportRows } from '../utils/transportFacts'
|
||||
|
||||
const props = defineProps<{ fragments: MerchantTransportFragment[] }>()
|
||||
const rows = computed(() => customerTransportRows(props.fragments))
|
||||
function time(value: string | null) { return value ? value.replace('T', ' ') : '—' }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="transport-facts" aria-label="实际装载片段运输节点">
|
||||
<strong>运输节点</strong>
|
||||
<el-table v-if="rows.length" :data="rows" row-key="key" border size="small">
|
||||
<el-table-column prop="inboundCode" label="入仓码" min-width="155" />
|
||||
<el-table-column prop="cabinetNo" label="柜次" width="90" />
|
||||
<el-table-column prop="containerNo" label="集装箱号" min-width="145" />
|
||||
<el-table-column prop="nodeLabel" label="节点" min-width="150" />
|
||||
<el-table-column label="实际时间" min-width="175"><template #default="{ row }">{{ time(row.actualAt) }}</template></el-table-column>
|
||||
<el-table-column label="预计时间" min-width="175"><template #default="{ row }">{{ time(row.estimatedAt) }}</template></el-table-column>
|
||||
<el-table-column prop="location" label="地点" min-width="130" />
|
||||
<el-table-column prop="source" label="来源" width="105" />
|
||||
</el-table>
|
||||
<p v-else>暂无运输节点</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.transport-facts { margin-top: 9px; }
|
||||
.transport-facts > strong { display: block; padding: 7px 0 5px; color: var(--navy); font-size: 11px; }
|
||||
.transport-facts > p { color: var(--muted); font-size: 11px; }
|
||||
</style>
|
||||
@@ -5,3 +5,4 @@ export { getMerchantWarehouses, type MerchantWarehouse } from './api/firstLeg'
|
||||
export { getFirstLegStatusLabel, getFirstLegStatusTone } from './utils/firstLegOrder'
|
||||
export { default as InboundCodeAssociationDialog } from './components/InboundCodeAssociationDialog.vue'
|
||||
export { default as FirstLegOrdersView } from './views/FirstLegOrdersView.vue'
|
||||
export { useCustomsPendingStore } from './store/customsPending'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FileText, Ship } from '@lucide/vue'
|
||||
import { Calculator, FileText, Ship } from '@lucide/vue'
|
||||
import type { ClientModuleManifest } from '../types.ts'
|
||||
|
||||
export const firstLegModule = {
|
||||
@@ -44,5 +44,21 @@ export const firstLegModule = {
|
||||
release: 'active',
|
||||
meta: { title: '快速下单', description: '按渠道、目的仓和产品 SKU 快速生成订单草稿', permission: 'order:first-leg:quick-create' },
|
||||
},
|
||||
{
|
||||
path: 'first-leg/customs-documents',
|
||||
name: 'first-leg-customs-documents',
|
||||
component: () => import('./views/CustomsDocumentsView.vue'),
|
||||
release: 'active',
|
||||
meta: { title: '报关资料', description: '管理装柜后的退税报关资料与回执', permission: 'order:first-leg:customs-list' },
|
||||
navigation: { key: 'first-leg-customs-documents', title: '报关资料', icon: FileText },
|
||||
},
|
||||
{
|
||||
path: 'first-leg/sailing-prices',
|
||||
name: 'first-leg-sailing-prices',
|
||||
component: () => import('./views/SailingPricesView.vue'),
|
||||
release: 'active',
|
||||
meta: { title: '船期价格', description: '查询渠道、参考船期与预估运费', permission: 'order:first-leg:pricing-list' },
|
||||
navigation: { key: 'first-leg-sailing-prices', title: '船期价格', icon: Calculator },
|
||||
},
|
||||
],
|
||||
} satisfies ClientModuleManifest
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
const source = readFileSync(new URL('./customsPending.ts', import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
function deferred() { let resolve, reject; const promise = new Promise((a,b) => { resolve=a; reject=b }); return { promise, resolve, reject } }
|
||||
function harness(t, read) {
|
||||
const context=pinia.createPinia();pinia.setActivePinia(context);t.after(()=>pinia.disposePinia(context))
|
||||
const deps={vue,pinia,'../api/customs':{getMerchantCustomsPendingCount:read}}, exports={}
|
||||
new Function('require','exports',code)(id=>{assert.ok(id in deps,id);return deps[id]},exports)
|
||||
return exports.useCustomsPendingStore()
|
||||
}
|
||||
test('does not request without a permitted identity; preserves counts while refreshing and accepts zero',async t=>{
|
||||
const pending=deferred();let calls=0
|
||||
const store=harness(t,()=>++calls===1?Promise.resolve(2):pending.promise)
|
||||
await store.refresh();assert.equal(calls,0)
|
||||
store.setScope('customer-a');await store.refresh();assert.equal(store.count,2)
|
||||
const load=store.refresh();await store.refresh();assert.equal(calls,2);assert.equal(store.count,2)
|
||||
pending.resolve(0);await load;assert.equal(store.count,0);assert.equal(store.loading,false)
|
||||
})
|
||||
test('logout, permission removal and account switches discard old in-flight responses',async t=>{
|
||||
const pending=deferred();const store=harness(t,()=>pending.promise)
|
||||
store.setScope('a');const load=store.refresh();store.setScope('')
|
||||
pending.resolve(9);await load;assert.equal(store.count,null);assert.equal(store.error,'')
|
||||
store.setScope('b');assert.equal(store.count,null)
|
||||
})
|
||||
test('successful mutation can force a newer refresh without being overwritten by an older query',async t=>{
|
||||
const a=deferred(),b=deferred();let calls=0;const store=harness(t,()=>++calls===1?a.promise:b.promise)
|
||||
store.setScope('a');const first=store.refresh();const second=store.refresh(true)
|
||||
b.resolve(1);await second;a.resolve(2);await first;assert.equal(store.count,1)
|
||||
})
|
||||
test('failure is distinguishable from zero and retry restores authoritative count',async t=>{
|
||||
let fail=true;const store=harness(t,()=>fail?Promise.reject(new Error('offline')):Promise.resolve(3))
|
||||
store.setScope('a');await store.refresh();assert.equal(store.count,null);assert.notEqual(store.error,'')
|
||||
fail=false;await store.refresh();assert.equal(store.count,3);assert.equal(store.error,'')
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { getMerchantCustomsPendingCount } from '../api/customs'
|
||||
|
||||
export const useCustomsPendingStore = defineStore('client-customs-pending', () => {
|
||||
const count = ref<number | null>(null)
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
let scope = ''
|
||||
let requestVersion = 0
|
||||
|
||||
function setScope(value: string) {
|
||||
if (scope === value) return
|
||||
scope = value
|
||||
requestVersion++
|
||||
count.value = null
|
||||
error.value = ''
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
async function refresh(force = false) {
|
||||
if (!scope || (loading.value && !force)) return
|
||||
const request = ++requestVersion
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await getMerchantCustomsPendingCount()
|
||||
if (request !== requestVersion) return
|
||||
count.value = result
|
||||
error.value = ''
|
||||
} catch {
|
||||
if (request !== requestVersion) return
|
||||
count.value = null
|
||||
error.value = '报关待办数量加载失败,请进入报关资料刷新'
|
||||
} finally {
|
||||
if (request === requestVersion) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
return { count, loading, error, setScope, refresh }
|
||||
})
|
||||
@@ -0,0 +1,334 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
import { requireOrderProgress } from '../utils/orderProgress.ts'
|
||||
|
||||
function compile(path, dependencies) {
|
||||
const source = readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function harness(t) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = []
|
||||
const behavior = { failWrite: false, failRead: false, version: 9, status: 'DRAFT' }
|
||||
const api = compile('../api/firstLeg.ts', { '@/api/http': { apiRequest: async config => {
|
||||
calls.push(structuredClone(config))
|
||||
if (config.method === 'GET') {
|
||||
if (behavior.failRead) throw new Error('读取失败')
|
||||
return { order: { id: 'one', orderNo: 'FL-ONE', version: behavior.version, status: behavior.status, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress, destinationCountryCode: 'US' }, cargoes: [] }
|
||||
}
|
||||
if (behavior.failWrite || (behavior.failSubmit && config.url.endsWith('/submit'))) throw new Error('响应丢失')
|
||||
if (config.url.endsWith('/submit') && behavior.failSubmitRead) behavior.failRead = true
|
||||
if (config.method === 'POST' && config.url === '/merchant/v1/orders/first-leg') return 'one'
|
||||
} } })
|
||||
const module = compile('./firstLegOrders.ts', {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': api,
|
||||
'@/modules/first-leg/api/unifiedOrders': {
|
||||
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/warehousePagination': {},
|
||||
'@/modules/first-leg/utils/orderProgress': { requireOrderProgress },
|
||||
})
|
||||
const store = module.useFirstLegOrdersStore()
|
||||
store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC' }]
|
||||
const draft = { receivingWarehouseId: 'warehouse', destinationType: 'PRIVATE', destinationCountryCode: 'US', items: [], customerRemark: '原草稿' }
|
||||
return { store, api, calls, behavior, draft }
|
||||
}
|
||||
|
||||
function displayedWarehouseAddress(order) {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const expressions = [...view.matchAll(/\{\{ (detailOrder\.receivingWarehouseSnapshot\.(?:province|city|address)) \}\}/g)]
|
||||
assert.equal(expressions.length, 3)
|
||||
return expressions.map(([, expression]) => new Function('detailOrder', `return ${expression}`)(order)).join('')
|
||||
}
|
||||
|
||||
test('complete address is identical for cold unified, warm unified, raw detail and remark-only save', async t => {
|
||||
const h = harness(t)
|
||||
const fullAddress = 'CN 浙江省 义乌市 仓库路 8 号 322000'
|
||||
h.behavior.receivingWarehouseAddress = fullAddress
|
||||
h.store.warehouses = []
|
||||
const cold = await h.store.loadDetail('one')
|
||||
assert.equal(displayedWarehouseAddress(cold), fullAddress)
|
||||
h.store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC', province: '浙江省', city: '义乌市', address: '主档已更新的地址' }]
|
||||
h.store.orders = []
|
||||
const warm = await h.store.loadDetail('one')
|
||||
const raw = await h.store.loadDraftDetail('one')
|
||||
for (const detail of [warm, raw]) {
|
||||
assert.equal(displayedWarehouseAddress(detail), fullAddress)
|
||||
assert.equal(detail.receivingWarehouseSnapshot.province, '')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.city, '')
|
||||
}
|
||||
const session = h.store.beginDraftEdit(raw)
|
||||
h.draft.customerRemark = '仅修改备注'
|
||||
const saved = await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
assert.equal(displayedWarehouseAddress(saved), fullAddress)
|
||||
const write = h.calls.find(call => call.method === 'PUT')
|
||||
assert.equal(write.data.draft.customerRemark, '仅修改备注')
|
||||
assert.equal(Object.hasOwn(write.data.draft, 'receivingWarehouseAddress'), false)
|
||||
assert.equal(h.behavior.receivingWarehouseAddress, fullAddress)
|
||||
assert.equal(h.store.warehouses[0].province, '浙江省')
|
||||
assert.equal(h.store.warehouses[0].address, '主档已更新的地址')
|
||||
})
|
||||
|
||||
test('structured master address stays structured when no order address snapshot exists', async t => {
|
||||
const h = harness(t)
|
||||
h.store.warehouses = [{ id: 'warehouse', name: '国内仓', province: '浙江省', city: '义乌市', address: '仓库路 8 号', warehouseType: 'DOMESTIC' }]
|
||||
const detail = await h.store.loadDetail('one')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.province, '浙江省')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.city, '义乌市')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.address, '仓库路 8 号')
|
||||
assert.equal(displayedWarehouseAddress(detail), '浙江省义乌市仓库路 8 号')
|
||||
})
|
||||
|
||||
test('raw and unified cancelled detail remain CANCELLED even when unified mainStatus is null', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.status = 'CANCELLED'
|
||||
const raw = await h.store.loadDraftDetail('one')
|
||||
assert.equal(raw.status, 'CANCELLED')
|
||||
const unified = await h.store.loadDetail('one')
|
||||
assert.equal(unified.status, 'CANCELLED')
|
||||
h.behavior.status = 'APPROVED'
|
||||
const unknown = await h.store.loadDetail('one')
|
||||
assert.notEqual(unknown.status, 'CANCELLED', 'unknown summary must not be reclassified as cancellation')
|
||||
})
|
||||
|
||||
test('fresh direct draft detail preserves raw DRAFT with null unified summary and opens an edit session', async t => {
|
||||
const h = harness(t)
|
||||
assert.equal(h.store.orders.length, 0)
|
||||
const direct = await h.store.loadDetail('one')
|
||||
assert.equal(direct.status, 'DRAFT')
|
||||
assert.equal(h.store.beginDraftEdit(direct).expectedVersion, 9)
|
||||
h.store.orders = []
|
||||
const refreshed = await h.store.loadDetail('one')
|
||||
assert.equal(refreshed.status, 'DRAFT')
|
||||
h.store.orders = []
|
||||
h.behavior.status = 'APPROVED'
|
||||
const unknown = await h.store.loadDetail('one')
|
||||
assert.notEqual(unknown.status, 'DRAFT')
|
||||
assert.notEqual(unknown.status, 'CANCELLED')
|
||||
assert.throws(() => h.store.beginDraftEdit(unknown), /重新打开/)
|
||||
})
|
||||
|
||||
test('cancelled detail summary has no pending overseas synchronization entries', () => {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const declaration = ast.statements.flatMap(node => ts.isVariableStatement(node) ? [...node.declarationList.declarations] : []).find(node => node.name.getText(ast) === 'progressSummaryItems')
|
||||
const code = ts.transpileModule('const progressSummaryItems = ' + declaration.initializer.getText(ast), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const summary = new Function('computed', 'detailOrder', code + '; return progressSummaryItems.value')(vue.computed, { value: { status: 'CANCELLED' } })
|
||||
assert.deepEqual(summary, [])
|
||||
})
|
||||
|
||||
test('edit preserves the detail version but generates a fresh command after failure', async t => {
|
||||
const h = harness(t), session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.store.orders = [{ id: 'one', version: 0 }]; h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /响应丢失/)
|
||||
h.behavior.failWrite = false; h.draft.customerRemark = '已修改'
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
const writes = h.calls.filter(call => call.method === 'PUT')
|
||||
assert.equal(writes[0].data.expectedVersion, 9); assert.equal(writes[1].data.draft.customerRemark, '已修改')
|
||||
assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
|
||||
})
|
||||
test('missing edit session is invalid while changed inputs after failure are accepted', async t => {
|
||||
const h = harness(t); await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one')); h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session))
|
||||
h.draft.customerRemark = '不同内容'; h.behavior.failWrite = false
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
|
||||
})
|
||||
test('read failure after edit does not retain a frozen request', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.behavior.failRead = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /读取失败/)
|
||||
h.behavior.failRead = false
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
const writes = h.calls.filter(call => call.method === 'PUT')
|
||||
assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
|
||||
})
|
||||
|
||||
test('cancel submits the current version and reason after a previous failure', async t => {
|
||||
const h = harness(t); h.behavior.status = 'SUBMITTED'; h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.cancelOrder('one', 12, '客户要求取消'), /响应丢失/)
|
||||
h.behavior.failWrite = false; await h.store.cancelOrder('one', 13, '其他原因')
|
||||
const writes = h.calls.filter(call => call.method === 'POST')
|
||||
assert.equal(writes.length, 2); assert.deepEqual(writes[1].data, { expectedVersion: 13, reason: '其他原因' })
|
||||
assert.notEqual(writes[0].headers['Idempotency-Key'], writes[1].headers['Idempotency-Key'])
|
||||
})
|
||||
test('cancel requires a detail version and a nonempty reason', async t => {
|
||||
const h = harness(t)
|
||||
await assert.rejects(h.store.cancelOrder('one', undefined, '理由'))
|
||||
await assert.rejects(h.store.cancelOrder('one', 1, ' '))
|
||||
assert.equal(h.calls.length, 0)
|
||||
})
|
||||
|
||||
test('cancellation decision reads raw server status and version including SUBMITTED', async t => {
|
||||
const h = harness(t)
|
||||
for (const status of ['DRAFT', 'SUBMITTED', 'APPROVED', 'ACCEPTED', 'REJECTED']) {
|
||||
h.behavior.status = status
|
||||
const target = await h.store.prepareCancellation('one')
|
||||
assert.equal(target.expectedVersion, 9)
|
||||
assert.equal(target.businessNo, 'FL-ONE')
|
||||
}
|
||||
for (const status of ['PROCESSING', 'COMPLETED', 'CANCELLED']) {
|
||||
h.behavior.status = status
|
||||
await assert.rejects(h.store.prepareCancellation('one'), /不允许取消/)
|
||||
}
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
})
|
||||
|
||||
function cancellationViewHarness() {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['canOfferCancellation', 'cancelOrder'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const calls = [], messages = [], prompts = []
|
||||
const canCancelOrder = vue.ref(true), cancellingOrderId = vue.ref(''), pendingCancellation = vue.shallowRef()
|
||||
class ApiError extends Error { constructor() { super('订单版本已变化'); this.code = 'A0409'; this.status = 409 } }
|
||||
const behavior = { error: null }
|
||||
const store = {
|
||||
prepareCancellation: async id => { calls.push(['prepare', id]); return { id, expectedVersion: 12, businessNo: 'FL-ONE', statusLabel: '审核中' } },
|
||||
cancelOrder: async (...args) => { calls.push(['cancel', ...args]); if (behavior.error) throw behavior.error },
|
||||
load: async query => calls.push(['load', query]),
|
||||
}
|
||||
const ElMessageBox = {
|
||||
prompt: async (message, title, options) => { prompts.push({ message, title, options }); return { value: '客户申请取消' } },
|
||||
confirm: async (...args) => calls.push(['confirm', ...args]),
|
||||
}
|
||||
const ElMessage = { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) }
|
||||
const globals = { canCancelOrder, cancellingOrderId, pendingCancellation, store, ElMessageBox, ElMessage, ApiError,
|
||||
loadOrderPage: async () => calls.push(['load']),
|
||||
isDetailPage: vue.ref(true), router: { push: async route => calls.push(['route', route]) } }
|
||||
const handler = new Function(...Object.keys(globals), code + '\nreturn cancelOrder')(...Object.values(globals))
|
||||
return { handler, calls, messages, prompts, canCancelOrder, pendingCancellation, behavior, ApiError }
|
||||
}
|
||||
|
||||
test('cancel UI uses mandatory-reason centered prompt and refreshes after successful submitted-order cancellation', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
await h.handler({ id: 'one', status: 'PENDING_REVIEW' })
|
||||
assert.match(h.prompts[0].message, /FL-ONE.*审核中/)
|
||||
const validate = h.prompts[0].options.inputValidator
|
||||
assert.notEqual(validate(' '), true)
|
||||
assert.notEqual(validate('x'.repeat(501)), true)
|
||||
assert.equal(validate('合理原因'), true)
|
||||
assert.deepEqual(h.calls.map(call => call[0]), ['prepare', 'cancel', 'load', 'route'])
|
||||
assert.deepEqual(h.calls[1], ['cancel', 'one', 12, '客户申请取消'])
|
||||
})
|
||||
|
||||
test('cancel UI releases failure and asks for a current cancellation decision on the next click', async () => {
|
||||
const h = cancellationViewHarness(), order = { id: 'one', status: 'DRAFT' }
|
||||
h.behavior.error = new Error('网络无响应'); await h.handler(order)
|
||||
h.behavior.error = null; await h.handler(order)
|
||||
assert.equal(h.prompts.length, 2); assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 2)
|
||||
assert.equal(h.calls.filter(call => call[0] === 'cancel').length, 2)
|
||||
})
|
||||
test('cancel UI blocks unavailable permission and irreversible visible stages before reads or writes', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
h.canCancelOrder.value = false
|
||||
await h.handler({ id: 'one', status: 'DRAFT' })
|
||||
h.canCancelOrder.value = true
|
||||
await h.handler({ id: 'one', status: 'LOADED' })
|
||||
assert.equal(h.calls.length, 0)
|
||||
assert.equal(h.prompts.length, 0)
|
||||
})
|
||||
|
||||
test('both editor entry points capture detail sessions and both save paths pass them', () => {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
assert.equal((view.match(/editingSession\.value = store\.beginDraftEdit\(detailedOrder\)/g) ?? []).length, 2)
|
||||
assert.equal((view.match(/store\.saveDraft(?:ForSubmission)?\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2)
|
||||
})
|
||||
|
||||
test('submit uses the current raw version and a fresh key after timeout', async t => {
|
||||
const h = harness(t); h.store.orders = [{id:'one',status:'DRAFT',version:0}]; h.behavior.failSubmit = true
|
||||
await assert.rejects(h.store.submitSaved('one', 'ACTIVE'), /响应丢失/)
|
||||
h.behavior.version = 10; h.behavior.failSubmit = false; await h.store.submitSaved('one', 'ACTIVE')
|
||||
const writes = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.deepEqual(writes.map(call => call.data.expectedVersion), [9,10]); assert.notEqual(writes[0].headers['Idempotency-Key'],writes[1].headers['Idempotency-Key'])
|
||||
})
|
||||
test('submit validates current status and releases failure after readback', async t => {
|
||||
const h = harness(t)
|
||||
for (const version of [undefined, -1, 1.5]) {
|
||||
h.behavior.version = version
|
||||
await assert.rejects(h.store.submitSaved('one'), /版本缺失/)
|
||||
}
|
||||
h.behavior.version = 0; h.behavior.status = 'SUBMITTED'
|
||||
await assert.rejects(h.store.submitSaved('one'), /不是草稿/)
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
h.behavior.status = 'DRAFT'; h.behavior.failSubmitRead = true
|
||||
await assert.rejects(h.store.submitSaved('one'), /读取失败/)
|
||||
h.behavior.failRead = false; h.behavior.failSubmitRead = false
|
||||
await h.store.submitSaved('one')
|
||||
const posts = h.calls.filter(call => call.method === 'POST')
|
||||
assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key'])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 0 }, 'raw detail zero is valid')
|
||||
})
|
||||
|
||||
test('failed submit leaves the draft editable for a fresh save and submission', async t => {
|
||||
const h = harness(t), session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session); h.behavior.failSubmit = true
|
||||
await assert.rejects(h.store.submitSaved('one')); h.draft.customerRemark = '新内容'
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session); h.behavior.failSubmit = false
|
||||
await h.store.submitSaved('one'); assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
|
||||
})
|
||||
test('failed initial submit read releases the submission guard for the next click', async t => {
|
||||
const h = harness(t); h.behavior.failRead = true; await assert.rejects(h.store.submitSaved('one'))
|
||||
h.behavior.failRead = false; await h.store.submitSaved('one')
|
||||
assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 1)
|
||||
})
|
||||
async function submissionViewHarness(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 ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['submitOrder', 'confirmSubmissionEdit', 'submitSelectedDraftOrders'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const messages = [], confirmations = []
|
||||
const globals = {
|
||||
store: h.store, saving: vue.ref(false), form: h.draft, cloneDraft: draft => structuredClone(draft),
|
||||
editingId: vue.ref('one'), editingSession: vue.shallowRef(h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))),
|
||||
companySubmissionBlocked: vue.ref(false), companyAuditLoaded: vue.ref(true), tenantStore: { company: { companyName: '客户', auditStatus: 'ACTIVE' } },
|
||||
validateEditorForm: async () => true, markEditorClean: () => {}, editorOpen: vue.ref(true), isCreatePage: vue.ref(false), loadPageData: async () => {},
|
||||
batchSubmitting: vue.ref(false), selectedDraftOrders: vue.ref([{ id: 'one', version: 0 }]), pendingBatchSubmissionIds: vue.ref([]),
|
||||
searchOrders: async () => { globals.selectedDraftOrders.value = [] }, appliedFilters: vue.ref({}),
|
||||
ElMessageBox: { confirm: async message => { confirmations.push(message); if (h.behavior.cancelConfirm) throw 'cancel' } },
|
||||
ElMessage: { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) },
|
||||
}
|
||||
const handlers = new Function(...Object.keys(globals), code + '\nreturn {submitOrder, submitSelectedDraftOrders}')(...Object.values(globals))
|
||||
return { ...h, ...handlers, globals, messages, confirmations }
|
||||
}
|
||||
|
||||
test('real editor releases failure and saves current edited input on another click', async t => {
|
||||
const h = await submissionViewHarness(t); h.behavior.failSubmit = true
|
||||
await h.submitOrder(); assert.equal(h.globals.saving.value, false)
|
||||
h.draft.customerRemark = '修改后的决定'; h.behavior.failSubmit = false; await h.submitOrder()
|
||||
const writes = h.calls.filter(call => call.method === 'PUT'), posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.equal(writes.length, 2); assert.equal(writes[1].data.draft.customerRemark, '修改后的决定')
|
||||
assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key']); assert.equal(h.globals.saving.value, false)
|
||||
})
|
||||
test('real batch handler uses only current selection after a failed batch', async t => {
|
||||
const h = await submissionViewHarness(t); h.behavior.failSubmit = true
|
||||
await h.submitSelectedDraftOrders(); assert.equal(h.globals.batchSubmitting.value, false)
|
||||
h.behavior.failSubmit = false; await h.submitSelectedDraftOrders()
|
||||
assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 1)
|
||||
h.globals.selectedDraftOrders.value = [{id:'one',version:9}]; await h.submitSelectedDraftOrders()
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.equal(posts.length, 2); assert.notEqual(posts[0].headers['Idempotency-Key'], posts[1].headers['Idempotency-Key'])
|
||||
})
|
||||
test('real new-order handler retains the created order and saves current edits after submit failure', async t => {
|
||||
const h = await submissionViewHarness(t); h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined
|
||||
h.behavior.version = 0; h.behavior.failSubmit = true; await h.submitOrder()
|
||||
assert.equal(h.globals.editingId.value, 'one'); h.behavior.failSubmit = false; h.draft.customerRemark = '修改'
|
||||
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 === 'PUT').length, 1)
|
||||
assert.equal(h.calls.filter(call => call.url.endsWith('/submit')).length, 2)
|
||||
})
|
||||
@@ -1,27 +1,77 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
|
||||
const storeSource = readFileSync(new URL('./firstLegOrders.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')
|
||||
|
||||
test('maps the first-leg aggregate list fields without loading detail rows', () => {
|
||||
assert.match(apiSource, /interface MerchantFirstLegOrderRow/)
|
||||
assert.match(apiSource, /skuNos: string \| string\[\] \| null/)
|
||||
assert.match(apiSource, /cargoes\?: Array<\{ skuNo\?: string \| null \}>/)
|
||||
assert.match(apiSource, /apiRequest<PageResult<MerchantFirstLegOrderRow>>/)
|
||||
assert.match(storeSource, /function mapFirstLegOrderRow/)
|
||||
for (const field of ['inboundId', 'inboundCode', 'channelName', 'destinationWarehouseName', 'pickupMethod', 'packageCount', 'expressCompany', 'trackingNo', 'totalGrossWeightKg', 'totalNetWeightKg', 'totalVolumeCbm', 'totalQuantity', 'remark', 'shipmentId', 'fulfillmentType', 'lxCode', 'referenceId', 'createdAt']) {
|
||||
assert.match(storeSource, new RegExp(`row\\.${field}`))
|
||||
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)
|
||||
}
|
||||
assert.match(storeSource, /row\.skuNos/)
|
||||
assert.match(storeSource, /row\.cargoes/)
|
||||
assert.match(storeSource, /chargeableWeightKg: null/)
|
||||
assert.match(storeSource, /chargeableVolumeCbm: null/)
|
||||
assert.match(apiSource, /pickupMethod: ApiPickupMethod \\| null/)
|
||||
assert.match(storeSource, /orderResult\.value\.records\.map\(mapFirstLegOrderRow\)/)
|
||||
assert.match(storeSource, /orderResult\.value\.records\.map\(\(item\) => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||
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', () => {
|
||||
const mapper = storeSource.slice(storeSource.indexOf('function businessSummary('), storeSource.indexOf('\nconst unifiedActionLabels'))
|
||||
const javascript = ts.transpileModule(mapper, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const map = runInNewContext(`${javascript}; businessSummary`)
|
||||
const transport = {
|
||||
vesselName: 'REASSIGNED', voyageNo: 'V02',
|
||||
estimatedSailingAt: '2026-10-07T08:00:00', actualSailingAt: '2026-10-08T09:00:00',
|
||||
effectiveSailingAt: '2026-10-08T09:00:00', effectiveSailingAtEstimated: false,
|
||||
estimatedPortArrivalAt: '2026-10-27T08:00:00', actualPortArrivalAt: null,
|
||||
}
|
||||
const mapped = map({ transport })
|
||||
assert.equal(mapped.estimatedSailingAt, transport.estimatedSailingAt)
|
||||
assert.equal(mapped.estimatedPortArrivalAt, transport.estimatedPortArrivalAt)
|
||||
assert.equal(mapped.vesselName, 'REASSIGNED')
|
||||
assert.equal(mapped.voyageNo, 'V02')
|
||||
assert.equal(map().estimatedSailingAt, '')
|
||||
assert.equal(map({ transport: null }).estimatedPortArrivalAt, '')
|
||||
})
|
||||
|
||||
test('maps the current workbench row without loading detail rows', () => {
|
||||
assert.match(storeSource, /result\.page\.records\.map\(item => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||
assert.match(storeSource, /version: summary\.orderVersion/)
|
||||
assert.doesNotMatch(storeSource, /function mapFirstLegOrderRow/)
|
||||
})
|
||||
|
||||
test('declares the documented merchant warehouse and first-leg endpoints', () => {
|
||||
@@ -64,14 +114,10 @@ test('maps transport and status fields instead of treating container mode as tra
|
||||
assert.doesNotMatch(storeSource, /status === 'COMPLETED'\) return 'DELIVERED'/)
|
||||
})
|
||||
|
||||
test('prefers unified reads and only falls back to the real legacy API when C02 is unavailable', () => {
|
||||
test('uses only the formal workbench read and surfaces failures', () => {
|
||||
assert.match(storeSource, /getMerchantOrderWorkbench\(query\)/)
|
||||
assert.match(storeSource, /orders\.value = \[\]/)
|
||||
assert.match(storeSource, /warehouses\.value = \[\]/)
|
||||
assert.match(storeSource, /Promise\.allSettled\(\[getOrdersForClient\(query\), loadWarehouseType\('DOMESTIC', true\)\]\)/)
|
||||
assert.match(storeSource, /getMerchantUnifiedOrders\(unifiedQuery\)/)
|
||||
assert.match(storeSource, /isUnifiedOrderQueryUnavailable\(error\)/)
|
||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query\)\)/)
|
||||
assert.doesNotMatch(storeSource, /DEMO_PLATFORM_RECEIVING_WAREHOUSES|initialOrders/)
|
||||
assert.doesNotMatch(storeSource, /isUnifiedOrderQueryUnavailable|getOrdersForClient|getMerchantFirstLegOrders|initialOrders/)
|
||||
})
|
||||
|
||||
test('declares the final C02 row and detail contract in the API adapter', () => {
|
||||
@@ -86,13 +132,14 @@ test('declares the final C02 row and detail contract in the API adapter', () =>
|
||||
for (const field of ['pickupMethod', 'requestedPickupAt', 'containerMode', 'destinationType', 'destinationCode', 'skuNos', 'totalQuantity', 'totalNetWeightKg', 'chargeableVolumeCbm', 'inboundCompletedAt', 'shipmentId', 'referenceId']) {
|
||||
assert.match(unifiedApiSource, new RegExp(`${field}:`))
|
||||
}
|
||||
assert.match(unifiedApiSource, /taxMode: ApiTaxMode \| null/)
|
||||
assert.match(unifiedApiSource, /customsInspection: boolean \| null/)
|
||||
assert.match(unifiedApiSource, /loadingVersion: number/)
|
||||
assert.match(unifiedApiSource, /pickingVersion: number/)
|
||||
assert.match(unifiedApiSource, /summary: MerchantUnifiedOrderRow/)
|
||||
assert.match(unifiedApiSource, /order: MerchantFirstLegOrderDetail/)
|
||||
assert.match(unifiedApiSource, /timeline: MerchantUnifiedTimelineEvent\[\]/)
|
||||
assert.match(unifiedApiSource, /customNodes\?: MerchantUnifiedCustomNode\[\]/)
|
||||
assert.match(unifiedApiSource, /error\.status === 404 \|\| error\.code === 'A0404'/)
|
||||
})
|
||||
|
||||
test('keeps unified order pagination valid when the store omits page and size', () => {
|
||||
@@ -100,27 +147,18 @@ test('keeps unified order pagination valid when the store omits page and size',
|
||||
assert.match(unifiedApiSource, /params: \{ page: page \?\? 1, size: size \?\? 200, \.\.\.filters \}/)
|
||||
})
|
||||
|
||||
test('keeps drafts on the legacy read path without assigning a unified main status', () => {
|
||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query, 'DRAFT'\)\)/)
|
||||
assert.match(storeSource, /const listOrder = getById\(id\)/)
|
||||
assert.match(storeSource, /listOrder\?\.status === 'DRAFT' \? loadLegacyDetail\(id, listOrder\) : loadUnifiedDetail\(id\)/)
|
||||
assert.match(storeSource, /detail\.order\.lxCode == null && listOrder\?\.lxCode/)
|
||||
assert.match(storeSource, /return loadLegacyDetail\(String\(createdId\)\)/)
|
||||
assert.match(storeSource, /draftLoadError/)
|
||||
})
|
||||
|
||||
test('routes supported filters to C02 without sending DRAFT as a main status', () => {
|
||||
assert.match(storeSource, /interface ClientOrderReadQuery extends MerchantUnifiedOrderQuery/)
|
||||
assert.match(storeSource, /if \(query\.draftOnly\)/)
|
||||
assert.match(storeSource, /const unifiedQuery: MerchantUnifiedOrderQuery/)
|
||||
assert.match(storeSource, /inboundCode: query\.inboundCode/)
|
||||
assert.match(storeSource, /getMerchantUnifiedOrders\(unifiedQuery\)/)
|
||||
test('draft editing reads the order aggregate while navigation uses unified detail', () => {
|
||||
assert.match(storeSource, /return loadOrderAggregate\(id\)/)
|
||||
assert.match(storeSource, /const detail = await getMerchantUnifiedOrder\(id\)/)
|
||||
assert.doesNotMatch(storeSource, /loadLegacyDetail|draftOnly|includeDrafts/)
|
||||
})
|
||||
|
||||
test('maps C02 authoritative status, transport, cargo and pickup snapshots', () => {
|
||||
assert.match(storeSource, /id: String\(summary\.orderId\)/)
|
||||
assert.match(storeSource, /transportMode: unifiedTransport\(summary\.containerMode\)/)
|
||||
assert.match(storeSource, /status: summary\.mainStatus/)
|
||||
assert.match(storeSource, /taxMode: summary\.taxMode \?\? 'BUY_DECLARATION'/)
|
||||
assert.match(storeSource, /customsInspection: summary\.customsInspection \?\? false/)
|
||||
assert.match(storeSource, /fulfillmentType: summary\.fulfillmentType \?\? 'STANDARD'/)
|
||||
assert.match(storeSource, /lxCode: summary\.lxCode \?\? ''/)
|
||||
assert.match(storeSource, /mapped\.fulfillmentType = detail\.summary\.fulfillmentType \?\? mapped\.fulfillmentType/)
|
||||
@@ -170,7 +208,7 @@ test('separates domestic receiving warehouses from public destinations', () => {
|
||||
assert.match(apiSource, /warehouseType\?: MerchantWarehouseType/)
|
||||
assert.match(apiSource, /params: \{ page: 1, size: 200, status: 'ACTIVE', \.\.\.params \}/)
|
||||
assert.match(storeSource, /loadAllWarehouseRecords\(warehouseType, getMerchantWarehouses\)/)
|
||||
assert.match(storeSource, /loadWarehouseType\('DOMESTIC', true\)/)
|
||||
assert.match(storeSource, /loadWarehouseType\('DOMESTIC'\)/)
|
||||
assert.match(storeSource, /warehouse\.warehouseType !== 'DOMESTIC'/)
|
||||
assert.match(storeSource, /item\.warehouseType === draft\.destinationType/)
|
||||
assert.match(storeSource, /draft\.amazonWarehouseCode = draft\.destinationType === 'FBA' \? destinationWarehouse\.code : ''/)
|
||||
@@ -181,20 +219,20 @@ test('only blocks submission when a known company audit status is not active', (
|
||||
assert.match(storeSource, /if \(companyAuditStatus && companyAuditStatus !== 'ACTIVE'\)/)
|
||||
})
|
||||
|
||||
test('does not expose the out-of-scope cancellation write', () => {
|
||||
assert.doesNotMatch(storeSource, /cancelMerchant|function cancel|\/cancel/)
|
||||
assert.doesNotMatch(apiSource, /\/cancel/)
|
||||
test('uses the versioned merchant cancellation contract', () => {
|
||||
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, payload, createIdempotencyKey\(/)
|
||||
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
|
||||
})
|
||||
|
||||
test('sends an idempotency key for create and submit writes', () => {
|
||||
assert.match(apiSource, /'Idempotency-Key': createIdempotencyKey\('first-leg-create'\)/)
|
||||
assert.match(apiSource, /submitMerchantFirstLegOrder\(id: number \| string, idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /submitMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number \}, idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /'Idempotency-Key': idempotencyKey/)
|
||||
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
||||
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
|
||||
assert.match(storeSource, /pendingSubmitKeys\.get\(id\) \?\? createIdempotencyKey\(`first-leg-submit-\$\{id\}`\)/)
|
||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, idempotencyKey\)/)
|
||||
assert.doesNotMatch(storeSource, /pendingSubmissions|pendingEdits|pendingCancellation/)
|
||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, \{ expectedVersion: order\.version \}, createIdempotencyKey\(/)
|
||||
})
|
||||
|
||||
test('does not expose the contradictory backend rejected state in the client model', () => {
|
||||
@@ -239,5 +277,5 @@ test('keeps failed order loads distinct from empty results', () => {
|
||||
assert.match(storeSource, /const loadError = ref\(''\)/)
|
||||
assert.match(storeSource, /orderResult\.reason instanceof Error/)
|
||||
assert.match(storeSource, /warehouseLoadError/)
|
||||
assert.match(storeSource, /return \{ orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError/)
|
||||
assert.match(storeSource, /return \{ orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError/)
|
||||
})
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import {
|
||||
createMerchantFirstLegOrderBatch,
|
||||
createMerchantFirstLegOrder,
|
||||
createIdempotencyKey,
|
||||
getMerchantFirstLegOrder,
|
||||
getMerchantFirstLegOrders,
|
||||
getMerchantWarehouseDetail,
|
||||
getMerchantWarehouses,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantFirstLegOrder,
|
||||
cancelMerchantFirstLegOrder,
|
||||
type ApiFirstLegStatus,
|
||||
type FirstLegOrderSaveRequest,
|
||||
type MerchantFirstLegOrder,
|
||||
type MerchantFirstLegOrderRow,
|
||||
type MerchantFirstLegOrderDetail,
|
||||
type MerchantBatchDraftResponse,
|
||||
type MerchantWarehouse,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import {
|
||||
getMerchantUnifiedOrder,
|
||||
getMerchantUnifiedOrders,
|
||||
isUnifiedOrderQueryUnavailable,
|
||||
getMerchantOrderWorkbench,
|
||||
type MerchantUnifiedOrderDetail,
|
||||
type MerchantUnifiedOrderQuery,
|
||||
type MerchantOrderWorkbenchQuery,
|
||||
type MerchantOrderProgress,
|
||||
type OrderQueueCounts,
|
||||
type MerchantUnifiedOrderRow,
|
||||
} from '@/modules/first-leg/api/unifiedOrders'
|
||||
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
|
||||
@@ -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 { canClientEditFirstLegOrder, getFirstLegStatusLabel } from '@/modules/first-leg/utils/firstLegOrder'
|
||||
import { loadAllWarehouseRecords } from '@/modules/first-leg/utils/warehousePagination'
|
||||
import { requireOrderProgress } from '@/modules/first-leg/utils/orderProgress'
|
||||
|
||||
export type ClientWarehouseType = 'DOMESTIC' | 'FBA' | 'OVERSEAS'
|
||||
export type ClientWarehouse = PlatformReceivingWarehouse & {
|
||||
@@ -46,7 +47,7 @@ function clientStatus(status: ApiFirstLegStatus): FirstLegOrder['status'] {
|
||||
if (status === 'REJECTED') return 'PENDING_REVIEW'
|
||||
if (status === 'APPROVED' || status === 'ACCEPTED' || status === 'PROCESSING') return 'WAIT_MEASURE'
|
||||
if (status === 'COMPLETED') return 'COMPLETED'
|
||||
if (status === 'CANCELLED') return 'PENDING_REVIEW'
|
||||
if (status === 'CANCELLED') return 'CANCELLED'
|
||||
return 'PENDING_REVIEW'
|
||||
}
|
||||
|
||||
@@ -119,6 +120,7 @@ function savePayload(draft: FirstLegOrderDraft, warehouse: ClientWarehouse, cust
|
||||
productImageFileId: item.productImageFileId || undefined,
|
||||
})),
|
||||
pickupMethod: draft.pickupMethod,
|
||||
expressTrackingNo: draft.pickupMethod === 'SELF_EXPRESS' ? draft.trackingNumber.trim() || undefined : undefined,
|
||||
receivingWarehouseId: warehouse.id,
|
||||
receivingWarehouseName: warehouse.name,
|
||||
channelCode: draft.channelCode,
|
||||
@@ -159,8 +161,10 @@ function orderWarehouseSnapshot(order: MerchantFirstLegOrder, warehouse?: Platfo
|
||||
id: String(order.receivingWarehouseId),
|
||||
code: warehouse?.code ?? '',
|
||||
name: order.receivingWarehouseName,
|
||||
province: warehouse?.province ?? '',
|
||||
city: warehouse?.city ?? '',
|
||||
// Order stores the complete formatted address, including province and city.
|
||||
// Do not prefix this snapshot with fields from the current warehouse master.
|
||||
province: '',
|
||||
city: '',
|
||||
address: order.receivingWarehouseAddress,
|
||||
}
|
||||
}
|
||||
@@ -198,6 +202,7 @@ function timeline(detail: MerchantFirstLegOrderDetail): FirstLegOrderTimelineIte
|
||||
|
||||
function businessSummary(summary?: MerchantUnifiedOrderRow): FirstLegOrder['businessSummary'] {
|
||||
return {
|
||||
transportFragments: [],
|
||||
customerFeeConfirmationRequired: summary?.customerFeeConfirmationRequired ?? false,
|
||||
totalPackageCount: summary?.totalPackageCount ?? null,
|
||||
actualGrossWeightKg: summary?.actualGrossWeightKg ?? null,
|
||||
@@ -220,8 +225,8 @@ function businessSummary(summary?: MerchantUnifiedOrderRow): FirstLegOrder['busi
|
||||
cabinetNo: summary?.transport?.cabinetNo ?? '',
|
||||
vesselName: summary?.transport?.vesselName ?? '',
|
||||
voyageNo: summary?.transport?.voyageNo ?? '',
|
||||
sailingAt: summary?.transport?.sailingAt ?? '',
|
||||
portArrivalAt: summary?.transport?.portArrivalAt ?? '',
|
||||
estimatedSailingAt: summary?.transport?.estimatedSailingAt ?? '',
|
||||
estimatedPortArrivalAt: summary?.transport?.estimatedPortArrivalAt ?? '',
|
||||
inboundId: summary?.inboundId == null ? '' : String(summary.inboundId),
|
||||
inboundVersion: summary?.inboundVersion ?? null,
|
||||
inboundCode: summary?.inboundCode ?? '',
|
||||
@@ -339,54 +344,25 @@ function mapUnifiedOrderRow(summary: MerchantUnifiedOrderRow, warehouses: Platfo
|
||||
trackingNumber: summary.expressTrackingNo ?? summary.delivery?.trackingNo ?? '', skuNos: summary.skuNos ?? [], totalNetWeightKg: summary.totalNetWeightKg ?? null,
|
||||
totalQuantity: summary.totalQuantity ?? null, chargeableVolumeCbm: summary.chargeableVolumeCbm ?? null,
|
||||
inboundedAt: summary.inboundCompletedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: summary.customerRemark ?? '', operatorName: '',
|
||||
status: summary.mainStatus, version: 0, items: [], timeline: [], businessSummary: businessSummary(summary),
|
||||
status: summary.mainStatus, version: summary.orderVersion, items: [], timeline: [], businessSummary: businessSummary(summary),
|
||||
createdAt: summary.createdAt, updatedAt: summary.updatedAt, tradeTerm: '', destinationCountryCode: '',
|
||||
destinationWarehouseId: summary.destinationWarehouseId == null ? '' : String(summary.destinationWarehouseId),
|
||||
destinationWarehouseName: summary.destinationWarehouseName ?? '', pickupMethod: summary.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||
channelName: summary.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: 'BUY_DECLARATION', customsInspection: false,
|
||||
channelName: summary.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: summary.taxMode ?? 'BUY_DECLARATION', customsInspection: summary.customsInspection ?? false,
|
||||
destinationType: summary.destinationType ?? 'PRIVATE', amazonWarehouseCode: summary.destinationCode ?? '', shipmentId: summary.shipmentId ?? '',
|
||||
requestedPickupAt: summary.requestedPickupAt ?? '', receivingTime: '', submittedAt: '', completedAt: '',
|
||||
}
|
||||
}
|
||||
|
||||
function mapFirstLegOrderRow(row: MerchantFirstLegOrderRow): FirstLegOrder {
|
||||
const skuNos = Array.isArray(row.skuNos)
|
||||
? row.skuNos
|
||||
: (row.skuNos ?? '').split('、').map((value) => value.trim()).filter(Boolean)
|
||||
const resolvedSkuNos = skuNos.length ? skuNos : (row.cargoes ?? [])
|
||||
.map((cargo) => cargo.skuNo?.trim())
|
||||
.filter((value): value is string => Boolean(value))
|
||||
const uniqueSkuNos = [...new Set(resolvedSkuNos)]
|
||||
return {
|
||||
id: String(row.orderId), orderNo: row.orderNo, referenceNo: row.referenceId ?? '', transportMode: null,
|
||||
businessType: 'EXPORT', fulfillmentType: row.fulfillmentType ?? 'STANDARD', lxCode: row.lxCode ?? '', origin: '', destination: row.destinationWarehouseName ?? '', receivingWarehouseId: '',
|
||||
receivingWarehouseName: '', receivingWarehouseSnapshot: null, expectedDepartureDate: '', etd: '', eta: '',
|
||||
shipperPartyId: '', shipperPartySnapshot: null, shipper: '', consigneePartyId: '', consigneePartySnapshot: null,
|
||||
consignee: row.receivingCompanyName ?? '', expressCompanyName: row.expressCompany ?? '', trackingNumber: row.trackingNo ?? '',
|
||||
skuNos: uniqueSkuNos, totalNetWeightKg: row.totalNetWeightKg, totalQuantity: row.totalQuantity,
|
||||
chargeableVolumeCbm: null, inboundedAt: row.inboundedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: row.remark ?? '',
|
||||
operatorName: '', status: clientStatus(row.status), version: 0, items: [], timeline: [],
|
||||
businessSummary: {
|
||||
...businessSummary(), totalPackageCount: row.packageCount, actualGrossWeightKg: row.totalGrossWeightKg ?? row.weightKg,
|
||||
actualVolumeCbm: row.totalVolumeCbm, chargeableWeightKg: null,
|
||||
inboundId: row.inboundId == null ? '' : String(row.inboundId), inboundCode: row.inboundCode ?? '',
|
||||
},
|
||||
createdAt: row.createdAt, updatedAt: row.createdAt, tradeTerm: '', destinationCountryCode: '', destinationWarehouseId: '',
|
||||
destinationWarehouseName: row.destinationWarehouseName ?? '', pickupMethod: row.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||
channelName: row.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: 'BUY_DECLARATION',
|
||||
customsInspection: false, destinationType: row.destinationType ?? 'PRIVATE', amazonWarehouseCode: '',
|
||||
shipmentId: row.shipmentId ?? row.internationalOrderNo ?? '', requestedPickupAt: '', receivingTime: '', submittedAt: '', completedAt: '',
|
||||
}
|
||||
}
|
||||
|
||||
function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: PlatformReceivingWarehouse[]): FirstLegOrder {
|
||||
if (!detail?.summary || !detail.order?.order) throw new Error('订单详情数据不完整,请刷新列表后重试')
|
||||
const mapped = mapOrder(detail.order.order, warehouses, detail.order)
|
||||
mapped.id = String(detail.summary.orderId)
|
||||
mapped.status = detail.summary.mainStatus
|
||||
const rawStatus = detail.order.order.status
|
||||
mapped.status = rawStatus === 'CANCELLED' || rawStatus === 'DRAFT' ? rawStatus : detail.summary.mainStatus
|
||||
mapped.fulfillmentType = detail.summary.fulfillmentType ?? mapped.fulfillmentType
|
||||
mapped.lxCode = detail.summary.lxCode ?? mapped.lxCode
|
||||
mapped.businessSummary = businessSummary(detail.summary)
|
||||
mapped.businessSummary = { ...businessSummary(detail.summary), transportFragments: detail.transportFragments }
|
||||
mapped.timeline = unifiedTimeline(detail)
|
||||
const summary = mapUnifiedOrderRow(detail.summary, warehouses)
|
||||
mapped.referenceNo = summary.referenceNo
|
||||
@@ -406,59 +382,6 @@ function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: P
|
||||
return mapped
|
||||
}
|
||||
|
||||
type OrderListReadResult =
|
||||
| { source: 'first-leg'; records: MerchantFirstLegOrderRow[] }
|
||||
| { source: 'unified'; records: MerchantUnifiedOrderRow[]; drafts: MerchantFirstLegOrderRow[] }
|
||||
|
||||
interface ClientOrderReadQuery extends MerchantUnifiedOrderQuery {
|
||||
fbaCode?: string
|
||||
draftOnly?: boolean
|
||||
includeDrafts?: boolean
|
||||
}
|
||||
|
||||
function legacyQuery(query: ClientOrderReadQuery, status?: ApiFirstLegStatus) {
|
||||
return {
|
||||
keyword: query.keyword,
|
||||
status,
|
||||
createdFrom: query.createdFrom,
|
||||
createdTo: query.createdTo,
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrdersForClient(query: ClientOrderReadQuery = {}): Promise<OrderListReadResult> {
|
||||
if (query.draftOnly) {
|
||||
const response = await getMerchantFirstLegOrders(legacyQuery(query, 'DRAFT'))
|
||||
return { source: 'first-leg', records: response.records }
|
||||
}
|
||||
|
||||
const unifiedQuery: MerchantUnifiedOrderQuery = {
|
||||
keyword: query.keyword,
|
||||
orderNo: query.orderNo,
|
||||
mainStatus: query.mainStatus,
|
||||
receivingWarehouseId: query.receivingWarehouseId,
|
||||
destinationWarehouseId: query.destinationWarehouseId,
|
||||
inboundCode: query.inboundCode,
|
||||
createdFrom: query.createdFrom,
|
||||
createdTo: query.createdTo,
|
||||
fbaCode: query.fbaCode,
|
||||
page: query.page,
|
||||
size: query.size,
|
||||
}
|
||||
try {
|
||||
const [response, draftResponse] = await Promise.all([
|
||||
getMerchantUnifiedOrders(unifiedQuery),
|
||||
query.includeDrafts
|
||||
? getMerchantFirstLegOrders(legacyQuery(query, 'DRAFT'))
|
||||
: Promise.resolve({ records: [] as MerchantFirstLegOrderRow[] }),
|
||||
])
|
||||
return { source: 'unified', records: response.records, drafts: draftResponse.records }
|
||||
} catch (error) {
|
||||
if (!isUnifiedOrderQueryUnavailable(error)) throw error
|
||||
const response = await getMerchantFirstLegOrders(legacyQuery(query))
|
||||
return { source: 'first-leg', records: response.records }
|
||||
}
|
||||
}
|
||||
|
||||
function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
return {
|
||||
id: String(item.id), code: item.warehouseCode, name: item.warehouseName, province: '',
|
||||
@@ -468,21 +391,34 @@ function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
}
|
||||
}
|
||||
|
||||
export interface DraftEditSession {
|
||||
readonly orderId: string
|
||||
readonly expectedVersion: number
|
||||
}
|
||||
|
||||
export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', () => {
|
||||
const orders = ref<FirstLegOrder[]>([])
|
||||
const pendingSubmitKeys = new Map<string, string>()
|
||||
const orderDetails = ref<Record<string, FirstLegOrder>>({})
|
||||
const total = ref(0)
|
||||
const queueCounts = ref<OrderQueueCounts>({ all: 0, fee: 0, customs: 0, draft: 0, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 })
|
||||
const orderProgress = ref<Record<string, MerchantOrderProgress>>({})
|
||||
const queryChannelNames = ref<string[]>([])
|
||||
let listRequest = 0
|
||||
const submittingIds = new Set<string>()
|
||||
|
||||
function beginDraftEdit(detail: FirstLegOrder): DraftEditSession {
|
||||
if (!canClientEditFirstLegOrder(detail.status) || !Number.isSafeInteger(detail.version) || detail.version < 0) throw new Error('请重新打开草稿详情后编辑')
|
||||
return Object.freeze({ orderId: detail.id, expectedVersion: detail.version })
|
||||
}
|
||||
const warehouses = ref<ClientWarehouse[]>([])
|
||||
const loading = ref(false)
|
||||
const loadedFromApi = ref(false)
|
||||
const loadError = ref('')
|
||||
const warehouseLoadError = ref('')
|
||||
const draftLoadError = ref('')
|
||||
const loadedWarehouseTypes = ref<ClientWarehouseType[]>([])
|
||||
const warehouseTypeRequests = new Map<ClientWarehouseType, Promise<ClientWarehouse[]>>()
|
||||
const activeCount = computed(() => orders.value.filter((item) => item.status !== 'DRAFT' && item.status !== 'DELIVERED').length)
|
||||
const pendingCount = computed(() => orders.value.filter((item) => item.status === 'PENDING_REVIEW').length)
|
||||
|
||||
function getById(id: string) { return orders.value.find((item) => item.id === id) }
|
||||
function getById(id: string) { return orders.value.find((item) => item.id === id) ?? orderDetails.value[id] }
|
||||
|
||||
async function loadWarehouseType(warehouseType: ClientWarehouseType, force = false) {
|
||||
if (warehouseType === 'DOMESTIC' && force) warehouseLoadError.value = ''
|
||||
@@ -509,27 +445,48 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
}
|
||||
}
|
||||
|
||||
async function load(query: ClientOrderReadQuery = {}) {
|
||||
async function load(query: MerchantOrderWorkbenchQuery = {}) {
|
||||
const request = ++listRequest
|
||||
loading.value = true
|
||||
loadedFromApi.value = true
|
||||
loadError.value = ''
|
||||
warehouseLoadError.value = ''
|
||||
draftLoadError.value = ''
|
||||
loadedWarehouseTypes.value = []
|
||||
warehouseTypeRequests.clear()
|
||||
orders.value = []
|
||||
warehouses.value = []
|
||||
const [orderResult, warehouseResult] = await Promise.allSettled([getOrdersForClient(query), loadWarehouseType('DOMESTIC', true)])
|
||||
if (warehouseResult.status === 'rejected' && !warehouseLoadError.value) warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||
total.value = 0
|
||||
// Keep the last confirmed category counts while refreshing; replace them only after validation.
|
||||
orderProgress.value = {}
|
||||
const [orderResult, warehouseResult] = await Promise.allSettled([
|
||||
getMerchantOrderWorkbench(query), loadWarehouseType('DOMESTIC'),
|
||||
])
|
||||
if (request !== listRequest) return 0
|
||||
if (warehouseResult.status === 'rejected') warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||
if (orderResult.status === 'fulfilled') {
|
||||
orders.value = orderResult.value.source === 'unified'
|
||||
? [
|
||||
...orderResult.value.drafts.map(mapFirstLegOrderRow),
|
||||
...orderResult.value.records.map((item) => mapUnifiedOrderRow(item, warehouses.value)),
|
||||
]
|
||||
: orderResult.value.records.map(mapFirstLegOrderRow)
|
||||
} else {
|
||||
loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||
try {
|
||||
const result = orderResult.value
|
||||
const expectedPage = query.page ?? 1, size = query.size ?? 10
|
||||
const count = Number(result.page.total), pages = Math.ceil(count / size)
|
||||
if (!Number.isSafeInteger(count) || count < 0 || Number(result.page.page) !== expectedPage
|
||||
|| Number(result.page.size) !== size || Number(result.page.pages) !== pages
|
||||
|| result.page.records.length !== Math.min(size, Math.max(0, count - (expectedPage - 1) * size))
|
||||
|| new Set(result.page.records.map(row => String(row.orderId))).size !== result.page.records.length
|
||||
|| ['all', 'fee', 'customs', 'draft', 'loaded', 'declared', 'cleared', 'scheduled', 'delivering', 'delivered'].some(key => { const value = result.queues[key as keyof typeof result.queues]; return !Number.isSafeInteger(Number(value)) || Number(value) < 0 })
|
||||
|| Number(result.queues[query.queue ?? 'all']) !== count
|
||||
|| !Array.isArray(result.progress) || result.progress.length !== result.page.records.length
|
||||
|| new Set(result.progress.map(p => String(p.orderId))).size !== result.progress.length
|
||||
|| result.progress.some(p => !result.page.records.some(row => String(row.orderId) === String(p.orderId))
|
||||
|| !['none', 'loaded', 'declared', 'cleared', 'scheduled', 'delivering', 'delivered'].includes(p.stage) || typeof p.partial !== 'boolean')
|
||||
|| !Array.isArray(result.channelNames)) {
|
||||
loadError.value = '订单分页数据不完整,请重新加载'
|
||||
} else {
|
||||
orders.value = result.page.records.map(item => mapUnifiedOrderRow(item, warehouses.value))
|
||||
total.value = count
|
||||
queueCounts.value = Object.fromEntries(Object.entries(result.queues).map(([key, value]) => [key, Number(value)])) as OrderQueueCounts
|
||||
orderProgress.value = Object.fromEntries(result.progress.map(p => [String(p.orderId), p]))
|
||||
queryChannelNames.value = result.channelNames
|
||||
}
|
||||
} catch { loadError.value = '订单分页数据不完整,请重新加载' }
|
||||
} else loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||
if (loadError.value) {
|
||||
queueCounts.value = { all: 0, fee: 0, customs: 0, draft: 0, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 }
|
||||
}
|
||||
loading.value = false
|
||||
return orders.value.length
|
||||
@@ -538,38 +495,22 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
function upsertOrder(mapped: FirstLegOrder) {
|
||||
const index = orders.value.findIndex((item) => item.id === mapped.id)
|
||||
if (index >= 0) orders.value[index] = mapped
|
||||
else orders.value.unshift(mapped)
|
||||
orderDetails.value[mapped.id] = mapped
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function loadLegacyDetail(id: string, listOrder?: FirstLegOrder) {
|
||||
async function loadOrderAggregate(id: string) {
|
||||
const detail = await getMerchantFirstLegOrder(id)
|
||||
const mapped = mapOrder(detail.order, warehouses.value, detail)
|
||||
// Older detail responses may omit newly added dropship fields. Keep the
|
||||
// values already returned by the list row so editing a draft does not
|
||||
// clear the persisted LX code in the form.
|
||||
if (detail.order.fulfillmentType == null && listOrder?.fulfillmentType) {
|
||||
mapped.fulfillmentType = listOrder.fulfillmentType
|
||||
}
|
||||
if (detail.order.lxCode == null && listOrder?.lxCode) {
|
||||
mapped.lxCode = listOrder.lxCode
|
||||
}
|
||||
return upsertOrder(mapped)
|
||||
}
|
||||
|
||||
async function loadUnifiedDetail(id: string) {
|
||||
try {
|
||||
const detail = await getMerchantUnifiedOrder(id)
|
||||
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value))
|
||||
} catch (error) {
|
||||
if (!isUnifiedOrderQueryUnavailable(error)) throw error
|
||||
return loadLegacyDetail(id)
|
||||
}
|
||||
return upsertOrder(mapOrder(detail.order, warehouses.value, detail))
|
||||
}
|
||||
|
||||
async function loadDetail(id: string) {
|
||||
const listOrder = getById(id)
|
||||
return listOrder?.status === 'DRAFT' ? loadLegacyDetail(id, listOrder) : loadUnifiedDetail(id)
|
||||
delete orderProgress.value[id]
|
||||
const detail = await getMerchantUnifiedOrder(id)
|
||||
const progress = requireOrderProgress(id, detail.progress)
|
||||
const mapped = mapUnifiedOrderDetail(detail, warehouses.value)
|
||||
orderProgress.value[id] = progress
|
||||
return upsertOrder(mapped)
|
||||
}
|
||||
|
||||
async function loadWarehouseDetail(id: string) {
|
||||
@@ -588,16 +529,32 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string) {
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||
const warehouse = prepareDraftForSave(draft, warehouses.value)
|
||||
if (id) {
|
||||
const order = getById(id)
|
||||
if (!order || !canClientEditFirstLegOrder(order.status)) throw new Error('当前订单状态不允许编辑')
|
||||
await updateMerchantFirstLegOrder(id, savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(id)
|
||||
if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑')
|
||||
const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) }
|
||||
await updateMerchantFirstLegOrder(id, payload, createIdempotencyKey(`first-leg-edit-${id}`))
|
||||
const saved = await loadOrderAggregate(id)
|
||||
return saved
|
||||
}
|
||||
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(String(createdId))
|
||||
return loadOrderAggregate(String(createdId))
|
||||
}
|
||||
|
||||
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 字取消原因')
|
||||
const payload = { expectedVersion, reason: reason.trim() }
|
||||
await cancelMerchantFirstLegOrder(id, payload, createIdempotencyKey(`first-leg-cancel-${id}`))
|
||||
orders.value = orders.value.filter(order => order.id !== id)
|
||||
}
|
||||
|
||||
async function prepareCancellation(id: string) {
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '审核中', APPROVED: '已审核', ACCEPTED: '已接单', REJECTED: '已退回' }
|
||||
if (!Object.hasOwn(labels, order.status)) throw new Error('当前订单状态不允许取消,请刷新订单查看最新进度')
|
||||
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
return { id, expectedVersion: order.version, businessNo: order.orderNo || order.inboundCode || '—', statusLabel: labels[order.status] }
|
||||
}
|
||||
|
||||
async function saveDraftBatch(
|
||||
@@ -614,21 +571,22 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
|
||||
async function submitSaved(id: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
if (companyAuditStatus && companyAuditStatus !== 'ACTIVE') throw new Error('企业资料尚未审核通过,请先完善企业资料并等待平台审核')
|
||||
const idempotencyKey = pendingSubmitKeys.get(id) ?? createIdempotencyKey(`first-leg-submit-${id}`)
|
||||
pendingSubmitKeys.set(id, idempotencyKey)
|
||||
await submitMerchantFirstLegOrder(id, idempotencyKey)
|
||||
pendingSubmitKeys.delete(id)
|
||||
return loadUnifiedDetail(id)
|
||||
}
|
||||
|
||||
async function submit(draft: FirstLegOrderDraft, customerName: string, id?: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
const order = await saveDraft(draft, customerName, id)
|
||||
return submitSaved(order.id, companyAuditStatus)
|
||||
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||
submittingIds.add(id)
|
||||
try {
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
if (order.status !== 'DRAFT') 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}`))
|
||||
return await loadOrderAggregate(id)
|
||||
} finally {
|
||||
submittingIds.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDraftDetail(id: string) {
|
||||
return loadLegacyDetail(id, getById(id))
|
||||
return loadOrderAggregate(id)
|
||||
}
|
||||
|
||||
return { orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError, activeCount, pendingCount, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, saveDraft, saveDraftBatch, submitSaved, submit }
|
||||
return { orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
import { requireOrderProgress } from '../utils/orderProgress.ts'
|
||||
|
||||
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 row = (id, mainStatus = 'LOADED') => ({ orderId: String(id), orderNo: `FL-${id}`, mainStatus, orderVersion: 7 })
|
||||
function result(page = 1, size = 10, total = 215) {
|
||||
return {
|
||||
page: { page, size, total, pages: Math.ceil(total / size), records: Array.from({ length: Math.min(size, Math.max(0, total - (page - 1) * size)) }, (_, i) => row((page - 1) * size + i + 1)) },
|
||||
queues: { all: total, fee: 2, customs: 1, draft: 3, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 }, channelNames: ['AIR', 'SEA'],
|
||||
progress: Array.from({ length: Math.min(size, Math.max(0, total - (page - 1) * size)) }, (_, i) => ({ orderId: String((page - 1) * size + i + 1), stage: 'loaded', partial: false })),
|
||||
}
|
||||
}
|
||||
function deferred() { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b }); return { promise, resolve, reject } }
|
||||
function harness(t, read) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = [], details = [], warehouseCalls = []
|
||||
const deps = {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': {},
|
||||
'@/modules/first-leg/api/unifiedOrders': {
|
||||
getMerchantOrderWorkbench: query => { calls.push(structuredClone(query)); return read(query) },
|
||||
getMerchantUnifiedOrder: async id => {
|
||||
details.push(id)
|
||||
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/warehousePagination': { loadAllWarehouseRecords: async type => { warehouseCalls.push(type); return [] } },
|
||||
'@/modules/first-leg/utils/orderProgress': { requireOrderProgress },
|
||||
}
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||
return { store: exports.useFirstLegOrdersStore(), calls, details, warehouseCalls }
|
||||
}
|
||||
|
||||
test('loads beyond 200 with server totals and forwards every filter using one request per page', async t => {
|
||||
const h = harness(t, q => result(q.page, q.size))
|
||||
const query = { page: 21, size: 10, cargoKeyword: 'SKU', channelName: 'SEA', receivingWarehouseId: '42', destinationType: 'FBA', trackingNumber: 'TRACK', mainStatus: 'LOADED', queue: 'all', createdFrom: '2026-10-01T00:00:00', createdTo: '2026-10-03T23:59:59.999' }
|
||||
assert.equal(await h.store.load(query), 10)
|
||||
assert.equal(h.store.orders[0].id, '201')
|
||||
assert.equal(h.store.total, 215)
|
||||
assert.deepEqual(h.calls, [query])
|
||||
assert.deepEqual(h.store.queueCounts, { all: 215, fee: 2, customs: 1, draft: 3, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 })
|
||||
assert.deepEqual(h.store.queryChannelNames, ['AIR', 'SEA'])
|
||||
await h.store.load({ page: 22, size: 10 })
|
||||
assert.deepEqual(h.store.orders.map(item => item.id), ['211', '212', '213', '214', '215'])
|
||||
assert.equal(h.calls.length, 2)
|
||||
assert.deepEqual(h.warehouseCalls, ['DOMESTIC'])
|
||||
})
|
||||
|
||||
test('late success cannot replace newer rows, counts, channels or loading state', async t => {
|
||||
const a = deferred(), b = deferred()
|
||||
const h = harness(t, q => q.page === 1 ? a.promise : b.promise)
|
||||
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||
b.resolve(result(2)); await second
|
||||
a.resolve(result(1, 10, 999)); await first
|
||||
assert.equal(h.store.orders[0].id, '11'); assert.equal(h.store.total, 215)
|
||||
assert.equal(h.store.queueCounts.all, 215); assert.equal(h.store.loading, false)
|
||||
})
|
||||
|
||||
test('late failure cannot clear the current page and an older completion cannot stop loading a newer page', async t => {
|
||||
const a = deferred(), b = deferred(), c = deferred()
|
||||
const h = harness(t, q => [a, b, c][q.page - 1].promise)
|
||||
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||
a.resolve(result(1)); await first
|
||||
assert.equal(h.store.loading, true); assert.equal(h.store.orders.length, 0)
|
||||
const third = h.store.load({ page: 3 })
|
||||
c.resolve(result(3)); await third
|
||||
b.reject(new Error('old failure')); await second
|
||||
assert.equal(h.store.orders[0].id, '21'); assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
test('current failure clears stale records and totals, never falls back, and retry restores the page', async t => {
|
||||
let fail = false
|
||||
const h = harness(t, () => fail ? Promise.reject(new Error('查询失败')) : result())
|
||||
await h.store.load(); fail = true; await h.store.load()
|
||||
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||
assert.equal(h.store.queueCounts.all, 0); assert.equal(h.store.loadError, '查询失败')
|
||||
assert.equal(h.store.loading, false)
|
||||
fail = false; await h.store.load(); assert.equal(h.store.orders.length, 10)
|
||||
assert.equal(h.calls.length, 3); assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
test('rejects inconsistent metadata, truncated pages and duplicate rows without displaying partial data', async t => {
|
||||
let response
|
||||
const h = harness(t, () => response)
|
||||
const corruptions = [r => { r.page.total = -1 }, r => { r.page.pages = 1 }, r => { r.page.page = 2 }, r => { r.page.records.pop() }, r => { r.page.records[1] = r.page.records[0] }, r => { r.queues.all = 99 }, r => { delete r.queues }, r => { r.channelNames = null }]
|
||||
for (const corrupt of corruptions) {
|
||||
response = result(); corrupt(response); await h.store.load()
|
||||
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||
assert.match(h.store.loadError, /分页数据不完整/); assert.equal(h.store.loading, false)
|
||||
}
|
||||
})
|
||||
|
||||
test('draft and cancelled rows retain authoritative versions; off-page detail cannot inflate list or totals', async t => {
|
||||
const response = result(1, 10, 2)
|
||||
response.page.records = [row(1, 'DRAFT'), row(2, 'CANCELLED')]
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load()
|
||||
assert.deepEqual(h.store.orders.map(item => [item.status, item.version]), [['DRAFT', 7], ['CANCELLED', 7]])
|
||||
await h.store.loadDetail('900')
|
||||
assert.equal(h.store.orders.length, 2); assert.equal(h.store.total, 2)
|
||||
assert.equal(h.store.getById('900').status, 'DRAFT')
|
||||
})
|
||||
|
||||
test('queue total is checked against the selected queue rather than all orders', async t => {
|
||||
const response = result(1, 10, 2)
|
||||
response.queues = { all: 215, fee: 2, customs: 1, draft: 3, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 }
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load({ queue: 'fee' })
|
||||
assert.equal(h.store.total, 2); assert.equal(h.store.queueCounts.all, 215)
|
||||
assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
|
||||
test('retains server progress and rejects missing or foreign progress without inferring milestones', async t => {
|
||||
let response = result()
|
||||
response.progress[0] = { orderId: '1', stage: 'scheduled', partial: true }
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load()
|
||||
assert.deepEqual(h.store.orderProgress['1'], response.progress[0])
|
||||
response = result(); response.progress[0].orderId = 'foreign'
|
||||
await h.store.load()
|
||||
assert.match(h.store.loadError, /分页数据不完整/)
|
||||
assert.deepEqual(h.store.orderProgress, {})
|
||||
response = result(); delete response.queues.cleared
|
||||
await h.store.load(); assert.match(h.store.loadError, /分页数据不完整/)
|
||||
})
|
||||
|
||||
|
||||
test('category counts remain visible throughout refresh and update together after the response is validated', async t => {
|
||||
const pending = deferred()
|
||||
let refreshing = false
|
||||
const h = harness(t, () => refreshing ? pending.promise : result())
|
||||
await h.store.load()
|
||||
const counts = h.store.queueCounts
|
||||
refreshing = true
|
||||
const request = h.store.load({ queue: 'fee' })
|
||||
assert.equal(h.store.loading, true)
|
||||
assert.equal(h.store.queueCounts, counts)
|
||||
assert.equal(h.store.queueCounts.fee, 2)
|
||||
const updated = result(1, 10, 3)
|
||||
updated.queues = { ...updated.queues, all: 216, fee: 3 }
|
||||
pending.resolve(updated)
|
||||
await request
|
||||
assert.equal(h.store.queueCounts.all, 216)
|
||||
assert.equal(h.store.queueCounts.fee, 3)
|
||||
assert.equal(h.store.loading, false)
|
||||
})
|
||||
|
||||
test('rapid category switches preserve counts and ignore an older response while the newest request is pending', async t => {
|
||||
const older = deferred(), latest = deferred()
|
||||
const h = harness(t, q => q.queue === 'fee' ? older.promise : q.queue === 'customs' ? latest.promise : result())
|
||||
await h.store.load()
|
||||
const oldRequest = h.store.load({ queue: 'fee' })
|
||||
const newRequest = h.store.load({ queue: 'customs' })
|
||||
const oldResult = result(1, 10, 2); oldResult.queues.all = 999
|
||||
older.resolve(oldResult); await oldRequest
|
||||
assert.equal(h.store.queueCounts.all, 215)
|
||||
assert.equal(h.store.loading, true)
|
||||
const newResult = result(1, 10, 1); newResult.queues.all = 216
|
||||
latest.resolve(newResult); await newRequest
|
||||
assert.equal(h.store.queueCounts.all, 216)
|
||||
assert.equal(h.store.total, 1)
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
import type {
|
||||
FirstLegOrderStatus,
|
||||
FirstLegTransportMode,
|
||||
@@ -64,6 +65,7 @@ export interface FirstLegOrderTimelineItem {
|
||||
}
|
||||
|
||||
export interface FirstLegOrderBusinessSummary {
|
||||
transportFragments: MerchantTransportFragment[]
|
||||
customerFeeConfirmationRequired: boolean
|
||||
totalPackageCount: number | null
|
||||
actualGrossWeightKg: number | null
|
||||
@@ -87,8 +89,8 @@ export interface FirstLegOrderBusinessSummary {
|
||||
cabinetNo: string
|
||||
vesselName: string
|
||||
voyageNo: string
|
||||
sailingAt: string
|
||||
portArrivalAt: string
|
||||
estimatedSailingAt: string
|
||||
estimatedPortArrivalAt: string
|
||||
inboundId: string
|
||||
inboundVersion: number | null
|
||||
inboundCode: string
|
||||
@@ -181,6 +183,7 @@ export type FirstLegOrderDraft = Omit<Pick<
|
||||
| 'destinationWarehouseId'
|
||||
| 'destinationWarehouseName'
|
||||
| 'pickupMethod'
|
||||
| 'trackingNumber'
|
||||
| 'channelCode'
|
||||
| 'channelName'
|
||||
| 'pricingTaxMode'
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { getMerchantUnifiedOrders } from '../api/unifiedOrders'
|
||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { isCustomsOrderCandidate } from './customsEligibility'
|
||||
|
||||
export interface CustomsDocumentRow {
|
||||
order: { id: string; orderNo: string | null; businessSummary: { inboundCode: string } }
|
||||
detail: MerchantCustomsContainer
|
||||
}
|
||||
|
||||
// Isolated from the shared order store: scan sequential pages, with at most
|
||||
// four document requests in flight. Inconsistent pagination must be visible.
|
||||
export async function readCustomsDocuments() {
|
||||
const records: CustomsDocumentRow[] = []
|
||||
const seen = new Set<string>()
|
||||
let expectedTotal: number | undefined
|
||||
let failedCount = 0
|
||||
const size = 200
|
||||
for (let page = 1; ; page += 1) {
|
||||
const response = await getMerchantUnifiedOrders({ page, size, taxMode: 'TAX_REFUND', loaded: true })
|
||||
const total = Number(response.total)
|
||||
const pages = Number(response.pages)
|
||||
if (!Number.isSafeInteger(total) || total < 0 || Number(response.page) !== page
|
||||
|| Number(response.size) !== size || pages !== Math.ceil(total / size)
|
||||
|| (expectedTotal !== undefined && total !== expectedTotal)
|
||||
|| response.records.length !== Math.min(size, Math.max(0, total - (page - 1) * size))) {
|
||||
throw new Error('订单分页数据不完整或已变化,请重新加载报关资料')
|
||||
}
|
||||
expectedTotal = total
|
||||
for (const row of response.records) {
|
||||
const id = String(row.orderId)
|
||||
if (seen.has(id)) throw new Error('订单分页存在重复记录,请重新加载报关资料')
|
||||
seen.add(id)
|
||||
}
|
||||
const candidates = response.records.filter(row => isCustomsOrderCandidate({ status: row.mainStatus, taxMode: row.taxMode ?? 'BUY_DECLARATION' }))
|
||||
for (let offset = 0; offset < candidates.length; offset += 4) {
|
||||
const results = await Promise.all(candidates.slice(offset, offset + 4).map(async row => {
|
||||
const id = String(row.orderId)
|
||||
try {
|
||||
const detail = await getMerchantCustomsForOrder(id)
|
||||
if (!detail.inbounds.some(item => item.orderId === id && item.taxMode === 'TAX_REFUND')) return null
|
||||
return { order: { id, orderNo: row.orderNo, businessSummary: { inboundCode: row.inboundCode ?? '' } }, detail }
|
||||
} catch (error) {
|
||||
if (!isMerchantCustomsUnavailable(error)) failedCount += 1
|
||||
return null
|
||||
}
|
||||
}))
|
||||
for (const result of results) if (result) records.push(result)
|
||||
}
|
||||
if (page >= pages) break
|
||||
}
|
||||
return { records, failedCount }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./customsEligibility.ts', import.meta.url), 'utf8')
|
||||
const exports = {}
|
||||
new Function('exports', ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText)(exports)
|
||||
|
||||
test('upload queue contains only customer uploads still required, while completed documents stay accessible', () => {
|
||||
const states = [null, {}, { status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED' },
|
||||
{ status: 'READY_TO_START', merchantStatus: 'DOCUMENT_UPLOADED' },
|
||||
{ status: 'DECLARING', merchantStatus: 'DECLARING' }, { status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED' }]
|
||||
for (const detail of states) assert.equal(exports.needsCustomsUpload(detail), false)
|
||||
assert.equal(exports.needsCustomsUpload({ status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }), true)
|
||||
for (const status of ['LOADED', 'DELIVERED', 'COMPLETED']) assert.equal(exports.isCustomsOrderCandidate({ status, taxMode: 'TAX_REFUND' }), true)
|
||||
})
|
||||
|
||||
test('upload status changes refresh server counts while initial detail reads do not reload the list', async () => {
|
||||
const page = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const block = page.slice(page.indexOf('function updateCustomsDetail('), page.indexOf('const detailOrder ='))
|
||||
const js = ts.transpileModule(block, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const states = {}, id = ref('one'), create = ref(false), detail = ref(false)
|
||||
let reloads = 0
|
||||
const update = new Function('customsByOrder', 'customsDialogOrderId', 'isCreatePage', 'isDetailPage', 'loadOrderPage', js + ';return updateCustomsDetail')(states, id, create, detail, async () => reloads++)
|
||||
update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 0)
|
||||
update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 0)
|
||||
update({ merchantStatus: 'DOCUMENT_UPLOADED' }); assert.equal(reloads, 1)
|
||||
assert.equal(states.one.merchantStatus, 'DOCUMENT_UPLOADED')
|
||||
detail.value = true; update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 1)
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { FirstLegOrder } from '../types/firstLegOrder'
|
||||
import type { MerchantCustomsContainer } from '../api/customs'
|
||||
|
||||
export function isCustomsOrderCandidate(order: Pick<FirstLegOrder, 'status' | 'taxMode'>): boolean {
|
||||
return order.taxMode === 'TAX_REFUND'
|
||||
&& (order.status === 'LOADED' || order.status === 'DELIVERED' || order.status === 'COMPLETED')
|
||||
}
|
||||
|
||||
export function needsCustomsUpload(detail: MerchantCustomsContainer | null | undefined): boolean {
|
||||
return detail?.status === 'WAITING_CUSTOMER_DOCUMENTS' && detail.merchantStatus === 'WAITING_UPLOAD'
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
FIRST_LEG_PROGRESS_STAGES,
|
||||
getFirstLegProgressIndex,
|
||||
getFirstLegStatusLabel,
|
||||
getFirstLegPickingStatusLabel,
|
||||
getFirstLegStatusTone,
|
||||
getFirstLegTransportModeLabel,
|
||||
summarizeFirstLegCargo,
|
||||
@@ -59,7 +60,22 @@ function validDraft() {
|
||||
}
|
||||
}
|
||||
|
||||
test('keeps picking states distinct from order completion and hides unknown internal codes', () => {
|
||||
assert.equal(getFirstLegPickingStatusLabel('PENDING'), '待拣货')
|
||||
assert.equal(getFirstLegPickingStatusLabel('IN_PROGRESS'), '拣货中')
|
||||
assert.equal(getFirstLegPickingStatusLabel('COMPLETED'), '拣货完成')
|
||||
assert.equal(getFirstLegPickingStatusLabel('NEW_INTERNAL_STATE'), '未知状态')
|
||||
assert.equal(getFirstLegPickingStatusLabel(null), '待更新')
|
||||
assert.equal(getFirstLegPickingStatusLabel(''), '待更新')
|
||||
})
|
||||
|
||||
test('uses the confirmed status and transport labels', () => {
|
||||
assert.equal(getFirstLegStatusLabel('CANCELLED'), '已取消')
|
||||
assert.equal(getFirstLegStatusLabel('NOT_A_STATUS'), '未知状态')
|
||||
assert.equal(getFirstLegStatusTone('CANCELLED'), 'info')
|
||||
assert.equal(getFirstLegProgressIndex('CANCELLED'), -1)
|
||||
assert.equal(canClientEditFirstLegOrder('CANCELLED'), false)
|
||||
assert.equal(canClientCancelFirstLegOrder('CANCELLED'), false)
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_MEASURE'), '待测量数据')
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_PALLETIZE'), '待组托')
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_SPLIT'), '待分柜')
|
||||
|
||||
@@ -19,6 +19,16 @@ export function getFirstLegStatusLabel(status: string) {
|
||||
return statusLabels.get(canonicalStatus as FirstLegOrderStatus) ?? '未知状态'
|
||||
}
|
||||
|
||||
export function getFirstLegPickingStatusLabel(status: string | null | undefined) {
|
||||
if (!status) return '待更新'
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
PENDING: '待拣货',
|
||||
IN_PROGRESS: '拣货中',
|
||||
COMPLETED: '拣货完成',
|
||||
}
|
||||
return labels[status] ?? '未知状态'
|
||||
}
|
||||
|
||||
export function getFirstLegTransportModeLabel(mode: FirstLegTransportMode | null) {
|
||||
if (!mode) return '运输方式待更新'
|
||||
return transportModeLabels.get(mode) ?? mode
|
||||
@@ -41,11 +51,11 @@ export function canClientCancelFirstLegOrder(status: FirstLegOrderStatus) {
|
||||
}
|
||||
|
||||
export const FIRST_LEG_PROGRESS_STAGES = FIRST_LEG_ORDER_STATUSES.filter(
|
||||
(item): item is (typeof FIRST_LEG_ORDER_STATUSES)[number] & { code: Exclude<FirstLegOrderStatus, 'DRAFT'> } => item.code !== 'DRAFT',
|
||||
(item): item is (typeof FIRST_LEG_ORDER_STATUSES)[number] & { code: Exclude<FirstLegOrderStatus, 'DRAFT' | 'CANCELLED'> } => item.code !== 'DRAFT' && item.code !== 'CANCELLED',
|
||||
)
|
||||
|
||||
export function getFirstLegProgressIndex(status: FirstLegOrderStatus) {
|
||||
if (status === 'DRAFT') return -1
|
||||
if (status === 'DRAFT' || status === 'CANCELLED') return -1
|
||||
return FIRST_LEG_PROGRESS_STAGES.findIndex((item) => item.code === status)
|
||||
}
|
||||
|
||||
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
const source = readFileSync(new URL('./orderProgress.ts', import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||
const exports = {}
|
||||
new Function('exports', code)(exports)
|
||||
test('prototype queues preserve order and distinguish partial progress from completion', () => {
|
||||
assert.deepEqual(exports.ORDER_QUEUES.slice(0, 7).map(q => q.key), ['all','fee','loaded','declared','cleared','scheduled','delivering'])
|
||||
assert.equal(exports.orderProgressLabel({ stage: 'scheduled', partial: true }), '部分已排车')
|
||||
assert.equal(exports.orderProgressLabel({ stage: 'cleared', partial: false }), '已清关')
|
||||
assert.equal(exports.orderProgressLabel({ stage: 'none', partial: false }), '—')
|
||||
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 }), /订单履约进度不完整/)
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { MerchantOrderProgress, OrderQueue } from '../api/unifiedOrders'
|
||||
|
||||
export const ORDER_QUEUES: ReadonlyArray<{ key: OrderQueue; label: string; todo?: boolean }> = [
|
||||
{ key: 'all', label: '全部' },
|
||||
{ key: 'fee', label: '确认计费重', todo: true },
|
||||
{ key: 'loaded', label: '装柜完成' },
|
||||
{ key: 'declared', label: '已报关' },
|
||||
{ key: 'cleared', label: '已清关' },
|
||||
{ key: 'scheduled', label: '已排车' },
|
||||
{ key: 'delivering', label: '派送中' },
|
||||
{ key: 'delivered', label: '派送完成' },
|
||||
{ key: 'customs', label: '上传资料', todo: true },
|
||||
{ key: 'draft', label: '草稿' },
|
||||
]
|
||||
|
||||
export function orderProgressLabel(progress?: MerchantOrderProgress) {
|
||||
if (!progress || progress.stage === 'none') return '—'
|
||||
const label = ORDER_QUEUES.find(q => q.key === progress.stage)?.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
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
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('./transportFacts.ts', import.meta.url), 'utf8')
|
||||
const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
runInNewContext(javascript, { exports })
|
||||
const rows = exports.customerTransportRows
|
||||
|
||||
test('split inbound fragments retain separate cabinet facts and actual/estimated times', () => {
|
||||
const result = rows([
|
||||
{ inboundCode: 'NY-1', cabinetNo: 'D1', containerNo: 'TSTU0000001', nodes: [
|
||||
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-05T09:00:00', estimatedAt: null, providerCode: 'MANUAL' },
|
||||
{ standardNode: 'DEPARTED_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-07T08:00:00', providerCode: 'MATSON' },
|
||||
] },
|
||||
{ inboundCode: 'NY-2', cabinetNo: 'D2', containerNo: 'TSTU0000002', nodes: [
|
||||
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-06T10:00:00', estimatedAt: null, providerCode: 'MATSON' },
|
||||
] },
|
||||
])
|
||||
assert.equal(result.length, 3)
|
||||
assert.equal(result[0].nodeLabel, '已进港')
|
||||
assert.equal(result[0].source, '人工记录')
|
||||
assert.equal(result[1].nodeLabel, '预计开航')
|
||||
assert.equal(result[1].actualAt, null)
|
||||
assert.equal(result[1].estimatedAt, '2026-10-07T08:00:00')
|
||||
assert.equal(result[2].cabinetNo, 'D2')
|
||||
assert.equal(result[2].inboundCode, 'NY-2')
|
||||
assert.equal(result[2].actualAt, '2026-10-06T10:00:00')
|
||||
})
|
||||
|
||||
test('empty actual scope creates no invented nodes or database identifier fallback', () => {
|
||||
assert.equal(rows([]).length, 0)
|
||||
assert.equal(rows([{ inboundCode: 'NY-1', nodes: [] }]).length, 0)
|
||||
const [row] = rows([{ id: 'INTERNAL', nodes: [{ standardNode: 'AT_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-05T09:00:00' }] }])
|
||||
assert.equal(row.cabinetNo, '—')
|
||||
assert.equal(row.containerNo, '—')
|
||||
assert.equal(row.inboundCode, '—')
|
||||
assert.equal(row.actualAt, null)
|
||||
})
|
||||
|
||||
test('detail consumes the existing merchant detail API and displays times separately', () => {
|
||||
const store = readFileSync(new URL('../store/firstLegOrders.ts', import.meta.url), 'utf8')
|
||||
const table = readFileSync(new URL('../components/TransportFactsTable.vue', import.meta.url), 'utf8')
|
||||
assert.match(store, /transportFragments: detail\.transportFragments/)
|
||||
assert.match(table, /label="实际时间".*time\(row\.actualAt\)/)
|
||||
assert.match(table, /label="预计时间".*time\(row\.estimatedAt\)/)
|
||||
assert.doesNotMatch(table, /platform\/|fetch\(|actualAt\s*\|\|\s*.*estimatedAt/)
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
DEPARTED_WAREHOUSE: '已离仓', AT_ORIGIN_PORT: '已进港', LOADED_ON_VESSEL: '已装船',
|
||||
DEPARTED_ORIGIN_PORT: '已开航', IN_TRANSIT: '海运途中', ARRIVED_DESTINATION_PORT: '船舶已到目的港',
|
||||
DISCHARGED_FROM_VESSEL: '已卸船', PICKUP_READY: '已清关、可提柜', PICKED_UP: '已提柜', EMPTY_RETURNED: '已还柜',
|
||||
}
|
||||
const estimatedLabels: Readonly<Record<string, string>> = {
|
||||
DEPARTED_WAREHOUSE: '预计离仓', AT_ORIGIN_PORT: '预计进港', LOADED_ON_VESSEL: '预计装船',
|
||||
DEPARTED_ORIGIN_PORT: '预计开航', IN_TRANSIT: '预计海运途中', ARRIVED_DESTINATION_PORT: '预计船舶到目的港',
|
||||
DISCHARGED_FROM_VESSEL: '预计卸船', PICKUP_READY: '预计可提柜', PICKED_UP: '预计提柜', EMPTY_RETURNED: '预计还柜',
|
||||
}
|
||||
|
||||
export function customerTransportRows(fragments: MerchantTransportFragment[]) {
|
||||
return fragments.flatMap((fragment, index) => fragment.nodes.map((node, nodeIndex) => ({
|
||||
key: `${index}-${nodeIndex}`,
|
||||
inboundCode: fragment.inboundCode || '—', cabinetNo: fragment.cabinetNo || '—',
|
||||
containerNo: fragment.containerNo || '—',
|
||||
nodeLabel: (node.actualAt ? labels : estimatedLabels)[node.standardNode] || '运输节点',
|
||||
actualAt: node.actualAt, estimatedAt: node.estimatedAt,
|
||||
location: [node.locationCode, node.locationName].filter(Boolean).join(' · ') || '—',
|
||||
source: node.providerCode === 'MANUAL' ? '人工记录' : node.providerCode === 'FIRSTLEG' ? '平台记录' : node.providerCode ? '承运轨迹' : '—',
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function evaluate(source, dependencies = {}) {
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => {
|
||||
assert.ok(id in dependencies, `Unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports)
|
||||
return exports
|
||||
}
|
||||
const eligibility = evaluate(readFileSync(new URL('../utils/customsEligibility.ts', import.meta.url), 'utf8'))
|
||||
const customsApi = evaluate(readFileSync(new URL('../api/customs.ts', import.meta.url), 'utf8'), {
|
||||
'@/api/http': {}, '@/modules/first-leg/api/firstLeg': {},
|
||||
})
|
||||
const order = (id, status = 'LOADED', taxMode = 'TAX_REFUND') => ({ id, status, taxMode, hasCompletedLoadingPlan: ['LOADED', 'DELIVERED', 'COMPLETED'].includes(status), orderNo: `ORDER-${id}`, businessSummary: { inboundCode: `IN-${id}` } })
|
||||
const detail = id => ({ status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED', inbounds: [{ orderId: id, taxMode: 'TAX_REFUND' }] })
|
||||
function harness(t, orders, getDetail = async id => detail(id)) {
|
||||
const store = { loadError: '', failPage: 0, transformPage: value => value }, calls = [], pageCalls = []
|
||||
const unifiedApi = evaluate(readFileSync(new URL('../api/unifiedOrders.ts', import.meta.url), 'utf8'), {
|
||||
'@/api/http': { apiRequest: async ({ method, url, params: { page, size, taxMode, loaded } }) => {
|
||||
assert.equal(method, 'GET')
|
||||
assert.equal(url, '/merchant/v1/orders')
|
||||
pageCalls.push({ page, size, taxMode, loaded })
|
||||
if (store.loadError || store.failPage === page) throw new Error(store.loadError || '第二页订单查询失败')
|
||||
// Model server filtering BEFORE pagination and COUNT, using the actual
|
||||
// request produced by the production API. Missing taxMode scans all rows.
|
||||
const filtered = orders.filter(row => (!taxMode || row.taxMode === taxMode)
|
||||
&& (loaded === undefined || row.hasCompletedLoadingPlan === loaded))
|
||||
return store.transformPage({ page, size, total: filtered.length, pages: Math.ceil(filtered.length / size),
|
||||
records: filtered.slice((page - 1) * size, page * size).map(row => ({ orderId: row.id, orderNo: row.orderNo, mainStatus: row.status, taxMode: row.taxMode, inboundCode: row.businessSummary.inboundCode })) })
|
||||
} },
|
||||
})
|
||||
const reader = evaluate(readFileSync(new URL('../utils/customsDocumentsReader.ts', import.meta.url), 'utf8'), {
|
||||
'./customsEligibility': eligibility,
|
||||
'../api/unifiedOrders': unifiedApi,
|
||||
'../api/customs': { getMerchantCustomsForOrder: id => { calls.push(id); return getDetail(id) }, isMerchantCustomsUnavailable: error => error?.code === 'A0404' },
|
||||
})
|
||||
const source = readFileSync(new URL('./CustomsDocumentsView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const scope = vue.effectScope()
|
||||
const view = scope.run(() => evaluate(source + '\nexport { load, records, loading, errorMessage, openDetail, selectedOrderId, selectedDetail, dialogOpen, search, queryModel, filteredRecords, pagedRecords, page, pageSize, queryFields, statusLabel, statusType, updateDetail }', {
|
||||
vue: { ...vue, onMounted() {} },
|
||||
'../utils/customsDocumentsReader': reader,
|
||||
'../api/customs': customsApi,
|
||||
'../store/customsPending': { useCustomsPendingStore: () => ({ refresh: async () => {} }) },
|
||||
}))
|
||||
t.after(() => scope.stop())
|
||||
return { view, store, calls, pageCalls }
|
||||
}
|
||||
|
||||
test('server-filtered request reaches five refund records originally on page 28 without scanning buy orders', async t => {
|
||||
const orders = Array.from({ length: 5528 }, (_, i) => order(`buy-${i}`, 'COMPLETED', 'BUY_DECLARATION'))
|
||||
orders.push(...Array.from({ length: 2613 }, (_, i) => order(`not-loaded-${i}`, 'WAIT_MEASURE')))
|
||||
orders.push(...Array.from({ length: 5 }, (_, i) => order(`historical-${i}`, 'COMPLETED')))
|
||||
const { view, calls, pageCalls } = harness(t, orders)
|
||||
await view.load()
|
||||
assert.deepEqual(calls, Array.from({ length: 5 }, (_, i) => `historical-${i}`))
|
||||
assert.equal(view.records.value.length, 5)
|
||||
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||
view.queryModel.value.inboundCode = 'historical-4'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 1)
|
||||
view.queryModel.value = { orderNo: '', inboundCode: '', containerNo: '', status: '' }; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 5)
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 5)
|
||||
})
|
||||
|
||||
test('second page failure is explicit and retry does not retain an incomplete result', async t => {
|
||||
const orders = Array.from({ length: 201 }, (_, i) => order(String(i)))
|
||||
const { view, store, pageCalls } = harness(t, orders)
|
||||
store.failPage = 2
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '第二页订单查询失败')
|
||||
store.failPage = 0
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 201)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
assert.equal(pageCalls.length, 4)
|
||||
})
|
||||
|
||||
test('display pagination reaches the final refund order without refetching or opening the wrong detail', async t => {
|
||||
const { view, calls, pageCalls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`, 'COMPLETED')))
|
||||
await view.load()
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
view.page.value = 2
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
view.openDetail(view.pagedRecords.value[0])
|
||||
assert.equal(view.selectedOrderId.value, 'refund-20')
|
||||
assert.deepEqual(view.selectedDetail.value.inbounds, [{ orderId: 'refund-20', taxMode: 'TAX_REFUND' }])
|
||||
view.pageSize.value = 10
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 10)
|
||||
view.page.value = 3
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 21)
|
||||
})
|
||||
|
||||
test('searching from a later display page resets pagination and clearing filters restores all documents', async t => {
|
||||
const { view, calls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||
await view.load()
|
||||
view.page.value = 2
|
||||
view.queryModel.value.inboundCode = 'IN-refund-20'
|
||||
view.search()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
view.queryModel.value.inboundCode = 'does-not-exist'
|
||||
view.search()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 0)
|
||||
view.queryModel.value.inboundCode = ''
|
||||
view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 21)
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
assert.equal(calls.length, 21)
|
||||
})
|
||||
|
||||
test('refresh failure on a later page clears stale rows and retry returns to a valid page', async t => {
|
||||
const { view, store } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||
await view.load()
|
||||
view.page.value = 2
|
||||
store.loadError = '资料列表请求失败'
|
||||
await view.load()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '资料列表请求失败')
|
||||
store.loadError = ''
|
||||
await view.load()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
assert.equal(view.filteredRecords.value.length, 21)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('empty pages, duplicate records and changing totals cannot silently truncate history', async t => {
|
||||
for (const change of [
|
||||
response => response.page === 2 ? { ...response, records: [] } : response,
|
||||
response => response.page === 2 ? { ...response, records: [{ ...response.records[0], orderId: '0' }] } : response,
|
||||
response => response.page === 2 ? { ...response, total: 202 } : response,
|
||||
]) {
|
||||
const { view, store, pageCalls } = harness(t, Array.from({ length: 201 }, (_, i) => order(String(i), 'COMPLETED')))
|
||||
store.transformPage = change
|
||||
await view.load()
|
||||
assert.ok(view.errorMessage.value)
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(pageCalls.length, 2)
|
||||
}
|
||||
})
|
||||
|
||||
test('document fetch concurrency never exceeds four and each candidate is requested once', async t => {
|
||||
let active = 0, peak = 0
|
||||
const { view, calls, pageCalls } = harness(t, Array.from({ length: 205 }, (_, i) => order(String(i))), async id => {
|
||||
active += 1; peak = Math.max(peak, active)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
active -= 1
|
||||
return detail(id)
|
||||
})
|
||||
await view.load()
|
||||
assert.equal(peak, 4)
|
||||
assert.equal(new Set(calls).size, 205)
|
||||
assert.equal(calls.length, 205)
|
||||
assert.equal(pageCalls.length, 2)
|
||||
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }, { page: 2, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||
assert.equal(view.records.value.length, 205)
|
||||
})
|
||||
|
||||
test('empty result uses one page request and no document requests', async t => {
|
||||
const { view, calls, pageCalls } = harness(t, [])
|
||||
await view.load()
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 0)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('tax-refund documents remain accessible through delivered and completed orders; buy orders and preloading are excluded', async t => {
|
||||
const stages = ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE', 'WAIT_PALLETIZE', 'WAIT_SPLIT', 'LOADING', 'LOADED', 'DELIVERED', 'COMPLETED']
|
||||
const orders = stages.flatMap(status => [order(status, status), order(`BUY-${status}`, status, 'BUY_DECLARATION')])
|
||||
const { view, calls } = harness(t, orders)
|
||||
await view.load()
|
||||
assert.deepEqual(calls, ['LOADED', 'DELIVERED', 'COMPLETED'])
|
||||
assert.deepEqual(view.records.value.map(row => row.order.id), calls)
|
||||
const completed = view.records.value.find(row => row.order.id === 'COMPLETED')
|
||||
view.openDetail(completed)
|
||||
assert.equal(view.selectedOrderId.value, 'COMPLETED')
|
||||
assert.equal(view.selectedDetail.value.status, 'COMPLETED')
|
||||
assert.equal(view.dialogOpen.value, true)
|
||||
view.queryModel.value.status = 'CUSTOMS_COMPLETED'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 3)
|
||||
assert.equal(calls.length, 3, 'local filtering does not refetch documents')
|
||||
})
|
||||
|
||||
test('only matching server-returned tax-refund ownership is displayed', async t => {
|
||||
const { view } = harness(t, [order('one'), order('two')], async id => id === 'one' ? detail('someone-else') : { inbounds: [{ orderId: id, taxMode: 'BUY_DECLARATION' }] })
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
})
|
||||
|
||||
test('partial failures are visible and retry replaces the result; unavailable customs is not a transport failure', async t => {
|
||||
let fail = true
|
||||
const { view } = harness(t, [order('ok'), order('retry'), order('unavailable')], async id => {
|
||||
if (id === 'unavailable') throw Object.assign(new Error('not associated'), { code: 'A0404' })
|
||||
if (id === 'retry' && fail) throw new Error('network')
|
||||
return detail(id)
|
||||
})
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 1)
|
||||
assert.equal(view.errorMessage.value, '1 票订单的报关资料加载失败,请重新加载')
|
||||
fail = false; await view.load()
|
||||
assert.equal(view.records.value.length, 2)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('order query failure is shown instead of a successful empty result', async t => {
|
||||
const { view, store, calls } = harness(t, [order('old')])
|
||||
await view.load()
|
||||
store.loadError = '订单查询失败'; await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '订单查询失败')
|
||||
assert.equal(calls.length, 1)
|
||||
assert.equal(view.loading.value, false)
|
||||
})
|
||||
|
||||
test('repeated refresh during an active load does not duplicate requests', async t => {
|
||||
let resolve
|
||||
const pending = new Promise(done => { resolve = done })
|
||||
const { view, calls } = harness(t, [order('one')], () => pending)
|
||||
const first = view.load()
|
||||
await Promise.resolve()
|
||||
await view.load()
|
||||
assert.deepEqual(calls, ['one'])
|
||||
resolve(detail('one')); await first
|
||||
assert.equal(view.loading.value, false)
|
||||
})
|
||||
|
||||
test('mixed-container labels and filters use only the current customer status', async t => {
|
||||
const states = [
|
||||
['uploaded', 'WAITING_CUSTOMER_DOCUMENTS', 'DOCUMENT_UPLOADED', 1, '资料已上传', 'success'],
|
||||
['waiting', 'WAITING_CUSTOMER_DOCUMENTS', 'WAITING_UPLOAD', 0, '待上传资料', 'warning'],
|
||||
['declaring', 'DECLARING', 'DECLARING', 1, '报关中', 'primary'],
|
||||
['completed', 'COMPLETED', 'CUSTOMS_COMPLETED', 1, '报关完成', 'success'],
|
||||
]
|
||||
const { view, calls } = harness(t, states.map(([id]) => order(id)), async id => {
|
||||
const [, status, merchantStatus, coveredTaxRefundCount] = states.find(row => row[0] === id)
|
||||
return { ...detail(id), status, merchantStatus, coveredTaxRefundCount, taxRefundCount: 1 }
|
||||
})
|
||||
await view.load()
|
||||
for (const [id, , merchantStatus, , label, tone] of states) {
|
||||
const row = view.records.value.find(item => item.order.id === id)
|
||||
assert.equal(view.statusLabel(row.detail), label)
|
||||
assert.equal(view.statusType(row.detail), tone)
|
||||
view.queryModel.value.status = merchantStatus; view.search()
|
||||
assert.deepEqual(view.filteredRecords.value.map(item => item.order.id), [id])
|
||||
}
|
||||
assert.deepEqual(view.queryFields.find(field => field.key === 'status').options,
|
||||
states.map(([, , value, , label]) => ({ value, label })).sort((a, b) =>
|
||||
['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(a.value)
|
||||
- ['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(b.value)))
|
||||
view.queryModel.value.status = 'WAITING_CUSTOMER_DOCUMENTS'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 0, 'container statuses are not customer filter values')
|
||||
view.queryModel.value.status = ''; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 4)
|
||||
assert.equal(calls.length, 4, 'filtering does not requery or infer status from coverage')
|
||||
})
|
||||
|
||||
test('dialog update refreshes customer status and active filter without inferring from container status', async t => {
|
||||
const { view } = harness(t, [order('one')], async id => ({ ...detail(id), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }))
|
||||
await view.load(); view.openDetail(view.records.value[0])
|
||||
view.queryModel.value.status = 'WAITING_UPLOAD'; view.search()
|
||||
view.updateDetail({ ...detail('one'), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED', coveredTaxRefundCount: 1, taxRefundCount: 1 })
|
||||
assert.equal(view.filteredRecords.value.length, 0)
|
||||
view.queryModel.value.status = 'DOCUMENT_UPLOADED'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 1)
|
||||
assert.equal(view.statusLabel(view.filteredRecords.value[0].detail), '资料已上传')
|
||||
assert.equal(view.statusLabel({ status: 'COMPLETED', coveredTaxRefundCount: 1, taxRefundCount: 1 }), '—')
|
||||
assert.equal(view.statusType({ status: 'COMPLETED' }), 'info')
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { RefreshCcw } from '@lucide/vue'
|
||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||
import type { TableAction } from '@/components/common/tableActions'
|
||||
import { MERCHANT_CUSTOMS_STATUS_LABELS, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { readCustomsDocuments, type CustomsDocumentRow } from '../utils/customsDocumentsReader'
|
||||
import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue'
|
||||
import CustomsHelp from '../components/CustomsHelp.vue'
|
||||
|
||||
import { useCustomsPendingStore } from '../store/customsPending'
|
||||
|
||||
const customsPending = useCustomsPendingStore()
|
||||
const loading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const queryModel = ref<QueryModel>({ orderNo: '', inboundCode: '', containerNo: '', status: '' })
|
||||
const appliedQuery = ref<QueryModel>({ ...queryModel.value })
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||
{ key: 'inboundCode', label: '入仓码', type: 'input', placeholder: '请输入入仓码' },
|
||||
{ key: 'containerNo', label: '柜号', type: 'input', placeholder: '请输入柜号' },
|
||||
{ key: 'status', label: '状态', type: 'select', placeholder: '全部', options: Object.entries(MERCHANT_CUSTOMS_STATUS_LABELS).map(([value, label]) => ({ label, value })) },
|
||||
]
|
||||
const columns: DataTableColumn[] = [
|
||||
{ label: '操作', slotName: 'actions', width: 120, fixed: 'left' },
|
||||
{ label: '订单号', slotName: 'orderNo', minWidth: 230 },
|
||||
{ label: '入仓码', slotName: 'inboundCode', minWidth: 190 },
|
||||
{ label: '柜号', slotName: 'containerNo', minWidth: 170 },
|
||||
{ label: '柜内退税箱数', prop: 'detail.actualBoxCount', width: 110, align: 'center' },
|
||||
{ label: '柜内资料覆盖', slotName: 'coverage', width: 110, align: 'center' },
|
||||
{ label: '状态', slotName: 'status', width: 130 },
|
||||
]
|
||||
const records = ref<CustomsDocumentRow[]>([])
|
||||
const dialogOpen = ref(false)
|
||||
const selectedOrderId = ref('')
|
||||
const selectedDetail = ref<MerchantCustomsContainer | null>(null)
|
||||
|
||||
const filteredRecords = computed(() => {
|
||||
const query = appliedQuery.value
|
||||
const matches = (value: string | null | undefined, key: string) => String(value ?? '').toLowerCase().includes(String(query[key] || '').trim().toLowerCase())
|
||||
return records.value.filter(({ order, detail }) =>
|
||||
matches(order.orderNo, 'orderNo')
|
||||
&& matches(order.businessSummary.inboundCode, 'inboundCode')
|
||||
&& (matches(detail.containerNo, 'containerNo') || matches(detail.cabinetNo, 'containerNo'))
|
||||
&& (!query.status || detail.merchantStatus === query.status),
|
||||
)
|
||||
})
|
||||
const pagedRecords = computed(() => filteredRecords.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
const emptyText = computed(() => Object.values(appliedQuery.value).some((value) => String(value || '').trim()) ? '暂无匹配的报关资料,请调整查询条件' : '暂无报关资料')
|
||||
|
||||
function search() {
|
||||
appliedQuery.value = { ...queryModel.value }
|
||||
page.value = 1
|
||||
}
|
||||
watch(pageSize, () => { page.value = 1 })
|
||||
watch(() => filteredRecords.value.length, (total) => {
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(total / pageSize.value)))
|
||||
})
|
||||
function rowActions(row: object): TableAction[] {
|
||||
return [{ key: 'documents', label: '查看资料', disabled: loading.value, run: () => openDetail(row) }]
|
||||
}
|
||||
|
||||
function statusLabel(detail: MerchantCustomsContainer) {
|
||||
return detail.merchantStatus ? MERCHANT_CUSTOMS_STATUS_LABELS[detail.merchantStatus] ?? '—' : '—'
|
||||
}
|
||||
function statusType(detail: MerchantCustomsContainer) {
|
||||
return detail.merchantStatus === 'CUSTOMS_COMPLETED' || detail.merchantStatus === 'DOCUMENT_UPLOADED'
|
||||
? 'success' : detail.merchantStatus === 'DECLARING' ? 'primary' : detail.merchantStatus === 'WAITING_UPLOAD' ? 'warning' : 'info'
|
||||
}
|
||||
async function load() {
|
||||
if (loading.value) return
|
||||
void customsPending.refresh(true)
|
||||
loading.value = true; errorMessage.value = ''
|
||||
try {
|
||||
const { records: loadedRecords, failedCount } = await readCustomsDocuments()
|
||||
records.value = loadedRecords
|
||||
if (failedCount) errorMessage.value = `${failedCount} 票订单的报关资料加载失败,请重新加载`
|
||||
} catch (error) {
|
||||
records.value = []
|
||||
errorMessage.value = error instanceof Error ? error.message : '报关资料加载失败,请稍后重试'
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
function openDetail(item: unknown) {
|
||||
const value = item as CustomsDocumentRow
|
||||
selectedOrderId.value = value.order.id; selectedDetail.value = value.detail; dialogOpen.value = true
|
||||
}
|
||||
function updateDetail(value: MerchantCustomsContainer) {
|
||||
const found = records.value.find((item) => item.order.id === selectedOrderId.value)
|
||||
if (found) found.detail = value
|
||||
}
|
||||
onMounted(() => { void load() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="customs-page">
|
||||
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" />
|
||||
<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">
|
||||
<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 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 #inboundCode="{ row }">{{ row.order.businessSummary.inboundCode || '—' }}</template>
|
||||
<template #containerNo="{ row }">{{ row.detail.containerNo || row.detail.cabinetNo || '—' }}</template>
|
||||
<template #coverage="{ row }">{{ row.detail.coveredTaxRefundCount }} / {{ row.detail.taxRefundCount }}</template>
|
||||
<template #status="{ row }"><el-tag :type="statusType(row.detail)" effect="light" size="small">{{ statusLabel(row.detail) }}</el-tag></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
<CustomsDocumentsDialog v-model="dialogOpen" :order-id="selectedOrderId" :can-edit="selectedDetail?.status !== 'COMPLETED'" :initial-detail="selectedDetail" @updated="updateDetail" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.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; }
|
||||
.state-error { display: flex; min-height: 84px; align-items: center; justify-content: center; gap: 12px; padding: 14px; color: #b42318; }
|
||||
</style>
|
||||
@@ -35,17 +35,16 @@ test('opens order creation as a dedicated protected page while keeping draft edi
|
||||
assert.match(editorShellSource, /\.editor-page-footer :deep\(\.editor-actions\) \{[^}]*justify-content: center;/)
|
||||
})
|
||||
|
||||
test('exposes real list, draft, submit, and detail workflow entries without cancellation', () => {
|
||||
test('exposes real list, draft, submit, and detail workflow entries', () => {
|
||||
assert.match(source, /function openCreate\(\)/)
|
||||
assert.match(source, /async function saveDraft\(\)/)
|
||||
assert.match(source, /function submitOrder\(\)/)
|
||||
assert.match(source, /async function openDetail\(order: FirstLegOrder\)/)
|
||||
assert.match(source, /Promise\.allSettled\(\[/)
|
||||
assert.match(source, /const orderPageRequest = isCreatePage\.value \|\| isDetailPage\.value\s*\? store\.loadWarehouseType\('DOMESTIC', true\)\s*:\s*store\.load\(\{ includeDrafts: true \}\)/)
|
||||
assert.match(source, /const orderPageRequest = isCreatePage\.value \|\| isDetailPage\.value\s*\? store\.loadWarehouseType\('DOMESTIC', true\)\s*:\s*loadOrderPage\(\)/)
|
||||
assert.match(source, /Promise\.allSettled\(\[\s*orderPageRequest,\s*companyRequest/)
|
||||
assert.match(source, /tenantStore\.loadCompanyContext\(\)/)
|
||||
assert.match(source, /await store\.loadDetail\(orderId\)/)
|
||||
assert.doesNotMatch(source, /cancelOrder|取消订单/)
|
||||
})
|
||||
|
||||
test('returns edited submissions to the refreshed order list instead of opening detail', () => {
|
||||
@@ -67,7 +66,7 @@ test('copies an order into the dedicated create page without reusing order ident
|
||||
})
|
||||
|
||||
test('keeps create-page support errors scoped to create-page requests', () => {
|
||||
assert.match(source, /if \(!isCreatePage\.value && store\.draftLoadError\)/)
|
||||
assert.doesNotMatch(source, /store\.draftLoadError/)
|
||||
})
|
||||
|
||||
test('blocks order submission before company approval while preserving draft actions', () => {
|
||||
@@ -115,7 +114,7 @@ test('uses the shared query toolbar and data table without metric cards', () =>
|
||||
assert.match(source, /<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" \/>/)
|
||||
assert.match(source, /async function searchOrders\(model: QueryModel\)/)
|
||||
assert.match(source, /await store\.load\(\{/)
|
||||
assert.match(source, /<DataTable v-model:page="tablePage" v-model:page-size="tablePageSize" :data="pagedOrders" :columns="visibleOrderColumns"/)
|
||||
assert.match(source, /<DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns"/)
|
||||
assert.match(source, /\{ key: 'actions', label: '操作', width: 284, fixed: 'left', align: 'left', headerAlign: 'left', slotName: 'actions' \}/)
|
||||
assert.doesNotMatch(source, /order-metrics|订单概览/)
|
||||
})
|
||||
@@ -177,7 +176,7 @@ test('exports every visible order field with normalized dates', () => {
|
||||
test('matches the prototype with selectable dense order-list columns', () => {
|
||||
assert.match(source, /aria-label="设置订单列表显示列"/)
|
||||
assert.match(source, /显示字段筛选/)
|
||||
assert.match(source, /const defaultVisibleColumnKeys = \['status', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt'\]/)
|
||||
assert.match(source, /const defaultVisibleColumnKeys = \['status', 'progress', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt'\]/)
|
||||
assert.match(source, /key: 'inboundCode', label: '入仓码', width: 230, fixed: 'left'/)
|
||||
assert.match(source, /<SlidersHorizontal :size="18"/)
|
||||
assert.match(source, /<el-checkbox-group v-model="visibleColumnKeys"/)
|
||||
@@ -224,7 +223,8 @@ test('shows one unified progress line and C02 business summaries without detail
|
||||
assert.match(source, /progressSummaryItems/)
|
||||
assert.match(source, /summary\.preloadStatus/)
|
||||
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, /订单主节点与关联柜次统一展示/)
|
||||
assert.match(progressSource, /履约进度/)
|
||||
@@ -232,7 +232,10 @@ test('shows one unified progress line and C02 business summaries without detail
|
||||
assert.doesNotMatch(source, /<h3>报关回执<\/h3>/)
|
||||
assert.match(source, /船期摘要/)
|
||||
assert.match(source, /柜次明细/)
|
||||
assert.match(source, /尚未分配柜次,后续柜次节点将在这里同步。/)
|
||||
assert.match(source, /pickingStatusLabel: getFirstLegPickingStatusLabel\(summary\.loadingStatus\)/)
|
||||
assert.match(source, /prop="pickingStatusLabel" label="拣货状态"/)
|
||||
assert.doesNotMatch(source, /label="当前节点"/)
|
||||
assert.match(source, /尚未分配柜次/)
|
||||
assert.doesNotMatch(source, /暂无柜次分配信息/)
|
||||
assert.doesNotMatch(source, /summary\.sealNo \|\|/)
|
||||
assert.doesNotMatch(progressSource, /客户确认|差异处理中|派送中/)
|
||||
@@ -245,9 +248,9 @@ test('uses only fields present on C02 rows before loading full detail', () => {
|
||||
assert.match(source, /displayListValue/)
|
||||
assert.doesNotMatch(source, /key: 'operator'/)
|
||||
assert.doesNotMatch(source, /key: 'transportMode', type: 'select'/)
|
||||
assert.match(source, /store\.draftLoadError/)
|
||||
assert.match(source, /mainStatus: statusValue && statusValue !== 'DRAFT' \? statusValue : undefined/)
|
||||
assert.match(source, /draftOnly: statusValue === 'DRAFT'/)
|
||||
assert.match(source, /:total="store\.total"/)
|
||||
assert.match(source, /mainStatus: text\('status'\)/)
|
||||
assert.match(source, /queue: activeOrderQueue\.value, page: requestedPage, size: tablePageSize\.value/)
|
||||
assert.match(source, /createdFrom: range\[0\] \? `\$\{range\[0\]\}T00:00:00`/)
|
||||
})
|
||||
|
||||
@@ -270,7 +273,7 @@ test('keeps all progress stages and business summary usable on mobile', () => {
|
||||
test('keeps the first viewport compact and moves create into the table toolbar', () => {
|
||||
const tableToolbarSource = source.slice(source.indexOf('#toolbar-actions'), source.indexOf('class="order-eligibility is-pending"'))
|
||||
assert.match(source, /#toolbar-actions/)
|
||||
assert.match(source, /class="order-queue-tabs"[\s\S]*确认计费重[\s\S]*上传资料[\s\S]*草稿/)
|
||||
assert.match(source, /class="order-queue-tabs"[\s\S]*v-for="queue in ORDER_QUEUES"[\s\S]*orderQueueCounts\[queue.key\]/)
|
||||
assert.match(source, /activeOrderQueue\.value === 'draft'[\s\S]*order\.status === 'DRAFT'/)
|
||||
assert.doesNotMatch(source, /共 \{\{ filteredOrders\.length \}\} 条/)
|
||||
assert.match(source, /#toolbar-actions[\s\S]*order:first-leg:create[\s\S]*创建订单[\s\S]*class="order-eligibility is-pending"/)
|
||||
@@ -394,7 +397,7 @@ test('distills order creation into the confirmed prototype sections with server
|
||||
assert.match(cargoToolbarSource, /isCreatePage && !routeDraftId && canCreateOrder/)
|
||||
assert.match(cargoToolbarSource, /downloadBatchTemplate[\s\S]*下载 Excel 模板/)
|
||||
assert.match(cargoToolbarSource, /openBatchImport[\s\S]*Excel 批量导入/)
|
||||
assert.match(cargoToolbarSource, /Excel 导入用于一次创建多条订单草稿/)
|
||||
assert.doesNotMatch(cargoToolbarSource, /Excel 导入用于一次创建多条订单草稿/)
|
||||
assert.match(source, /导入成功的数据只创建草稿,不会直接提交审核/)
|
||||
assert.match(source, /下载正式模板[\s\S]*选择 Excel/)
|
||||
assert.match(source, /仅支持 \.xlsx,文件不超过 5MB、最多 50 行/)
|
||||
@@ -457,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', () => {
|
||||
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/)
|
||||
})
|
||||
|
||||
@@ -546,9 +549,19 @@ test('shows fulfillment courier information as read-only client detail', () => {
|
||||
assert.match(source, /履约快递信息/)
|
||||
assert.match(source, /detailOrder\.expressCompanyName/)
|
||||
assert.match(source, /detailOrder\.trackingNumber/)
|
||||
assert.match(source, /客户端仅只读展示/)
|
||||
assert.match(source, /快递公司由平台维护/)
|
||||
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', () => {
|
||||
@@ -610,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\.message \|\| unavailableMessage/)
|
||||
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.doesNotMatch(source, /confirmMerchantInbound|adjustMerchantInbound|sendMerchantInbound/)
|
||||
})
|
||||
@@ -623,22 +636,51 @@ test('keeps platform enterprise scope and tenant terminology out of the customer
|
||||
test('opens billing-weight confirmation independently from order details', () => {
|
||||
const handler = source.slice(source.indexOf('function openFeeConfirmation'), source.indexOf('async function retryDetail'))
|
||||
assert.match(handler, /feeConfirmationOpen\.value = true/)
|
||||
assert.match(handler, /loadInboundBilling\(order, '未推送计费重'\)/)
|
||||
assert.match(handler, /loadInboundBilling\(order, '未推送费用'\)/)
|
||||
assert.doesNotMatch(handler, /openDetail\(/)
|
||||
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', () => {
|
||||
assert.match(source, /if \(canConfirmInboundFee\.value && order\.businessSummary\.customerFeeConfirmationRequired\) \{\s*actions\.push\(\{ key: 'fee'/)
|
||||
test('only offers published-fee confirmation for pending orders with confirmation permission', () => {
|
||||
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(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', () => {
|
||||
assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/)
|
||||
assert.match(source, /Promise\.allSettled\(drafts\.map\(\(order\) => submitMerchantFirstLegOrder/)
|
||||
assert.match(source, /createIdempotencyKey\(`first-leg-batch-submit-\$\{order\.id\}`\)/)
|
||||
assert.match(source, /Promise\.allSettled\(ids\.map\(id => store\.submitSaved/)
|
||||
assert.doesNotMatch(source, /submitMerchantFirstLegOrder/)
|
||||
assert.match(source, /v-if="canSubmitOrder"[\s\S]*批量提交草稿/)
|
||||
})
|
||||
|
||||
@@ -684,8 +726,8 @@ test('opens the server-owned inbound-code association from the order detail', ()
|
||||
assert.doesNotMatch(source, /openInboundCodeAssociation\([^)]*\.id\)/)
|
||||
})
|
||||
|
||||
test('opens customer customs documents only for server-confirmed loaded tax-refund orders', () => {
|
||||
assert.match(source, /order\.status !== 'LOADED'/)
|
||||
test('opens customer customs documents only for server-confirmed tax-refund orders after loading', () => {
|
||||
assert.match(source, /!isCustomsOrderCandidate\(order\)/)
|
||||
assert.match(source, /item\.orderId === order\.id && item\.taxMode === 'TAX_REFUND'/)
|
||||
assert.match(source, /getMerchantCustomsForOrder\(order\.id\)/)
|
||||
assert.match(source, /if \(eligibleCustomsDetail\(order\)\) \{\s*actions\.push\(\{ key: 'customs', label: '报关资料'/)
|
||||
@@ -700,13 +742,15 @@ test('supports the frozen customs document workflow and customer-safe downloads'
|
||||
'/merchant/v1/customs/loading-plans/',
|
||||
'/merchant/v1/customs/documents/',
|
||||
'/inbounds',
|
||||
'/completion/download',
|
||||
'/receipt/download',
|
||||
]) assert.match(customsApiSource, new RegExp(path.replaceAll('/', '\\/')))
|
||||
assert.match(customsApiSource, /MAX_CUSTOMS_FILE_SIZE = 50 \* 1024 \* 1024/)
|
||||
assert.match(customsApiSource, /data: \{ inboundIds, expectedVersion: document\.source\.version \}/)
|
||||
assert.match(customsApiSource, /requestId: error\.requestId/)
|
||||
assert.match(customsDialogSource, /报关开始后仅可查看和下载,不提供退回或解锁/)
|
||||
assert.match(customsDialogSource, /detail\.status === 'COMPLETED' && item\.completion/)
|
||||
assert.match(customsDialogSource, /客户原始资料已冻结,仍可确认或打回待确认的报关行回执/)
|
||||
assert.match(customsDialogSource, /v-if="detail.status === 'COMPLETED'"[^>]*><strong>报关已完成/)
|
||||
assert.match(customsDialogSource, /真实报关完税文件已齐全/)
|
||||
assert.match(customsDialogSource, /item\.finalDocument/)
|
||||
assert.match(customsDialogSource, /资料版本历史/)
|
||||
assert.match(customsDialogSource, /尚未上传退税报关资料/)
|
||||
assert.match(customsDialogSource, /退税报关资料加载失败/)
|
||||
@@ -729,7 +773,7 @@ test('shows authoritative warehouse, loading and sailing fields on desktop and n
|
||||
}
|
||||
assert.match(source, /businessSummary\.cabinetNo \|\| .*businessSummary\.containerNo/)
|
||||
assert.match(source, /businessSummary\.vesselName.*businessSummary\.voyageNo/s)
|
||||
assert.match(source, /businessSummary\.sailingAt/)
|
||||
assert.match(source, /businessSummary\.estimatedSailingAt/)
|
||||
})
|
||||
|
||||
test('loads complete order detail before editing and rejects an unavailable historical warehouse', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormItemRule, type FormRules, type UploadRequestOptions } from 'element-plus'
|
||||
import { AlertTriangle, ChevronDown, ChevronUp, Download, FilePlus2, FileText, GripVertical, ImagePlus, MapPin, PackageCheck, Pencil, Plus, RotateCcw, Send, SlidersHorizontal, Trash2, Upload } from '@lucide/vue'
|
||||
@@ -12,9 +12,11 @@ import FirstLegOrderEditorShell from '@/modules/first-leg/components/FirstLegOrd
|
||||
import InboundBillingPanel from '@/modules/first-leg/components/InboundBillingPanel.vue'
|
||||
import InboundCodeAssociationDialog from '@/modules/first-leg/components/InboundCodeAssociationDialog.vue'
|
||||
import OrderProgressPanel from '@/modules/first-leg/components/OrderProgressPanel.vue'
|
||||
import TransportFactsTable from '@/modules/first-leg/components/TransportFactsTable.vue'
|
||||
import CustomsDocumentsDialog from '@/modules/first-leg/components/CustomsDocumentsDialog.vue'
|
||||
import { getMerchantInboundBilling } from '@/modules/first-leg/api/inboundBilling'
|
||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '@/modules/first-leg/api/customs'
|
||||
import { isCustomsOrderCandidate, needsCustomsUpload } from '../utils/customsEligibility'
|
||||
import {
|
||||
estimateMerchantFirstLegPrice,
|
||||
createIdempotencyKey,
|
||||
@@ -28,7 +30,6 @@ import {
|
||||
getMerchantOrderAddresses,
|
||||
getMerchantPricingChannels,
|
||||
importMerchantFirstLegOrders,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantOrderAddress,
|
||||
uploadMerchantProductImage,
|
||||
type CustomerOrderAddress,
|
||||
@@ -40,7 +41,7 @@ import {
|
||||
type MerchantPricingChannel,
|
||||
type InboundCodePolicy,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import { useFirstLegOrdersStore } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useFirstLegOrdersStore, type DraftEditSession } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useTenantAdministrationStore } from '@/modules/tenant-management/public'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
|
||||
@@ -52,11 +53,15 @@ import {
|
||||
canClientEditFirstLegOrder,
|
||||
createEmptyCargoItem,
|
||||
getFirstLegStatusLabel,
|
||||
getFirstLegPickingStatusLabel,
|
||||
getFirstLegStatusTone,
|
||||
getFirstLegTransportModeLabel,
|
||||
summarizeFirstLegCargo,
|
||||
validateFirstLegOrderDraft,
|
||||
} from '@/modules/first-leg/utils/firstLegOrder'
|
||||
import { ORDER_QUEUES, orderProgressLabel } from '../utils/orderProgress'
|
||||
import { orderBillingMetric } from '../utils/orderDetailSummary'
|
||||
import type { OrderQueue } from '../api/unifiedOrders'
|
||||
import { validateProductImageFile } from '@/modules/first-leg/utils/productImage'
|
||||
import { createPriceEstimateBreakdown } from '@/modules/first-leg/utils/priceEstimate'
|
||||
|
||||
@@ -78,6 +83,32 @@ const companyAuditLoaded = ref(false)
|
||||
const companySubmissionBlocked = computed(() => companyAuditLoaded.value && tenantStore.company.auditStatus !== 'ACTIVE')
|
||||
const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create'))
|
||||
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel'))
|
||||
const cancellingOrderId = ref('')
|
||||
|
||||
function canOfferCancellation(order: FirstLegOrder) {
|
||||
return canCancelOrder.value && ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE'].includes(order.status)
|
||||
}
|
||||
|
||||
async function cancelOrder(order: FirstLegOrder) {
|
||||
if (!canOfferCancellation(order) || cancellingOrderId.value) return
|
||||
cancellingOrderId.value = order.id
|
||||
try {
|
||||
const target = await store.prepareCancellation(order.id)
|
||||
const { value } = await ElMessageBox.prompt(
|
||||
`订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
|
||||
type: 'warning', inputType: 'textarea', confirmButtonText: '确认取消订单', cancelButtonText: '返回',
|
||||
inputValidator: value => Boolean(value?.trim()) && value.trim().length <= 500 || '请填写 1–500 字取消原因',
|
||||
})
|
||||
await store.cancelOrder(target.id, target.expectedVersion, value.trim())
|
||||
ElMessage.success('订单已取消'); await loadOrderPage()
|
||||
if (isDetailPage.value) await router.push({ name: 'first-leg-orders' })
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
ElMessage.error(error instanceof Error ? error.message : '取消失败,请重新操作')
|
||||
void loadOrderPage()
|
||||
} finally { cancellingOrderId.value = '' }
|
||||
}
|
||||
const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
|
||||
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const availableWarehouses = computed(() => store.warehouses.filter((warehouse) => warehouse.warehouseType === 'DOMESTIC'))
|
||||
@@ -87,9 +118,9 @@ const appliedFilters = ref<QueryModel>({ ...filters.value })
|
||||
const queryFields = computed<QueryField[]>(() => [
|
||||
{ key: 'cargoKeyword', label: '入仓码 / SKU', type: 'input', placeholder: '请输入入仓码或 SKU', props: { 'aria-label': '入仓码或 SKU' } },
|
||||
{ key: 'receivingWarehouseId', label: '收货仓', type: 'select', placeholder: '全部', options: availableWarehouses.value.map((item) => ({ label: item.name, value: item.id })), props: { 'aria-label': '收货仓' } },
|
||||
{ key: 'channelName', label: '渠道名称', type: 'select', placeholder: '全部', options: [...new Set(store.orders.map((item) => item.channelName).filter(Boolean))].map((name) => ({ label: name, value: name })), props: { 'aria-label': '渠道名称' } },
|
||||
{ key: 'channelName', label: '渠道名称', type: 'select', placeholder: '全部', options: store.queryChannelNames.map((name) => ({ label: name, value: name })), props: { 'aria-label': '渠道名称' } },
|
||||
{ key: 'createdRange', label: '创建时间', type: 'daterange', placeholder: '请选择创建时间', props: { 'aria-label': '创建时间' } },
|
||||
{ key: 'status', label: '当前状态', type: 'select', placeholder: '全部', options: FIRST_LEG_ORDER_STATUSES.map((item) => ({ label: item.label, value: item.code })), props: { 'aria-label': '当前状态' } },
|
||||
{ key: 'status', label: '当前状态', type: 'select', placeholder: '全部', options: FIRST_LEG_ORDER_STATUSES.filter(item => item.code !== 'CANCELLED').map((item) => ({ label: item.label, value: item.code })), props: { 'aria-label': '当前状态' } },
|
||||
{ key: 'destinationType', label: '目的仓类型', type: 'select', placeholder: '全部', options: [{ label: 'FBA 仓', value: 'FBA' }, { label: '海外仓', value: 'OVERSEAS' }, { label: '私人地址', value: 'PRIVATE' }], props: { 'aria-label': '目的仓类型' } },
|
||||
{ key: 'trackingNumber', label: '快递单号', type: 'input', placeholder: '请输入快递单号', props: { 'aria-label': '快递单号' } },
|
||||
])
|
||||
@@ -119,6 +150,7 @@ const fixedOrderColumns: DataTableColumn[] = [
|
||||
]
|
||||
const selectableOrderColumns: DataTableColumn[] = [
|
||||
{ key: 'status', label: '当前订单状态', width: 126, align: 'center', headerAlign: 'center', slotName: 'status' },
|
||||
{ key: 'progress', label: '履约进度', width: 142, align: 'center', headerAlign: 'center', slotName: 'progress' },
|
||||
{ key: 'channel', label: '渠道', width: 150, align: 'left', headerAlign: 'left', showOverflowTooltip: true, slotName: 'channel' },
|
||||
{ key: 'transportMode', label: '运输方式', width: 104, align: 'center', headerAlign: 'center', slotName: 'transportMode' },
|
||||
{ key: 'pickupMethod', label: '交货方式', width: 112, align: 'center', headerAlign: 'center', slotName: 'pickupMethod' },
|
||||
@@ -144,12 +176,12 @@ const selectableOrderColumns: DataTableColumn[] = [
|
||||
{ key: 'expectedShipDate', label: '期望出运', width: 132, align: 'center', headerAlign: 'center', slotName: 'expectedShipDate' },
|
||||
{ key: 'cabinetNo', label: '柜号 / 柜次', width: 150, align: 'left', headerAlign: 'left', showOverflowTooltip: true, slotName: 'cabinetNo' },
|
||||
{ key: 'vesselVoyage', label: '船名 / 航次', width: 160, align: 'left', headerAlign: 'left', showOverflowTooltip: true, slotName: 'vesselVoyage' },
|
||||
{ key: 'sailingAt', label: '预计船期', width: 164, align: 'center', headerAlign: 'center', slotName: 'sailingAt' },
|
||||
{ key: 'estimatedSailingAt', label: '预计船期', width: 164, align: 'center', headerAlign: 'center', slotName: 'estimatedSailingAt' },
|
||||
{ key: 'createdAt', label: '创建时间', width: 164, align: 'center', headerAlign: 'center', slotName: 'createdAt' },
|
||||
{ key: 'updatedAt', label: '更新时间', width: 164, align: 'center', headerAlign: 'center', slotName: 'updatedAt' },
|
||||
]
|
||||
const allSelectableColumnKeys = selectableOrderColumns.map((column) => String(column.key))
|
||||
const defaultVisibleColumnKeys = ['status', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt']
|
||||
const defaultVisibleColumnKeys = ['status', 'progress', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt']
|
||||
const visibleColumnKeys = ref<string[]>([...defaultVisibleColumnKeys])
|
||||
const orderedColumnKeys = ref<string[]>([...allSelectableColumnKeys])
|
||||
const draggedColumnKey = ref('')
|
||||
@@ -193,11 +225,11 @@ const selectedOrders = ref<FirstLegOrder[]>([])
|
||||
const selectedOrderCount = computed(() => selectedOrders.value.length)
|
||||
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
|
||||
const orderTableVersion = ref(0)
|
||||
type OrderQueue = 'all' | 'fee' | 'customs' | 'draft'
|
||||
const activeOrderQueue = ref<OrderQueue>('all')
|
||||
const editorOpen = ref(false)
|
||||
const orderFormRef = ref<FormInstance>()
|
||||
const editingId = ref<string>()
|
||||
const editingSession = shallowRef<DraftEditSession>()
|
||||
const openingEditor = ref(false)
|
||||
const copyingOrderId = ref('')
|
||||
const detailId = ref<string>()
|
||||
@@ -318,9 +350,9 @@ function formatExportDateTime(value: string | null | undefined) {
|
||||
}
|
||||
|
||||
const pickupMethodLabels: Record<FirstLegOrder['pickupMethod'], string> = {
|
||||
SELF_EXPRESS: '自行快递到仓',
|
||||
PICKUP: '平台上门提货',
|
||||
SELF_TRUCK: '自行送货到仓',
|
||||
SELF_TRUCK: '卡车自送',
|
||||
PICKUP: '我司提货',
|
||||
SELF_EXPRESS: '快递自提',
|
||||
}
|
||||
const destinationTypeLabels: Record<FirstLegOrder['destinationType'], string> = {
|
||||
FBA: 'FBA 仓',
|
||||
@@ -369,7 +401,8 @@ function emptyDraft(): FirstLegOrderDraft {
|
||||
destinationCountryCode: 'US',
|
||||
destinationWarehouseId: '',
|
||||
destinationWarehouseName: '',
|
||||
pickupMethod: 'SELF_EXPRESS',
|
||||
pickupMethod: 'SELF_TRUCK',
|
||||
trackingNumber: '',
|
||||
channelCode: '',
|
||||
channelName: '',
|
||||
pricingTaxMode: 'TAX_INCLUDED',
|
||||
@@ -429,6 +462,12 @@ function quickOrderDraft() {
|
||||
} catch {
|
||||
// Keep the standard empty row when quick-order data is malformed.
|
||||
}
|
||||
const pricingTaxMode = String(route.query.pricingTaxMode ?? '')
|
||||
if (pricingTaxMode === 'TAX_INCLUDED' || pricingTaxMode === 'TAX_EXCLUDED') draft.pricingTaxMode = pricingTaxMode
|
||||
const grossWeightKg = Number(route.query.grossWeightKg)
|
||||
const volumeCbm = Number(route.query.volumeCbm)
|
||||
if (Number.isFinite(grossWeightKg) && grossWeightKg > 0) draft.items[0].grossWeightKg = grossWeightKg
|
||||
if (Number.isFinite(volumeCbm) && volumeCbm > 0) draft.items[0].volumeCbm = volumeCbm
|
||||
return draft
|
||||
}
|
||||
|
||||
@@ -444,61 +483,60 @@ useUnsavedWorkRegistration({
|
||||
dirty: editorDirty,
|
||||
})
|
||||
|
||||
function matchesAppliedFilters(order: FirstLegOrder) {
|
||||
const statusValue = appliedFilters.value.status
|
||||
const createdRangeValue = appliedFilters.value.createdRange
|
||||
const textValue = (key: string) => typeof appliedFilters.value[key] === 'string' ? String(appliedFilters.value[key]).trim().toLowerCase() : ''
|
||||
const receivingWarehouseId = textValue('receivingWarehouseId')
|
||||
const channelName = textValue('channelName')
|
||||
const cargoKeyword = textValue('cargoKeyword')
|
||||
const destinationType = textValue('destinationType')
|
||||
const trackingNumber = textValue('trackingNumber')
|
||||
const status = typeof statusValue === 'string' ? statusValue as FirstLegOrderStatus | '' : ''
|
||||
const createdRange = Array.isArray(createdRangeValue) ? createdRangeValue.filter((value): value is string => typeof value === 'string') : []
|
||||
const matchesWarehouse = !receivingWarehouseId || order.receivingWarehouseId.toLowerCase() === receivingWarehouseId
|
||||
const matchesChannel = !channelName || order.channelName.toLowerCase() === channelName
|
||||
const matchesCargo = !cargoKeyword || [order.businessSummary.inboundCode, ...order.skuNos, ...order.items.map((item) => item.sku)]
|
||||
.filter(Boolean).some((value) => String(value).toLowerCase().includes(cargoKeyword))
|
||||
const matchesDestinationType = !destinationType || order.destinationType.toLowerCase() === destinationType
|
||||
const matchesTrackingNumber = !trackingNumber || order.trackingNumber.toLowerCase().includes(trackingNumber)
|
||||
const matchesStatus = !status || order.status === status
|
||||
const matchesDate = createdRange.length !== 2 || (order.createdAt.slice(0, 10) >= createdRange[0] && order.createdAt.slice(0, 10) <= createdRange[1])
|
||||
return matchesWarehouse && matchesChannel && matchesCargo && matchesDestinationType && matchesTrackingNumber && matchesStatus && matchesDate
|
||||
}
|
||||
const orderQueueCounts = computed(() => store.queueCounts)
|
||||
const pagedOrders = computed(() => store.orders)
|
||||
|
||||
const queryMatchedOrders = computed(() => store.orders.filter(matchesAppliedFilters))
|
||||
const orderQueueCounts = computed(() => ({
|
||||
all: queryMatchedOrders.value.length,
|
||||
fee: queryMatchedOrders.value.filter((order) => order.businessSummary.customerFeeConfirmationRequired).length,
|
||||
customs: queryMatchedOrders.value.filter((order) => Boolean(eligibleCustomsDetail(order))).length,
|
||||
draft: queryMatchedOrders.value.filter((order) => order.status === 'DRAFT').length,
|
||||
}))
|
||||
const filteredOrders = computed(() => queryMatchedOrders.value.filter((order) => {
|
||||
if (activeOrderQueue.value === 'fee') return order.businessSummary.customerFeeConfirmationRequired
|
||||
if (activeOrderQueue.value === 'customs') return Boolean(eligibleCustomsDetail(order))
|
||||
if (activeOrderQueue.value === 'draft') return order.status === 'DRAFT'
|
||||
return true
|
||||
}))
|
||||
const pagedOrders = computed(() => {
|
||||
const start = (tablePage.value - 1) * tablePageSize.value
|
||||
return filteredOrders.value.slice(start, start + tablePageSize.value)
|
||||
})
|
||||
|
||||
function selectOrderQueue(queue: OrderQueue) {
|
||||
async function selectOrderQueue(queue: OrderQueue) {
|
||||
if (activeOrderQueue.value === queue && !store.loadError) return
|
||||
activeOrderQueue.value = queue
|
||||
tablePage.value = 1
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
async function changeOrderPage(page: number) {
|
||||
tablePage.value = page
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
async function changeOrderPageSize(size: number) {
|
||||
tablePageSize.value = size
|
||||
tablePage.value = 1
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
let orderPageRequestVersion = 0
|
||||
async function loadOrderPage() {
|
||||
const requestVersion = ++orderPageRequestVersion
|
||||
const text = (key: string) => typeof appliedFilters.value[key] === 'string' ? String(appliedFilters.value[key]).trim() || undefined : undefined
|
||||
const range = Array.isArray(appliedFilters.value.createdRange) ? appliedFilters.value.createdRange : []
|
||||
const requestedPage = tablePage.value
|
||||
await store.load({
|
||||
cargoKeyword: text('cargoKeyword'), receivingWarehouseId: text('receivingWarehouseId'),
|
||||
channelName: text('channelName'), destinationType: text('destinationType'),
|
||||
trackingNumber: text('trackingNumber'), mainStatus: text('status'),
|
||||
createdFrom: range[0] ? `${range[0]}T00:00:00` : undefined,
|
||||
createdTo: range[1] ? `${range[1]}T23:59:59.999` : undefined,
|
||||
queue: activeOrderQueue.value, page: requestedPage, size: tablePageSize.value,
|
||||
})
|
||||
if (requestVersion !== orderPageRequestVersion) return
|
||||
const lastPage = Math.max(1, Math.ceil(store.total / tablePageSize.value))
|
||||
if (!store.loadError && requestedPage > lastPage) {
|
||||
tablePage.value = lastPage
|
||||
await loadOrderPage()
|
||||
return
|
||||
}
|
||||
selectedOrders.value = []
|
||||
orderTableVersion.value += 1
|
||||
}
|
||||
|
||||
function eligibleCustomsDetail(order: FirstLegOrder) {
|
||||
const value = customsByOrder[order.id]
|
||||
if (order.status !== 'LOADED' || !value?.merchantStatus) return null
|
||||
if (!isCustomsOrderCandidate(order) || !value?.merchantStatus) return null
|
||||
return value.inbounds.some((item) => item.orderId === order.id && item.taxMode === 'TAX_REFUND') ? value : null
|
||||
}
|
||||
|
||||
async function loadCustomsEligibility(order: FirstLegOrder) {
|
||||
if (order.status !== 'LOADED' || customsByOrder[order.id] !== undefined || customsEligibilityPending.has(order.id)) return
|
||||
if (!isCustomsOrderCandidate(order) || customsByOrder[order.id] !== undefined || customsEligibilityPending.has(order.id)) return
|
||||
customsEligibilityPending.add(order.id)
|
||||
try {
|
||||
customsByOrder[order.id] = await getMerchantCustomsForOrder(order.id)
|
||||
@@ -530,7 +568,9 @@ function openInboundCodeAssociation(inboundCode: string) {
|
||||
}
|
||||
|
||||
function updateCustomsDetail(value: MerchantCustomsContainer) {
|
||||
const previous = customsByOrder[customsDialogOrderId.value]
|
||||
if (customsDialogOrderId.value) customsByOrder[customsDialogOrderId.value] = value
|
||||
if (!isCreatePage.value && !isDetailPage.value && previous && previous.merchantStatus !== value.merchantStatus) void loadOrderPage()
|
||||
}
|
||||
|
||||
const detailOrder = computed(() => detailId.value ? store.getById(detailId.value) : undefined)
|
||||
@@ -542,9 +582,11 @@ const pagedDetailCargoItems = computed(() => {
|
||||
})
|
||||
const progressSummaryItems = computed(() => {
|
||||
const order = detailOrder.value
|
||||
if (!order) return []
|
||||
const inbound = inboundBilling.value?.inbound.summary
|
||||
if (!order || order.status === 'CANCELLED') return []
|
||||
const billing = inboundBillingOrderId.value === order.id ? inboundBilling.value : null
|
||||
const inbound = billing?.inbound.summary
|
||||
const summary = order.businessSummary
|
||||
const billingMetric = orderBillingMetric(billing, summary.chargeableWeightKg)
|
||||
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 transportReference = [summary.vesselName, summary.voyageNo].filter(Boolean).join(' · ')
|
||||
@@ -555,18 +597,18 @@ const progressSummaryItems = computed(() => {
|
||||
{ label: '实际箱数', value: formatMetric(summary.totalPackageCount ?? inbound?.totalPackageCount, '箱') },
|
||||
{ label: '实测毛重', value: formatMetric(summary.actualGrossWeightKg ?? inbound?.actualGrossWeightKg, 'kg') },
|
||||
{ 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: summary.cabinetNo || summary.containerNo || '—' },
|
||||
{ label: '船期摘要', value: transportReference || '待更新' },
|
||||
{ label: '计费重量', value: formatMetric(summary.chargeableWeightKg, 'kg') },
|
||||
{ label: '后续履约', value: summary.deliveryTrackingNo || (summary.deliveryCompletedAt ? `海外回传于 ${formatDateTime(summary.deliveryCompletedAt)}` : '待海外同步') },
|
||||
{ label: billingMetric.label, value: formatMetric(billingMetric.quantity, billingMetric.unit) },
|
||||
{ label: '后续履约', value: orderProgressLabel(store.orderProgress[order.id]) },
|
||||
]
|
||||
})
|
||||
const cabinetProgressItems = computed(() => {
|
||||
const summary = detailOrder.value?.businessSummary
|
||||
if (!summary || (!summary.cabinetNo && !summary.containerNo)) return []
|
||||
return [{ cabinetId: summary.cabinetNo || summary.containerNo, cabinetNo: summary.cabinetNo || summary.containerNo, status: summary.loadingStatus || '待更新', vesselName: summary.vesselName, voyageNo: summary.voyageNo, sailingAt: summary.sailingAt }]
|
||||
return [{ cabinetId: summary.cabinetNo || summary.containerNo, cabinetNo: summary.cabinetNo || summary.containerNo, pickingStatusLabel: getFirstLegPickingStatusLabel(summary.loadingStatus), vesselName: summary.vesselName, voyageNo: summary.voyageNo, estimatedSailingAt: summary.estimatedSailingAt }]
|
||||
})
|
||||
const selectedWarehouse = computed(() => availableWarehouses.value.find((item) => item.id === form.receivingWarehouseId))
|
||||
const selectedDestinationWarehouse = computed(() => store.warehouses.find((item) => item.id === form.destinationWarehouseId && item.warehouseType === form.destinationType))
|
||||
@@ -576,7 +618,14 @@ const hasActiveFilters = computed(() => {
|
||||
const values = appliedFilters.value
|
||||
return Object.values(values).some((value) => Array.isArray(value) ? value.length > 0 : Boolean(typeof value === 'string' ? value.trim() : value))
|
||||
})
|
||||
const emptyDescription = computed(() => hasActiveFilters.value ? '没有符合筛选条件的订单' : '还没有订单')
|
||||
const emptyDescription = computed(() => {
|
||||
if (hasActiveFilters.value) return '没有符合筛选条件的订单'
|
||||
if (activeOrderQueue.value === 'customs') return '暂无需要上传报关资料的订单'
|
||||
if (activeOrderQueue.value === 'fee') return '暂无需要确认计费重的订单'
|
||||
if (activeOrderQueue.value === 'draft') return '暂无草稿订单'
|
||||
if (activeOrderQueue.value !== 'all') return `暂无${ORDER_QUEUES.find(q => q.key === activeOrderQueue.value)?.label ?? ''}的订单`
|
||||
return '还没有订单'
|
||||
})
|
||||
|
||||
async function loadPageData() {
|
||||
supportingDataLoading.value = true
|
||||
@@ -590,7 +639,7 @@ async function loadPageData() {
|
||||
: Promise.resolve()
|
||||
const orderPageRequest = isCreatePage.value || isDetailPage.value
|
||||
? store.loadWarehouseType('DOMESTIC', true)
|
||||
: store.load({ includeDrafts: true })
|
||||
: loadOrderPage()
|
||||
const addressRequest = isCreatePage.value ? loadOrderAddresses() : Promise.resolve()
|
||||
const [ordersResult, companyResult, destinationResult, policyResult, addressResult] = await Promise.allSettled([
|
||||
orderPageRequest,
|
||||
@@ -611,7 +660,6 @@ async function loadPageData() {
|
||||
}
|
||||
if (!isCreatePage.value && ordersResult.status === 'rejected' && !store.loadError) supportingDataErrors.value.push(`订单加载失败:${errorMessage(ordersResult.reason)}`)
|
||||
if (store.warehouseLoadError) supportingDataErrors.value.push(`公共仓库加载失败:${store.warehouseLoadError}`)
|
||||
if (!isCreatePage.value && store.draftLoadError) supportingDataErrors.value.push(`订单草稿加载失败:${store.draftLoadError}`)
|
||||
if (destinationResult.status === 'rejected') supportingDataErrors.value.push(`目的仓加载失败:${errorMessage(destinationResult.reason)}`)
|
||||
if (addressResult.status === 'rejected') supportingDataErrors.value.push(`企业地址簿加载失败:${errorMessage(addressResult.reason)}`)
|
||||
await autofillWarehouseSelections()
|
||||
@@ -627,6 +675,7 @@ async function loadRouteDraft(id: string) {
|
||||
const draft = draftFromOrder(detailedOrder)
|
||||
if (draft.destinationType !== 'PRIVATE') await loadDestinationWarehouses(draft.destinationType)
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (form.receivingWarehouseId) await loadSelectedWarehouse(form.receivingWarehouseId)
|
||||
@@ -850,6 +899,7 @@ function draftFromOrder(order: FirstLegOrder): FirstLegOrderDraft {
|
||||
destinationWarehouseId: order.destinationWarehouseId,
|
||||
destinationWarehouseName: order.destinationWarehouseName,
|
||||
pickupMethod: order.pickupMethod,
|
||||
trackingNumber: order.pickupMethod === 'SELF_EXPRESS' ? order.trackingNumber : '',
|
||||
channelCode: order.channelCode,
|
||||
channelName: order.channelName,
|
||||
pricingTaxMode: order.pricingTaxMode,
|
||||
@@ -872,6 +922,7 @@ function copyDraftFromOrder(order: FirstLegOrder): FirstLegOrderDraft {
|
||||
return {
|
||||
...draft,
|
||||
inboundCode: '',
|
||||
trackingNumber: '',
|
||||
items: draft.items.map((item) => ({
|
||||
...item,
|
||||
id: `copied-cargo-${++cargoSequence}`,
|
||||
@@ -971,6 +1022,7 @@ function createEstimateRequest(): MerchantPriceEstimateRequest | null {
|
||||
destinationWarehouseId: form.destinationType === 'OVERSEAS' ? form.destinationWarehouseId : undefined,
|
||||
destinationName: form.destinationWarehouseName || undefined,
|
||||
pricingTaxMode: form.pricingTaxMode,
|
||||
chargeMode: form.pricingTaxMode === 'TAX_INCLUDED' ? 'KG' : 'CBM',
|
||||
actualWeightKg: summary.grossWeightKg,
|
||||
actualVolumeCbm: summary.volumeCbm,
|
||||
}
|
||||
@@ -1063,6 +1115,7 @@ async function changeDestinationType() {
|
||||
}
|
||||
|
||||
function changePickupMethod() {
|
||||
if (form.pickupMethod !== 'SELF_EXPRESS') form.trackingNumber = ''
|
||||
if (form.pickupMethod === 'PICKUP') {
|
||||
form.shipperPartySnapshot ??= createPickupPartySnapshot()
|
||||
} else {
|
||||
@@ -1267,6 +1320,11 @@ async function autofillWarehouseSelections() {
|
||||
if (form.receivingWarehouseId) {
|
||||
await loadSelectedWarehouse(form.receivingWarehouseId)
|
||||
}
|
||||
if (form.destinationType !== 'PRIVATE' && !form.destinationWarehouseId && form.amazonWarehouseCode) {
|
||||
const destinationCode = form.amazonWarehouseCode.trim().toUpperCase()
|
||||
const matchedDestination = availableDestinationWarehouses.value.find((warehouse) => warehouse.code.trim().toUpperCase() === destinationCode)
|
||||
if (matchedDestination) await selectDestinationWarehouse(matchedDestination.id)
|
||||
}
|
||||
if (form.destinationType !== 'PRIVATE' && !form.destinationWarehouseId && availableDestinationWarehouses.value.length === 1) {
|
||||
await selectDestinationWarehouse(availableDestinationWarehouses.value[0].id)
|
||||
}
|
||||
@@ -1287,6 +1345,9 @@ function getOrderRowActions(row: object): TableAction[] {
|
||||
if (canEditOrder.value && canClientEditFirstLegOrder(order.status)) {
|
||||
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
|
||||
}
|
||||
if (canOfferCancellation(order)) {
|
||||
actions.push({ key: 'cancel', label: '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) })
|
||||
}
|
||||
if (eligibleCustomsDetail(order)) {
|
||||
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
|
||||
}
|
||||
@@ -1349,6 +1410,7 @@ async function openEdit(order: FirstLegOrder) {
|
||||
}
|
||||
}
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (warehouseAvailable) void loadSelectedWarehouse(detailedOrder.receivingWarehouseId)
|
||||
@@ -1373,7 +1435,8 @@ async function loadDetailPage(orderId: string) {
|
||||
detailError.value = ''
|
||||
try {
|
||||
const detailedOrder = await store.loadDetail(orderId)
|
||||
void loadInboundBilling(detailedOrder)
|
||||
if (detailedOrder.status === 'CANCELLED') resetInboundBillingState()
|
||||
else void loadInboundBilling(detailedOrder)
|
||||
// Load previews from the persisted file IDs after the store has replaced the detail row.
|
||||
await Promise.all((detailOrder.value?.items ?? detailedOrder.items).map(ensureProductImagePreview))
|
||||
} catch (error) {
|
||||
@@ -1386,9 +1449,9 @@ async function loadDetailPage(orderId: string) {
|
||||
|
||||
function openFeeConfirmation(order: FirstLegOrder) {
|
||||
resetInboundBillingState()
|
||||
inboundBillingUnavailableMessage.value = '未推送计费重'
|
||||
inboundBillingUnavailableMessage.value = '未推送费用'
|
||||
feeConfirmationOpen.value = true
|
||||
void loadInboundBilling(order, '未推送计费重')
|
||||
void loadInboundBilling(order, '未推送费用')
|
||||
}
|
||||
|
||||
async function retryDetail() {
|
||||
@@ -1423,7 +1486,7 @@ async function loadInboundBilling(order: FirstLegOrder, unavailableMessage = '
|
||||
if (order.status === 'DRAFT') {
|
||||
inboundBillingUnavailable.value = true
|
||||
inboundBillingUnavailableMessage.value = feeConfirmationOpen.value
|
||||
? '未推送计费重'
|
||||
? '未推送费用'
|
||||
: '订单提交后可查看入库结果'
|
||||
return
|
||||
}
|
||||
@@ -1438,7 +1501,7 @@ async function loadInboundBilling(order: FirstLegOrder, unavailableMessage = '
|
||||
if (error instanceof ApiError && error.code === 'A0404') {
|
||||
inboundBillingUnavailable.value = true
|
||||
inboundBillingUnavailableMessage.value = feeConfirmationOpen.value
|
||||
? '未推送计费重'
|
||||
? '未推送费用'
|
||||
: error.message || unavailableMessage
|
||||
} else {
|
||||
inboundBillingError.value = error instanceof Error ? error.message : '入库与费用加载失败'
|
||||
@@ -1450,10 +1513,11 @@ async function loadInboundBilling(order: FirstLegOrder, unavailableMessage = '
|
||||
|
||||
async function retryInboundBilling() {
|
||||
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() {
|
||||
if (!isCreatePage.value && !isDetailPage.value) void loadOrderPage()
|
||||
if (!feeConfirmationOpen.value) void retryInboundBilling()
|
||||
}
|
||||
|
||||
@@ -1665,14 +1729,14 @@ function handleOrderSelectionChange(rows: FirstLegOrder[]) {
|
||||
}
|
||||
|
||||
async function submitSelectedDraftOrders() {
|
||||
const drafts = selectedDraftOrders.value
|
||||
if (batchSubmitting.value || !drafts.length) return
|
||||
const ids = [...new Set(selectedDraftOrders.value.map(order => order.id))]
|
||||
if (batchSubmitting.value || !ids.length) return
|
||||
if (companySubmissionBlocked.value) {
|
||||
ElMessage.warning('企业资料审核通过后才能提交订单')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认提交选中的 ${drafts.length} 条草稿订单吗?`, '批量提交订单', {
|
||||
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?`, '批量提交订单', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '确认提交',
|
||||
cancelButtonText: '取消',
|
||||
@@ -1684,10 +1748,7 @@ async function submitSelectedDraftOrders() {
|
||||
|
||||
batchSubmitting.value = true
|
||||
try {
|
||||
const results = await Promise.allSettled(drafts.map((order) => submitMerchantFirstLegOrder(
|
||||
order.id,
|
||||
createIdempotencyKey(`first-leg-batch-submit-${order.id}`),
|
||||
)))
|
||||
const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined)))
|
||||
const successCount = results.filter((result) => result.status === 'fulfilled').length
|
||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
||||
await searchOrders(appliedFilters.value)
|
||||
@@ -1739,6 +1800,7 @@ function exportOrderInformation() {
|
||||
displayListValue(order.destinationWarehouseName),
|
||||
destinationTypeLabels[order.destinationType],
|
||||
getFirstLegStatusLabel(order.status),
|
||||
orderProgressLabel(store.orderProgress[order.id]),
|
||||
formatListMetric(orderPackageCount(order)),
|
||||
displayListValue(order.expressCompanyName),
|
||||
displayListValue(order.trackingNumber),
|
||||
@@ -1757,7 +1819,7 @@ function exportOrderInformation() {
|
||||
formatExportDateTime(order.createdAt),
|
||||
])
|
||||
downloadCsv('订单信息.csv', [[
|
||||
'入仓码', '渠道', '运输方式', '交货方式', '预约提货时间', '目的仓', '目的仓类型', '当前订单状态', '箱数', '快递公司', '快递单号', 'SKUS',
|
||||
'入仓码', '渠道', '运输方式', '交货方式', '预约提货时间', '目的仓', '目的仓类型', '当前订单状态', '履约进度', '箱数', '快递公司', '快递单号', 'SKUS',
|
||||
'总毛重', '总净重', '总体积', '总数量', '计费单价', '计费体积', '计费重量', '备注',
|
||||
'货件编号', '跟踪编号', '国内仓入库时间', '创建时间',
|
||||
], ...rows])
|
||||
@@ -1881,7 +1943,7 @@ async function submitBatchImport() {
|
||||
batchImportIdempotencyKey.value,
|
||||
)
|
||||
const result = batchImportResult.value.result
|
||||
if (result.succeeded && auth.hasPermission('order:first-leg:list')) await store.load({ includeDrafts: true })
|
||||
if (result.succeeded && auth.hasPermission('order:first-leg:list')) await loadOrderPage()
|
||||
if (result.failed) ElMessage.warning(`导入完成:成功 ${result.succeeded} 条,失败 ${result.failed} 条`)
|
||||
else ElMessage.success(`已成功导入 ${result.succeeded} 条订单草稿`)
|
||||
} catch (error) {
|
||||
@@ -1939,8 +2001,9 @@ async function saveDraft() {
|
||||
if (!await validateEditorForm()) return
|
||||
saving.value = true
|
||||
try {
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = order.id
|
||||
editingSession.value = store.beginDraftEdit(order)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
if (isCreatePage.value) await router.push({ name: 'first-leg-orders' })
|
||||
@@ -1975,8 +2038,9 @@ async function submitOrder() {
|
||||
try {
|
||||
saving.value = true
|
||||
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
|
||||
const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = savedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(savedOrder)
|
||||
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
@@ -1996,37 +2060,13 @@ async function submitOrder() {
|
||||
}
|
||||
|
||||
async function searchOrders(model: QueryModel) {
|
||||
const createdRange = model.createdRange
|
||||
appliedFilters.value = {
|
||||
...model,
|
||||
createdRange: Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||
appliedFilters.value = { ...model,
|
||||
createdRange: Array.isArray(model.createdRange) ? model.createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||
}
|
||||
tablePage.value = 1
|
||||
try {
|
||||
const statusValue = typeof model.status === 'string' ? model.status as FirstLegOrderStatus | '' : ''
|
||||
const cargoKeyword = typeof model.cargoKeyword === 'string' ? model.cargoKeyword.trim() : ''
|
||||
const range = Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : []
|
||||
const query = {
|
||||
keyword: undefined,
|
||||
inboundCode: cargoKeyword || undefined,
|
||||
receivingWarehouseId: typeof model.receivingWarehouseId === 'string' && model.receivingWarehouseId ? model.receivingWarehouseId : undefined,
|
||||
mainStatus: statusValue && statusValue !== 'DRAFT' ? statusValue : undefined,
|
||||
draftOnly: statusValue === 'DRAFT',
|
||||
includeDrafts: !statusValue,
|
||||
createdFrom: range[0] ? `${range[0]}T00:00:00` : undefined,
|
||||
createdTo: range[1] ? `${range[1]}T23:59:59` : undefined,
|
||||
}
|
||||
await store.load(query)
|
||||
const cargoMatched = cargoKeyword && store.orders.some((order) => order.status !== 'DRAFT' && orderMatchesCargoKeyword(order, cargoKeyword))
|
||||
if (cargoKeyword && !cargoMatched && statusValue !== 'DRAFT') {
|
||||
await store.load({ ...query, keyword: undefined, inboundCode: undefined, fbaCode: cargoKeyword })
|
||||
}
|
||||
selectedOrders.value = []
|
||||
orderTableVersion.value += 1
|
||||
} catch {
|
||||
// Store keeps the recoverable error state rendered below the query toolbar.
|
||||
}
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -2035,14 +2075,16 @@ async function searchOrders(model: QueryModel) {
|
||||
<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" />
|
||||
|
||||
<div class="client-card order-table-card">
|
||||
<DataTable v-model:page="tablePage" v-model:page-size="tablePageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="filteredOrders.length" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange">
|
||||
<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">
|
||||
<template #toolbar>
|
||||
<nav class="order-queue-tabs" aria-label="订单事项分类">
|
||||
<button type="button" :class="{ active: activeOrderQueue === 'all' }" @click="selectOrderQueue('all')">全部</button>
|
||||
<button type="button" :class="{ active: activeOrderQueue === 'fee' }" @click="selectOrderQueue('fee')">确认计费重<span v-if="orderQueueCounts.fee" class="queue-count">{{ orderQueueCounts.fee }}</span></button>
|
||||
<button type="button" :class="{ active: activeOrderQueue === 'customs' }" @click="selectOrderQueue('customs')">上传资料<span v-if="orderQueueCounts.customs" class="queue-count">{{ orderQueueCounts.customs }}</span></button>
|
||||
<button type="button" :class="{ active: activeOrderQueue === 'draft' }" @click="selectOrderQueue('draft')">草稿<span v-if="orderQueueCounts.draft" class="queue-count">{{ orderQueueCounts.draft }}</span></button>
|
||||
</nav>
|
||||
<span v-if="selectedOrderCount">已选 {{ selectedOrderCount }} 条</span>
|
||||
</template>
|
||||
<template #toolbar-actions>
|
||||
@@ -2051,7 +2093,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-button class="column-settings-trigger" aria-label="设置订单列表显示列" title="设置显示列"><SlidersHorizontal :size="18" />显示字段筛选</el-button>
|
||||
</template>
|
||||
<div class="column-settings-panel">
|
||||
<p>拖动调整顺序,也可使用上下移动按钮。</p>
|
||||
|
||||
<el-checkbox-group v-model="visibleColumnKeys" aria-label="订单列表显示列">
|
||||
<div
|
||||
v-for="(column, index) in orderedSelectableColumns"
|
||||
@@ -2117,6 +2159,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<template #receivingWarehouse="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).receivingWarehouseName)">{{ displayListValue((row as FirstLegOrder).receivingWarehouseName) }}</span></template>
|
||||
<template #destinationWarehouse="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).destinationWarehouseName)">{{ displayListValue((row as FirstLegOrder).destinationWarehouseName) }}</span></template>
|
||||
<template #destinationType="{ row }">{{ destinationTypeLabels[(row as FirstLegOrder).destinationType] }}</template>
|
||||
<template #progress="{ row }">{{ orderProgressLabel(store.orderProgress[row.id]) }}</template>
|
||||
<template #status="{ row }"><span class="client-status" :data-tone="getFirstLegStatusTone((row as FirstLegOrder).status)">{{ getFirstLegStatusLabel((row as FirstLegOrder).status) }}</span></template>
|
||||
<template #packageCount="{ row }">{{ formatListMetric(orderPackageCount(row as FirstLegOrder)) }}</template>
|
||||
<template #expressCompany="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).expressCompanyName)">{{ displayListValue((row as FirstLegOrder).expressCompanyName) }}</span></template>
|
||||
@@ -2136,7 +2179,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<template #expectedShipDate="{ row }">{{ (row as FirstLegOrder).expectedDepartureDate ? formatDateTime((row as FirstLegOrder).expectedDepartureDate) : '-' }}</template>
|
||||
<template #cabinetNo="{ row }"><span class="table-ellipsis table-code" :title="displayListValue((row as FirstLegOrder).businessSummary.cabinetNo || (row as FirstLegOrder).businessSummary.containerNo)">{{ displayListValue((row as FirstLegOrder).businessSummary.cabinetNo || (row as FirstLegOrder).businessSummary.containerNo) }}</span></template>
|
||||
<template #vesselVoyage="{ row }"><span class="table-ellipsis" :title="displayListValue([(row as FirstLegOrder).businessSummary.vesselName, (row as FirstLegOrder).businessSummary.voyageNo].filter(Boolean).join(' · '))">{{ displayListValue([(row as FirstLegOrder).businessSummary.vesselName, (row as FirstLegOrder).businessSummary.voyageNo].filter(Boolean).join(' · ')) }}</span></template>
|
||||
<template #sailingAt="{ row }">{{ (row as FirstLegOrder).businessSummary.sailingAt ? formatDateTime((row as FirstLegOrder).businessSummary.sailingAt) : '-' }}</template>
|
||||
<template #estimatedSailingAt="{ row }">{{ (row as FirstLegOrder).businessSummary.estimatedSailingAt ? formatDateTime((row as FirstLegOrder).businessSummary.estimatedSailingAt) : '-' }}</template>
|
||||
<template #createdAt="{ row }">{{ formatDateTime((row as FirstLegOrder).createdAt) }}</template>
|
||||
<template #updatedAt="{ row }">{{ formatDateTime((row as FirstLegOrder).updatedAt) }}</template>
|
||||
<template #empty>
|
||||
@@ -2161,17 +2204,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="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 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 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 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_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">
|
||||
<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>
|
||||
</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="州 / 省" 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.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.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="州 / 省" 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.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>
|
||||
<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>
|
||||
@@ -2191,8 +2235,8 @@ async function searchOrders(model: QueryModel) {
|
||||
</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="期望出货日期"><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-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>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -2205,17 +2249,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>
|
||||
</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="`${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>{{ 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>
|
||||
<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>
|
||||
<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="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.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="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="城市" 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="邮编" 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--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.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>
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
@@ -2226,9 +2270,9 @@ async function searchOrders(model: QueryModel) {
|
||||
<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-upload-button" type="primary" plain @click="openBatchImport"><Upload :size="16" />Excel 批量导入</el-button>
|
||||
<span class="cargo-table-hint">Excel 导入用于一次创建多条订单草稿。</span>
|
||||
|
||||
</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>
|
||||
<div class="cargo-table-wrap" :class="{ 'is-dropship': form.fulfillmentType === 'ONE_CLICK_DROPSHIP' }">
|
||||
@@ -2251,7 +2295,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-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><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>
|
||||
</table>
|
||||
</div>
|
||||
@@ -2259,7 +2303,7 @@ async function searchOrders(model: QueryModel) {
|
||||
</section>
|
||||
|
||||
<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 v-if="priceEstimateLoading" class="price-estimate__state" v-loading="true">正在获取实时参考报价</div>
|
||||
<div v-else-if="priceEstimateError" class="price-estimate__state is-error" role="alert">
|
||||
@@ -2337,16 +2381,16 @@ async function searchOrders(model: QueryModel) {
|
||||
<div class="order-detail-heading">
|
||||
<div class="detail-heading-main">
|
||||
<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 === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div>
|
||||
<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>
|
||||
<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></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>
|
||||
<section class="detail-section">
|
||||
<h3>订单与运输</h3>
|
||||
<dl class="order-detail-grid">
|
||||
<div><dt>入仓码</dt><dd><button v-if="detailOrder.businessSummary.inboundCode" class="inbound-code-link table-code" type="button" @click="openInboundCodeAssociation(detailOrder.businessSummary.inboundCode)">{{ detailOrder.businessSummary.inboundCode }}</button><span v-else>{{ detailOrder.status === 'DRAFT' ? '提交后生成' : '待生成' }}</span></dd></div>
|
||||
<div><dt>入仓码</dt><dd><button v-if="detailOrder.businessSummary.inboundCode" class="inbound-code-link table-code" type="button" @click="openInboundCodeAssociation(detailOrder.businessSummary.inboundCode)">{{ detailOrder.businessSummary.inboundCode }}</button><span v-else>{{ detailOrder.status === 'CANCELLED' ? '—' : detailOrder.status === 'DRAFT' ? '提交后生成' : '待生成' }}</span></dd></div>
|
||||
<div><dt>创建时间</dt><dd>{{ formatDateTime(detailOrder.createdAt) }}</dd></div>
|
||||
<div><dt>运输方式</dt><dd>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }}</dd></div>
|
||||
<div><dt>运输方式</dt><dd>{{ detailOrder.status === 'CANCELLED' && !detailOrder.transportMode ? '—' : getFirstLegTransportModeLabel(detailOrder.transportMode) }}</dd></div>
|
||||
<div><dt>贸易条款</dt><dd>{{ displayValue(detailOrder.tradeTerm) }}</dd></div>
|
||||
<div><dt>发货方式</dt><dd>{{ pickupMethodLabels[detailOrder.pickupMethod] }}</dd></div>
|
||||
<div><dt>预约提货时间</dt><dd>{{ detailOrder.pickupMethod === 'PICKUP' && detailOrder.requestedPickupAt ? formatDateTime(detailOrder.requestedPickupAt) : '-' }}</dd></div>
|
||||
@@ -2371,7 +2415,7 @@ async function searchOrders(model: QueryModel) {
|
||||
</dl>
|
||||
<div v-if="detailOrder.customerRemark" class="customer-remark"><strong>客户备注</strong><p>{{ detailOrder.customerRemark }}</p></div>
|
||||
</section>
|
||||
<section v-if="detailOrder.status !== 'DRAFT'" class="detail-section">
|
||||
<section v-if="detailOrder.status !== 'DRAFT' && detailOrder.status !== 'CANCELLED'" class="detail-section">
|
||||
<h3>关键业务摘要</h3>
|
||||
<dl class="fulfillment-summary">
|
||||
<div v-for="item in progressSummaryItems" :key="item.label"><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>
|
||||
@@ -2384,17 +2428,18 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-table v-if="cabinetProgressItems.length" :data="cabinetProgressItems" border size="small" class="cabinet-progress-table" row-key="cabinetId">
|
||||
<el-table-column prop="cabinetNo" label="柜号 / 柜次" min-width="150"><template #default="{ row }"><span class="table-code">{{ row.cabinetNo || '—' }}</span></template></el-table-column>
|
||||
<el-table-column label="船名 / 航次" min-width="180"><template #default="{ row }">{{ [row.vesselName, row.voyageNo].filter(Boolean).join(' · ') || '待更新' }}</template></el-table-column>
|
||||
<el-table-column label="预计船期" width="170"><template #default="{ row }">{{ row.sailingAt ? formatDateTime(row.sailingAt) : '待更新' }}</template></el-table-column>
|
||||
<el-table-column prop="status" label="当前节点" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.status || '待更新' }}</el-tag></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>
|
||||
<p v-else class="detail-inline-empty">尚未分配柜次,后续柜次节点将在这里同步。</p>
|
||||
<p v-else class="detail-inline-empty">尚未分配柜次</p>
|
||||
<TransportFactsTable :fragments="detailOrder.businessSummary.transportFragments" />
|
||||
</div>
|
||||
</template>
|
||||
</OrderProgressPanel>
|
||||
<section class="detail-section">
|
||||
<section v-if="detailOrder.status !== 'CANCELLED' || detailOrder.expressCompanyName || detailOrder.trackingNumber" class="detail-section">
|
||||
<h3>履约快递信息</h3>
|
||||
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || '待平台补充' }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || '待平台补充' }}</dd></div></dl>
|
||||
<div v-else class="express-empty"><PackageCheck :size="20" /><div><strong>平台尚未维护快递信息</strong><span>快递公司和快递单号由平台后台维护,客户端仅只读展示。</span></div></div>
|
||||
<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>
|
||||
</section>
|
||||
<section class="detail-section">
|
||||
<h3>货物明细</h3>
|
||||
@@ -2443,6 +2488,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-empty v-else description="暂无货物明细" :image-size="56" />
|
||||
</section>
|
||||
<InboundBillingPanel
|
||||
v-if="detailOrder.status !== 'CANCELLED'"
|
||||
:data="inboundBilling"
|
||||
:loading="inboundBillingLoading"
|
||||
:unavailable="inboundBillingUnavailable"
|
||||
@@ -2462,7 +2508,7 @@ async function searchOrders(model: QueryModel) {
|
||||
:data="inboundBilling"
|
||||
:loading="inboundBillingLoading"
|
||||
:unavailable="inboundBillingUnavailable"
|
||||
unavailable-message="未推送计费重"
|
||||
unavailable-message="未推送费用"
|
||||
:error="inboundBillingError"
|
||||
:can-confirm="canConfirmInboundFee"
|
||||
@retry="retryInboundBilling"
|
||||
@@ -2500,7 +2546,9 @@ async function searchOrders(model: QueryModel) {
|
||||
.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-table-card { padding: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); box-shadow: none; }
|
||||
.order-queue-tabs { display: flex; align-items: center; gap: 4px; }
|
||||
.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; }
|
||||
.order-queue-tabs button { flex-shrink: 0; white-space: nowrap; }
|
||||
.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:hover { color: var(--client-action); }
|
||||
.order-queue-tabs button.active { border-color: #cfe0ff; background: #f3f7ff; color: var(--client-action); }
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { ref } from 'vue'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const names = ['loadOrderPage', 'changeOrderPage', 'changeOrderPageSize', 'selectOrderQueue', 'searchOrders']
|
||||
const functions = ast.statements.filter(n => ts.isFunctionDeclaration(n) && names.includes(n.name?.text)).map(n => n.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule('let orderPageRequestVersion = 0;\n' + functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
function harness() {
|
||||
const calls = []
|
||||
const values = {
|
||||
tablePage: ref(1), tablePageSize: ref(10), activeOrderQueue: ref('all'), appliedFilters: ref({}),
|
||||
selectedOrders: ref(['previous']), orderTableVersion: ref(0),
|
||||
store: { total: 215, loadError: '', load: async q => { calls.push(q) } },
|
||||
}
|
||||
const handlers = new Function(...Object.keys(values), code + ';return {' + names.join(',') + '}')(...Object.values(values))
|
||||
return { ...values, ...handlers, calls }
|
||||
}
|
||||
test('page events request server pages; size, queue and search reset to the first page', async () => {
|
||||
const h = harness()
|
||||
await h.changeOrderPage(21); assert.equal(h.calls.at(-1).page, 21)
|
||||
await h.changeOrderPageSize(50); assert.equal(h.calls.at(-1).page, 1); assert.equal(h.calls.at(-1).size, 50)
|
||||
await h.selectOrderQueue('customs'); assert.equal(h.calls.at(-1).queue, 'customs'); assert.equal(h.tablePage.value, 1)
|
||||
await h.searchOrders({ cargoKeyword: ' SKU ', status: 'DRAFT', createdRange: ['2026-10-01', '2026-10-03'] })
|
||||
assert.equal(h.calls.at(-1).cargoKeyword, 'SKU'); assert.equal(h.calls.at(-1).mainStatus, 'DRAFT')
|
||||
assert.equal(h.calls.at(-1).createdFrom, '2026-10-01T00:00:00')
|
||||
assert.equal(h.calls.at(-1).createdTo, '2026-10-03T23:59:59.999')
|
||||
assert.deepEqual(h.selectedOrders.value, [])
|
||||
})
|
||||
test('deletion on the last page clamps and reloads once; failed reads retain the requested page for retry', async () => {
|
||||
const h = harness(); h.store.total = 200
|
||||
await h.changeOrderPage(22)
|
||||
assert.deepEqual(h.calls.map(q => q.page), [22, 20]); assert.equal(h.tablePage.value, 20)
|
||||
h.store.total = 0; h.store.loadError = 'failed'
|
||||
await h.changeOrderPage(22)
|
||||
assert.equal(h.tablePage.value, 22); assert.equal(h.calls.length, 3)
|
||||
})
|
||||
test('old same-page response cannot clamp a newer query or clear its current selection', async () => {
|
||||
const h = harness(); let release
|
||||
h.store.load = () => new Promise(resolve => { release = resolve })
|
||||
const first = h.loadOrderPage(); const oldRelease = release
|
||||
const second = h.searchOrders({ cargoKeyword: 'new' })
|
||||
h.store.total = 215; release(); await second
|
||||
h.selectedOrders.value = ['new-selection']
|
||||
oldRelease(); await first
|
||||
assert.deepEqual(h.selectedOrders.value, ['new-selection'])
|
||||
assert.equal(h.orderTableVersion.value, 1)
|
||||
})
|
||||
|
||||
|
||||
test('clicking the current category does not reload or reset its page, but an error can be retried', async () => {
|
||||
const h = harness(); h.tablePage.value = 3
|
||||
await h.selectOrderQueue('all')
|
||||
assert.equal(h.calls.length, 0); assert.equal(h.tablePage.value, 3)
|
||||
h.store.loadError = 'failed'
|
||||
await h.selectOrderQueue('all')
|
||||
assert.equal(h.calls.length, 1); assert.equal(h.tablePage.value, 1)
|
||||
})
|
||||
@@ -201,7 +201,8 @@ function buildOrderDraft(row: QuickOrderRow, channel: QuickChannelOption): First
|
||||
destinationCountryCode: row.destinationCountryCode,
|
||||
destinationWarehouseId: row.destinationWarehouseId,
|
||||
destinationWarehouseName: row.destinationWarehouseName,
|
||||
pickupMethod: 'SELF_EXPRESS',
|
||||
pickupMethod: 'SELF_TRUCK',
|
||||
trackingNumber: '',
|
||||
channelCode: channel.channelCode,
|
||||
channelName: channel.channelName,
|
||||
pricingTaxMode,
|
||||
@@ -421,7 +422,7 @@ onMounted(loadChannels)
|
||||
<section class="quick-order-page" aria-labelledby="quick-order-heading">
|
||||
<header class="quick-order-intro">
|
||||
<h2 id="quick-order-heading">客户下单</h2>
|
||||
<p>只需输入渠道、目的仓、产品 SKU 和箱数,即可快速填写订单。</p>
|
||||
|
||||
<small v-if="manualInboundCodeRequired">当前全局使用旧系统入仓码,每张草稿都需要填写旧系统生成的入仓码。</small>
|
||||
<small>每一行会直接生成一张独立草稿单,其他明细可进入草稿后继续编辑并提交。</small>
|
||||
</header>
|
||||
@@ -482,7 +483,7 @@ onMounted(loadChannels)
|
||||
<td class="products-cell">
|
||||
<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-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>
|
||||
</div>
|
||||
</td>
|
||||
@@ -509,7 +510,7 @@ onMounted(loadChannels)
|
||||
</el-form-item>
|
||||
<el-form-item v-if="destinationForm.type !== 'PRIVATE'" :label="destinationForm.type === 'FBA' ? 'FBA 仓' : '海外仓'" required>
|
||||
<el-select v-model="destinationForm.warehouseId" filterable :loading="destinationLoading" placeholder="请选择当前可送达的目的仓">
|
||||
<el-option v-for="warehouse in availableDestinationWarehouses" :key="warehouse.id" :label="`${warehouse.name} · ${warehouse.code}`" :value="warehouse.id" />
|
||||
<el-option v-for="warehouse in availableDestinationWarehouses" :key="warehouse.id" :label="destinationForm.type === 'FBA' ? warehouse.code : `${warehouse.name} · ${warehouse.code}`" :value="warehouse.id" />
|
||||
</el-select>
|
||||
<small v-if="!destinationLoading && availableDestinationWarehouses.length === 0">平台暂未维护可用目的仓,请联系平台管理员。</small>
|
||||
</el-form-item>
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue'
|
||||
import { Calculator, Search } from '@lucide/vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { estimateMerchantFirstLegPrice, getMerchantPricingChannels, getMerchantWarehouses, type MerchantPriceEstimate, type MerchantPricingChannel, type MerchantWarehouse } from '../api/firstLeg'
|
||||
|
||||
const loading = ref(false); const querying = ref(false); const errorMessage = ref('')
|
||||
const router = useRouter()
|
||||
const warehouses = ref<MerchantWarehouse[]>([]); const destinationWarehouses = ref<MerchantWarehouse[]>([]); const channels = ref<MerchantPricingChannel[]>([]); const quotes = ref<MerchantPriceEstimate[]>([])
|
||||
const quoteDialogOpen = ref(false); const originWarehouseId = ref<string | number>(''); const destinationWarehouseId = ref<string | number>(''); const weight = ref<number | undefined>(); const volume = ref<number | undefined>(); const taxMode = ref<'TAX_INCLUDED' | 'TAX_EXCLUDED'>('TAX_INCLUDED')
|
||||
const selectedDestinationWarehouse = computed(() => destinationWarehouses.value.find((item) => String(item.id) === String(destinationWarehouseId.value)))
|
||||
const destinationCode = computed(() => selectedDestinationWarehouse.value?.warehouseCode || '')
|
||||
const hasMeasureInput = computed(() => Number(weight.value || 0) > 0 || Number(volume.value || 0) > 0)
|
||||
const hasInput = computed(() => Boolean(originWarehouseId.value && destinationWarehouseId.value && hasMeasureInput.value))
|
||||
// The pricing API accepts either dimension, but normalizing both here keeps
|
||||
// every channel on the same calculation path when one field is omitted.
|
||||
const normalizedWeightKg = computed(() => weight.value || (volume.value ? volume.value * 167 : 0))
|
||||
const normalizedVolumeCbm = computed(() => volume.value || (weight.value ? weight.value / 167 : 0))
|
||||
type QuoteCard = { quote: MerchantPriceEstimate; channel: MerchantPricingChannel }
|
||||
const allQuoteCards = computed<QuoteCard[]>(() => quotes.value.map((quote) => ({ quote, channel: channels.value.find((item) => item.channelCode === quote.channelCode) })).filter((item): item is QuoteCard => Boolean(item.channel)))
|
||||
const priceWinner = computed<QuoteCard | undefined>(() => allQuoteCards.value.reduce<QuoteCard | undefined>((winner, item) => !winner || item.quote.estimatedAmount < winner.quote.estimatedAmount ? item : winner, undefined))
|
||||
const timeWinner = computed<QuoteCard | undefined>(() => allQuoteCards.value.reduce<QuoteCard | undefined>((winner, item) => { const days = transitDays(item.channel.referenceTransit); if (days === null) return winner; return !winner || days < transitDays(winner.channel.referenceTransit)! ? item : winner }, undefined))
|
||||
const quoteCards = computed(() => {
|
||||
const prioritized: QuoteCard[] = []
|
||||
if (timeWinner.value) prioritized.push(timeWinner.value)
|
||||
if (priceWinner.value && priceWinner.value.quote.channelCode !== timeWinner.value?.quote.channelCode) prioritized.push(priceWinner.value)
|
||||
const prioritizedCodes = new Set(prioritized.map((item) => item.quote.channelCode))
|
||||
const remaining = [...allQuoteCards.value].filter((item) => !prioritizedCodes.has(item.quote.channelCode)).sort((a, b) => a.quote.estimatedAmount - b.quote.estimatedAmount)
|
||||
return [...prioritized, ...remaining]
|
||||
})
|
||||
const resultSummary = computed(() => {
|
||||
const quoteUnit = (volume.value || 0) >= (weight.value || 0) / 167 ? 'CBM' : 'KG'
|
||||
const quoteQuantity = quoteUnit === 'CBM' ? volume.value : weight.value
|
||||
return `${quoteQuantity || 0} ${quoteUnit} · ${destinationCode.value || '—'} · 匹配 ${quoteCards.value.length} 个渠道`
|
||||
})
|
||||
function transitDays(value: string | null) { const match = value?.match(/\d+/); return match ? Number(match[0]) : null }
|
||||
function formatMoney(item: MerchantPriceEstimate) { const currency = item.currency === 'CNY' ? '¥' : `${item.currency} `; return `${currency}${item.estimatedAmount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` }
|
||||
function formatUnitPrice(item: MerchantPriceEstimate) { const currency = item.currency === 'CNY' ? '¥' : `${item.currency} `; return `${currency}${item.unitPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}/${item.chargeUnit || 'CBM'}` }
|
||||
function recommendation(item: QuoteCard) { if (timeWinner.value?.quote.channelCode === item.quote.channelCode) return { label: '时间优选', className: 'time' }; if (priceWinner.value?.quote.channelCode === item.quote.channelCode) return { label: '价格优选', className: 'price' }; return undefined }
|
||||
async function loadBase() { loading.value = true; errorMessage.value = ''; try { const [originResult, destinationResult] = await Promise.all([getMerchantWarehouses({ warehouseType: 'DOMESTIC' }), getMerchantWarehouses({ warehouseType: 'FBA' })]); warehouses.value = originResult.records; destinationWarehouses.value = destinationResult.records; if (originResult.records[0]) originWarehouseId.value = originResult.records[0].id; if (destinationResult.records[0]) destinationWarehouseId.value = destinationResult.records[0].id; await loadChannels() } catch (error) { errorMessage.value = error instanceof Error ? error.message : '船期价格加载失败' } finally { loading.value = false } }
|
||||
async function loadChannels() { if (!originWarehouseId.value) return; try { channels.value = await getMerchantPricingChannels(originWarehouseId.value) } catch (error) { channels.value = []; errorMessage.value = error instanceof Error ? error.message : '船期渠道加载失败' } }
|
||||
async function query() { const destination = selectedDestinationWarehouse.value; if (!hasInput.value || !destination) { ElMessage.warning('请选择目的 FBA 仓,并填写重量或体积(填写一项即可)'); return }; if (!channels.value.length) { ElMessage.warning('暂无可查询的船期渠道'); return }; querying.value = true; quotes.value = []; try { const results = await Promise.allSettled(channels.value.map((channel) => estimateMerchantFirstLegPrice({ originWarehouseId: originWarehouseId.value, channelCode: channel.channelCode, destinationCode: destination.warehouseCode, destinationType: 'FBA', destinationWarehouseId: destination.id, destinationName: destination.warehouseName, pricingTaxMode: taxMode.value, chargeMode: taxMode.value === 'TAX_INCLUDED' ? 'KG' : 'CBM', actualWeightKg: normalizedWeightKg.value, actualVolumeCbm: normalizedVolumeCbm.value }))); quotes.value = results.flatMap((item) => item.status === 'fulfilled' ? [item.value] : []); if (!quotes.value.length) { const failure = results.find((item): item is PromiseRejectedResult => item.status === 'rejected'); const message = failure?.reason instanceof Error ? failure.reason.message : '当前条件暂无匹配报价'; ElMessage.warning(message); return }; quoteDialogOpen.value = true } finally { querying.value = false } }
|
||||
async function placeOrder(channelCode: string, channelName: string) {
|
||||
if (!quotes.value.some((quote) => quote.channelCode === channelCode)) {
|
||||
ElMessage.warning('请先查询该渠道价格')
|
||||
return
|
||||
}
|
||||
// Release Element Plus dialog scroll locking before changing routes. If the
|
||||
// route is replaced while the close transition is still active, the dialog
|
||||
// can otherwise leave body overflow hidden on the order page.
|
||||
quoteDialogOpen.value = false
|
||||
await nextTick()
|
||||
router.push({
|
||||
name: 'first-leg-order-create',
|
||||
query: {
|
||||
quick: '1',
|
||||
receivingWarehouseId: String(originWarehouseId.value),
|
||||
channelCode,
|
||||
channelName,
|
||||
destinationType: 'FBA',
|
||||
destinationWarehouseId: String(selectedDestinationWarehouse.value!.id),
|
||||
destinationWarehouseName: selectedDestinationWarehouse.value!.warehouseName,
|
||||
amazonWarehouseCode: selectedDestinationWarehouse.value!.warehouseCode,
|
||||
destinationCountryCode: selectedDestinationWarehouse.value!.countryCode || 'US',
|
||||
pricingTaxMode: taxMode.value,
|
||||
grossWeightKg: String(normalizedWeightKg.value),
|
||||
volumeCbm: String(normalizedVolumeCbm.value),
|
||||
cargo: JSON.stringify([{ sku: '', packageCount: 1 }]),
|
||||
},
|
||||
})
|
||||
}
|
||||
watch(originWarehouseId, (value, previous) => { if (!value || previous === '') return; void loadChannels() }); onMounted(() => { void loadBase() })
|
||||
</script>
|
||||
|
||||
<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>
|
||||
<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></section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pricing-page { display:flex; flex-direction:column; gap:16px; }.pricing-heading { display:flex; justify-content:space-between; align-items:flex-start; padding:0 2px; }.eyebrow { color:#5b82c9; font-size:11px; font-weight:750; letter-spacing:.14em; }.pricing-heading h1 { margin:6px 0 5px; color:#1f2f46; font-size:26px; line-height:1.25; letter-spacing:-.025em; }.pricing-heading p { margin:0; color:#7d8da2; font-size:13px; }.refresh-button { margin-top:3px; border-color:#d9e3ef; border-radius:9px; background:#fff; color:#61738b; box-shadow:0 3px 8px rgba(26,55,91,.04); }.pricing-inquiry { position:relative; overflow:hidden; padding:24px; border:1px solid rgba(99,135,255,.36); border-radius:18px; background:linear-gradient(112deg,#152754 0%,#203d8f 42%,#315bd9 75%,#4c70f5 100%); box-shadow:0 14px 36px rgba(31,61,140,.2); }.pricing-inquiry::before { content:''; position:absolute; right:-75px; top:-165px; width:410px; height:410px; border:48px solid rgba(255,255,255,.07); border-radius:50%; background:radial-gradient(circle,rgba(255,255,255,.07),transparent 64%); pointer-events:none; }.inquiry-copy { position:relative; z-index:1; margin-bottom:19px; }.inquiry-copy > span { color:rgba(255,255,255,.7); font-size:10px; font-weight:850; letter-spacing:.18em; }.inquiry-copy h2 { margin:5px 0 4px; color:#fff; font-size:22px; font-weight:850; }.inquiry-copy p { margin:0; color:rgba(255,255,255,.7); font-size:13px; }.pricing-form { position:relative; z-index:1; display:grid; grid-template-columns:minmax(130px,.9fr) minmax(120px,.75fr) minmax(120px,.75fr) minmax(170px,1.1fr) minmax(125px,.8fr) 128px; align-items:end; gap:10px; }.pricing-form :deep(.el-form-item) { margin-bottom:0; }.pricing-form :deep(.el-form-item__label) { height:auto; margin-bottom:8px; color:rgba(255,255,255,.82); font-size:12px; font-weight:750; line-height:1.2; }.pricing-form :deep(.el-input__wrapper), .pricing-form :deep(.el-select__wrapper) { min-height:48px; border:1px solid #d4e0ed; border-radius:11px; background:#fff; box-shadow:0 4px 13px rgba(45,72,105,.04); }.pricing-form :deep(.el-input__inner), .pricing-form :deep(.el-select__selected-item) { color:#24354d; font-size:14px; font-weight:600; }.unit-input { display:flex; min-height:48px; overflow:hidden; border:1px solid #d4e0ed; border-radius:11px; background:#fff; }.unit-input :deep(.el-input__wrapper) { min-height:46px; border:0; box-shadow:none; }.unit-input span { display:flex; align-items:center; padding:0 13px 0 4px; color:#7690ad; font-size:12px; font-weight:750; }.pricing-form :deep(.el-radio-group) { display:flex; min-height:48px; align-items:center; padding:0 4px; border-radius:11px; background:#fff; }.pricing-form :deep(.el-radio-button__inner) { height:40px; padding:12px 12px; border:0; border-radius:8px; color:#61738b; box-shadow:none; }.pricing-form :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) { border-color:#3d70e8; background:#3d70e8; color:#fff; box-shadow:0 5px 12px rgba(37,99,235,.2); }.query-item :deep(.el-form-item__content) { display:block; }.query-item :deep(.el-button) { width:100%; min-height:48px; border:0; border-radius:11px; background:linear-gradient(135deg,#ffca4b,#ffb82e); color:#48350b; box-shadow:0 9px 20px rgba(255,185,46,.25); font-size:14px; font-weight:850; }.query-item :deep(.el-button:hover) { background:linear-gradient(135deg,#ffd363,#ffc13e); color:#48350b; transform:translateY(-1px); }.pricing-results { padding:4px; overflow:hidden; border:1px solid #dce4ef; border-radius:16px; background:#fff; box-shadow:0 5px 16px rgba(31,56,88,.045); }.section-title { display:flex; align-items:center; justify-content:space-between; padding:17px 18px 13px; }.section-title h2 { margin:0 0 4px; color:#20324a; font-size:16px; }.section-title span { color:#7d8da2; font-size:12px; }.section-title svg { color:#3d70e8; }.pricing-results small { display:block; margin-top:3px; color:#7d8da2; font-size:11px; }.pricing-results :deep(.el-table) { --el-table-header-bg-color:#f4f7fb; --el-table-row-hover-bg-color:#eaf2ff; --el-table-border-color:#edf1f6; color:#53647a; }.pricing-results :deep(.el-table th.el-table__cell) { padding:13px 16px; color:#607089; font-size:12px; font-weight:750; }.pricing-results :deep(.el-table td.el-table__cell) { height:58px; padding:13px 16px; font-size:13px; }.pricing-results :deep(.el-table__row:nth-child(even)) { background:#f8fbff; }.pricing-results :deep(.el-button--link) { font-weight:750; }.muted { color:#94a0af; }
|
||||
.quote-dialog { --el-dialog-bg-color:transparent; }.quote-dialog :deep(.el-dialog) { overflow:hidden; border-radius:18px; background:linear-gradient(125deg,#182e69 0%,#274cbd 55%,#416bf1 100%); box-shadow:0 18px 52px rgba(11,31,89,.3); }.quote-dialog :deep(.el-dialog__header) { margin:0; padding:0; }.quote-dialog :deep(.el-dialog__body) { padding:0 14px 16px; }.quote-dialog-head { display:flex; align-items:flex-start; justify-content:space-between; padding:16px 18px 12px; color:#fff; }.quote-dialog-head h3 { margin:0 0 2px; font-size:19px; }.quote-dialog-head span { color:rgba(255,255,255,.72); font-size:12px; }.quote-close { width:36px; height:36px; border:1px solid #cfddf2; border-radius:10px; background:#fff; color:#8392a8; font-size:26px; line-height:29px; cursor:pointer; }.quote-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:12px; align-items:stretch; }.quote-card { position:relative; display:flex; height:100%; min-height:240px; box-sizing:border-box; flex-direction:column; overflow:hidden; padding:18px 17px 14px; border:1px solid #d5deee; border-radius:15px; background:#f8f9fd; color:#263a55; box-shadow:0 6px 16px rgba(22,48,117,.1); }.quote-card.price { border:2px solid #ffae3c; }.quote-card.time { border:2px solid #27c28c; }.quote-ribbon { position:absolute; right:-43px; top:13px; width:130px; padding:5px 0; transform:rotate(43deg); background:#ff8d14; color:#fff; text-align:center; font-size:10px; font-weight:850; }.quote-card.time .quote-ribbon { background:#0db886; }.quote-card-title { display:flex; min-width:0; align-items:flex-start; justify-content:space-between; gap:6px; }.quote-card.price .quote-card-title, .quote-card.time .quote-card-title { padding-right:38px; }.quote-card-title strong { min-width:0; overflow-wrap:anywhere; font-size:16px; line-height:1.25; word-break:break-word; }.quote-card-title span { flex:none; padding:5px 7px; border-radius:15px; background:#edf5ff; color:#367ae0; font-size:10px; font-weight:750; white-space:nowrap; }.quote-price { display:flex; flex-shrink:0; align-items:baseline; gap:6px; margin:17px 0 15px; }.quote-price b { color:#ed5a2a; font-size:26px; line-height:1; white-space:nowrap; }.quote-price small { flex-shrink:0; color:#96a4b8; font-size:12px; }.quote-meta { display:grid; min-width:0; flex:1; grid-template-columns:minmax(0,1fr) minmax(0,1fr); align-content:start; gap:11px 10px; }.quote-meta > div { min-width:0; }.quote-meta span { display:block; margin-bottom:3px; color:#93a0b2; font-size:10px; }.quote-meta strong { display:block; min-width:0; overflow-wrap:anywhere; color:#344961; font-size:12px; line-height:1.35; word-break:break-word; }.quote-order { width:100%; min-height:32px; flex-shrink:0; margin-top:16px; border-radius:7px; font-size:12px; }.quote-card:not(.price):not(.time) .quote-order { background:#fff; }
|
||||
@media (max-width:1200px) { .pricing-form { grid-template-columns:repeat(3,minmax(0,1fr)); }.quote-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
|
||||
@media (max-width:720px) { .quote-grid { grid-template-columns:1fr; }.pricing-form { grid-template-columns:1fr; } }
|
||||
:global(.quote-dialog.el-dialog) { overflow:hidden; border-radius:18px; background:linear-gradient(125deg,#182e69 0%,#274cbd 55%,#416bf1 100%); box-shadow:0 18px 52px rgba(11,31,89,.3); }
|
||||
:global(.quote-dialog.el-dialog .el-dialog__header) { margin:0; padding:0; }
|
||||
:global(.quote-dialog.el-dialog .el-dialog__body) { padding:0 14px 16px; }
|
||||
</style>
|
||||
@@ -1,6 +1,8 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
|
||||
const firstLeg = readFileSync(new URL('./FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const quickOrder = readFileSync(new URL('./QuickOrderView.vue', import.meta.url), 'utf8')
|
||||
@@ -18,7 +20,22 @@ test('uses business identifiers and names without visible internal-ID fallbacks'
|
||||
assert.doesNotMatch(quickOrder, />\{\{ result\.orderNo/)
|
||||
assert.doesNotMatch(customs, /detail\.planNo \|\| detail\.loadingPlanId/)
|
||||
assert.doesNotMatch(overseas, /overseasWarehouseName \|\| (?:item|candidate)\.overseasWarehouseId/)
|
||||
assert.doesNotMatch(overseas, /row\(\[[^\]]*(?:item\.overseasWarehouseId|item\.operatingWarehouseId)/)
|
||||
// Warehouse IDs may be inputs to a resolver, but must never be raw cells.
|
||||
assert.doesNotMatch(overseas, /row\(\[[^\]]*[,[]\s*item\.(?:overseasWarehouseId|operatingWarehouseId)\s*[,\]]/)
|
||||
})
|
||||
|
||||
test('warehouse labels never fall back to unknown internal IDs', () => {
|
||||
const source = overseas.slice(overseas.indexOf('function warehouseDisplay('), overseas.indexOf('function statusLabel('))
|
||||
const javascript = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const display = runInNewContext(`${javascript}; warehouseDisplay`, {
|
||||
operationWarehouses: { value: [{ id: '1234567890123456789', warehouseCode: 'LAX', warehouseName: '洛杉矶仓' }] },
|
||||
fbaWarehouses: { value: [] }, warehouseLabel: (warehouse) => warehouse.warehouseName,
|
||||
})
|
||||
assert.equal(display('1234567890123456789'), '洛杉矶仓')
|
||||
assert.equal(display('LAX'), '洛杉矶仓')
|
||||
assert.equal(display('9999999999999999999'), '—')
|
||||
assert.equal(display('1234567890123456789,9999999999999999999'), '洛杉矶仓、—')
|
||||
assert.equal(display(undefined), '—')
|
||||
})
|
||||
|
||||
test('keeps internal IDs only as non-rendered routing, selection, and request values', () => {
|
||||
|
||||
@@ -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`。
|
||||
@@ -36,7 +36,7 @@ test('keeps customer message actions first and covers the requested local states
|
||||
assert.match(source, /notification-state--error/)
|
||||
assert.match(source, /暂无消息/)
|
||||
assert.doesNotMatch(source, /清空已读|删除消息/)
|
||||
assert.match(source, /Promise\.all\(\[load\(\), notifications\.refreshUnreadCount\(\)\]\)/)
|
||||
assert.match(source, /Promise\.all\(\[load\(\), notifications\.refreshUnreadCount\(true\)\]\)/)
|
||||
assert.match(source, /auth\.hasPermission\('merchant:notification:read'\)/)
|
||||
assert.match(source, /auth\.hasPermission\('merchant:notification:read-all'\)/)
|
||||
assert.match(source, /v-if="canMarkAllRead"/)
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
function setup() {
|
||||
const requests = []
|
||||
const source = readFileSync(new URL('./notifications.ts', import.meta.url), 'utf8').replace(/^import [^\r\n]*\r?\n/gm, '').replace('export const', 'const')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const store = new Function('computed', 'ref', 'defineStore', 'getMyUnreadNotificationCount', code + '\nreturn useNotificationsStore()')(computed, ref, (_id, factory) => factory, () => new Promise((resolve, reject) => requests.push({ resolve, reject })))
|
||||
return { store, requests }
|
||||
}
|
||||
|
||||
test('shell and page concurrent reads share one pending request', async () => {
|
||||
const { store, requests } = setup()
|
||||
const a = store.refreshUnreadCount(), b = store.refreshUnreadCount()
|
||||
assert.equal(requests.length, 1)
|
||||
requests[0].resolve(5)
|
||||
await Promise.all([a, b])
|
||||
assert.equal(store.unreadCount.value, 5)
|
||||
assert.equal(store.loading.value, false)
|
||||
})
|
||||
|
||||
test('post-mutation refresh reads again after a pending pre-mutation read', async () => {
|
||||
const { store, requests } = setup()
|
||||
const a = store.refreshUnreadCount(), b = store.refreshUnreadCount(true)
|
||||
assert.equal(requests.length, 1)
|
||||
requests[0].resolve(5)
|
||||
await a
|
||||
await Promise.resolve()
|
||||
assert.equal(requests.length, 2)
|
||||
requests[1].resolve(0)
|
||||
await b
|
||||
assert.equal(store.unreadCount.value, 0)
|
||||
})
|
||||
|
||||
test('failed request releases the pending guard for retry', async () => {
|
||||
const { store, requests } = setup()
|
||||
const a = store.refreshUnreadCount()
|
||||
requests[0].reject(new Error('network'))
|
||||
await a
|
||||
const b = store.refreshUnreadCount()
|
||||
assert.equal(requests.length, 2)
|
||||
requests[1].resolve(2)
|
||||
await b
|
||||
assert.equal(store.unreadCount.value, 2)
|
||||
assert.equal(store.errorMessage.value, '')
|
||||
})
|
||||
@@ -9,7 +9,19 @@ export const useNotificationsStore = defineStore('client-notifications', () => {
|
||||
|
||||
const hasUnread = computed(() => (unreadCount.value ?? 0) > 0)
|
||||
|
||||
async function refreshUnreadCount() {
|
||||
let pending: Promise<void> | null = null
|
||||
|
||||
async function refreshUnreadCount(afterMutation = false): Promise<void> {
|
||||
if (pending) {
|
||||
if (!afterMutation) return pending
|
||||
await pending
|
||||
return refreshUnreadCount()
|
||||
}
|
||||
pending = loadUnreadCount().finally(() => { pending = null })
|
||||
return pending
|
||||
}
|
||||
|
||||
async function loadUnreadCount() {
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { NotificationDetail } from '../contracts'
|
||||
import { notificationCategoryLabel, notificationSentAt } from '../presentation'
|
||||
const route = useRoute(); const router = useRouter(); const auth = useAuthStore(); const notifications = useNotificationsStore(); const detail = ref<NotificationDetail | null>(null); const loading = ref(false); const errorMessage = ref(''); const readErrorMessage = ref('')
|
||||
const canMarkRead = computed(() => auth.hasPermission('merchant:notification:read'))
|
||||
async function markReadIfAllowed(){if(!detail.value||detail.value.status!=='UNREAD'||!canMarkRead.value)return;try{await markMyNotificationRead(detail.value.id);detail.value={...detail.value,status:'READ'};await notifications.refreshUnreadCount()}catch(error){readErrorMessage.value=error instanceof ApiError?error.message:'消息已加载,但自动标记已读失败'}}
|
||||
async function markReadIfAllowed(){if(!detail.value||detail.value.status!=='UNREAD'||!canMarkRead.value)return;try{await markMyNotificationRead(detail.value.id);detail.value={...detail.value,status:'READ'};await notifications.refreshUnreadCount(true)}catch(error){readErrorMessage.value=error instanceof ApiError?error.message:'消息已加载,但自动标记已读失败'}}
|
||||
async function load(){loading.value=true;errorMessage.value='';readErrorMessage.value='';try{detail.value=await getMyNotification(String(route.params.notificationId));await markReadIfAllowed()}catch(error){detail.value=null;errorMessage.value=error instanceof ApiError?error.message:'消息加载失败,请稍后重试'}finally{loading.value=false}}
|
||||
onMounted(()=>{void load()})
|
||||
</script>
|
||||
|
||||
@@ -78,7 +78,7 @@ async function markRead(row: NotificationSummary) {
|
||||
if (!canMarkRead.value) return
|
||||
try {
|
||||
await markMyNotificationRead(row.id)
|
||||
await Promise.all([load(), notifications.refreshUnreadCount()])
|
||||
await Promise.all([load(), notifications.refreshUnreadCount(true)])
|
||||
} catch (error) {
|
||||
errorMessage.value = messageOf(error)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ async function markAllRead() {
|
||||
markingAll.value = true
|
||||
try {
|
||||
await markAllMyNotificationsRead()
|
||||
await Promise.all([load(), notifications.refreshUnreadCount()])
|
||||
await Promise.all([load(), notifications.refreshUnreadCount(true)])
|
||||
} catch (error) {
|
||||
errorMessage.value = messageOf(error)
|
||||
} finally {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user