Compare commits
327
Commits
3d2344ce0e
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5a6c7fd88 | ||
|
|
d67da9af82 | ||
|
|
d28408f678 | ||
|
|
90ef9893f3 | ||
|
|
aa68e93b08 | ||
|
|
c168afa1e1 | ||
|
|
6355bb69df | ||
|
|
15015d8bfc | ||
|
|
bd8f9433ed | ||
|
|
4db8700817 | ||
|
|
c72c819f95 | ||
|
|
a0e9ad808b | ||
|
|
cd06e264ff | ||
|
|
aaab5041f9 | ||
|
|
700074e983 | ||
|
|
06f91c8b91 | ||
|
|
6cb9b91435 | ||
|
|
6d0eb2a5f3 | ||
|
|
db44d24eb4 | ||
|
|
3692f9d27f | ||
|
|
90e1e646ec | ||
|
|
5751973c83 | ||
|
|
d7f8365ecc | ||
|
|
3cdd14a521 | ||
|
|
509dc677cb | ||
|
|
c0b151bc15 | ||
|
|
639b1ae22c | ||
|
|
33d86d2a64 | ||
|
|
9891ac3e29 | ||
|
|
d2bbd5024b | ||
|
|
07ba9fcb7c | ||
|
|
2aa20b7172 | ||
|
|
c63fb704a2 | ||
|
|
d39c1f4ea7 | ||
|
|
bc84686658 | ||
|
|
62cf7829d3 | ||
|
|
0be4088fa9 | ||
|
|
7759c7e9f3 | ||
|
|
19f060727b | ||
|
|
47385d46f2 | ||
|
|
a853b1e0c2 | ||
|
|
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 | ||
|
|
0fa80874bc | ||
|
|
b4403ab188 | ||
|
|
da0f306d9b | ||
|
|
befd22af96 | ||
|
|
bdb42f1256 | ||
|
|
8048279465 | ||
|
|
a96cbbd57d | ||
|
|
524cf79952 | ||
|
|
3cdd04e9b7 | ||
|
|
386ff8cced | ||
|
|
5887837407 | ||
|
|
97d0f82256 | ||
|
|
3ab07188d1 | ||
|
|
dd7306c7fc | ||
|
|
8a3a90217c | ||
|
|
4b7becf9c2 | ||
|
|
ca7021a145 | ||
|
|
e89b9d3722 | ||
|
|
d6b9d44431 | ||
|
|
4f515982f4 | ||
|
|
63d1bcef26 | ||
|
|
308f7573c1 | ||
|
|
486d5163b2 | ||
|
|
375e5e53ce | ||
|
|
c08a10a125 | ||
|
|
1dcb93c69d | ||
|
|
653e79d3e7 | ||
|
|
3f39264141 | ||
|
|
40f2b2ba11 | ||
|
|
e3d9f8c637 | ||
|
|
6355529627 | ||
|
|
138d4a64dd | ||
|
|
60e875b2c6 | ||
|
|
514abf6eda | ||
|
|
4eb17ece4f | ||
|
|
0303168c26 | ||
|
|
3c17f6a5cd | ||
|
|
77afdb1c42 | ||
|
|
fcb9e584ad | ||
|
|
1d407620d2 | ||
|
|
8fbefcf657 | ||
|
|
e3cca80ff2 | ||
|
|
bb94f88bb3 | ||
|
|
5542ee80e6 | ||
|
|
f5f5525a1b | ||
|
|
5df199a324 | ||
|
|
958da32b00 | ||
|
|
8c078f6208 | ||
|
|
51f27ccda7 | ||
|
|
6c17df2a9b | ||
|
|
8024fd4717 | ||
|
|
cee2818944 | ||
|
|
dd1e6af8b3 | ||
|
|
09b0c4452d | ||
|
|
fbd61debf5 | ||
|
|
7068f49100 | ||
|
|
03c5bf717e | ||
|
|
d0c92f6f84 | ||
|
|
056f9ef073 | ||
|
|
9d6fde286b | ||
|
|
9a8a72b1bd | ||
|
|
c2611a1bfd | ||
|
|
ecd0317b58 | ||
|
|
7e4c452608 | ||
|
|
ad02451065 | ||
|
|
cd057845bf | ||
|
|
7286d08975 | ||
|
|
71ae7e8f18 | ||
|
|
ad4710fac2 | ||
|
|
12edb30cf1 | ||
|
|
61a562b828 | ||
|
|
bee47f1a6c | ||
|
|
23cef8e106 | ||
|
|
ec7f76fede | ||
|
|
80e83a6668 | ||
|
|
53c48501dc | ||
|
|
e1eabf2946 | ||
|
|
55914382de | ||
|
|
b2c92d5666 | ||
|
|
84c3b90d4a | ||
|
|
aa4e1616a1 | ||
|
|
0886c864af | ||
|
|
b506e4e59a | ||
|
|
5c4578ce00 | ||
|
|
56398e98eb | ||
|
|
bab284b865 | ||
|
|
a9de9f762e | ||
|
|
911623d5a3 | ||
|
|
354f65afe8 | ||
|
|
c08c76c22a | ||
|
|
6e4483135b | ||
|
|
e062365ca7 | ||
|
|
7dc02d8327 | ||
|
|
e5039f2707 | ||
|
|
a7f073c783 | ||
|
|
f76c5cfd09 | ||
|
|
2add4b001e | ||
|
|
9b9a2b103c | ||
|
|
1fc730d845 | ||
|
|
c611698aac | ||
|
|
cf79b8cd08 | ||
|
|
72027e7ff2 | ||
|
|
7e596b8d77 | ||
|
|
658b2e84cf | ||
|
|
f11d85e280 | ||
|
|
6c4af419cf | ||
|
|
b13295f292 | ||
|
|
85871d5c2c | ||
|
|
46a91fbca0 | ||
|
|
719a6421c9 | ||
|
|
e81490296e | ||
|
|
dbd3c61996 | ||
|
|
c5ad4af29e | ||
|
|
d9862402d0 | ||
|
|
6998f81738 | ||
|
|
0957324fb0 | ||
|
|
2a7e042420 | ||
|
|
d07d08c7e0 | ||
|
|
af226977be | ||
|
|
cf3a48230e | ||
|
|
ecec741a9d | ||
|
|
e43cb8546e | ||
|
|
213f4da651 | ||
|
|
534f0e1b88 | ||
|
|
278949d3b1 | ||
|
|
57b5e203e8 | ||
|
|
93572fb784 | ||
|
|
c726e1e4a8 | ||
|
|
91e5014fc6 | ||
|
|
fc6756fb5d | ||
|
|
b3649c314a | ||
|
|
39e1c8e6ee | ||
|
|
23f4a9aef9 | ||
|
|
5ba19f6744 | ||
|
|
72d77a7f70 | ||
|
|
7068de5a2f | ||
|
|
5ad42344de | ||
|
|
0622d412a9 | ||
|
|
2285c8bf05 | ||
|
|
e25a244ed9 | ||
|
|
6780228f86 | ||
|
|
a7c36771e4 | ||
|
|
4ee8ac3ee7 | ||
|
|
d1c7bde492 | ||
|
|
12424281c7 | ||
|
|
6d10251161 | ||
|
|
4518ec0ada | ||
|
|
399243974b | ||
|
|
bd9e07d9d3 | ||
|
|
9d53a78b33 | ||
|
|
7636871774 | ||
|
|
517b6718f0 | ||
|
|
255e012c1b | ||
|
|
098355bb66 | ||
|
|
47a47e1e1f | ||
|
|
b3b6ef014f | ||
|
|
7d97be6450 | ||
|
|
6dcea387d3 | ||
|
|
e5e412682c | ||
|
|
d4166a75f8 | ||
|
|
00506b5793 | ||
|
|
4f3b83f16d | ||
|
|
d485719128 | ||
|
|
aadd063028 | ||
|
|
fb8a4743f6 | ||
|
|
16dd722c15 | ||
|
|
1305ae4669 | ||
|
|
f4de324393 | ||
|
|
159b1053a2 | ||
|
|
47fdb67bb1 | ||
|
|
c1e7ba411e | ||
|
|
a831a594a5 | ||
|
|
e22c671de4 | ||
|
|
da92b75ae1 | ||
|
|
bfedef815e | ||
|
|
545a0f23ed | ||
|
|
bf20224a48 | ||
|
|
2cbc362795 | ||
|
|
ee5c0493d0 | ||
|
|
033091ab59 | ||
|
|
a10ee73ba9 | ||
|
|
6a445bbb8f | ||
|
|
f28b7f178b | ||
|
|
22f0528593 | ||
|
|
458c8d5961 | ||
|
|
df4b7eba8e | ||
|
|
040f73c73e | ||
|
|
20a4a51899 | ||
|
|
b7eb6c1acd | ||
|
|
57633f451e | ||
|
|
b12196c7a8 | ||
|
|
63170f9b73 | ||
|
|
cbfefd860e | ||
|
|
cb4729da3d | ||
|
|
6344df7de2 | ||
|
|
f9af04fdd5 | ||
|
|
4618c5a92c | ||
|
|
86e6c81fc7 | ||
|
|
78a2f7da96 | ||
|
|
dca29d5eb0 | ||
|
|
2b25efdfc9 | ||
|
|
ffba7cde03 | ||
|
|
e2e57455e6 | ||
|
|
641ea7f628 |
+3
-1
@@ -4,6 +4,8 @@
|
|||||||
dist
|
dist
|
||||||
node_modules
|
node_modules
|
||||||
node_modules.broken-by-path
|
node_modules.broken-by-path
|
||||||
.env.local
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
npm-debug.log*
|
npm-debug.log*
|
||||||
pnpm-debug.log*
|
pnpm-debug.log*
|
||||||
|
|||||||
+8
-1
@@ -1,3 +1,10 @@
|
|||||||
VITE_API_BASE_URL=/api
|
VITE_API_BASE_URL=/api
|
||||||
API_PROXY_TARGET=http://8.163.30.128:9000
|
API_PROXY_TARGET=http://127.0.0.1:9000
|
||||||
VITE_ADMIN_WEB_ORIGIN=http://localhost:5173
|
VITE_ADMIN_WEB_ORIGIN=http://localhost:5173
|
||||||
|
|
||||||
|
# Test container deployment (Jenkins environment or untracked .env).
|
||||||
|
# API_UPSTREAM: unified Gateway origin, no /api suffix.
|
||||||
|
# TEST_NETWORK: shared test Docker network.
|
||||||
|
API_UPSTREAM=http://gateway:9000
|
||||||
|
TEST_NETWORK=firstleg-test-network
|
||||||
|
IMAGE_TAG=
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,7 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
node_modules.broken-by-path/
|
node_modules.broken-by-path/
|
||||||
dist/
|
dist/
|
||||||
|
tmp/
|
||||||
|
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
@@ -16,4 +17,3 @@ outputs/
|
|||||||
*.log
|
*.log
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|
||||||
|
|||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
Generated
+9
@@ -0,0 +1,9 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="JAVA_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||||
|
<exclude-output />
|
||||||
|
<content url="file://$MODULE_DIR$" />
|
||||||
|
<orderEntry type="inheritedJdk" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
|
||||||
|
<output url="file://$PROJECT_DIR$/out" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/client-web.iml" filepath="$PROJECT_DIR$/.idea/client-web.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
## 项目定位
|
## 项目定位
|
||||||
|
|
||||||
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
|
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
|
||||||
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单,以及客户财务账单查询与客户确认。
|
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。
|
||||||
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及海外 API、海外 Token 或跨区域事件时读取 `../../docs/跨区域认证与服务通信契约.md`。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及统一 API、Token、会话撤销或可靠事件时按需读取 `../../docs/统一认证与服务通信契约.md` 对应章节。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
||||||
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
|
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
|
||||||
|
|
||||||
## 技术基线
|
## 技术基线
|
||||||
@@ -26,43 +26,54 @@
|
|||||||
- 模块内 `store/`:该业务跨页面状态;局部表单状态仍留在页面或组件内。跨模块使用 store 时只能导入其公开 store 文件,不得读取模块内部页面或组件实现。
|
- 模块内 `store/`:该业务跨页面状态;局部表单状态仍留在页面或组件内。跨模块使用 store 时只能导入其公开 store 文件,不得读取模块内部页面或组件实现。
|
||||||
- `src/api/`:只保留 HTTP、会话令牌、响应类型等全局请求基础设施;业务接口放入对应模块的 `api/`。页面不得直接创建独立 Axios 客户端。
|
- `src/api/`:只保留 HTTP、会话令牌、响应类型等全局请求基础设施;业务接口放入对应模块的 `api/`。页面不得直接创建独立 Axios 客户端。
|
||||||
- 模块之间不得通过相对路径或内部目录穿透;确需协作时只能从目标模块的 `public.ts` 导入。模块内稳定契约放在 `contracts.ts`,稳定的跨应用模型仍应上移到 `@chongchong/shared`。
|
- 模块之间不得通过相对路径或内部目录穿透;确需协作时只能从目标模块的 `public.ts` 导入。模块内稳定契约放在 `contracts.ts`,稳定的跨应用模型仍应上移到 `@chongchong/shared`。
|
||||||
- `VITE_API_BASE_URL` 控制浏览器请求前缀,`API_PROXY_TARGET` 控制 Vite 开发代理上游;后者只由开发服务器读取,不进入客户端构建。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
|
- `VITE_API_BASE_URL` 控制唯一浏览器 API 前缀;全部业务共用 `src/api/http.ts` 和同一 Access/Refresh Token。`API_PROXY_TARGET` 仅供本地 Vite 代理连接测试入口,不进入客户端构建。独立海外 HTTP 客户端与代理已移除。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
|
||||||
- `src/styles/`:全局设计令牌和布局;优先复用现有 `--primary`、`--navy`、`--border`、`--muted`。
|
- `src/styles/`:全局设计令牌和布局;优先复用现有 `--primary`、`--navy`、`--border`、`--muted`。
|
||||||
- 本应用多个模块稳定复用的前端模型放到应用内 `shared/`,客户工作台专属类型保留在对应业务模块。不要链接应用目录之外的 TypeScript 包,服务端契约以 `baiyue-firstleg` Controller/OpenAPI 为准。
|
- 本应用多个模块稳定复用的前端模型放到应用内 `shared/`,客户工作台专属类型保留在对应业务模块。不要链接应用目录之外的 TypeScript 包,服务端契约以 `baiyue-firstleg` Controller/OpenAPI 为准。
|
||||||
|
|
||||||
## 开发环境样式验收
|
## 测试环境样式验收
|
||||||
|
|
||||||
- 默认验收身份:`merchant_admin`,用于“客户端”的样式、路由、权限展示和交互验收。
|
- 测试环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。
|
||||||
- 密码不写入仓库;从本机未提交环境变量 `CHONGCHONG_CLIENT_ACCEPTANCE_PASSWORD` 或 `C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env` 读取。若凭据不存在,再向用户索取,不重复询问账号名。
|
- 账号与密码不写入仓库;从本机未提交环境变量或 `C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env` 读取。若显式验收凭据不存在,再向用户索取。
|
||||||
- 该身份仅适用于开发环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;开发环境变更时只更新本机凭据。
|
- 当前只有一个测试环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;测试环境变更时只更新本机凭据。
|
||||||
- 由人工使用该身份进入真实页面,按 `1920×1080` 视口和 `100%` 浏览器缩放完成操作与截图,再把截图发送给 AI 核对加载、空态、错误态、权限态和桌面布局;AI 默认不主动调用截图或视觉类技能取证。
|
- 由人工使用该身份进入真实页面,按 `1920×1080` 视口和 `100%` 浏览器缩放完成操作与截图,再把截图发送给 AI 核对加载、空态、错误态、权限态和桌面布局;AI 默认不主动调用截图或视觉类技能取证。
|
||||||
|
|
||||||
## 模块快速查询
|
## 模块快速查询
|
||||||
|
|
||||||
|
退货预报与签收结果:`src/modules/overseas-warehouse/views/ReturnOrdersView.vue`、`api/returnOrders.ts`;菜单仍名为“退货换标”。列表路由 `return-relabel`、独立新建路由 `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/registry.ts` 确认模块,再按目标模块的 `routes.ts → views/ → api/、store/、contracts.ts 或 public.ts` 查询。页面是否正式开放以 `routes.ts` 的 `release` 为准,不从任务或进度文档推断。
|
||||||
|
|
||||||
| 业务 | 模块入口 | 联查模块或服务端 |
|
| 业务 | 模块入口 | 联查模块或服务端 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 登录、注册与会话 | `src/modules/auth/` | Backend `auth/`、`iam/` |
|
| 登录、注册与会话 | `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/`、`file/` |
|
| 企业资料、成员与角色 | `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/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/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/firstLeg.ts` 进入 | Backend `order/`、`firstleg/`、`warehouse/`;稳定箱码与打印契约先读 Backend `firstleg/AGENTS.md` |
|
| 头程下单、中文批量导入、入仓码关系、箱唛、履约进度与入库费用确认 | `src/modules/first-leg/`;列表与批量入口 `views/FirstLegOrdersView.vue`,模板/导入 API `api/firstLeg.ts`,入仓详情 `components/InboundCodeAssociationDialog.vue`、`api/inboundCodeAssociations.ts`,独立计费重弹框 `components/InboundBillingPanel.vue`、`api/inboundBilling.ts` | 中文 XLSX 模板按当前客户生成地址、全部有效仓库和渠道下拉,最多 50 行,只创建草稿并支持部分/原子导入;导入结果只显示 Excel 行号,不展示内部 `clientRowId`。所有订单行均可进入计费重弹框,尚未推送时展示明确空态;只有具备编辑权限且服务端返回当前 `SENT` 费用时才可二次确认并提交 `expectedFeeVersion` 与幂等键,成功后版本锁定、平台不得再修改。Backend `order/`、`firstleg/`、`warehouse/`,不得用内部 ID 补齐缺失业务编号 |
|
||||||
|
| 装柜完成后的退税报关资料 | `src/modules/first-leg/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/order-management/` | `src/modules/first-leg/` 与对应后端订单契约 |
|
||||||
| 客户财务账单、收款、未收余额与客户确认 | `src/modules/finance/`;确认入口 `views/FinanceBillsView.vue`、`api/finance.ts` | Backend `finance/`;只能查看登录态客户的已出账账单。出账或已出账调整后为 `PENDING_CONFIRMATION`,客户确认以登录成员、`expectedVersion` 和幂等键提交,成功后记录确认人姓名快照与时间 |
|
| 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `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/cross-border/`、`src/modules/overseas-warehouse/` | 先核对各自 `routes.ts` 的发布状态与阶段范围,不自动扩展实现 |
|
| 客户资金账户、授信与充值申请 | `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 |
|
||||||
|
|
||||||
## 租户、认证与数据安全
|
## 租户、认证与数据安全
|
||||||
|
|
||||||
|
- 换标申请必须提交正数 CNY `chargeAmount`;入口为 `src/modules/overseas-warehouse/views/WarehouseServiceView.vue` 与 `api/warehouseServices.ts`,金额由服务端再次校验,资金状态以服务端返回为准,不在客户端模拟冻结成功。
|
||||||
|
|
||||||
- 任何查询和变更都必须以服务端确认的当前租户为边界;绝不从可篡改的前端参数推断授权租户。
|
- 任何查询和变更都必须以服务端确认的当前租户为边界;绝不从可篡改的前端参数推断授权租户。
|
||||||
- 企业成员、角色和权限只能管理当前企业范围。前端隐藏不是安全控制,服务端必须重复校验租户与权限。
|
- 企业成员、角色和权限只能管理当前企业范围。前端隐藏不是安全控制,服务端必须重复校验租户与权限。
|
||||||
- 认证统一经过 `src/modules/auth/store/auth.ts` 和 `src/api/http.ts`;不要在页面中复制令牌逻辑或持久化密码、敏感资质内容。
|
- 注册时登录手机号同时初始化公司联系电话;注册完成后两者独立维护。企业资料只修改 `contactPhone`,个人资料或成员管理中的登录手机号由 IAM/Auth 同步并撤销该账号现有会话,不得在前端互相回填或联动提交。
|
||||||
|
- 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;全部请求共用统一 Access Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。
|
||||||
- 当前认证仍包含模拟数据。接入真实 API 后移除对应模拟分支,生产环境不得回退为模拟成功。
|
- 当前认证仍包含模拟数据。接入真实 API 后移除对应模拟分支,生产环境不得回退为模拟成功。
|
||||||
|
- 头程订单统一使用当前正式读写契约;不得继续扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API、历史部分响应兼容或其他新旧并跑逻辑。触及该链路时按根无兼容规则同步删除生产分支、类型、文案、Mock 和测试,不以现有代码或测试仍覆盖旧路径作为保留依据。
|
||||||
- 注册、上传资质、成员邀请和订单操作必须提供明确校验、幂等保护、提交中状态和可恢复的失败反馈。
|
- 注册、上传资质、成员邀请和订单操作必须提供明确校验、幂等保护、提交中状态和可恢复的失败反馈。
|
||||||
|
|
||||||
## UI 与交互
|
## UI 与交互
|
||||||
|
|
||||||
- 修改已有 Client 原型页面前先读 `../../docs/Admin-Client前端原型还原验收规则.md`,按页面和操作形成原型核对矩阵;本节维护 Client 的实现约束,不复制跨前端验收文档全文。
|
- 视觉还原、布局/交互承载方式变更或真实页面验收时读取 `../../docs/Admin-Client前端原型还原验收规则.md`,只为受影响操作形成原型核对矩阵;纯文案、逻辑或测试修改不自动读取。自动检查与人工视觉验收分开报告,无视觉变化时标记“无需视觉验收”。
|
||||||
- 已向客户讲解或确认过的产品原型是页面视觉与布局实现的直接事实来源。字段顺序、字段分组、字段摆放、列宽、控件宽高、对齐方式、换行方式、区块层级、上下左右边距、内边距、间隙、留白、圆角、边框、阴影、背景色、文字颜色和字号均必须按原型还原,不得只参考大致风格后自行重新排版。
|
- 已向客户讲解或确认过的产品原型是页面视觉与布局实现的直接事实来源。字段顺序、字段分组、字段摆放、列宽、控件宽高、对齐方式、换行方式、区块层级、上下左右边距、内边距、间隙、留白、圆角、边框、阴影、背景色、文字颜色和字号均必须按原型还原,不得只参考大致风格后自行重新排版。
|
||||||
- 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。
|
- 原型中的按钮位置、顺序、尺寸、圆角、边框、背景色、文字色、图标、悬停态、激活态、禁用态和危险语义必须直接按原型实现;不得擅自改为文字链接、不同颜色、不同按钮类型、折叠菜单或自创交互效果,也不得增加原型没有的上浮、缩放、渐变线、装饰图标或其他视觉元素。
|
||||||
- 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。
|
- 原型已经给出明确图标、字符图标、图片资源或按钮内图标时,直接使用原型中的同一方案和资源,不得以 Lucide、Element Plus 默认图标、手绘图标或个人偏好替换。仅当原型没有定义对应图标时,才按本节的默认图标语义补齐。
|
||||||
@@ -92,18 +103,18 @@ pnpm build
|
|||||||
|
|
||||||
## 全量验收脚本
|
## 全量验收脚本
|
||||||
|
|
||||||
- Client 全量验收唯一入口为 `../../baiyue-firstleg/scripts/client-test-env-acceptance.mjs`;二期专项场景才单独执行 `client-phase2-test-env-acceptance.mjs`,不替代完整入口。
|
- Client 全量验收唯一入口为 `../../baiyue-firstleg/scripts/client-test-env-acceptance.mjs`;入库测量与计费专项场景才单独执行 `client-phase2-test-env-acceptance.mjs`,不替代完整入口。
|
||||||
- 入口通过测试环境 HTTP 验证注册/审核、客户隔离、订单、入库计费、文件、财务和权限链路,会创建或修改测试数据,必须获得当前对话明确授权。
|
- 入口通过测试环境 HTTP 验证注册/审核、客户隔离、订单、入库计费、文件、财务和权限链路,会创建或修改测试数据,必须获得当前对话明确授权。
|
||||||
- `pnpm test/typecheck` 和 `frontend-full-regression.ps1` 仅是本地质量检查,不代表 Client 服务已完成全量验收。
|
- `pnpm test/typecheck` 和 `frontend-full-regression.ps1` 仅是本地质量检查,不代表 Client 服务已完成全量验收。
|
||||||
- HTTP 验收通过后,由人工使用开发验收账号逐页检查真实接口调用、客户可见字段、原型、权限、错误态、空态和 `1920×1080` 桌面布局,并将截图发送给 AI 分析;未收到人工截图时标记为待人工确认,不追加 AI 截图或窄屏浏览器验收。
|
- HTTP 验收通过后,由人工使用开发验收账号逐页检查真实接口调用、客户可见字段、原型、权限、错误态、空态和 `1920×1080` 桌面布局,并将截图发送给 AI 分析;未收到人工截图时标记为待人工确认,不追加 AI 截图或窄屏浏览器验收。
|
||||||
|
|
||||||
## Client 全量验收快速索引
|
## Client 全量验收快速索引
|
||||||
|
|
||||||
当前按客户侧全量业务闭环验收。阶段文档仍用于核对功能来源和验收证据,不再限制本次验收的模块范围;按“模块 `routes.ts` → 页面/组件 → `api`、store、contracts”定位。本表只描述 Client 页面与客户可见契约,服务端实现详见后端模块指引。
|
当前按客户侧全量业务闭环验收。业务域文档用于核对功能来源和验收证据,不限制本次验收的模块范围;按“模块 `routes.ts` → 页面/组件 → `api`、store、contracts”定位。本表只描述 Client 页面与客户可见契约,服务端实现详见后端模块指引。
|
||||||
|
|
||||||
| 验收域 | Client 范围与代码入口 | 验收首读 |
|
| 验收域 | Client 范围与代码入口 | 验收首读 |
|
||||||
|---|---|---|---|
|
|---|---|---|
|
||||||
| 客户基础与订单 | 登录/注册、企业资料与资质、成员/角色权限、工作台和订单 | `src/modules/auth/`、`tenant-management/`、`account/`、`system/`、`dashboard/`、`first-leg/`、`order-management/`;按客户可见契约核对权限、状态、幂等和错误处理 |
|
| 客户基础与订单 | 登录/注册、企业资料与资质、成员/角色权限、工作台和订单 | `src/modules/auth/`、`tenant-management/`、`account/`、`system/`、`dashboard/`、`first-leg/`、`order-management/`;按客户可见契约核对权限、状态、幂等和错误处理 |
|
||||||
| 履约与财务 | 入库计费、柜次进度、船期、消息和客户账单 | `src/modules/first-leg/`、`finance/`、`notifications/`;按服务端权限核对客户可见字段和只读/写入边界 |
|
| 履约、海外仓与财务 | 入库计费、柜次进度、船期、海外仓贴标/转运/废弃/退货换标、消息和客户账单 | `src/modules/first-leg/`、`overseas-warehouse/`、`finance/`、`notifications/`;按服务端权限核对客户可见字段、客户隔离和只读/写入边界 |
|
||||||
|
|
||||||
客户侧边界:仍以服务端权限和客户可见字段为准;PDA、平台后台操作和内部证据不因全量验收自动暴露到 Client。财务按 `../../docs/财务管理/` 与 `src/modules/finance/routes.ts` 定位。
|
客户侧边界:仍以服务端权限和客户可见字段为准;PDA、平台后台操作和内部证据不因全量验收自动暴露到 Client。财务按 `../../docs/财务管理/` 与 `src/modules/finance/routes.ts` 定位。
|
||||||
|
|||||||
+6
-3
@@ -1,5 +1,8 @@
|
|||||||
# 构建 Vue 静态文件
|
# 构建 Vue 静态文件。CI 通过构建参数切换到内网基础镜像,
|
||||||
FROM node:22-alpine AS build
|
# 本地开发仍可使用 Docker Hub 默认值。
|
||||||
|
ARG NODE_IMAGE=node:22-alpine
|
||||||
|
ARG NGINX_IMAGE=nginx:1.27-alpine
|
||||||
|
FROM ${NODE_IMAGE} AS build
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -21,7 +24,7 @@ ENV VITE_ADMIN_WEB_ORIGIN=${VITE_ADMIN_WEB_ORIGIN}
|
|||||||
RUN pnpm build
|
RUN pnpm build
|
||||||
|
|
||||||
# 运行阶段仅保留构建产物与 Nginx。
|
# 运行阶段仅保留构建产物与 Nginx。
|
||||||
FROM nginx:1.27-alpine
|
FROM ${NGINX_IMAGE}
|
||||||
|
|
||||||
COPY nginx/default.conf.template /etc/nginx/templates/default.conf.template
|
COPY nginx/default.conf.template /etc/nginx/templates/default.conf.template
|
||||||
COPY --from=build /app/dist /usr/share/nginx/html
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|||||||
Vendored
+38
-70
@@ -1,94 +1,62 @@
|
|||||||
pipeline {
|
pipeline {
|
||||||
agent any
|
agent { label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : 'java-test'}" }
|
||||||
|
|
||||||
environment {
|
|
||||||
DEVELOPMENT_SSH_TARGET = 'deploy@172.31.198.8'
|
|
||||||
DEVELOPMENT_SSH_KEY = '/var/jenkins_home/.ssh/dev_deploy'
|
|
||||||
DEVELOPMENT_SSH_KNOWN_HOSTS = '/var/jenkins_home/.ssh/known_hosts'
|
|
||||||
DEVELOPMENT_DEPLOY_DIR = '/opt/firstleg/frontend/client-web'
|
|
||||||
}
|
|
||||||
|
|
||||||
options {
|
options {
|
||||||
timestamps()
|
timestamps()
|
||||||
disableConcurrentBuilds()
|
disableConcurrentBuilds()
|
||||||
}
|
}
|
||||||
|
|
||||||
stages {
|
stages {
|
||||||
stage('确认提交版本') {
|
stage('检查测试发布参数') {
|
||||||
|
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||||
steps {
|
steps {
|
||||||
script {
|
script {
|
||||||
env.IS_DEVELOPMENT = env.JOB_BASE_NAME?.endsWith('-dev') ? 'true' : 'false'
|
if (env.JOB_BASE_NAME?.endsWith('-dev')) {
|
||||||
env.SOURCE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
error('此流水线仅支持 test 和本轮授权的 prod 灰度')
|
||||||
}
|
}
|
||||||
sh 'git log -1 --oneline'
|
env.IMAGE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||||
|
}
|
||||||
|
sh '''set -eu
|
||||||
|
export API_UPSTREAM="${API_UPSTREAM:-http://gateway:9000}"
|
||||||
|
export TEST_NETWORK="${TEST_NETWORK:-firstleg-test-network}"
|
||||||
|
: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN 未设置}"
|
||||||
|
docker network inspect "$TEST_NETWORK" >/dev/null
|
||||||
|
docker compose -f docker-compose.test.yml config --quiet
|
||||||
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
stage('构建并部署测试前端') {
|
stage('构建并部署测试前端') {
|
||||||
when { expression { env.IS_DEVELOPMENT != 'true' } }
|
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||||
steps {
|
steps {
|
||||||
sh '''
|
sh '''set -eu
|
||||||
set -eu
|
|
||||||
docker compose -f docker-compose.test.yml build --pull=false
|
docker compose -f docker-compose.test.yml build --pull=false
|
||||||
docker compose -f docker-compose.test.yml up -d --remove-orphans
|
docker compose -f docker-compose.test.yml up -d --wait --wait-timeout 120
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('构建并部署开发前端') {
|
|
||||||
when { expression { env.IS_DEVELOPMENT == 'true' } }
|
|
||||||
steps {
|
|
||||||
sh '''
|
|
||||||
set -eu
|
|
||||||
image="client-web-development:${SOURCE_TAG}"
|
|
||||||
ssh_args="-i ${DEVELOPMENT_SSH_KEY} -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=${DEVELOPMENT_SSH_KNOWN_HOSTS} -o ConnectTimeout=10"
|
|
||||||
|
|
||||||
docker build \
|
|
||||||
--build-arg VITE_ADMIN_WEB_ORIGIN=http://8.163.49.32:9001 \
|
|
||||||
-t "$image" .
|
|
||||||
docker save "$image" | gzip -1 | ssh $ssh_args "$DEVELOPMENT_SSH_TARGET" 'gzip -dc | docker load'
|
|
||||||
|
|
||||||
ssh $ssh_args "$DEVELOPMENT_SSH_TARGET" "install -d -m 750 '$DEVELOPMENT_DEPLOY_DIR'"
|
|
||||||
scp $ssh_args docker-compose.development.yml \
|
|
||||||
"$DEVELOPMENT_SSH_TARGET:$DEVELOPMENT_DEPLOY_DIR/docker-compose.yml.tmp"
|
|
||||||
ssh $ssh_args "$DEVELOPMENT_SSH_TARGET" \
|
|
||||||
"mv -f '$DEVELOPMENT_DEPLOY_DIR/docker-compose.yml.tmp' '$DEVELOPMENT_DEPLOY_DIR/docker-compose.yml'"
|
|
||||||
|
|
||||||
ssh $ssh_args "$DEVELOPMENT_SSH_TARGET" sh -s -- "$DEVELOPMENT_DEPLOY_DIR" "$SOURCE_TAG" <<'REMOTE'
|
|
||||||
set -eu
|
|
||||||
cd "$1"
|
|
||||||
export IMAGE_TAG="$2"
|
|
||||||
docker compose -f docker-compose.yml up -d --remove-orphans --pull never
|
|
||||||
docker compose -f docker-compose.yml ps
|
|
||||||
docker compose -f docker-compose.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
|
||||||
REMOTE
|
|
||||||
'''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('部署检查') {
|
|
||||||
when { expression { env.IS_DEVELOPMENT != '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
|
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
stage('发布临时生产灰度') {
|
||||||
|
when { expression { env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||||
|
steps {
|
||||||
|
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')
|
||||||
|
]) {
|
||||||
|
sh 'sh scripts/deploy-production.sh'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
post {
|
post {
|
||||||
failure {
|
failure {
|
||||||
sh '''
|
script {
|
||||||
if [ "${IS_DEVELOPMENT:-false}" = "true" ]; then
|
if (!env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||||
ssh -i "$DEVELOPMENT_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
sh 'docker compose -f docker-compose.test.yml logs --tail=100 || true'
|
||||||
-o UserKnownHostsFile="$DEVELOPMENT_SSH_KNOWN_HOSTS" \
|
}
|
||||||
"$DEVELOPMENT_SSH_TARGET" 'docker logs --tail=100 client-web-development || true' || true
|
}
|
||||||
else
|
|
||||||
docker compose -f docker-compose.test.yml logs --tail=100 || true
|
|
||||||
fi
|
|
||||||
'''
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ pnpm install
|
|||||||
pnpm dev
|
pnpm dev
|
||||||
```
|
```
|
||||||
|
|
||||||
生产构建:
|
发布资源构建:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pnpm typecheck
|
pnpm typecheck
|
||||||
@@ -35,16 +35,22 @@ pnpm test
|
|||||||
|
|
||||||
依赖和 `pnpm-lock.yaml` 均保存在当前前端项目中,不需要在仓库根目录安装 Node 依赖。
|
依赖和 `pnpm-lock.yaml` 均保存在当前前端项目中,不需要在仓库根目录安装 Node 依赖。
|
||||||
|
|
||||||
一期路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限和头程订单。登录、注册、退出、令牌刷新、个人资料、修改密码、企业资料、企业资质、权限资源、角色列表/新增/授权和成员完整维护已经接入一期后端接口;开发代理默认转发到测试环境 `http://8.163.30.128:9000`,可通过 `API_PROXY_TARGET` 覆盖。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
|
订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经统一 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。本地代理仅通过 `API_PROXY_TARGET` 配置统一 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
|
||||||
|
|
||||||
认证会话保存 Access Token 和轮换后的 Refresh Token,并对并发 401 请求执行单次刷新。刷新或会话上下文加载遇到临时网络故障、超时等非认证错误时保留当前有效 Token,只有服务端明确返回 401/会话失效才清理登录状态。客户端只接受 `app_code` 为 `MERCHANT` 的 JWT;页面权限通过当前用户授权接口实时加载,不从 JWT 携带或解析角色权限。前端权限仅用于导航和交互控制,服务端仍须按用户、客户和权限编码完成最终授权。
|
认证会话保存 Access Token 和轮换后的 Refresh Token,并对并发 401 请求执行单次刷新。刷新或会话上下文加载遇到临时网络故障、超时等非认证错误时保留当前有效 Token,只有服务端明确返回 401/会话失效才清理登录状态。客户端只接受 `app_code` 为 `MERCHANT` 的 JWT;页面权限通过当前用户授权接口实时加载,不从 JWT 携带或解析角色权限。前端权限仅用于导航和交互控制,服务端仍须按用户、客户和权限编码完成最终授权。
|
||||||
|
|
||||||
登录表单在开发和生产环境均默认留空;URL 显式传入的登录用户名仍优先。源码和构建产物不得包含联调账号、默认密码或开发提示文案。
|
登录表单在开发和生产环境默认留空;用户主动选择“记住账号”后只回填登录账号、不保存密码,也不改变 Access/Refresh Token 的持久化和刷新策略;URL 显式传入的登录用户名仍优先。源码和构建产物不得包含联调账号、默认密码或开发提示文案。
|
||||||
|
|
||||||
“我的信息”使用真实个人资料和修改密码接口,姓名、电话、邮箱按服务端约束维护;修改密码成功后清理旧会话并返回登录页。成员列表返回姓名、联系方式和 `roleIds`,新增、编辑、角色全量保存、启停和管理员重置密码均使用真实接口,不回退静态成功。角色页同时加载成员关系,直接打开或刷新后成员数仍按真实 `roleIds` 统计。角色列表返回 `permissionIds`,页面可回显并全量保存角色权限;角色编辑、启停、删除分别调用 `PUT /merchant/v1/iam/roles/{roleId}`、`PUT /merchant/v1/iam/roles/{roleId}/status` 和 `DELETE /merchant/v1/iam/roles/{roleId}`,内置角色及仍有关联成员的角色继续受保护。
|
“我的信息”使用真实个人资料和修改密码接口,姓名、电话、邮箱按服务端约束维护;修改密码成功后清理旧会话并返回登录页。成员列表返回姓名、联系方式和 `roleIds`,新增、编辑、角色全量保存、启停和管理员重置密码均使用真实接口,不回退静态成功。角色页同时加载成员关系,直接打开或刷新后成员数仍按真实 `roleIds` 统计。角色列表返回 `permissionIds`,页面可回显并全量保存角色权限;角色编辑、启停、删除分别调用 `PUT /merchant/v1/iam/roles/{roleId}`、`PUT /merchant/v1/iam/roles/{roleId}/status` 和 `DELETE /merchant/v1/iam/roles/{roleId}`,内置角色及仍有关联成员的角色继续受保护。
|
||||||
|
|
||||||
企业资料和资质列表使用真实租户接口,覆盖 `PROFILE_REQUIRED`、`PENDING`、`ACTIVE`、`REJECTED`、`DISABLED` 五种企业状态。企业名称、法定名称和联系人信息支持真实保存;营业执照、法人身份证为必填资质,货代资质证书和银行开户许可证为选填资质,均使用文件服务分别上传,接受 PDF、JPG、PNG 且不超过 5MB;两项必填资质齐全后可显式提交审核,文件预览通过当前商户 Token 临时下载并在关闭弹窗后释放。
|
企业资料和资质列表使用真实租户接口,覆盖 `PROFILE_REQUIRED`、`PENDING`、`ACTIVE`、`REJECTED`、`DISABLED` 五种企业状态。企业名称、法定名称和联系人信息支持真实保存;营业执照、法人身份证为必填资质,货代资质证书和银行开户许可证为选填资质,均使用文件服务分别上传,接受 PDF、JPG、PNG 且不超过 5MB;两项必填资质齐全后可显式提交审核,文件预览通过当前商户 Token 临时下载并在关闭弹窗后释放。
|
||||||
|
|
||||||
头程订单列表、详情、仓库查询、创建/编辑草稿和提交已经接入真实 API,并显式映射后端 `transportMode`、`containerMode` 和订单状态。创建与提交请求携带幂等键,`merchant:order:create`、`merchant:order:edit`、`merchant:order:submit` 分别映射到独立前端操作权限。页面补齐渠道、提货方式、报关模式、目的仓类型、包装类型等后端必填字段;API 模式先清空本地记录,请求失败不会回退模拟成功。FBA 和海外仓按公共仓类型筛选,选择后由仓库主数据生成目的仓字段,不再要求客户重复选择收货单位;私人仓才填写并按当前用户缓存收件资料。只有“我司提货”需要填写提货联系人和地址,其他送货方式不发送发货方快照,订单也不再依赖往来单位 `customerId`。快递信息仍由平台维护、客户只读。订单取消不属于本轮本地一期验收,客户端不暴露取消写操作。订单产品状态仍按已确认的七状态执行,不设置“已驳回”;若兼容旧接口数据收到 `REJECTED`,只按待审核展示且不开放编辑。
|
头程订单列表、详情、仓库查询、创建/编辑草稿和提交已经接入真实 API,并显式映射后端 `transportMode`、`containerMode` 和订单状态。创建与提交请求携带幂等键,`merchant:order:create`、`merchant:order:edit`、`merchant:order:submit` 分别映射到独立前端操作权限。页面补齐渠道、提货方式、报关模式、目的仓类型、包装类型等后端必填字段;API 模式先清空本地记录,请求失败不会回退模拟成功。FBA 和海外仓按公共仓类型筛选,选择后由仓库主数据生成目的仓字段,不再要求客户重复选择收货单位;私人仓才填写并按当前用户缓存收件资料。只有“我司提货”需要填写提货联系人和地址,其他送货方式不发送发货方快照,订单也不再依赖往来单位 `customerId`。快递信息仍由平台维护、客户只读。订单取消不属于本轮本地订单与客户验收,客户端不暴露取消写操作。订单产品状态仍按已确认的七状态执行,不设置“已驳回”;若兼容旧接口数据收到 `REJECTED`,只按待审核展示且不开放编辑。
|
||||||
|
|
||||||
联调远端 Gateway 时可在启动命令前设置 `API_PROXY_TARGET=http://8.163.30.128:9000`;进程环境变量优先于 `.env` 文件。浏览器仍统一请求同源 `/api`,源码中不写死业务服务地址。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。2026-07-31 测试 Gateway 登录和真实角色列表读取正常;Warehouse 服务已注册,但仓库和往来单位业务查询仍返回 `S0500`,头程草稿创建和相关浏览器流程需待后端修复后继续验收。
|
联调远端 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,11 +0,0 @@
|
|||||||
services:
|
|
||||||
client-web:
|
|
||||||
image: client-web-development:${IMAGE_TAG:?IMAGE_TAG is required}
|
|
||||||
container_name: client-web-development
|
|
||||||
restart: unless-stopped
|
|
||||||
ports:
|
|
||||||
- "9002:80"
|
|
||||||
extra_hosts:
|
|
||||||
- "host.docker.internal:host-gateway"
|
|
||||||
environment:
|
|
||||||
API_UPSTREAM: "http://host.docker.internal:9000"
|
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
name: firstleg-prod-client-web
|
||||||
|
services:
|
||||||
|
client-web:
|
||||||
|
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:-29012}:80"
|
||||||
|
environment:
|
||||||
|
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:
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
|
external: true
|
||||||
|
name: firstleg-production-network
|
||||||
+19
-7
@@ -1,17 +1,29 @@
|
|||||||
|
name: firstleg-test-client-web
|
||||||
services:
|
services:
|
||||||
client-web:
|
client-web:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
args:
|
args:
|
||||||
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:-http://8.163.30.128:9001}"
|
NODE_IMAGE: "${NODE_BASE_IMAGE:-node:22-alpine}"
|
||||||
image: client-web-test:local
|
NGINX_IMAGE: "${NGINX_BASE_IMAGE:-nginx:1.27-alpine}"
|
||||||
|
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN is required}"
|
||||||
|
image: client-web-test:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||||
container_name: client-web-test
|
container_name: client-web-test
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 12
|
||||||
|
start_period: 5s
|
||||||
ports:
|
ports:
|
||||||
- "${HOST_PORT:-9002}:80"
|
- "127.0.0.1:${HOST_PORT:-9002}:80"
|
||||||
extra_hosts:
|
|
||||||
- "host.docker.internal:host-gateway"
|
|
||||||
environment:
|
environment:
|
||||||
# Gateway 与前端容器在同一台测试服务器,通过宿主机内部地址访问。
|
API_UPSTREAM: "${API_UPSTREAM:-http://gateway:9000}"
|
||||||
API_UPSTREAM: "${API_UPSTREAM:-http://host.docker.internal:9000}"
|
networks:
|
||||||
|
- test-backend
|
||||||
|
networks:
|
||||||
|
test-backend:
|
||||||
|
external: true
|
||||||
|
name: "${TEST_NETWORK:-firstleg-test-network}"
|
||||||
|
|||||||
@@ -12,3 +12,5 @@
|
|||||||
<script type="module" src="/src/main.ts"></script>
|
<script type="module" src="/src/main.ts"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -11,19 +11,34 @@ server {
|
|||||||
return 200 "ok\n";
|
return 200 "ok\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# SPA 入口每次重新校验,避免发布后浏览器继续运行旧资源清单。
|
||||||
|
location = /index.html {
|
||||||
|
add_header Cache-Control "no-store, no-cache, must-revalidate" always;
|
||||||
|
add_header Pragma "no-cache" always;
|
||||||
|
add_header Expires "0" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Vite 产物文件名带内容哈希,可安全长期缓存。
|
||||||
|
location /assets/ {
|
||||||
|
try_files $uri =404;
|
||||||
|
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||||
|
}
|
||||||
|
|
||||||
# 前端统一请求 /api,保持原始路径转发给 Gateway。
|
# 前端统一请求 /api,保持原始路径转发给 Gateway。
|
||||||
location /api/ {
|
location /api/ {
|
||||||
client_max_body_size 12m;
|
client_max_body_size 55m;
|
||||||
proxy_pass ${API_UPSTREAM};
|
proxy_pass ${API_UPSTREAM};
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $proxy_host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# 支持 Vue Router history 路由直接刷新。
|
# 支持 Vue Router history 路由直接刷新。
|
||||||
location / {
|
location / {
|
||||||
|
add_header Cache-Control "no-store, no-cache, must-revalidate" always;
|
||||||
try_files $uri $uri/ /index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@chongchong/shared": "link:./shared",
|
"@chongchong/shared": "link:./shared",
|
||||||
"axios": "^1.18.1",
|
"axios": "^1.18.1",
|
||||||
|
"dayjs": "^1.11.21",
|
||||||
"element-plus": "^2.14.3",
|
"element-plus": "^2.14.3",
|
||||||
"@lucide/vue": "^1.27.0",
|
"@lucide/vue": "^1.27.0",
|
||||||
"pinia": "^4.0.2",
|
"pinia": "^4.0.2",
|
||||||
|
|||||||
Generated
+3
@@ -17,6 +17,9 @@ importers:
|
|||||||
axios:
|
axios:
|
||||||
specifier: ^1.18.1
|
specifier: ^1.18.1
|
||||||
version: 1.18.1(debug@4.4.3)
|
version: 1.18.1(debug@4.4.3)
|
||||||
|
dayjs:
|
||||||
|
specifier: ^1.11.21
|
||||||
|
version: 1.11.21
|
||||||
element-plus:
|
element-plus:
|
||||||
specifier: ^2.14.3
|
specifier: ^2.14.3
|
||||||
version: 2.14.3(vue@3.5.40(typescript@5.9.3))
|
version: 2.14.3(vue@3.5.40(typescript@5.9.3))
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,12 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 240 240" role="img" aria-labelledby="title desc">
|
||||||
|
<title id="title">开发环境示例收款二维码</title>
|
||||||
|
<desc id="desc">仅用于开发流程验收,不包含真实收款信息</desc>
|
||||||
|
<rect width="240" height="240" fill="#fff"/>
|
||||||
|
<g fill="#111827">
|
||||||
|
<path d="M16 16h64v64H16zm10 10v44h44V26zm10 10h24v24H36zM160 16h64v64h-64zm10 10v44h44V26zm10 10h24v24h-24zM16 160h64v64H16zm10 10v44h44v-44zm10 10h24v24H36z"/>
|
||||||
|
<path d="M96 16h12v12H96zm24 0h12v24h-12zm16 8h12v12h-12zM88 44h20v12H88zm28 8h12v20h-12zm20-8h12v28h-12zM88 84h12v20H88zm24 0h28v12h-28zm36 4h12v20h-12zm20 0h20v12h-20zm28 0h28v12h-28zM16 96h20v12H16zm32-8h12v28H48zm20 8h20v12H68zm96 16h20v12h-20zm32-8h28v12h-28zM16 124h12v20H16zm20-8h20v12H36zm32 4h20v20H68zm92 16h12v16h-12zm20-4h20v12h-20zm28 4h16v20h-16zM92 160h20v12H92zm28-8h12v28h-12zm16 8h20v12h-20zm28 0h20v20h-20zm32 4h28v12h-28zM88 188h12v20H88zm20-4h20v12h-20zm28 4h16v20h-16zm28 0h12v12h-12zm20 0h20v12h-20zm28 4h12v28h-12zM96 216h24v8H96zm36-4h28v12h-28zm48 4h20v8h-20z"/>
|
||||||
|
</g>
|
||||||
|
<rect x="82" y="100" width="76" height="42" rx="5" fill="#fff" stroke="#111827" stroke-width="3"/>
|
||||||
|
<text x="120" y="119" text-anchor="middle" font-family="Arial, sans-serif" font-size="13" font-weight="700" fill="#111827">开发示例</text>
|
||||||
|
<text x="120" y="135" text-anchor="middle" font-family="Arial, sans-serif" font-size="10" fill="#b42318">不可付款</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,58 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
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 "$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 "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||||
|
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$@"
|
||||||
|
}
|
||||||
|
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
|
||||||
|
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"
|
||||||
+5
-5
@@ -19,12 +19,12 @@
|
|||||||
- 当前开发阶段按目标模型直接修改;破坏性修改必须同步更新当前应用全部消费者、测试和接口映射,不保留旧模型兼容分支。
|
- 当前开发阶段按目标模型直接修改;破坏性修改必须同步更新当前应用全部消费者、测试和接口映射,不保留旧模型兼容分支。
|
||||||
- 本包没有独立质量脚本;变更后运行父应用声明的类型检查、测试或构建命令。
|
- 本包没有独立质量脚本;变更后运行父应用声明的类型检查、测试或构建命令。
|
||||||
|
|
||||||
## 一期/二期/三期契约索引
|
## 订单与客户/入库测量与计费/国内货柜履约契约索引
|
||||||
|
|
||||||
- 一期共享模型服务客户认证、企业资料/成员权限和头程订单;修改订单状态、仓库摘要、资质或权限枚举前,先核对阶段契约并搜索 `src/modules/` 全部消费者。
|
- 订单与客户共享模型服务客户认证、企业资料/成员权限和头程订单;修改订单状态、仓库摘要、资质或权限枚举前,先核对阶段契约并搜索 `src/modules/` 全部消费者。
|
||||||
- 二期仅承接客户可见的到仓与计费结果。`WAIT_SPLIT + APPROVED + CONFIRMED` 为当前终点;内部测量明细、备注和文件权限不得通过共享类型绕过。
|
- 入库测量与计费仅承接客户可见的到仓与计费结果。`WAIT_SPLIT + APPROVED + CONFIRMED` 为当前终点;内部测量明细、备注和文件权限不得通过共享类型绕过。
|
||||||
- 三期仅在服务端字段、权限和 OpenAPI 已稳定,且确有多个 Client 模块复用时才新增共享导出;先读 `../../../docs/三期/三期开工门禁.md`。只建客户可见的柜次、进度、授权回执和船期类型,不通过 shared 暴露照片、锁码或后台内部资料。
|
- 国内货柜履约仅在服务端字段、权限和 OpenAPI 已稳定,且确有多个 Client 模块复用时才新增共享导出;先读 `../../../docs/国内货柜履约/国内货柜履约开工门禁.md`。只建客户可见的柜次、进度、授权回执和船期类型,不通过 shared 暴露照片、锁码或后台内部资料。
|
||||||
|
|
||||||
定位规则:从 `src/index.ts` 的导出开始,反查模块 `api`、store 和 `contracts.ts` 消费者;字段含义不明确时回到服务端 DTO/OpenAPI,不在 shared 中扩展业务语义。
|
定位规则:从 `src/index.ts` 的导出开始,反查模块 `api`、store 和 `contracts.ts` 消费者;字段含义不明确时回到服务端 DTO/OpenAPI,不在 shared 中扩展业务语义。
|
||||||
|
|
||||||
阶段文档入口(路径相对本文件所在目录):一期 `../../../docs/一期/README.md`;二期 `../../../docs/二期/README.md` 与 `../../../docs/二期/二期需求优化版-v2-测量计费入库主流程.md`;三期 `../../../docs/三期/README.md`、`../../../docs/三期/三期开发规划.md` 和 `../../../docs/三期/三期需求确认表.md`。范围与契约以阶段确认和设计文档为准,原型只作补充。
|
业务域文档入口(路径相对本文件所在目录):订单与客户 `../../../docs/订单与客户/README.md`;入库测量与计费 `../../../docs/入库测量与计费/README.md` 与 `../../../docs/入库测量与计费/入库测量与计费需求优化版-v2-测量计费入库主流程.md`;国内货柜履约 `../../../docs/国内货柜履约/README.md`、`../../../docs/国内货柜履约/国内货柜履约开发规划.md` 和 `../../../docs/国内货柜履约/国内货柜履约需求确认表.md`。范围与契约以正式确认和设计文档为准,原型只作补充。
|
||||||
|
|||||||
@@ -86,10 +86,13 @@ export const FIRST_LEG_ORDER_STATUSES = [
|
|||||||
{ code: 'DRAFT', label: '草稿' },
|
{ code: 'DRAFT', label: '草稿' },
|
||||||
{ code: 'PENDING_REVIEW', label: '待审核' },
|
{ code: 'PENDING_REVIEW', label: '待审核' },
|
||||||
{ code: 'WAIT_MEASURE', label: '待测量数据' },
|
{ code: 'WAIT_MEASURE', label: '待测量数据' },
|
||||||
|
{ code: 'WAIT_PALLETIZE', label: '待组托' },
|
||||||
{ code: 'WAIT_SPLIT', label: '待分柜' },
|
{ code: 'WAIT_SPLIT', label: '待分柜' },
|
||||||
{ code: 'LOADING', label: '装柜中' },
|
{ code: 'LOADING', label: '装柜中' },
|
||||||
{ code: 'LOADED', label: '装柜完成' },
|
{ code: 'LOADED', label: '装柜完成' },
|
||||||
{ code: 'DELIVERED', label: '派送完成' },
|
{ code: 'DELIVERED', label: '派送完成' },
|
||||||
|
{ code: 'COMPLETED', label: '已完成' },
|
||||||
|
{ code: 'CANCELLED', label: '已取消' },
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
|
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
|
||||||
|
|||||||
+31
-11
@@ -1,32 +1,52 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onBeforeUnmount, onMounted } from 'vue'
|
import { onBeforeUnmount, onMounted } from 'vue'
|
||||||
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
|
||||||
let readyInterval: number | null = null
|
let readyInterval: number | null = null
|
||||||
|
let expectedAdminOrigin = ''
|
||||||
|
let impersonationExchangePending = false
|
||||||
|
|
||||||
|
function configuredImpersonationOrigin() {
|
||||||
|
const queryOrigin = new URLSearchParams(window.location.search).get('impersonationOrigin')
|
||||||
|
if (queryOrigin) {
|
||||||
|
try { return new URL(queryOrigin).origin } catch { return '' }
|
||||||
|
}
|
||||||
|
return String(import.meta.env.VITE_ADMIN_WEB_ORIGIN || '').trim() || window.location.origin
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
const configuredAdminOrigin = String(import.meta.env.VITE_ADMIN_WEB_ORIGIN || '').trim()
|
expectedAdminOrigin = configuredImpersonationOrigin()
|
||||||
const targetOrigin = configuredAdminOrigin || window.location.origin
|
if (!window.opener || !expectedAdminOrigin) return
|
||||||
const announceReady = () => window.opener?.postMessage({ source: 'chongchong-client', type: 'impersonation-ready' }, targetOrigin)
|
window.addEventListener('message', acceptImpersonationTicket)
|
||||||
|
const announceReady = () => window.opener?.postMessage({ source: 'chongchong-client', type: 'impersonation-ready' }, expectedAdminOrigin)
|
||||||
announceReady()
|
announceReady()
|
||||||
readyInterval = window.setInterval(announceReady, 300)
|
readyInterval = window.setInterval(announceReady, 300)
|
||||||
window.setTimeout(() => {
|
window.setTimeout(() => {
|
||||||
if (readyInterval !== null) window.clearInterval(readyInterval)
|
if (readyInterval !== null) window.clearInterval(readyInterval)
|
||||||
readyInterval = null
|
readyInterval = null
|
||||||
}, 10000)
|
}, 10000)
|
||||||
window.addEventListener('message', stopReadyAnnouncement)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
function stopReadyAnnouncement(event: MessageEvent<unknown>) {
|
async function acceptImpersonationTicket(event: MessageEvent<unknown>) {
|
||||||
const configuredAdminOrigin = String(import.meta.env.VITE_ADMIN_WEB_ORIGIN || '').trim()
|
const message = event.data as { source?: string; type?: string; code?: string } | null
|
||||||
const expectedAdminOrigin = configuredAdminOrigin || window.location.origin
|
if (event.source !== window.opener || event.origin !== expectedAdminOrigin || message?.source !== 'chongchong-admin' || message.type !== 'impersonation-ticket' || !message.code || impersonationExchangePending) return
|
||||||
const message = event.data as { source?: string; type?: string } | null
|
impersonationExchangePending = true
|
||||||
if (event.source !== window.opener || event.origin !== expectedAdminOrigin || message?.source !== 'chongchong-admin' || message.type !== 'impersonation-ticket' || readyInterval === null) return
|
if (readyInterval !== null) window.clearInterval(readyInterval)
|
||||||
window.clearInterval(readyInterval)
|
|
||||||
readyInterval = null
|
readyInterval = null
|
||||||
|
const auth = useAuthStore()
|
||||||
|
try {
|
||||||
|
await auth.acceptImpersonationCode(message.code)
|
||||||
|
window.opener?.postMessage({ source: 'chongchong-client', type: 'impersonation-complete' }, expectedAdminOrigin)
|
||||||
|
window.location.replace('/')
|
||||||
|
} catch {
|
||||||
|
window.opener?.postMessage({ source: 'chongchong-client', type: 'impersonation-failed' }, expectedAdminOrigin)
|
||||||
|
window.location.replace('/login?impersonation=failed')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
if (readyInterval !== null) window.clearInterval(readyInterval)
|
if (readyInterval !== null) window.clearInterval(readyInterval)
|
||||||
window.removeEventListener('message', stopReadyAnnouncement)
|
window.removeEventListener('message', acceptImpersonationTicket)
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
import { coordinateCrossTabRefresh } from './crossTabRefresh.ts'
|
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from './crossTabRefresh.ts'
|
||||||
|
|
||||||
test('reuses tokens rotated by another browser tab while waiting for the refresh lock', async () => {
|
test('reuses tokens rotated by another browser tab while waiting for the refresh lock', async () => {
|
||||||
let currentRefreshToken = 'refresh-old'
|
let currentRefreshToken = 'refresh-old'
|
||||||
@@ -10,7 +10,7 @@ test('reuses tokens rotated by another browser tab while waiting for the refresh
|
|||||||
configurable: true,
|
configurable: true,
|
||||||
value: {
|
value: {
|
||||||
locks: {
|
locks: {
|
||||||
async request(_name, callback) {
|
async request(_name, _options, callback) {
|
||||||
currentRefreshToken = 'refresh-new'
|
currentRefreshToken = 'refresh-new'
|
||||||
return callback()
|
return callback()
|
||||||
},
|
},
|
||||||
@@ -41,7 +41,7 @@ test('refreshes normally when this tab owns the current refresh token', async ()
|
|||||||
const originalNavigator = globalThis.navigator
|
const originalNavigator = globalThis.navigator
|
||||||
Object.defineProperty(globalThis, 'navigator', {
|
Object.defineProperty(globalThis, 'navigator', {
|
||||||
configurable: true,
|
configurable: true,
|
||||||
value: { locks: { request: async (_name, callback) => callback() } },
|
value: { locks: { request: async (_name, _options, callback) => callback() } },
|
||||||
})
|
})
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -76,3 +76,32 @@ test('does not wait for rotation after the shared session was removed', async ()
|
|||||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: originalNavigator })
|
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: originalNavigator })
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('aborts a refresh lock that cannot be acquired', async () => {
|
||||||
|
const originalNavigator = globalThis.navigator
|
||||||
|
Object.defineProperty(globalThis, 'navigator', {
|
||||||
|
configurable: true,
|
||||||
|
value: {
|
||||||
|
locks: {
|
||||||
|
request(_name, options) {
|
||||||
|
return new Promise((_resolve, reject) => {
|
||||||
|
options.signal.addEventListener('abort', () => reject(options.signal.reason), { once: true })
|
||||||
|
})
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
await assert.rejects(coordinateCrossTabRefresh({
|
||||||
|
lockName: 'client-refresh',
|
||||||
|
lockTimeoutMs: 5,
|
||||||
|
observedRefreshToken: 'refresh-old',
|
||||||
|
currentRefreshToken: () => 'refresh-old',
|
||||||
|
reuseCurrentSession: async () => 'unexpected',
|
||||||
|
refresh: async () => 'unexpected',
|
||||||
|
}), CrossTabRefreshTimeoutError)
|
||||||
|
} finally {
|
||||||
|
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: originalNavigator })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,11 +1,21 @@
|
|||||||
export interface CrossTabRefreshOptions<T> {
|
export interface CrossTabRefreshOptions<T> {
|
||||||
lockName: string
|
lockName: string
|
||||||
|
lockTimeoutMs?: number
|
||||||
observedRefreshToken: string
|
observedRefreshToken: string
|
||||||
currentRefreshToken: () => string
|
currentRefreshToken: () => string
|
||||||
reuseCurrentSession: () => Promise<T>
|
reuseCurrentSession: () => Promise<T>
|
||||||
refresh: (refreshToken: string) => Promise<T>
|
refresh: (refreshToken: string) => Promise<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class CrossTabRefreshTimeoutError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('登录状态刷新等待超时,请重新登录')
|
||||||
|
this.name = 'CrossTabRefreshTimeoutError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_LOCK_TIMEOUT_MS = 20_000
|
||||||
|
|
||||||
export async function coordinateCrossTabRefresh<T>(options: CrossTabRefreshOptions<T>): Promise<T> {
|
export async function coordinateCrossTabRefresh<T>(options: CrossTabRefreshOptions<T>): Promise<T> {
|
||||||
const run = async () => {
|
const run = async () => {
|
||||||
const currentRefreshToken = options.currentRefreshToken()
|
const currentRefreshToken = options.currentRefreshToken()
|
||||||
@@ -33,5 +43,14 @@ export async function coordinateCrossTabRefresh<T>(options: CrossTabRefreshOptio
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return navigator.locks.request(options.lockName, run)
|
const controller = new AbortController()
|
||||||
|
const timeout = setTimeout(() => controller.abort(), options.lockTimeoutMs ?? DEFAULT_LOCK_TIMEOUT_MS)
|
||||||
|
try {
|
||||||
|
return await navigator.locks.request(options.lockName, { signal: controller.signal }, run)
|
||||||
|
} catch (error) {
|
||||||
|
if (controller.signal.aborted) throw new CrossTabRefreshTimeoutError()
|
||||||
|
throw error
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+139
-16
@@ -1,9 +1,9 @@
|
|||||||
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||||
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
import { accessTokenIdentity, clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||||
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
||||||
import { ApiError, isApiEnvelope, type ApiEnvelope } from '@/api/types'
|
import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
|
||||||
import { coordinateCrossTabRefresh } from '@/api/crossTabRefresh'
|
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
|
||||||
|
|
||||||
const transport = axios.create({
|
const transport = axios.create({
|
||||||
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
|
||||||
@@ -13,12 +13,21 @@ const transport = axios.create({
|
|||||||
|
|
||||||
interface RetryableRequest extends InternalAxiosRequestConfig {
|
interface RetryableRequest extends InternalAxiosRequestConfig {
|
||||||
_retriedAfterRefresh?: boolean
|
_retriedAfterRefresh?: boolean
|
||||||
|
_sessionIdentity?: string | null
|
||||||
|
_logoutGeneration?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
||||||
|
if (!isApiEnvelope(envelope)) {
|
||||||
|
const invalid: unknown = envelope
|
||||||
|
if (isApiFailure(invalid)) {
|
||||||
|
throw new ApiError(invalid.message, invalid.code, undefined, undefined, invalid.traceId, invalid.requestId)
|
||||||
|
}
|
||||||
|
throw new ApiError('接口响应格式错误', 'INVALID_RESPONSE')
|
||||||
|
}
|
||||||
if (envelope.code !== '200') {
|
if (envelope.code !== '200') {
|
||||||
const fieldErrors = asFieldErrors(envelope.data)
|
const fieldErrors = asFieldErrors(envelope.data)
|
||||||
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId)
|
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId, envelope.requestId)
|
||||||
}
|
}
|
||||||
return envelope.data
|
return envelope.data
|
||||||
}
|
}
|
||||||
@@ -28,14 +37,15 @@ function mapError(error: unknown) {
|
|||||||
if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败')
|
if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败')
|
||||||
|
|
||||||
const body = error.response?.data
|
const body = error.response?.data
|
||||||
if (isApiEnvelope(body)) {
|
if (isApiEnvelope(body) || isApiFailure(body)) {
|
||||||
const fieldErrors = asFieldErrors(body.data)
|
const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
|
||||||
return new ApiError(
|
return new ApiError(
|
||||||
apiErrorMessage(body.message, fieldErrors),
|
apiErrorMessage(body.message, fieldErrors),
|
||||||
body.code,
|
body.code,
|
||||||
error.response?.status,
|
error.response?.status,
|
||||||
fieldErrors,
|
fieldErrors,
|
||||||
typeof body.traceId === 'string' ? body.traceId : null,
|
typeof body.traceId === 'string' ? body.traceId : null,
|
||||||
|
typeof body.requestId === 'string' ? body.requestId : null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (error.code === AxiosError.ERR_NETWORK) return new ApiError('无法连接服务器,请确认后端服务已启动', 'NETWORK_ERROR')
|
if (error.code === AxiosError.ERR_NETWORK) return new ApiError('无法连接服务器,请确认后端服务已启动', 'NETWORK_ERROR')
|
||||||
@@ -43,8 +53,16 @@ function mapError(error: unknown) {
|
|||||||
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let refreshExchange: { identity: string; refreshToken: string; promise: Promise<TokenPair> } | null = null
|
||||||
|
let logoutGeneration = 0
|
||||||
let refreshPromise: Promise<string> | null = null
|
let refreshPromise: Promise<string> | null = null
|
||||||
|
let refreshIdentity: string | null = null
|
||||||
let redirectingToLogin = false
|
let redirectingToLogin = false
|
||||||
|
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout', '/auth/impersonations/exchange']
|
||||||
|
|
||||||
|
function isPublicAuthRequest(url?: string) {
|
||||||
|
return publicAuthPaths.some((path) => url?.endsWith(path))
|
||||||
|
}
|
||||||
|
|
||||||
function redirectToLoginAfterSessionExpiry() {
|
function redirectToLoginAfterSessionExpiry() {
|
||||||
if (redirectingToLogin || typeof window === 'undefined') return
|
if (redirectingToLogin || typeof window === 'undefined') return
|
||||||
@@ -57,58 +75,110 @@ function redirectToLoginAfterSessionExpiry() {
|
|||||||
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function refreshSession() {
|
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()
|
const observedRefreshToken = getRefreshToken()
|
||||||
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||||
if (!refreshPromise) {
|
if (!refreshPromise) {
|
||||||
|
refreshIdentity = observedIdentity
|
||||||
refreshPromise = coordinateCrossTabRefresh({
|
refreshPromise = coordinateCrossTabRefresh({
|
||||||
lockName: 'cc-client-auth-refresh',
|
lockName: 'cc-client-auth-refresh',
|
||||||
observedRefreshToken,
|
observedRefreshToken,
|
||||||
currentRefreshToken: getRefreshToken,
|
currentRefreshToken: getRefreshToken,
|
||||||
reuseCurrentSession: async () => {
|
reuseCurrentSession: async () => {
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
const currentAccessToken = getAccessToken()
|
const currentAccessToken = getAccessToken()
|
||||||
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||||
return currentAccessToken
|
return currentAccessToken
|
||||||
},
|
},
|
||||||
refresh: async (currentRefreshToken) => {
|
refresh: async (currentRefreshToken) => {
|
||||||
const response = await transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken })
|
requireCurrentIdentity(observedIdentity)
|
||||||
const tokens = unwrap(response.data)
|
const exchange = { identity: observedIdentity!, refreshToken: currentRefreshToken, promise: transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }).then(response => unwrap(response.data)) }
|
||||||
|
refreshExchange = exchange
|
||||||
|
let tokens: TokenPair
|
||||||
|
try { tokens = await exchange.promise } finally { if (refreshExchange === exchange) refreshExchange = null }
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
|
requireCurrentIdentity(observedIdentity, tokens.accessToken)
|
||||||
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
||||||
|
if (getRefreshToken() !== currentRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
persistTokenPair(tokens)
|
persistTokenPair(tokens)
|
||||||
|
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('cc-client-session-updated'))
|
||||||
return tokens.accessToken
|
return tokens.accessToken
|
||||||
},
|
},
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
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'))
|
||||||
|
redirectToLoginAfterSessionExpiry()
|
||||||
|
throw expiredError
|
||||||
|
}
|
||||||
|
throw error
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
refreshPromise = null
|
refreshPromise = null
|
||||||
|
refreshIdentity = null
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return refreshPromise
|
if (refreshIdentity !== observedIdentity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
const refreshed = await refreshPromise
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
|
return refreshed
|
||||||
}
|
}
|
||||||
|
|
||||||
transport.interceptors.request.use((config) => {
|
transport.interceptors.request.use((config) => {
|
||||||
const token = getAccessToken()
|
const token = getAccessToken()
|
||||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
const request = config as RetryableRequest
|
||||||
|
if (request._retriedAfterRefresh && !isPublicAuthRequest(config.url)) requireCurrentIdentity(request._sessionIdentity, token)
|
||||||
|
if (token && !isPublicAuthRequest(config.url)) {
|
||||||
|
if (!request._retriedAfterRefresh) {
|
||||||
|
request._sessionIdentity = accessTokenIdentity(token)
|
||||||
|
request._logoutGeneration = logoutGeneration
|
||||||
|
}
|
||||||
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
|
}
|
||||||
return config
|
return config
|
||||||
})
|
})
|
||||||
|
|
||||||
transport.interceptors.response.use(
|
transport.interceptors.response.use(
|
||||||
(response) => response,
|
(response) => {
|
||||||
|
const request = response.config as RetryableRequest
|
||||||
|
if (request._sessionIdentity) {
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
},
|
||||||
async (error: AxiosError) => {
|
async (error: AxiosError) => {
|
||||||
const request = error.config as RetryableRequest | undefined
|
const request = error.config as RetryableRequest | undefined
|
||||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/impersonations/exchange']
|
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
|
||||||
const isPublicAuthRequest = publicAuthPaths.some((path) => request?.url?.endsWith(path))
|
|
||||||
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest) {
|
|
||||||
throw mapError(error)
|
throw mapError(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
request._retriedAfterRefresh = true
|
request._retriedAfterRefresh = true
|
||||||
|
const refreshTokenBeforeRetry = getRefreshToken()
|
||||||
try {
|
try {
|
||||||
const accessToken = await refreshSession()
|
const accessToken = await refreshAuthenticatedSession()
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
request.headers.Authorization = `Bearer ${accessToken}`
|
request.headers.Authorization = `Bearer ${accessToken}`
|
||||||
return await transport.request(request)
|
return await transport.request(request)
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
const mappedError = mapError(refreshError)
|
const mappedError = mapError(refreshError)
|
||||||
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
||||||
|
if (getRefreshToken() && getRefreshToken() !== refreshTokenBeforeRetry) throw mappedError
|
||||||
clearSessionTokens()
|
clearSessionTokens()
|
||||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||||
redirectToLoginAfterSessionExpiry()
|
redirectToLoginAfterSessionExpiry()
|
||||||
@@ -118,6 +188,33 @@ transport.interceptors.response.use(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Captured revocation never persists credentials or restores local login state.
|
||||||
|
export async function revokeCapturedSession(accessToken: string, refreshToken: string) {
|
||||||
|
logoutGeneration++
|
||||||
|
const identity = accessTokenIdentity(accessToken)
|
||||||
|
if (!identity || !refreshToken) throw new ApiError('服务器会话注销未确认', 'SESSION_CHANGED')
|
||||||
|
const pending = refreshExchange?.identity === identity && refreshExchange.refreshToken === refreshToken ? refreshExchange.promise : null
|
||||||
|
const revoke = (pair: Pick<TokenPair, 'accessToken' | 'refreshToken'>) => apiRequest<void>({
|
||||||
|
method: 'POST', url: '/auth/logout', data: { refreshToken: pair.refreshToken },
|
||||||
|
headers: { Authorization: `Bearer ${pair.accessToken}` },
|
||||||
|
})
|
||||||
|
const validate = (pair: TokenPair) => {
|
||||||
|
if (accessTokenIdentity(pair.accessToken) !== identity || !pair.refreshToken) throw new ApiError('刷新身份不一致,服务器会话注销未确认', 'SESSION_CHANGED')
|
||||||
|
return pair
|
||||||
|
}
|
||||||
|
// An already sent refresh can rotate the pair. Consume its actual result
|
||||||
|
// without issuing a competing refresh or restoring it to local storage.
|
||||||
|
if (pending) {
|
||||||
|
await revoke(validate(await pending))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try { await revoke({ accessToken, refreshToken }) } catch (error) {
|
||||||
|
if (!(error instanceof ApiError) || error.status !== 401) throw error
|
||||||
|
const pair = await apiRequest<TokenPair>({ method: 'POST', url: '/auth/refresh', data: { refreshToken } })
|
||||||
|
await revoke(validate(pair))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
||||||
try {
|
try {
|
||||||
const response = await transport.request<ApiEnvelope<T>>(config)
|
const response = await transport.request<ApiEnvelope<T>>(config)
|
||||||
@@ -130,8 +227,10 @@ export async function apiRequest<T>(config: AxiosRequestConfig) {
|
|||||||
export async function apiBlobRequest(config: AxiosRequestConfig) {
|
export async function apiBlobRequest(config: AxiosRequestConfig) {
|
||||||
try {
|
try {
|
||||||
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
||||||
|
await throwBlobApiError(response.data, response.status)
|
||||||
return response.data
|
return response.data
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
await throwBlobApiError(error)
|
||||||
throw mapError(error)
|
throw mapError(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,10 +238,34 @@ export async function apiBlobRequest(config: AxiosRequestConfig) {
|
|||||||
export async function apiBlobResponseRequest(config: AxiosRequestConfig) {
|
export async function apiBlobResponseRequest(config: AxiosRequestConfig) {
|
||||||
try {
|
try {
|
||||||
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
||||||
|
await throwBlobApiError(response.data, response.status)
|
||||||
return { blob: response.data, headers: response.headers }
|
return { blob: response.data, headers: response.headers }
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
await throwBlobApiError(error)
|
||||||
throw mapError(error)
|
throw mapError(error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function throwBlobApiError(error: unknown, responseStatus?: number) {
|
||||||
|
const blob = error instanceof Blob
|
||||||
|
? error
|
||||||
|
: axios.isAxiosError(error) && error.response?.data instanceof Blob ? error.response.data : null
|
||||||
|
if (!blob || !blob.type.toLowerCase().includes('json')) return
|
||||||
|
try {
|
||||||
|
const body = JSON.parse(await blob.text()) as unknown
|
||||||
|
if (!isApiEnvelope(body) && !isApiFailure(body)) return
|
||||||
|
const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
|
||||||
|
throw new ApiError(
|
||||||
|
apiErrorMessage(body.message, fieldErrors),
|
||||||
|
body.code,
|
||||||
|
responseStatus ?? (axios.isAxiosError(error) ? error.response?.status : undefined),
|
||||||
|
fieldErrors,
|
||||||
|
typeof body.traceId === 'string' ? body.traceId : null,
|
||||||
|
typeof body.requestId === 'string' ? body.requestId : null,
|
||||||
|
)
|
||||||
|
} catch (parsedError) {
|
||||||
|
if (parsedError instanceof ApiError) throw parsedError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export { ApiError }
|
export { ApiError }
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFile } from 'node:fs/promises'
|
||||||
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
|
const source = await readFile(new URL('./types.ts', import.meta.url), 'utf8')
|
||||||
|
const compiled = ts.transpileModule(source, {
|
||||||
|
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 },
|
||||||
|
}).outputText
|
||||||
|
const { isApiFailure, isApiEnvelope } = await import(`data:text/javascript;base64,${Buffer.from(compiled).toString('base64')}`)
|
||||||
|
|
||||||
|
test('recognizes a security failure without data and preserves diagnostics', () => {
|
||||||
|
const failure = { code: 'A0403', message: 'Access denied', requestId: 'request-1', traceId: 'trace-1' }
|
||||||
|
assert.equal(isApiFailure(failure), true)
|
||||||
|
assert.equal(isApiEnvelope(failure), false)
|
||||||
|
assert.equal(failure.requestId, 'request-1')
|
||||||
|
assert.equal(failure.traceId, 'trace-1')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('does not accept malformed or data-less successful responses', () => {
|
||||||
|
for (const value of [null, {}, { code: 403, message: 'Denied' }, { code: 'A0403' },
|
||||||
|
{ code: 'A0403', message: 'Denied', traceId: {} }, { code: '200', message: 'OK' }]) {
|
||||||
|
assert.equal(isApiFailure(value), false)
|
||||||
|
}
|
||||||
|
assert.equal(isApiEnvelope({ code: '200', message: 'OK' }), false)
|
||||||
|
assert.equal(isApiEnvelope({ code: '200', message: 'OK', data: [] }), true)
|
||||||
|
})
|
||||||
|
|
||||||
|
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\)/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import {
|
||||||
|
accessTokenIdentity,
|
||||||
|
ACCESS_TOKEN_KEY,
|
||||||
|
REFRESH_TOKEN_KEY,
|
||||||
|
REMEMBERED_LOGIN_ID_KEY,
|
||||||
|
clearSessionTokens,
|
||||||
|
getRememberedLoginId,
|
||||||
|
persistRememberedLoginId,
|
||||||
|
persistTokenPair,
|
||||||
|
} from './session.ts'
|
||||||
|
|
||||||
|
function storage() {
|
||||||
|
const values = new Map()
|
||||||
|
return {
|
||||||
|
getItem: (key) => values.get(key) ?? null,
|
||||||
|
setItem: (key, value) => values.set(key, String(value)),
|
||||||
|
removeItem: (key) => values.delete(key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function installStorage() {
|
||||||
|
globalThis.localStorage = storage()
|
||||||
|
globalThis.sessionStorage = storage()
|
||||||
|
}
|
||||||
|
|
||||||
|
test('persists the normal rotating session independently of remembered account preference', () => {
|
||||||
|
installStorage()
|
||||||
|
persistTokenPair({
|
||||||
|
tokenType: 'Bearer',
|
||||||
|
accessToken: 'access-token',
|
||||||
|
expiresIn: 1440,
|
||||||
|
refreshToken: 'refresh-token',
|
||||||
|
refreshExpiresIn: 604800,
|
||||||
|
})
|
||||||
|
|
||||||
|
assert.equal(localStorage.getItem(ACCESS_TOKEN_KEY), 'access-token')
|
||||||
|
assert.equal(localStorage.getItem(REFRESH_TOKEN_KEY), 'refresh-token')
|
||||||
|
assert.equal(sessionStorage.getItem(ACCESS_TOKEN_KEY), null)
|
||||||
|
assert.equal(sessionStorage.getItem(REFRESH_TOKEN_KEY), null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('remembers only the login id and keeps it when session tokens are cleared', () => {
|
||||||
|
installStorage()
|
||||||
|
persistRememberedLoginId('merchant-user', true)
|
||||||
|
localStorage.setItem(ACCESS_TOKEN_KEY, 'access-token')
|
||||||
|
localStorage.setItem(REFRESH_TOKEN_KEY, 'refresh-token')
|
||||||
|
|
||||||
|
clearSessionTokens()
|
||||||
|
|
||||||
|
assert.equal(getRememberedLoginId(), 'merchant-user')
|
||||||
|
assert.equal(localStorage.getItem(REMEMBERED_LOGIN_ID_KEY), 'merchant-user')
|
||||||
|
assert.equal(localStorage.getItem(ACCESS_TOKEN_KEY), null)
|
||||||
|
assert.equal(localStorage.getItem(REFRESH_TOKEN_KEY), null)
|
||||||
|
|
||||||
|
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'))
|
||||||
|
})
|
||||||
+44
-9
@@ -1,5 +1,6 @@
|
|||||||
export const ACCESS_TOKEN_KEY = 'cc-client-access-token'
|
export const ACCESS_TOKEN_KEY = 'cc-client-access-token'
|
||||||
export const REFRESH_TOKEN_KEY = 'cc-client-refresh-token'
|
export const REFRESH_TOKEN_KEY = 'cc-client-refresh-token'
|
||||||
|
export const REMEMBERED_LOGIN_ID_KEY = 'cc-client-remembered-login-id'
|
||||||
|
|
||||||
export interface TokenPair {
|
export interface TokenPair {
|
||||||
tokenType: string
|
tokenType: string
|
||||||
@@ -9,10 +10,6 @@ export interface TokenPair {
|
|||||||
refreshExpiresIn: number
|
refreshExpiresIn: number
|
||||||
}
|
}
|
||||||
|
|
||||||
function activeStorage() {
|
|
||||||
if (localStorage.getItem(ACCESS_TOKEN_KEY)) return localStorage
|
|
||||||
return sessionStorage
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getAccessToken() {
|
export function getAccessToken() {
|
||||||
return localStorage.getItem(ACCESS_TOKEN_KEY) || sessionStorage.getItem(ACCESS_TOKEN_KEY) || ''
|
return localStorage.getItem(ACCESS_TOKEN_KEY) || sessionStorage.getItem(ACCESS_TOKEN_KEY) || ''
|
||||||
@@ -22,11 +19,49 @@ export function getRefreshToken() {
|
|||||||
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
||||||
}
|
}
|
||||||
|
|
||||||
export function persistTokenPair(tokens: TokenPair, remember?: boolean) {
|
// Only binds a retry to its original identity; never grants permissions. Expired
|
||||||
const storage = remember === undefined ? activeStorage() : remember ? localStorage : sessionStorage
|
// access tokens remain readable here because they are the normal refresh trigger.
|
||||||
clearSessionTokens()
|
export function accessTokenIdentity(token: string): string | null {
|
||||||
storage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
|
try {
|
||||||
storage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
|
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) {
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRememberedLoginId() {
|
||||||
|
return localStorage.getItem(REMEMBERED_LOGIN_ID_KEY) || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function persistRememberedLoginId(loginId: string, remember: boolean) {
|
||||||
|
if (remember) localStorage.setItem(REMEMBERED_LOGIN_ID_KEY, loginId)
|
||||||
|
else localStorage.removeItem(REMEMBERED_LOGIN_ID_KEY)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function persistTemporaryAccessToken(accessToken: string) {
|
export function persistTemporaryAccessToken(accessToken: string) {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export class ApiError extends Error {
|
|||||||
readonly status?: number,
|
readonly status?: number,
|
||||||
readonly fieldErrors?: ApiFieldErrors,
|
readonly fieldErrors?: ApiFieldErrors,
|
||||||
readonly traceId?: string | null,
|
readonly traceId?: string | null,
|
||||||
|
readonly requestId?: string | null,
|
||||||
) {
|
) {
|
||||||
super(message)
|
super(message)
|
||||||
this.name = 'ApiError'
|
this.name = 'ApiError'
|
||||||
@@ -29,3 +30,13 @@ export function isApiEnvelope(value: unknown): value is ApiEnvelope<unknown> {
|
|||||||
const record = value as Record<string, unknown>
|
const record = value as Record<string, unknown>
|
||||||
return typeof record.code === 'string' && typeof record.message === 'string' && 'data' in record
|
return typeof record.code === 'string' && typeof record.message === 'string' && 'data' in record
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Security failures have no business data, unlike successful API responses.
|
||||||
|
export function isApiFailure(value: unknown): value is Omit<ApiEnvelope<never>, 'data'> {
|
||||||
|
if (!value || typeof value !== 'object') return false
|
||||||
|
const record = value as Record<string, unknown>
|
||||||
|
return typeof record.code === 'string' && record.code !== '200'
|
||||||
|
&& typeof record.message === 'string'
|
||||||
|
&& (record.requestId == null || typeof record.requestId === 'string')
|
||||||
|
&& (record.traceId == null || typeof record.traceId === 'string')
|
||||||
|
}
|
||||||
|
|||||||
@@ -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
+6
@@ -19,8 +19,11 @@ declare module 'vue' {
|
|||||||
DataTable: typeof import('./components/common/DataTable.vue')['default']
|
DataTable: typeof import('./components/common/DataTable.vue')['default']
|
||||||
ElAlert: typeof import('element-plus/es')['ElAlert']
|
ElAlert: typeof import('element-plus/es')['ElAlert']
|
||||||
ElButton: typeof import('element-plus/es')['ElButton']
|
ElButton: typeof import('element-plus/es')['ElButton']
|
||||||
|
ElCard: typeof import('element-plus/es')['ElCard']
|
||||||
ElCheckbox: typeof import('element-plus/es')['ElCheckbox']
|
ElCheckbox: typeof import('element-plus/es')['ElCheckbox']
|
||||||
ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup']
|
ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup']
|
||||||
|
ElCollapse: typeof import('element-plus/es')['ElCollapse']
|
||||||
|
ElCollapseItem: typeof import('element-plus/es')['ElCollapseItem']
|
||||||
ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
|
ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
|
||||||
ElDialog: typeof import('element-plus/es')['ElDialog']
|
ElDialog: typeof import('element-plus/es')['ElDialog']
|
||||||
ElDrawer: typeof import('element-plus/es')['ElDrawer']
|
ElDrawer: typeof import('element-plus/es')['ElDrawer']
|
||||||
@@ -30,6 +33,7 @@ declare module 'vue' {
|
|||||||
ElEmpty: typeof import('element-plus/es')['ElEmpty']
|
ElEmpty: typeof import('element-plus/es')['ElEmpty']
|
||||||
ElForm: typeof import('element-plus/es')['ElForm']
|
ElForm: typeof import('element-plus/es')['ElForm']
|
||||||
ElFormItem: typeof import('element-plus/es')['ElFormItem']
|
ElFormItem: typeof import('element-plus/es')['ElFormItem']
|
||||||
|
ElImage: typeof import('element-plus/es')['ElImage']
|
||||||
ElInput: typeof import('element-plus/es')['ElInput']
|
ElInput: typeof import('element-plus/es')['ElInput']
|
||||||
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
|
ElInputNumber: typeof import('element-plus/es')['ElInputNumber']
|
||||||
ElOption: typeof import('element-plus/es')['ElOption']
|
ElOption: typeof import('element-plus/es')['ElOption']
|
||||||
@@ -38,6 +42,7 @@ declare module 'vue' {
|
|||||||
ElRadio: typeof import('element-plus/es')['ElRadio']
|
ElRadio: typeof import('element-plus/es')['ElRadio']
|
||||||
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
||||||
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
||||||
|
ElResult: typeof import('element-plus/es')['ElResult']
|
||||||
ElSelect: typeof import('element-plus/es')['ElSelect']
|
ElSelect: typeof import('element-plus/es')['ElSelect']
|
||||||
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
|
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
|
||||||
ElSwitch: typeof import('element-plus/es')['ElSwitch']
|
ElSwitch: typeof import('element-plus/es')['ElSwitch']
|
||||||
@@ -53,6 +58,7 @@ declare module 'vue' {
|
|||||||
QueryToolbar: typeof import('./components/common/QueryToolbar.vue')['default']
|
QueryToolbar: typeof import('./components/common/QueryToolbar.vue')['default']
|
||||||
RouterLink: typeof import('vue-router')['RouterLink']
|
RouterLink: typeof import('vue-router')['RouterLink']
|
||||||
RouterView: typeof import('vue-router')['RouterView']
|
RouterView: typeof import('vue-router')['RouterView']
|
||||||
|
SingleLineText: typeof import('./components/common/SingleLineText.vue')['default']
|
||||||
WorkspaceTabs: typeof import('./components/WorkspaceTabs.vue')['default']
|
WorkspaceTabs: typeof import('./components/WorkspaceTabs.vue')['default']
|
||||||
}
|
}
|
||||||
export interface GlobalDirectives {
|
export interface GlobalDirectives {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref, watch } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue'
|
import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue'
|
||||||
import {
|
import {
|
||||||
clientNavigation,
|
clientNavigation,
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
getNavigationParentKeys,
|
getNavigationParentKeys,
|
||||||
} from '@/navigation/clientNavigation'
|
} from '@/navigation/clientNavigation'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import { useCustomsPendingStore } from '@/modules/first-leg/public'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
activePath: string
|
activePath: string
|
||||||
@@ -16,14 +17,34 @@ const emit = defineEmits<{
|
|||||||
navigate: [path: string]
|
navigate: [path: string]
|
||||||
}>()
|
}>()
|
||||||
const auth = useAuthStore()
|
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 visibleNavigation = computed(() => filterNavigationByPermissions(clientNavigation, auth.permissionCodes))
|
||||||
|
|
||||||
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath)))
|
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath)))
|
||||||
const openedKeys = ref<ReadonlySet<string>>(new Set(activeParentKeys.value))
|
const openedKeys = ref<ReadonlySet<string>>(new Set(activeParentKeys.value))
|
||||||
|
|
||||||
function handleToggle(key: string) {
|
function handleToggle(key: string) {
|
||||||
if (activeParentKeys.value.has(key)) return
|
|
||||||
|
|
||||||
const next = new Set(openedKeys.value)
|
const next = new Set(openedKeys.value)
|
||||||
if (next.has(key)) next.delete(key)
|
if (next.has(key)) next.delete(key)
|
||||||
else next.add(key)
|
else next.add(key)
|
||||||
@@ -49,6 +70,7 @@ function handleSelect(path: string) {
|
|||||||
v-for="node in visibleNavigation"
|
v-for="node in visibleNavigation"
|
||||||
:key="node.key"
|
:key="node.key"
|
||||||
:node="node"
|
:node="node"
|
||||||
|
:badges="badges"
|
||||||
:active-path="activePath"
|
:active-path="activePath"
|
||||||
:opened-keys="openedKeys"
|
:opened-keys="openedKeys"
|
||||||
:active-parent-keys="activeParentKeys"
|
:active-parent-keys="activeParentKeys"
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const props = defineProps<{
|
|||||||
activePath: string
|
activePath: string
|
||||||
openedKeys: ReadonlySet<string>
|
openedKeys: ReadonlySet<string>
|
||||||
activeParentKeys: ReadonlySet<string>
|
activeParentKeys: ReadonlySet<string>
|
||||||
|
badges?: Readonly<Record<string, { count: number | null; error: string }>>
|
||||||
level?: number
|
level?: number
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
@@ -16,6 +17,9 @@ const emit = defineEmits<{
|
|||||||
toggle: [key: string]
|
toggle: [key: string]
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
|
const badge = computed(() => props.badges?.[props.node.key])
|
||||||
|
const badgeTitle = computed(() => badge.value?.error || `${badge.value?.count ?? 0} 个柜次待上传资料或确认回执`)
|
||||||
|
|
||||||
const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -54,6 +58,7 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
|||||||
v-for="child in node.children"
|
v-for="child in node.children"
|
||||||
:key="child.key"
|
:key="child.key"
|
||||||
:node="child"
|
:node="child"
|
||||||
|
:badges="badges"
|
||||||
:active-path="activePath"
|
:active-path="activePath"
|
||||||
:opened-keys="openedKeys"
|
:opened-keys="openedKeys"
|
||||||
:active-parent-keys="activeParentKeys"
|
:active-parent-keys="activeParentKeys"
|
||||||
@@ -78,6 +83,14 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
|||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
<span>{{ node.title }}</span>
|
<span>{{ node.title }}</span>
|
||||||
|
<span v-if="badge?.error || (badge?.count != null && badge.count > 0)" class="client-nav-badge"
|
||||||
|
:title="badgeTitle" :aria-label="badgeTitle" role="status">
|
||||||
|
{{ badge?.error ? '!' : badge!.count! > 99 ? '99+' : badge?.count }}
|
||||||
|
</span>
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</li>
|
</li>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.client-sidebar-link .client-nav-badge { display: inline-flex; flex: 0 0 auto; min-width: 23px; height: 23px; align-items: center; justify-content: center; margin-left: auto; padding: 0 5px; border: 2px solid #fff; border-radius: 999px; background: #ef4444; color: #fff; box-shadow: 0 3px 9px rgb(239 68 68 / 24%); font-size: 12px; font-weight: 700; line-height: 1; }
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { parse, compileScript } from 'vue/compiler-sfc'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
|
||||||
|
const source = readFileSync(new URL('./DataTable.vue', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
function paginationHarness(t) {
|
||||||
|
const descriptor = parse(source).descriptor
|
||||||
|
const compiled = compileScript(descriptor, { id: 'data-table-pagination-test' })
|
||||||
|
const code = ts.transpileModule(compiled.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const exports = {}
|
||||||
|
const deps = { vue, '@lucide/vue': { ChevronLeft: {}, ChevronRight: {} }, './tableActions': {} }
|
||||||
|
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||||
|
const component = exports.default
|
||||||
|
component.render = () => null
|
||||||
|
const state = vue.reactive({ page: 5, total: 5542, loading: false, error: false })
|
||||||
|
const emitted = []
|
||||||
|
const renderer = vue.createRenderer({
|
||||||
|
createElement: tag => ({ tag }), createText: text => ({ text }), createComment: text => ({ text }),
|
||||||
|
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||||
|
parentNode: () => null, nextSibling: () => null,
|
||||||
|
})
|
||||||
|
const app = renderer.createApp({ render: () => vue.h(component, {
|
||||||
|
data: [], columns: [], page: state.page, pageSize: 50, total: state.total, loading: state.loading,
|
||||||
|
'onUpdate:page': value => { emitted.push(value); state.page = value },
|
||||||
|
}, state.error ? { error: () => vue.h('div', 'Request failed') } : {}) })
|
||||||
|
app.mount({})
|
||||||
|
t.after(() => app.unmount())
|
||||||
|
return { state, emitted }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('server-page loading must not reset the requested page when total temporarily clears', async t => {
|
||||||
|
const { state, emitted } = paginationHarness(t)
|
||||||
|
state.loading = true; state.total = 0
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(state.page, 5)
|
||||||
|
assert.deepEqual(emitted, [])
|
||||||
|
state.total = 5542; state.loading = false
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(state.page, 5)
|
||||||
|
assert.deepEqual(emitted, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('failed server page retains its page for explicit retry and emits no automatic fallback request', async t => {
|
||||||
|
const { state, emitted } = paginationHarness(t)
|
||||||
|
state.loading = true; state.total = 0
|
||||||
|
await vue.nextTick()
|
||||||
|
state.error = true; state.loading = false
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(state.page, 5)
|
||||||
|
assert.deepEqual(emitted, [])
|
||||||
|
state.error = false; state.loading = true
|
||||||
|
await vue.nextTick()
|
||||||
|
state.total = 5542; state.loading = false
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(state.page, 5)
|
||||||
|
assert.deepEqual(emitted, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('settled successful totals still clamp out-of-range and empty pages', async t => {
|
||||||
|
const { state, emitted } = paginationHarness(t)
|
||||||
|
state.total = 120
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(state.page, 3)
|
||||||
|
state.total = 0
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(state.page, 1)
|
||||||
|
assert.deepEqual(emitted, [3, 1])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('keeps action-only table toolbars on the left', () => {
|
||||||
|
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
|
||||||
|
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
|
||||||
|
assert.match(source, /\.data-table__toolbar--actions-only \{ justify-content: flex-start; \}/)
|
||||||
|
})
|
||||||
@@ -7,6 +7,9 @@ export interface DataTableColumn {
|
|||||||
columnKey?: string
|
columnKey?: string
|
||||||
slotName?: string
|
slotName?: string
|
||||||
headerSlotName?: string
|
headerSlotName?: string
|
||||||
|
singleLine?: boolean
|
||||||
|
showOverflowTooltip?: boolean
|
||||||
|
className?: string
|
||||||
[attribute: string]: unknown
|
[attribute: string]: unknown
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,6 +44,7 @@ export function createPaginationItems(page: number, pageCount: number): Paginati
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, useSlots, watch } from 'vue'
|
import { computed, useSlots, watch } from 'vue'
|
||||||
import { ChevronLeft, ChevronRight } from '@lucide/vue'
|
import { ChevronLeft, ChevronRight } from '@lucide/vue'
|
||||||
|
import { splitTableActions, runTableAction, type TableAction } from './tableActions'
|
||||||
|
|
||||||
defineOptions({ inheritAttrs: false })
|
defineOptions({ inheritAttrs: false })
|
||||||
|
|
||||||
@@ -51,6 +55,7 @@ const props = withDefaults(defineProps<{
|
|||||||
emptyText?: string
|
emptyText?: string
|
||||||
total?: number
|
total?: number
|
||||||
pageSizes?: number[]
|
pageSizes?: number[]
|
||||||
|
rowActions?: (row: object) => TableAction[]
|
||||||
}>(), {
|
}>(), {
|
||||||
loading: false,
|
loading: false,
|
||||||
emptyText: '暂无数据',
|
emptyText: '暂无数据',
|
||||||
@@ -83,15 +88,41 @@ watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
|
|||||||
page.value = 1
|
page.value = 1
|
||||||
}, { immediate: true })
|
}, { immediate: true })
|
||||||
|
|
||||||
watch([page, pageCount], ([value, count]) => {
|
watch([page, pageCount, () => props.loading, () => Boolean(slots.error)], ([value, count, loading, hasError]) => {
|
||||||
|
// A cleared total is not an authoritative page count while loading or showing a request error.
|
||||||
|
if (loading || hasError) return
|
||||||
const nextValue = normalizePage(value, count)
|
const nextValue = normalizePage(value, count)
|
||||||
if (value !== nextValue) page.value = nextValue
|
if (value !== nextValue) page.value = nextValue
|
||||||
}, { immediate: true })
|
}, { immediate: true })
|
||||||
|
|
||||||
function columnAttrs({ key, slotName, headerSlotName, ...attrs }: DataTableColumn) {
|
function columnAttrs({ key, slotName, headerSlotName, singleLine, ...attrs }: DataTableColumn) {
|
||||||
return attrs
|
return attrs
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function systemColumn(column: DataTableColumn) {
|
||||||
|
return column.type === 'selection'
|
||||||
|
|| column.type === 'index'
|
||||||
|
|| column.type === 'expand'
|
||||||
|
|| column.slotName === 'actions'
|
||||||
|
|| column.label === '操作'
|
||||||
|
}
|
||||||
|
|
||||||
|
function singleLineColumn(column: DataTableColumn) {
|
||||||
|
return column.singleLine !== false && !systemColumn(column)
|
||||||
|
}
|
||||||
|
|
||||||
|
function columnOverflowTooltip(column: DataTableColumn) {
|
||||||
|
return singleLineColumn(column) ? column.showOverflowTooltip ?? true : column.showOverflowTooltip
|
||||||
|
}
|
||||||
|
|
||||||
|
function columnClassName(column: DataTableColumn) {
|
||||||
|
return [
|
||||||
|
column.className,
|
||||||
|
systemColumn(column) ? 'data-table__system-cell' : '',
|
||||||
|
singleLineColumn(column) ? 'data-table__single-line-cell' : '',
|
||||||
|
].filter(Boolean).join(' ')
|
||||||
|
}
|
||||||
|
|
||||||
function columnRenderKey(column: DataTableColumn, index: number) {
|
function columnRenderKey(column: DataTableColumn, index: number) {
|
||||||
return String(column.key ?? column.columnKey ?? column.prop ?? column.property ?? index)
|
return String(column.key ?? column.columnKey ?? column.prop ?? column.property ?? index)
|
||||||
}
|
}
|
||||||
@@ -113,17 +144,45 @@ function setPage(value: number) {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="data-table">
|
<div class="data-table" :class="$attrs.class">
|
||||||
<el-table v-bind="$attrs" v-loading="loading" :data="data" :empty-text="emptyText" :aria-busy="loading">
|
<header v-if="$slots.toolbar || $slots['toolbar-actions']" class="data-table__toolbar" :class="{ 'data-table__toolbar--actions-only': !$slots.toolbar }">
|
||||||
|
<div v-if="$slots.toolbar" class="data-table__toolbar-heading"><slot name="toolbar" /></div>
|
||||||
|
<div class="data-table__toolbar-actions"><slot name="toolbar-actions" /></div>
|
||||||
|
</header>
|
||||||
|
<slot name="before-table" />
|
||||||
|
<slot v-if="$slots.error" name="error" />
|
||||||
|
<template v-else>
|
||||||
|
<el-table v-bind="{ ...$attrs, class: undefined }" v-loading="loading" :data="data" :empty-text="emptyText" :aria-busy="loading">
|
||||||
<el-table-column
|
<el-table-column
|
||||||
v-for="(column, index) in columns"
|
v-for="(column, index) in columns"
|
||||||
:key="columnRenderKey(column, index)"
|
:key="columnRenderKey(column, index)"
|
||||||
v-bind="columnAttrs(column)"
|
v-bind="columnAttrs(column)"
|
||||||
|
:class-name="columnClassName(column)"
|
||||||
|
:show-overflow-tooltip="columnOverflowTooltip(column)"
|
||||||
>
|
>
|
||||||
<template v-if="hasSlot(column.headerSlotName)" #header="scope">
|
<template v-if="hasSlot(column.headerSlotName)" #header="scope">
|
||||||
<slot :name="column.headerSlotName" v-bind="scope" />
|
<slot :name="column.headerSlotName" v-bind="scope" />
|
||||||
</template>
|
</template>
|
||||||
<template v-if="hasSlot(column.slotName)" #default="scope">
|
<template v-if="column.slotName === 'actions' && rowActions" #default="{ row }">
|
||||||
|
<div class="data-table__row-actions">
|
||||||
|
<el-button v-for="action in splitTableActions(rowActions(row)).visible" :key="action.key" link type="primary"
|
||||||
|
:disabled="action.disabled" :loading="action.loading" @click="runTableAction(action)">
|
||||||
|
{{ action.label }}
|
||||||
|
</el-button>
|
||||||
|
<el-dropdown v-if="splitTableActions(rowActions(row)).overflow.length" trigger="click">
|
||||||
|
<el-button class="data-table__more" aria-label="更多操作" title="更多操作">…</el-button>
|
||||||
|
<template #dropdown>
|
||||||
|
<el-dropdown-menu>
|
||||||
|
<el-dropdown-item v-for="action in splitTableActions(rowActions(row)).overflow" :key="action.key"
|
||||||
|
:disabled="action.disabled || action.loading" @click="runTableAction(action)">
|
||||||
|
{{ action.label }}
|
||||||
|
</el-dropdown-item>
|
||||||
|
</el-dropdown-menu>
|
||||||
|
</template>
|
||||||
|
</el-dropdown>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="hasSlot(column.slotName)" #default="scope">
|
||||||
<slot :name="column.slotName" v-bind="scope" />
|
<slot :name="column.slotName" v-bind="scope" />
|
||||||
</template>
|
</template>
|
||||||
</el-table-column>
|
</el-table-column>
|
||||||
@@ -163,12 +222,33 @@ function setPage(value: number) {
|
|||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.data-table { min-width: 0; }
|
.data-table { min-width: 0; }
|
||||||
.data-table__pagination { display: flex; min-height: 58px; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 18px; border-top: 1px solid var(--border); color: var(--muted); font-size: 12px; }
|
.data-table__toolbar { display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: var(--client-gap); padding: var(--client-toolbar-padding); border-bottom: 1px solid var(--client-border); }
|
||||||
|
.data-table__toolbar--actions-only { justify-content: flex-start; }
|
||||||
|
.data-table__toolbar-heading, .data-table__toolbar-actions { display: flex; align-items: center; flex-wrap: wrap; gap: var(--client-gap); }
|
||||||
|
.data-table__toolbar-heading { color: var(--client-muted); font-size: 12px; }
|
||||||
|
.data-table__toolbar-heading :slotted(strong) { color: var(--client-text); font-size: 14px; }
|
||||||
|
.data-table__toolbar-actions :deep(.el-button + .el-button) { margin-left: 0; }
|
||||||
|
.data-table__row-actions { display: flex; align-items: center; gap: var(--client-gap); white-space: nowrap; }
|
||||||
|
.data-table__row-actions :deep(.el-button) { height: var(--client-row-action-height); padding: 0 4px; margin: 0; }
|
||||||
|
.data-table__row-actions :deep(.el-button.is-link + .el-button.is-link) { position: relative; }
|
||||||
|
.data-table__row-actions :deep(.el-button.is-link + .el-button.is-link)::before { position: absolute; left: -5px; width: 1px; height: 12px; background: var(--client-border); content: ''; }
|
||||||
|
.data-table :deep(.data-table__system-cell .data-table__row-actions .el-button + .el-button), .data-table :deep(.data-table__system-cell .data-table__row-actions .el-button + .el-dropdown) { margin-left: 0; }
|
||||||
|
.data-table__more { min-width: 28px; width: 28px; padding: 0; }
|
||||||
|
:global(.client-ui .data-table .el-table) { color: var(--client-text); font-size: var(--client-font-size); --el-table-border-color: var(--client-border); --el-table-header-bg-color: var(--client-header-bg); --el-table-row-hover-bg-color: var(--client-hover-bg); }
|
||||||
|
:global(.client-ui .data-table th.el-table__cell) { height: var(--client-table-header-height); padding: 0; color: var(--client-muted); font-weight: 600; }
|
||||||
|
:global(.client-ui .data-table td.el-table__cell) { height: var(--client-table-row-height); padding: 0; }
|
||||||
|
:global(.client-ui .data-table .el-table .cell) { padding: 0 12px; line-height: 20px; }
|
||||||
|
:global(.client-ui .data-table .el-table__row:nth-child(even)) { --el-table-tr-bg-color: #fcfcfd; }
|
||||||
|
.data-table :deep(.data-table__single-line-cell .cell) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.data-table :deep(.data-table__system-cell .cell) { white-space: nowrap; }
|
||||||
|
.data-table :deep(.data-table__system-cell .el-button + .el-button), .data-table :deep(.data-table__system-cell .el-button + .el-dropdown) { margin-left: 8px; }
|
||||||
|
.data-table__pagination { display: flex; min-height: 58px; align-items: center; justify-content: space-between; gap: 16px; padding: var(--client-pagination-padding); border-top: 1px solid var(--border); color: var(--muted); font-size: 12px; }
|
||||||
.data-table__pagination-left { display: flex; min-width: 0; flex: 1; align-items: center; gap: 8px; }
|
.data-table__pagination-left { display: flex; min-width: 0; flex: 1; align-items: center; gap: 8px; }
|
||||||
.data-table__pagination-controls, .data-table__page-size, .data-table__page-buttons { display: flex; align-items: center; gap: 8px; }
|
.data-table__pagination-controls, .data-table__page-size, .data-table__page-buttons { display: flex; align-items: center; gap: 8px; }
|
||||||
.data-table__pagination-controls { min-width: 0; flex-wrap: wrap; justify-content: flex-end; }
|
.data-table__pagination-controls { min-width: 0; flex-wrap: wrap; justify-content: flex-end; }
|
||||||
|
|||||||
@@ -23,12 +23,14 @@ export interface QueryField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{
|
const props = withDefaults(defineProps<{
|
||||||
|
layout?: 'inline' | 'grid'
|
||||||
ariaLabel: string
|
ariaLabel: string
|
||||||
fields: QueryField[]
|
fields: QueryField[]
|
||||||
searchText?: string
|
searchText?: string
|
||||||
resetText?: string
|
resetText?: string
|
||||||
searchOnReset?: boolean
|
searchOnReset?: boolean
|
||||||
}>(), {
|
}>(), {
|
||||||
|
layout: 'inline',
|
||||||
searchText: '查询',
|
searchText: '查询',
|
||||||
resetText: '重置',
|
resetText: '重置',
|
||||||
searchOnReset: true,
|
searchOnReset: true,
|
||||||
@@ -77,6 +79,7 @@ defineExpose({ search, reset })
|
|||||||
<section
|
<section
|
||||||
v-bind="$attrs"
|
v-bind="$attrs"
|
||||||
class="query-toolbar"
|
class="query-toolbar"
|
||||||
|
:class="{ 'query-toolbar--grid': layout === 'grid' }"
|
||||||
:aria-label="ariaLabel"
|
:aria-label="ariaLabel"
|
||||||
>
|
>
|
||||||
<div class="query-toolbar__filters">
|
<div class="query-toolbar__filters">
|
||||||
@@ -118,8 +121,8 @@ defineExpose({ search, reset })
|
|||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
<div class="query-toolbar__actions">
|
<div class="query-toolbar__actions">
|
||||||
<el-button type="primary" @click="search"><Search :size="16" />{{ searchText }}</el-button>
|
<el-button class="query-toolbar__search" type="primary" @click="search"><Search :size="16" />{{ searchText }}</el-button>
|
||||||
<el-button @click="reset"><RotateCcw :size="16" />{{ resetText }}</el-button>
|
<el-button class="query-toolbar__reset" @click="reset"><RotateCcw :size="16" />{{ resetText }}</el-button>
|
||||||
<slot name="actions" />
|
<slot name="actions" />
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -133,5 +136,12 @@ defineExpose({ search, reset })
|
|||||||
.query-toolbar__filters :deep(.el-input), .query-toolbar__filters :deep(.el-select), .query-toolbar__filters :deep(.el-date-editor) { width: 260px; max-width: 100%; min-width: 0; }
|
.query-toolbar__filters :deep(.el-input), .query-toolbar__filters :deep(.el-select), .query-toolbar__filters :deep(.el-date-editor) { width: 260px; max-width: 100%; min-width: 0; }
|
||||||
.query-toolbar__actions { display: flex; flex: 0 0 auto; flex-wrap: wrap; justify-content: flex-start; gap: 8px; }
|
.query-toolbar__actions { display: flex; flex: 0 0 auto; flex-wrap: wrap; justify-content: flex-start; gap: 8px; }
|
||||||
.query-toolbar__actions :deep(.el-button + .el-button) { margin-left: 0; }
|
.query-toolbar__actions :deep(.el-button + .el-button) { margin-left: 0; }
|
||||||
|
.query-toolbar__actions :deep(.query-toolbar__search), .query-toolbar__actions :deep(.query-toolbar__reset) { min-width: 72px; }
|
||||||
|
.query-toolbar--grid { display: block; padding: var(--client-query-padding); border: 1px solid var(--client-border); border-radius: var(--client-radius); }
|
||||||
|
.query-toolbar--grid .query-toolbar__filters { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px 16px; }
|
||||||
|
.query-toolbar--grid .query-toolbar__field { min-width: 0; }
|
||||||
|
.query-toolbar--grid .query-toolbar__field :deep(.el-input), .query-toolbar--grid .query-toolbar__field :deep(.el-select), .query-toolbar--grid .query-toolbar__field :deep(.el-date-editor) { flex: 1; width: 100%; min-width: 0; }
|
||||||
|
.query-toolbar--grid .query-toolbar__actions { margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--client-border); }
|
||||||
|
@media (max-width: 1200px) { .query-toolbar--grid .query-toolbar__filters { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||||
@media (max-width: 720px) { .query-toolbar { align-items: stretch; flex-direction: column; } .query-toolbar__filters { width: 100%; flex-direction: column; } .query-toolbar__field { display: grid; gap: 6px; } .query-toolbar__filters :deep(.el-input), .query-toolbar__filters :deep(.el-select), .query-toolbar__filters :deep(.el-date-editor) { width: 100%; } .query-toolbar__actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); width: 100%; } .query-toolbar__actions :deep(.el-button) { min-height: 40px; margin-left: 0; } }
|
@media (max-width: 720px) { .query-toolbar { align-items: stretch; flex-direction: column; } .query-toolbar__filters { width: 100%; flex-direction: column; } .query-toolbar__field { display: grid; gap: 6px; } .query-toolbar__filters :deep(.el-input), .query-toolbar__filters :deep(.el-select), .query-toolbar__filters :deep(.el-date-editor) { width: 100%; } .query-toolbar__actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); width: 100%; } .query-toolbar__actions :deep(.el-button) { min-height: 40px; margin-left: 0; } }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
withDefaults(defineProps<{
|
||||||
|
value?: string | number | null
|
||||||
|
emptyText?: string
|
||||||
|
}>(), {
|
||||||
|
value: null,
|
||||||
|
emptyText: '—',
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span class="single-line-text" :title="value == null || value === '' ? undefined : String(value)">
|
||||||
|
{{ value == null || value === '' ? emptyText : value }}
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.single-line-text {
|
||||||
|
display: block;
|
||||||
|
max-width: 220px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { splitTableActions, runTableAction } from './tableActions.ts'
|
||||||
|
|
||||||
|
test('shows up to three permitted actions and folds only when there are more', () => {
|
||||||
|
const actions = Array.from({ length: 5 }, (_, index) => ({ key: String(index), label: String(index), run() {} }))
|
||||||
|
for (const count of [0, 1, 2, 3]) {
|
||||||
|
const result = splitTableActions(actions.slice(0, count))
|
||||||
|
assert.equal(result.visible.length, count)
|
||||||
|
assert.equal(result.overflow.length, 0)
|
||||||
|
}
|
||||||
|
for (const count of [4, 5]) {
|
||||||
|
const result = splitTableActions(actions.slice(0, count))
|
||||||
|
assert.deepEqual(result.visible, actions.slice(0, 2))
|
||||||
|
assert.deepEqual(result.overflow, actions.slice(2, count))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('disabled and loading actions cannot execute or disappear from the layout', () => {
|
||||||
|
let count = 0
|
||||||
|
const action = { key: 'edit', label: '编辑', run() { count++ } }
|
||||||
|
runTableAction({ ...action, disabled: true })
|
||||||
|
runTableAction({ ...action, loading: true })
|
||||||
|
assert.equal(count, 0)
|
||||||
|
runTableAction(action)
|
||||||
|
assert.equal(count, 1)
|
||||||
|
assert.equal(splitTableActions([{ ...action, disabled: true }]).visible.length, 1)
|
||||||
|
})
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
export interface TableAction {
|
||||||
|
key: string
|
||||||
|
label: string
|
||||||
|
disabled?: boolean
|
||||||
|
loading?: boolean
|
||||||
|
run: () => unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
// Callers supply only permitted actions; disabled actions retain their place.
|
||||||
|
export function splitTableActions(actions: readonly TableAction[]) {
|
||||||
|
return actions.length > 3
|
||||||
|
? { visible: actions.slice(0, 2), overflow: actions.slice(2) }
|
||||||
|
: { visible: actions, overflow: [] }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runTableAction(action: TableAction) {
|
||||||
|
if (!action.disabled && !action.loading) return action.run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
|
||||||
|
const recoverySource = readFileSync(new URL('./staticAssetRecovery.ts', import.meta.url), 'utf8')
|
||||||
|
const mainSource = readFileSync(new URL('../main.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
test('refreshes once when a deployment invalidates lazy chunks or same-origin scripts and styles', () => {
|
||||||
|
assert.match(mainSource, /installStaticAssetRecovery\(router\)/)
|
||||||
|
assert.match(recoverySource, /vite:preloadError/)
|
||||||
|
assert.match(recoverySource, /router\.onError/)
|
||||||
|
assert.match(recoverySource, /HTMLScriptElement/)
|
||||||
|
assert.match(recoverySource, /HTMLLinkElement/)
|
||||||
|
assert.match(recoverySource, /window\.location\.reload\(\)/)
|
||||||
|
assert.match(recoverySource, /RECOVERY_COOLDOWN_MS/)
|
||||||
|
assert.match(recoverySource, /previous\?\.href === window\.location\.href/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('does not turn ordinary application errors or third-party asset failures into refresh loops', () => {
|
||||||
|
assert.match(recoverySource, /isStaticAssetLoadError\(error\)/)
|
||||||
|
assert.match(recoverySource, /origin !== window\.location\.origin/)
|
||||||
|
assert.match(recoverySource, /sessionStorage/)
|
||||||
|
assert.match(recoverySource, /setTimeout\(clearRecoveryRecord, RECOVERY_STABLE_MS\)/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import type { Router } from 'vue-router'
|
||||||
|
|
||||||
|
const RECOVERY_KEY = 'client-static-asset-recovery'
|
||||||
|
const RECOVERY_COOLDOWN_MS = 60_000
|
||||||
|
const RECOVERY_STABLE_MS = 15_000
|
||||||
|
|
||||||
|
interface RecoveryRecord {
|
||||||
|
href: string
|
||||||
|
refreshedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(error: unknown) {
|
||||||
|
if (error instanceof Error) return `${error.name}: ${error.message}`
|
||||||
|
return typeof error === 'string' ? error : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isStaticAssetLoadError(error: unknown) {
|
||||||
|
return /ChunkLoadError|Loading chunk [\w-]+ failed|Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Unable to preload CSS/i.test(errorMessage(error))
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRecoveryRecord(): RecoveryRecord | null {
|
||||||
|
try {
|
||||||
|
const raw = window.sessionStorage.getItem(RECOVERY_KEY)
|
||||||
|
if (!raw) return null
|
||||||
|
const value = JSON.parse(raw) as Partial<RecoveryRecord>
|
||||||
|
return typeof value.href === 'string' && typeof value.refreshedAt === 'number'
|
||||||
|
? { href: value.href, refreshedAt: value.refreshedAt }
|
||||||
|
: null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeRecoveryRecord(record: RecoveryRecord) {
|
||||||
|
try {
|
||||||
|
window.sessionStorage.setItem(RECOVERY_KEY, JSON.stringify(record))
|
||||||
|
return true
|
||||||
|
} catch {
|
||||||
|
// Without a persistent guard, reloading could loop while the deployment is still unavailable.
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearRecoveryRecord() {
|
||||||
|
try {
|
||||||
|
window.sessionStorage.removeItem(RECOVERY_KEY)
|
||||||
|
} catch {
|
||||||
|
// Storage availability must not affect application startup.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function recoverFromStaticAssetFailure(error: unknown, confirmedAssetFailure = false) {
|
||||||
|
if (!confirmedAssetFailure && !isStaticAssetLoadError(error)) return false
|
||||||
|
const now = Date.now()
|
||||||
|
const previous = readRecoveryRecord()
|
||||||
|
if (previous?.href === window.location.href && now - previous.refreshedAt < RECOVERY_COOLDOWN_MS) return false
|
||||||
|
if (!writeRecoveryRecord({ href: window.location.href, refreshedAt: now })) return false
|
||||||
|
window.location.reload()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function failedApplicationAsset(event: Event) {
|
||||||
|
const target = event.target
|
||||||
|
if (target instanceof HTMLScriptElement) return target.src
|
||||||
|
if (target instanceof HTMLLinkElement && ['stylesheet', 'modulepreload', 'preload'].includes(target.rel)) return target.href
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function installStaticAssetRecovery(router: Router) {
|
||||||
|
window.addEventListener('vite:preloadError', (event) => {
|
||||||
|
const preloadEvent = event as Event & { payload?: unknown }
|
||||||
|
if (recoverFromStaticAssetFailure(preloadEvent.payload, true)) preloadEvent.preventDefault()
|
||||||
|
})
|
||||||
|
|
||||||
|
window.addEventListener('error', (event) => {
|
||||||
|
const assetUrl = failedApplicationAsset(event)
|
||||||
|
if (!assetUrl) return
|
||||||
|
try {
|
||||||
|
if (new URL(assetUrl, window.location.href).origin !== window.location.origin) return
|
||||||
|
} catch {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
recoverFromStaticAssetFailure(assetUrl, true)
|
||||||
|
}, true)
|
||||||
|
|
||||||
|
router.onError((error) => {
|
||||||
|
recoverFromStaticAssetFailure(error)
|
||||||
|
})
|
||||||
|
|
||||||
|
window.setTimeout(clearRecoveryRecord, RECOVERY_STABLE_MS)
|
||||||
|
}
|
||||||
@@ -1,9 +1,63 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync, existsSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
|
||||||
const config = readFileSync(new URL('../../nginx/default.conf.template', import.meta.url), 'utf8')
|
const root = new URL('../../', import.meta.url)
|
||||||
|
const 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 qualification uploads with multipart overhead through the API proxy', () => {
|
test('all business traffic uses one Gateway without rewriting API paths', () => {
|
||||||
assert.match(config, /location \/api\/ \{[\s\S]*?client_max_body_size 12m;/)
|
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(vite, /OVERSEAS_API|AUTH_API_PROXY_TARGET|IAM_API_PROXY_TARGET|WAREHOUSE_API_PROXY_TARGET/)
|
||||||
|
})
|
||||||
|
|
||||||
|
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('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('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/)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readdirSync, readFileSync } from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const sourceRoot = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
|
||||||
|
function collectVueFiles(directory) {
|
||||||
|
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
||||||
|
const target = path.join(directory, entry.name)
|
||||||
|
return entry.isDirectory() ? collectVueFiles(target) : entry.name.endsWith('.vue') ? [target] : []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function lineNumber(source, offset) {
|
||||||
|
return source.slice(0, offset).split('\n').length
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasLiteralAttribute(tag, name) {
|
||||||
|
return new RegExp(`\\s${name}(?:\\s|=|/?>)`).test(tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isEditableNativeTextInput(tag) {
|
||||||
|
if (hasLiteralAttribute(tag, 'disabled') || hasLiteralAttribute(tag, 'readonly')) return false
|
||||||
|
const type = tag.match(/\stype\s*=\s*["']([^"']+)["']/)?.[1]?.toLowerCase() ?? 'text'
|
||||||
|
return ['text', 'search', 'email', 'tel', 'url', 'password'].includes(type)
|
||||||
|
}
|
||||||
|
|
||||||
|
test('all editable text inputs provide a user-facing placeholder', () => {
|
||||||
|
const violations = []
|
||||||
|
|
||||||
|
for (const file of collectVueFiles(sourceRoot)) {
|
||||||
|
const source = readFileSync(file, 'utf8')
|
||||||
|
const template = source.match(/<template(?:\s[^>]*)?>([\s\S]*)<\/template>/)?.[1] ?? ''
|
||||||
|
const withoutComments = template.replace(/<!--[\s\S]*?-->/g, '')
|
||||||
|
const attributeContent = String.raw`(?:[^>"']|"[^"]*"|'[^']*')*`
|
||||||
|
const tagPattern = new RegExp(`<el-input(?:-number)?\\b${attributeContent}/?>|<(?:input|textarea)\\b${attributeContent}/?>`, 'g')
|
||||||
|
|
||||||
|
for (const match of withoutComments.matchAll(tagPattern)) {
|
||||||
|
const tag = match[0]
|
||||||
|
const isElementInput = tag.startsWith('<el-input')
|
||||||
|
const editable = isElementInput
|
||||||
|
? !hasLiteralAttribute(tag, 'disabled') && !hasLiteralAttribute(tag, 'readonly')
|
||||||
|
: isEditableNativeTextInput(tag)
|
||||||
|
|
||||||
|
if (editable && !/\s:?(?:placeholder)\s*=/.test(tag)) {
|
||||||
|
violations.push(`${path.relative(sourceRoot, file)}:${lineNumber(withoutComments, match.index ?? 0)} ${tag.replace(/\s+/g, ' ')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.deepEqual(violations, [], `Editable text inputs without placeholders:\n${violations.join('\n')}`)
|
||||||
|
})
|
||||||
Vendored
+1
@@ -11,6 +11,7 @@ declare module 'vue-router' {
|
|||||||
requiresAuth?: boolean
|
requiresAuth?: boolean
|
||||||
permission?: string
|
permission?: string
|
||||||
workspaceTab?: boolean
|
workspaceTab?: boolean
|
||||||
|
workspaceTitle?: string
|
||||||
keepAlive?: boolean
|
keepAlive?: boolean
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
|
||||||
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
||||||
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
||||||
@@ -13,12 +15,13 @@ test('source contract: renders the grouped sidebar menu and mobile drawer contro
|
|||||||
assert.match(layoutSource, /import \{ computed, nextTick, onBeforeUnmount, onMounted, ref, watch \} from 'vue'/)
|
assert.match(layoutSource, /import \{ computed, nextTick, onBeforeUnmount, onMounted, ref, watch \} from 'vue'/)
|
||||||
assert.match(layoutSource, /import \{[\s\S]*?\bX\s*\} from '@lucide\/vue'/)
|
assert.match(layoutSource, /import \{[\s\S]*?\bX\s*\} from '@lucide\/vue'/)
|
||||||
assert.match(layoutSource, /import ClientSidebarMenu from '@\/components\/ClientSidebarMenu\.vue'/)
|
assert.match(layoutSource, /import ClientSidebarMenu from '@\/components\/ClientSidebarMenu\.vue'/)
|
||||||
assert.match(layoutSource, /:class="\{ 'mobile-menu-open': mobileMenuOpen \}"/)
|
assert.match(layoutSource, /:class="\{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route\.path === '\/' \}"/)
|
||||||
assert.match(layoutSource, /<button\s+v-if="mobileMenuOpen"[^>]*class="client-sidebar-scrim"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"/s)
|
assert.match(layoutSource, /<button\s+v-if="mobileMenuOpen"[^>]*class="client-sidebar-scrim"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"/s)
|
||||||
assert.match(layoutSource, /<aside\s+ref="sidebarRef"\s+id="client-sidebar"\s+class="client-sidebar"\s+:inert="!desktopViewport && !mobileMenuOpen"\s+:aria-hidden="!desktopViewport && !mobileMenuOpen \? 'true' : undefined"\s*>/)
|
assert.match(layoutSource, /<aside\s+ref="sidebarRef"\s+id="client-sidebar"\s+class="client-sidebar"\s+:inert="!desktopViewport && !mobileMenuOpen"\s+:aria-hidden="!desktopViewport && !mobileMenuOpen \? 'true' : undefined"\s*>/)
|
||||||
assert.doesNotMatch(layoutSource, /<aside[^>]*aria-label=/)
|
assert.doesNotMatch(layoutSource, /<aside[^>]*aria-label=/)
|
||||||
assert.match(layoutSource, /<nav aria-label="客户工作台导航">/)
|
assert.match(layoutSource, /<nav aria-label="客户工作台导航">/)
|
||||||
assert.match(layoutSource, /<div class="client-sidebar-brand">[\s\S]*?<RouterLink class="client-sidebar-brand-link" to="\/" aria-label="返回业务总览" @click="closeMobileMenu">[\s\S]*?alt="柏悦物流"[\s\S]*?客户工作台/s)
|
assert.match(layoutSource, /<div class="client-sidebar-brand">[\s\S]*?<RouterLink class="client-sidebar-brand-link" to="\/" aria-label="返回业务总览" @click="closeMobileMenu">[\s\S]*?alt="柏悦物流"/s)
|
||||||
|
assert.doesNotMatch(layoutSource, /client-sidebar-brand-copy/)
|
||||||
assert.match(layoutSource, /<button[^>]*ref="sidebarCloseButtonRef"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"[^>]*>\s*<X :size="20" \/>/s)
|
assert.match(layoutSource, /<button[^>]*ref="sidebarCloseButtonRef"[^>]*aria-label="关闭导航"[^>]*@click="closeMobileMenu"[^>]*>\s*<X :size="20" \/>/s)
|
||||||
assert.match(layoutSource, /<ClientSidebarMenu\s+:active-path="route\.path"\s+@navigate="closeMobileMenu"\s*\/>/s)
|
assert.match(layoutSource, /<ClientSidebarMenu\s+:active-path="route\.path"\s+@navigate="closeMobileMenu"\s*\/>/s)
|
||||||
assert.match(layoutSource, /<button type="button" class="client-sidebar-logout" @click="handleLogout">[\s\S]*?退出登录/s)
|
assert.match(layoutSource, /<button type="button" class="client-sidebar-logout" @click="handleLogout">[\s\S]*?退出登录/s)
|
||||||
@@ -45,25 +48,40 @@ test('source contract: removes the header and main content from the accessibilit
|
|||||||
assert.match(layoutSource, /<main\s+class="client-main"\s+:inert="mobileMenuOpen"\s+:aria-hidden="mobileMenuOpen \? 'true' : undefined"\s*>/)
|
assert.match(layoutSource, /<main\s+class="client-main"\s+:inert="mobileMenuOpen"\s+:aria-hidden="mobileMenuOpen \? 'true' : undefined"\s*>/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('source contract: keeps route context and user identity in the compact header', () => {
|
test('source contract: keeps the prototype greeting and fixed message and profile utilities in the compact header', () => {
|
||||||
assert.match(layoutSource, /const pageTitle = computed\(\(\) => route\.meta\.title \|\| '业务总览'\)/)
|
assert.match(layoutSource, /const pageTitle = computed\(\(\) => route\.meta\.title \|\| '业务总览'\)/)
|
||||||
assert.match(layoutSource, /const pageDescription = computed\(\(\) => route\.meta\.description \|\| ''\)/)
|
assert.doesNotMatch(layoutSource, /const pageDescription/)
|
||||||
assert.match(layoutSource, /<div class="client-header-heading">\s*<h1>\{\{ pageTitle \}\}<\/h1>\s*<p v-if="pageDescription">\{\{ pageDescription \}\}<\/p>/s)
|
assert.match(layoutSource, /<p class="client-header-greeting">Hi, 客户<\/p>/)
|
||||||
assert.match(layoutSource, /<div class="client-user">[\s\S]*\{\{ auth\.user\?\.name \}\}/)
|
assert.match(layoutSource, /<div class="client-user">[\s\S]*\{\{ auth\.user\?\.name \}\}/)
|
||||||
|
assert.match(layoutSource, /class="client-header-notifications" to="\/notifications" aria-label="打开我的消息"/)
|
||||||
|
assert.match(layoutSource, /class="client-header-profile"[\s\S]*to="\/account\/profile"[\s\S]*aria-label="打开我的信息"/)
|
||||||
assert.doesNotMatch(layoutSource, /<div class="client-user">[\s\S]*aria-label="退出登录"/)
|
assert.doesNotMatch(layoutSource, /<div class="client-user">[\s\S]*aria-label="退出登录"/)
|
||||||
assert.doesNotMatch(layoutSource, /Building2|tenant-name|tenantName/)
|
assert.doesNotMatch(layoutSource, /Building2|tenant-name|tenantName/)
|
||||||
assert.doesNotMatch(routerSource, /showPageHeading|showTenantName/)
|
assert.doesNotMatch(routerSource, /showPageHeading|showTenantName/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('source contract: aligns the light top bar beside the prototype-inspired dark sidebar and bounds the mobile header', () => {
|
test('source contract: renders the complete route breadcrumb before page content', () => {
|
||||||
assert.match(shellStyles, /\.top-header \{[^}]*inset: 0 0 auto 250px;[^}]*max-width: calc\(100vw - 250px\);[^}]*padding: 0 24px;/)
|
assert.match(layoutSource, /import \{ getFirstAccessiblePath, getRouteBreadcrumbs \} from '@\/navigation\/clientNavigation'/)
|
||||||
assert.match(shellStyles, /\.top-header \{[^}]*background: rgba\(255, 255, 255, \.96\)/)
|
assert.match(layoutSource, /const breadcrumbs = computed\(\(\) => getRouteBreadcrumbs\(route\.path, String\(pageTitle\.value\)\)\)/)
|
||||||
assert.match(shellStyles, /\.client-sidebar \{[^}]*inset: 0 auto 0 0;[^}]*width: 250px;[^}]*background: linear-gradient\(180deg, #0b1f3a 0%, #0c2a52 100%\)/)
|
assert.match(layoutSource, /<nav v-if="route\.path !== '\/'" class="client-breadcrumb" aria-label="页面路径">[\s\S]*?v-for="\(item, index\) in breadcrumbs"[\s\S]*?<RouterLink v-if="item\.path" :to="item\.path">[\s\S]*?<strong v-else aria-current="page">/)
|
||||||
assert.match(shellStyles, /\.client-sidebar-brand \{[^}]*border-bottom: 1px solid rgba\(255, 255, 255, \.09\)/)
|
assert.match(shellStyles, /\.client-breadcrumb \{[^}]*margin: 0 0 14px;/)
|
||||||
assert.match(shellStyles, /\.client-main \{[^}]*padding: 134px 20px 40px;/)
|
})
|
||||||
|
|
||||||
|
test('source contract: aligns the blue-tinted prototype shell around a compact sidebar and bounds the mobile header', () => {
|
||||||
|
assert.match(shellStyles, /\.top-header \{[^}]*inset: 0 0 auto 224px;[^}]*max-width: calc\(100vw - 224px\);[^}]*padding: 0 24px;/)
|
||||||
|
assert.match(shellStyles, /\.top-header \{[^}]*background: rgba\(255, 255, 255, \.98\)/)
|
||||||
|
assert.match(shellStyles, /\.client-sidebar \{[^}]*inset: 0 auto 0 0;[^}]*width: 224px;[^}]*border-right: 1px solid #dfe8f3;[^}]*background: linear-gradient\(180deg, #f5f8ff 0%, #edf5fc 100%\)/)
|
||||||
|
assert.match(shellStyles, /\.client-sidebar-brand \{[^}]*border-radius: 15px;[^}]*background: linear-gradient\(145deg, #0a2b50, #0b3d6c\)/)
|
||||||
|
assert.match(shellStyles, /\.client-main \{[^}]*padding: 126px 20px 40px;/)
|
||||||
|
assert.match(shellStyles, /\.is-dashboard-route \.client-main \{ padding-top: 88px; \}/)
|
||||||
assert.match(globalStyles, /@media \(max-width: 720px\) \{[\s\S]*\.top-header \{ inset: 0;[^}]*padding: 0 14px; \}/)
|
assert.match(globalStyles, /@media \(max-width: 720px\) \{[\s\S]*\.top-header \{ inset: 0;[^}]*padding: 0 14px; \}/)
|
||||||
assert.match(globalStyles, /\.client-header-menu-button \{ display: grid; \}/)
|
assert.match(globalStyles, /\.client-header-menu-button \{ display: grid; \}/)
|
||||||
assert.match(globalStyles, /\.client-header-heading p, \.client-user-copy \{ display: none; \}/)
|
assert.match(globalStyles, /\.client-header-greeting, \.client-user-copy \{ display: none; \}/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('source contract: keeps the dashboard free of a redundant workspace tab', () => {
|
||||||
|
assert.match(layoutSource, /<WorkspaceTabs\s+v-if="route\.path !== '\/'"/)
|
||||||
|
assert.match(layoutSource, /'is-dashboard-route': route\.path === '\/'/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('source contract: closes the mobile menu on route changes and Escape', () => {
|
test('source contract: closes the mobile menu on route changes and Escape', () => {
|
||||||
@@ -92,7 +110,7 @@ test('source contract: locks body scrolling while open and restores it on close
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
|
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
|
||||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*try \{/)
|
assert.match(layoutSource, /async function handleLogout\(\) \{\s*const logoutToken = auth.token\s*try \{/)
|
||||||
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -103,7 +121,8 @@ test('source contract: uses a native recursive disclosure list without Element m
|
|||||||
assert.match(sidebarMenuSource, /const activeParentKeys = computed\(\(\) => new Set\(getNavigationParentKeys\(visibleNavigation\.value, props\.activePath\)\)\)/)
|
assert.match(sidebarMenuSource, /const activeParentKeys = computed\(\(\) => new Set\(getNavigationParentKeys\(visibleNavigation\.value, props\.activePath\)\)\)/)
|
||||||
assert.match(sidebarMenuSource, /const openedKeys = ref<ReadonlySet<string>>\(new Set\(activeParentKeys\.value\)\)/)
|
assert.match(sidebarMenuSource, /const openedKeys = ref<ReadonlySet<string>>\(new Set\(activeParentKeys\.value\)\)/)
|
||||||
assert.match(sidebarMenuSource, /openedKeys\.value = new Set\(\[\.\.\.openedKeys\.value, \.\.\.activeParentKeys\.value\]\)/)
|
assert.match(sidebarMenuSource, /openedKeys\.value = new Set\(\[\.\.\.openedKeys\.value, \.\.\.activeParentKeys\.value\]\)/)
|
||||||
assert.match(sidebarMenuSource, /if \(activeParentKeys\.value\.has\(key\)\) return/)
|
assert.doesNotMatch(sidebarMenuSource, /if \(activeParentKeys\.value\.has\(key\)\) return/)
|
||||||
|
assert.match(sidebarMenuSource, /if \(next\.has\(key\)\) next\.delete\(key\)/)
|
||||||
assert.match(sidebarMenuSource, /<ul class="client-nav-menu">/)
|
assert.match(sidebarMenuSource, /<ul class="client-nav-menu">/)
|
||||||
assert.match(sidebarMenuSource, /:active-path="activePath"/)
|
assert.match(sidebarMenuSource, /:active-path="activePath"/)
|
||||||
assert.match(sidebarMenuSource, /:opened-keys="openedKeys"/)
|
assert.match(sidebarMenuSource, /:opened-keys="openedKeys"/)
|
||||||
@@ -131,3 +150,49 @@ test('source contract: routes denied pages to an explicit 403 state', () => {
|
|||||||
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
||||||
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function logoutHarness(t) {
|
||||||
|
const script = layoutSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||||
|
const ast = ts.createSourceFile('layout.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||||
|
const nodes = ast.statements.filter(node => (ts.isFunctionDeclaration(node) && node.name?.text === 'handleLogout') || (ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes('() => auth.isAuthenticated')))
|
||||||
|
const code = ts.transpileModule(nodes.map(node => node.getText(ast)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
let rejectLogout, confirm
|
||||||
|
const remote = new Promise((_, no) => { rejectLogout = no })
|
||||||
|
const confirmation = new Promise(yes => { confirm = yes })
|
||||||
|
const calls = [], warnings = []
|
||||||
|
const auth = vue.reactive({ token: 'A', isAuthenticated: true, logout: () => { calls.push('logout'); auth.token = ''; auth.isAuthenticated = false; return remote } })
|
||||||
|
const scope = vue.effectScope(); t.after(() => scope.stop())
|
||||||
|
const handler = scope.run(() => new Function('watch', 'auth', 'workspace', 'unsaved', 'router', 'ElMessageBox', 'ElMessage', code + ';return handleLogout')(vue.watch, auth, { clear: () => calls.push('workspace') }, { hasDirty: false, clear: () => calls.push('unsaved') }, { replace: path => { calls.push(path); return Promise.resolve() } }, { confirm: () => confirmation }, { warning: value => warnings.push(value) }))
|
||||||
|
return { auth, handler, confirm, rejectLogout, calls, warnings }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('logout navigates before remote completion and late failure cannot affect a new login', async t => {
|
||||||
|
const h = logoutHarness(t)
|
||||||
|
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||||
|
assert.deepEqual(h.calls, ['logout', 'workspace', 'unsaved', '/login'])
|
||||||
|
assert.equal(h.auth.isAuthenticated, false)
|
||||||
|
h.auth.token = 'B'; h.auth.isAuthenticated = true; await vue.nextTick()
|
||||||
|
h.rejectLogout(new Error('SESSION_CHANGED')); await Promise.resolve(); await vue.nextTick()
|
||||||
|
assert.equal(h.auth.token, 'B'); assert.equal(h.auth.isAuthenticated, true)
|
||||||
|
assert.equal(h.calls.filter(item => item === '/login').length, 1)
|
||||||
|
assert.equal(h.warnings.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('cross-tab logout leaves protected route and stale confirmation never logs out a new identity', async t => {
|
||||||
|
const h = logoutHarness(t)
|
||||||
|
const clicked = h.handler()
|
||||||
|
h.auth.token = 'B'; h.confirm(); await clicked
|
||||||
|
assert.equal(h.calls.length, 0)
|
||||||
|
h.auth.token = ''; h.auth.isAuthenticated = false; await vue.nextTick()
|
||||||
|
assert.deepEqual(h.calls, ['workspace', 'unsaved', '/login'])
|
||||||
|
assert.match(layoutSource, /<div v-if="auth.isAuthenticated" class="client-shell"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('remote logout failure reports incomplete server revocation without leaving protected content visible', async t => {
|
||||||
|
const h = logoutHarness(t)
|
||||||
|
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||||
|
h.rejectLogout(new Error('offline')); await Promise.resolve()
|
||||||
|
assert.equal(h.auth.isAuthenticated, false)
|
||||||
|
assert.ok(h.calls.includes('/login'))
|
||||||
|
assert.deepEqual(h.warnings, ['已退出本页,服务器会话注销未完成'])
|
||||||
|
})
|
||||||
|
|||||||
+32
-13
@@ -1,14 +1,14 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
||||||
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
||||||
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
||||||
import WorkspaceTabs from '@/components/WorkspaceTabs.vue'
|
import WorkspaceTabs from '@/components/WorkspaceTabs.vue'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
import { useNotificationsStore } from '@/modules/notifications/public'
|
import { useNotificationsStore } from '@/modules/notifications/public'
|
||||||
import { getFirstAccessiblePath } from '@/navigation/clientNavigation'
|
import { getFirstAccessiblePath, getRouteBreadcrumbs } from '@/navigation/clientNavigation'
|
||||||
import { useUnsavedWorkStore } from '@/navigation/workspace-tabs/unsavedWork'
|
import { useUnsavedWorkStore } from '@/navigation/workspace-tabs/unsavedWork'
|
||||||
import {
|
import {
|
||||||
MAX_CACHED_WORKSPACE_VIEWS,
|
MAX_CACHED_WORKSPACE_VIEWS,
|
||||||
@@ -24,7 +24,7 @@ const notifications = useNotificationsStore()
|
|||||||
const workspace = useWorkspaceTabsStore()
|
const workspace = useWorkspaceTabsStore()
|
||||||
const unsaved = useUnsavedWorkStore()
|
const unsaved = useUnsavedWorkStore()
|
||||||
const pageTitle = computed(() => route.meta.title || '业务总览')
|
const pageTitle = computed(() => route.meta.title || '业务总览')
|
||||||
const pageDescription = computed(() => route.meta.description || '')
|
const breadcrumbs = computed(() => getRouteBreadcrumbs(route.path, String(pageTitle.value)))
|
||||||
const mobileMenuOpen = ref(false)
|
const mobileMenuOpen = ref(false)
|
||||||
const desktopViewport = ref(true)
|
const desktopViewport = ref(true)
|
||||||
const menuButtonRef = ref<HTMLButtonElement>()
|
const menuButtonRef = ref<HTMLButtonElement>()
|
||||||
@@ -108,6 +108,7 @@ watch(
|
|||||||
watch(
|
watch(
|
||||||
() => auth.permissionCodes.join('|'),
|
() => auth.permissionCodes.join('|'),
|
||||||
() => {
|
() => {
|
||||||
|
if (!auth.isAuthenticated) return
|
||||||
const result = workspace.reconcile(isAllowedTab)
|
const result = workspace.reconcile(isAllowedTab)
|
||||||
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
||||||
},
|
},
|
||||||
@@ -119,6 +120,7 @@ watch(
|
|||||||
if (authenticated) return
|
if (authenticated) return
|
||||||
workspace.clear()
|
workspace.clear()
|
||||||
unsaved.clear()
|
unsaved.clear()
|
||||||
|
void router.replace('/login')
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -163,6 +165,7 @@ function handleBeforeUnload(event: BeforeUnloadEvent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleLogout() {
|
async function handleLogout() {
|
||||||
|
const logoutToken = auth.token
|
||||||
try {
|
try {
|
||||||
await ElMessageBox.confirm(unsaved.hasDirty
|
await ElMessageBox.confirm(unsaved.hasDirty
|
||||||
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
||||||
@@ -176,15 +179,16 @@ async function handleLogout() {
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
workspace.clear()
|
if (auth.token !== logoutToken) return
|
||||||
unsaved.clear()
|
void auth.logout().catch(() => {
|
||||||
await auth.logout()
|
if (!auth.isAuthenticated) ElMessage.warning('已退出本页,服务器会话注销未完成')
|
||||||
await router.replace('/login')
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen }">
|
<div v-if="auth.isAuthenticated" class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||||
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
|
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
|
||||||
<button
|
<button
|
||||||
ref="menuButtonRef"
|
ref="menuButtonRef"
|
||||||
@@ -197,14 +201,22 @@ async function handleLogout() {
|
|||||||
>
|
>
|
||||||
<Menu :size="20" />
|
<Menu :size="20" />
|
||||||
</button>
|
</button>
|
||||||
<div class="client-header-heading">
|
<p class="client-header-greeting">Hi, 客户</p>
|
||||||
<h1>{{ pageTitle }}</h1>
|
|
||||||
<p v-if="pageDescription">{{ pageDescription }}</p>
|
|
||||||
</div>
|
|
||||||
<div class="client-user">
|
<div class="client-user">
|
||||||
<RouterLink v-if="auth.hasPermission('merchant:notification:view')" class="client-header-notifications" to="/notifications" aria-label="打开我的消息"><Bell :size="19" /><span v-if="notifications.unreadCount !== null && notifications.unreadCount > 0" class="client-header-notifications-badge">{{ notifications.unreadCount > 99 ? '99+' : notifications.unreadCount }}</span></RouterLink>
|
<RouterLink v-if="auth.hasPermission('merchant:notification:view')" class="client-header-notifications" to="/notifications" aria-label="打开我的消息"><Bell :size="19" /><span v-if="notifications.unreadCount !== null && notifications.unreadCount > 0" class="client-header-notifications-badge">{{ notifications.unreadCount > 99 ? '99+' : notifications.unreadCount }}</span></RouterLink>
|
||||||
|
<RouterLink
|
||||||
|
v-if="auth.hasPermission('account:profile:view')"
|
||||||
|
class="client-header-profile"
|
||||||
|
to="/account/profile"
|
||||||
|
aria-label="打开我的信息"
|
||||||
|
>
|
||||||
<span class="client-avatar">{{ auth.user?.name.slice(0, 1) }}</span>
|
<span class="client-avatar">{{ auth.user?.name.slice(0, 1) }}</span>
|
||||||
<span class="client-user-copy"><strong>{{ auth.user?.name }}</strong><small>{{ auth.user?.roles.join('、') }}</small></span>
|
<span class="client-user-copy"><strong>{{ auth.user?.name }}</strong><small>{{ auth.user?.roles.join('、') }}</small></span>
|
||||||
|
</RouterLink>
|
||||||
|
<template v-else>
|
||||||
|
<span class="client-avatar">{{ auth.user?.name.slice(0, 1) }}</span>
|
||||||
|
<span class="client-user-copy"><strong>{{ auth.user?.name }}</strong><small>{{ auth.user?.roles.join('、') }}</small></span>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -226,7 +238,6 @@ async function handleLogout() {
|
|||||||
<div class="client-sidebar-brand">
|
<div class="client-sidebar-brand">
|
||||||
<RouterLink class="client-sidebar-brand-link" to="/" aria-label="返回业务总览" @click="closeMobileMenu">
|
<RouterLink class="client-sidebar-brand-link" to="/" aria-label="返回业务总览" @click="closeMobileMenu">
|
||||||
<img class="client-sidebar-brand-logo" :src="baiyueLogoDark" alt="柏悦物流" />
|
<img class="client-sidebar-brand-logo" :src="baiyueLogoDark" alt="柏悦物流" />
|
||||||
<span class="client-sidebar-brand-copy"><small>客户工作台</small></span>
|
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<button
|
<button
|
||||||
ref="sidebarCloseButtonRef"
|
ref="sidebarCloseButtonRef"
|
||||||
@@ -250,6 +261,7 @@ async function handleLogout() {
|
|||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<WorkspaceTabs
|
<WorkspaceTabs
|
||||||
|
v-if="route.path !== '/'"
|
||||||
:inert="mobileMenuOpen"
|
:inert="mobileMenuOpen"
|
||||||
:aria-hidden="mobileMenuOpen ? 'true' : undefined"
|
:aria-hidden="mobileMenuOpen ? 'true' : undefined"
|
||||||
/>
|
/>
|
||||||
@@ -259,6 +271,13 @@ async function handleLogout() {
|
|||||||
:inert="mobileMenuOpen"
|
:inert="mobileMenuOpen"
|
||||||
:aria-hidden="mobileMenuOpen ? 'true' : undefined"
|
:aria-hidden="mobileMenuOpen ? 'true' : undefined"
|
||||||
>
|
>
|
||||||
|
<nav v-if="route.path !== '/'" class="client-breadcrumb" aria-label="页面路径">
|
||||||
|
<template v-for="(item, index) in breadcrumbs" :key="`${item.title}-${index}`">
|
||||||
|
<span v-if="index" aria-hidden="true">/</span>
|
||||||
|
<RouterLink v-if="item.path" :to="item.path">{{ item.title }}</RouterLink>
|
||||||
|
<strong v-else aria-current="page">{{ item.title }}</strong>
|
||||||
|
</template>
|
||||||
|
</nav>
|
||||||
<RouterView v-slot="{ Component, route: viewRoute }">
|
<RouterView v-slot="{ Component, route: viewRoute }">
|
||||||
<KeepAlive :max="MAX_CACHED_WORKSPACE_VIEWS">
|
<KeepAlive :max="MAX_CACHED_WORKSPACE_VIEWS">
|
||||||
<component
|
<component
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
import { createApp } from 'vue'
|
import { createApp } from 'vue'
|
||||||
import { h } from 'vue'
|
import { h } from 'vue'
|
||||||
|
import 'dayjs/locale/zh-cn'
|
||||||
import { createPinia } from 'pinia'
|
import { createPinia } from 'pinia'
|
||||||
import { ElConfigProvider } from 'element-plus'
|
import { ElConfigProvider } from 'element-plus'
|
||||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||||
import App from './App.vue'
|
import App from './App.vue'
|
||||||
import router from './router'
|
import router from './router'
|
||||||
|
import { installStaticAssetRecovery } from './core/staticAssetRecovery'
|
||||||
import 'element-plus/es/components/message/style/css'
|
import 'element-plus/es/components/message/style/css'
|
||||||
import 'element-plus/es/components/message-box/style/css'
|
import 'element-plus/es/components/message-box/style/css'
|
||||||
import './styles/index.css'
|
import './styles/index.css'
|
||||||
|
|
||||||
|
installStaticAssetRecovery(router)
|
||||||
|
|
||||||
const app = createApp({ render: () => h(ElConfigProvider, { locale: zhCn }, { default: () => h(App) }) })
|
const app = createApp({ render: () => h(ElConfigProvider, { locale: zhCn }, { default: () => h(App) }) })
|
||||||
app.use(createPinia()).use(router).mount('#app')
|
app.use(createPinia()).use(router).mount('#app')
|
||||||
|
|||||||
@@ -3,20 +3,26 @@ import test from 'node:test'
|
|||||||
import {
|
import {
|
||||||
getPasswordStrength,
|
getPasswordStrength,
|
||||||
validateEditableAccountProfile,
|
validateEditableAccountProfile,
|
||||||
|
validateLoginIdentifierChange,
|
||||||
validatePasswordChange,
|
validatePasswordChange,
|
||||||
} from './accountProfile.ts'
|
} from './accountProfile.ts'
|
||||||
|
|
||||||
test('accepts a complete editable account profile', () => {
|
test('accepts a complete editable account profile', () => {
|
||||||
assert.deepEqual(validateEditableAccountProfile({
|
assert.deepEqual(validateEditableAccountProfile({
|
||||||
realName: '企业管理员',
|
realName: '企业管理员',
|
||||||
phone: '13800006601',
|
|
||||||
email: 'admin@example.com',
|
email: 'admin@example.com',
|
||||||
}), [])
|
}), [])
|
||||||
})
|
})
|
||||||
|
|
||||||
test('reports invalid profile fields together', () => {
|
test('reports invalid profile fields together', () => {
|
||||||
const errors = validateEditableAccountProfile({ realName: '', phone: '1'.repeat(33), email: 'bad' })
|
const errors = validateEditableAccountProfile({ realName: '', email: 'bad' })
|
||||||
assert.equal(errors.length, 3)
|
assert.equal(errors.length, 2)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('validates the frozen username, mainland mobile and current-password rules', () => {
|
||||||
|
assert.deepEqual(validateLoginIdentifierChange({ username: 'Merchant.Admin', phone: '13800006601', currentPassword: 'Current123' }), [])
|
||||||
|
assert.equal(validateLoginIdentifierChange({ username: '1bad', phone: '10086', currentPassword: '' }).length, 3)
|
||||||
|
assert.match(validateLoginIdentifierChange({ username: 'Merchant.Admin', phone: '11111111111', currentPassword: 'Current123' }).join('|'), /有效的中国大陆手机号/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('validates password length, equality and confirmation', () => {
|
test('validates password length, equality and confirmation', () => {
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
export interface EditableAccountProfile {
|
export interface EditableAccountProfile {
|
||||||
realName: string
|
realName: string
|
||||||
phone: string
|
|
||||||
email: string
|
email: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface LoginIdentifierChangePayload {
|
||||||
|
username: string
|
||||||
|
phone: string
|
||||||
|
currentPassword: string
|
||||||
|
}
|
||||||
|
|
||||||
export interface PasswordChangePayload {
|
export interface PasswordChangePayload {
|
||||||
currentPassword: string
|
currentPassword: string
|
||||||
newPassword: string
|
newPassword: string
|
||||||
@@ -11,20 +16,30 @@ export interface PasswordChangePayload {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
const USERNAME_PATTERN = /^[A-Za-z][A-Za-z0-9_.@-]{3,63}$/
|
||||||
|
const MAINLAND_MOBILE_PATTERN = /^1[3-9]\d{9}$/
|
||||||
|
|
||||||
export function validateEditableAccountProfile(profile: EditableAccountProfile): string[] {
|
export function validateEditableAccountProfile(profile: EditableAccountProfile): string[] {
|
||||||
const errors: string[] = []
|
const errors: string[] = []
|
||||||
const realName = profile.realName.trim()
|
const realName = profile.realName.trim()
|
||||||
const phone = profile.phone.trim()
|
|
||||||
const email = profile.email.trim()
|
const email = profile.email.trim()
|
||||||
|
|
||||||
if (realName.length < 1 || realName.length > 64) errors.push('姓名需为 1–64 个字符')
|
if (realName.length < 1 || realName.length > 64) errors.push('姓名需为 1–64 个字符')
|
||||||
if (phone.length > 32) errors.push('联系电话不能超过 32 个字符')
|
|
||||||
if (email && !EMAIL_PATTERN.test(email)) errors.push('请输入有效的邮箱地址')
|
if (email && !EMAIL_PATTERN.test(email)) errors.push('请输入有效的邮箱地址')
|
||||||
|
|
||||||
return errors
|
return errors
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function validateLoginIdentifierChange(payload: LoginIdentifierChangePayload): string[] {
|
||||||
|
const errors: string[] = []
|
||||||
|
if (!USERNAME_PATTERN.test(payload.username.trim())) {
|
||||||
|
errors.push('用户名须以字母开头,并由 4–64 位字母、数字或 _.@- 组成')
|
||||||
|
}
|
||||||
|
if (!MAINLAND_MOBILE_PATTERN.test(payload.phone.trim())) errors.push('请输入有效的中国大陆手机号')
|
||||||
|
if (!payload.currentPassword) errors.push('请输入当前密码')
|
||||||
|
return errors
|
||||||
|
}
|
||||||
|
|
||||||
export function validatePasswordChange(payload: PasswordChangePayload): string[] {
|
export function validatePasswordChange(payload: PasswordChangePayload): string[] {
|
||||||
const errors: string[] = []
|
const errors: string[] = []
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const routerSource = fs.readFileSync(new URL('../routes.ts', import.meta.url), '
|
|||||||
const viewSource = fs.readFileSync(new URL('./AccountProfileView.vue', import.meta.url), 'utf8')
|
const viewSource = fs.readFileSync(new URL('./AccountProfileView.vue', import.meta.url), 'utf8')
|
||||||
const authSource = fs.readFileSync(new URL('../../auth/store/auth.ts', import.meta.url), 'utf8')
|
const authSource = fs.readFileSync(new URL('../../auth/store/auth.ts', import.meta.url), 'utf8')
|
||||||
const authApiSource = fs.readFileSync(new URL('../../auth/api/auth.ts', import.meta.url), 'utf8')
|
const authApiSource = fs.readFileSync(new URL('../../auth/api/auth.ts', import.meta.url), 'utf8')
|
||||||
|
const iamApiSource = fs.readFileSync(new URL('../../tenant-management/api/merchantIam.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
test('registers the account profile route and navigation entry', () => {
|
test('registers the account profile route and navigation entry', () => {
|
||||||
assert.match(routerSource, /path: 'account\/profile'[\s\S]*?component: \(\) => import\('\.\/views\/AccountProfileView\.vue'\)/)
|
assert.match(routerSource, /path: 'account\/profile'[\s\S]*?component: \(\) => import\('\.\/views\/AccountProfileView\.vue'\)/)
|
||||||
@@ -21,12 +22,29 @@ test('implements profile view, edit, save and cancel states', () => {
|
|||||||
assert.match(viewSource, /function startEditing\(\)/)
|
assert.match(viewSource, /function startEditing\(\)/)
|
||||||
assert.match(viewSource, /function cancelEditing\(\)/)
|
assert.match(viewSource, /function cancelEditing\(\)/)
|
||||||
assert.match(viewSource, /async function saveProfile\(\)/)
|
assert.match(viewSource, /async function saveProfile\(\)/)
|
||||||
assert.match(viewSource, /账号标识暂不支持在客户端修改/)
|
assert.match(viewSource, /请在“登录标识”中修改/)
|
||||||
|
assert.match(viewSource, /<dt>登录手机号<\/dt><dd>\{\{ auth\.profile\.phone/)
|
||||||
|
assert.doesNotMatch(viewSource, /<dt>联系电话<\/dt><dd>\{\{ auth\.profile\.phone/)
|
||||||
assert.match(viewSource, /企业归属由平台审核关系确定/)
|
assert.match(viewSource, /企业归属由平台审核关系确定/)
|
||||||
assert.match(authSource, /async function savePersonalProfile\(/)
|
assert.match(authSource, /async function savePersonalProfile\(/)
|
||||||
assert.match(viewSource, /await auth\.savePersonalProfile/)
|
assert.match(viewSource, /await auth\.savePersonalProfile/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('changes username and mobile with current-password verification then clears every local session', () => {
|
||||||
|
assert.match(viewSource, /name="identifiers"/)
|
||||||
|
assert.match(viewSource, /validateLoginIdentifierChange/)
|
||||||
|
assert.match(viewSource, /await updateMerchantLoginIdentifiers/)
|
||||||
|
assert.match(iamApiSource, /url: '\/merchant\/v1\/iam\/profile\/login-identifiers'/)
|
||||||
|
assert.match(iamApiSource, /data: payload/)
|
||||||
|
assert.match(viewSource, /error\.code === 'A0409'/)
|
||||||
|
assert.match(viewSource, /error\.code === 'A0401'/)
|
||||||
|
assert.match(viewSource, /auth\.clearSession\(\)/)
|
||||||
|
assert.match(viewSource, /reason: 'identifiers-updated'/)
|
||||||
|
assert.match(viewSource, /label="登录手机号" prop="phone"/)
|
||||||
|
assert.match(viewSource, /全部登录会话都会立即退出/)
|
||||||
|
assert.doesNotMatch(viewSource, /auth\.logout\(\)[\s\S]*identifiers-updated/)
|
||||||
|
})
|
||||||
|
|
||||||
test('implements password validation, strength feedback and double-submit protection', () => {
|
test('implements password validation, strength feedback and double-submit protection', () => {
|
||||||
assert.match(viewSource, /async function changePassword\(\)/)
|
assert.match(viewSource, /async function changePassword\(\)/)
|
||||||
assert.match(viewSource, /validatePasswordChange/)
|
assert.match(viewSource, /validatePasswordChange/)
|
||||||
|
|||||||
@@ -13,14 +13,18 @@ import {
|
|||||||
X,
|
X,
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
import { changeCurrentPassword, useAuthStore } from '@/modules/auth/public'
|
import { changeCurrentPassword, useAuthStore } from '@/modules/auth/public'
|
||||||
|
import { ApiError } from '@/api/http'
|
||||||
|
import { updateMerchantLoginIdentifiers } from '@/modules/tenant-management/public'
|
||||||
import {
|
import {
|
||||||
getPasswordStrength,
|
getPasswordStrength,
|
||||||
validateEditableAccountProfile,
|
validateEditableAccountProfile,
|
||||||
|
validateLoginIdentifierChange,
|
||||||
validatePasswordChange,
|
validatePasswordChange,
|
||||||
|
type LoginIdentifierChangePayload,
|
||||||
type PasswordChangePayload,
|
type PasswordChangePayload,
|
||||||
} from '@/modules/account/utils/accountProfile'
|
} from '@/modules/account/utils/accountProfile'
|
||||||
|
|
||||||
type AccountTab = 'profile' | 'password'
|
type AccountTab = 'profile' | 'identifiers' | 'password'
|
||||||
|
|
||||||
interface ProfileForm {
|
interface ProfileForm {
|
||||||
username: string
|
username: string
|
||||||
@@ -35,9 +39,12 @@ const router = useRouter()
|
|||||||
const activeTab = ref<AccountTab>('profile')
|
const activeTab = ref<AccountTab>('profile')
|
||||||
const editing = ref(false)
|
const editing = ref(false)
|
||||||
const profileSaving = ref(false)
|
const profileSaving = ref(false)
|
||||||
|
const identifiersSaving = ref(false)
|
||||||
|
const identifiersError = ref('')
|
||||||
const passwordSaving = ref(false)
|
const passwordSaving = ref(false)
|
||||||
const passwordChangedAt = ref('')
|
const passwordChangedAt = ref('')
|
||||||
const profileFormRef = ref<FormInstance>()
|
const profileFormRef = ref<FormInstance>()
|
||||||
|
const identifiersFormRef = ref<FormInstance>()
|
||||||
const passwordFormRef = ref<FormInstance>()
|
const passwordFormRef = ref<FormInstance>()
|
||||||
|
|
||||||
const profileForm = reactive<ProfileForm>({ ...auth.profile })
|
const profileForm = reactive<ProfileForm>({ ...auth.profile })
|
||||||
@@ -46,20 +53,38 @@ const passwordForm = reactive<PasswordChangePayload>({
|
|||||||
newPassword: '',
|
newPassword: '',
|
||||||
confirmPassword: '',
|
confirmPassword: '',
|
||||||
})
|
})
|
||||||
|
const identifiersForm = reactive<LoginIdentifierChangePayload>({
|
||||||
|
username: auth.profile.username,
|
||||||
|
phone: auth.profile.phone,
|
||||||
|
currentPassword: '',
|
||||||
|
})
|
||||||
|
|
||||||
const profileRules: FormRules<ProfileForm> = {
|
const profileRules: FormRules<ProfileForm> = {
|
||||||
realName: [
|
realName: [
|
||||||
{ required: true, message: '请输入真实姓名', trigger: 'blur' },
|
{ required: true, message: '请输入真实姓名', trigger: 'blur' },
|
||||||
{ min: 1, max: 64, message: '姓名需为 1–64 个字符', trigger: 'blur' },
|
{ min: 1, max: 64, message: '姓名需为 1–64 个字符', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
phone: [
|
|
||||||
{ max: 32, message: '联系电话不能超过 32 个字符', trigger: 'blur' },
|
|
||||||
],
|
|
||||||
email: [
|
email: [
|
||||||
{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
|
{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const identifierRules: FormRules<LoginIdentifierChangePayload> = {
|
||||||
|
username: [{
|
||||||
|
required: true,
|
||||||
|
pattern: /^[A-Za-z][A-Za-z0-9_.@-]{3,63}$/,
|
||||||
|
message: '用户名须以字母开头,并由 4–64 位字母、数字或 _.@- 组成',
|
||||||
|
trigger: 'blur',
|
||||||
|
}],
|
||||||
|
phone: [{
|
||||||
|
required: true,
|
||||||
|
pattern: /^1[3-9]\d{9}$/,
|
||||||
|
message: '请输入有效的中国大陆手机号',
|
||||||
|
trigger: 'blur',
|
||||||
|
}],
|
||||||
|
currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
const passwordRules: FormRules<PasswordChangePayload> = {
|
const passwordRules: FormRules<PasswordChangePayload> = {
|
||||||
currentPassword: [{
|
currentPassword: [{
|
||||||
required: true,
|
required: true,
|
||||||
@@ -129,7 +154,6 @@ async function saveProfile() {
|
|||||||
try {
|
try {
|
||||||
await auth.savePersonalProfile({
|
await auth.savePersonalProfile({
|
||||||
realName: profileForm.realName.trim(),
|
realName: profileForm.realName.trim(),
|
||||||
phone: profileForm.phone.trim(),
|
|
||||||
email: profileForm.email.trim(),
|
email: profileForm.email.trim(),
|
||||||
})
|
})
|
||||||
syncProfileForm()
|
syncProfileForm()
|
||||||
@@ -142,6 +166,42 @@ async function saveProfile() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resetIdentifiersForm() {
|
||||||
|
Object.assign(identifiersForm, {
|
||||||
|
username: auth.profile.username,
|
||||||
|
phone: auth.profile.phone,
|
||||||
|
currentPassword: '',
|
||||||
|
})
|
||||||
|
identifiersError.value = ''
|
||||||
|
identifiersFormRef.value?.clearValidate()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function changeLoginIdentifiers() {
|
||||||
|
if (identifiersSaving.value) return
|
||||||
|
identifiersError.value = ''
|
||||||
|
const valid = await identifiersFormRef.value?.validate().catch(() => false)
|
||||||
|
if (!valid || validateLoginIdentifierChange(identifiersForm).length > 0) return
|
||||||
|
identifiersSaving.value = true
|
||||||
|
const username = identifiersForm.username.trim()
|
||||||
|
try {
|
||||||
|
await updateMerchantLoginIdentifiers({
|
||||||
|
username,
|
||||||
|
phone: identifiersForm.phone.trim(),
|
||||||
|
currentPassword: identifiersForm.currentPassword,
|
||||||
|
})
|
||||||
|
auth.clearSession()
|
||||||
|
await router.replace({ path: '/login', query: { account: username, reason: 'identifiers-updated' } })
|
||||||
|
} catch (error) {
|
||||||
|
identifiersForm.currentPassword = ''
|
||||||
|
if (error instanceof ApiError && error.code === 'A0409') identifiersError.value = '用户名或登录手机号已被使用,请更换后重试'
|
||||||
|
else if (error instanceof ApiError && error.code === 'A0401') identifiersError.value = '当前密码错误'
|
||||||
|
else if (error instanceof ApiError && error.code === 'A0403') identifiersError.value = '当前会话不允许修改登录标识,请退出代登录后重试'
|
||||||
|
else identifiersError.value = error instanceof Error ? error.message : '登录标识修改失败,请重试'
|
||||||
|
} finally {
|
||||||
|
identifiersSaving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function resetPasswordForm() {
|
function resetPasswordForm() {
|
||||||
passwordForm.currentPassword = ''
|
passwordForm.currentPassword = ''
|
||||||
passwordForm.newPassword = ''
|
passwordForm.newPassword = ''
|
||||||
@@ -190,12 +250,9 @@ async function changePassword() {
|
|||||||
class="account-form-grid"
|
class="account-form-grid"
|
||||||
@submit.prevent="saveProfile"
|
@submit.prevent="saveProfile"
|
||||||
>
|
>
|
||||||
<el-form-item label="用户名">
|
<el-form-item label="用户名"><el-input v-model="profileForm.username" disabled /><span class="field-help">请在“登录标识”中修改</span></el-form-item>
|
||||||
<el-input v-model="profileForm.username" disabled />
|
|
||||||
<span class="field-help">账号标识暂不支持在客户端修改</span>
|
|
||||||
</el-form-item>
|
|
||||||
<el-form-item label="姓名" prop="realName"><el-input v-model="profileForm.realName" maxlength="64" show-word-limit placeholder="请输入真实姓名" /></el-form-item>
|
<el-form-item label="姓名" prop="realName"><el-input v-model="profileForm.realName" maxlength="64" show-word-limit placeholder="请输入真实姓名" /></el-form-item>
|
||||||
<el-form-item label="联系电话" prop="phone"><el-input v-model="profileForm.phone" maxlength="32" inputmode="tel" placeholder="选填" /></el-form-item>
|
<el-form-item label="登录手机号"><el-input v-model="profileForm.phone" disabled /><span class="field-help">请在“登录标识”中修改</span></el-form-item>
|
||||||
<el-form-item label="邮箱" prop="email"><el-input v-model="profileForm.email" maxlength="128" inputmode="email" placeholder="选填" /></el-form-item>
|
<el-form-item label="邮箱" prop="email"><el-input v-model="profileForm.email" maxlength="128" inputmode="email" placeholder="选填" /></el-form-item>
|
||||||
<el-form-item label="所属公司">
|
<el-form-item label="所属公司">
|
||||||
<el-input v-model="profileForm.tenantName" disabled />
|
<el-input v-model="profileForm.tenantName" disabled />
|
||||||
@@ -210,12 +267,26 @@ async function changePassword() {
|
|||||||
<dl v-else class="account-info-grid">
|
<dl v-else class="account-info-grid">
|
||||||
<div><dt>用户名</dt><dd>{{ auth.profile.username }}</dd></div>
|
<div><dt>用户名</dt><dd>{{ auth.profile.username }}</dd></div>
|
||||||
<div><dt>姓名</dt><dd>{{ auth.profile.realName }}</dd></div>
|
<div><dt>姓名</dt><dd>{{ auth.profile.realName }}</dd></div>
|
||||||
<div><dt>联系电话</dt><dd>{{ auth.profile.phone || '未填写' }}</dd></div>
|
<div><dt>登录手机号</dt><dd>{{ auth.profile.phone || '未填写' }}</dd></div>
|
||||||
<div><dt>邮箱</dt><dd>{{ auth.profile.email || '未填写' }}</dd></div>
|
<div><dt>邮箱</dt><dd>{{ auth.profile.email || '未填写' }}</dd></div>
|
||||||
<div><dt>所属公司</dt><dd>{{ auth.profile.tenantName }}</dd></div>
|
<div><dt>所属公司</dt><dd>{{ auth.profile.tenantName }}</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
</el-tab-pane>
|
</el-tab-pane>
|
||||||
|
|
||||||
|
<el-tab-pane name="identifiers">
|
||||||
|
<template #label><span class="account-tab-label"><ShieldCheck :size="16" />登录标识</span></template>
|
||||||
|
<div class="identifier-layout">
|
||||||
|
<el-form ref="identifiersFormRef" :model="identifiersForm" :rules="identifierRules" label-position="top" class="identifier-form" @submit.prevent="changeLoginIdentifiers">
|
||||||
|
<el-alert title="修改成功后,国内与海外的全部登录会话都会立即退出,需要使用新用户名或登录手机号重新登录。" type="warning" :closable="false" show-icon />
|
||||||
|
<el-form-item label="用户名" prop="username"><el-input v-model="identifiersForm.username" maxlength="64" autocomplete="username" placeholder="请输入新用户名" /></el-form-item>
|
||||||
|
<el-form-item label="登录手机号" prop="phone"><el-input v-model="identifiersForm.phone" maxlength="11" inputmode="tel" autocomplete="tel" placeholder="请输入11位中国大陆手机号" /></el-form-item>
|
||||||
|
<el-form-item label="当前密码" prop="currentPassword"><el-input v-model="identifiersForm.currentPassword" type="password" show-password maxlength="72" autocomplete="current-password" placeholder="用于确认是本人操作" /></el-form-item>
|
||||||
|
<el-alert v-if="identifiersError" :title="identifiersError" type="error" :closable="false" show-icon />
|
||||||
|
<div class="identifier-actions"><el-button :disabled="identifiersSaving" @click="resetIdentifiersForm">重置</el-button><el-button type="primary" native-type="submit" :loading="identifiersSaving"><Save :size="16" />保存并重新登录</el-button></div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</el-tab-pane>
|
||||||
|
|
||||||
<el-tab-pane name="password">
|
<el-tab-pane name="password">
|
||||||
<template #label><span class="account-tab-label"><KeyRound :size="16" />修改密码</span></template>
|
<template #label><span class="account-tab-label"><KeyRound :size="16" />修改密码</span></template>
|
||||||
|
|
||||||
@@ -280,6 +351,10 @@ async function changePassword() {
|
|||||||
.account-form-grid :deep(.el-form-item) { align-content: start; margin-bottom: 21px; }
|
.account-form-grid :deep(.el-form-item) { align-content: start; margin-bottom: 21px; }
|
||||||
.account-form-actions { display: flex; grid-column: 1 / -1; justify-content: flex-end; gap: 8px; padding-top: 2px; }
|
.account-form-actions { display: flex; grid-column: 1 / -1; justify-content: flex-end; gap: 8px; padding-top: 2px; }
|
||||||
.field-help { margin-top: 6px; color: var(--muted); font-size: 10px; line-height: 1.5; }
|
.field-help { margin-top: 6px; color: var(--muted); font-size: 10px; line-height: 1.5; }
|
||||||
|
.identifier-layout { max-width: 620px; padding-top: 22px; }
|
||||||
|
.identifier-form { display: grid; gap: 2px; }
|
||||||
|
.identifier-form > :deep(.el-alert) { margin-bottom: 16px; }
|
||||||
|
.identifier-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; padding-top: 18px; border-top: 1px solid var(--border); }
|
||||||
.password-layout { display: grid; grid-template-columns: minmax(0, 440px) minmax(260px, 1fr); align-items: start; max-width: 980px; gap: clamp(32px, 6vw, 72px); padding-top: 22px; }
|
.password-layout { display: grid; grid-template-columns: minmax(0, 440px) minmax(260px, 1fr); align-items: start; max-width: 980px; gap: clamp(32px, 6vw, 72px); padding-top: 22px; }
|
||||||
.password-form { max-width: 440px; }
|
.password-form { max-width: 440px; }
|
||||||
.password-form :deep(.el-form-item) { margin-bottom: 18px; }
|
.password-form :deep(.el-form-item) { margin-bottom: 18px; }
|
||||||
@@ -316,5 +391,6 @@ async function changePassword() {
|
|||||||
.account-info-grid div { min-height: 82px; }
|
.account-info-grid div { min-height: 82px; }
|
||||||
.password-actions { width: 100%; }
|
.password-actions { width: 100%; }
|
||||||
.password-actions .el-button { min-height: 44px; flex: 1; }
|
.password-actions .el-button { min-height: 44px; flex: 1; }
|
||||||
|
.identifier-actions .el-button { min-height: 44px; flex: 1; }
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { apiRequest } from '@/api/http'
|
import { apiRequest, revokeCapturedSession } from '@/api/http'
|
||||||
import type { TokenPair } from '@/api/session'
|
import type { TokenPair } from '@/api/session'
|
||||||
|
|
||||||
export interface RegisterMerchantRequest {
|
export interface RegisterMerchantRequest {
|
||||||
@@ -6,8 +6,8 @@ export interface RegisterMerchantRequest {
|
|||||||
password: string
|
password: string
|
||||||
displayName: string
|
displayName: string
|
||||||
companyName: string
|
companyName: string
|
||||||
legalPerson: string
|
legalPerson?: string
|
||||||
legalPhone: string
|
phone: string
|
||||||
contactEmail?: string
|
contactEmail?: string
|
||||||
countryCode?: string
|
countryCode?: string
|
||||||
address?: string
|
address?: string
|
||||||
@@ -27,16 +27,16 @@ export interface ImpersonationExchangeResult {
|
|||||||
expiresIn: number
|
expiresIn: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loginMerchant(username: string, password: string) {
|
export function loginMerchant(loginId: string, password: string) {
|
||||||
return apiRequest<TokenPair>({ method: 'POST', url: '/auth/login', data: { username, password } })
|
return apiRequest<TokenPair>({ method: 'POST', url: '/auth/login', data: { loginId, password } })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function registerMerchant(payload: RegisterMerchantRequest) {
|
export function registerMerchant(payload: RegisterMerchantRequest) {
|
||||||
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logoutMerchant(refreshToken: string) {
|
export function logoutMerchant(accessToken: string, refreshToken: string) {
|
||||||
return apiRequest<void>({ method: 'POST', url: '/auth/logout', data: { refreshToken } })
|
return revokeCapturedSession(accessToken, refreshToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
||||||
|
|||||||
+114
-105
@@ -2,7 +2,7 @@ import { computed, ref } from 'vue'
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import type { CurrentUser } from '@chongchong/shared'
|
import type { CurrentUser } from '@chongchong/shared'
|
||||||
import { exchangeImpersonationCode, loginMerchant, logoutMerchant } from '@/modules/auth/api/auth'
|
import { exchangeImpersonationCode, loginMerchant, logoutMerchant } from '@/modules/auth/api/auth'
|
||||||
import { ApiError } from '@/api/http'
|
import { ApiError, refreshAuthenticatedSession } from '@/api/http'
|
||||||
import {
|
import {
|
||||||
FRONTEND_TO_MERCHANT_PERMISSION_CODES,
|
FRONTEND_TO_MERCHANT_PERMISSION_CODES,
|
||||||
hasMappedMerchantPermission,
|
hasMappedMerchantPermission,
|
||||||
@@ -11,8 +11,8 @@ import {
|
|||||||
getTenantProfile,
|
getTenantProfile,
|
||||||
updateMerchantPersonalProfile,
|
updateMerchantPersonalProfile,
|
||||||
} from '@/modules/tenant-management/public'
|
} from '@/modules/tenant-management/public'
|
||||||
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTemporaryAccessToken, persistTokenPair } from '@/api/session'
|
import { clearSessionTokens, getAccessToken, getRefreshToken, persistRememberedLoginId, persistTemporaryAccessToken, persistTokenPair } from '@/api/session'
|
||||||
import { decodeMerchantToken, type MerchantJwtPayload } from '@/modules/auth/utils/jwt'
|
import { decodeMerchantToken, MerchantTokenExpiredError, type MerchantJwtPayload } from '@/modules/auth/utils/jwt'
|
||||||
|
|
||||||
export interface ClientAccountProfile {
|
export interface ClientAccountProfile {
|
||||||
username: string
|
username: string
|
||||||
@@ -61,18 +61,34 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
const permissionCodes = ref<string[]>([])
|
const permissionCodes = ref<string[]>([])
|
||||||
const sessionRestored = ref(false)
|
const sessionRestored = ref(false)
|
||||||
|
|
||||||
|
let logoutRequest: { accessToken: string; refreshToken: string; promise: Promise<void> } | undefined
|
||||||
|
let generation = 0
|
||||||
|
let contextRequest: { generation: number; promise: Promise<void> } | undefined
|
||||||
|
let restoreTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
function identity(value: MerchantJwtPayload | null) {
|
||||||
|
return value ? JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type]) : ''
|
||||||
|
}
|
||||||
|
|
||||||
function applyToken(accessToken: string) {
|
function applyToken(accessToken: string) {
|
||||||
const decoded = decodeMerchantToken(accessToken)
|
const decoded = decodeMerchantToken(accessToken)
|
||||||
|
const changedIdentity = identity(decoded) !== identity(payload.value)
|
||||||
|
if (accessToken === token.value && payload.value && !changedIdentity) return
|
||||||
|
generation++
|
||||||
|
if (changedIdentity) {
|
||||||
|
user.value = null
|
||||||
|
profile.value = { ...emptyProfile }
|
||||||
|
permissionCodes.value = mapPermissions()
|
||||||
|
}
|
||||||
payload.value = decoded
|
payload.value = decoded
|
||||||
token.value = accessToken
|
token.value = accessToken
|
||||||
user.value = currentUser(decoded, user.value?.tenantName)
|
user.value = currentUser(decoded, user.value?.tenantName)
|
||||||
profile.value.username = decoded.username
|
profile.value.username = decoded.username
|
||||||
profile.value.realName = decoded.username
|
sessionRestored.value = false
|
||||||
permissionCodes.value = mapPermissions()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearSession() {
|
function resetLocalSession() {
|
||||||
clearSessionTokens()
|
generation++
|
||||||
token.value = ''
|
token.value = ''
|
||||||
payload.value = null
|
payload.value = null
|
||||||
user.value = null
|
user.value = null
|
||||||
@@ -81,124 +97,123 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
sessionRestored.value = true
|
sessionRestored.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearSession() {
|
||||||
|
clearSessionTokens()
|
||||||
|
resetLocalSession()
|
||||||
|
}
|
||||||
|
|
||||||
function applyStoredSession() {
|
function applyStoredSession() {
|
||||||
const storedToken = getAccessToken()
|
const storedToken = getAccessToken()
|
||||||
if (!storedToken) {
|
if (!storedToken) {
|
||||||
token.value = ''
|
resetLocalSession()
|
||||||
payload.value = null
|
|
||||||
user.value = null
|
|
||||||
permissionCodes.value = []
|
|
||||||
profile.value = { ...emptyProfile }
|
|
||||||
sessionRestored.value = true
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
applyToken(storedToken)
|
applyToken(storedToken)
|
||||||
sessionRestored.value = false
|
} catch (error) {
|
||||||
} catch {
|
resetLocalSession()
|
||||||
clearSession()
|
if (error instanceof MerchantTokenExpiredError && getRefreshToken()) sessionRestored.value = false
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.value) {
|
|
||||||
try {
|
|
||||||
applyToken(token.value)
|
|
||||||
} catch {
|
|
||||||
clearSession()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
applyStoredSession()
|
||||||
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
||||||
|
|
||||||
async function loadSessionContext() {
|
|
||||||
if (!payload.value) return
|
|
||||||
const currentPermissionCodes = await getCurrentMerchantPermissionCodes()
|
|
||||||
const currentAccessToken = getAccessToken()
|
|
||||||
if (currentAccessToken && currentAccessToken !== token.value) applyToken(currentAccessToken)
|
|
||||||
permissionCodes.value = mapPermissions(currentPermissionCodes)
|
|
||||||
const [tenant, personalProfile] = await Promise.all([
|
|
||||||
getTenantProfile(),
|
|
||||||
getMerchantPersonalProfile(),
|
|
||||||
])
|
|
||||||
user.value = currentUser(payload.value, tenant.tenantName)
|
|
||||||
profile.value = {
|
|
||||||
...profile.value,
|
|
||||||
realName: personalProfile.displayName || payload.value.username,
|
|
||||||
phone: personalProfile.phone || '',
|
|
||||||
email: personalProfile.email || '',
|
|
||||||
tenantName: tenant.tenantName,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function restoreSession() {
|
async function restoreSession() {
|
||||||
if (sessionRestored.value) return
|
if (sessionRestored.value) return
|
||||||
if (!isAuthenticated.value) {
|
if (contextRequest?.generation === generation) return contextRequest.promise
|
||||||
sessionRestored.value = true
|
let requestGeneration = generation
|
||||||
return
|
let requestAccessToken = getAccessToken()
|
||||||
}
|
const isCurrent = () => requestGeneration === generation && getAccessToken() === requestAccessToken
|
||||||
|
const promise = (async () => {
|
||||||
try {
|
try {
|
||||||
await loadSessionContext()
|
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) {
|
} catch (error) {
|
||||||
|
if (!isCurrent()) return
|
||||||
|
sessionRestored.value = false
|
||||||
if (isExpiredSessionError(error)) {
|
if (isExpiredSessionError(error)) {
|
||||||
clearSession()
|
clearSession()
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
sessionRestored.value = true
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
sessionRestored.value = true
|
})()
|
||||||
|
contextRequest = { generation: requestGeneration, promise }
|
||||||
|
try { await promise } finally {
|
||||||
|
if (contextRequest?.promise === promise) contextRequest = undefined
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function login(username: string, password: string, remember = false) {
|
function synchronizeSession() {
|
||||||
const tokens = await loginMerchant(username, password)
|
// Identity changes and logout revoke local rights immediately. Coalesce pair writes
|
||||||
const decoded = decodeMerchantToken(tokens.accessToken)
|
// before loading the new context; same-identity rotation retains confirmed rights.
|
||||||
persistTokenPair(tokens, remember)
|
applyStoredSession()
|
||||||
token.value = tokens.accessToken
|
if (restoreTimer) clearTimeout(restoreTimer)
|
||||||
payload.value = decoded
|
restoreTimer = setTimeout(() => {
|
||||||
user.value = currentUser(decoded)
|
restoreTimer = undefined
|
||||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
void restoreSession().catch(() => {})
|
||||||
permissionCodes.value = mapPermissions()
|
}, 0)
|
||||||
sessionRestored.value = false
|
|
||||||
try {
|
|
||||||
await loadSessionContext()
|
|
||||||
sessionRestored.value = true
|
|
||||||
} catch (error) {
|
|
||||||
if (isExpiredSessionError(error)) {
|
|
||||||
clearSession()
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
sessionRestored.value = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function login(loginId: string, password: string, remember = false) {
|
||||||
|
const attempt = ++generation
|
||||||
|
const tokens = await loginMerchant(loginId, password)
|
||||||
|
if (attempt !== generation) return
|
||||||
|
decodeMerchantToken(tokens.accessToken)
|
||||||
|
persistTokenPair(tokens)
|
||||||
|
persistRememberedLoginId(loginId, remember)
|
||||||
|
applyToken(tokens.accessToken)
|
||||||
|
await restoreSession()
|
||||||
}
|
}
|
||||||
|
|
||||||
async function acceptImpersonationCode(code: string) {
|
async function acceptImpersonationCode(code: string) {
|
||||||
|
const attempt = ++generation
|
||||||
const exchanged = await exchangeImpersonationCode(code)
|
const exchanged = await exchangeImpersonationCode(code)
|
||||||
const decoded = decodeMerchantToken(exchanged.accessToken)
|
if (attempt !== generation) return
|
||||||
|
decodeMerchantToken(exchanged.accessToken)
|
||||||
persistTemporaryAccessToken(exchanged.accessToken)
|
persistTemporaryAccessToken(exchanged.accessToken)
|
||||||
token.value = exchanged.accessToken
|
applyToken(exchanged.accessToken)
|
||||||
payload.value = decoded
|
await restoreSession()
|
||||||
user.value = currentUser(decoded)
|
|
||||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
|
||||||
permissionCodes.value = mapPermissions()
|
|
||||||
sessionRestored.value = false
|
|
||||||
try {
|
|
||||||
await loadSessionContext()
|
|
||||||
} catch (error) {
|
|
||||||
if (isExpiredSessionError(error)) {
|
|
||||||
clearSession()
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sessionRestored.value = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function logout() {
|
function logout() {
|
||||||
|
const accessToken = getAccessToken()
|
||||||
const refreshToken = getRefreshToken()
|
const refreshToken = getRefreshToken()
|
||||||
try {
|
if (logoutRequest && ((!accessToken && !refreshToken)
|
||||||
if (refreshToken) await logoutMerchant(refreshToken)
|
|| (logoutRequest.accessToken === accessToken && logoutRequest.refreshToken === refreshToken))) return logoutRequest.promise
|
||||||
} finally {
|
const pending = accessToken || refreshToken
|
||||||
|
? logoutMerchant(accessToken, refreshToken)
|
||||||
|
: Promise.resolve()
|
||||||
clearSession()
|
clearSession()
|
||||||
}
|
const request = { accessToken, refreshToken, promise: pending.finally(() => {
|
||||||
|
if (logoutRequest === request) logoutRequest = undefined
|
||||||
|
}) }
|
||||||
|
logoutRequest = request
|
||||||
|
return request.promise
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasPermission(permission?: string) {
|
function hasPermission(permission?: string) {
|
||||||
@@ -210,12 +225,14 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
if (user.value) user.value = { ...user.value, name: next.realName }
|
if (user.value) user.value = { ...user.value, name: next.realName }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'phone' | 'email'>) {
|
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
|
||||||
|
const requestGeneration = generation
|
||||||
|
const requestToken = getAccessToken()
|
||||||
const updated = await updateMerchantPersonalProfile({
|
const updated = await updateMerchantPersonalProfile({
|
||||||
displayName: next.realName.trim(),
|
displayName: next.realName.trim(),
|
||||||
phone: next.phone.trim(),
|
|
||||||
email: next.email.trim(),
|
email: next.email.trim(),
|
||||||
})
|
})
|
||||||
|
if (requestGeneration !== generation || requestToken !== getAccessToken()) return
|
||||||
updateProfile({
|
updateProfile({
|
||||||
realName: updated.displayName,
|
realName: updated.displayName,
|
||||||
phone: updated.phone || '',
|
phone: updated.phone || '',
|
||||||
@@ -224,18 +241,10 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('cc-client-session-expired', clearSession)
|
window.addEventListener('cc-client-session-expired', clearSession)
|
||||||
window.addEventListener('message', (event: MessageEvent<unknown>) => {
|
window.addEventListener('cc-client-session-updated', synchronizeSession)
|
||||||
const configuredAdminOrigin = String(import.meta.env.VITE_ADMIN_WEB_ORIGIN || '').trim()
|
|
||||||
const expectedAdminOrigin = configuredAdminOrigin || window.location.origin
|
|
||||||
const message = event.data as { source?: string; type?: string; code?: string } | null
|
|
||||||
if (event.source !== window.opener || event.origin !== expectedAdminOrigin || message?.source !== 'chongchong-admin' || message.type !== 'impersonation-ticket' || !message.code) return
|
|
||||||
void acceptImpersonationCode(message.code)
|
|
||||||
.then(() => window.location.replace('/'))
|
|
||||||
.catch(() => window.location.replace('/login?impersonation=failed'))
|
|
||||||
})
|
|
||||||
window.addEventListener('storage', (event) => {
|
window.addEventListener('storage', (event) => {
|
||||||
if (event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token') applyStoredSession()
|
if (event.storageArea === localStorage && (event.key === null || event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token')) synchronizeSession()
|
||||||
})
|
})
|
||||||
|
|
||||||
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
|
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])
|
||||||
|
})
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
import { decodeMerchantToken } from './jwt.ts'
|
import { decodeMerchantToken, MerchantTokenExpiredError } from './jwt.ts'
|
||||||
|
|
||||||
function tokenFor(payload) {
|
function tokenFor(payload) {
|
||||||
const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url')
|
const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url')
|
||||||
@@ -29,5 +29,5 @@ test('rejects malformed tokens', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('rejects expired tokens', () => {
|
test('rejects expired tokens', () => {
|
||||||
assert.throws(() => decodeMerchantToken(tokenFor({ ...payload, exp: 1 })), /登录状态已过期/)
|
assert.throws(() => decodeMerchantToken(tokenFor({ ...payload, exp: 1 })), MerchantTokenExpiredError)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,6 +9,13 @@ export interface MerchantJwtPayload {
|
|||||||
exp: number
|
exp: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class MerchantTokenExpiredError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super('登录状态已过期')
|
||||||
|
this.name = 'MerchantTokenExpiredError'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function decodeBase64Url(value: string) {
|
function decodeBase64Url(value: string) {
|
||||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
|
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
|
||||||
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')
|
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')
|
||||||
@@ -27,10 +34,11 @@ export function decodeMerchantToken(token: string): MerchantJwtPayload {
|
|||||||
const payload = value as Partial<MerchantJwtPayload>
|
const payload = value as Partial<MerchantJwtPayload>
|
||||||
if (!payload.user_id || !payload.username || !payload.tenant_id || !payload.membership_id || !payload.exp) throw new Error()
|
if (!payload.user_id || !payload.username || !payload.tenant_id || !payload.membership_id || !payload.exp) throw new Error()
|
||||||
if (payload.app_code !== 'MERCHANT') throw new Error('账号不属于当前应用端')
|
if (payload.app_code !== 'MERCHANT') throw new Error('账号不属于当前应用端')
|
||||||
if (payload.exp * 1000 <= Date.now()) throw new Error('登录状态已过期')
|
if (payload.exp * 1000 <= Date.now()) throw new MerchantTokenExpiredError()
|
||||||
return payload as MerchantJwtPayload
|
return payload as MerchantJwtPayload
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof Error && ['账号不属于当前应用端', '登录状态已过期'].includes(error.message)) throw error
|
if (error instanceof Error && error.message === '账号不属于当前应用端') throw error
|
||||||
|
if (error instanceof MerchantTokenExpiredError) throw error
|
||||||
throw new Error('登录凭证无法解析,请重新登录')
|
throw new Error('登录凭证无法解析,请重新登录')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ const httpSource = readFileSync(new URL('../../../api/http.ts', import.meta.url)
|
|||||||
const sessionSource = readFileSync(new URL('../../../api/session.ts', import.meta.url), 'utf8')
|
const sessionSource = readFileSync(new URL('../../../api/session.ts', import.meta.url), 'utf8')
|
||||||
const authApiSource = readFileSync(new URL('../api/auth.ts', import.meta.url), 'utf8')
|
const authApiSource = readFileSync(new URL('../api/auth.ts', import.meta.url), 'utf8')
|
||||||
const mainSource = readFileSync(new URL('../../../main.ts', import.meta.url), 'utf8')
|
const mainSource = readFileSync(new URL('../../../main.ts', import.meta.url), 'utf8')
|
||||||
|
const appSource = readFileSync(new URL('../../../App.vue', import.meta.url), 'utf8')
|
||||||
|
const routerSource = readFileSync(new URL('../../../router/index.ts', import.meta.url), 'utf8')
|
||||||
const stylesSource = readFileSync(new URL('../../../styles/index.css', import.meta.url), 'utf8')
|
const stylesSource = readFileSync(new URL('../../../styles/index.css', import.meta.url), 'utf8')
|
||||||
|
|
||||||
test('uses one prototype-inspired responsive shell for login and registration', () => {
|
test('uses one prototype-inspired responsive shell for login and registration', () => {
|
||||||
@@ -30,38 +32,59 @@ test('groups the full registration contract without adding out-of-scope sign-in
|
|||||||
assert.doesNotMatch(loginSource + registerSource, /微信登录|企业微信登录|短信验证码|邮箱验证码|lang-switcher/)
|
assert.doesNotMatch(loginSource + registerSource, /微信登录|企业微信登录|短信验证码|邮箱验证码|lang-switcher/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('matches the backend username login contract', () => {
|
test('matches the frozen username-or-mobile login contract', () => {
|
||||||
assert.match(loginSource, /label="用户名"/)
|
assert.match(loginSource, /label="用户名或手机号"/)
|
||||||
assert.match(loginSource, /\^\[A-Za-z0-9_\]/)
|
assert.match(loginSource, /const usernamePattern = \/\^\[A-Za-z\]/)
|
||||||
|
assert.match(loginSource, /const mainlandMobilePattern = \/\^1\[3-9\]\\d\{9\}\$\//)
|
||||||
|
assert.match(authApiSource, /data: \{ loginId, password \}/)
|
||||||
|
assert.doesNotMatch(authApiSource, /data: \{ username, password \}/)
|
||||||
assert.match(loginSource, /typeof route\.query\.account === 'string'/)
|
assert.match(loginSource, /typeof route\.query\.account === 'string'/)
|
||||||
assert.doesNotMatch(loginSource, /developmentHint|demo-tip|merchant_admin|联调账号|本地后端/)
|
assert.doesNotMatch(loginSource, /developmentHint|demo-tip|merchant_admin|联调账号|本地后端/)
|
||||||
assert.match(loginSource, /form\.remember/)
|
assert.match(loginSource, /form\.remember/)
|
||||||
assert.match(loginSource, /忘记密码/)
|
assert.match(loginSource, /忘记密码/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('persists both rotating tokens according to the remember choice', () => {
|
test('persists rotating tokens independently and only remembers the login id by choice', () => {
|
||||||
assert.match(sessionSource, /ACCESS_TOKEN_KEY/)
|
assert.match(sessionSource, /ACCESS_TOKEN_KEY/)
|
||||||
assert.match(sessionSource, /REFRESH_TOKEN_KEY/)
|
assert.match(sessionSource, /REFRESH_TOKEN_KEY/)
|
||||||
assert.match(sessionSource, /remember \? localStorage : sessionStorage/)
|
assert.match(sessionSource, /localStorage\.setItem\(ACCESS_TOKEN_KEY, tokens\.accessToken\)/)
|
||||||
|
assert.match(sessionSource, /localStorage\.setItem\(REFRESH_TOKEN_KEY, tokens\.refreshToken\)/)
|
||||||
|
assert.match(sessionSource, /persistRememberedLoginId/)
|
||||||
|
assert.match(loginSource, /getRememberedLoginId/)
|
||||||
|
assert.match(loginSource, /记住账号/)
|
||||||
assert.match(sessionSource, /clearSessionTokens/)
|
assert.match(sessionSource, /clearSessionTokens/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('implements every backend registration field and real submission', () => {
|
test('implements every backend registration field and real submission', () => {
|
||||||
for (const field of ['username', 'companyName', 'displayName', 'legalPerson', 'legalPhone', 'contactEmail', 'countryCode', 'address', 'password', 'agreement']) {
|
for (const field of ['username', 'companyName', 'displayName', 'legalPerson', 'phone', 'contactEmail', 'countryCode', 'address', 'password', 'agreement']) {
|
||||||
assert.match(registerSource, new RegExp(`prop="${field}"`))
|
assert.match(registerSource, new RegExp(`prop="${field}"`))
|
||||||
}
|
}
|
||||||
|
assert.match(registerSource, /label="登录手机号" prop="phone"/)
|
||||||
|
assert.doesNotMatch(registerSource, /legalPhone/)
|
||||||
|
assert.match(authApiSource, /phone: string/)
|
||||||
|
assert.doesNotMatch(authApiSource, /legalPhone/)
|
||||||
|
assert.match(registerSource, /注册时同时初始化公司联系电话;注册后两者可分别修改,互不联动/)
|
||||||
assert.match(registerSource, /registerMerchant\(/)
|
assert.match(registerSource, /registerMerchant\(/)
|
||||||
assert.match(registerSource, /4–64 位/)
|
assert.match(registerSource, /4–64 位/)
|
||||||
assert.match(registerSource, /8–72 位/)
|
assert.match(registerSource, /8–72 位/)
|
||||||
|
assert.match(registerSource, /label="法定代表人(选填)" prop="legalPerson"/)
|
||||||
|
assert.doesNotMatch(registerSource, /label="法定代表人[^\"]*" prop="legalPerson" required/)
|
||||||
|
assert.doesNotMatch(registerSource, /required: true, message: '请输入法定代表人'/)
|
||||||
|
assert.match(authApiSource, /legalPerson\?: string/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('shows an explicit registration entry directly below the login button', () => {
|
||||||
|
assert.match(loginSource, /<el-button[^>]*class="auth-submit"[\s\S]*?<p class="login-register-entry">还没有企业账号?<RouterLink to="\/register">立即注册<\/RouterLink><\/p>/)
|
||||||
|
assert.match(stylesSource, /\.login-register-entry \{[^}]*text-align: center;/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('shows immediate login after registration and separates company review from account activation', () => {
|
test('shows immediate login after registration and separates company review from account activation', () => {
|
||||||
assert.match(registerSource, /企业账号注册成功/)
|
assert.match(registerSource, /企业账号注册成功/)
|
||||||
assert.match(registerSource, /无需等待注册审核/)
|
assert.match(registerSource, /无需等待注册审核/)
|
||||||
assert.match(registerSource, /提交订单前还需完成企业审核/)
|
assert.match(registerSource, /提交订单前还需完成企业审核/)
|
||||||
assert.match(registerSource, /营业执照和法人身份证/)
|
assert.match(registerSource, /首次登录需上传营业执照/)
|
||||||
assert.match(registerSource, /货代资质证书、银行开户许可证可选填/)
|
assert.match(registerSource, /法人身份证、货代资质证书和银行开户许可证可选填/)
|
||||||
assert.match(registerSource, /其他资质可选填/)
|
assert.match(registerSource, /法人身份证及其他资质可选填/)
|
||||||
assert.match(registerSource, /立即登录/)
|
assert.match(registerSource, /立即登录/)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -79,22 +102,35 @@ test('opens complete service and privacy documents from registration', () => {
|
|||||||
test('uses real auth endpoints and single-flight refresh handling', () => {
|
test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||||
assert.match(authApiSource, /\/auth\/login/)
|
assert.match(authApiSource, /\/auth\/login/)
|
||||||
assert.match(authApiSource, /\/auth\/register/)
|
assert.match(authApiSource, /\/auth\/register/)
|
||||||
assert.match(authApiSource, /\/auth\/logout/)
|
assert.match(authApiSource, /revokeCapturedSession\(accessToken, refreshToken\)/)
|
||||||
|
assert.match(httpSource, /\/auth\/logout/)
|
||||||
assert.match(httpSource, /refreshPromise/)
|
assert.match(httpSource, /refreshPromise/)
|
||||||
assert.match(httpSource, /\/auth\/refresh/)
|
assert.match(httpSource, /\/auth\/refresh/)
|
||||||
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
||||||
|
assert.match(httpSource, /token && !isPublicAuthRequest\(config\.url\)/)
|
||||||
assert.match(httpSource, /request\._retriedAfterRefresh = true/)
|
assert.match(httpSource, /request\._retriedAfterRefresh = true/)
|
||||||
assert.match(httpSource, /return await transport\.request\(request\)/)
|
assert.match(httpSource, /return await transport\.request\(request\)/)
|
||||||
assert.match(httpSource, /envelope\.code !== '200'/)
|
assert.match(httpSource, /envelope\.code !== '200'/)
|
||||||
assert.match(httpSource, /redirectToLoginAfterSessionExpiry/)
|
assert.match(httpSource, /redirectToLoginAfterSessionExpiry/)
|
||||||
|
assert.match(httpSource, /error instanceof CrossTabRefreshTimeoutError/)
|
||||||
|
assert.match(httpSource, /const expiredError = new ApiError\(error\.message, 'A0401', 401\)/)
|
||||||
|
assert.match(httpSource, /error instanceof CrossTabRefreshTimeoutError[\s\S]*window\.dispatchEvent\(new CustomEvent\('cc-client-session-expired'\)\)[\s\S]*redirectToLoginAfterSessionExpiry\(\)/)
|
||||||
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
||||||
assert.match(authStoreSource, /decodeMerchantToken/)
|
assert.match(authStoreSource, /decodeMerchantToken/)
|
||||||
|
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
|
||||||
|
assert.match(authStoreSource, /const refreshedToken = await refreshAuthenticatedSession\(\)/)
|
||||||
|
assert.match(authStoreSource, /applyToken\(refreshedToken\)/)
|
||||||
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('handles impersonation exchange as public authentication and exposes failures', () => {
|
test('handles impersonation exchange as public authentication and exposes failures', () => {
|
||||||
assert.match(httpSource, /publicAuthPaths = \[[^\]]*'\/auth\/impersonations\/exchange'/)
|
assert.match(httpSource, /publicAuthPaths = \[[^\]]*'\/auth\/impersonations\/exchange'/)
|
||||||
assert.match(authStoreSource, /\/login\?impersonation=failed/)
|
assert.match(appSource, /impersonationOrigin/)
|
||||||
|
assert.match(appSource, /await auth\.acceptImpersonationCode\(message\.code\)/)
|
||||||
|
assert.match(appSource, /type: 'impersonation-complete'/)
|
||||||
|
assert.match(appSource, /type: 'impersonation-failed'/)
|
||||||
|
assert.doesNotMatch(authStoreSource, /message\.type !== 'impersonation-ticket'/)
|
||||||
|
assert.match(routerSource, /isImpersonationHandoff[\s\S]*!isImpersonationHandoff/)
|
||||||
assert.match(loginSource, /route\.query\.impersonation === 'failed'/)
|
assert.match(loginSource, /route\.query\.impersonation === 'failed'/)
|
||||||
assert.match(loginSource, /代登录失败或授权已失效,请返回管理后台重新发起/)
|
assert.match(loginSource, /代登录失败或授权已失效,请返回管理后台重新发起/)
|
||||||
})
|
})
|
||||||
@@ -110,10 +146,15 @@ test('shows the backend credential error on login', () => {
|
|||||||
assert.doesNotMatch(loginSource, /登录状态已失效,请重新登录/)
|
assert.doesNotMatch(loginSource, /登录状态已失效,请重新登录/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('shows a forced re-login notice after login identifiers change', () => {
|
||||||
|
assert.match(loginSource, /route\.query\.reason === 'identifiers-updated'/)
|
||||||
|
assert.match(loginSource, /所有会话均已退出,请重新登录/)
|
||||||
|
})
|
||||||
|
|
||||||
test('keeps a valid local session during temporary context and refresh outages', () => {
|
test('keeps a valid local session during temporary context and refresh outages', () => {
|
||||||
assert.match(authStoreSource, /function isExpiredSessionError/)
|
assert.match(authStoreSource, /function isExpiredSessionError/)
|
||||||
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
||||||
assert.match(authStoreSource, /sessionRestored\.value = true\s+return/)
|
assert.match(authStoreSource, /if \(!isCurrent\(\)\) return\s+sessionRestored\.value = false/)
|
||||||
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
||||||
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
|||||||
import { ArrowRight, LockKeyhole, UserRound } from '@lucide/vue'
|
import { ArrowRight, LockKeyhole, UserRound } from '@lucide/vue'
|
||||||
import { useAuthStore } from '@/modules/auth/store/auth'
|
import { useAuthStore } from '@/modules/auth/store/auth'
|
||||||
import AuthShell from '@/modules/auth/components/AuthShell.vue'
|
import AuthShell from '@/modules/auth/components/AuthShell.vue'
|
||||||
|
import { getRememberedLoginId } from '@/api/session'
|
||||||
|
|
||||||
interface LoginForm {
|
interface LoginForm {
|
||||||
account: string
|
account: string
|
||||||
@@ -18,19 +19,32 @@ const auth = useAuthStore()
|
|||||||
const formRef = ref<FormInstance>()
|
const formRef = ref<FormInstance>()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const impersonationFailed = route.query.impersonation === 'failed'
|
const impersonationFailed = route.query.impersonation === 'failed'
|
||||||
|
const loginIdentifiersUpdated = route.query.reason === 'identifiers-updated'
|
||||||
|
const rememberedLoginId = getRememberedLoginId()
|
||||||
const form = reactive<LoginForm>({
|
const form = reactive<LoginForm>({
|
||||||
account: typeof route.query.account === 'string'
|
account: typeof route.query.account === 'string'
|
||||||
? route.query.account
|
? route.query.account
|
||||||
: '',
|
: rememberedLoginId,
|
||||||
password: '',
|
password: '',
|
||||||
remember: false,
|
remember: Boolean(rememberedLoginId),
|
||||||
})
|
})
|
||||||
const accountPattern = /^[A-Za-z0-9_]{4,64}$/
|
const usernamePattern = /^[A-Za-z][A-Za-z0-9_.@-]{3,63}$/
|
||||||
|
const mainlandMobilePattern = /^1[3-9]\d{9}$/
|
||||||
|
|
||||||
|
function validLoginId(value: string) {
|
||||||
|
return usernamePattern.test(value) || mainlandMobilePattern.test(value)
|
||||||
|
}
|
||||||
|
|
||||||
const rules: FormRules<LoginForm> = {
|
const rules: FormRules<LoginForm> = {
|
||||||
account: [
|
account: [
|
||||||
{ required: true, message: '请输入用户名', trigger: 'blur' },
|
{ required: true, message: '请输入用户名或手机号', trigger: 'blur' },
|
||||||
{ pattern: accountPattern, message: '用户名为 4–64 位字母、数字或下划线', trigger: 'blur' },
|
{
|
||||||
|
validator: (_rule, value: string, callback) => {
|
||||||
|
if (!value || validLoginId(value.trim())) callback()
|
||||||
|
else callback(new Error('请输入有效用户名或中国大陆手机号'))
|
||||||
|
},
|
||||||
|
trigger: 'blur',
|
||||||
|
},
|
||||||
],
|
],
|
||||||
password: [
|
password: [
|
||||||
{ required: true, message: '请输入密码', trigger: 'blur' },
|
{ required: true, message: '请输入密码', trigger: 'blur' },
|
||||||
@@ -76,7 +90,7 @@ function showResetHint() {
|
|||||||
<div class="auth-form-content auth-form-content--login">
|
<div class="auth-form-content auth-form-content--login">
|
||||||
<div class="auth-form-heading">
|
<div class="auth-form-heading">
|
||||||
<h2 id="login-title">登录客户工作台</h2>
|
<h2 id="login-title">登录客户工作台</h2>
|
||||||
<p>使用企业账号登录,继续管理您的跨境物流业务。</p>
|
<p>使用用户名或中国大陆手机号登录,继续管理您的跨境物流业务。</p>
|
||||||
</div>
|
</div>
|
||||||
<el-alert
|
<el-alert
|
||||||
v-if="impersonationFailed"
|
v-if="impersonationFailed"
|
||||||
@@ -85,19 +99,27 @@ function showResetHint() {
|
|||||||
:closable="false"
|
:closable="false"
|
||||||
show-icon
|
show-icon
|
||||||
/>
|
/>
|
||||||
|
<el-alert
|
||||||
|
v-if="loginIdentifiersUpdated"
|
||||||
|
title="用户名或手机号已更新,所有会话均已退出,请重新登录"
|
||||||
|
type="success"
|
||||||
|
:closable="false"
|
||||||
|
show-icon
|
||||||
|
/>
|
||||||
<div class="auth-account-note">企业注册成功后即可登录;提交订单前需完成企业资料审核。</div>
|
<div class="auth-account-note">企业注册成功后即可登录;提交订单前需完成企业资料审核。</div>
|
||||||
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" size="large" @submit.prevent="submit">
|
<el-form ref="formRef" :model="form" :rules="rules" label-position="top" size="large" @submit.prevent="submit">
|
||||||
<el-form-item label="用户名" prop="account">
|
<el-form-item label="用户名或手机号" prop="account">
|
||||||
<el-input v-model="form.account" autocomplete="username" maxlength="64" placeholder="请输入用户名" :prefix-icon="UserRound" />
|
<el-input v-model="form.account" autocomplete="username" maxlength="64" placeholder="请输入用户名或中国大陆手机号" :prefix-icon="UserRound" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<el-form-item label="密码" prop="password">
|
<el-form-item label="密码" prop="password">
|
||||||
<el-input v-model="form.password" autocomplete="current-password" maxlength="72" type="password" show-password placeholder="请输入 8–72 位密码" :prefix-icon="LockKeyhole" @keyup.enter="submit" />
|
<el-input v-model="form.password" autocomplete="current-password" maxlength="72" type="password" show-password placeholder="请输入 8–72 位密码" :prefix-icon="LockKeyhole" @keyup.enter="submit" />
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<div class="auth-form-options">
|
<div class="auth-form-options">
|
||||||
<el-checkbox v-model="form.remember">记住我</el-checkbox>
|
<el-checkbox v-model="form.remember">记住账号</el-checkbox>
|
||||||
<button type="button" @click="showResetHint">忘记密码?</button>
|
<button type="button" @click="showResetHint">忘记密码?</button>
|
||||||
</div>
|
</div>
|
||||||
<el-button native-type="submit" class="auth-submit" type="primary" :loading="loading">登录 <ArrowRight :size="17" /></el-button>
|
<el-button native-type="submit" class="auth-submit" type="primary" :loading="loading">登录 <ArrowRight :size="17" /></el-button>
|
||||||
|
<p class="login-register-entry">还没有企业账号?<RouterLink to="/register">立即注册</RouterLink></p>
|
||||||
</el-form>
|
</el-form>
|
||||||
</div>
|
</div>
|
||||||
</AuthShell>
|
</AuthShell>
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ interface RegisterForm {
|
|||||||
companyName: string
|
companyName: string
|
||||||
displayName: string
|
displayName: string
|
||||||
legalPerson: string
|
legalPerson: string
|
||||||
legalPhone: string
|
phone: string
|
||||||
contactEmail: string
|
contactEmail: string
|
||||||
countryCode: string
|
countryCode: string
|
||||||
address: string
|
address: string
|
||||||
@@ -24,12 +24,12 @@ const formRef = ref<FormInstance>()
|
|||||||
const submitting = ref(false)
|
const submitting = ref(false)
|
||||||
const submitted = ref(false)
|
const submitted = ref(false)
|
||||||
const submittedAt = ref('')
|
const submittedAt = ref('')
|
||||||
const form = reactive<RegisterForm>({ username: '', companyName: '', displayName: '', legalPerson: '', legalPhone: '', contactEmail: '', countryCode: 'CN', address: '', password: '', agreement: false })
|
const form = reactive<RegisterForm>({ username: '', companyName: '', displayName: '', legalPerson: '', phone: '', contactEmail: '', countryCode: 'CN', address: '', password: '', agreement: false })
|
||||||
|
|
||||||
const rules: FormRules<RegisterForm> = {
|
const rules: FormRules<RegisterForm> = {
|
||||||
username: [
|
username: [
|
||||||
{ required: true, message: '请输入登录用户名', trigger: 'blur' },
|
{ required: true, message: '请输入登录用户名', trigger: 'blur' },
|
||||||
{ pattern: /^[A-Za-z0-9_]{4,64}$/, message: '用户名为 4–64 位字母、数字或下划线', trigger: 'blur' },
|
{ pattern: /^[A-Za-z][A-Za-z0-9_.@-]{3,63}$/, message: '用户名须以字母开头,并由 4–64 位字母、数字或 _.@- 组成', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
companyName: [
|
companyName: [
|
||||||
{ required: true, message: '请输入企业名称', trigger: 'blur' },
|
{ required: true, message: '请输入企业名称', trigger: 'blur' },
|
||||||
@@ -40,15 +40,14 @@ const rules: FormRules<RegisterForm> = {
|
|||||||
{ max: 64, message: '联系人姓名最多 64 个字符', trigger: 'blur' },
|
{ max: 64, message: '联系人姓名最多 64 个字符', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
legalPerson: [
|
legalPerson: [
|
||||||
{ required: true, message: '请输入法定代表人', trigger: 'blur' },
|
|
||||||
{ max: 64, message: '法定代表人最多 64 个字符', trigger: 'blur' },
|
{ max: 64, message: '法定代表人最多 64 个字符', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
contactEmail: [
|
contactEmail: [
|
||||||
{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
|
{ type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
legalPhone: [
|
phone: [
|
||||||
{ required: true, message: '请输入手机号', trigger: 'blur' },
|
{ required: true, message: '请输入手机号', trigger: 'blur' },
|
||||||
{ pattern: /^1\d{10}$/, message: '请输入有效的 11 位手机号', trigger: 'blur' },
|
{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效的中国大陆手机号', trigger: 'blur' },
|
||||||
],
|
],
|
||||||
password: [
|
password: [
|
||||||
{ required: true, message: '请设置登录密码', trigger: 'blur' },
|
{ required: true, message: '请设置登录密码', trigger: 'blur' },
|
||||||
@@ -68,13 +67,14 @@ async function submit() {
|
|||||||
|
|
||||||
submitting.value = true
|
submitting.value = true
|
||||||
try {
|
try {
|
||||||
|
const legalPerson = form.legalPerson.trim()
|
||||||
await registerMerchant({
|
await registerMerchant({
|
||||||
username: form.username.trim(),
|
username: form.username.trim(),
|
||||||
password: form.password,
|
password: form.password,
|
||||||
displayName: form.displayName.trim(),
|
displayName: form.displayName.trim(),
|
||||||
companyName: form.companyName.trim(),
|
companyName: form.companyName.trim(),
|
||||||
legalPerson: form.legalPerson.trim(),
|
...(legalPerson ? { legalPerson } : {}),
|
||||||
legalPhone: form.legalPhone.trim(),
|
phone: form.phone.trim(),
|
||||||
contactEmail: form.contactEmail.trim() || undefined,
|
contactEmail: form.contactEmail.trim() || undefined,
|
||||||
countryCode: form.countryCode,
|
countryCode: form.countryCode,
|
||||||
address: form.address.trim() || undefined,
|
address: form.address.trim() || undefined,
|
||||||
@@ -113,7 +113,7 @@ async function submit() {
|
|||||||
<section class="register-section" aria-labelledby="account-section-title">
|
<section class="register-section" aria-labelledby="account-section-title">
|
||||||
<h2 id="account-section-title">账号信息</h2>
|
<h2 id="account-section-title">账号信息</h2>
|
||||||
<div class="register-form-grid">
|
<div class="register-form-grid">
|
||||||
<el-form-item label="登录用户名" prop="username" required><el-input v-model="form.username" autocomplete="username" maxlength="64" placeholder="4–64 位字母、数字或下划线" /></el-form-item>
|
<el-form-item label="登录用户名" prop="username" required><el-input v-model="form.username" autocomplete="username" maxlength="64" placeholder="以字母开头,支持数字和 _.@-" /></el-form-item>
|
||||||
<el-form-item label="登录密码" prop="password" required><el-input v-model="form.password" type="password" autocomplete="new-password" maxlength="72" show-password placeholder="请设置 8–72 位密码" /></el-form-item>
|
<el-form-item label="登录密码" prop="password" required><el-input v-model="form.password" type="password" autocomplete="new-password" maxlength="72" show-password placeholder="请设置 8–72 位密码" /></el-form-item>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -122,7 +122,7 @@ async function submit() {
|
|||||||
<h2 id="company-section-title">企业信息</h2>
|
<h2 id="company-section-title">企业信息</h2>
|
||||||
<div class="register-form-grid">
|
<div class="register-form-grid">
|
||||||
<el-form-item label="企业名称" prop="companyName" class="register-form-full" required><el-input v-model="form.companyName" maxlength="100" placeholder="请输入营业执照上的企业名称" /></el-form-item>
|
<el-form-item label="企业名称" prop="companyName" class="register-form-full" required><el-input v-model="form.companyName" maxlength="100" placeholder="请输入营业执照上的企业名称" /></el-form-item>
|
||||||
<el-form-item label="法定代表人" prop="legalPerson" required><el-input v-model="form.legalPerson" maxlength="64" placeholder="请输入营业执照法定代表人" /></el-form-item>
|
<el-form-item label="法定代表人(选填)" prop="legalPerson"><el-input v-model="form.legalPerson" maxlength="64" placeholder="可在企业资料中后续补充" /></el-form-item>
|
||||||
<el-form-item label="国家/地区" prop="countryCode"><el-select v-model="form.countryCode" class="register-select"><el-option label="中国大陆(CN)" value="CN" /></el-select></el-form-item>
|
<el-form-item label="国家/地区" prop="countryCode"><el-select v-model="form.countryCode" class="register-select"><el-option label="中国大陆(CN)" value="CN" /></el-select></el-form-item>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -131,7 +131,7 @@ async function submit() {
|
|||||||
<h2 id="contact-section-title">联系信息</h2>
|
<h2 id="contact-section-title">联系信息</h2>
|
||||||
<div class="register-form-grid">
|
<div class="register-form-grid">
|
||||||
<el-form-item label="联系人" prop="displayName" required><el-input v-model="form.displayName" maxlength="64" placeholder="请输入联系人姓名" /></el-form-item>
|
<el-form-item label="联系人" prop="displayName" required><el-input v-model="form.displayName" maxlength="64" placeholder="请输入联系人姓名" /></el-form-item>
|
||||||
<el-form-item label="法人手机号" prop="legalPhone" required><el-input v-model="form.legalPhone" type="tel" autocomplete="tel" inputmode="numeric" maxlength="11" placeholder="请输入 11 位手机号" :prefix-icon="Phone" /></el-form-item>
|
<el-form-item label="登录手机号" prop="phone" required><el-input v-model="form.phone" type="tel" autocomplete="tel" inputmode="numeric" maxlength="11" placeholder="请输入 11 位手机号" :prefix-icon="Phone" /><span class="register-security-note">注册时同时初始化公司联系电话;注册后两者可分别修改,互不联动。</span></el-form-item>
|
||||||
<el-form-item label="联系邮箱" prop="contactEmail"><el-input v-model="form.contactEmail" type="email" autocomplete="email" maxlength="128" placeholder="选填,用于接收业务通知" :prefix-icon="Mail" /></el-form-item>
|
<el-form-item label="联系邮箱" prop="contactEmail"><el-input v-model="form.contactEmail" type="email" autocomplete="email" maxlength="128" placeholder="选填,用于接收业务通知" :prefix-icon="Mail" /></el-form-item>
|
||||||
<el-form-item label="企业地址" prop="address"><el-input v-model="form.address" maxlength="255" placeholder="选填,最多 255 个字符" /></el-form-item>
|
<el-form-item label="企业地址" prop="address"><el-input v-model="form.address" maxlength="255" placeholder="选填,最多 255 个字符" /></el-form-item>
|
||||||
</div>
|
</div>
|
||||||
@@ -143,7 +143,7 @@ async function submit() {
|
|||||||
<span><RouterLink to="/legal/terms" target="_blank" rel="noopener">《用户服务协议》</RouterLink> 和 <RouterLink to="/legal/privacy" target="_blank" rel="noopener">《隐私政策》</RouterLink></span>
|
<span><RouterLink to="/legal/terms" target="_blank" rel="noopener">《用户服务协议》</RouterLink> 和 <RouterLink to="/legal/privacy" target="_blank" rel="noopener">《隐私政策》</RouterLink></span>
|
||||||
</div>
|
</div>
|
||||||
</el-form-item>
|
</el-form-item>
|
||||||
<p class="register-security-note">注册成功后账号可立即登录;首次登录需上传营业执照和法人身份证,货代资质证书、银行开户许可证可选填。提交平台审核通过后才能提交订单。</p>
|
<p class="register-security-note">注册成功后账号可立即登录;首次登录需上传营业执照,法人身份证、货代资质证书和银行开户许可证可选填。提交平台审核通过后才能提交订单。</p>
|
||||||
<el-button native-type="submit" class="register-submit" type="success" :loading="submitting">注册企业账号</el-button>
|
<el-button native-type="submit" class="register-submit" type="success" :loading="submitting">注册企业账号</el-button>
|
||||||
</el-form>
|
</el-form>
|
||||||
</template>
|
</template>
|
||||||
@@ -153,7 +153,7 @@ async function submit() {
|
|||||||
<h1>企业账号注册成功</h1>
|
<h1>企业账号注册成功</h1>
|
||||||
<p><strong>{{ form.username }}</strong> 现在可以直接登录客户工作台,无需等待注册审核。</p>
|
<p><strong>{{ form.username }}</strong> 现在可以直接登录客户工作台,无需等待注册审核。</p>
|
||||||
<dl><div><dt>企业名称</dt><dd>{{ form.companyName }}</dd></div><div><dt>登录账号</dt><dd>{{ form.username }}</dd></div><div><dt>注册时间</dt><dd>{{ submittedAt }}</dd></div><div><dt>账号状态</dt><dd><el-tag type="success" effect="light">可登录</el-tag></dd></div></dl>
|
<dl><div><dt>企业名称</dt><dd>{{ form.companyName }}</dd></div><div><dt>登录账号</dt><dd>{{ form.username }}</dd></div><div><dt>注册时间</dt><dd>{{ submittedAt }}</dd></div><div><dt>账号状态</dt><dd><el-tag type="success" effect="light">可登录</el-tag></dd></div></dl>
|
||||||
<div class="registration-next-step" role="note"><strong>提交订单前还需完成企业审核</strong><span>登录后请在“企业资料”上传营业执照和法人身份证并提交审核,其他资质可选填。审核期间仍可维护资料、成员和订单草稿。</span></div>
|
<div class="registration-next-step" role="note"><strong>提交订单前还需完成企业审核</strong><span>登录后请在“企业资料”上传营业执照并提交审核;法人身份证及其他资质可选填。审核期间仍可维护资料、成员和订单草稿。</span></div>
|
||||||
<div class="registration-result-actions"><el-button type="primary" @click="router.push({ path: '/login', query: { account: form.username } })">立即登录</el-button></div>
|
<div class="registration-result-actions"><el-button type="primary" @click="router.push({ path: '/login', query: { account: form.username } })">立即登录</el-button></div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { apiRequest } from '@/api/http'
|
||||||
|
|
||||||
|
export interface PageResult<T> {
|
||||||
|
records: T[]
|
||||||
|
page: number
|
||||||
|
size: number
|
||||||
|
total: number
|
||||||
|
pages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CrossBorderBusinessKind = 'trucking' | 'looseboard'
|
||||||
|
|
||||||
|
export interface BusinessOrderQuery {
|
||||||
|
page: number
|
||||||
|
size: number
|
||||||
|
orderNo?: string
|
||||||
|
status?: string
|
||||||
|
routeKeyword?: string
|
||||||
|
transportType?: string
|
||||||
|
transportMode?: string
|
||||||
|
requestedFrom?: string
|
||||||
|
requestedTo?: string
|
||||||
|
createdFrom?: string
|
||||||
|
createdTo?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TransportSummary {
|
||||||
|
fleetArrangement: import('../fleetArrangement').FleetArrangement | null
|
||||||
|
orderNo: string
|
||||||
|
transportType: string
|
||||||
|
transportMode?: 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
|
||||||
|
status: string
|
||||||
|
version: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TransportDetail {
|
||||||
|
summary: TransportSummary
|
||||||
|
originAddress: string | null
|
||||||
|
destinationAddress: string | null
|
||||||
|
remark: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TransportCreate {
|
||||||
|
transportType: string
|
||||||
|
transportMode?: string
|
||||||
|
palletRequired?: string
|
||||||
|
origin: string
|
||||||
|
originAddress?: string
|
||||||
|
destination: string
|
||||||
|
destinationAddress?: string
|
||||||
|
containerType?: string
|
||||||
|
palletCount?: number
|
||||||
|
packageCount: number
|
||||||
|
totalWeightKg: number
|
||||||
|
totalVolumeCbm: number
|
||||||
|
budgetAmount?: number
|
||||||
|
currency?: string
|
||||||
|
contactName?: string
|
||||||
|
contactInfo?: string
|
||||||
|
requestedDate?: string
|
||||||
|
remark?: string
|
||||||
|
idempotencyKey: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TransportUpdate extends Omit<TransportCreate, 'idempotencyKey'> {
|
||||||
|
version: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const endpointByKind: Record<CrossBorderBusinessKind, string> = {
|
||||||
|
trucking: '/merchant/v1/last-leg/us-truck-orders',
|
||||||
|
looseboard: '/merchant/v1/last-leg/local-looseboard-orders',
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePage<T>(data: PageResult<T>): PageResult<T> {
|
||||||
|
return { ...data, page: Number(data.page), size: Number(data.size), total: Number(data.total), pages: Number(data.pages) }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listBusinessOrders<T>(kind: CrossBorderBusinessKind, params: BusinessOrderQuery) {
|
||||||
|
return apiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: string) {
|
||||||
|
return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) {
|
||||||
|
return apiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateTransport(kind: 'trucking' | 'looseboard', orderNo: string, payload: TransportUpdate) {
|
||||||
|
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 })
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
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 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 [
|
||||||
|
['cross-border/procurement', 'merchant:cross-border:procurement:list'],
|
||||||
|
['cross-border/domestic-trucking', 'merchant:cross-border:domestic-trucking:list'],
|
||||||
|
['cross-border/pallet-shipping', 'merchant:cross-border:pallet-shipping:list'],
|
||||||
|
]) {
|
||||||
|
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?release: 'active'[\\s\\S]*?permission: '${permission}'`))
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(view, /PrototypeFeatureView|mock|customerId|tenantId/i)
|
||||||
|
assert.match(procurementView, /merchant:cross-border:procurement:create/)
|
||||||
|
assert.match(view, /merchant:cross-border:domestic-trucking:create/)
|
||||||
|
assert.match(view, /merchant:cross-border:pallet-shipping:create/)
|
||||||
|
assert.match(view, /v-if="canCreate"[^>]*type="primary"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('uses only merchant overseas endpoints and keeps retry idempotency stable', () => {
|
||||||
|
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/)
|
||||||
|
assert.match(view, /const stableSubmitKey = submitKey\.value \|\| idempotencyKey\(\)/)
|
||||||
|
assert.match(view, /submitKey\.value = stableSubmitKey/)
|
||||||
|
assert.match(view, /idempotencyKey: stableSubmitKey/g)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('covers list detail create loading error empty pagination and actions-first contracts', () => {
|
||||||
|
assert.match(view, /mode\.value = 'detail'/)
|
||||||
|
assert.match(view, /mode\.value = 'list'/)
|
||||||
|
assert.match(view, /mode = 'create'/)
|
||||||
|
assert.match(view, /v-loading="loading"/)
|
||||||
|
assert.match(view, /class="business-load-error"/)
|
||||||
|
assert.match(view, /empty-text="暂无订单"/)
|
||||||
|
assert.match(view, /<QueryToolbar[^>]*layout="grid"/)
|
||||||
|
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.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', () => {
|
||||||
|
for (const [path, permission] of [
|
||||||
|
['cross-border/procurement/create', 'merchant:cross-border:procurement:create'],
|
||||||
|
['cross-border/domestic-trucking/create', 'merchant:cross-border:domestic-trucking:create'],
|
||||||
|
['cross-border/pallet-shipping/create', 'merchant:cross-border:pallet-shipping:create'],
|
||||||
|
]) {
|
||||||
|
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?props: \\{ createPage: true \\}[\\s\\S]*?permission: '${permission}'`))
|
||||||
|
}
|
||||||
|
assert.match(view, /props\.createPage \? 'create' : 'list'/)
|
||||||
|
assert.match(view, /if \(props\.createPage\) await router\.push/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('opens all cross-border details on dedicated protected routes', () => {
|
||||||
|
for (const [path, routeName] of [
|
||||||
|
['cross-border/procurement/:orderNo/detail', 'cross-border-procurement-detail'],
|
||||||
|
['cross-border/domestic-trucking/:orderNo/detail', 'cross-border-domestic-trucking-detail'],
|
||||||
|
['cross-border/pallet-shipping/:orderNo/detail', 'cross-border-pallet-shipping-detail'],
|
||||||
|
]) {
|
||||||
|
assert.match(routes, new RegExp(`path: '${path.replaceAll('/', '\\/')}'[\\s\\S]*?name: '${routeName}'`))
|
||||||
|
}
|
||||||
|
assert.match(view, /name: detailRouteName\.value, params: \{ orderNo: row\.orderNo \}/)
|
||||||
|
assert.match(view, /class="business-detail-error"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('preserves the existing transport responsive rules without adding a narrow-screen procurement acceptance gate', () => {
|
||||||
|
assert.match(view, /@media \(max-width: 767px\)/)
|
||||||
|
assert.match(view, /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; \}/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('uses the shared dense order-list and detail visual language', () => {
|
||||||
|
assert.match(view, /class="business-orders client-ui"/)
|
||||||
|
assert.match(view, /\.business-detail-page \{[^}]*border: 1px solid var\(--client-border\);[^}]*border-radius: var\(--client-radius\);/)
|
||||||
|
assert.match(view, /\.detail-grid \{[^}]*grid-template-columns: repeat\(4, minmax\(0, 1fr\)\)/)
|
||||||
|
assert.match(view, /\.detail-grid div \{[^}]*min-height: 34px;[^}]*grid-template-columns: 76px minmax\(0, 1fr\)/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
<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 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 {
|
||||||
|
createTransport,
|
||||||
|
getBusinessOrder,
|
||||||
|
listBusinessOrders,
|
||||||
|
type CrossBorderBusinessKind,
|
||||||
|
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()
|
||||||
|
const router = useRouter()
|
||||||
|
const route = useRoute()
|
||||||
|
const detailOrderNo = computed(() => String(route.params.orderNo || ''))
|
||||||
|
const canCreate = computed(() => auth.hasPermission(({
|
||||||
|
trucking: 'merchant:cross-border:domestic-trucking:create',
|
||||||
|
looseboard: 'merchant:cross-border:pallet-shipping:create',
|
||||||
|
} as Record<CrossBorderBusinessKind, string>)[props.kind]))
|
||||||
|
|
||||||
|
type BusinessRow = TransportSummary
|
||||||
|
type BusinessDetail = TransportDetail
|
||||||
|
type PageMode = 'list' | 'create' | 'detail'
|
||||||
|
|
||||||
|
interface ColumnDefinition { key: string; label: string; width?: number }
|
||||||
|
|
||||||
|
interface BusinessForm {
|
||||||
|
transportMode: string
|
||||||
|
palletRequired: string
|
||||||
|
transportType: string
|
||||||
|
origin: string
|
||||||
|
originAddress: string
|
||||||
|
destination: string
|
||||||
|
destinationAddress: string
|
||||||
|
containerType: string
|
||||||
|
palletCount: number
|
||||||
|
packageCount: number
|
||||||
|
totalWeightKg: number
|
||||||
|
totalVolumeCbm: number
|
||||||
|
budgetAmount?: number
|
||||||
|
currency: string
|
||||||
|
contactName: string
|
||||||
|
contactInfo: string
|
||||||
|
requestedDate: string
|
||||||
|
remark: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const configuration = computed(() => ({
|
||||||
|
trucking: {
|
||||||
|
title: '美国本土卡',
|
||||||
|
description: '查询并管理美国本土卡订单',
|
||||||
|
columns: transportColumns(false),
|
||||||
|
},
|
||||||
|
looseboard: {
|
||||||
|
title: '美本土散板',
|
||||||
|
description: '查询并管理美本土散板订单',
|
||||||
|
columns: transportColumns(true),
|
||||||
|
},
|
||||||
|
})[props.kind])
|
||||||
|
|
||||||
|
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 },
|
||||||
|
{ key: 'origin', label: '起运地', width: 150 },
|
||||||
|
{ key: 'destination', label: '目的地', width: 150 },
|
||||||
|
{ key: 'containerType', label: '柜型', width: 100 },
|
||||||
|
{ key: 'totalWeightKg', label: '总重量(kg)', width: 120 },
|
||||||
|
{ key: 'budgetAmount', label: '预算总价', width: 110 },
|
||||||
|
{ key: 'requestedDate', label: '要求时间', width: 120 },
|
||||||
|
{ key: 'status', label: '状态', width: 130 },
|
||||||
|
{ key: 'fleetArrangement', label: '承运安排', width: 190 },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
const mode = ref<PageMode>(props.detailPage ? 'detail' : props.createPage ? 'create' : 'list')
|
||||||
|
const loading = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
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: '' })
|
||||||
|
const total = ref(0)
|
||||||
|
|
||||||
|
const queryModel = computed<QueryModel>({
|
||||||
|
get: () => ({
|
||||||
|
orderNo: query.orderNo,
|
||||||
|
routeKeyword: query.routeKeyword,
|
||||||
|
status: query.status,
|
||||||
|
}),
|
||||||
|
set: (value) => {
|
||||||
|
query.orderNo = String(value.orderNo || '')
|
||||||
|
query.routeKeyword = String(value.routeKeyword || '')
|
||||||
|
query.status = String(value.status || '')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const queryFields = computed<QueryField[]>(() => [
|
||||||
|
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||||
|
{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: '请输入起运地或目的地' },
|
||||||
|
{
|
||||||
|
key: 'status',
|
||||||
|
label: '状态',
|
||||||
|
type: 'select',
|
||||||
|
placeholder: '全部',
|
||||||
|
options: [
|
||||||
|
{ label: '待审核', value: 'PENDING_REVIEW' },
|
||||||
|
{ label: '已通过', value: 'APPROVED' },
|
||||||
|
{ label: '已拒绝', value: 'REJECTED' },
|
||||||
|
{ label: '待接单', value: 'PENDING_ACCEPTANCE' },
|
||||||
|
...Object.entries(poolOrderStatusLabels).filter(([value]) => !['IN_TRANSIT', 'COMPLETED', 'CANCELLED'].includes(value)).map(([value, label]) => ({ value, label })),
|
||||||
|
{ label: '处理中', value: 'PROCESSING' },
|
||||||
|
{ label: '运输中', value: 'IN_TRANSIT' },
|
||||||
|
{ label: '已完成', value: 'COMPLETED' },
|
||||||
|
{ label: '已取消', value: 'CANCELLED' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
|
const form = reactive<BusinessForm>(emptyForm())
|
||||||
|
const rules: FormRules<BusinessForm> = {
|
||||||
|
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
|
||||||
|
const current = detail.value as TransportDetail
|
||||||
|
return [
|
||||||
|
['运输方式', transportModeLabel(read(summary, 'transportMode'))],
|
||||||
|
['是否打盘', yesNo(read(summary, 'palletRequired'))], ['运输类型', transportTypeLabel(read(summary, 'transportType'))],
|
||||||
|
['起运地', 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],
|
||||||
|
]
|
||||||
|
})
|
||||||
|
|
||||||
|
const tableColumns = computed<DataTableColumn[]>(() => [
|
||||||
|
{ key: 'actions', label: '操作', width: 90, fixed: 'left', slotName: 'actions' },
|
||||||
|
...configuration.value.columns.map((column) => ({
|
||||||
|
...column,
|
||||||
|
prop: column.key,
|
||||||
|
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 {
|
||||||
|
transportMode: 'SHARED_TRUCK', palletRequired: 'NO', transportType: 'PORT_PICKUP', origin: '', originAddress: '',
|
||||||
|
destination: '', destinationAddress: '', containerType: DEFAULT_CONTAINER_TYPE, palletCount: 1, packageCount: 0,
|
||||||
|
totalWeightKg: 0, totalVolumeCbm: 0, currency: 'USD', contactName: '', contactInfo: '', requestedDate: '',
|
||||||
|
remark: '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetForm() { Object.assign(form, emptyForm()); submitKey.value = ''; formRef.value?.clearValidate() }
|
||||||
|
function 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 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 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) {
|
||||||
|
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', 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 === 'transportType') return transportTypeLabel(value)
|
||||||
|
if (key === 'transportMode') return transportModeLabel(value)
|
||||||
|
if (key === 'palletRequired') return yesNo(value)
|
||||||
|
if (key === 'createdAt') return dateTime(value)
|
||||||
|
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)}` }
|
||||||
|
function errorMessage(cause: unknown) { return cause instanceof Error ? cause.message : '请求失败,请稍后重试' }
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
loading.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
const params = {
|
||||||
|
page: query.page, size: query.size, orderNo: query.orderNo || undefined, status: query.status || undefined,
|
||||||
|
routeKeyword: query.routeKeyword || undefined,
|
||||||
|
}
|
||||||
|
const result = await listBusinessOrders<TransportSummary>(props.kind, params)
|
||||||
|
rows.value = result.records
|
||||||
|
total.value = result.total
|
||||||
|
} catch (cause) {
|
||||||
|
error.value = errorMessage(cause)
|
||||||
|
rows.value = []
|
||||||
|
total.value = 0
|
||||||
|
} finally { loading.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetQuery() {
|
||||||
|
const reloadDirectly = query.page === 1
|
||||||
|
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '' })
|
||||||
|
if (reloadDirectly) void load()
|
||||||
|
}
|
||||||
|
|
||||||
|
function searchOrders() {
|
||||||
|
if (query.page !== 1) query.page = 1
|
||||||
|
else void load()
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRowActions(candidate: object): TableAction[] {
|
||||||
|
return [{ key: 'detail', label: '详情', run: () => openDetail(candidate) }]
|
||||||
|
}
|
||||||
|
|
||||||
|
function detailFieldClass(label: unknown) {
|
||||||
|
return ['备注', '起运地址', '目的地址'].includes(String(label)) ? 'is-wide' : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const listRouteName = computed(() => ({
|
||||||
|
trucking: 'cross-border-domestic-trucking',
|
||||||
|
looseboard: 'cross-border-pallet-shipping',
|
||||||
|
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
||||||
|
const detailRouteName = computed(() => ({
|
||||||
|
trucking: 'cross-border-domestic-trucking-detail',
|
||||||
|
looseboard: 'cross-border-pallet-shipping-detail',
|
||||||
|
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
||||||
|
|
||||||
|
function returnToList() {
|
||||||
|
if (props.createPage || props.detailPage) {
|
||||||
|
void router.push({ name: listRouteName.value })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mode.value = 'list'
|
||||||
|
}
|
||||||
|
|
||||||
|
function openDetail(candidate: unknown) {
|
||||||
|
const row = candidate as BusinessRow
|
||||||
|
void router.push({ name: detailRouteName.value, params: { orderNo: row.orderNo } })
|
||||||
|
}
|
||||||
|
async function loadDetail() {
|
||||||
|
if (!detailOrderNo.value) return
|
||||||
|
loading.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
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() {
|
||||||
|
if (!await formRef.value?.validate().catch(() => false)) return
|
||||||
|
submitting.value = true
|
||||||
|
const stableSubmitKey = submitKey.value || idempotencyKey()
|
||||||
|
submitKey.value = stableSubmitKey
|
||||||
|
try {
|
||||||
|
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 })
|
||||||
|
ElMessage.success('订单提交成功')
|
||||||
|
resetForm()
|
||||||
|
if (props.createPage) await router.push({ name: listRouteName.value })
|
||||||
|
else { mode.value = 'list'; await load() }
|
||||||
|
} catch (cause) { ElMessage.error(errorMessage(cause)) }
|
||||||
|
finally { submitting.value = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => [query.page, query.size], () => { if (!props.createPage && mode.value === 'list') void load() })
|
||||||
|
onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.createPage) void load() })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section v-loading="loading" class="business-orders client-ui" :aria-busy="loading">
|
||||||
|
<header v-if="mode === 'create'" class="page-head">
|
||||||
|
<div>
|
||||||
|
<h2>{{ configuration.title }}下单</h2>
|
||||||
|
<p>请填写订单信息,带 * 项为必填项</p>
|
||||||
|
</div>
|
||||||
|
<el-button @click="returnToList">返回列表</el-button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<template v-if="mode === 'list'">
|
||||||
|
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="订单查询条件" :fields="queryFields" :search-on-reset="false" @search="searchOrders" @reset="resetQuery" />
|
||||||
|
<div class="business-table-card">
|
||||||
|
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" :row-actions="getRowActions" row-key="orderNo" empty-text="暂无订单">
|
||||||
|
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="resetForm(); mode = 'create'">新增下单</el-button></template>
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<section v-else-if="mode === 'detail'" class="business-detail-page" aria-label="订单详情">
|
||||||
|
<header class="business-detail-heading">
|
||||||
|
<div class="business-detail-heading-main"><el-button link type="primary" @click="returnToList">← 返回列表</el-button><div><h2>{{ detail?.summary.orderNo || '订单详情' }}</h2><p>{{ configuration.title }}订单</p></div></div>
|
||||||
|
<el-tag :type="statusTone(detail?.summary.status)" effect="light">{{ detailStatus }}</el-tag>
|
||||||
|
</header>
|
||||||
|
<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">
|
||||||
|
<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">
|
||||||
|
<el-form-item v-if="kind === 'looseboard'" label="运输方式"><el-radio-group v-model="form.transportMode"><el-radio-button value="SHARED_TRUCK">拼车</el-radio-button><el-radio-button value="PRIORITY_CONSOLIDATION">优先拼载</el-radio-button></el-radio-group></el-form-item>
|
||||||
|
<el-form-item v-if="kind === 'looseboard'" label="是否打盘"><el-radio-group v-model="form.palletRequired"><el-radio-button value="NO">否</el-radio-button><el-radio-button value="YES">是</el-radio-button></el-radio-group></el-form-item>
|
||||||
|
<el-form-item label="运输类型"><el-select v-model="form.transportType"><el-option label="港口提柜" value="PORT_PICKUP" /><el-option label="仓到仓" value="WAREHOUSE_TO_WAREHOUSE" /><el-option label="仓到门" value="WAREHOUSE_TO_DOOR" /></el-select></el-form-item>
|
||||||
|
<el-form-item label="起运地" prop="origin"><el-input v-model.trim="form.origin" maxlength="255" placeholder="请输入起运地" /></el-form-item>
|
||||||
|
<el-form-item label="起运地址"><el-input v-model.trim="form.originAddress" maxlength="500" placeholder="请输入详细起运地址" /></el-form-item>
|
||||||
|
<el-form-item label="目的地" prop="destination"><el-input v-model.trim="form.destination" maxlength="255" placeholder="请输入目的地" /></el-form-item>
|
||||||
|
<el-form-item label="目的地址"><el-input v-model.trim="form.destinationAddress" maxlength="500" placeholder="请输入详细目的地址" /></el-form-item>
|
||||||
|
<el-form-item label="柜型"><el-select v-model="form.containerType"><el-option v-for="item in CONTAINER_SPECIFICATIONS" :key="item.type" :label="item.type" :value="item.type" /></el-select></el-form-item>
|
||||||
|
<el-form-item v-if="kind === 'trucking'" label="托盘数" prop="palletCount"><el-input-number v-model="form.palletCount" :min="1" placeholder="请输入托盘数" /></el-form-item>
|
||||||
|
<el-form-item label="件数"><el-input-number v-model="form.packageCount" :min="0" placeholder="请输入件数" /></el-form-item>
|
||||||
|
<el-form-item label="总重量(kg)"><el-input-number v-model="form.totalWeightKg" :min="0" :precision="2" placeholder="请输入总重量" /></el-form-item>
|
||||||
|
<el-form-item label="总体积(m³)"><el-input-number v-model="form.totalVolumeCbm" :min="0" :precision="3" placeholder="请输入总体积" /></el-form-item>
|
||||||
|
<el-form-item label="要求时间" :prop="kind === 'trucking' ? 'requestedDate' : undefined"><el-date-picker v-model="form.requestedDate" type="date" value-format="YYYY-MM-DD" /></el-form-item>
|
||||||
|
<el-form-item class="budget-form-item" label="预算金额"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2" placeholder="请输入预算金额" /><el-select v-model="form.currency" class="currency"><el-option label="USD" value="USD" /><el-option label="CNY" value="CNY" /></el-select></el-form-item>
|
||||||
|
<el-form-item label="联系人" prop="contactName"><el-input v-model.trim="form.contactName" maxlength="128" placeholder="请输入联系人" /></el-form-item>
|
||||||
|
<el-form-item label="联系方式" prop="contactInfo"><el-input v-model.trim="form.contactInfo" maxlength="128" placeholder="请输入电话、微信或邮箱" /></el-form-item>
|
||||||
|
<el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请输入其他要求" /></el-form-item>
|
||||||
|
<el-form-item><el-button @click="returnToList">取消</el-button><el-button v-if="canCreate" type="primary" :loading="submitting" @click="submit">提交订单</el-button></el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.business-orders { display: grid; gap: var(--client-section-gap); }
|
||||||
|
.page-head { display: flex; align-items: center; justify-content: space-between; gap: 24px; }
|
||||||
|
.page-head h2 { margin: 0; color: #111827; font-size: 26px; }
|
||||||
|
.page-head 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; }
|
||||||
|
.business-order-link { max-width: 100%; overflow: hidden; padding: 0; border: 0; background: transparent; color: var(--client-action); cursor: pointer; font: inherit; font-weight: 650; text-align: left; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.business-order-link:hover { text-decoration: underline; text-underline-offset: 3px; }
|
||||||
|
.business-load-error { display: flex; min-height: 84px; align-items: center; justify-content: center; gap: 12px; padding: 14px; color: #b42318; }
|
||||||
|
.business-detail-error { display: flex; min-height: 180px; align-items: center; justify-content: center; gap: 12px; color: #b42318; }
|
||||||
|
.business-detail-page { min-width: 0; padding: 10px 14px 20px; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
|
||||||
|
.business-detail-heading { display: flex; min-height: 50px; align-items: center; justify-content: space-between; gap: 16px; padding: 5px 0; border-bottom: 1px solid var(--border); }
|
||||||
|
.business-detail-heading-main { display: flex; min-width: 0; align-items: center; gap: 12px; }
|
||||||
|
.business-detail-heading-main > div { min-width: 0; }
|
||||||
|
.business-detail-heading h2 { margin: 0; overflow: hidden; color: var(--navy); font-size: 18px; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.business-detail-heading p { margin: 3px 0 0; color: var(--muted); font-size: 11px; }
|
||||||
|
.business-detail-section { margin-top: 10px; }
|
||||||
|
.business-detail-section h3 { margin: 0; padding: 0 0 5px; border-bottom: 1px solid #eaf0f7; color: var(--navy); font-size: 13px; }
|
||||||
|
.detail-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin: 0; border-top: 1px solid var(--border); border-left: 1px solid var(--border); }
|
||||||
|
.detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 76px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||||
|
.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; }
|
||||||
|
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
.business-orders { gap: 14px; }
|
||||||
|
.page-head { align-items: flex-start; gap: 12px; }
|
||||||
|
.page-head h2 { font-size: 24px; }
|
||||||
|
.page-head > div { min-width: 0; }
|
||||||
|
|
||||||
|
.detail-grid { grid-template-columns: 1fr; }
|
||||||
|
.detail-grid div, .detail-grid div.is-wide { grid-column: auto; }
|
||||||
|
.detail-grid dd { overflow-wrap: break-word; word-break: normal; }
|
||||||
|
.business-detail-heading { align-items: flex-start; flex-direction: column; }
|
||||||
|
|
||||||
|
.form-card :deep(.el-form-item) { display: block; }
|
||||||
|
.form-card :deep(.el-form-item__label) {
|
||||||
|
width: auto !important;
|
||||||
|
height: auto;
|
||||||
|
margin-bottom: 7px;
|
||||||
|
line-height: 1.4;
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
.form-card :deep(.el-form-item__content) { width: 100%; margin-left: 0 !important; }
|
||||||
|
.form-card :deep(.el-input-number) { width: 100%; }
|
||||||
|
.form-card .budget-form-item :deep(.el-form-item__content) { display: flex; flex-wrap: nowrap; }
|
||||||
|
.form-card .budget-form-item :deep(.el-input-number) { width: auto; min-width: 0; flex: 1 1 auto; }
|
||||||
|
.form-card .currency { width: 96px; flex: 0 0 96px; margin-left: 8px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -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>
|
||||||
|
<p class="procurement-note">这里显示已实际交给承运方的记录;国内寄客户后,本单履约完成。</p>
|
||||||
|
</section>
|
||||||
|
<section class="procurement-section" aria-label="采购费用与资金结果">
|
||||||
|
<h3>费用与资金结果</h3>
|
||||||
|
<dl class="procurement-grid money-grid">
|
||||||
|
<div><dt>累计成功扣款</dt><dd>{{ money(totals?.paid) }}</dd></div>
|
||||||
|
<div><dt>累计成功退款</dt><dd>{{ money(totals?.refunded) }}</dd></div>
|
||||||
|
<div><dt>净实扣</dt><dd>{{ money(totals?.net) }}</dd></div>
|
||||||
|
<div><dt>预估国际运费占款</dt><dd>{{ money(totals?.estimatedHold) }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
<p class="procurement-note">预算上限仅包含样品货款。预估国际运费只冻结、不直接扣款,最终以实际费用结算;表内保留原费用、追加及退款记录。</p>
|
||||||
|
<el-table :data="detail.fees" border stripe empty-text="尚无已核定费用" row-key="feeNo">
|
||||||
|
<el-table-column prop="feeNo" label="费用编号" min-width="270" />
|
||||||
|
<el-table-column label="费用用途" min-width="145"><template #default="{ row }">{{ feePurposes[row.purpose] || '待核定' }}</template></el-table-column>
|
||||||
|
<el-table-column prop="name" label="费用名称" min-width="145" />
|
||||||
|
<el-table-column label="原币金额" min-width="130"><template #default="{ row }">{{ money(row.originalAmount, row.originalCurrency) }}</template></el-table-column>
|
||||||
|
<el-table-column label="汇率 / 月份" min-width="150"><template #default="{ row }">{{ measurement(row.exchangeRate, 6) }}<br /><small>{{ text(row.exchangeRateMonth) }}</small></template></el-table-column>
|
||||||
|
<el-table-column label="人民币金额" min-width="130"><template #default="{ row }">{{ money(row.amount) }}</template></el-table-column>
|
||||||
|
<el-table-column label="处理结果" min-width="190"><template #default="{ row }"><el-tag :type="feeTone(row as ProcurementFee)" size="small">{{ feeStatus(row as ProcurementFee) }}</el-tag><small v-if="row.purpose !== 'INTERNATIONAL_ESTIMATE' && row.walletStatus === 'SETTLED' && !row.sourceLinked" class="fee-sync">费用结果同步中</small></template></el-table-column>
|
||||||
|
<el-table-column prop="parentFeeNo" label="关联原费用 / 预估" min-width="270"><template #default="{ row }">{{ text(row.parentFeeNo) }}</template></el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<p v-if="hasPending" class="procurement-note">部分资金处理尚未完成,可点击页面“刷新”查看最新结果;如需协助请联系客户服务。</p>
|
||||||
|
</section>
|
||||||
|
<section v-if="detail.exceptionSummaries.length" class="procurement-section" aria-label="客服处理说明">
|
||||||
|
<h3>客服处理说明</h3><ul class="procurement-summaries"><li v-for="(summary, index) in detail.exceptionSummaries" :key="index">{{ summary }}</li></ul>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<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,7 @@
|
|||||||
|
export const CONTAINER_SPECIFICATIONS = [
|
||||||
|
{ type: '40GP', recommendedMinCbm: 56, capacityCbm: 58, maxWeightKg: 19500 },
|
||||||
|
{ type: '40HQ', recommendedMinCbm: 65, capacityCbm: 68, maxWeightKg: 19500 },
|
||||||
|
{ type: '45HQ', recommendedMinCbm: 82, capacityCbm: 86, maxWeightKg: 19500 },
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export const DEFAULT_CONTAINER_TYPE = '40HQ' as const
|
||||||
@@ -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,165 @@
|
|||||||
|
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('request recovery preserves content and identity while malformed recovery cannot create a replacement', () => {
|
||||||
|
const original = presentation.buildProcurementCreate(draft(), 'Company', 'fixed-key')
|
||||||
|
assert.deepEqual(normalized(submission.restoreProcurementSubmission(JSON.stringify(original))), normalized(original))
|
||||||
|
assert.throws(() => submission.restoreProcurementSubmission('{}'))
|
||||||
|
assert.throws(() => submission.restoreProcurementSubmission(JSON.stringify({ ...original, currency: 'EUR' })))
|
||||||
|
assert.equal(submission.definitelyRejected({ code: 'TIMEOUT' }), false)
|
||||||
|
assert.equal(submission.definitelyRejected({ status: 500 }), false)
|
||||||
|
assert.equal(submission.definitelyRejected({ status: 409 }), false)
|
||||||
|
assert.equal(submission.definitelyRejected({ status: 400 }), true)
|
||||||
|
assert.equal(submission.procurementRequestKey({ getRandomValues: target => { target.set([1, 2, 3, 4]); return target } }), 'proc-00000001000000020000000300000004')
|
||||||
|
})
|
||||||
|
|
||||||
|
class ApiError extends Error { constructor(message, code, status) { super(message); this.code = code; this.status = status } }
|
||||||
|
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 retries the exact original body after reload and does not accept changed form data', async () => {
|
||||||
|
const storage = new Map(), calls = []
|
||||||
|
const first = viewHarness({ createPage: true, storage, api: { createProcurement: async payload => { calls.push(normalized(payload)); throw new ApiError('timeout', 'TIMEOUT') } } })
|
||||||
|
try {
|
||||||
|
Object.assign(first.state.form, draft()); await first.state.submit(); assert.equal(calls.length, 1); assert.ok(first.state.pending.value)
|
||||||
|
first.state.form.productName = 'changed'; await first.state.submit(); assert.deepEqual(calls[1], calls[0])
|
||||||
|
} finally { first.dispose() }
|
||||||
|
const recovered = viewHarness({ createPage: true, storage, api: { createProcurement: async payload => { calls.push(normalized(payload)); return { order: { orderNo: 'PO-SAME' } } } } })
|
||||||
|
try {
|
||||||
|
assert.equal(recovered.state.form.productName, 'Test product'); await recovered.state.submit(); assert.deepEqual(calls[2], calls[0])
|
||||||
|
assert.equal(storage.size, 0); assert.equal(recovered.pushes[0].params.orderNo, 'PO-SAME')
|
||||||
|
} finally { recovered.dispose() }
|
||||||
|
})
|
||||||
|
|
||||||
|
test('submission double-click sends once and definitive validation rejection permits correction', async () => {
|
||||||
|
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.pending.value, null); 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('replay rejection cannot discard an earlier unknown creation outcome', async () => {
|
||||||
|
const calls = []; let attempt = 0
|
||||||
|
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => {
|
||||||
|
calls.push(normalized(payload)); attempt++
|
||||||
|
if (attempt === 1) throw new ApiError('timeout', 'TIMEOUT')
|
||||||
|
throw new ApiError('permission revoked', 'A0403')
|
||||||
|
} } })
|
||||||
|
try {
|
||||||
|
Object.assign(harness.state.form, draft()); await harness.state.submit()
|
||||||
|
const saved = [...harness.storage.values()][0]; await harness.state.submit()
|
||||||
|
assert.equal([...harness.storage.values()][0], saved); assert.ok(harness.state.pending.value)
|
||||||
|
assert.deepEqual(calls[1], calls[0])
|
||||||
|
} finally { harness.dispose() }
|
||||||
|
})
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
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 [
|
||||||
|
['purchaseCategory', '采购品类', 128], ['productName', '商品名称', 255], ['receivingAddress', '完整国内收货地址', 1000],
|
||||||
|
['contactName', '最终收件人', 128], ['contactPhone', '联系电话', 64],
|
||||||
|
] as const) {
|
||||||
|
if (!draft[field].trim() || draft[field].trim().length > max) throw new Error(`请填写有效的${label}`)
|
||||||
|
}
|
||||||
|
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,24 @@
|
|||||||
|
import type { ProcurementCreate } from './api/procurement'
|
||||||
|
import { buildProcurementCreate, emptyProcurementDraft } from './procurementPresentation'
|
||||||
|
|
||||||
|
/** Restore the exact request; an unknown result cannot become a new order. */
|
||||||
|
export function restoreProcurementSubmission(raw: string): ProcurementCreate {
|
||||||
|
const saved: unknown = JSON.parse(raw)
|
||||||
|
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) throw new Error('提交记录格式错误')
|
||||||
|
const value = saved as Record<string, unknown>
|
||||||
|
for (const key of ['customerName', 'purchaseCategory', 'productName', 'currency', 'receivingAddress', 'contactName', 'contactPhone', 'idempotencyKey']) if (typeof value[key] !== 'string') throw new Error('提交记录不完整')
|
||||||
|
if (typeof value.purchaseQuantity !== 'number' || typeof value.budgetUnitPrice !== 'number' || !String(value.idempotencyKey).trim() || String(value.idempotencyKey).length > 255) throw new Error('提交记录不完整')
|
||||||
|
for (const key of ['productSpecification', 'productUrl', 'remark']) if (value[key] !== undefined && typeof value[key] !== 'string') throw new Error('提交记录不完整')
|
||||||
|
if (value.currency !== 'CNY' && value.currency !== 'USD') throw new Error('提交记录币种无效')
|
||||||
|
return buildProcurementCreate({ ...emptyProcurementDraft(), purchaseCategory: String(value.purchaseCategory), productName: String(value.productName),
|
||||||
|
productSpecification: String(value.productSpecification || ''), productUrl: String(value.productUrl || ''), purchaseQuantity: String(value.purchaseQuantity),
|
||||||
|
budgetUnitPrice: String(value.budgetUnitPrice), currency: value.currency, receivingAddress: String(value.receivingAddress), contactName: String(value.contactName),
|
||||||
|
contactPhone: String(value.contactPhone), remark: String(value.remark || '') }, String(value.customerName), String(value.idempotencyKey))
|
||||||
|
}
|
||||||
|
export function definitelyRejected(error: { code?: string; status?: number }) {
|
||||||
|
return ['A0400', 'A0401', 'A0403', 'A0422'].includes(error.code || '') || [400, 401, 403, 422].includes(error.status || 0)
|
||||||
|
}
|
||||||
|
export function procurementRequestKey(provider: Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>> = globalThis.crypto) {
|
||||||
|
if (provider.randomUUID) return provider.randomUUID()
|
||||||
|
return `proc-${Array.from(provider.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('')}`
|
||||||
|
}
|
||||||
@@ -5,28 +5,67 @@ export const crossBorderModule = {
|
|||||||
key: 'cross-border',
|
key: 'cross-border',
|
||||||
navigationGroup: { title: '出海下单', icon: PlaneTakeoff },
|
navigationGroup: { title: '出海下单', icon: PlaneTakeoff },
|
||||||
routes: [
|
routes: [
|
||||||
|
{
|
||||||
|
path: 'cross-border/procurement/create',
|
||||||
|
name: 'cross-border-procurement-create',
|
||||||
|
component: () => import('./views/ProcurementView.vue'),
|
||||||
|
props: { createPage: true },
|
||||||
|
release: 'active',
|
||||||
|
meta: { title: '海外采购下单', workspaceTitle: '海外采购 · 新建', description: '填写并提交海外采购订单', permission: 'merchant:cross-border:procurement:create' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'cross-border/procurement/:orderNo/detail', name: 'cross-border-procurement-detail',
|
||||||
|
component: () => import('./views/ProcurementView.vue'), props: { detailPage: true }, release: 'active',
|
||||||
|
meta: { title: '海外采购详情', workspaceTitle: '海外采购 · 详情', description: '查看海外采购订单详情', permission: 'merchant:cross-border:procurement:list', keepAlive: false },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'cross-border/procurement',
|
path: 'cross-border/procurement',
|
||||||
name: 'cross-border-procurement',
|
name: 'cross-border-procurement',
|
||||||
component: () => import('./views/ProcurementView.vue'),
|
component: () => import('./views/ProcurementView.vue'),
|
||||||
release: 'prototype',
|
release: 'active',
|
||||||
meta: { title: '海外采购', description: '管理海外采购订单', permission: 'merchant:cross-border:procurement' },
|
meta: { title: '海外采购', description: '管理海外采购订单', permission: 'merchant:cross-border:procurement:list' },
|
||||||
navigation: { key: 'cross-border-procurement', icon: Package },
|
navigation: { key: 'cross-border-procurement', icon: Package },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'cross-border/domestic-trucking/create',
|
||||||
|
name: 'cross-border-domestic-trucking-create',
|
||||||
|
component: () => import('./views/DomesticTruckingView.vue'),
|
||||||
|
props: { createPage: true },
|
||||||
|
release: 'active',
|
||||||
|
meta: { title: '美国本土卡下单', workspaceTitle: '美国本土卡 · 新建', description: '填写并提交美国本土卡车运输订单', permission: 'merchant:cross-border:domestic-trucking:create' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'cross-border/domestic-trucking/:orderNo/detail', name: 'cross-border-domestic-trucking-detail',
|
||||||
|
component: () => import('./views/DomesticTruckingView.vue'), props: { detailPage: true }, release: 'active',
|
||||||
|
meta: { title: '美国本土卡详情', workspaceTitle: '美国本土卡 · 详情', description: '查看美国本土卡订单详情', permission: 'merchant:cross-border:domestic-trucking:list', keepAlive: false },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'cross-border/domestic-trucking',
|
path: 'cross-border/domestic-trucking',
|
||||||
name: 'cross-border-domestic-trucking',
|
name: 'cross-border-domestic-trucking',
|
||||||
component: () => import('./views/DomesticTruckingView.vue'),
|
component: () => import('./views/DomesticTruckingView.vue'),
|
||||||
release: 'prototype',
|
release: 'active',
|
||||||
meta: { title: '美国本土卡', description: '创建美国本土卡车运输订单', permission: 'merchant:cross-border:domestic-trucking' },
|
meta: { title: '美国本土卡', description: '创建美国本土卡车运输订单', permission: 'merchant:cross-border:domestic-trucking:list' },
|
||||||
navigation: { key: 'cross-border-domestic-trucking', icon: Truck },
|
navigation: { key: 'cross-border-domestic-trucking', icon: Truck },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'cross-border/pallet-shipping/create',
|
||||||
|
name: 'cross-border-pallet-shipping-create',
|
||||||
|
component: () => import('./views/PalletShippingView.vue'),
|
||||||
|
props: { createPage: true },
|
||||||
|
release: 'active',
|
||||||
|
meta: { title: '美本土散板下单', workspaceTitle: '美本土散板 · 新建', description: '填写并提交美国本土散板运输订单', permission: 'merchant:cross-border:pallet-shipping:create' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'cross-border/pallet-shipping/:orderNo/detail', name: 'cross-border-pallet-shipping-detail',
|
||||||
|
component: () => import('./views/PalletShippingView.vue'), props: { detailPage: true }, release: 'active',
|
||||||
|
meta: { title: '美本土散板详情', workspaceTitle: '美本土散板 · 详情', description: '查看美本土散板运输订单详情', permission: 'merchant:cross-border:pallet-shipping:list', keepAlive: false },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'cross-border/pallet-shipping',
|
path: 'cross-border/pallet-shipping',
|
||||||
name: 'cross-border-pallet-shipping',
|
name: 'cross-border-pallet-shipping',
|
||||||
component: () => import('./views/PalletShippingView.vue'),
|
component: () => import('./views/PalletShippingView.vue'),
|
||||||
release: 'prototype',
|
release: 'active',
|
||||||
meta: { title: '美本土散板', description: '创建美国本土散板运输订单', permission: 'merchant:cross-border:pallet-shipping' },
|
meta: { title: '美本土散板', description: '创建美国本土散板运输订单', permission: 'merchant:cross-border:pallet-shipping:list' },
|
||||||
navigation: { key: 'cross-border-pallet-shipping', icon: Ship },
|
navigation: { key: 'cross-border-pallet-shipping', icon: Ship },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import PrototypeFeatureView from '@/components/common/PrototypeFeatureView.vue'
|
import BusinessOrdersView from '../components/BusinessOrdersView.vue'
|
||||||
|
defineProps<{ createPage?: boolean; detailPage?: boolean }>()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template><PrototypeFeatureView title="美国本土卡" description="创建美国本土卡车运输订单" /></template>
|
<template><BusinessOrdersView kind="trucking" :create-page="createPage" :detail-page="detailPage" /></template>
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import PrototypeFeatureView from '@/components/common/PrototypeFeatureView.vue'
|
import BusinessOrdersView from '../components/BusinessOrdersView.vue'
|
||||||
|
defineProps<{ createPage?: boolean; detailPage?: boolean }>()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template><PrototypeFeatureView title="美本土散板" description="创建美国本土散板运输订单" /></template>
|
<template><BusinessOrdersView kind="looseboard" :create-page="createPage" :detail-page="detailPage" /></template>
|
||||||
|
|||||||
@@ -1,5 +1,187 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import PrototypeFeatureView from '@/components/common/PrototypeFeatureView.vue'
|
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 ProcurementCreate, type ProcurementDetail, type ProcurementSummary } from '../api/procurement'
|
||||||
|
import { buildProcurementCreate, dateTime, draftBudgetTotal, emptyProcurementDraft, money, procurementStatuses, statusLabel, statusTone } from '../procurementPresentation'
|
||||||
|
import { definitelyRejected, procurementRequestKey, restoreProcurementSubmission } 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 storageKey = computed(() => identity.value ? `cc-procurement-submit:${encodeURIComponent(identity.value)}` : null)
|
||||||
|
const companyName = computed(() => auth.profile.tenantName || (auth.user?.tenantName && !/^企业租户 \d+$/.test(auth.user.tenantName) ? auth.user.tenantName : ''))
|
||||||
|
const form = reactive(emptyProcurementDraft())
|
||||||
|
const pending = shallowRef<ProcurementCreate | null>(null)
|
||||||
|
const recoveryError = ref(''), 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 populate(payload: ProcurementCreate) {
|
||||||
|
Object.assign(form, { purchaseCategory: payload.purchaseCategory, productName: payload.productName, productSpecification: payload.productSpecification || '', productUrl: payload.productUrl || '',
|
||||||
|
purchaseQuantity: String(payload.purchaseQuantity), budgetUnitPrice: String(payload.budgetUnitPrice), currency: payload.currency, receivingAddress: payload.receivingAddress,
|
||||||
|
contactName: payload.contactName, contactPhone: payload.contactPhone, remark: payload.remark || '' })
|
||||||
|
}
|
||||||
|
function restorePending() {
|
||||||
|
pending.value = null; recoveryError.value = ''; submitError.value = ''; submittedOrder.value = ''; Object.assign(form, emptyProcurementDraft())
|
||||||
|
if (!storageKey.value) return
|
||||||
|
try { const saved = sessionStorage.getItem(storageKey.value); if (saved) { pending.value = Object.freeze(restoreProcurementSubmission(saved)); populate(pending.value) } }
|
||||||
|
catch { recoveryError.value = '上次提交记录暂无法恢复,请先在订单列表或通过客服核对提交结果,避免重复下单。' }
|
||||||
|
}
|
||||||
|
async function submit() {
|
||||||
|
if (submitting.value || !canCreate.value || recoveryError.value || !storageKey.value) return
|
||||||
|
submitError.value = ''; const owner = identity.value, key = storageKey.value; const resuming = Boolean(pending.value)
|
||||||
|
let started = false
|
||||||
|
try {
|
||||||
|
if (!pending.value) {
|
||||||
|
const payload = buildProcurementCreate(form, companyName.value, procurementRequestKey())
|
||||||
|
try { sessionStorage.setItem(key, JSON.stringify(payload)) } catch { throw new Error('浏览器暂无法保留提交信息,请允许会话存储后重试') }
|
||||||
|
pending.value = Object.freeze(payload)
|
||||||
|
}
|
||||||
|
submitting.value = true; started = true
|
||||||
|
const result = await createProcurement(pending.value)
|
||||||
|
sessionStorage.removeItem(key)
|
||||||
|
if (!active || owner !== identity.value) return
|
||||||
|
pending.value = null; 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) return
|
||||||
|
if (!resuming && cause instanceof ApiError && definitelyRejected(cause)) { sessionStorage.removeItem(key); pending.value = null }
|
||||||
|
submitError.value = started && pending.value ? `${message(cause)}。提交结果尚未确认,请再次确认上次提交结果。` : message(cause)
|
||||||
|
} finally { submitting.value = false }
|
||||||
|
}
|
||||||
|
watch(() => [mode.value, orderNo.value, query.page, query.size, identity.value], (values, previous) => {
|
||||||
|
if (values[4] !== previous?.[4]) { rows.value = []; total.value = 0 }
|
||||||
|
++requestSequence; inFlight = ''; loading.value = false; error.value = ''; detail.value = null
|
||||||
|
if (mode.value === 'create') restorePending()
|
||||||
|
else if (mode.value === 'detail') void loadDetail()
|
||||||
|
else void loadList()
|
||||||
|
}, { immediate: true })
|
||||||
|
onBeforeUnmount(() => { active = false; ++requestSequence })
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template><PrototypeFeatureView title="海外采购" description="管理海外采购订单" /></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="restorePending">新建另一单</el-button></template></el-result>
|
||||||
|
<template v-else>
|
||||||
|
<el-alert v-if="recoveryError" :title="recoveryError" type="error" :closable="false" />
|
||||||
|
<el-alert v-else-if="pending" title="已保留本次提交内容。请再次确认上次提交结果,确认前不修改订单信息。" type="warning" :closable="false" />
|
||||||
|
<el-alert v-if="submitError" class="submit-error" :title="submitError" type="error" :closable="false" />
|
||||||
|
<el-form :model="form" label-position="top" :disabled="submitting || Boolean(pending) || Boolean(recoveryError)" @submit.prevent="submit">
|
||||||
|
<h3>商品与预算</h3><div class="procurement-form-grid">
|
||||||
|
<el-form-item label="采购品类" required><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 label="下单企业"><el-input :model-value="companyName" disabled /></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 v-if="canList" :disabled="submitting" @click="returnToList">返回列表</el-button><el-button type="primary" :loading="submitting" :disabled="Boolean(recoveryError) || (!pending && !companyName) || !identity" @click="submit">{{ pending ? '确认上次提交结果' : '提交采购订单' }}</el-button></footer>
|
||||||
|
</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,156 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { loadDashboardOverview } from './overview.ts'
|
||||||
|
|
||||||
|
const dashboardView = readFileSync(new URL('./views/DashboardView.vue', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
const profile = 'company:profile:view'
|
||||||
|
const list = 'order:first-leg:list'
|
||||||
|
const edit = 'order:first-leg:edit'
|
||||||
|
const company = { tenantName: '示例企业', status: 'ACTIVE' }
|
||||||
|
|
||||||
|
function order(overrides = {}) {
|
||||||
|
return {
|
||||||
|
orderId: 101,
|
||||||
|
orderNo: 'ORDER-101',
|
||||||
|
inboundCode: 'INBOUND-101',
|
||||||
|
destinationWarehouseName: '示例目的仓',
|
||||||
|
channelName: '示例渠道',
|
||||||
|
mainStatus: 'WAIT_MEASURE',
|
||||||
|
customerFeeConfirmationRequired: false,
|
||||||
|
createdAt: '2026-09-18T08:00:00Z',
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function draft(overrides = {}) {
|
||||||
|
return { ...order(), status: 'DRAFT', ...overrides }
|
||||||
|
}
|
||||||
|
|
||||||
|
function requests(overrides = {}) {
|
||||||
|
return {
|
||||||
|
company: async () => company,
|
||||||
|
orders: async () => ({ records: [order()] }),
|
||||||
|
drafts: async () => ({ records: [draft()] }),
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('only calls sources allowed by their complete permission requirements', async (t) => {
|
||||||
|
const cases = [
|
||||||
|
{ permissions: [], expected: [] },
|
||||||
|
{ permissions: [profile], expected: ['company'] },
|
||||||
|
{ permissions: [list], expected: ['orders'] },
|
||||||
|
{ permissions: [edit], expected: [] },
|
||||||
|
{ permissions: [list, edit], expected: ['orders', 'drafts'] },
|
||||||
|
{ permissions: [profile, list, edit], expected: ['company', 'orders', 'drafts'] },
|
||||||
|
]
|
||||||
|
for (const { permissions, expected } of cases) {
|
||||||
|
await t.test(permissions.join(',') || 'no permissions', async () => {
|
||||||
|
const calls = []
|
||||||
|
const result = await loadDashboardOverview(permissions, requests({
|
||||||
|
company: async () => { calls.push('company'); return company },
|
||||||
|
orders: async () => { calls.push('orders'); return { records: [order()] } },
|
||||||
|
drafts: async () => { calls.push('drafts'); return { records: [draft()] } },
|
||||||
|
}))
|
||||||
|
assert.deepEqual(calls, expected)
|
||||||
|
assert.equal(result.company, expected.includes('company') ? company : null)
|
||||||
|
assert.equal(result.orders.length, expected.includes('orders') ? 1 : 0)
|
||||||
|
assert.equal(result.drafts.length, expected.includes('drafts') ? 1 : 0)
|
||||||
|
assert.deepEqual(result.errors, {})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('one failed source preserves successful sources and exposes its error', async (t) => {
|
||||||
|
for (const failedSource of ['company', 'orders', 'drafts']) {
|
||||||
|
await t.test(failedSource, async () => {
|
||||||
|
const result = await loadDashboardOverview([profile, list, edit], requests({
|
||||||
|
[failedSource]: async () => { throw new Error(`${failedSource} unavailable`) },
|
||||||
|
}))
|
||||||
|
assert.deepEqual(result.errors, { [failedSource]: `${failedSource} unavailable` })
|
||||||
|
assert.equal(result.company, failedSource === 'company' ? null : company)
|
||||||
|
assert.equal(result.orders.length, failedSource === 'orders' ? 0 : 1)
|
||||||
|
assert.equal(result.drafts.length, failedSource === 'drafts' ? 0 : 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('loads sources concurrently and distinguishes a failed source from an empty result', async () => {
|
||||||
|
const pending = new Map()
|
||||||
|
const operation = loadDashboardOverview([profile, list, edit], requests(Object.fromEntries(
|
||||||
|
['company', 'orders', 'drafts'].map((source) => [source, () => new Promise((resolve, reject) => pending.set(source, { resolve, reject }))]),
|
||||||
|
)))
|
||||||
|
assert.deepEqual([...pending.keys()], ['company', 'orders', 'drafts'])
|
||||||
|
pending.get('company').resolve(company)
|
||||||
|
pending.get('orders').resolve({ records: [] })
|
||||||
|
pending.get('drafts').reject(null)
|
||||||
|
const result = await operation
|
||||||
|
assert.deepEqual(result.orders, [])
|
||||||
|
assert.equal(result.errors.orders, undefined)
|
||||||
|
assert.deepEqual(result.drafts, [])
|
||||||
|
assert.equal(result.errors.drafts, '订单草稿加载失败,请重试')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sorts each source by creation time and includes only actual drafts', async () => {
|
||||||
|
const orders = [
|
||||||
|
order({ orderId: 1, createdAt: '2026-09-16T08:00:00Z' }),
|
||||||
|
order({ orderId: 2, createdAt: '2026-09-18T08:00:00Z', mainStatus: 'COMPLETED', customerFeeConfirmationRequired: true }),
|
||||||
|
]
|
||||||
|
const drafts = [
|
||||||
|
draft({ orderId: 3, createdAt: '2026-09-15T08:00:00Z' }),
|
||||||
|
draft({ orderId: 4, status: 'SUBMITTED', createdAt: '2026-09-19T08:00:00Z' }),
|
||||||
|
draft({ orderId: 5, createdAt: '2026-09-17T08:00:00Z' }),
|
||||||
|
]
|
||||||
|
const result = await loadDashboardOverview([list, edit], requests({
|
||||||
|
orders: async () => ({ records: orders }),
|
||||||
|
drafts: async () => ({ records: drafts }),
|
||||||
|
}))
|
||||||
|
assert.deepEqual(result.orders.map(({ id }) => id), ['2', '1'])
|
||||||
|
assert.deepEqual(result.drafts.map(({ id }) => id), ['5', '3'])
|
||||||
|
assert.equal(result.orders[0].status, 'COMPLETED')
|
||||||
|
assert.equal(result.orders[0].requiresFeeConfirmation, true)
|
||||||
|
assert.ok(result.drafts.every(({ status, requiresFeeConfirmation }) => status === 'DRAFT' && !requiresFeeConfirmation))
|
||||||
|
assert.deepEqual(orders.map(({ orderId }) => orderId), [1, 2])
|
||||||
|
assert.deepEqual(drafts.map(({ orderId }) => orderId), [3, 4, 5])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('keeps absent business numbers null and internal identifiers out of display fields', async () => {
|
||||||
|
const missing = { orderId: 987654, orderNo: null, inboundCode: null, destinationWarehouseName: null, channelName: null }
|
||||||
|
const result = await loadDashboardOverview([list, edit], requests({
|
||||||
|
orders: async () => ({ records: [order(missing)] }),
|
||||||
|
drafts: async () => ({ records: [draft(missing)] }),
|
||||||
|
}))
|
||||||
|
for (const item of [...result.orders, ...result.drafts]) {
|
||||||
|
assert.equal(item.id, '987654')
|
||||||
|
assert.equal(item.orderNo, null)
|
||||||
|
assert.equal(item.inboundCode, null)
|
||||||
|
assert.equal(item.destination, null)
|
||||||
|
assert.equal(item.channel, null)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('matches the updated six-action icon and motion treatment', () => {
|
||||||
|
assert.match(dashboardView, /icon: Forklift/)
|
||||||
|
assert.doesNotMatch(dashboardView, /PanelsTopLeft/)
|
||||||
|
assert.match(dashboardView, /featured: true/)
|
||||||
|
assert.match(dashboardView, /quick-action--featured/)
|
||||||
|
assert.match(dashboardView, /featured-aura 5s ease-in-out infinite/)
|
||||||
|
assert.match(dashboardView, /featured-shine 3\.6s ease-in-out infinite/)
|
||||||
|
assert.match(dashboardView, /\.quick-action:hover \{[^}]*border-color:[^}]*transform: translateY\(-9px\);/)
|
||||||
|
assert.match(dashboardView, /prefers-reduced-motion: reduce/)
|
||||||
|
assert.match(dashboardView, /\.client-dashboard a:focus-visible/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('opens all six dashboard businesses through their dedicated create pages', () => {
|
||||||
|
for (const route of [
|
||||||
|
'/orders/first-leg/create',
|
||||||
|
'/overseas-warehouse/return-relabel/create',
|
||||||
|
'/cross-border/domestic-trucking/create',
|
||||||
|
'/cross-border/pallet-shipping/create',
|
||||||
|
'/cross-border/procurement/create',
|
||||||
|
'/overseas-warehouse/labeling/create',
|
||||||
|
]) assert.match(dashboardView, new RegExp(`route: '${route.replaceAll('/', '\\/')}'`))
|
||||||
|
assert.match(dashboardView, /title: '退货换标'[\s\S]*?permission: 'merchant:overseas-warehouse:return-order:create'/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import type { FirstLegOrderStatus } from '@chongchong/shared'
|
||||||
|
import type { MerchantFirstLegOrderRow, MerchantUnifiedOrderRow } from '@/modules/first-leg/public'
|
||||||
|
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
|
||||||
|
|
||||||
|
export interface DashboardCompany {
|
||||||
|
tenantName: string
|
||||||
|
status: MerchantTenantStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DashboardOrder {
|
||||||
|
id: string
|
||||||
|
orderNo: string | null
|
||||||
|
inboundCode: string | null
|
||||||
|
destination: string | null
|
||||||
|
channel: string | null
|
||||||
|
status: FirstLegOrderStatus
|
||||||
|
createdAt: string
|
||||||
|
requiresFeeConfirmation: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DashboardSource = 'company' | 'orders' | 'drafts'
|
||||||
|
|
||||||
|
export interface DashboardOverview {
|
||||||
|
company: DashboardCompany | null
|
||||||
|
orders: DashboardOrder[]
|
||||||
|
drafts: DashboardOrder[]
|
||||||
|
errors: Partial<Record<DashboardSource, string>>
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DashboardRequests {
|
||||||
|
company: () => Promise<DashboardCompany>
|
||||||
|
orders: () => Promise<{ records: MerchantUnifiedOrderRow[] }>
|
||||||
|
drafts: () => Promise<{ records: MerchantFirstLegOrderRow[] }>
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceErrorMessages: Record<DashboardSource, string> = {
|
||||||
|
company: '企业资料加载失败,请重试',
|
||||||
|
orders: '订单动态加载失败,请重试',
|
||||||
|
drafts: '订单草稿加载失败,请重试',
|
||||||
|
}
|
||||||
|
|
||||||
|
function newestFirst(records: DashboardOrder[]) {
|
||||||
|
return records.sort((left, right) => (Date.parse(right.createdAt) || 0) - (Date.parse(left.createdAt) || 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadDashboardOverview(permissions: readonly string[], requests: DashboardRequests): Promise<DashboardOverview> {
|
||||||
|
const result: DashboardOverview = { company: null, orders: [], drafts: [], errors: {} }
|
||||||
|
const allowed = new Set(permissions)
|
||||||
|
const tasks: Array<{ source: DashboardSource; run: () => Promise<void> }> = []
|
||||||
|
|
||||||
|
if (allowed.has('company:profile:view')) {
|
||||||
|
tasks.push({ source: 'company', run: async () => { result.company = await requests.company() } })
|
||||||
|
}
|
||||||
|
if (allowed.has('order:first-leg:list')) {
|
||||||
|
tasks.push({ source: 'orders', run: async () => {
|
||||||
|
const response = await requests.orders()
|
||||||
|
result.orders = newestFirst(response.records.map((order) => ({
|
||||||
|
id: String(order.orderId),
|
||||||
|
orderNo: order.orderNo ?? null,
|
||||||
|
inboundCode: order.inboundCode ?? null,
|
||||||
|
destination: order.destinationWarehouseName ?? null,
|
||||||
|
channel: order.channelName ?? null,
|
||||||
|
status: order.mainStatus,
|
||||||
|
createdAt: order.createdAt,
|
||||||
|
requiresFeeConfirmation: order.customerFeeConfirmationRequired === true,
|
||||||
|
})))
|
||||||
|
} })
|
||||||
|
if (allowed.has('order:first-leg:edit')) {
|
||||||
|
tasks.push({ source: 'drafts', run: async () => {
|
||||||
|
const response = await requests.drafts()
|
||||||
|
result.drafts = newestFirst(response.records.filter((order) => order.status === 'DRAFT').map((order) => ({
|
||||||
|
id: String(order.orderId),
|
||||||
|
orderNo: order.orderNo ?? null,
|
||||||
|
inboundCode: order.inboundCode ?? null,
|
||||||
|
destination: order.destinationWarehouseName ?? null,
|
||||||
|
channel: order.channelName ?? null,
|
||||||
|
status: 'DRAFT',
|
||||||
|
createdAt: order.createdAt,
|
||||||
|
requiresFeeConfirmation: false,
|
||||||
|
})))
|
||||||
|
} })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const settled = await Promise.allSettled(tasks.map(async (task) => task.run()))
|
||||||
|
settled.forEach((outcome, index) => {
|
||||||
|
if (outcome.status === 'fulfilled') return
|
||||||
|
const source = tasks[index]!.source
|
||||||
|
result.errors[source] = outcome.reason instanceof Error && outcome.reason.message.trim()
|
||||||
|
? outcome.reason.message
|
||||||
|
: sourceErrorMessages[source]
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ export const dashboardModule = {
|
|||||||
name: 'dashboard',
|
name: 'dashboard',
|
||||||
component: () => import('./views/DashboardView.vue'),
|
component: () => import('./views/DashboardView.vue'),
|
||||||
release: 'active',
|
release: 'active',
|
||||||
meta: { title: '业务总览', description: '企业账户与头程业务概览', permission: 'dashboard:view' },
|
meta: { title: '业务总览', description: '企业账户与头程业务概览', permission: 'dashboard:view', workspaceTab: false },
|
||||||
navigation: { key: 'dashboard', icon: Gauge },
|
navigation: { key: 'dashboard', icon: Gauge },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
import assert from 'node:assert/strict'
|
|
||||||
import { readFileSync } from 'node:fs'
|
|
||||||
import test from 'node:test'
|
|
||||||
|
|
||||||
const source = readFileSync(new URL('./DashboardView.vue', import.meta.url), 'utf8')
|
|
||||||
|
|
||||||
test('loads real dashboard data allowed by the current permissions', () => {
|
|
||||||
assert.match(source, /auth\.hasPermission\('company:profile:view'\).*tenant\.loadCompanyContext\(\)/)
|
|
||||||
assert.match(source, /auth\.hasPermission\('company:member:list'\).*tenant\.loadMembers\(\)/)
|
|
||||||
assert.match(source, /auth\.hasPermission\('order:first-leg:list'\).*orders\.load\(\)/)
|
|
||||||
assert.match(source, /onMounted\(\(\) => void loadDashboardData\(\)\)/)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('isolates recoverable dashboard failures without hiding successful sections', () => {
|
|
||||||
assert.match(source, /Promise\.allSettled/)
|
|
||||||
assert.match(source, /Partial<Record<DashboardDataSource, string>>/)
|
|
||||||
assert.match(source, /:aria-busy="loading"/)
|
|
||||||
assert.match(source, /role="alert"/)
|
|
||||||
assert.match(source, /部分业务数据加载失败/)
|
|
||||||
assert.match(source, /ordersUnavailable/)
|
|
||||||
assert.match(source, /companyUnavailable/)
|
|
||||||
assert.match(source, /订单数据暂不可用,请重新加载后查看。/)
|
|
||||||
assert.match(source, /企业资料暂不可用,请重新加载后查看。/)
|
|
||||||
assert.match(source, /@click="loadDashboardData"/)
|
|
||||||
assert.doesNotMatch(source, /<template v-else>\s*<section class="quick-order-band">/)
|
|
||||||
})
|
|
||||||
|
|
||||||
test('matches the prototype business overview while keeping real order routing and data', () => {
|
|
||||||
assert.match(source, /选择业务,快速下单/)
|
|
||||||
assert.match(source, /海外采购/)
|
|
||||||
assert.match(source, /美国本土卡/)
|
|
||||||
assert.match(source, /美本土散板/)
|
|
||||||
assert.match(source, /void router\.push\('\/orders\/first-leg\/create'\)/)
|
|
||||||
assert.match(source, /order\.status === 'DELIVERED'/)
|
|
||||||
assert.match(source, /currentMonthOrderCount/)
|
|
||||||
assert.match(source, /提交订单后,专属客户经理将在 24 小时内与您联系/)
|
|
||||||
})
|
|
||||||
@@ -1,615 +1,104 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { ArrowRight, Forklift, PackageOpen, RefreshCcw, Ship, ShoppingCart, Tags, Truck, Warehouse } from '@lucide/vue'
|
||||||
import { ElMessage } from 'element-plus'
|
|
||||||
import {
|
|
||||||
AlertTriangle,
|
|
||||||
ArrowRight,
|
|
||||||
CircleQuestionMark,
|
|
||||||
Headphones,
|
|
||||||
Lightbulb,
|
|
||||||
PanelsTopLeft,
|
|
||||||
ShoppingCart,
|
|
||||||
Tags,
|
|
||||||
Truck,
|
|
||||||
} from '@lucide/vue'
|
|
||||||
import { useFirstLegOrdersStore } from '@/modules/first-leg/public'
|
|
||||||
import { useTenantAdministrationStore } from '@/modules/tenant-management/public'
|
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import { FirstLegOrdersView } from '@/modules/first-leg/public'
|
||||||
|
|
||||||
const router = useRouter()
|
|
||||||
const orders = useFirstLegOrdersStore()
|
|
||||||
const tenant = useTenantAdministrationStore()
|
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
const loading = ref(false)
|
|
||||||
type DashboardDataSource = 'company' | 'members' | 'orders'
|
|
||||||
const loadErrors = ref<Partial<Record<DashboardDataSource, string>>>({})
|
|
||||||
const dataSourceLabels: Record<DashboardDataSource, string> = {
|
|
||||||
company: '企业资料',
|
|
||||||
members: '企业成员',
|
|
||||||
orders: '头程订单',
|
|
||||||
}
|
|
||||||
|
|
||||||
const companyUnavailable = computed(() => Boolean(loadErrors.value.company))
|
const primaryActions = computed(() => [
|
||||||
const ordersUnavailable = computed(() => Boolean(loadErrors.value.orders))
|
{ title: '头程下单', description: '国内提货 · 海运订舱 · 清关派送', icon: Ship, route: '/orders/first-leg/create', permission: 'order:first-leg:create', tone: 'blue', featured: true },
|
||||||
const loadErrorItems = computed(() =>
|
{ title: '退货换标', description: '退件接收 · 标签更换 · 重新入仓', icon: RefreshCcw, route: '/overseas-warehouse/return-relabel/create', permission: 'merchant:overseas-warehouse:return-order:create', tone: 'purple', featured: false },
|
||||||
(Object.keys(loadErrors.value) as DashboardDataSource[]).map((key) => ({
|
{ title: '美国本土卡', description: '港口提柜 · 仓到仓 · 仓到门', icon: Truck, route: '/cross-border/domestic-trucking/create', permission: 'merchant:cross-border:domestic-trucking:create', tone: 'green', featured: false },
|
||||||
key,
|
{ title: '美本土散板', description: '拼车拼载 · 打盘服务 · 灵活派送', icon: Forklift, route: '/cross-border/pallet-shipping/create', permission: 'merchant:cross-border:pallet-shipping:create', tone: 'cyan', featured: false },
|
||||||
label: dataSourceLabels[key],
|
{ title: '海外采购', description: '采购代购 · 验货质检 · 集中发货', icon: ShoppingCart, route: '/cross-border/procurement/create', permission: 'merchant:cross-border:procurement:create', tone: 'orange', featured: false },
|
||||||
message: loadErrors.value[key] ?? '请求失败',
|
{ title: '贴标申请', description: '产品建档 · 标签上传 · 批量贴标', icon: Tags, route: '/overseas-warehouse/labeling/create', permission: 'merchant:overseas-warehouse:relabel:create', tone: 'rose', featured: false },
|
||||||
})),
|
{ title: '仓储转运', description: '仓储管理 · 货物转运', icon: Warehouse, route: '/overseas-warehouse/storage-transfer', permission: 'merchant:overseas-warehouse:transfer:list', tone: 'teal', featured: false, actionLabel: '开始办理' },
|
||||||
)
|
{ title: '货物废弃', description: '废弃申请 · 处理进度', icon: PackageOpen, route: '/overseas-warehouse/cargo-disposal', permission: 'merchant:overseas-warehouse:discard:list', tone: 'brown', featured: false, actionLabel: '开始办理' },
|
||||||
const canViewOrders = computed(() => auth.hasPermission('order:first-leg:list'))
|
].filter((action) => auth.hasPermission(action.permission)))
|
||||||
const canCreateOrders = computed(() => auth.hasPermission('order:first-leg:create'))
|
|
||||||
const accountName = computed(() => {
|
|
||||||
if (!companyUnavailable.value && tenant.company.companyName) return tenant.company.companyName
|
|
||||||
return auth.user?.tenantName || auth.user?.name || '企业客户'
|
|
||||||
})
|
|
||||||
const accountInitial = computed(() => accountName.value.trim().slice(0, 1).toUpperCase() || 'C')
|
|
||||||
const completedOrderCount = computed(() => orders.orders.filter((order) => order.status === 'DELIVERED').length)
|
|
||||||
const currentMonthOrderCount = computed(() => {
|
|
||||||
const now = new Date()
|
|
||||||
return orders.orders.filter((order) => {
|
|
||||||
const createdAt = new Date(order.createdAt)
|
|
||||||
return !Number.isNaN(createdAt.getTime())
|
|
||||||
&& createdAt.getFullYear() === now.getFullYear()
|
|
||||||
&& createdAt.getMonth() === now.getMonth()
|
|
||||||
}).length
|
|
||||||
})
|
|
||||||
const overviewStats = computed(() => [
|
|
||||||
{ label: '进行中订单', value: dashboardOrderValue(orders.activeCount) },
|
|
||||||
{ label: '已完成订单', value: dashboardOrderValue(completedOrderCount.value) },
|
|
||||||
{ label: '本月下单', value: dashboardOrderValue(currentMonthOrderCount.value) },
|
|
||||||
])
|
|
||||||
const businessCards = [
|
|
||||||
{
|
|
||||||
title: '海外采购',
|
|
||||||
description: '采购代购 · 验货质检 · 集中发货',
|
|
||||||
icon: ShoppingCart,
|
|
||||||
tone: 'blue',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '美国本土卡',
|
|
||||||
description: '港口提柜 · 仓到仓 · 仓到门',
|
|
||||||
icon: Truck,
|
|
||||||
tone: 'green',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
title: '美本土散板',
|
|
||||||
description: '拼车拼载 · 打盘服务 · 灵活派送',
|
|
||||||
icon: PanelsTopLeft,
|
|
||||||
tone: 'teal',
|
|
||||||
},
|
|
||||||
] as const
|
|
||||||
|
|
||||||
function dashboardOrderValue(value: number) {
|
|
||||||
if (!canViewOrders.value || ordersUnavailable.value) return '—'
|
|
||||||
return String(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
function errorMessage(error: unknown) {
|
|
||||||
return error instanceof Error ? error.message : '请求失败,请稍后重试'
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadDashboardData() {
|
|
||||||
loading.value = true
|
|
||||||
loadErrors.value = {}
|
|
||||||
const requests: Array<{ source: DashboardDataSource; request: Promise<unknown> }> = []
|
|
||||||
if (auth.hasPermission('company:profile:view')) requests.push({ source: 'company', request: tenant.loadCompanyContext() })
|
|
||||||
if (auth.hasPermission('company:member:list')) requests.push({ source: 'members', request: tenant.loadMembers() })
|
|
||||||
if (auth.hasPermission('order:first-leg:list')) requests.push({ source: 'orders', request: orders.load() })
|
|
||||||
try {
|
|
||||||
const results = await Promise.allSettled(requests.map(({ request }) => request))
|
|
||||||
const nextErrors: Partial<Record<DashboardDataSource, string>> = {}
|
|
||||||
results.forEach((result, index) => {
|
|
||||||
const request = requests[index]
|
|
||||||
if (request && result.status === 'rejected') nextErrors[request.source] = errorMessage(result.reason)
|
|
||||||
})
|
|
||||||
loadErrors.value = nextErrors
|
|
||||||
} finally {
|
|
||||||
loading.value = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function openBusinessOrder() {
|
|
||||||
if (canCreateOrders.value) {
|
|
||||||
void router.push('/orders/first-leg/create')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (canViewOrders.value) {
|
|
||||||
void router.push('/orders/first-leg')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ElMessage.warning('当前账号暂无头程订单权限,请联系企业管理员。')
|
|
||||||
}
|
|
||||||
|
|
||||||
function showSupportMessage(type: 'service' | 'faq' | 'quote') {
|
|
||||||
const messages = {
|
|
||||||
service: '客服联系方式正在配置中,请联系您的专属客户经理。',
|
|
||||||
faq: '常见问题页面即将上线。',
|
|
||||||
quote: '提交订单后,客户经理将根据货物信息为您提供报价。',
|
|
||||||
}
|
|
||||||
ElMessage.info(messages[type])
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => void loadDashboardData())
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-loading="loading" class="client-dashboard" :aria-busy="loading">
|
<div class="client-dashboard">
|
||||||
<div v-if="loadErrorItems.length" class="dashboard-load-error" role="alert">
|
<header class="business-intro">
|
||||||
<AlertTriangle :size="20" aria-hidden="true" />
|
<h1>选择业务,快速下单</h1>
|
||||||
<div>
|
|
||||||
<strong>部分业务数据加载失败</strong>
|
|
||||||
<ul>
|
|
||||||
<li v-for="item in loadErrorItems" :key="item.key">
|
|
||||||
<span>{{ item.label }}:</span>{{ item.message }}
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
<el-button :loading="loading" @click="loadDashboardData">重新加载</el-button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="dashboard-layout">
|
|
||||||
<main class="dashboard-business" aria-labelledby="dashboard-heading">
|
|
||||||
<header class="dashboard-intro">
|
|
||||||
<h2 id="dashboard-heading">选择业务,快速下单</h2>
|
|
||||||
<p>请选择您需要的业务类型,填写信息后提交订单,我们将尽快为您安排。</p>
|
<p>请选择您需要的业务类型,填写信息后提交订单,我们将尽快为您安排。</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<section class="business-card-grid" aria-label="可选业务">
|
<section class="quick-actions" aria-label="业务选择">
|
||||||
<button
|
<RouterLink v-for="(action, index) in primaryActions" :key="action.route" :to="action.route" class="quick-action" :class="[`quick-action--${action.tone}`, { 'quick-action--featured': action.featured }]" :style="{ '--entry-index': index }">
|
||||||
v-for="business in businessCards"
|
<span class="action-icon"><component :is="action.icon" :size="25" :stroke-width="2.2" aria-hidden="true" /></span>
|
||||||
:key="business.title"
|
<span class="action-copy"><strong>{{ action.title }}</strong><small>{{ action.description }}</small></span>
|
||||||
type="button"
|
<span class="action-enter"><span>{{ action.actionLabel ?? '开始下单' }}</span><ArrowRight :size="15" aria-hidden="true" /></span>
|
||||||
class="business-card"
|
</RouterLink>
|
||||||
:class="`business-card--${business.tone}`"
|
<p v-if="!primaryActions.length" class="no-actions">当前账号暂无常用业务权限,请通过已授权菜单办理业务,或联系企业管理员。</p>
|
||||||
@click="openBusinessOrder"
|
|
||||||
>
|
|
||||||
<span class="business-card__icon" aria-hidden="true">
|
|
||||||
<component :is="business.icon" :size="29" :stroke-width="2.4" />
|
|
||||||
</span>
|
|
||||||
<span class="business-card__copy">
|
|
||||||
<strong>{{ business.title }}</strong>
|
|
||||||
<small>{{ business.description }}</small>
|
|
||||||
</span>
|
|
||||||
<span class="business-card__action">
|
|
||||||
{{ canCreateOrders ? '开始下单' : canViewOrders ? '查看订单' : '暂无权限' }}
|
|
||||||
<ArrowRight :size="18" aria-hidden="true" />
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</section>
|
|
||||||
</main>
|
|
||||||
|
|
||||||
<aside class="dashboard-aside" aria-label="账户与业务信息">
|
|
||||||
<section class="aside-card account-card">
|
|
||||||
<h3>账户信息</h3>
|
|
||||||
<div class="account-summary">
|
|
||||||
<span class="account-avatar">{{ accountInitial }}</span>
|
|
||||||
<span class="account-copy">
|
|
||||||
<strong>{{ accountName }}</strong>
|
|
||||||
<small>企业客户</small>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<p v-if="companyUnavailable" class="account-load-error" role="status">企业资料暂不可用,请重新加载后查看。</p>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="aside-card">
|
<FirstLegOrdersView v-if="auth.hasPermission('order:first-leg:list')" :show-create-action="false" class="dashboard-order-list" />
|
||||||
<h3>数据概览</h3>
|
<section v-else class="orders-permission-empty">
|
||||||
<dl class="overview-stats">
|
<strong>暂无头程订单查看权限</strong>
|
||||||
<div v-for="stat in overviewStats" :key="stat.label">
|
<span>需要查看企业订单时,请联系企业管理员开通。</span>
|
||||||
<dt>{{ stat.label }}</dt>
|
|
||||||
<dd>{{ stat.value }}</dd>
|
|
||||||
</div>
|
|
||||||
</dl>
|
|
||||||
<p v-if="ordersUnavailable" class="dashboard-section-error" role="status">订单数据暂不可用,请重新加载后查看。</p>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="aside-card">
|
|
||||||
<h3>帮助与支持</h3>
|
|
||||||
<div class="support-links">
|
|
||||||
<button type="button" @click="showSupportMessage('service')"><Headphones :size="19" /><span>联系客服</span></button>
|
|
||||||
<button type="button" @click="showSupportMessage('faq')"><CircleQuestionMark :size="19" /><span>常见问题</span></button>
|
|
||||||
<button type="button" @click="showSupportMessage('quote')"><Tags :size="19" /><span>获取报价</span></button>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<div class="dashboard-tip">
|
|
||||||
<Lightbulb :size="19" aria-hidden="true" />
|
|
||||||
<p>提交订单后,专属客户经理将在 24 小时内与您联系,确认运输方案与报价。</p>
|
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.client-dashboard {
|
.client-dashboard { display: flex; min-width: 0; container-name: dashboard-content; container-type: inline-size; flex-direction: column; gap: 14px; padding: 0 8px 18px; color: var(--navy); animation: dashboard-enter .3s ease-out both; }
|
||||||
--dashboard-blue: #1565c0;
|
.business-intro { padding-top: 0; }
|
||||||
--dashboard-green: #3f9f47;
|
.business-intro h1 { margin: 0; color: #172033; font-size: 27px; font-weight: 750; letter-spacing: -.5px; line-height: 1.3; }
|
||||||
--dashboard-teal: #078a99;
|
.business-intro p { margin: 5px 0 0; color: #7a8495; font-size: 13px; line-height: 1.55; }
|
||||||
display: block;
|
.quick-actions { display: grid; grid-template-columns: repeat(8, minmax(150px, 1fr)); gap: 10px; overflow-x: auto; padding: 0 0 6px; scroll-snap-type: x proximity; scrollbar-color: #bdc9dc transparent; scrollbar-width: thin; }
|
||||||
min-height: calc(100vh - 128px);
|
.quick-actions::-webkit-scrollbar { height: 7px; }
|
||||||
}
|
.quick-actions::-webkit-scrollbar-thumb { border-radius: 999px; background: #bdc9dc; }
|
||||||
|
.quick-actions::-webkit-scrollbar-track { background: transparent; }
|
||||||
.dashboard-load-error {
|
.quick-action { scroll-snap-align: start; }
|
||||||
margin-bottom: 20px;
|
.quick-action { --action-a: #2563eb; --action-b: #3730a3; --action-soft: rgba(37, 99, 235, .18); position: relative; isolation: isolate; display: flex; min-width: 0; min-height: 190px; overflow: hidden; align-items: center; flex-direction: column; padding: 21px 10px 18px; border: 1px solid rgba(148, 163, 184, .2); border-radius: 17px; background: linear-gradient(155deg, #fff 8%, rgba(248, 250, 252, .96) 100%); color: inherit; text-align: center; text-decoration: none; box-shadow: 0 12px 34px rgba(15, 23, 42, .07); backdrop-filter: blur(10px); animation: action-enter .4s cubic-bezier(.22, 1, .36, 1) both; animation-delay: calc(var(--entry-index) * 55ms); transition: border-color .35s ease, box-shadow .35s ease, transform .35s cubic-bezier(.22, 1, .36, 1); }
|
||||||
}
|
.quick-action::before { position: absolute; width: 120px; height: 120px; border-radius: 50%; background: radial-gradient(circle, var(--action-soft), transparent 70%); content: ''; right: -62px; top: -66px; transition: transform .4s ease; }
|
||||||
|
.quick-action::after { position: absolute; right: 20%; bottom: 0; left: 20%; height: 3px; border-radius: 99px 99px 0 0; background: linear-gradient(90deg, var(--action-a), var(--action-b)); content: ''; opacity: .55; transform: scaleX(.35); transition: all .35s ease; }
|
||||||
.dashboard-load-error ul {
|
.quick-action--blue { --action-a: #2563eb; --action-b: #3730a3; --action-soft: rgba(37, 99, 235, .18); }
|
||||||
display: grid;
|
.quick-action--purple { --action-a: #8b5cf6; --action-b: #c026d3; --action-soft: rgba(139, 92, 246, .18); }
|
||||||
gap: 3px;
|
.quick-action--green { --action-a: #059669; --action-b: #0f766e; --action-soft: rgba(5, 150, 105, .18); }
|
||||||
margin: 0;
|
.quick-action--cyan { --action-a: #0891b2; --action-b: #0e7490; --action-soft: rgba(8, 145, 178, .18); }
|
||||||
padding: 0;
|
.quick-action--orange { --action-a: #f59e0b; --action-b: #dc6b12; --action-soft: rgba(245, 158, 11, .2); }
|
||||||
list-style: none;
|
.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); }
|
||||||
.dashboard-load-error li {
|
.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); }
|
||||||
overflow-wrap: anywhere;
|
.quick-action:hover::before { transform: scale(1.25); }
|
||||||
color: var(--muted);
|
.quick-action:hover::after { right: 12%; left: 12%; opacity: 1; transform: scaleX(1); }
|
||||||
font-size: 12px;
|
.action-icon { position: relative; display: grid; width: 58px; height: 58px; flex: 0 0 auto; place-items: center; margin-bottom: 16px; border-radius: 18px; background: linear-gradient(135deg, var(--action-a), var(--action-b)); color: #fff; box-shadow: 0 11px 22px color-mix(in srgb, var(--action-a) 25%, transparent); transition: transform .35s ease; }
|
||||||
line-height: 1.5;
|
.action-icon::before { position: absolute; inset: 7px; border-radius: 12px; background: linear-gradient(135deg, rgba(255, 255, 255, .32), transparent 42%); content: ''; pointer-events: none; }
|
||||||
}
|
.action-icon::after { position: absolute; border: 1px solid color-mix(in srgb, var(--action-a) 20%, transparent); border-radius: 22px; content: ''; inset: -5px; }
|
||||||
|
.quick-action:hover .action-icon { transform: translateY(-3px) scale(1.06) rotate(-3deg); }
|
||||||
.dashboard-load-error li span {
|
.action-copy { position: relative; display: flex; min-width: 0; width: 100%; align-items: center; flex-direction: column; }
|
||||||
color: #9a5a09;
|
.action-copy strong { color: #172033; font-size: 16px; font-weight: 800; line-height: 1.35; white-space: nowrap; }
|
||||||
font-weight: 650;
|
.action-copy small { overflow: hidden; width: 100%; margin-top: 6px; color: #718096; font-size: 11px; line-height: 1.5; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
}
|
.action-enter { position: relative; display: inline-flex; align-items: center; gap: 6px; margin-top: auto; color: var(--action-a); font-size: 11px; font-weight: 750; }
|
||||||
|
.action-enter svg { transition: transform .25s ease; }
|
||||||
.dashboard-layout {
|
.quick-action:hover .action-enter svg { transform: translateX(4px); }
|
||||||
display: grid;
|
.quick-action--featured { border-color: rgba(49, 126, 255, .62); background: radial-gradient(circle at 8% 2%, rgba(34, 211, 238, .23), transparent 32%), radial-gradient(circle at 100% 100%, rgba(79, 70, 229, .22), transparent 44%), linear-gradient(145deg, #f2fbff 0%, #f8faff 45%, #eef2ff 100%); box-shadow: 0 20px 48px rgba(37, 99, 235, .2), 0 0 0 1px rgba(255, 255, 255, .88) inset, 0 0 34px rgba(34, 211, 238, .1); }
|
||||||
grid-template-columns: minmax(0, 1fr) 286px;
|
.quick-action--featured::before { width: 220px; height: 220px; right: -88px; top: -112px; background: radial-gradient(circle, rgba(34, 211, 238, .35) 0%, rgba(59, 130, 246, .2) 34%, transparent 69%); filter: blur(1px); animation: featured-aura 5s ease-in-out infinite; }
|
||||||
gap: clamp(24px, 3vw, 42px);
|
.quick-action--featured::after { right: 8%; left: 8%; height: 4px; background: linear-gradient(90deg, #22d3ee 0%, #2563eb 48%, #4f46e5 100%); box-shadow: 0 -4px 16px rgba(37, 99, 235, .44), 0 -1px 6px rgba(34, 211, 238, .55); opacity: 1; transform: scaleX(1); }
|
||||||
align-items: start;
|
.quick-action--featured:hover { border-color: rgba(34, 211, 238, .8); box-shadow: 0 30px 70px rgba(37, 99, 235, .27), 0 0 0 1px rgba(255, 255, 255, .95) inset, 0 0 40px rgba(34, 211, 238, .15); transform: translateY(-11px) scale(1.015); }
|
||||||
}
|
.quick-action--featured .action-icon { width: 64px; height: 64px; margin-bottom: 17px; border-radius: 20px; background: linear-gradient(145deg, #22c7df 0%, #2875ef 48%, #4338ca 100%); box-shadow: 0 16px 32px rgba(37, 99, 235, .37), 0 0 0 7px rgba(59, 130, 246, .09), 0 0 26px rgba(34, 211, 238, .24); }
|
||||||
|
.quick-action--featured .action-icon::after { inset: -6px; border-color: rgba(59, 130, 246, .25); border-radius: 25px; box-shadow: 0 0 0 1px rgba(34, 211, 238, .09); }
|
||||||
.dashboard-business {
|
.quick-action--featured .action-copy strong { color: #15233e; font-size: 17px; }
|
||||||
min-width: 0;
|
.quick-action--featured .action-enter { overflow: hidden; padding: 8px 15px; border-radius: 999px; background: linear-gradient(100deg, #12b8d0 0%, #2563eb 52%, #4338ca 100%); box-shadow: 0 10px 24px rgba(37, 99, 235, .3), 0 0 18px rgba(34, 211, 238, .12); color: #fff; }
|
||||||
padding: 14px 0 24px;
|
.quick-action--featured .action-enter::before { position: absolute; top: -60%; bottom: -60%; left: -55%; width: 38%; transform: rotate(18deg); background: linear-gradient(90deg, transparent, rgba(255, 255, 255, .55), transparent); content: ''; animation: featured-shine 3.6s ease-in-out infinite; }
|
||||||
}
|
.quick-action--featured .action-enter > * { position: relative; z-index: 1; }
|
||||||
|
.no-actions { margin: 0; padding: 20px; border: 1px solid var(--border); border-radius: 10px; background: #fff; color: #667085; font-size: 14px; }
|
||||||
.dashboard-intro {
|
.dashboard-order-list { min-width: 0; }
|
||||||
margin-bottom: 34px;
|
.orders-permission-empty { display: flex; min-height: 180px; align-items: center; justify-content: center; flex-direction: column; gap: 8px; border: 1px solid var(--border); border-radius: 10px; background: #fff; color: #7b8494; }
|
||||||
}
|
.orders-permission-empty strong { color: #475467; font-size: 15px; }
|
||||||
|
.orders-permission-empty span { font-size: 12px; }
|
||||||
.dashboard-intro h2 {
|
.client-dashboard a:focus-visible { border-radius: 6px; outline: 2px solid var(--primary); outline-offset: 4px; }
|
||||||
max-width: 720px;
|
@keyframes dashboard-enter { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
|
||||||
margin: 0;
|
@keyframes action-enter { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: translateY(0); } }
|
||||||
color: #111827;
|
@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); } }
|
||||||
font-size: clamp(30px, 3.2vw, 46px);
|
@keyframes featured-shine { 0%, 55% { left: -55%; opacity: 0; } 65% { opacity: 1; } 88%, 100% { left: 125%; opacity: 0; } }
|
||||||
line-height: 1.18;
|
@container dashboard-content (max-width: 1180px) { .quick-actions { grid-template-columns: repeat(8, minmax(178px, 1fr)); } }
|
||||||
letter-spacing: -.025em;
|
@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(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; } }
|
||||||
.dashboard-intro p {
|
|
||||||
max-width: 720px;
|
|
||||||
margin: 16px 0 0;
|
|
||||||
color: #697586;
|
|
||||||
font-size: 15px;
|
|
||||||
line-height: 1.7;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card-grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
|
||||||
gap: 18px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card {
|
|
||||||
--card-accent: var(--dashboard-blue);
|
|
||||||
display: flex;
|
|
||||||
min-width: 0;
|
|
||||||
min-height: 286px;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: flex-start;
|
|
||||||
padding: 30px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: 16px;
|
|
||||||
background: #fff;
|
|
||||||
box-shadow: 0 12px 36px rgba(23, 50, 77, .08);
|
|
||||||
color: #111827;
|
|
||||||
cursor: pointer;
|
|
||||||
text-align: left;
|
|
||||||
transition: transform .25s cubic-bezier(.16, 1, .3, 1), box-shadow .25s cubic-bezier(.16, 1, .3, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card--green { --card-accent: var(--dashboard-green); }
|
|
||||||
.business-card--teal { --card-accent: var(--dashboard-teal); }
|
|
||||||
|
|
||||||
.business-card:hover {
|
|
||||||
transform: translateY(-5px);
|
|
||||||
box-shadow: 0 20px 46px rgba(23, 50, 77, .14);
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card:focus-visible {
|
|
||||||
outline: 3px solid color-mix(in srgb, var(--card-accent) 36%, white);
|
|
||||||
outline-offset: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__icon {
|
|
||||||
display: grid;
|
|
||||||
width: 60px;
|
|
||||||
height: 60px;
|
|
||||||
place-items: center;
|
|
||||||
border-radius: 16px;
|
|
||||||
background: var(--card-accent);
|
|
||||||
box-shadow: 0 8px 18px color-mix(in srgb, var(--card-accent) 24%, transparent);
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__copy {
|
|
||||||
display: flex;
|
|
||||||
min-width: 0;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 10px;
|
|
||||||
margin-top: 34px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__copy strong {
|
|
||||||
font-size: 22px;
|
|
||||||
line-height: 1.35;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__copy small {
|
|
||||||
color: #697586;
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 1.65;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__action {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
margin-top: auto;
|
|
||||||
padding-top: 28px;
|
|
||||||
color: var(--card-accent);
|
|
||||||
font-size: 14px;
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__action svg {
|
|
||||||
transition: transform .2s cubic-bezier(.16, 1, .3, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card:hover .business-card__action svg {
|
|
||||||
transform: translateX(3px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-aside {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.aside-card {
|
|
||||||
padding: 20px;
|
|
||||||
border: 1px solid #e9eef5;
|
|
||||||
border-radius: 14px;
|
|
||||||
background: #f8fafc;
|
|
||||||
}
|
|
||||||
|
|
||||||
.aside-card h3 {
|
|
||||||
margin: 0 0 18px;
|
|
||||||
color: #8b9bb2;
|
|
||||||
font-size: 12px;
|
|
||||||
font-weight: 750;
|
|
||||||
letter-spacing: .06em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.account-summary {
|
|
||||||
display: flex;
|
|
||||||
min-width: 0;
|
|
||||||
align-items: center;
|
|
||||||
gap: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.account-avatar {
|
|
||||||
display: grid;
|
|
||||||
width: 52px;
|
|
||||||
height: 52px;
|
|
||||||
flex: 0 0 52px;
|
|
||||||
place-items: center;
|
|
||||||
border-radius: 14px;
|
|
||||||
background: linear-gradient(135deg, #1976d2, #00a993);
|
|
||||||
color: #fff;
|
|
||||||
font-size: 20px;
|
|
||||||
font-weight: 750;
|
|
||||||
}
|
|
||||||
|
|
||||||
.account-copy {
|
|
||||||
display: flex;
|
|
||||||
min-width: 0;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.account-copy strong {
|
|
||||||
overflow: hidden;
|
|
||||||
color: #111827;
|
|
||||||
font-size: 15px;
|
|
||||||
line-height: 1.35;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.account-copy small {
|
|
||||||
color: #66758a;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.account-load-error {
|
|
||||||
margin: 14px 0 0;
|
|
||||||
color: #8a5a22;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overview-stats {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overview-stats div {
|
|
||||||
display: flex;
|
|
||||||
min-height: 48px;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: space-between;
|
|
||||||
gap: 16px;
|
|
||||||
border-bottom: 1px dashed #dfe6ef;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overview-stats div:last-child {
|
|
||||||
border-bottom: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overview-stats dt {
|
|
||||||
color: #475569;
|
|
||||||
font-size: 13px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.overview-stats dd {
|
|
||||||
margin: 0;
|
|
||||||
color: #111827;
|
|
||||||
font-size: 15px;
|
|
||||||
font-weight: 750;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-section-error {
|
|
||||||
margin: 10px 0 0;
|
|
||||||
padding: 10px 0 0;
|
|
||||||
border-top: 1px solid #e9eef5;
|
|
||||||
color: #8a5a22;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.55;
|
|
||||||
}
|
|
||||||
|
|
||||||
.support-links {
|
|
||||||
display: grid;
|
|
||||||
gap: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.support-links button {
|
|
||||||
display: flex;
|
|
||||||
width: 100%;
|
|
||||||
min-height: 44px;
|
|
||||||
align-items: center;
|
|
||||||
gap: 11px;
|
|
||||||
padding: 0 9px;
|
|
||||||
border: 0;
|
|
||||||
border-radius: 9px;
|
|
||||||
background: transparent;
|
|
||||||
color: #334155;
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 14px;
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
|
|
||||||
.support-links button svg {
|
|
||||||
flex: 0 0 19px;
|
|
||||||
color: #00a993;
|
|
||||||
}
|
|
||||||
|
|
||||||
.support-links button:hover {
|
|
||||||
background: #edf2f7;
|
|
||||||
color: var(--dashboard-blue);
|
|
||||||
}
|
|
||||||
|
|
||||||
.support-links button:focus-visible {
|
|
||||||
outline: 2px solid var(--dashboard-blue);
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-tip {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: auto minmax(0, 1fr);
|
|
||||||
gap: 10px;
|
|
||||||
padding: 16px;
|
|
||||||
border: 1px solid rgba(0, 169, 147, .24);
|
|
||||||
border-radius: 14px;
|
|
||||||
background: #eef9f8;
|
|
||||||
color: #53657a;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-tip svg {
|
|
||||||
margin-top: 2px;
|
|
||||||
color: #00a993;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-tip p {
|
|
||||||
margin: 0;
|
|
||||||
font-size: 12px;
|
|
||||||
line-height: 1.75;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 1180px) {
|
|
||||||
.dashboard-layout {
|
|
||||||
grid-template-columns: 1fr;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-aside {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
|
||||||
align-items: stretch;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-tip {
|
|
||||||
grid-column: 1 / -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 960px) {
|
|
||||||
.business-card-grid {
|
|
||||||
grid-template-columns: 1fr;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card {
|
|
||||||
min-height: 232px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 720px) {
|
|
||||||
.client-dashboard {
|
|
||||||
min-height: calc(100vh - 118px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-business {
|
|
||||||
padding-top: 2px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-intro {
|
|
||||||
margin-bottom: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-intro h2 {
|
|
||||||
font-size: 28px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-intro p {
|
|
||||||
margin-top: 12px;
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card {
|
|
||||||
min-height: 220px;
|
|
||||||
padding: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.business-card__copy {
|
|
||||||
margin-top: 24px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-aside {
|
|
||||||
grid-template-columns: 1fr;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dashboard-tip {
|
|
||||||
grid-column: auto;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
.business-card,
|
|
||||||
.business-card__action svg {
|
|
||||||
transition: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { apiRequest } from '@/api/http'
|
||||||
|
|
||||||
|
export interface PageResult<T> {
|
||||||
|
records: T[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
size: number
|
||||||
|
pages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PageResultWire<T> extends Omit<PageResult<T>, 'total' | 'page' | 'size' | 'pages'> {
|
||||||
|
total: number | string
|
||||||
|
page: number | string
|
||||||
|
size: number | string
|
||||||
|
pages: number | string
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePageResult<T>(result: PageResultWire<T>): PageResult<T> {
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
total: Number(result.total),
|
||||||
|
page: Number(result.page),
|
||||||
|
size: Number(result.size),
|
||||||
|
pages: Number(result.pages),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FinanceAccount {
|
||||||
|
currencyCode: 'CNY'
|
||||||
|
actualBalance: string
|
||||||
|
frozenBalance: string
|
||||||
|
availableBalance: string
|
||||||
|
creditLimit: string
|
||||||
|
creditUsed: string
|
||||||
|
creditFrozen: string
|
||||||
|
availableCredit: string
|
||||||
|
creditExpiresOn: string | null
|
||||||
|
creditActive: boolean
|
||||||
|
version: number
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AccountChangeType = 'RECHARGE' | 'DEDUCTION' | 'FREEZE' | 'UNFREEZE' | 'CONSUMPTION' | 'CREDIT_LIMIT'
|
||||||
|
|
||||||
|
export interface AccountLedgerEntry {
|
||||||
|
ledgerId: string
|
||||||
|
businessNo: string
|
||||||
|
changeType: AccountChangeType
|
||||||
|
amount: string
|
||||||
|
actualBalanceAfter: string
|
||||||
|
frozenBalanceAfter: string
|
||||||
|
availableBalanceAfter: string
|
||||||
|
creditLimitAfter: string
|
||||||
|
creditUsedAfter: string
|
||||||
|
availableCreditAfter: string
|
||||||
|
creditExpiresOnAfter: string | null
|
||||||
|
sourceType: 'CLIENT_RECHARGE' | 'MANUAL_RECHARGE' | 'MANUAL_DEDUCTION' | 'CREDIT_LIMIT_ADJUSTMENT' | string
|
||||||
|
sourceNo: string
|
||||||
|
operatorName: string | null
|
||||||
|
remark: string | null
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RechargeStatus = 'PENDING' | 'APPROVED' | 'REJECTED'
|
||||||
|
|
||||||
|
export interface RechargeRequest {
|
||||||
|
requestId: string
|
||||||
|
requestNo: string
|
||||||
|
amount: string
|
||||||
|
voucherFileId: string
|
||||||
|
voucherFileName: string
|
||||||
|
status: RechargeStatus
|
||||||
|
version: number
|
||||||
|
submittedByName: string | null
|
||||||
|
reviewedByName: string | null
|
||||||
|
reviewRemark: string | null
|
||||||
|
createdAt: string
|
||||||
|
reviewedAt: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getFinanceAccount() {
|
||||||
|
return apiRequest<FinanceAccount>({ method: 'GET', url: '/client/finance/v1/account' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getAccountLedger(page: number, size: number) {
|
||||||
|
const result = await apiRequest<PageResultWire<AccountLedgerEntry>>({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/client/finance/v1/account/ledger',
|
||||||
|
params: { page, size },
|
||||||
|
})
|
||||||
|
return normalizePageResult(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRechargeRequests(page: number, size: number) {
|
||||||
|
const result = await apiRequest<PageResultWire<RechargeRequest>>({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/client/finance/v1/recharge-requests',
|
||||||
|
params: { page, size },
|
||||||
|
})
|
||||||
|
return normalizePageResult(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRechargeRequest(amount: string, file: File, idempotencyKey: string) {
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('amount', amount)
|
||||||
|
formData.append('file', file, file.name)
|
||||||
|
return apiRequest<RechargeRequest>({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/client/finance/v1/recharge-requests',
|
||||||
|
headers: { 'Idempotency-Key': idempotencyKey },
|
||||||
|
data: formData,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -34,6 +34,7 @@ export interface FinanceBillLineWire {
|
|||||||
sourceVersion: number
|
sourceVersion: number
|
||||||
orderId: WireScalar | null
|
orderId: WireScalar | null
|
||||||
inboundId: WireScalar | null
|
inboundId: WireScalar | null
|
||||||
|
inboundCode: string | null
|
||||||
feeItemCode: string
|
feeItemCode: string
|
||||||
feeItemName: string
|
feeItemName: string
|
||||||
amount: WireScalar
|
amount: WireScalar
|
||||||
@@ -89,6 +90,7 @@ function mapBillLine(line: FinanceBillLineWire): FinanceBillLine {
|
|||||||
return {
|
return {
|
||||||
id: text(line.id),
|
id: text(line.id),
|
||||||
orderId: line.orderId == null ? null : text(line.orderId),
|
orderId: line.orderId == null ? null : text(line.orderId),
|
||||||
|
inboundCode: line.inboundCode?.trim() || null,
|
||||||
feeNo: `${line.sourceType}:${text(line.sourceId)}/v${line.sourceVersion}`,
|
feeNo: `${line.sourceType}:${text(line.sourceId)}/v${line.sourceVersion}`,
|
||||||
feeName: line.feeItemName,
|
feeName: line.feeItemName,
|
||||||
amount: text(line.amount),
|
amount: text(line.amount),
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export interface FinanceCustomerConfirmationResult {
|
|||||||
export interface FinanceBillLine {
|
export interface FinanceBillLine {
|
||||||
id: string
|
id: string
|
||||||
orderId: string | null
|
orderId: string | null
|
||||||
|
inboundCode: string | null
|
||||||
feeNo: string | null
|
feeNo: string | null
|
||||||
feeName: string
|
feeName: string
|
||||||
amount: string
|
amount: string
|
||||||
|
|||||||
@@ -1,10 +1,18 @@
|
|||||||
import { ReceiptText } from '@lucide/vue'
|
import { CircleDollarSign, ReceiptText } from '@lucide/vue'
|
||||||
import type { ClientModuleManifest } from '../types.ts'
|
import type { ClientModuleManifest } from '../types.ts'
|
||||||
|
|
||||||
export const financeModule = {
|
export const financeModule = {
|
||||||
key: 'finance',
|
key: 'finance',
|
||||||
navigationGroup: { title: '财务结算', icon: ReceiptText },
|
navigationGroup: { title: '财务结算', icon: ReceiptText },
|
||||||
routes: [
|
routes: [
|
||||||
|
{
|
||||||
|
path: 'finance/account',
|
||||||
|
name: 'finance-account',
|
||||||
|
component: () => import('./views/FinanceAccountView.vue'),
|
||||||
|
release: 'active',
|
||||||
|
meta: { title: '资金账户', description: '查看本企业资金余额、流水与充值申请', permission: 'merchant:finance:account:view' },
|
||||||
|
navigation: { key: 'finance-account', title: '资金账户', icon: CircleDollarSign },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'finance/bills',
|
path: 'finance/bills',
|
||||||
name: 'finance-bills',
|
name: 'finance-bills',
|
||||||
@@ -13,5 +21,10 @@ export const financeModule = {
|
|||||||
meta: { title: '客户账单', description: '查看本企业账单、收款记录和未收余额', permission: 'finance:bill:view' },
|
meta: { title: '客户账单', description: '查看本企业账单、收款记录和未收余额', permission: 'finance:bill:view' },
|
||||||
navigation: { key: 'finance-bills', title: '客户账单', icon: ReceiptText },
|
navigation: { key: 'finance-bills', title: '客户账单', icon: ReceiptText },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'finance/bills/:billNo/detail', name: 'finance-bill-detail',
|
||||||
|
component: () => import('./views/FinanceBillDetailView.vue'), release: 'active',
|
||||||
|
meta: { title: '账单详情', workspaceTitle: '客户账单 · 详情', description: '查看费用明细、收款记录和客户确认信息', permission: 'finance:bill:view', keepAlive: false },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
} satisfies ClientModuleManifest
|
} satisfies ClientModuleManifest
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
|
||||||
|
const apiSource = readFileSync(new URL('../api/account.ts', import.meta.url), 'utf8')
|
||||||
|
const viewSource = readFileSync(new URL('./FinanceAccountView.vue', import.meta.url), 'utf8')
|
||||||
|
const routesSource = readFileSync(new URL('../routes.ts', import.meta.url), 'utf8')
|
||||||
|
const permissionsSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
test('uses only authenticated client finance account endpoints without customer scope', () => {
|
||||||
|
for (const path of ['/client/finance/v1/account', '/client/finance/v1/account/ledger', '/client/finance/v1/recharge-requests']) {
|
||||||
|
assert.match(apiSource, new RegExp(path.replaceAll('/', '\\/')))
|
||||||
|
}
|
||||||
|
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
||||||
|
assert.match(apiSource, /formData\.append\('amount', amount\)/)
|
||||||
|
assert.match(apiSource, /formData\.append\('file', file, file\.name\)/)
|
||||||
|
assert.doesNotMatch(apiSource, /RechargePaymentMethod|paymentMethod|WECHAT|ALIPAY/)
|
||||||
|
assert.doesNotMatch(apiSource, /customerId|tenantId|mock|fallback/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('activates the account route and maps read and recharge permissions independently', () => {
|
||||||
|
assert.match(routesSource, /path: 'finance\/account'[\s\S]*FinanceAccountView\.vue[\s\S]*release: 'active'[\s\S]*permission: 'merchant:finance:account:view'/)
|
||||||
|
assert.match(permissionsSource, /'merchant:finance:account:view': \['merchant:finance:account:view'\]/)
|
||||||
|
assert.match(permissionsSource, /'merchant:finance:recharge:create': \['merchant:finance:recharge:create'\]/)
|
||||||
|
assert.match(viewSource, /auth\.hasPermission\('merchant:finance:recharge:create'\)/)
|
||||||
|
assert.match(viewSource, /class="balance-title"[\s\S]*?<el-button v-if="canRecharge" size="small" type="primary"/)
|
||||||
|
assert.match(viewSource, /\.balance-summary \{[^}]*grid-template-columns: repeat\(6,/)
|
||||||
|
assert.doesNotMatch(viewSource, /class="account-actions"|class="balance-grid"/)
|
||||||
|
assert.doesNotMatch(viewSource, /class="account-heading"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('renders server balances, ledger and recharge states without internal identifiers', () => {
|
||||||
|
for (const field of ['actualBalance', 'frozenBalance', 'availableBalance', 'creditLimit', 'creditUsed', 'availableCredit']) assert.match(viewSource, new RegExp(`account\\?\\.${field}`))
|
||||||
|
assert.match(viewSource, /实际可用资金与可用授信合计/)
|
||||||
|
assert.match(viewSource, /CREDIT_LIMIT: '授信调整'/)
|
||||||
|
assert.match(viewSource, /row-key="businessNo"/)
|
||||||
|
assert.match(viewSource, /row-key="requestNo"/)
|
||||||
|
assert.match(viewSource, /empty-text="暂无资金流水"/)
|
||||||
|
assert.match(viewSource, /empty-text="暂无充值申请"/)
|
||||||
|
assert.match(viewSource, /account-state--error/)
|
||||||
|
assert.match(viewSource, /v-loading="pageLoading"/)
|
||||||
|
assert.match(viewSource, /function formatAccountAmount[\s\S]*value == null \? '—' : formatAmount\(value\)/)
|
||||||
|
assert.match(viewSource, /formatAccountAmount\(account\?\.actualBalance\)/)
|
||||||
|
assert.match(viewSource, /<DataTable v-model:page="ledgerPage" v-model:page-size="ledgerPageSize"/)
|
||||||
|
assert.match(viewSource, /<DataTable v-model:page="rechargePage" v-model:page-size="rechargePageSize"/)
|
||||||
|
assert.match(viewSource, /const ledgerColumns: DataTableColumn\[]/)
|
||||||
|
assert.match(viewSource, /const rechargeColumns: DataTableColumn\[]/)
|
||||||
|
assert.doesNotMatch(viewSource, /label: '已用授信'|label: '可用授信'/)
|
||||||
|
assert.doesNotMatch(viewSource, /<el-table|<el-pagination/)
|
||||||
|
assert.match(apiSource, /function normalizePageResult<[\s\S]*total: Number\(result\.total\)/)
|
||||||
|
assert.match(apiSource, /page: Number\(result\.page\)/)
|
||||||
|
assert.doesNotMatch(viewSource, /requestId|ledgerId|customerId|tenantId/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('matches the frozen recharge workflow and preserves an idempotency key for failed retries', () => {
|
||||||
|
assert.match(viewSource, /title="账户充值" width="760px"/)
|
||||||
|
for (const amount of ['1000', '5000', '20000', '50000']) assert.match(viewSource, new RegExp(amount))
|
||||||
|
assert.match(viewSource, /自定义/)
|
||||||
|
assert.match(viewSource, /src="\/customer-recharge-qr\.png"/)
|
||||||
|
assert.match(viewSource, /alt="平台收款二维码"/)
|
||||||
|
assert.match(viewSource, /请扫描平台收款二维码,付款后上传截图。/)
|
||||||
|
assert.match(viewSource, /accept="\.jpg,\.jpeg,\.png,image\/jpeg,image\/png"/)
|
||||||
|
assert.match(viewSource, /if \(!pendingIdempotencyKey\)[\s\S]*globalThis\.crypto\?\.randomUUID\?\.\(\)/)
|
||||||
|
assert.match(viewSource, /pendingIdempotencyKey = ''[\s\S]*rechargeVisible\.value = false/)
|
||||||
|
assert.match(viewSource, /:disabled="!canSubmit"/)
|
||||||
|
assert.match(viewSource, /await loadAccountData\(\)/)
|
||||||
|
assert.doesNotMatch(viewSource, /payment SDK|支付成功|模拟成功/)
|
||||||
|
assert.doesNotMatch(viewSource, /微信支付|支付宝|payment-methods|paymentMethod/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||||
|
import { CircleDollarSign, RefreshCcw, Upload } from '@lucide/vue'
|
||||||
|
import { ElMessage, type UploadFile, type UploadFiles, type UploadInstance } from 'element-plus'
|
||||||
|
import { ApiError } from '@/api/http'
|
||||||
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import {
|
||||||
|
createRechargeRequest,
|
||||||
|
getAccountLedger,
|
||||||
|
getFinanceAccount,
|
||||||
|
getRechargeRequests,
|
||||||
|
type AccountChangeType,
|
||||||
|
type AccountLedgerEntry,
|
||||||
|
type FinanceAccount,
|
||||||
|
type RechargeRequest,
|
||||||
|
type RechargeStatus,
|
||||||
|
} from '../api/account'
|
||||||
|
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const account = ref<FinanceAccount | null>(null)
|
||||||
|
const ledger = ref<AccountLedgerEntry[]>([])
|
||||||
|
const rechargeRequests = ref<RechargeRequest[]>([])
|
||||||
|
const pageLoading = ref(false)
|
||||||
|
const pageError = ref('')
|
||||||
|
const qrCodeLoadError = ref(false)
|
||||||
|
const ledgerPage = ref(1)
|
||||||
|
const ledgerTotal = ref(0)
|
||||||
|
const ledgerPageSize = ref(10)
|
||||||
|
const rechargePage = ref(1)
|
||||||
|
const rechargeTotal = ref(0)
|
||||||
|
const rechargePageSize = ref(10)
|
||||||
|
const rechargeVisible = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const submitError = ref('')
|
||||||
|
const voucherFile = ref<File | null>(null)
|
||||||
|
const voucherUpload = ref<UploadInstance>()
|
||||||
|
let pendingIdempotencyKey = ''
|
||||||
|
|
||||||
|
const form = reactive({ amount: '1000' })
|
||||||
|
const quickAmounts = ['1000', '5000', '20000', '50000']
|
||||||
|
const amountMode = ref<'preset' | 'custom'>('preset')
|
||||||
|
const canRecharge = computed(() => auth.hasPermission('merchant:finance:recharge:create'))
|
||||||
|
const channelReady = computed(() => !qrCodeLoadError.value)
|
||||||
|
const amountValid = computed(() => {
|
||||||
|
const value = Number(form.amount)
|
||||||
|
return Number.isFinite(value) && value > 0 && /^\d+(?:\.\d{1,2})?$/.test(form.amount.trim())
|
||||||
|
})
|
||||||
|
const canSubmit = computed(() => amountValid.value && channelReady.value && Boolean(voucherFile.value) && !submitting.value)
|
||||||
|
|
||||||
|
const changeLabels: Record<AccountChangeType, string> = {
|
||||||
|
RECHARGE: '充值', DEDUCTION: '扣款', FREEZE: '冻结', UNFREEZE: '解冻', CONSUMPTION: '消费', CREDIT_LIMIT: '授信调整',
|
||||||
|
}
|
||||||
|
const statusLabels: Record<RechargeStatus, string> = { PENDING: '待审核', APPROVED: '已通过', REJECTED: '已驳回' }
|
||||||
|
const ledgerColumns: DataTableColumn[] = [
|
||||||
|
{ label: '业务单号', prop: 'businessNo', minWidth: 180 },
|
||||||
|
{ label: '变动类型', slotName: 'changeType', width: 100 },
|
||||||
|
{ label: '变动金额', slotName: 'amount', width: 120, align: 'right' },
|
||||||
|
{ label: '实际余额', slotName: 'actualBalance', width: 120, align: 'right' },
|
||||||
|
{ label: '冻结金额', slotName: 'frozenBalance', width: 120, align: 'right' },
|
||||||
|
{ label: '可用余额', slotName: 'availableBalance', width: 120, align: 'right' },
|
||||||
|
{ label: '操作人', slotName: 'operatorName', width: 120 },
|
||||||
|
{ label: '备注', slotName: 'remark', minWidth: 180 },
|
||||||
|
{ label: '发生时间', slotName: 'createdAt', width: 160 },
|
||||||
|
]
|
||||||
|
const rechargeColumns: DataTableColumn[] = [
|
||||||
|
{ label: '充值申请单号', prop: 'requestNo', minWidth: 180 },
|
||||||
|
{ label: '金额', slotName: 'amount', width: 120, align: 'right' },
|
||||||
|
{ label: '付款截图', prop: 'voucherFileName', minWidth: 150 },
|
||||||
|
{ label: '状态', slotName: 'status', width: 100 },
|
||||||
|
{ label: '提交人', slotName: 'submittedByName', width: 120 },
|
||||||
|
{ label: '审核备注', slotName: 'reviewRemark', minWidth: 180 },
|
||||||
|
{ label: '提交时间', slotName: 'createdAt', width: 160 },
|
||||||
|
{ label: '审核时间', slotName: 'reviewedAt', width: 160 },
|
||||||
|
]
|
||||||
|
|
||||||
|
function messageOf(error: unknown, fallback: string) {
|
||||||
|
return error instanceof ApiError ? error.message : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAmount(value: string | null | undefined) {
|
||||||
|
const number = Number(value ?? '0')
|
||||||
|
return Number.isFinite(number)
|
||||||
|
? number.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||||
|
: '0.00'
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAccountAmount(value: string | null | undefined) {
|
||||||
|
return value == null ? '—' : formatAmount(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDateTime(value: string | null | undefined) {
|
||||||
|
return value ? value.replace('T', ' ').replace(/Z$/, '').slice(0, 16) : '—'
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusType(status: RechargeStatus) {
|
||||||
|
return ({ PENDING: 'warning', APPROVED: 'success', REJECTED: 'danger' })[status] as 'warning' | 'success' | 'danger'
|
||||||
|
}
|
||||||
|
|
||||||
|
function amountClass(amount: string) {
|
||||||
|
return Number(amount) >= 0 ? 'amount-positive' : 'amount-negative'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAccountData() {
|
||||||
|
pageLoading.value = true
|
||||||
|
pageError.value = ''
|
||||||
|
qrCodeLoadError.value = false
|
||||||
|
const requests = [getFinanceAccount(), getAccountLedger(ledgerPage.value, ledgerPageSize.value), getRechargeRequests(rechargePage.value, rechargePageSize.value)] as const
|
||||||
|
try {
|
||||||
|
const [accountResult, ledgerResult, rechargeResult] = await Promise.all(requests)
|
||||||
|
account.value = accountResult
|
||||||
|
ledger.value = ledgerResult.records
|
||||||
|
ledgerTotal.value = ledgerResult.total
|
||||||
|
rechargeRequests.value = rechargeResult.records
|
||||||
|
rechargeTotal.value = rechargeResult.total
|
||||||
|
} catch (error) {
|
||||||
|
account.value = null
|
||||||
|
ledger.value = []
|
||||||
|
rechargeRequests.value = []
|
||||||
|
ledgerTotal.value = 0
|
||||||
|
rechargeTotal.value = 0
|
||||||
|
pageError.value = messageOf(error, '资金账户加载失败,请稍后重试')
|
||||||
|
} finally {
|
||||||
|
pageLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function changeLedgerPage(nextPage: number) {
|
||||||
|
try {
|
||||||
|
const result = await getAccountLedger(nextPage, ledgerPageSize.value)
|
||||||
|
ledger.value = result.records
|
||||||
|
ledgerTotal.value = result.total
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error(messageOf(error, '资金流水加载失败,请重试'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function changeRechargePage(nextPage: number) {
|
||||||
|
try {
|
||||||
|
const result = await getRechargeRequests(nextPage, rechargePageSize.value)
|
||||||
|
rechargeRequests.value = result.records
|
||||||
|
rechargeTotal.value = result.total
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error(messageOf(error, '充值申请加载失败,请重试'))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openRecharge() {
|
||||||
|
submitError.value = ''
|
||||||
|
qrCodeLoadError.value = false
|
||||||
|
amountMode.value = 'preset'
|
||||||
|
form.amount = '1000'
|
||||||
|
rechargeVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleQrCodeError() {
|
||||||
|
qrCodeLoadError.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function chooseAmount(amount: string) {
|
||||||
|
amountMode.value = 'preset'
|
||||||
|
form.amount = amount
|
||||||
|
}
|
||||||
|
|
||||||
|
function chooseCustomAmount() {
|
||||||
|
amountMode.value = 'custom'
|
||||||
|
if (quickAmounts.includes(form.amount)) form.amount = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleVoucherChange(uploadFile: UploadFile, _uploadFiles: UploadFiles) {
|
||||||
|
const file = uploadFile.raw
|
||||||
|
if (!file) return
|
||||||
|
const extensionAllowed = /\.(?:jpe?g|png)$/i.test(file.name)
|
||||||
|
const mimeAllowed = ['image/jpeg', 'image/png'].includes(file.type)
|
||||||
|
if (!extensionAllowed || !mimeAllowed) {
|
||||||
|
voucherFile.value = null
|
||||||
|
ElMessage.error('付款截图仅支持 jpg、jpeg 或 png 图片')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
voucherFile.value = file
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleVoucherRemove() {
|
||||||
|
voucherFile.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizedAmount() {
|
||||||
|
return Number(form.amount).toFixed(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitRecharge() {
|
||||||
|
if (submitting.value) return
|
||||||
|
submitError.value = ''
|
||||||
|
if (!amountValid.value) {
|
||||||
|
submitError.value = '请输入大于 0 且最多两位小数的充值金额'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!channelReady.value) {
|
||||||
|
submitError.value = '收款二维码尚未配置,暂不能提交充值申请'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!voucherFile.value) {
|
||||||
|
submitError.value = '请上传付款截图'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!pendingIdempotencyKey) {
|
||||||
|
pendingIdempotencyKey = globalThis.crypto?.randomUUID?.() ?? `recharge-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||||
|
}
|
||||||
|
submitting.value = true
|
||||||
|
try {
|
||||||
|
await createRechargeRequest(normalizedAmount(), voucherFile.value, pendingIdempotencyKey)
|
||||||
|
pendingIdempotencyKey = ''
|
||||||
|
rechargeVisible.value = false
|
||||||
|
voucherFile.value = null
|
||||||
|
voucherUpload.value?.clearFiles()
|
||||||
|
ElMessage.success('充值申请已提交,等待平台审核')
|
||||||
|
await loadAccountData()
|
||||||
|
} catch (error) {
|
||||||
|
submitError.value = messageOf(error, '充值申请提交失败,请使用当前内容重试')
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch([() => form.amount, voucherFile], () => {
|
||||||
|
if (!submitting.value) pendingIdempotencyKey = ''
|
||||||
|
submitError.value = ''
|
||||||
|
})
|
||||||
|
|
||||||
|
watch([ledgerPage, ledgerPageSize], () => { void changeLedgerPage(ledgerPage.value) })
|
||||||
|
watch([rechargePage, rechargePageSize], () => { void changeRechargePage(rechargePage.value) })
|
||||||
|
|
||||||
|
onMounted(() => { void loadAccountData() })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-loading="pageLoading" class="finance-account-page" :aria-busy="pageLoading">
|
||||||
|
<div v-if="pageError" class="account-state account-state--error" role="alert">
|
||||||
|
<p>{{ pageError }}</p><el-button @click="loadAccountData"><RefreshCcw :size="15" />重新加载</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<section class="balance-summary" aria-label="账户余额">
|
||||||
|
<article><div class="balance-title"><span>实际余额</span><el-button v-if="canRecharge" size="small" type="primary" @click="openRecharge"><CircleDollarSign :size="15" />账户充值</el-button></div><strong>¥ {{ formatAccountAmount(account?.actualBalance) }}</strong><small>当前账户实际资金</small></article>
|
||||||
|
<article><span>冻结金额</span><strong>¥ {{ formatAccountAmount(account?.frozenBalance) }}</strong><small>暂不可使用的资金</small></article>
|
||||||
|
<article class="balance-available"><span>总可用余额</span><strong>¥ {{ formatAccountAmount(account?.availableBalance) }}</strong><small>实际可用资金与可用授信合计</small></article>
|
||||||
|
<article><span>授信额度</span><strong>¥ {{ formatAccountAmount(account?.creditLimit) }}</strong><small>{{ account?.creditExpiresOn ? `${account.creditExpiresOn} ${account.creditActive ? '到期' : '已到期'}` : '未设置有效期' }}</small></article>
|
||||||
|
<article><span>已用授信</span><strong>¥ {{ formatAccountAmount(account?.creditUsed) }}</strong><small>已结算使用的授信</small></article>
|
||||||
|
<article><span>可用授信</span><strong>¥ {{ formatAccountAmount(account?.availableCredit) }}</strong><small>扣除已用和冻结后的授信</small></article>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="account-card">
|
||||||
|
<div class="section-heading"><div><h3>账户流水</h3><p>每次资金变动均生成唯一业务单号。</p></div></div>
|
||||||
|
<DataTable v-model:page="ledgerPage" v-model:page-size="ledgerPageSize" :data="ledger" :columns="ledgerColumns" :total="ledgerTotal" :page-sizes="[10, 20, 50]" row-key="businessNo" empty-text="暂无资金流水">
|
||||||
|
<template #changeType="{ row }">{{ changeLabels[row.changeType as AccountChangeType] }}</template>
|
||||||
|
<template #amount="{ row }"><strong :class="amountClass(row.amount)">{{ Number(row.amount) >= 0 ? '+' : '' }}¥ {{ formatAmount(row.amount) }}</strong></template>
|
||||||
|
<template #actualBalance="{ row }">¥ {{ formatAmount(row.actualBalanceAfter) }}</template>
|
||||||
|
<template #frozenBalance="{ row }">¥ {{ formatAmount(row.frozenBalanceAfter) }}</template>
|
||||||
|
<template #availableBalance="{ row }">¥ {{ formatAmount(row.availableBalanceAfter) }}</template>
|
||||||
|
<template #operatorName="{ row }">{{ row.operatorName || '—' }}</template>
|
||||||
|
<template #remark="{ row }">{{ row.remark || '—' }}</template>
|
||||||
|
<template #createdAt="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
||||||
|
</DataTable>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="account-card">
|
||||||
|
<div class="section-heading"><div><h3>充值申请</h3><p>付款后上传截图,平台审核通过后资金入账。</p></div></div>
|
||||||
|
<DataTable v-model:page="rechargePage" v-model:page-size="rechargePageSize" :data="rechargeRequests" :columns="rechargeColumns" :total="rechargeTotal" :page-sizes="[10, 20, 50]" row-key="requestNo" empty-text="暂无充值申请">
|
||||||
|
<template #amount="{ row }">¥ {{ formatAmount(row.amount) }}</template>
|
||||||
|
<template #status="{ row }"><el-tag :type="statusType(row.status as RechargeStatus)">{{ statusLabels[row.status as RechargeStatus] }}</el-tag></template>
|
||||||
|
<template #submittedByName="{ row }">{{ row.submittedByName || '—' }}</template>
|
||||||
|
<template #reviewRemark="{ row }">{{ row.reviewRemark || '—' }}</template>
|
||||||
|
<template #createdAt="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
||||||
|
<template #reviewedAt="{ row }">{{ formatDateTime(row.reviewedAt) }}</template>
|
||||||
|
</DataTable>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<el-dialog v-model="rechargeVisible" title="账户充值" width="760px" :close-on-click-modal="false" :close-on-press-escape="!submitting" :show-close="!submitting" class="recharge-dialog">
|
||||||
|
<div class="recharge-form">
|
||||||
|
<label class="field-label" for="recharge-amount">充值金额</label>
|
||||||
|
<el-input v-if="amountMode === 'custom'" id="recharge-amount" v-model="form.amount" size="large" inputmode="decimal" placeholder="请输入充值金额" aria-label="充值金额"><template #prefix>¥</template></el-input>
|
||||||
|
<div class="quick-amounts" aria-label="快捷充值金额">
|
||||||
|
<button v-for="amount in quickAmounts" :key="amount" type="button" :class="{ active: amountMode === 'preset' && form.amount === amount }" @click="chooseAmount(amount)">¥{{ Number(amount).toLocaleString() }}</button>
|
||||||
|
<button type="button" :class="{ active: amountMode === 'custom' }" @click="chooseCustomAmount">自定义</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="channelReady" class="qr-panel">
|
||||||
|
<img src="/customer-recharge-qr.png" alt="平台收款二维码" @error="handleQrCodeError">
|
||||||
|
<div><strong>扫码付款</strong><p>请扫描平台收款二维码,付款后上传截图。</p></div>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="qrCodeLoadError" class="channel-warning" role="alert">平台收款二维码资源不可用,请联系管理员更新二维码</div>
|
||||||
|
<div v-else class="channel-warning" role="status">收款二维码尚未配置,暂不能提交充值申请。</div>
|
||||||
|
|
||||||
|
<div class="voucher-upload">
|
||||||
|
<span class="field-label">付款截图</span>
|
||||||
|
<el-upload ref="voucherUpload" :auto-upload="false" :limit="1" accept=".jpg,.jpeg,.png,image/jpeg,image/png" :on-change="handleVoucherChange" :on-remove="handleVoucherRemove">
|
||||||
|
<el-button><Upload :size="16" />选择付款截图</el-button>
|
||||||
|
<template #tip><div class="el-upload__tip">仅支持 jpg、jpeg、png 图片;提交后进入平台审核。</div></template>
|
||||||
|
</el-upload>
|
||||||
|
</div>
|
||||||
|
<p v-if="submitError" class="submit-error" role="alert">{{ submitError }}</p>
|
||||||
|
</div>
|
||||||
|
<template #footer><div class="dialog-actions"><el-button :disabled="submitting" @click="rechargeVisible = false">取消</el-button><el-button type="primary" :loading="submitting" :disabled="!canSubmit" @click="submitRecharge">确认充值</el-button></div></template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.finance-account-page { display: flex; min-height: 420px; flex-direction: column; gap: 16px; }
|
||||||
|
.section-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
|
||||||
|
.section-heading h3 { margin: 0; color: var(--navy); font-size: 16px; }
|
||||||
|
.section-heading p { margin: 5px 0 0; color: var(--muted); font-size: 13px; }
|
||||||
|
.balance-summary { display: grid; overflow: hidden; grid-template-columns: repeat(6, minmax(0, 1fr)); border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
|
||||||
|
.balance-summary article { display: flex; min-width: 0; min-height: 104px; flex-direction: column; padding: 14px 16px; border-right: 1px solid var(--client-border); }
|
||||||
|
.balance-summary article:last-child { border-right: 0; }
|
||||||
|
.balance-summary span { color: var(--muted); font-size: 12px; }.balance-summary strong { margin-top: 10px; overflow: hidden; color: var(--navy); font-size: 22px; line-height: 1.1; text-overflow: ellipsis; white-space: nowrap; }.balance-summary small { margin-top: auto; overflow: hidden; color: #8a98a8; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.balance-title { display: flex; min-height: 28px; align-items: center; justify-content: space-between; gap: 8px; }.balance-title .el-button { flex: 0 0 auto; height: 28px; padding: 0 9px; }.balance-title .el-button :deep(span) { display: inline-flex; align-items: center; gap: 4px; color: inherit; }
|
||||||
|
.balance-summary .balance-available { background: #f3faf8; }.balance-summary .balance-available strong { color: #058b78; }
|
||||||
|
.account-card { min-width: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }.section-heading { padding: 14px 16px; border-bottom: 1px solid var(--client-border); }
|
||||||
|
.amount-positive { color: #078a72; }.amount-negative { color: #b42318; }
|
||||||
|
.account-state { display: flex; min-height: 240px; align-items: center; justify-content: center; flex-direction: column; gap: 12px; border-radius: 8px; }.account-state--error { border: 1px solid #f5c2bd; background: #fff8f7; color: #b42318; }.account-state p { margin: 0; }
|
||||||
|
.recharge-form { display: flex; flex-direction: column; gap: 16px; }.field-label { color: #4e6075; font-size: 14px; font-weight: 650; }
|
||||||
|
.quick-amounts { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; }.quick-amounts button { min-height: 54px; border: 1px solid #dbe3ed; border-radius: 10px; background: #f8fafc; color: #506077; cursor: pointer; font: inherit; }.quick-amounts button.active { border: 2px solid #1671c9; background: #eef8f7; color: #1467b8; font-weight: 700; }
|
||||||
|
.qr-panel { display: grid; grid-template-columns: 210px minmax(0, 1fr); align-items: center; gap: 24px; padding: 20px; border: 1px solid #dbe3ed; border-radius: 12px; background: #f8fafc; }.qr-panel img { width: 210px; height: 210px; border: 1px solid #dae3ed; border-radius: 10px; background: #fff; object-fit: contain; }.qr-panel strong { color: var(--navy); font-size: 17px; }.qr-panel p { margin: 8px 0 0; color: #62758d; }
|
||||||
|
.channel-warning { padding: 24px; border: 1px solid #f0d39b; border-radius: 10px; background: #fff9ed; color: #8b5b12; text-align: center; }.voucher-upload { display: grid; gap: 10px; }.voucher-upload :deep(.el-button) { display: inline-flex; align-items: center; gap: 6px; }.submit-error { margin: 0; color: #b42318; font-size: 13px; }.dialog-actions { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }.dialog-actions .el-button { min-height: 46px; margin: 0; }
|
||||||
|
@media (max-width: 1200px) { .balance-summary { grid-template-columns: repeat(3, minmax(0, 1fr)); }.balance-summary article { border-bottom: 1px solid var(--client-border); }.balance-summary article:nth-child(3n) { border-right: 0; }.balance-summary article:nth-last-child(-n + 3) { border-bottom: 0; } }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { ArrowLeft } from '@lucide/vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { ApiError } from '@/api/http'
|
||||||
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import { InboundCodeAssociationDialog } from '@/modules/first-leg/public'
|
||||||
|
import { confirmMerchantFinanceStatement, getMerchantFinanceBill, getMerchantFinanceBills, getMerchantFinanceReceipts } from '../api/finance'
|
||||||
|
import type { FinanceBillDetail, FinanceBillSummary, FinanceBillStatus, FinanceCustomerConfirmationStatus } from '../contracts'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const auth = useAuthStore()
|
||||||
|
const billNo = computed(() => String(route.params.billNo || ''))
|
||||||
|
const loading = ref(false)
|
||||||
|
const errorMessage = ref('')
|
||||||
|
const detail = ref<FinanceBillDetail | null>(null)
|
||||||
|
const confirming = ref(false)
|
||||||
|
const inboundAssociationVisible = ref(false)
|
||||||
|
const inboundAssociationCode = ref('')
|
||||||
|
const canConfirm = computed(() => auth.hasPermission('finance:bill:confirm'))
|
||||||
|
const lineColumns: DataTableColumn[] = [
|
||||||
|
{ key: 'inboundCode', label: '入仓码', slotName: 'inboundCode', minWidth: 180 },
|
||||||
|
{ prop: 'feeName', label: '费用项目', minWidth: 220 },
|
||||||
|
{ key: 'amount', label: '金额', slotName: 'amount', width: 150, align: 'right', headerAlign: 'right' },
|
||||||
|
]
|
||||||
|
const receiptColumns: DataTableColumn[] = [
|
||||||
|
{ key: 'receivedAt', label: '收款日期', slotName: 'receivedAt', width: 130 },
|
||||||
|
{ prop: 'receiptNo', label: '收款编号', minWidth: 180 },
|
||||||
|
{ key: 'allocatedAmount', label: '本次金额', slotName: 'allocatedAmount', width: 150, align: 'right', headerAlign: 'right' },
|
||||||
|
{ key: 'method', label: '方式', slotName: 'method', minWidth: 120 },
|
||||||
|
]
|
||||||
|
|
||||||
|
function formatAmount(value?: string | null) { const number = Number(value); return Number.isFinite(number) ? number.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : value || '0.00' }
|
||||||
|
function formatDate(value?: string | null) { return value ? value.slice(0, 10) : '—' }
|
||||||
|
function formatDateTime(value?: string | null) { return value ? value.replace('T', ' ').replace(/Z$/, '').slice(0, 16) : '—' }
|
||||||
|
function statusLabel(status: FinanceBillStatus) { return ({ DRAFT: '草稿', ISSUED: '已出账', PARTIALLY_PAID: '部分收款', PAID: '已收清', VOIDED: '作废' } as Record<string, string>)[status] || status }
|
||||||
|
function statusType(status: FinanceBillStatus) { return ({ ISSUED: 'info', PARTIALLY_PAID: 'warning', PAID: 'success', VOIDED: 'danger', DRAFT: 'info' } as const)[status] }
|
||||||
|
function confirmationLabel(status: FinanceCustomerConfirmationStatus) { return ({ NOT_REQUIRED: '无需确认', PENDING_CONFIRMATION: '待确认', CONFIRMED: '已确认' })[status] }
|
||||||
|
function paymentMethodLabel(method?: string | null) { return ({ BANK_TRANSFER: '银行转账', CASH: '现金', OTHER: '其他' } as Record<string, string>)[method || ''] || '其他' }
|
||||||
|
function messageOf(error: unknown) { return error instanceof ApiError ? error.message : '账单详情加载失败,请稍后重试' }
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
if (!billNo.value) return
|
||||||
|
loading.value = true
|
||||||
|
errorMessage.value = ''
|
||||||
|
try {
|
||||||
|
const result = await getMerchantFinanceBills({ keyword: billNo.value, page: 1, size: 100 })
|
||||||
|
const summary = result.records.find(item => item.billNo === billNo.value)
|
||||||
|
if (!summary) throw new Error('未找到该账单')
|
||||||
|
const [bill, receipts] = await Promise.all([getMerchantFinanceBill(summary.id), getMerchantFinanceReceipts(summary.id)])
|
||||||
|
detail.value = { ...bill, receipts }
|
||||||
|
} catch (error) { detail.value = null; errorMessage.value = error instanceof Error ? error.message : messageOf(error) }
|
||||||
|
finally { loading.value = false }
|
||||||
|
}
|
||||||
|
async function confirmStatement(statement: FinanceBillSummary) {
|
||||||
|
if (!canConfirm.value || statement.customerConfirmationStatus !== 'PENDING_CONFIRMATION' || confirming.value) return
|
||||||
|
try { await ElMessageBox.confirm(`确认账单 ${statement.billNo}(¥ ${formatAmount(statement.totalAmount)})金额与费用明细无误?`, '确认客户账单', { type: 'warning', confirmButtonText: '确认无误', cancelButtonText: '取消' }) } catch { return }
|
||||||
|
confirming.value = true
|
||||||
|
try { await confirmMerchantFinanceStatement(statement.id, statement.version); ElMessage.success('账单已确认'); await load() }
|
||||||
|
catch (error) { ElMessage.error(messageOf(error)) }
|
||||||
|
finally { confirming.value = false }
|
||||||
|
}
|
||||||
|
function openInboundAssociation(value?: string | null) { if (!value) return; inboundAssociationCode.value = value; inboundAssociationVisible.value = true }
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<article v-loading="loading" class="bill-detail-surface">
|
||||||
|
<template v-if="detail">
|
||||||
|
<header class="bill-detail-header"><button type="button" class="bill-detail-back" @click="router.push({ name: 'finance-bills' })"><ArrowLeft :size="16" />返回列表</button><div class="bill-detail-title"><strong>{{ detail.billNo }}</strong><span>出账 {{ formatDate(detail.issueDate) }} · 到期 {{ formatDate(detail.dueDate) }}</span></div><div class="bill-detail-actions"><el-tag :type="statusType(detail.status)" effect="light">{{ statusLabel(detail.status) }}</el-tag><el-tag effect="light">{{ confirmationLabel(detail.customerConfirmationStatus) }}</el-tag><el-button v-if="detail.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm" type="primary" :loading="confirming" @click="confirmStatement(detail)">确认账单</el-button></div></header>
|
||||||
|
<section class="bill-detail-section"><h3>账单概览</h3><dl class="bill-detail-grid"><div><dt>账单金额</dt><dd>¥ {{ formatAmount(detail.totalAmount) }}</dd></div><div><dt>已收金额</dt><dd>¥ {{ formatAmount(detail.receivedAmount) }}</dd></div><div><dt>未收余额</dt><dd class="amount-warning">¥ {{ formatAmount(detail.outstandingAmount) }}</dd></div><div><dt>客户确认</dt><dd>{{ confirmationLabel(detail.customerConfirmationStatus) }}</dd></div><div><dt>确认成员</dt><dd>{{ detail.customerConfirmedByName || '—' }}</dd></div><div><dt>确认时间</dt><dd>{{ formatDateTime(detail.customerConfirmedAt) }}</dd></div></dl></section>
|
||||||
|
<section class="bill-detail-section"><h3>费用明细</h3><DataTable :data="detail.lines" :columns="lineColumns" row-key="id" empty-text="暂无费用明细"><template #inboundCode="{ row }"><el-button v-if="row.inboundCode" link type="primary" @click="openInboundAssociation(row.inboundCode)">{{ row.inboundCode }}</el-button><span v-else>—</span></template><template #amount="{ row }">¥ {{ formatAmount(row.amount) }}</template></DataTable></section>
|
||||||
|
<section class="bill-detail-section"><h3>收款记录</h3><DataTable :data="detail.receipts" :columns="receiptColumns" row-key="id" empty-text="暂无收款记录"><template #receivedAt="{ row }">{{ formatDate(row.receivedAt) }}</template><template #allocatedAmount="{ row }">¥ {{ formatAmount(row.allocatedAmount) }}</template><template #method="{ row }">{{ paymentMethodLabel(row.method) }}</template></DataTable></section>
|
||||||
|
<p class="bill-detail-notice">如对账单内容有疑问,请先联系平台财务,核对无误后再确认。</p>
|
||||||
|
</template>
|
||||||
|
<div v-else-if="errorMessage" class="bill-detail-error" role="alert"><strong>{{ errorMessage }}</strong><el-button @click="load">重新加载</el-button></div>
|
||||||
|
</article>
|
||||||
|
<InboundCodeAssociationDialog v-model="inboundAssociationVisible" :inbound-code="inboundAssociationCode" />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.bill-detail-surface{overflow:hidden;min-height:240px;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff}.bill-detail-header{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:14px;min-height:64px;padding:10px 16px;border-bottom:1px solid var(--client-border)}.bill-detail-back{display:inline-flex;align-items:center;gap:5px;padding:5px 0;border:0;background:transparent;color:var(--el-color-primary);cursor:pointer}.bill-detail-title{display:flex;min-width:0;flex-direction:column;gap:3px}.bill-detail-title strong{overflow:hidden;color:#1f2d45;font-size:18px;text-overflow:ellipsis;white-space:nowrap}.bill-detail-title span{color:var(--client-muted);font-size:12px}.bill-detail-actions{display:flex;align-items:center;gap:8px}.bill-detail-section+.bill-detail-section{border-top:1px solid var(--client-border)}.bill-detail-section>h3{display:flex;min-height:40px;align-items:center;margin:0;padding:0 16px;border-bottom:1px solid var(--client-border);background:var(--client-header-bg);font-size:14px}.bill-detail-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:0}.bill-detail-grid div{display:grid;min-height:42px;grid-template-columns:88px minmax(0,1fr);align-items:center;gap:8px;padding:5px 12px;border-right:1px solid var(--client-border);border-bottom:1px solid var(--client-border)}.bill-detail-grid dt{color:var(--client-muted);font-size:12px}.bill-detail-grid dd{margin:0;overflow:hidden;color:var(--client-text);font-size:13px;font-weight:600;text-overflow:ellipsis;white-space:nowrap}.amount-warning{color:#b45309!important}.bill-detail-notice{margin:0;padding:10px 14px;border-top:1px solid var(--client-border);background:#f5faf8;color:#45615d;font-size:12px}.bill-detail-error{display:flex;min-height:220px;align-items:center;justify-content:center;gap:12px;color:#b42318}@media(max-width:1100px){.bill-detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.bill-detail-header{grid-template-columns:1fr auto}.bill-detail-back{grid-column:1/-1}.bill-detail-grid{grid-template-columns:1fr}}
|
||||||
|
</style>
|
||||||
@@ -5,6 +5,7 @@ import ts from 'typescript'
|
|||||||
|
|
||||||
const routesSource = readFileSync(new URL('../routes.ts', import.meta.url), 'utf8')
|
const routesSource = readFileSync(new URL('../routes.ts', import.meta.url), 'utf8')
|
||||||
const viewSource = readFileSync(new URL('./FinanceBillsView.vue', import.meta.url), 'utf8')
|
const viewSource = readFileSync(new URL('./FinanceBillsView.vue', import.meta.url), 'utf8')
|
||||||
|
const detailViewSource = readFileSync(new URL('./FinanceBillDetailView.vue', import.meta.url), 'utf8')
|
||||||
const apiSource = readFileSync(new URL('../api/finance.ts', import.meta.url), 'utf8')
|
const apiSource = readFileSync(new URL('../api/finance.ts', import.meta.url), 'utf8')
|
||||||
const adapterSource = readFileSync(new URL('../api/adapters.ts', import.meta.url), 'utf8')
|
const adapterSource = readFileSync(new URL('../api/adapters.ts', import.meta.url), 'utf8')
|
||||||
const permissionSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8')
|
const permissionSource = readFileSync(new URL('../../tenant-management/contracts.ts', import.meta.url), 'utf8')
|
||||||
@@ -22,6 +23,8 @@ const permissionContracts = await importTypeScriptModule(new URL('../../tenant-m
|
|||||||
|
|
||||||
test('activates the customer finance route with its existing list and detail permission', () => {
|
test('activates the customer finance route with its existing list and detail permission', () => {
|
||||||
assert.match(routesSource, /path: 'finance\/bills'/)
|
assert.match(routesSource, /path: 'finance\/bills'/)
|
||||||
|
assert.match(routesSource, /path: 'finance\/bills\/:billNo\/detail'/)
|
||||||
|
assert.match(routesSource, /name: 'finance-bill-detail'/)
|
||||||
assert.match(routesSource, /FinanceBillsView\.vue/)
|
assert.match(routesSource, /FinanceBillsView\.vue/)
|
||||||
assert.match(routesSource, /release: 'active'/)
|
assert.match(routesSource, /release: 'active'/)
|
||||||
assert.match(routesSource, /permission: 'finance:bill:view'/)
|
assert.match(routesSource, /permission: 'finance:bill:view'/)
|
||||||
@@ -52,8 +55,10 @@ test('adapts the Finance Java DTO contract and filters nested receipt allocation
|
|||||||
assert.doesNotMatch(adapterSource, /bill_no|customer_name|bill_date|total_amount|outstanding_amount|receipt_no|bill_id|applied_amount/)
|
assert.doesNotMatch(adapterSource, /bill_no|customer_name|bill_date|total_amount|outstanding_amount|receipt_no|bill_id|applied_amount/)
|
||||||
assert.doesNotMatch(adapterSource, /receipt\.billId|receipt\.appliedAmount/)
|
assert.doesNotMatch(adapterSource, /receipt\.billId|receipt\.appliedAmount/)
|
||||||
assert.doesNotMatch(adapterSource, /voucherNo|voucher_no/)
|
assert.doesNotMatch(adapterSource, /voucherNo|voucher_no/)
|
||||||
assert.match(viewSource, /loadDetail\(row\.id\)/)
|
assert.match(viewSource, /name: 'finance-bill-detail', params: \{ billNo: row\.billNo \}/)
|
||||||
assert.doesNotMatch(viewSource, /loadDetail\(row\.billNo\)/)
|
assert.match(detailViewSource, /getMerchantFinanceBill\(summary\.id\)/)
|
||||||
|
assert.match(detailViewSource, /getMerchantFinanceReceipts\(summary\.id\)/)
|
||||||
|
assert.doesNotMatch(detailViewSource, /getMerchantFinanceBill\(billNo\.value\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('does not expose draft or voided bills returned by the server', () => {
|
test('does not expose draft or voided bills returned by the server', () => {
|
||||||
@@ -92,7 +97,7 @@ test('maps nested bill detail and customer-safe receipt allocations', () => {
|
|||||||
receivedAmount: '40.00', outstandingAmount: '60.00',
|
receivedAmount: '40.00', outstandingAmount: '60.00',
|
||||||
version: 3, customerConfirmationStatus: 'PENDING_CONFIRMATION', customerConfirmedByName: null, customerConfirmedAt: null,
|
version: 3, customerConfirmationStatus: 'PENDING_CONFIRMATION', customerConfirmedByName: null, customerConfirmedAt: null,
|
||||||
},
|
},
|
||||||
lines: [{ id: 21, sourceType: 'INBOUND_FEE', sourceId: 81, sourceVersion: 3, orderId: 31, inboundId: 41, feeItemCode: 'FREIGHT', feeItemName: '运费', amount: '100.00', currency: 'CNY' }],
|
lines: [{ id: 21, sourceType: 'INBOUND_FEE', sourceId: 81, sourceVersion: 3, orderId: 31, inboundId: 41, inboundCode: 'NYEXX2608180003', feeItemCode: 'FREIGHT', feeItemName: '运费', amount: '100.00', currency: 'CNY' }],
|
||||||
})
|
})
|
||||||
const receipts = financeAdapters.mapFinanceReceipts([{
|
const receipts = financeAdapters.mapFinanceReceipts([{
|
||||||
id: 51, receiptNo: 'RCPT-51', receivedAmount: '40.00', receivedAt: '2026-08-12T10:00:00',
|
id: 51, receiptNo: 'RCPT-51', receivedAmount: '40.00', receivedAt: '2026-08-12T10:00:00',
|
||||||
@@ -101,7 +106,7 @@ test('maps nested bill detail and customer-safe receipt allocations', () => {
|
|||||||
}], '2')
|
}], '2')
|
||||||
|
|
||||||
assert.equal(detail.billNo, 'B-2')
|
assert.equal(detail.billNo, 'B-2')
|
||||||
assert.deepEqual(detail.lines[0], { id: '21', orderId: '31', feeNo: 'INBOUND_FEE:81/v3', feeName: '运费', amount: '100.00', currencyCode: 'CNY' })
|
assert.deepEqual(detail.lines[0], { id: '21', orderId: '31', inboundCode: 'NYEXX2608180003', feeNo: 'INBOUND_FEE:81/v3', feeName: '运费', amount: '100.00', currencyCode: 'CNY' })
|
||||||
assert.deepEqual(receipts[0], { id: '51', receiptNo: 'RCPT-51', receivedAt: '2026-08-12T10:00:00', amount: '40.00', currencyCode: 'CNY', method: 'BANK_TRANSFER', allocatedAmount: '40.00' })
|
assert.deepEqual(receipts[0], { id: '51', receiptNo: 'RCPT-51', receivedAt: '2026-08-12T10:00:00', amount: '40.00', currencyCode: 'CNY', method: 'BANK_TRANSFER', allocatedAmount: '40.00' })
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -114,24 +119,44 @@ test('requires both finance statement authorities for the page permission', () =
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('keeps actions first and exposes list, balance, detail, confirmation, receipt, empty and error states', () => {
|
test('keeps actions first and exposes list, balance, detail, confirmation, receipt, empty and error states', () => {
|
||||||
const actionIndex = viewSource.indexOf('label="操作"')
|
const tableDefinition = viewSource.slice(viewSource.indexOf('const tableColumns'))
|
||||||
const billNumberIndex = viewSource.indexOf('label="账单编号"')
|
const actionIndex = tableDefinition.indexOf("label: '操作'")
|
||||||
|
const billNumberIndex = tableDefinition.indexOf("label: '账单编号'")
|
||||||
assert.ok(actionIndex >= 0 && actionIndex < billNumberIndex)
|
assert.ok(actionIndex >= 0 && actionIndex < billNumberIndex)
|
||||||
for (const expected of ['未收余额', '账单详情', '确认账单', '客户确认信息', '收款记录', '暂无账单', '暂无收款记录', 'state-panel--error']) {
|
for (const expected of ['未收余额', '确认账单', '暂无账单', 'state-panel--error']) {
|
||||||
assert.match(viewSource, new RegExp(expected))
|
assert.match(viewSource, new RegExp(expected))
|
||||||
}
|
}
|
||||||
|
for (const expected of ['账单概览', '费用明细', '收款记录', '暂无收款记录']) assert.match(detailViewSource, new RegExp(expected))
|
||||||
|
assert.match(detailViewSource, /BANK_TRANSFER: '银行转账'/)
|
||||||
|
assert.match(detailViewSource, /paymentMethodLabel\(row\.method\)/)
|
||||||
|
assert.match(detailViewSource, /label: '入仓码'/)
|
||||||
|
assert.match(detailViewSource, /openInboundAssociation\(row\.inboundCode\)/)
|
||||||
|
assert.match(detailViewSource, /InboundCodeAssociationDialog/)
|
||||||
|
assert.match(detailViewSource, /:inbound-code="inboundAssociationCode"/)
|
||||||
assert.match(viewSource, /auth\.hasPermission\('finance:bill:confirm'\)/)
|
assert.match(viewSource, /auth\.hasPermission\('finance:bill:confirm'\)/)
|
||||||
assert.match(viewSource, /row\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm/)
|
assert.match(viewSource, /statement\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm\.value/)
|
||||||
assert.match(viewSource, /size="small" type="success" plain/)
|
assert.match(viewSource, /label: '确认账单'/)
|
||||||
assert.match(viewSource, /confirmStatement\(row as FinanceBillSummary\)/)
|
assert.match(viewSource, /run: \(\) => confirmStatement\(statement\)/)
|
||||||
assert.match(viewSource, /detail\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm/)
|
assert.match(detailViewSource, /detail\.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm/)
|
||||||
assert.match(viewSource, /confirmStatement\(detail\)/)
|
assert.match(detailViewSource, /confirmStatement\(detail\)/)
|
||||||
assert.match(viewSource, /confirmMerchantFinanceStatement\(statementId, statement\.version, key\)/)
|
assert.match(viewSource, /confirmMerchantFinanceStatement\(statementId, statement\.version, key\)/)
|
||||||
assert.match(viewSource, /ElMessage\.success\('对账单已确认'\)/)
|
assert.match(viewSource, /ElMessage\.success\('对账单已确认'\)/)
|
||||||
assert.match(viewSource, /ElMessage\.error\(error instanceof ApiError \? error\.message : '对账单确认失败,请重试'\)/)
|
assert.match(viewSource, /ElMessage\.error\(error instanceof ApiError \? error\.message : '对账单确认失败,请重试'\)/)
|
||||||
for (const forbidden of ['发起争议', '新增收款', '核销', '修改金额']) {
|
for (const forbidden of ['发起争议', '新增收款', '核销', '修改金额']) {
|
||||||
assert.doesNotMatch(viewSource, new RegExp(forbidden))
|
assert.doesNotMatch(viewSource, new RegExp(forbidden))
|
||||||
|
assert.doesNotMatch(detailViewSource, new RegExp(forbidden))
|
||||||
}
|
}
|
||||||
|
assert.doesNotMatch(viewSource, /<el-drawer|InboundCodeAssociationDialog/)
|
||||||
|
assert.match(detailViewSource, /class="bill-detail-surface"/)
|
||||||
|
assert.match(detailViewSource, /bill-detail-error/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('uses the shared compact query, table and pagination layout', () => {
|
||||||
|
assert.match(viewSource, /<QueryToolbar[^>]*layout="grid"/)
|
||||||
|
assert.match(viewSource, /<DataTable[^>]*:row-actions="rowActions"/)
|
||||||
|
assert.match(viewSource, /v-model:page="page" v-model:page-size="pageSize"/)
|
||||||
|
assert.match(viewSource, /:page-sizes="\[20, 50, 100\]"/)
|
||||||
|
assert.doesNotMatch(viewSource, /class="filter-bar"|class="pagination-row"|class="table-empty"/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('keeps the existing customer finance view permission mapping', () => {
|
test('keeps the existing customer finance view permission mapping', () => {
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, reactive, ref } from 'vue'
|
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||||
import { CircleDollarSign, Eye, RefreshCcw, Search } from '@lucide/vue'
|
import { RefreshCcw } from '@lucide/vue'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
import { ApiError } from '@/api/http'
|
import { ApiError } from '@/api/http'
|
||||||
|
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||||
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
|
import type { TableAction } from '@/components/common/tableActions'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
import { confirmMerchantFinanceStatement, getMerchantFinanceBill, getMerchantFinanceBills, getMerchantFinanceReceipts } from '../api/finance'
|
import { confirmMerchantFinanceStatement, getMerchantFinanceBills } from '../api/finance'
|
||||||
import type { FinanceBillDetail, FinanceBillQuery, FinanceBillStatus, FinanceBillSummary, FinanceCustomerConfirmationStatus } from '../contracts'
|
import type { FinanceBillQuery, FinanceBillStatus, FinanceBillSummary, FinanceCustomerConfirmationStatus } from '../contracts'
|
||||||
|
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
const detailLoading = ref(false)
|
const router = useRouter()
|
||||||
const errorMessage = ref('')
|
const errorMessage = ref('')
|
||||||
const detailError = ref('')
|
|
||||||
const bills = ref<FinanceBillSummary[]>([])
|
const bills = ref<FinanceBillSummary[]>([])
|
||||||
const detail = ref<FinanceBillDetail | null>(null)
|
|
||||||
const selectedBillId = ref('')
|
|
||||||
const detailVisible = ref(false)
|
|
||||||
const confirmingBillId = ref('')
|
const confirmingBillId = ref('')
|
||||||
const confirmationKeys = new Map<string, string>()
|
const confirmationKeys = new Map<string, string>()
|
||||||
const page = ref(1)
|
const page = ref(1)
|
||||||
@@ -31,7 +31,23 @@ const statusOptions: Array<{ label: string; value: FinanceBillStatus }> = [
|
|||||||
{ label: '作废', value: 'VOIDED' },
|
{ label: '作废', value: 'VOIDED' },
|
||||||
]
|
]
|
||||||
|
|
||||||
const hasData = computed(() => bills.value.length > 0)
|
const queryModel = ref<QueryModel>({ keyword: '', status: '' })
|
||||||
|
const queryFields: QueryField[] = [
|
||||||
|
{ key: 'keyword', label: '账单编号', type: 'input', placeholder: '请输入账单编号' },
|
||||||
|
{ key: 'status', label: '账单状态', type: 'select', placeholder: '全部', options: statusOptions },
|
||||||
|
]
|
||||||
|
const tableColumns: DataTableColumn[] = [
|
||||||
|
{ label: '操作', slotName: 'actions', width: 190, fixed: 'left' },
|
||||||
|
{ label: '账单编号', prop: 'billNo', minWidth: 160 },
|
||||||
|
{ label: '出账日期', slotName: 'issueDate', width: 120 },
|
||||||
|
{ label: '到期日', slotName: 'dueDate', width: 120 },
|
||||||
|
{ label: '账单金额', slotName: 'totalAmount', width: 145, align: 'right' },
|
||||||
|
{ label: '已收', slotName: 'receivedAmount', width: 145, align: 'right' },
|
||||||
|
{ label: '未收余额', slotName: 'outstandingAmount', width: 145, align: 'right' },
|
||||||
|
{ label: '状态', slotName: 'status', width: 110 },
|
||||||
|
{ label: '客户确认', slotName: 'confirmationStatus', width: 110 },
|
||||||
|
]
|
||||||
|
|
||||||
const canConfirm = computed(() => auth.hasPermission('finance:bill:confirm'))
|
const canConfirm = computed(() => auth.hasPermission('finance:bill:confirm'))
|
||||||
|
|
||||||
function formatAmount(value: string | null | undefined) {
|
function formatAmount(value: string | null | undefined) {
|
||||||
@@ -45,10 +61,6 @@ function formatDate(value: string | null | undefined) {
|
|||||||
return value.slice(0, 10)
|
return value.slice(0, 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDateTime(value: string | null | undefined) {
|
|
||||||
return value ? value.replace('T', ' ').replace(/Z$/, '').slice(0, 16) : '-'
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusLabel(status: FinanceBillStatus) {
|
function statusLabel(status: FinanceBillStatus) {
|
||||||
return ({ DRAFT: '草稿', ISSUED: '已出账', PARTIALLY_PAID: '部分收款', PAID: '已收清', VOIDED: '作废' })[status] ?? status
|
return ({ DRAFT: '草稿', ISSUED: '已出账', PARTIALLY_PAID: '部分收款', PAID: '已收清', VOIDED: '作废' })[status] ?? status
|
||||||
}
|
}
|
||||||
@@ -92,24 +104,21 @@ async function loadBills(nextPage = page.value) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function openDetail(row: FinanceBillSummary) {
|
function openDetail(row: FinanceBillSummary) { void router.push({ name: 'finance-bill-detail', params: { billNo: row.billNo } }) }
|
||||||
selectedBillId.value = row.id
|
|
||||||
await loadDetail(row.id)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadDetail(billId: string) {
|
function rowActions(row: object): TableAction[] {
|
||||||
detailVisible.value = true
|
const statement = row as FinanceBillSummary
|
||||||
detailLoading.value = true
|
const actions: TableAction[] = [{ key: 'detail', label: '查看', run: () => openDetail(statement) }]
|
||||||
detailError.value = ''
|
if (statement.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm.value) {
|
||||||
detail.value = null
|
actions.push({
|
||||||
try {
|
key: 'confirm',
|
||||||
const [bill, receipts] = await Promise.all([getMerchantFinanceBill(billId), getMerchantFinanceReceipts(billId)])
|
label: '确认账单',
|
||||||
detail.value = { ...bill, receipts }
|
loading: confirmingBillId.value === statement.id,
|
||||||
} catch (error) {
|
disabled: Boolean(confirmingBillId.value),
|
||||||
detailError.value = messageOf(error)
|
run: () => confirmStatement(statement),
|
||||||
} finally {
|
})
|
||||||
detailLoading.value = false
|
|
||||||
}
|
}
|
||||||
|
return actions
|
||||||
}
|
}
|
||||||
|
|
||||||
async function confirmStatement(statement: FinanceBillSummary) {
|
async function confirmStatement(statement: FinanceBillSummary) {
|
||||||
@@ -135,9 +144,7 @@ async function confirmStatement(statement: FinanceBillSummary) {
|
|||||||
await confirmMerchantFinanceStatement(statementId, statement.version, key)
|
await confirmMerchantFinanceStatement(statementId, statement.version, key)
|
||||||
confirmationKeys.delete(statementId)
|
confirmationKeys.delete(statementId)
|
||||||
ElMessage.success('对账单已确认')
|
ElMessage.success('对账单已确认')
|
||||||
const refreshes: Array<Promise<void>> = [loadBills(page.value)]
|
await loadBills(page.value)
|
||||||
if (detailVisible.value && selectedBillId.value === statementId) refreshes.push(loadDetail(statementId))
|
|
||||||
await Promise.all(refreshes)
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
ElMessage.error(error instanceof ApiError ? error.message : '对账单确认失败,请重试')
|
ElMessage.error(error instanceof ApiError ? error.message : '对账单确认失败,请重试')
|
||||||
} finally {
|
} finally {
|
||||||
@@ -145,16 +152,19 @@ async function confirmStatement(statement: FinanceBillSummary) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetFilters() {
|
function applyQuery(model: QueryModel) {
|
||||||
filters.keyword = ''
|
filters.keyword = String(model.keyword || '')
|
||||||
filters.status = undefined
|
filters.status = (model.status || undefined) as FinanceBillStatus | undefined
|
||||||
void loadBills(1)
|
if (page.value !== 1) page.value = 1
|
||||||
|
else void loadBills(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
function handlePageChange(nextPage: number) {
|
function resetFilters(model: QueryModel) {
|
||||||
void loadBills(nextPage)
|
queryModel.value = model
|
||||||
|
applyQuery(model)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
watch([page, pageSize], () => { void loadBills(page.value) })
|
||||||
onMounted(() => { void loadBills(1) })
|
onMounted(() => { void loadBills(1) })
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -166,64 +176,29 @@ onMounted(() => { void loadBills(1) })
|
|||||||
<span class="amount-warning">未收 <strong>¥ {{ formatAmount(totals.outstanding) }}</strong></span>
|
<span class="amount-warning">未收 <strong>¥ {{ formatAmount(totals.outstanding) }}</strong></span>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="客户账单筛选" :fields="queryFields" :search-on-reset="false" @search="applyQuery" @reset="resetFilters" />
|
||||||
|
|
||||||
<section class="content-card">
|
<section class="content-card">
|
||||||
<form class="filter-bar" @submit.prevent="loadBills(1)">
|
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="bills" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[20, 50, 100]" :row-actions="rowActions" row-key="billNo" empty-text="暂无账单">
|
||||||
<el-input v-model="filters.keyword" clearable placeholder="搜索账单编号" aria-label="搜索账单编号" class="keyword-input">
|
<template v-if="errorMessage" #error><div class="state-panel state-panel--error" role="alert"><p>{{ errorMessage }}</p><el-button @click="loadBills(1)"><RefreshCcw :size="15" />重试</el-button></div></template>
|
||||||
<template #prefix><Search :size="16" /></template>
|
<template #issueDate="{ row }">{{ formatDate(row.issueDate) }}</template>
|
||||||
</el-input>
|
<template #dueDate="{ row }">{{ formatDate(row.dueDate) }}</template>
|
||||||
<el-select v-model="filters.status" clearable placeholder="全部状态" aria-label="账单状态" class="status-select">
|
<template #totalAmount="{ row }">¥ {{ formatAmount(row.totalAmount) }}</template>
|
||||||
<el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value" />
|
<template #receivedAmount="{ row }">¥ {{ formatAmount(row.receivedAmount) }}</template>
|
||||||
</el-select>
|
<template #outstandingAmount="{ row }"><strong :class="{ 'amount-warning': row.outstandingAmount !== '0' }">¥ {{ formatAmount(row.outstandingAmount) }}</strong></template>
|
||||||
<el-button type="primary" native-type="submit" :loading="loading">查询</el-button>
|
<template #status="{ row }"><el-tag :type="statusType(row.status)">{{ statusLabel(row.status) }}</el-tag></template>
|
||||||
<el-button :disabled="loading" @click="resetFilters">重置</el-button>
|
<template #confirmationStatus="{ row }"><el-tag :type="confirmationType(row.customerConfirmationStatus)">{{ confirmationLabel(row.customerConfirmationStatus) }}</el-tag></template>
|
||||||
</form>
|
</DataTable>
|
||||||
|
|
||||||
<div v-if="errorMessage" class="state-panel state-panel--error" role="alert">
|
|
||||||
<p>{{ errorMessage }}</p>
|
|
||||||
<el-button @click="loadBills(1)"><RefreshCcw :size="15" />重试</el-button>
|
|
||||||
</div>
|
|
||||||
<el-table v-else v-loading="loading" :data="bills" row-key="billNo" class="finance-table" aria-label="客户账单列表">
|
|
||||||
<el-table-column label="操作" width="190" fixed="left">
|
|
||||||
<template #default="{ row }"><div class="table-actions"><el-button link type="primary" @click="openDetail(row as FinanceBillSummary)"><Eye :size="15" />查看</el-button><el-button v-if="row.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm" size="small" type="success" plain :loading="confirmingBillId === row.id" :disabled="Boolean(confirmingBillId)" @click="confirmStatement(row as FinanceBillSummary)">确认账单</el-button></div></template>
|
|
||||||
</el-table-column>
|
|
||||||
<el-table-column prop="billNo" label="账单编号" min-width="160" />
|
|
||||||
<el-table-column prop="issueDate" label="出账日期" width="120"><template #default="{ row }">{{ formatDate(row.issueDate) }}</template></el-table-column>
|
|
||||||
<el-table-column prop="dueDate" label="到期日" width="120"><template #default="{ row }">{{ formatDate(row.dueDate) }}</template></el-table-column>
|
|
||||||
<el-table-column label="账单金额" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.totalAmount) }}</template></el-table-column>
|
|
||||||
<el-table-column label="已收" width="145" align="right"><template #default="{ row }">¥ {{ formatAmount(row.receivedAmount) }}</template></el-table-column>
|
|
||||||
<el-table-column label="未收余额" width="145" align="right"><template #default="{ row }"><strong :class="{ 'amount-warning': row.outstandingAmount !== '0' }">¥ {{ formatAmount(row.outstandingAmount) }}</strong></template></el-table-column>
|
|
||||||
<el-table-column label="状态" width="110"><template #default="{ row }"><el-tag :type="statusType(row.status)">{{ statusLabel(row.status) }}</el-tag></template></el-table-column>
|
|
||||||
<el-table-column label="客户确认" width="110"><template #default="{ row }"><el-tag :type="confirmationType(row.customerConfirmationStatus)">{{ confirmationLabel(row.customerConfirmationStatus) }}</el-tag></template></el-table-column>
|
|
||||||
<template #empty><div class="table-empty"><CircleDollarSign :size="32" /><strong>暂无账单</strong><span>平台财务出账后,这里会显示本企业账单。</span></div></template>
|
|
||||||
</el-table>
|
|
||||||
|
|
||||||
<div v-if="!errorMessage && hasData" class="pagination-row"><span>共 {{ total }} 条</span><el-pagination v-model:current-page="page" :page-size="pageSize" layout="prev, pager, next" :total="total" @current-change="handlePageChange" /></div>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<el-drawer v-model="detailVisible" title="账单详情" size="min(680px, 100%)" destroy-on-close>
|
|
||||||
<div v-loading="detailLoading" class="detail-content">
|
|
||||||
<div v-if="detailError" class="state-panel state-panel--error" role="alert"><p>{{ detailError }}</p><el-button @click="loadDetail(selectedBillId)">重试</el-button></div>
|
|
||||||
<template v-else-if="detail">
|
|
||||||
<div class="detail-heading"><div><h2>{{ detail.billNo }}</h2><p>出账 {{ formatDate(detail.issueDate) }} · 到期 {{ formatDate(detail.dueDate) }} · 未收 <strong class="amount-warning">¥ {{ formatAmount(detail.outstandingAmount) }}</strong></p></div><div class="detail-statuses"><el-tag :type="statusType(detail.status)">{{ statusLabel(detail.status) }}</el-tag><el-tag :type="confirmationType(detail.customerConfirmationStatus)">{{ confirmationLabel(detail.customerConfirmationStatus) }}</el-tag></div></div>
|
|
||||||
<section class="confirmation-panel" aria-label="客户确认信息"><div><strong>{{ confirmationLabel(detail.customerConfirmationStatus) }}</strong><p v-if="detail.customerConfirmationStatus === 'CONFIRMED'">{{ detail.customerConfirmedByName || '当前企业成员' }} · {{ formatDateTime(detail.customerConfirmedAt) }}</p><p v-else>请核对本期金额和费用明细,确认后将记录当前登录成员与确认时间。</p></div><el-button v-if="detail.customerConfirmationStatus === 'PENDING_CONFIRMATION' && canConfirm" type="primary" :loading="confirmingBillId === detail.id" :disabled="Boolean(confirmingBillId)" @click="confirmStatement(detail)">确认账单</el-button></section>
|
|
||||||
<section class="detail-section"><h3>费用明细</h3><el-table :data="detail.lines" size="small"><el-table-column prop="feeName" label="费用项目" min-width="180" /><el-table-column label="金额" width="130" align="right"><template #default="{ row }">¥ {{ formatAmount(row.amount) }}</template></el-table-column></el-table></section>
|
|
||||||
<section class="detail-section"><h3>收款记录</h3><el-table v-if="detail.receipts.length" :data="detail.receipts" size="small"><el-table-column prop="receivedAt" label="收款日期" width="110"><template #default="{ row }">{{ formatDate(row.receivedAt) }}</template></el-table-column><el-table-column prop="receiptNo" label="收款编号" min-width="130" /><el-table-column label="本次金额" width="130" align="right"><template #default="{ row }">¥ {{ formatAmount(row.allocatedAmount) }}</template></el-table-column><el-table-column prop="method" label="方式" min-width="100" /></el-table><div v-else class="sub-empty">暂无收款记录</div></section>
|
|
||||||
<p class="readonly-notice">如对账单内容有疑问,请先线下联系平台财务,核对无误后再确认。</p>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</el-drawer>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.finance-bills-page { display: flex; flex-direction: column; gap: 12px; }
|
.finance-bills-page { display: flex; flex-direction: column; gap: 12px; }
|
||||||
.finance-summary { display: flex; flex-wrap: wrap; gap: 8px 26px; color: var(--muted); font-size: 13px; }.finance-summary strong { margin-left: 6px; color: var(--navy); font-size: 18px; }.amount-warning, .amount-warning strong { color: #b45309; }
|
.finance-summary { display: flex; flex-wrap: wrap; gap: 8px 26px; color: var(--muted); font-size: 13px; }.finance-summary strong { margin-left: 6px; color: var(--navy); font-size: 18px; }.amount-warning, .amount-warning strong { color: #b45309; }
|
||||||
.content-card { min-width: 0; padding: 16px; border: 1px solid var(--border); border-radius: 8px; background: var(--surface, #fff); }
|
.content-card { min-width: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: var(--surface, #fff); }
|
||||||
.filter-bar { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }.keyword-input { width: 260px; }.status-select { width: 140px; }
|
|
||||||
.finance-table { width: 100%; }.finance-table :deep(.el-button) { display: inline-flex; align-items: center; gap: 4px; }.table-actions { display: flex; align-items: center; gap: 8px; white-space: nowrap; }
|
|
||||||
.state-panel { display: flex; min-height: 180px; align-items: center; justify-content: center; gap: 12px; flex-direction: column; color: var(--muted); text-align: center; }.state-panel p { margin: 0; }.state-panel--error { color: #b42318; background: #fff8f7; border: 1px solid #f5c2bd; border-radius: 6px; }
|
.state-panel { display: flex; min-height: 180px; align-items: center; justify-content: center; gap: 12px; flex-direction: column; color: var(--muted); text-align: center; }.state-panel p { margin: 0; }.state-panel--error { color: #b42318; background: #fff8f7; border: 1px solid #f5c2bd; border-radius: 6px; }
|
||||||
.table-empty { display: flex; align-items: center; flex-direction: column; gap: 8px; padding: 42px 12px; color: var(--muted); }.table-empty strong { color: var(--navy); }.table-empty span { font-size: 12px; }
|
|
||||||
.pagination-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 14px; color: var(--muted); font-size: 12px; }
|
|
||||||
.detail-content { min-height: 300px; }.detail-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.detail-heading h2 { margin: 0 0 5px; color: var(--navy); font-size: 18px; }.detail-heading p { margin: 0; color: var(--muted); font-size: 13px; }.detail-statuses { display: flex; align-items: center; gap: 8px; }.confirmation-panel { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-top: 18px; padding: 14px 16px; border: 1px solid #d7e9e4; border-radius: 8px; background: #f3f9f7; }.confirmation-panel strong { color: var(--navy); }.confirmation-panel p { margin: 4px 0 0; color: var(--muted); font-size: 12px; }.detail-section { margin-top: 22px; }.detail-section h3 { margin: 0 0 10px; color: var(--navy); font-size: 14px; }.sub-empty { padding: 22px; color: var(--muted); font-size: 12px; text-align: center; background: #f7fafb; }.readonly-notice { margin: 22px 0 0; padding: 11px 12px; color: #45615d; background: #edf6f4; font-size: 12px; }
|
.detail-content { min-height: 300px; }.detail-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; }.detail-heading h2 { margin: 0 0 5px; color: var(--navy); font-size: 18px; }.detail-heading p { margin: 0; color: var(--muted); font-size: 13px; }.detail-statuses { display: flex; align-items: center; gap: 8px; }.confirmation-panel { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-top: 18px; padding: 14px 16px; border: 1px solid #d7e9e4; border-radius: 8px; background: #f3f9f7; }.confirmation-panel strong { color: var(--navy); }.confirmation-panel p { margin: 4px 0 0; color: var(--muted); font-size: 12px; }.detail-section { margin-top: 22px; }.detail-section h3 { margin: 0 0 10px; color: var(--navy); font-size: 14px; }.sub-empty { padding: 22px; color: var(--muted); font-size: 12px; text-align: center; background: #f7fafb; }.readonly-notice { margin: 22px 0 0; padding: 11px 12px; color: #45615d; background: #edf6f4; font-size: 12px; }
|
||||||
@media (max-width: 720px) { .keyword-input, .status-select { width: 100%; }.filter-bar > .el-button { flex: 1; }.content-card { padding: 12px; }.pagination-row { align-items: flex-start; flex-direction: column; }.finance-summary { align-items: flex-start; flex-direction: column; gap: 6px; } }
|
@media (max-width: 720px) { .finance-summary { align-items: flex-start; flex-direction: column; gap: 6px; } }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
|
||||||
|
const source = readFileSync(new URL('./customs.ts', import.meta.url), 'utf8')
|
||||||
|
const httpTypes = readFileSync(new URL('../../../api/types.ts', import.meta.url), 'utf8')
|
||||||
|
const httpSource = readFileSync(new URL('../../../api/http.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
test('maps only the frozen merchant container-customs contract', () => {
|
||||||
|
assert.match(source, /type MerchantCustomsStatus = 'WAITING_UPLOAD' \| 'DOCUMENT_UPLOADED' \| 'DECLARING' \| 'CUSTOMS_COMPLETED'/)
|
||||||
|
assert.match(source, /inboundId: string/)
|
||||||
|
assert.match(source, /orderId: string/)
|
||||||
|
assert.match(source, /documentId: string/)
|
||||||
|
assert.match(source, /loadingPlanId: string/)
|
||||||
|
assert.match(source, /getMerchantCustomsForOrder\(orderId: string\)/)
|
||||||
|
assert.doesNotMatch(source, /number \| string/)
|
||||||
|
assert.match(source, /url: `\/merchant\/v1\/customs\/orders\/\$\{encodedId\(orderId\)\}`/)
|
||||||
|
assert.doesNotMatch(source, /customs\/cases|MerchantCustomsCaseDetail|getMerchantCustomsByOrder/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('sends multi-inbound scope, optimistic versions and idempotency for every write', () => {
|
||||||
|
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, 6)
|
||||||
|
assert.match(source, /data\.append\('file', file\)/)
|
||||||
|
assert.match(source, /file\.size > MAX_CUSTOMS_FILE_SIZE/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('preserves request and trace identifiers on API errors', () => {
|
||||||
|
assert.match(httpTypes, /readonly requestId\?: string \| null/)
|
||||||
|
assert.match(httpSource, /envelope\.traceId, envelope\.requestId/)
|
||||||
|
assert.match(source, /interface ApiErrorMeta/)
|
||||||
|
assert.match(source, /requestId: error\.requestId \?\? null/)
|
||||||
|
assert.match(source, /traceId: error\.traceId \?\? null/)
|
||||||
|
})
|
||||||
@@ -1,31 +1,293 @@
|
|||||||
import { ApiError, apiRequest } from '@/api/http'
|
import { ApiError, apiBlobResponseRequest, apiRequest } from '@/api/http'
|
||||||
|
import { createIdempotencyKey } from '@/modules/first-leg/api/firstLeg'
|
||||||
|
|
||||||
export interface MerchantCustomsReceipt {
|
export type MerchantCustomsStatus = 'WAITING_UPLOAD' | 'DOCUMENT_UPLOADED' | 'DECLARING' | 'CUSTOMS_COMPLETED'
|
||||||
id: number | string
|
export type ContainerCustomsStatus = 'WAITING_CUSTOMER_DOCUMENTS' | 'READY_TO_START' | 'DECLARING' | 'COMPLETED'
|
||||||
receiptType: 'RECEIVED' | 'DECLARED' | 'REJECTED' | 'INSPECTION' | 'RELEASED' | 'OTHER' | string
|
|
||||||
receiptVersion: number | null
|
export interface MerchantCustomsFile {
|
||||||
fileName: string | null
|
fileId: string
|
||||||
uploadedAt: string | null
|
fileName: string
|
||||||
|
fileHash: string
|
||||||
|
contentType: string | null
|
||||||
|
sizeBytes: number
|
||||||
|
version: number
|
||||||
|
uploadedAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MerchantCustomsCaseDetail {
|
export interface MerchantCustomsReceiptVersion {
|
||||||
customsCase: {
|
version: number
|
||||||
id: number | string
|
file: MerchantCustomsFile
|
||||||
customsNo: string | null
|
operatorName: string | null
|
||||||
orderId: number | string
|
createdAt: string
|
||||||
status: string | null
|
|
||||||
updatedAt: string | null
|
|
||||||
}
|
|
||||||
receipts: MerchantCustomsReceipt[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getMerchantCustomsByOrder(orderId: number | string) {
|
export type MerchantCustomsConfirmationAction = 'CONFIRM' | 'REJECT'
|
||||||
return apiRequest<MerchantCustomsCaseDetail>({
|
|
||||||
|
export interface MerchantCustomsConfirmationHistory {
|
||||||
|
id: string
|
||||||
|
receiptVersion: number
|
||||||
|
action: MerchantCustomsConfirmationAction
|
||||||
|
reason: string | null
|
||||||
|
operatorName: string
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantCustomsInbound {
|
||||||
|
inboundId: string
|
||||||
|
orderId: string
|
||||||
|
orderNo: string
|
||||||
|
inboundCode: string
|
||||||
|
tenantId: string
|
||||||
|
customerName: string
|
||||||
|
taxMode: 'TAX_REFUND' | 'BUY_DECLARATION'
|
||||||
|
covered: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantCustomsDocument {
|
||||||
|
documentId: string
|
||||||
|
tenantId: string
|
||||||
|
source: MerchantCustomsFile
|
||||||
|
inboundIds: string[]
|
||||||
|
inboundCodes: string[]
|
||||||
|
frozen: boolean
|
||||||
|
receipt: MerchantCustomsFile | null
|
||||||
|
receiptStatus: 'PENDING' | 'CONFIRMED' | 'REJECTED' | null
|
||||||
|
receiptRejectReason: string | null
|
||||||
|
finalDocument: MerchantCustomsFile | null
|
||||||
|
receiptHistory?: MerchantCustomsReceiptVersion[]
|
||||||
|
confirmationHistory: MerchantCustomsConfirmationHistory[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantCustomsContainer {
|
||||||
|
aggregateId: string
|
||||||
|
loadingPlanId: string
|
||||||
|
containerBookingId: string
|
||||||
|
planNo?: string
|
||||||
|
cabinetNo?: string
|
||||||
|
containerNo: string | null
|
||||||
|
status: ContainerCustomsStatus
|
||||||
|
merchantStatus?: MerchantCustomsStatus | null
|
||||||
|
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
|
||||||
|
traceId: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantCustomsDownload {
|
||||||
|
blob: Blob
|
||||||
|
fileName: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MERCHANT_CUSTOMS_STATUS_LABELS: Record<MerchantCustomsStatus, string> = {
|
||||||
|
WAITING_UPLOAD: '待上传资料',
|
||||||
|
DOCUMENT_UPLOADED: '资料已上传',
|
||||||
|
DECLARING: '报关中',
|
||||||
|
CUSTOMS_COMPLETED: '报关完成',
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_CUSTOMS_FILE_SIZE = 50 * 1024 * 1024
|
||||||
|
|
||||||
|
function encodedId(value: string) {
|
||||||
|
return encodeURIComponent(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function inboundQuery(inboundIds: string[]) {
|
||||||
|
const params = new URLSearchParams()
|
||||||
|
inboundIds.forEach((id) => params.append('inboundIds', id))
|
||||||
|
return params.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
function fileBody(file: File) {
|
||||||
|
const data = new FormData()
|
||||||
|
data.append('file', file)
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateMerchantCustomsFile(file: File) {
|
||||||
|
if (file.size > MAX_CUSTOMS_FILE_SIZE) throw new Error('单个文件不能超过 50MB')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMerchantCustomsForOrder(orderId: string) {
|
||||||
|
return apiRequest<MerchantCustomsContainer>({
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
url: `/merchant/v1/customs/orders/${orderId}`,
|
url: `/merchant/v1/customs/orders/${encodedId(orderId)}`,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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>({
|
||||||
|
method: 'POST',
|
||||||
|
url: `/merchant/v1/customs/loading-plans/${encodedId(planId)}/documents/upload?${inboundQuery(inboundIds)}`,
|
||||||
|
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-upload-${planId}`) },
|
||||||
|
data: fileBody(file),
|
||||||
|
timeout: 120_000,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function replaceMerchantCustomsDocument(document: MerchantCustomsDocument, inboundIds: string[], file: File) {
|
||||||
|
validateMerchantCustomsFile(file)
|
||||||
|
const params = new URLSearchParams(inboundQuery(inboundIds))
|
||||||
|
params.set('expectedVersion', String(document.source.version))
|
||||||
|
return apiRequest<MerchantCustomsDocument>({
|
||||||
|
method: 'POST',
|
||||||
|
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}/upload?${params.toString()}`,
|
||||||
|
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-replace-${document.documentId}`) },
|
||||||
|
data: fileBody(file),
|
||||||
|
timeout: 120_000,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMerchantCustomsDocumentInbounds(document: MerchantCustomsDocument, inboundIds: string[]) {
|
||||||
|
return apiRequest<MerchantCustomsDocument>({
|
||||||
|
method: 'PUT',
|
||||||
|
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}/inbounds`,
|
||||||
|
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-scope-${document.documentId}`) },
|
||||||
|
data: { inboundIds, expectedVersion: document.source.version },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteMerchantCustomsDocument(document: MerchantCustomsDocument) {
|
||||||
|
return apiRequest<MerchantCustomsContainer>({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/merchant/v1/customs/documents/${encodedId(document.documentId)}`,
|
||||||
|
headers: { 'Idempotency-Key': createIdempotencyKey(`merchant-customs-delete-${document.documentId}`) },
|
||||||
|
params: { expectedVersion: document.source.version },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function contentDispositionFileName(value: unknown, fallback: string) {
|
||||||
|
if (typeof value !== 'string') return fallback
|
||||||
|
const encoded = value.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||||
|
if (encoded) {
|
||||||
|
try { return decodeURIComponent(encoded) } catch { return fallback }
|
||||||
|
}
|
||||||
|
return value.match(/filename="?([^";]+)"?/i)?.[1] || fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireBinaryDownload(blob: Blob) {
|
||||||
|
if (!blob.type.toLowerCase().includes('json')) return
|
||||||
|
try {
|
||||||
|
const body = JSON.parse(await blob.text()) as { code?: unknown; message?: unknown; requestId?: unknown; traceId?: unknown }
|
||||||
|
if (typeof body.message === 'string') {
|
||||||
|
throw new ApiError(
|
||||||
|
body.message,
|
||||||
|
typeof body.code === 'string' ? body.code : 'DOWNLOAD_FAILED',
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
typeof body.traceId === 'string' ? body.traceId : null,
|
||||||
|
typeof body.requestId === 'string' ? body.requestId : null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof ApiError) throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function download(url: string, fallbackName: string): Promise<MerchantCustomsDownload> {
|
||||||
|
const response = await apiBlobResponseRequest({ method: 'GET', url })
|
||||||
|
await requireBinaryDownload(response.blob)
|
||||||
|
return {
|
||||||
|
blob: response.blob,
|
||||||
|
fileName: contentDispositionFileName(response.headers['content-disposition'], fallbackName),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function downloadMerchantCustomsSource(document: MerchantCustomsDocument) {
|
||||||
|
return download(`/merchant/v1/customs/documents/${encodedId(document.documentId)}/download`, document.source.fileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function downloadMerchantCustomsReceipt(document: MerchantCustomsDocument) {
|
||||||
|
return download(
|
||||||
|
`/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 }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function merchantCustomsErrorMessage(error: unknown, fallback: string) {
|
||||||
|
if (!(error instanceof ApiError)) return error instanceof Error ? error.message : fallback
|
||||||
|
const identifiers = [
|
||||||
|
error.code ? `错误码 ${error.code}` : '',
|
||||||
|
error.requestId ? `请求号 ${error.requestId}` : '',
|
||||||
|
error.traceId ? `追踪号 ${error.traceId}` : '',
|
||||||
|
].filter(Boolean)
|
||||||
|
return `${error.message || fallback}${identifiers.length ? `(${identifiers.join(',')})` : ''}`
|
||||||
|
}
|
||||||
|
|
||||||
export function isMerchantCustomsUnavailable(error: unknown) {
|
export function isMerchantCustomsUnavailable(error: unknown) {
|
||||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export async function getMerchantCustomsPendingCount() {
|
||||||
|
const result = await apiRequest<{ pendingCount: string | number }>({ method: 'GET', url: '/merchant/v1/customs/pending-summary' })
|
||||||
|
const count = Number(result.pendingCount)
|
||||||
|
if (result.pendingCount == null || result.pendingCount === '' || !Number.isSafeInteger(count) || count < 0) throw new Error('报关待办数量返回不完整')
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ export type ApiContainerMode = 'FULL_CONTAINER' | 'LCL'
|
|||||||
export type ApiDestinationType = 'FBA' | 'OVERSEAS' | 'PRIVATE'
|
export type ApiDestinationType = 'FBA' | 'OVERSEAS' | 'PRIVATE'
|
||||||
export type ApiPricingTaxMode = 'TAX_INCLUDED' | 'TAX_EXCLUDED'
|
export type ApiPricingTaxMode = 'TAX_INCLUDED' | 'TAX_EXCLUDED'
|
||||||
export type ApiPriceModel = 'FBA_WAREHOUSE_RATE' | 'REGION_WEIGHT_TIER'
|
export type ApiPriceModel = 'FBA_WAREHOUSE_RATE' | 'REGION_WEIGHT_TIER'
|
||||||
|
export type CustomerOrderAddressType = 'PICKUP' | 'PRIVATE_DESTINATION'
|
||||||
|
export type MerchantBatchImportMode = 'ATOMIC' | 'PARTIAL'
|
||||||
|
|
||||||
export interface PageResult<T> {
|
export interface PageResult<T> {
|
||||||
records: T[]
|
records: T[]
|
||||||
@@ -91,6 +93,7 @@ export interface FirstLegOrderCargoPayload {
|
|||||||
declaredValue?: number
|
declaredValue?: number
|
||||||
currency?: string
|
currency?: string
|
||||||
dangerousGoods?: boolean
|
dangerousGoods?: boolean
|
||||||
|
woodenProduct: boolean
|
||||||
cargoRemark?: string
|
cargoRemark?: string
|
||||||
skuNo?: string
|
skuNo?: string
|
||||||
upcNo?: string
|
upcNo?: string
|
||||||
@@ -110,6 +113,7 @@ export interface FirstLegOrderCargoPayload {
|
|||||||
shipmentId?: string
|
shipmentId?: string
|
||||||
referenceId?: string
|
referenceId?: string
|
||||||
productImageFileId?: number | string
|
productImageFileId?: number | string
|
||||||
|
packingGroupNo?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProductImageUploadResult {
|
export interface ProductImageUploadResult {
|
||||||
@@ -122,6 +126,8 @@ export interface ProductImageUploadResult {
|
|||||||
export interface FirstLegOrderSaveRequest {
|
export interface FirstLegOrderSaveRequest {
|
||||||
inboundCode?: string
|
inboundCode?: string
|
||||||
customerName: string
|
customerName: string
|
||||||
|
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP'
|
||||||
|
lxCode?: string
|
||||||
transportMode: ApiTransportMode
|
transportMode: ApiTransportMode
|
||||||
tradeTerm?: string
|
tradeTerm?: string
|
||||||
destinationCountryCode: string
|
destinationCountryCode: string
|
||||||
@@ -129,8 +135,8 @@ export interface FirstLegOrderSaveRequest {
|
|||||||
destinationWarehouseName: string
|
destinationWarehouseName: string
|
||||||
expectedShipDate?: string
|
expectedShipDate?: string
|
||||||
customerRemark?: string
|
customerRemark?: string
|
||||||
sender?: FirstLegOrderPartyPayload
|
senderAddressId?: number | string
|
||||||
receiver?: FirstLegOrderPartyPayload
|
privateDestinationAddressId?: number | string
|
||||||
cargoes: FirstLegOrderCargoPayload[]
|
cargoes: FirstLegOrderCargoPayload[]
|
||||||
pickupMethod: ApiPickupMethod
|
pickupMethod: ApiPickupMethod
|
||||||
receivingWarehouseId: number | string
|
receivingWarehouseId: number | string
|
||||||
@@ -142,13 +148,33 @@ export interface FirstLegOrderSaveRequest {
|
|||||||
pricingTaxMode: ApiPricingTaxMode
|
pricingTaxMode: ApiPricingTaxMode
|
||||||
taxMode: ApiTaxMode
|
taxMode: ApiTaxMode
|
||||||
containerMode?: ApiContainerMode
|
containerMode?: ApiContainerMode
|
||||||
customsInspection: boolean
|
customsInspection: boolean | null
|
||||||
destinationType: ApiDestinationType
|
destinationType: ApiDestinationType
|
||||||
amazonWarehouseCode?: string
|
amazonWarehouseCode?: string
|
||||||
shipmentId?: string
|
shipmentId?: string
|
||||||
referenceId?: string
|
referenceId?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface CustomerOrderAddressSaveRequest {
|
||||||
|
addressType: CustomerOrderAddressType
|
||||||
|
addressName: string
|
||||||
|
companyName: string
|
||||||
|
contactName: string
|
||||||
|
phone: string
|
||||||
|
email?: string
|
||||||
|
countryCode: string
|
||||||
|
province?: string
|
||||||
|
city: string
|
||||||
|
district?: string
|
||||||
|
addressLine: string
|
||||||
|
postalCode?: string
|
||||||
|
defaultAddress: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CustomerOrderAddress extends CustomerOrderAddressSaveRequest {
|
||||||
|
id: number | string
|
||||||
|
}
|
||||||
|
|
||||||
export interface InboundCodePolicy {
|
export interface InboundCodePolicy {
|
||||||
mode: 'AUTO' | 'LEGACY_MANUAL'
|
mode: 'AUTO' | 'LEGACY_MANUAL'
|
||||||
manualEntryRequired: boolean
|
manualEntryRequired: boolean
|
||||||
@@ -177,12 +203,22 @@ export interface MerchantBatchDraftResponse {
|
|||||||
items: MerchantBatchDraftResult[]
|
items: MerchantBatchDraftResult[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MerchantBatchImportResponse {
|
||||||
|
batchNo: string
|
||||||
|
mode: MerchantBatchImportMode
|
||||||
|
sourceFileId: number | string
|
||||||
|
errorReportFileId: number | string | null
|
||||||
|
result: MerchantBatchDraftResponse
|
||||||
|
}
|
||||||
|
|
||||||
export interface MerchantFirstLegOrder {
|
export interface MerchantFirstLegOrder {
|
||||||
id?: number | string
|
id?: number | string
|
||||||
orderId?: number | string
|
orderId?: number | string
|
||||||
orderNo: string | null
|
orderNo: string | null
|
||||||
customerId: number | string | null
|
customerId: number | string | null
|
||||||
customerName: string
|
customerName: string
|
||||||
|
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||||
|
lxCode?: string | null
|
||||||
status: ApiFirstLegStatus
|
status: ApiFirstLegStatus
|
||||||
transportMode?: ApiTransportMode
|
transportMode?: ApiTransportMode
|
||||||
tradeTerm: string | null
|
tradeTerm: string | null
|
||||||
@@ -203,7 +239,7 @@ export interface MerchantFirstLegOrder {
|
|||||||
carrierName?: string | null
|
carrierName?: string | null
|
||||||
taxMode: ApiTaxMode
|
taxMode: ApiTaxMode
|
||||||
containerMode: ApiContainerMode | null
|
containerMode: ApiContainerMode | null
|
||||||
customsInspection: boolean
|
customsInspection: boolean | null
|
||||||
destinationType: ApiDestinationType
|
destinationType: ApiDestinationType
|
||||||
amazonWarehouseCode: string | null
|
amazonWarehouseCode: string | null
|
||||||
shipmentId: string | null
|
shipmentId: string | null
|
||||||
@@ -238,6 +274,7 @@ export interface MerchantFirstLegOrderRow {
|
|||||||
inboundCode: string | null
|
inboundCode: string | null
|
||||||
channelName: string | null
|
channelName: string | null
|
||||||
destinationType: ApiDestinationType | null
|
destinationType: ApiDestinationType | null
|
||||||
|
pickupMethod: ApiPickupMethod | null
|
||||||
customerName: string | null
|
customerName: string | null
|
||||||
receivingCompanyName: string | null
|
receivingCompanyName: string | null
|
||||||
specificationModel: string | null
|
specificationModel: string | null
|
||||||
@@ -259,6 +296,8 @@ export interface MerchantFirstLegOrderRow {
|
|||||||
inboundedAt: string | null
|
inboundedAt: string | null
|
||||||
businessDate: string | null
|
businessDate: string | null
|
||||||
shipmentId: string | null
|
shipmentId: string | null
|
||||||
|
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||||
|
lxCode?: string | null
|
||||||
createdAt: string
|
createdAt: string
|
||||||
cargoes?: Array<{ skuNo?: string | null }>
|
cargoes?: Array<{ skuNo?: string | null }>
|
||||||
}
|
}
|
||||||
@@ -302,6 +341,13 @@ export function downloadMerchantProductImage(fileId: number | string) {
|
|||||||
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/files/product-images/${fileId}` })
|
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/files/product-images/${fileId}` })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function downloadMerchantFirstLegBatchImportErrorReport(batchNo: string, fileId: number | string) {
|
||||||
|
return apiBlobRequest({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/merchant/v1/files/order-batch-imports/${encodeURIComponent(batchNo)}/error-reports/${encodeURIComponent(String(fileId))}`,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export async function downloadMerchantInboundCartonLabels(inboundId: number | string) {
|
export async function downloadMerchantInboundCartonLabels(inboundId: number | string) {
|
||||||
return downloadMerchantCartonLabelPdf(
|
return downloadMerchantCartonLabelPdf(
|
||||||
`/merchant/v1/first-leg/inbounds/${encodeURIComponent(String(inboundId))}/carton-label-pdf`,
|
`/merchant/v1/first-leg/inbounds/${encodeURIComponent(String(inboundId))}/carton-label-pdf`,
|
||||||
@@ -395,6 +441,7 @@ export interface MerchantPriceEstimateRequest {
|
|||||||
destinationWarehouseId?: number | string
|
destinationWarehouseId?: number | string
|
||||||
destinationName?: string
|
destinationName?: string
|
||||||
pricingTaxMode: ApiPricingTaxMode
|
pricingTaxMode: ApiPricingTaxMode
|
||||||
|
chargeMode?: 'KG' | 'CBM'
|
||||||
actualWeightKg: number
|
actualWeightKg: number
|
||||||
actualVolumeCbm: number
|
actualVolumeCbm: number
|
||||||
}
|
}
|
||||||
@@ -413,15 +460,32 @@ export interface MerchantPriceEstimate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getMerchantWarehouses(params: MerchantWarehouseQuery = {}) {
|
export function getMerchantWarehouses(params: MerchantWarehouseQuery = {}) {
|
||||||
return apiRequest<PageResult<MerchantWarehouse>>({
|
const request = apiRequest<PageResult<MerchantWarehouse>>({
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
url: '/merchant/v1/warehouses',
|
url: '/merchant/v1/warehouses',
|
||||||
params: { page: 1, size: 200, status: 'ACTIVE', ...params },
|
params: { page: 1, size: 200, status: 'ACTIVE', ...params },
|
||||||
})
|
})
|
||||||
|
if (params.warehouseType !== 'OVERSEAS') return request
|
||||||
|
return request.then(async (result) => {
|
||||||
|
const usableRecords = result.records.filter((item) => item.status === 'ACTIVE' && item.warehouseType === 'OVERSEAS')
|
||||||
|
if (usableRecords.length > 0) return { ...result, records: usableRecords }
|
||||||
|
const fallback = await apiRequest<PageResult<MerchantWarehouse>>({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/platform/v1/warehouse-admin',
|
||||||
|
params: { page: params.page || 1, size: params.size || 200, tenantId: 0, warehouseType: 'OVERSEAS', status: 'ACTIVE' },
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
...fallback,
|
||||||
|
records: fallback.records.filter((item) => item.status === 'ACTIVE' && item.warehouseType === 'OVERSEAS'),
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getMerchantWarehouseDetail(id: number | string) {
|
export function getMerchantWarehouseDetail(id: number | string) {
|
||||||
return apiRequest<MerchantWarehouseDetail>({ method: 'GET', url: `/merchant/v1/warehouses/${id}` })
|
return apiRequest<MerchantWarehouseDetail>({ method: 'GET', url: `/merchant/v1/warehouses/${id}` }).catch(async () => {
|
||||||
|
const fallback = await apiRequest<MerchantWarehouseDetail>({ method: 'GET', url: `/platform/v1/warehouse-admin/${encodeURIComponent(id)}`, params: { tenantId: 0 } })
|
||||||
|
return fallback
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getMerchantPricingChannels(originWarehouseId: number | string) {
|
export function getMerchantPricingChannels(originWarehouseId: number | string) {
|
||||||
@@ -452,6 +516,38 @@ export function getMerchantInboundCodePolicy() {
|
|||||||
return apiRequest<InboundCodePolicy>({ method: 'GET', url: '/merchant/v1/orders/first-leg/inbound-code-policy' })
|
return apiRequest<InboundCodePolicy>({ method: 'GET', url: '/merchant/v1/orders/first-leg/inbound-code-policy' })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getMerchantOrderAddresses(addressType?: CustomerOrderAddressType) {
|
||||||
|
return apiRequest<CustomerOrderAddress[]>({ method: 'GET', url: '/merchant/v1/orders/first-leg/addresses', params: { addressType } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMerchantOrderAddress(payload: CustomerOrderAddressSaveRequest) {
|
||||||
|
return apiRequest<number | string>({ method: 'POST', url: '/merchant/v1/orders/first-leg/addresses', data: payload })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateMerchantOrderAddress(id: number | string, payload: CustomerOrderAddressSaveRequest) {
|
||||||
|
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/addresses/${id}`, data: payload })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function disableMerchantOrderAddress(id: number | string) {
|
||||||
|
return apiRequest<void>({ method: 'DELETE', url: `/merchant/v1/orders/first-leg/addresses/${id}` })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function downloadMerchantFirstLegBatchImportTemplate() {
|
||||||
|
return apiBlobRequest({ method: 'GET', url: '/merchant/v1/orders/first-leg/batch-imports/template' })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importMerchantFirstLegOrders(file: File, mode: MerchantBatchImportMode, idempotencyKey: string) {
|
||||||
|
const data = new FormData()
|
||||||
|
data.append('file', file)
|
||||||
|
return apiRequest<MerchantBatchImportResponse>({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/merchant/v1/orders/first-leg/batch-imports',
|
||||||
|
params: { mode },
|
||||||
|
headers: { 'Idempotency-Key': idempotencyKey },
|
||||||
|
data,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
export function createMerchantFirstLegOrder(payload: FirstLegOrderSaveRequest) {
|
export function createMerchantFirstLegOrder(payload: FirstLegOrderSaveRequest) {
|
||||||
return apiRequest<number | string>({
|
return apiRequest<number | string>({
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -470,14 +566,19 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) {
|
export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
|
||||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload })
|
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) {
|
export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
|
||||||
|
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function submitMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number }, idempotencyKey: string) {
|
||||||
return apiRequest<void>({
|
return apiRequest<void>({
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
||||||
|
data: payload,
|
||||||
headers: { 'Idempotency-Key': idempotencyKey },
|
headers: { 'Idempotency-Key': idempotencyKey },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,9 +6,17 @@ const source = readFileSync(new URL('./inboundBilling.ts', import.meta.url), 'ut
|
|||||||
const typesSource = readFileSync(new URL('../types/inboundBilling.ts', import.meta.url), 'utf8')
|
const typesSource = readFileSync(new URL('../types/inboundBilling.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
test('queries the merchant order inbound-billing endpoint without tenant parameters', () => {
|
test('queries the merchant order inbound-billing endpoint without tenant parameters', () => {
|
||||||
assert.match(source, /url: `\/merchant\/v1\/first-leg\/orders\/\$\{orderId\}\/inbound-billing`/)
|
const readSource = source.slice(source.indexOf('export async function getMerchantInboundBilling'), source.indexOf('function createFeeConfirmationKey'))
|
||||||
assert.match(source, /method: 'GET'/)
|
assert.match(readSource, /url: `\/merchant\/v1\/first-leg\/orders\/\$\{orderId\}\/inbound-billing`/)
|
||||||
assert.doesNotMatch(source, /tenantId|method: '(?:POST|PUT|PATCH|DELETE)'/)
|
assert.match(readSource, /method: 'GET'/)
|
||||||
|
assert.doesNotMatch(readSource, /tenantId|method: '(?:POST|PUT|PATCH|DELETE)'/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('confirms the latest customer fee version with an idempotency key', () => {
|
||||||
|
assert.match(source, /function confirmMerchantInboundFee/)
|
||||||
|
assert.match(source, /\/inbound-billing\/confirm/)
|
||||||
|
assert.match(source, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
||||||
|
assert.match(source, /data: \{ expectedFeeVersion \}/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('sanitizes the platform-shaped response into a merchant whitelist', () => {
|
test('sanitizes the platform-shaped response into a merchant whitelist', () => {
|
||||||
@@ -27,3 +35,7 @@ test('keeps all backend Long identifiers as strings', () => {
|
|||||||
assert.doesNotMatch(typesSource, /(?:id|Id): number/)
|
assert.doesNotMatch(typesSource, /(?:id|Id): number/)
|
||||||
assert.doesNotMatch(typesSource, /internalNotes|statusHistory|files/)
|
assert.doesNotMatch(typesSource, /internalNotes|statusHistory|files/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('accepts the one-click dropship palletization process status', () => {
|
||||||
|
assert.match(typesSource, /MerchantInboundProcessStatus[\s\S]*?'WAIT_PALLETIZE'[\s\S]*?'WAIT_SPLIT'/)
|
||||||
|
})
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import type {
|
|||||||
|
|
||||||
interface MerchantInboundBillingWireResponse {
|
interface MerchantInboundBillingWireResponse {
|
||||||
inbound: MerchantInboundResult
|
inbound: MerchantInboundResult
|
||||||
|
measurementSummary: MerchantInboundBilling['measurementSummary']
|
||||||
|
measurementItems: MerchantInboundBilling['measurementItems']
|
||||||
|
billingBasis: MerchantInboundBilling['billingBasis']
|
||||||
latestFee: MerchantInboundFeeSnapshot
|
latestFee: MerchantInboundFeeSnapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,6 +65,8 @@ function sanitizeFee(fee: MerchantInboundFeeSnapshot): MerchantInboundFeeSnapsho
|
|||||||
feeStatus: fee.feeStatus,
|
feeStatus: fee.feeStatus,
|
||||||
inboundId: fee.inboundId,
|
inboundId: fee.inboundId,
|
||||||
inboundCode: fee.inboundCode,
|
inboundCode: fee.inboundCode,
|
||||||
|
measurementId: fee.measurementId == null ? null : String(fee.measurementId),
|
||||||
|
measurementSource: fee.measurementSource,
|
||||||
chargeRuleId: fee.chargeRuleId,
|
chargeRuleId: fee.chargeRuleId,
|
||||||
ruleCode: fee.ruleCode,
|
ruleCode: fee.ruleCode,
|
||||||
chargeRuleVersion: fee.chargeRuleVersion,
|
chargeRuleVersion: fee.chargeRuleVersion,
|
||||||
@@ -98,6 +103,43 @@ function sanitizeFee(fee: MerchantInboundFeeSnapshot): MerchantInboundFeeSnapsho
|
|||||||
confirmedAt: fee.confirmedAt,
|
confirmedAt: fee.confirmedAt,
|
||||||
sentAt: fee.sentAt,
|
sentAt: fee.sentAt,
|
||||||
nextProcessStatus: fee.nextProcessStatus,
|
nextProcessStatus: fee.nextProcessStatus,
|
||||||
|
customerConfirmationStatus: fee.customerConfirmationStatus,
|
||||||
|
customerConfirmedBy: fee.customerConfirmedBy == null ? null : String(fee.customerConfirmedBy),
|
||||||
|
customerConfirmedByName: fee.customerConfirmedByName,
|
||||||
|
customerConfirmedAt: fee.customerConfirmedAt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeMeasurementSummary(item: MerchantInboundBilling['measurementSummary']): MerchantInboundBilling['measurementSummary'] {
|
||||||
|
return {
|
||||||
|
measurementId: item.measurementId == null ? null : String(item.measurementId),
|
||||||
|
sourceType: item.sourceType,
|
||||||
|
measurementStatus: item.measurementStatus,
|
||||||
|
actualPackageCount: item.actualPackageCount,
|
||||||
|
actualGrossWeightKg: item.actualGrossWeightKg,
|
||||||
|
actualNetWeightKg: item.actualNetWeightKg,
|
||||||
|
actualVolumeCbm: item.actualVolumeCbm,
|
||||||
|
volumeWeightKg: item.volumeWeightKg,
|
||||||
|
actualGoodsName: item.actualGoodsName,
|
||||||
|
calculationSource: item.calculationSource,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sanitizeMeasurementItem(item: MerchantInboundBilling['measurementItems'][number]): MerchantInboundBilling['measurementItems'][number] {
|
||||||
|
return {
|
||||||
|
id: String(item.id),
|
||||||
|
itemNo: item.itemNo,
|
||||||
|
boxSpecification: item.boxSpecification,
|
||||||
|
packageCount: item.packageCount,
|
||||||
|
lengthCm: item.lengthCm,
|
||||||
|
widthCm: item.widthCm,
|
||||||
|
heightCm: item.heightCm,
|
||||||
|
unitVolumeCbm: item.unitVolumeCbm,
|
||||||
|
totalVolumeCbm: item.totalVolumeCbm,
|
||||||
|
volumeWeightKg: item.volumeWeightKg,
|
||||||
|
chargeRuleId: item.chargeRuleId == null ? null : String(item.chargeRuleId),
|
||||||
|
coefficientMode: item.coefficientMode,
|
||||||
|
calculationRuleVersion: item.calculationRuleVersion,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,6 +150,9 @@ function sanitizeInboundBilling(response: MerchantInboundBillingWireResponse): M
|
|||||||
publicRemark: response.inbound.publicRemark,
|
publicRemark: response.inbound.publicRemark,
|
||||||
palletLocations: response.inbound.palletLocations.map(sanitizePalletLocation),
|
palletLocations: response.inbound.palletLocations.map(sanitizePalletLocation),
|
||||||
},
|
},
|
||||||
|
measurementSummary: sanitizeMeasurementSummary(response.measurementSummary),
|
||||||
|
measurementItems: (response.measurementItems || []).map(sanitizeMeasurementItem),
|
||||||
|
billingBasis: response.billingBasis,
|
||||||
latestFee: sanitizeFee(response.latestFee),
|
latestFee: sanitizeFee(response.latestFee),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -119,3 +164,19 @@ export async function getMerchantInboundBilling(orderId: string): Promise<Mercha
|
|||||||
})
|
})
|
||||||
return sanitizeInboundBilling(response)
|
return sanitizeInboundBilling(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function createFeeConfirmationKey(orderId: string, feeVersion: number) {
|
||||||
|
const randomPart = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||||
|
return `inbound-fee-confirm-${orderId}-${feeVersion}-${randomPart}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function confirmMerchantInboundFee(orderId: string, expectedFeeVersion: number,
|
||||||
|
idempotencyKey = createFeeConfirmationKey(orderId, expectedFeeVersion)) {
|
||||||
|
const response = await apiRequest<MerchantInboundFeeSnapshot>({
|
||||||
|
method: 'POST',
|
||||||
|
url: `/merchant/v1/first-leg/orders/${encodeURIComponent(orderId)}/inbound-billing/confirm`,
|
||||||
|
headers: { 'Idempotency-Key': idempotencyKey },
|
||||||
|
data: { expectedFeeVersion },
|
||||||
|
})
|
||||||
|
return sanitizeFee(response)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
|
||||||
|
const source = readFileSync(new URL('./inboundCodeAssociations.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
test('queries the customer-scoped inbound-code association without browser-selected customer scope', () => {
|
||||||
|
assert.match(source, /method: 'GET'/)
|
||||||
|
assert.match(source, /`\/merchant\/v1\/orders\/first-leg\/inbound-code-associations\/\$\{encodeURIComponent\(inboundCode\.trim\(\)\)\}`/)
|
||||||
|
assert.doesNotMatch(source, /params:[\s\S]*customerId/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('keeps internal association identifiers as strings without making them display keys', () => {
|
||||||
|
for (const field of ['orderId', 'customerId']) assert.match(source, new RegExp(`${field}: string`))
|
||||||
|
assert.match(source, /destinationWarehouseId: string \| null/)
|
||||||
|
for (const field of ['inboundCode', 'orderNo', 'customerName', 'destinationWarehouseCode', 'destinationWarehouseName']) {
|
||||||
|
assert.match(source, new RegExp(`${field}: string`))
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { apiRequest } from '@/api/http'
|
||||||
|
|
||||||
|
export interface MerchantInboundCodeAssociation {
|
||||||
|
inboundCode: string
|
||||||
|
orderNo: string
|
||||||
|
orderStatus: string
|
||||||
|
orderId: string
|
||||||
|
customerId: string
|
||||||
|
customerName: string
|
||||||
|
destinationType: string
|
||||||
|
destinationCountryCode: string | null
|
||||||
|
destinationWarehouseId: string | null
|
||||||
|
destinationWarehouseCode: string | null
|
||||||
|
destinationWarehouseName: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMerchantInboundCodeAssociation(inboundCode: string) {
|
||||||
|
return apiRequest<MerchantInboundCodeAssociation>({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/merchant/v1/orders/first-leg/inbound-code-associations/${encodeURIComponent(inboundCode.trim())}`,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,11 +1,33 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
test('keeps the merchant unified-order boundary and phase-two WAIT_SPLIT status', () => {
|
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, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
|
||||||
|
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
|
||||||
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_SPLIT'/)
|
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_SPLIT'/)
|
||||||
|
assert.match(source, /fulfillmentType\?: 'STANDARD' \| 'ONE_CLICK_DROPSHIP' \| null/)
|
||||||
|
assert.match(source, /lxCode\?: string \| null/)
|
||||||
assert.match(source, /mainStatus\?: ApiUnifiedOrderMainStatus/)
|
assert.match(source, /mainStatus\?: ApiUnifiedOrderMainStatus/)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import { ApiError, apiRequest } from '@/api/http'
|
import { apiRequest } from '@/api/http'
|
||||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||||
|
|
||||||
export type ApiUnifiedOrderMainStatus =
|
export type ApiUnifiedOrderMainStatus =
|
||||||
| 'PENDING_REVIEW'
|
| 'PENDING_REVIEW'
|
||||||
| 'WAIT_MEASURE'
|
| 'WAIT_MEASURE'
|
||||||
|
| 'WAIT_PALLETIZE'
|
||||||
| 'WAIT_SPLIT'
|
| 'WAIT_SPLIT'
|
||||||
| 'LOADING'
|
| 'LOADING'
|
||||||
| 'LOADED'
|
| 'LOADED'
|
||||||
| 'DELIVERED'
|
| 'DELIVERED'
|
||||||
|
| 'COMPLETED'
|
||||||
|
|
||||||
export interface MerchantUnifiedMeasurementSummary {
|
export interface MerchantUnifiedMeasurementSummary {
|
||||||
reviewStatus: string | null
|
reviewStatus: string | null
|
||||||
@@ -46,16 +48,26 @@ export interface MerchantUnifiedTransportSummary {
|
|||||||
cabinetNo: string | null
|
cabinetNo: string | null
|
||||||
vesselName: string | null
|
vesselName: string | null
|
||||||
voyageNo: string | null
|
voyageNo: string | null
|
||||||
sailingAt: string | null
|
estimatedSailingAt: string | null
|
||||||
portArrivalAt: string | null
|
actualSailingAt: string | null
|
||||||
|
effectiveSailingAt: string | null
|
||||||
|
effectiveSailingAtEstimated: boolean | null
|
||||||
|
estimatedPortArrivalAt: string | null
|
||||||
|
actualPortArrivalAt: string | null
|
||||||
|
effectivePortArrivalAt: string | null
|
||||||
|
effectivePortArrivalAtEstimated: boolean | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MerchantUnifiedOrderRow {
|
export interface MerchantUnifiedOrderRow {
|
||||||
orderId: number | string
|
orderId: number | string
|
||||||
|
orderVersion: number
|
||||||
tenantId: number | string
|
tenantId: number | string
|
||||||
orderNo: string | null
|
orderNo: string | null
|
||||||
mainStatus: ApiUnifiedOrderMainStatus
|
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||||
|
lxCode?: string | null
|
||||||
|
mainStatus: ApiUnifiedOrderMainStatus | 'DRAFT' | 'CANCELLED'
|
||||||
nextAction: string | null
|
nextAction: string | null
|
||||||
|
customerFeeConfirmationRequired: boolean
|
||||||
internalOrderStatus: ApiFirstLegStatus | null
|
internalOrderStatus: ApiFirstLegStatus | null
|
||||||
customerId: number | string | null
|
customerId: number | string | null
|
||||||
customerName: string
|
customerName: string
|
||||||
@@ -72,6 +84,8 @@ export interface MerchantUnifiedOrderRow {
|
|||||||
actualGrossWeightKg: number | null
|
actualGrossWeightKg: number | null
|
||||||
actualVolumeCbm: number | null
|
actualVolumeCbm: number | null
|
||||||
pickupMethod: ApiPickupMethod | null
|
pickupMethod: ApiPickupMethod | null
|
||||||
|
taxMode: ApiTaxMode | null
|
||||||
|
customsInspection: boolean | null
|
||||||
requestedPickupAt: string | null
|
requestedPickupAt: string | null
|
||||||
containerMode: ApiContainerMode | null
|
containerMode: ApiContainerMode | null
|
||||||
destinationType: ApiDestinationType | null
|
destinationType: ApiDestinationType | null
|
||||||
@@ -119,7 +133,25 @@ export interface MerchantUnifiedCustomNode {
|
|||||||
attachmentIds: Array<number | string>
|
attachmentIds: Array<number | string>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MerchantTransportNode {
|
||||||
|
standardNode: string
|
||||||
|
nodeSequence: number
|
||||||
|
providerCode: string | null
|
||||||
|
estimatedAt: string | null
|
||||||
|
actualAt: string | null
|
||||||
|
locationCode: string | null
|
||||||
|
locationName: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantTransportFragment {
|
||||||
|
inboundCode: string | null
|
||||||
|
cabinetNo: string | null
|
||||||
|
containerNo: string | null
|
||||||
|
nodes: MerchantTransportNode[]
|
||||||
|
}
|
||||||
|
|
||||||
export interface MerchantUnifiedOrderDetail {
|
export interface MerchantUnifiedOrderDetail {
|
||||||
|
transportFragments: MerchantTransportFragment[]
|
||||||
summary: MerchantUnifiedOrderRow
|
summary: MerchantUnifiedOrderRow
|
||||||
order: MerchantFirstLegOrderDetail
|
order: MerchantFirstLegOrderDetail
|
||||||
timeline: MerchantUnifiedTimelineEvent[]
|
timeline: MerchantUnifiedTimelineEvent[]
|
||||||
@@ -128,8 +160,12 @@ export interface MerchantUnifiedOrderDetail {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface MerchantUnifiedOrderQuery {
|
export interface MerchantUnifiedOrderQuery {
|
||||||
|
taxMode?: ApiTaxMode
|
||||||
|
loaded?: boolean
|
||||||
keyword?: string
|
keyword?: string
|
||||||
|
fbaCode?: string
|
||||||
orderNo?: string
|
orderNo?: string
|
||||||
|
inboundCode?: string
|
||||||
mainStatus?: ApiUnifiedOrderMainStatus
|
mainStatus?: ApiUnifiedOrderMainStatus
|
||||||
receivingWarehouseId?: number | string
|
receivingWarehouseId?: number | string
|
||||||
destinationWarehouseId?: number | string
|
destinationWarehouseId?: number | string
|
||||||
@@ -141,6 +177,37 @@ export interface MerchantUnifiedOrderQuery {
|
|||||||
|
|
||||||
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
||||||
|
|
||||||
|
export type OrderQueue = 'all' | 'fee' | 'customs' | 'draft' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
|
||||||
|
export type OrderProgressStage = 'none' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
|
||||||
|
export interface MerchantOrderProgress { orderId: string | number; stage: OrderProgressStage; partial: boolean }
|
||||||
|
export type OrderQueueCounts = Record<OrderQueue, number>
|
||||||
|
|
||||||
|
export interface MerchantOrderWorkbenchQuery {
|
||||||
|
cargoKeyword?: string
|
||||||
|
receivingWarehouseId?: string
|
||||||
|
channelName?: string
|
||||||
|
destinationType?: string
|
||||||
|
trackingNumber?: string
|
||||||
|
mainStatus?: string
|
||||||
|
createdFrom?: string
|
||||||
|
createdTo?: string
|
||||||
|
queue?: OrderQueue
|
||||||
|
page?: number
|
||||||
|
size?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantOrderWorkbench {
|
||||||
|
page: PageResult<MerchantUnifiedOrderRow>
|
||||||
|
queues: OrderQueueCounts
|
||||||
|
progress: MerchantOrderProgress[]
|
||||||
|
channelNames: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMerchantOrderWorkbench(params: MerchantOrderWorkbenchQuery = {}) {
|
||||||
|
return apiRequest<MerchantOrderWorkbench>({ method: 'GET', url: `${unifiedOrderBaseUrl}/workbench`,
|
||||||
|
params: { ...params, page: params.page ?? 1, size: params.size ?? 10 } })
|
||||||
|
}
|
||||||
|
|
||||||
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
||||||
const { page, size, ...filters } = params
|
const { page, size, ...filters } = params
|
||||||
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
||||||
@@ -156,7 +223,3 @@ export function getMerchantUnifiedOrder(orderId: number | string) {
|
|||||||
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isUnifiedOrderQueryUnavailable(error: unknown) {
|
|
||||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
|
||||||
}
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user