发布当前测试版本至临时灰度环境 #11
+3
-1
@@ -4,6 +4,8 @@
|
||||
dist
|
||||
node_modules
|
||||
node_modules.broken-by-path
|
||||
.env.local
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
+7
-2
@@ -1,5 +1,10 @@
|
||||
VITE_API_BASE_URL=/api
|
||||
VITE_OVERSEAS_API_BASE_URL=/overseas-api
|
||||
OVERSEAS_API_PROXY_TARGET=http://127.0.0.1:9300
|
||||
API_PROXY_TARGET=http://127.0.0.1:9000
|
||||
VITE_ADMIN_WEB_ORIGIN=http://localhost:5173
|
||||
|
||||
# Test container deployment (Jenkins environment or untracked .env).
|
||||
# API_UPSTREAM: unified Gateway origin, no /api suffix.
|
||||
# TEST_NETWORK: shared test Docker network.
|
||||
API_UPSTREAM=http://gateway:9000
|
||||
TEST_NETWORK=firstleg-test-network
|
||||
IMAGE_TAG=
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
|
||||
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。
|
||||
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及海外 API、海外 Token 或跨区域事件时读取 `../../docs/跨区域认证与服务通信契约.md`。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
||||
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及海外 API、海外 Token 或跨区域事件时读取 `../../docs/统一认证与服务通信契约.md`。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
||||
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
|
||||
|
||||
## 技术基线
|
||||
@@ -26,15 +26,15 @@
|
||||
- 模块内 `store/`:该业务跨页面状态;局部表单状态仍留在页面或组件内。跨模块使用 store 时只能导入其公开 store 文件,不得读取模块内部页面或组件实现。
|
||||
- `src/api/`:只保留 HTTP、会话令牌、响应类型等全局请求基础设施;业务接口放入对应模块的 `api/`。页面不得直接创建独立 Axios 客户端。
|
||||
- 模块之间不得通过相对路径或内部目录穿透;确需协作时只能从目标模块的 `public.ts` 导入。模块内稳定契约放在 `contracts.ts`,稳定的跨应用模型仍应上移到 `@chongchong/shared`。
|
||||
- `VITE_API_BASE_URL`、`VITE_OVERSEAS_API_BASE_URL` 分别控制国内和海外浏览器前缀;`API_PROXY_TARGET`、`OVERSEAS_API_PROXY_TARGET` 只由 Vite 开发代理读取,不进入客户端构建。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
|
||||
- `VITE_API_BASE_URL` 控制唯一浏览器 API 前缀;全部业务共用 `src/api/http.ts` 和同一 Access/Refresh Token。`API_PROXY_TARGET` 仅供本地 Vite 代理连接测试入口,不进入客户端构建。独立海外 HTTP 客户端与代理已移除。新增或变更环境变量时同步更新 `.env.example`,不得提交真实密钥或环境专属凭据。
|
||||
- `src/styles/`:全局设计令牌和布局;优先复用现有 `--primary`、`--navy`、`--border`、`--muted`。
|
||||
- 本应用多个模块稳定复用的前端模型放到应用内 `shared/`,客户工作台专属类型保留在对应业务模块。不要链接应用目录之外的 TypeScript 包,服务端契约以 `baiyue-firstleg` Controller/OpenAPI 为准。
|
||||
|
||||
## 开发环境样式验收
|
||||
## 测试环境样式验收
|
||||
|
||||
- 开发环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。
|
||||
- 测试环境验收使用本轮动态创建并已审核通过的客户管理员,或由用户显式提供的客户账号,不依赖固定业务客户或固定账号。
|
||||
- 账号与密码不写入仓库;从本机未提交环境变量或 `C:/Users/BY-OY/.codex/chongchong-global-dev-acceptance.env` 读取。若显式验收凭据不存在,再向用户索取。
|
||||
- 该身份仅适用于开发环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;开发环境变更时只更新本机凭据。
|
||||
- 当前只有一个测试环境。不要把密码、Token 或真实接口地址写入源码、测试快照、日志或 `AGENTS.md`;测试环境变更时只更新本机凭据。
|
||||
- 由人工使用该身份进入真实页面,按 `1920×1080` 视口和 `100%` 浏览器缩放完成操作与截图,再把截图发送给 AI 核对加载、空态、错误态、权限态和桌面布局;AI 默认不主动调用截图或视觉类技能取证。
|
||||
|
||||
## 模块快速查询
|
||||
@@ -45,7 +45,7 @@
|
||||
|
||||
| 业务 | 模块入口 | 联查模块或服务端 |
|
||||
|---|---|---|
|
||||
| 登录、注册与会话 | `src/modules/auth/`、`src/api/session.ts`、`src/api/http.ts` | Backend `auth/`、`iam/`;正常旋转的国内/海外 Token 会话统一持久化,“记住账号”只记登录标识;访问令牌失效但刷新令牌仍在时先恢复会话,公开认证接口不得携带旧 Token |
|
||||
| 登录、注册与会话 | `src/modules/auth/`、`src/api/session.ts`、`src/api/http.ts` | Backend `auth/`、`iam/`;正常轮换的统一 Access/Refresh Token 会话持久化,“记住账号”只记登录标识;访问令牌失效但刷新令牌仍在时先恢复会话,公开认证接口不得携带旧 Token |
|
||||
| 企业资料、成员与角色 | `src/modules/tenant-management/`、`src/modules/account/` | Backend `iam/`、`auth/`、`file/`;公司联系电话/邮箱是企业资料,不作为登录标识;成员登录手机号可选,修改时同步 Auth、撤销该账号会话并审计。审核必填资质仅营业执照与统一社会信用代码;法人身份证选填,可随营业执照提交,也可在已有营业执照后单独补传或替换。前端角色树到服务端权限的映射统一维护在 `contracts.ts` 的 `FRONTEND_TO_MERCHANT_PERMISSION_CODES`,海外入仓、采购、本土卡车和散板权限必须显式进入该映射 |
|
||||
| 工作台与系统入口 | `src/modules/dashboard/`、`src/modules/system/` | `src/navigation/clientNavigation.ts`、`src/router/index.ts` |
|
||||
| 企业成员消息收件箱 | `src/modules/notifications/` | Backend `iam/src/main/java/com/baiyue/iam/notification/`;列表、详情、已读与未读数契约见 `iam/src/main/resources/openapi/notification-v1.yaml` |
|
||||
@@ -65,7 +65,7 @@
|
||||
- 任何查询和变更都必须以服务端确认的当前租户为边界;绝不从可篡改的前端参数推断授权租户。
|
||||
- 企业成员、角色和权限只能管理当前企业范围。前端隐藏不是安全控制,服务端必须重复校验租户与权限。
|
||||
- 注册时登录手机号同时初始化公司联系电话;注册完成后两者独立维护。企业资料只修改 `contactPhone`,个人资料或成员管理中的登录手机号由 IAM/Auth 同步并撤销该账号现有会话,不得在前端互相回填或联动提交。
|
||||
- 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;国内请求使用国内 Access Token,海外请求统一由 `src/api/overseasHttp.ts` 读取短时海外 Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。
|
||||
- 认证统一经过 `src/modules/auth/store/auth.ts`、`src/api/http.ts`、`src/api/session.ts`;全部请求共用统一 Access Token。启动时 Access Token 已过期但 Refresh Token 仍存在,必须先尝试恢复会话;并发或跨标签页 401 共用一次刷新编排,每个原请求最多重放一次,只有明确 401/会话失效才清理 Token 并保留原路径跳转登录页。登录页“记住账号”只保存登录 ID,不改变 Access/Refresh Token 的持久化与续期策略;页面不要复制令牌逻辑或持久化密码、敏感资质内容。
|
||||
- 当前认证仍包含模拟数据。接入真实 API 后移除对应模拟分支,生产环境不得回退为模拟成功。
|
||||
- 头程订单统一使用当前正式读写契约;不得继续扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API、历史部分响应兼容或其他新旧并跑逻辑。触及该链路时按根无兼容规则同步删除生产分支、类型、文案、Mock 和测试,不以现有代码或测试仍覆盖旧路径作为保留依据。
|
||||
- 注册、上传资质、成员邀请和订单操作必须提供明确校验、幂等保护、提交中状态和可恢复的失败反馈。
|
||||
|
||||
Vendored
+26
-216
@@ -1,250 +1,60 @@
|
||||
def sendProductionWeComNotification(String title, String status, String color, String detail) {
|
||||
withCredentials([string(credentialsId: 'wecom-prod-webhook', variable: 'WECOM_WEBHOOK')]) {
|
||||
String sourceVersion = env.SOURCE_TAG ?: env.GIT_COMMIT ?: '未解析'
|
||||
String duration = currentBuild.durationString?.replace(' and counting', '') ?: '—'
|
||||
String content = """## ${title}
|
||||
> 应用:客户工作台
|
||||
> Job:${env.JOB_NAME}
|
||||
> 构建:[#${env.BUILD_NUMBER}](${env.BUILD_URL})
|
||||
> 提交:${sourceVersion}
|
||||
> 状态:<font color="${color}">${status}</font>
|
||||
${detail}
|
||||
> 耗时:${duration}
|
||||
> 时间:${new Date().format('yyyy-MM-dd HH:mm:ss', TimeZone.getTimeZone('Asia/Shanghai'))}
|
||||
"""
|
||||
String payloadFile = 'wecom-production-notification.json'
|
||||
writeFile(
|
||||
file: payloadFile,
|
||||
text: groovy.json.JsonOutput.toJson([
|
||||
msgtype: 'markdown',
|
||||
markdown: [content: content]
|
||||
]),
|
||||
encoding: 'UTF-8'
|
||||
)
|
||||
sh '''
|
||||
set -eu
|
||||
payload_file='wecom-production-notification.json'
|
||||
trap 'rm -f "$payload_file"' EXIT HUP INT TERM
|
||||
response="$(curl --fail --silent --show-error \
|
||||
-H 'Content-Type: application/json' \
|
||||
--data-binary @"$payload_file" \
|
||||
"$WECOM_WEBHOOK")"
|
||||
printf '%s\n' "$response"
|
||||
printf '%s' "$response" | grep -Eq '"errcode"[[:space:]]*:[[:space:]]*0([[:space:]]*[,}])'
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
pipeline {
|
||||
agent {
|
||||
label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : (env.JOB_BASE_NAME?.endsWith('-dev') ? 'java-dev' : 'java-test')}"
|
||||
}
|
||||
|
||||
environment {
|
||||
DEVELOPMENT_COMPOSE_FILE = 'docker-compose.development.yml'
|
||||
DEVELOPMENT_COMPOSE_PROJECT = 'client-web'
|
||||
REGISTRY_HOST = '172.31.198.7:10082'
|
||||
REGISTRY_CREDENTIALS = 'gitea-registry-token'
|
||||
NODE_BASE_IMAGE = '172.31.198.7:10082/java-project/node:22-alpine'
|
||||
NGINX_BASE_IMAGE = '172.31.198.7:10082/java-project/nginx:1.27-alpine'
|
||||
PRODUCTION_IMAGE_REPOSITORY = 'git.buggoglobal.com/html/client-web'
|
||||
}
|
||||
|
||||
agent { label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : 'java-test'}" }
|
||||
options {
|
||||
timestamps()
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('确认提交版本') {
|
||||
stage('检查测试发布参数') {
|
||||
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||
steps {
|
||||
script {
|
||||
env.IS_DEVELOPMENT = env.JOB_BASE_NAME?.endsWith('-dev') ? 'true' : 'false'
|
||||
env.IS_PRODUCTION = env.JOB_BASE_NAME?.endsWith('-prod') ? 'true' : 'false'
|
||||
if (env.IS_PRODUCTION == 'true') {
|
||||
sh '''
|
||||
set -eu
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)" || {
|
||||
echo "生产部署只允许 origin/main 当前提交;请先合并代码到 main" >&2
|
||||
exit 1
|
||||
}
|
||||
'''
|
||||
if (env.JOB_BASE_NAME?.endsWith('-dev')) {
|
||||
error('此流水线仅支持 test 和本轮授权的 prod 灰度')
|
||||
}
|
||||
env.SOURCE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||
env.IMAGE_TAG = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||
}
|
||||
sh 'git log -1 --oneline'
|
||||
sh '''set -eu
|
||||
export API_UPSTREAM="${API_UPSTREAM:-http://gateway:9000}"
|
||||
export TEST_NETWORK="${TEST_NETWORK:-firstleg-test-network}"
|
||||
: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN 未设置}"
|
||||
docker network inspect "$TEST_NETWORK" >/dev/null
|
||||
docker compose -f docker-compose.test.yml config --quiet
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('构建并部署测试前端') {
|
||||
when { expression { env.IS_DEVELOPMENT != 'true' && env.IS_PRODUCTION != 'true' } }
|
||||
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
|
||||
sh '''
|
||||
set -eu
|
||||
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
mkdir -p "$DOCKER_CONFIG"
|
||||
cleanup_registry() {
|
||||
docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
}
|
||||
trap cleanup_registry EXIT HUP INT TERM
|
||||
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
|
||||
docker compose -f docker-compose.test.yml build --pull=false
|
||||
docker compose -f docker-compose.test.yml up -d --remove-orphans
|
||||
'''
|
||||
}
|
||||
sh '''set -eu
|
||||
docker compose -f docker-compose.test.yml build --pull=false
|
||||
docker compose -f docker-compose.test.yml up -d --wait --wait-timeout 120
|
||||
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
||||
stage('构建并发布生产镜像') {
|
||||
when { expression { env.IS_PRODUCTION == 'true' } }
|
||||
stage('发布临时生产灰度') {
|
||||
when { expression { env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
|
||||
sh '''
|
||||
set -eu
|
||||
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
mkdir -p "$DOCKER_CONFIG"
|
||||
cleanup_registry() {
|
||||
docker logout git.buggoglobal.com >/dev/null 2>&1 || true
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
}
|
||||
trap cleanup_registry EXIT HUP INT TERM
|
||||
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin git.buggoglobal.com
|
||||
image="$PRODUCTION_IMAGE_REPOSITORY:$SOURCE_TAG"
|
||||
docker build \
|
||||
--build-arg NODE_IMAGE="$NODE_BASE_IMAGE" \
|
||||
--build-arg NGINX_IMAGE="$NGINX_BASE_IMAGE" \
|
||||
--build-arg VITE_ADMIN_WEB_ORIGIN=https://admin.buggoglobal.com \
|
||||
-t "$image" .
|
||||
docker push "$image"
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('部署生产前端') {
|
||||
when { expression { env.IS_PRODUCTION == 'true' } }
|
||||
steps {
|
||||
lock(resource: 'firstleg-production-client-web-deploy', inversePrecedence: true) {
|
||||
lock(resource: 'firstleg-production-client-web-deploy') {
|
||||
withCredentials([
|
||||
usernamePassword(credentialsId: 'gitea-registry-token', usernameVariable: 'BUILD_REGISTRY_USER', passwordVariable: 'BUILD_REGISTRY_PASSWORD'),
|
||||
usernamePassword(credentialsId: 'gitea-production-pull-token', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD'),
|
||||
sshUserPrivateKey(credentialsId: 'firstleg-production-ssh', keyFileVariable: 'TARGET_SSH_KEY', usernameVariable: 'TARGET_SSH_USER'),
|
||||
string(credentialsId: 'firstleg-production-host', variable: 'TARGET_SSH_HOST'),
|
||||
file(credentialsId: 'firstleg-production-known-hosts', variable: 'TARGET_SSH_KNOWN_HOSTS')
|
||||
]) {
|
||||
withEnv([
|
||||
'TARGET_DEPLOY_DIR=/data/firstleg/deploy/frontend',
|
||||
'TARGET_SSH_TARGET=' + env.TARGET_SSH_USER + '@' + env.TARGET_SSH_HOST
|
||||
]) {
|
||||
sh "sh scripts/deploy-production.sh client-web '${env.PRODUCTION_IMAGE_REPOSITORY}' '${env.SOURCE_TAG}' docker-compose.production.yml"
|
||||
}
|
||||
sh 'sh scripts/deploy-production.sh'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('构建并部署开发前端') {
|
||||
when { expression { env.IS_DEVELOPMENT == 'true' } }
|
||||
steps {
|
||||
withCredentials([usernamePassword(credentialsId: env.REGISTRY_CREDENTIALS, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
|
||||
sh '''
|
||||
set -eu
|
||||
export DOCKER_CONFIG="${WORKSPACE}@tmp/docker-auth"
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
mkdir -p "$DOCKER_CONFIG"
|
||||
cleanup_registry() {
|
||||
docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true
|
||||
rm -rf "$DOCKER_CONFIG"
|
||||
}
|
||||
trap cleanup_registry EXIT HUP INT TERM
|
||||
printf %s "$REGISTRY_PASSWORD" | docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
|
||||
image="client-web-development:${SOURCE_TAG}"
|
||||
|
||||
docker build \
|
||||
--build-arg NODE_IMAGE="$NODE_BASE_IMAGE" \
|
||||
--build-arg NGINX_IMAGE="$NGINX_BASE_IMAGE" \
|
||||
--build-arg VITE_ADMIN_WEB_ORIGIN=http://8.163.49.32:9001 \
|
||||
-t "$image" .
|
||||
export IMAGE_TAG="$SOURCE_TAG"
|
||||
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" up -d --remove-orphans --pull never
|
||||
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" ps
|
||||
docker compose -p "$DEVELOPMENT_COMPOSE_PROJECT" -f "$DEVELOPMENT_COMPOSE_FILE" exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('部署检查') {
|
||||
when { expression { env.IS_DEVELOPMENT != 'true' && env.IS_PRODUCTION != 'true' } }
|
||||
steps {
|
||||
sh '''
|
||||
set -eu
|
||||
docker compose -f docker-compose.test.yml ps
|
||||
docker compose -f docker-compose.test.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
if (env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
try {
|
||||
sendProductionWeComNotification(
|
||||
'✅ 生产部署成功',
|
||||
'成功',
|
||||
'info',
|
||||
'> 结果:Client 生产前端已完成发布和部署流程'
|
||||
)
|
||||
} catch (Exception error) {
|
||||
echo "企业微信通知失败,不影响原构建结果:${error.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
failure {
|
||||
sh '''
|
||||
if [ "${IS_PRODUCTION:-false}" = "true" ]; then
|
||||
echo "生产部署失败,请查看上方远程部署日志"
|
||||
elif [ "${IS_DEVELOPMENT:-false}" = "true" ]; then
|
||||
docker logs --tail=100 client-web-development || true
|
||||
else
|
||||
docker compose -f docker-compose.test.yml logs --tail=100 || true
|
||||
fi
|
||||
'''
|
||||
script {
|
||||
if (env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
try {
|
||||
sendProductionWeComNotification(
|
||||
'❌ 生产发布失败',
|
||||
'失败',
|
||||
'warning',
|
||||
'> 说明:请打开 Jenkins 构建日志查看失败阶段'
|
||||
)
|
||||
} catch (Exception error) {
|
||||
echo "企业微信通知失败,不影响原构建结果:${error.message}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
if (env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
try {
|
||||
sendProductionWeComNotification(
|
||||
'⏹ 生产部署已取消',
|
||||
'已取消',
|
||||
'comment',
|
||||
'> 说明:生产部署流程被人工取消或中止'
|
||||
)
|
||||
} catch (Exception error) {
|
||||
echo "企业微信通知失败,不影响原构建结果:${error.message}"
|
||||
}
|
||||
if (!env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||
sh 'docker compose -f docker-compose.test.yml logs --tail=100 || true'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ pnpm install
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
生产构建:
|
||||
发布资源构建:
|
||||
|
||||
```bash
|
||||
pnpm typecheck
|
||||
@@ -35,7 +35,7 @@ pnpm test
|
||||
|
||||
依赖和 `pnpm-lock.yaml` 均保存在当前前端项目中,不需要在仓库根目录安装 Node 依赖。
|
||||
|
||||
订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经海外 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。开发代理通过 `API_PROXY_TARGET` 与 `OVERSEAS_API_PROXY_TARGET` 分别配置国内、海外 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
|
||||
订单与客户路由:登录、注册、工作台、我的信息、企业资料、企业成员、角色权限、头程订单、海外采购、美国本土卡、美本土散板以及海外仓入库订单。跨境下单支持真实列表、详情和新增,海外入库支持当前客户列表与详情;均经统一 Gateway 的客户接口访问,客户范围只取 Token,不提交客户 ID。本地代理仅通过 `API_PROXY_TARGET` 配置统一 Gateway。登录使用后端约定的用户名和 8–72 位密码,注册成功后可立即登录,企业资料审核只影响订单提交资格。
|
||||
|
||||
认证会话保存 Access Token 和轮换后的 Refresh Token,并对并发 401 请求执行单次刷新。刷新或会话上下文加载遇到临时网络故障、超时等非认证错误时保留当前有效 Token,只有服务端明确返回 401/会话失效才清理登录状态。客户端只接受 `app_code` 为 `MERCHANT` 的 JWT;页面权限通过当前用户授权接口实时加载,不从 JWT 携带或解析角色权限。前端权限仅用于导航和交互控制,服务端仍须按用户、客户和权限编码完成最终授权。
|
||||
|
||||
@@ -47,4 +47,10 @@ pnpm test
|
||||
|
||||
头程订单列表、详情、仓库查询、创建/编辑草稿和提交已经接入真实 API,并显式映射后端 `transportMode`、`containerMode` 和订单状态。创建与提交请求携带幂等键,`merchant:order:create`、`merchant:order:edit`、`merchant:order:submit` 分别映射到独立前端操作权限。页面补齐渠道、提货方式、报关模式、目的仓类型、包装类型等后端必填字段;API 模式先清空本地记录,请求失败不会回退模拟成功。FBA 和海外仓按公共仓类型筛选,选择后由仓库主数据生成目的仓字段,不再要求客户重复选择收货单位;私人仓才填写并按当前用户缓存收件资料。只有“我司提货”需要填写提货联系人和地址,其他送货方式不发送发货方快照,订单也不再依赖往来单位 `customerId`。快递信息仍由平台维护、客户只读。订单取消不属于本轮本地订单与客户验收,客户端不暴露取消写操作。订单产品状态仍按已确认的七状态执行,不设置“已驳回”;若兼容旧接口数据收到 `REJECTED`,只按待审核展示且不开放编辑。
|
||||
|
||||
联调远端 Gateway 时,进程环境变量优先于 `.env` 文件。浏览器国内业务统一请求同源 `/api`,海外业务请求同源 `/overseas-api`,由代理分别转发并确保最终路径只有一个 `/api` 前缀。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。
|
||||
联调远端 Gateway 时,进程环境变量优先于 `.env` 文件。浏览器全部业务统一请求同源 `/api`,由同一代理转发并确保最终路径只有一个 `/api` 前缀。联调时可只读检查同工作区的 `baiyue-firstleg/` Controller、DTO、Service、Repository 和回归脚本,用于发现后端拉取后的契约变化,但不修改后端仓库。
|
||||
|
||||
## 唯一测试部署入口
|
||||
|
||||
仅保留 `docker-compose.test.yml` 与 test Jenkins Job。发布前注入 `API_UPSTREAM`(统一 Gateway origin,不含 `/api`)、`TEST_NETWORK`(后端共享测试网络)、`VITE_ADMIN_WEB_ORIGIN`(管理后台 origin,构建时用于安全代登录)与 `IMAGE_TAG`(Jenkins 从当前提交生成)。`HOST_PORT` 默认 9002 且仅绑定 loopback;宿主机反向代理负责外部入口。可选 `NODE_BASE_IMAGE`/`NGINX_BASE_IMAGE`,私有镜像认证由构建节点管理。不得把本地构建结果描述为测试环境已发布。
|
||||
|
||||
同机目标默认值:`API_UPSTREAM=http://gateway:9000`、`TEST_NETWORK=firstleg-test-network`;必须与后端同批 test Compose 配置一致。
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
services:
|
||||
client-web:
|
||||
image: client-web-development:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||
container_name: client-web-development
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:9002:80"
|
||||
environment:
|
||||
API_UPSTREAM: "http://firstleg-development-gateway:9000"
|
||||
OVERSEAS_API_UPSTREAM: "http://firstleg-development-gateway-overseas:9300"
|
||||
networks:
|
||||
- development-backend
|
||||
- development-overseas-backend
|
||||
|
||||
networks:
|
||||
development-backend:
|
||||
external: true
|
||||
name: firstleg-development-network
|
||||
development-overseas-backend:
|
||||
external: true
|
||||
name: firstleg-development-overseas-network
|
||||
@@ -1,23 +1,22 @@
|
||||
name: firstleg-prod-client-web
|
||||
|
||||
services:
|
||||
client-web:
|
||||
image: ${IMAGE_REPOSITORY:?IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||
image: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required}"
|
||||
container_name: firstleg-prod-client-web
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:${HOST_PORT:-9002}:80"
|
||||
- "127.0.0.1:${HOST_PORT:-29012}:80"
|
||||
environment:
|
||||
API_UPSTREAM: "http://gateway-active:9000"
|
||||
OVERSEAS_API_UPSTREAM: "http://gateway-overseas-active:9300"
|
||||
API_UPSTREAM: "http://gateway:9000"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
networks:
|
||||
- infra-network
|
||||
- routing-network
|
||||
|
||||
- backend
|
||||
networks:
|
||||
infra-network:
|
||||
backend:
|
||||
external: true
|
||||
name: firstleg-prod-infra-network
|
||||
routing-network:
|
||||
external: true
|
||||
name: firstleg-production-routing
|
||||
name: firstleg-production-network
|
||||
|
||||
+17
-7
@@ -1,19 +1,29 @@
|
||||
name: firstleg-test-client-web
|
||||
services:
|
||||
client-web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:-https://test-admin.buggoglobal.com}"
|
||||
NODE_IMAGE: "${NODE_BASE_IMAGE:-node:22-alpine}"
|
||||
NGINX_IMAGE: "${NGINX_BASE_IMAGE:-nginx:1.27-alpine}"
|
||||
image: client-web-test:local
|
||||
VITE_ADMIN_WEB_ORIGIN: "${VITE_ADMIN_WEB_ORIGIN:?VITE_ADMIN_WEB_ORIGIN is required}"
|
||||
image: client-web-test:${IMAGE_TAG:?IMAGE_TAG is required}
|
||||
container_name: client-web-test
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
ports:
|
||||
- "${HOST_PORT:-9002}:80"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
- "127.0.0.1:${HOST_PORT:-9002}:80"
|
||||
environment:
|
||||
API_UPSTREAM: "${API_UPSTREAM:-http://host.docker.internal:9000}"
|
||||
OVERSEAS_API_UPSTREAM: "${OVERSEAS_API_UPSTREAM:-http://host.docker.internal:9300}"
|
||||
API_UPSTREAM: "${API_UPSTREAM:-http://gateway:9000}"
|
||||
networks:
|
||||
- test-backend
|
||||
networks:
|
||||
test-backend:
|
||||
external: true
|
||||
name: "${TEST_NETWORK:-firstleg-test-network}"
|
||||
|
||||
@@ -35,17 +35,6 @@ server {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 海外业务使用独立 Gateway;浏览器前缀只在此处改写一次为 /api。
|
||||
location /overseas-api/ {
|
||||
client_max_body_size 55m;
|
||||
rewrite ^/overseas-api/(.*)$ /api/$1 break;
|
||||
proxy_pass ${OVERSEAS_API_UPSTREAM};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $proxy_host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# 支持 Vue Router history 路由直接刷新。
|
||||
location / {
|
||||
|
||||
+52
-144
@@ -1,150 +1,58 @@
|
||||
#!/usr/bin/env sh
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
if [ "$#" -ne 4 ]; then
|
||||
echo "用法: $0 <服务名> <镜像仓库> <镜像标签> <Compose 文件>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
SERVICE="$1"
|
||||
IMAGE_REPOSITORY="$2"
|
||||
IMAGE_TAG="$3"
|
||||
COMPOSE_FILE="$4"
|
||||
IMAGE="$IMAGE_REPOSITORY:$IMAGE_TAG"
|
||||
REGISTRY_HOST="${IMAGE_REPOSITORY%%/*}"
|
||||
SSH_TARGET="${TARGET_SSH_TARGET:?TARGET_SSH_TARGET 未设置}"
|
||||
SSH_KEY="${TARGET_SSH_KEY:?TARGET_SSH_KEY 未设置}"
|
||||
SSH_KNOWN_HOSTS="${TARGET_SSH_KNOWN_HOSTS:?TARGET_SSH_KNOWN_HOSTS 未设置}"
|
||||
REMOTE_DIR="${TARGET_DEPLOY_DIR:?TARGET_DEPLOY_DIR 未设置}"
|
||||
: "${REGISTRY_USER:?REGISTRY_USER 未设置}"
|
||||
: "${REGISTRY_PASSWORD:?REGISTRY_PASSWORD 未设置}"
|
||||
|
||||
set +x
|
||||
: "${PUBLIC_WEB_ORIGIN:?PUBLIC_WEB_ORIGIN is required}"
|
||||
: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}"
|
||||
: "${TARGET_SSH_KEY:?}"
|
||||
: "${TARGET_SSH_USER:?}"
|
||||
: "${TARGET_SSH_HOST:?}"
|
||||
: "${TARGET_SSH_KNOWN_HOSTS:?}"
|
||||
: "${BUILD_REGISTRY_USER:?}"
|
||||
: "${BUILD_REGISTRY_PASSWORD:?}"
|
||||
: "${REGISTRY_USER:?}"
|
||||
: "${REGISTRY_PASSWORD:?}"
|
||||
case "$PUBLIC_WEB_ORIGIN" in https://*) ;; *) echo 'prod requires HTTPS web origin' >&2; exit 2 ;; esac
|
||||
# Only an origin (optionally a trailing slash) is accepted; no shell/env-file metacharacters.
|
||||
printf '%s' "$PUBLIC_WEB_ORIGIN" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]+)?/?$'
|
||||
printf '%s' "$PRODUCTION_IMAGE_REPOSITORY" | grep -Eq '^[A-Za-z0-9.-]+(:[0-9]+)?/[a-z0-9._/-]+$'
|
||||
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||
test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)"
|
||||
IMAGE_TAG=$(git rev-parse --short=12 HEAD)
|
||||
registry=${PRODUCTION_IMAGE_REPOSITORY%%/*}
|
||||
image="$PRODUCTION_IMAGE_REPOSITORY:$IMAGE_TAG"
|
||||
TARGET_SSH_TARGET="$TARGET_SSH_USER@$TARGET_SSH_HOST"
|
||||
remote_dir=/data/firstleg/deploy/gray-client-web
|
||||
run_ssh() {
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$SSH_TARGET" "$@"
|
||||
ssh -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$TARGET_SSH_TARGET" "$@"
|
||||
}
|
||||
|
||||
run_scp() {
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$SSH_KNOWN_HOSTS" -o ConnectTimeout=10 "$@"
|
||||
scp -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$@"
|
||||
}
|
||||
|
||||
run_ssh install -d -m 750 "$REMOTE_DIR"
|
||||
REMOTE_COMPOSE="$REMOTE_DIR/docker-compose.$SERVICE.yml"
|
||||
run_scp "$COMPOSE_FILE" "$SSH_TARGET:$REMOTE_COMPOSE.tmp"
|
||||
run_ssh sh -s -- "$REMOTE_COMPOSE.tmp" "$REMOTE_COMPOSE" <<'REMOTE_PREPARE'
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
|
||||
trap cleanup EXIT HUP INT TERM
|
||||
printf '%s' "$BUILD_REGISTRY_PASSWORD" | docker login -u "$BUILD_REGISTRY_USER" --password-stdin "$registry"
|
||||
docker build --build-arg NODE_IMAGE="${NODE_BASE_IMAGE:-node:22-alpine}" \
|
||||
--build-arg NGINX_IMAGE="${NGINX_BASE_IMAGE:-nginx:1.27-alpine}" \
|
||||
--build-arg VITE_ADMIN_WEB_ORIGIN="$PUBLIC_WEB_ORIGIN" -t "$image" .
|
||||
docker push "$image"
|
||||
run_ssh install -d -m 750 "$remote_dir"
|
||||
run_scp docker-compose.production.yml "$TARGET_SSH_TARGET:$remote_dir/compose.yml"
|
||||
# The remote env file contains only image coordinates and public web origin, never credentials.
|
||||
printf 'PRODUCTION_IMAGE_REPOSITORY=%s\nIMAGE_TAG=%s\nPUBLIC_WEB_ORIGIN=%s\n' \
|
||||
"$PRODUCTION_IMAGE_REPOSITORY" "$IMAGE_TAG" "$PUBLIC_WEB_ORIGIN" | run_ssh sh -c "'umask 077; cat > $remote_dir/release.env'"
|
||||
# Registry credentials exist only in an isolated temporary Docker config, removed after pull.
|
||||
printf '%s' "$REGISTRY_USER" | grep -Eq '^[A-Za-z0-9_.@-]+$'
|
||||
run_scp scripts/pull-production-image.sh "$TARGET_SSH_TARGET:$remote_dir/pull-image.sh"
|
||||
printf '%s' "$REGISTRY_PASSWORD" | run_ssh sh "$remote_dir/pull-image.sh" "$REGISTRY_USER" "$registry" "$image"
|
||||
run_ssh sh -s -- "$remote_dir" <<'REMOTE'
|
||||
set -eu
|
||||
compose_tmp="$1"
|
||||
compose_target="$2"
|
||||
chmod 644 "$compose_tmp"
|
||||
mv -f "$compose_tmp" "$compose_target"
|
||||
REMOTE_PREPARE
|
||||
|
||||
printf '%s' "$REGISTRY_PASSWORD" | run_ssh docker login -u "$REGISTRY_USER" --password-stdin "$REGISTRY_HOST"
|
||||
trap 'run_ssh docker logout "$REGISTRY_HOST" >/dev/null 2>&1 || true' EXIT HUP INT TERM
|
||||
run_ssh docker pull "$IMAGE"
|
||||
|
||||
run_ssh sh -s -- "$REMOTE_DIR" "$SERVICE" "$IMAGE_REPOSITORY" "$IMAGE_TAG" <<'REMOTE_DEPLOY'
|
||||
set -eu
|
||||
remote_dir="$1"
|
||||
service="$2"
|
||||
image_repository="$3"
|
||||
image_tag="$4"
|
||||
compose_file="docker-compose.$service.yml"
|
||||
project_name="firstleg-prod-$service"
|
||||
cd "$remote_dir"
|
||||
export IMAGE_REPOSITORY="$image_repository" IMAGE_TAG="$image_tag"
|
||||
|
||||
compose() {
|
||||
docker compose --project-name "$project_name" -f "$compose_file" "$@"
|
||||
}
|
||||
|
||||
case "$service" in
|
||||
admin-web)
|
||||
base_port=9001
|
||||
nginx_config=/www/server/panel/vhost/nginx/00-blue-green-admin-web.conf
|
||||
legacy_container=firstleg-prod-admin-web
|
||||
;;
|
||||
client-web)
|
||||
base_port=9002
|
||||
nginx_config=/www/server/panel/vhost/nginx/00-blue-green-client-web.conf
|
||||
legacy_container=firstleg-prod-client-web
|
||||
;;
|
||||
*) echo "不支持蓝绿部署的前端服务: $service" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
state_root=/data/firstleg/deploy/blue-green-state
|
||||
state_file="$state_root/frontend-$service.active"
|
||||
routing_network=firstleg-production-routing
|
||||
mkdir -p "$state_root"
|
||||
chmod 750 "$state_root"
|
||||
docker network inspect "$routing_network" >/dev/null 2>&1 || docker network create "$routing_network" >/dev/null
|
||||
|
||||
for pair in gateway-active:firstleg-production-gateway gateway-overseas-active:firstleg-production-gateway-overseas; do
|
||||
alias_name="${pair%%:*}"
|
||||
container="${pair#*:}"
|
||||
if docker inspect "$container" >/dev/null 2>&1; then
|
||||
docker network inspect "$routing_network" --format '{{json .Containers}}' | grep -q "\"$container\"" \
|
||||
|| docker network connect --alias "$alias_name" "$routing_network" "$container"
|
||||
fi
|
||||
done
|
||||
|
||||
active_slot=""
|
||||
active_container=""
|
||||
active_port=""
|
||||
if [ -s "$state_file" ]; then
|
||||
IFS='|' read -r active_slot active_container active_port active_image < "$state_file"
|
||||
elif docker inspect "$legacy_container" >/dev/null 2>&1; then
|
||||
active_slot=legacy
|
||||
active_container="$legacy_container"
|
||||
active_port="$base_port"
|
||||
fi
|
||||
|
||||
if [ "$active_slot" = blue ]; then target_slot=green; else target_slot=blue; fi
|
||||
[ "$active_slot" = legacy ] && target_slot=green
|
||||
if [ "$target_slot" = blue ]; then target_port=$((base_port + 20000)); else target_port=$((base_port + 10000)); fi
|
||||
candidate="${legacy_container}-${target_slot}"
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
|
||||
if ! compose run -d --no-deps --name "$candidate" \
|
||||
-p "127.0.0.1:$target_port:80" "$service" >/dev/null; then
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
healthy=false
|
||||
elapsed=0
|
||||
while [ "$elapsed" -lt 120 ]; do
|
||||
if docker exec "$candidate" wget -qO- http://127.0.0.1/healthz >/dev/null 2>&1; then
|
||||
healthy=true
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
elapsed=$((elapsed + 2))
|
||||
done
|
||||
if [ "$healthy" != true ]; then
|
||||
docker logs --tail 100 "$candidate" >&2 || true
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
backup="$nginx_config.blue-green-backup"
|
||||
cp -f "$nginx_config" "$backup"
|
||||
if ! sed -i "s#127\.0\.0\.1:${active_port:-$base_port}#127.0.0.1:$target_port#g" "$nginx_config" \
|
||||
|| cmp -s "$nginx_config" "$backup" || ! nginx -t || ! nginx -s reload; then
|
||||
cp -f "$backup" "$nginx_config"
|
||||
nginx -t && nginx -s reload || true
|
||||
docker rm -f "$candidate" >/dev/null 2>&1 || true
|
||||
exit 1
|
||||
fi
|
||||
rm -f "$backup"
|
||||
|
||||
if [ -n "$active_container" ] && docker inspect "$active_container" >/dev/null 2>&1; then
|
||||
docker stop --time 30 "$active_container" >/dev/null
|
||||
docker rm "$active_container" >/dev/null
|
||||
fi
|
||||
printf '%s|%s|%s|%s\n' "$target_slot" "$candidate" "$target_port" "$image_repository:$image_tag" > "$state_file.tmp"
|
||||
chmod 640 "$state_file.tmp"
|
||||
mv -f "$state_file.tmp" "$state_file"
|
||||
echo "生产前端蓝绿部署成功: service=$service slot=$target_slot port=$target_port image=$image_repository:$image_tag"
|
||||
REMOTE_DEPLOY
|
||||
cd "$1"
|
||||
docker network inspect firstleg-production-network >/dev/null
|
||||
docker compose --env-file release.env -f compose.yml config --quiet
|
||||
docker compose --env-file release.env -f compose.yml up -d --wait --wait-timeout 120
|
||||
docker compose --env-file release.env -f compose.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||
REMOTE
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
set +x
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
|
||||
trap cleanup EXIT HUP INT TERM
|
||||
docker login -u "$1" --password-stdin "$2"
|
||||
docker pull "$3"
|
||||
@@ -92,6 +92,7 @@ export const FIRST_LEG_ORDER_STATUSES = [
|
||||
{ code: 'LOADED', label: '装柜完成' },
|
||||
{ code: 'DELIVERED', label: '派送完成' },
|
||||
{ code: 'COMPLETED', label: '已完成' },
|
||||
{ code: 'CANCELLED', label: '已取消' },
|
||||
] as const
|
||||
|
||||
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
|
||||
|
||||
+95
-12
@@ -1,8 +1,8 @@
|
||||
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||
import { accessTokenIdentity, clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
||||
import { ApiError, isApiEnvelope, type ApiEnvelope } from '@/api/types'
|
||||
import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
|
||||
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
|
||||
|
||||
const transport = axios.create({
|
||||
@@ -13,9 +13,18 @@ const transport = axios.create({
|
||||
|
||||
interface RetryableRequest extends InternalAxiosRequestConfig {
|
||||
_retriedAfterRefresh?: boolean
|
||||
_sessionIdentity?: string | null
|
||||
_logoutGeneration?: number
|
||||
}
|
||||
|
||||
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
||||
if (!isApiEnvelope(envelope)) {
|
||||
const invalid: unknown = envelope
|
||||
if (isApiFailure(invalid)) {
|
||||
throw new ApiError(invalid.message, invalid.code, undefined, undefined, invalid.traceId, invalid.requestId)
|
||||
}
|
||||
throw new ApiError('接口响应格式错误', 'INVALID_RESPONSE')
|
||||
}
|
||||
if (envelope.code !== '200') {
|
||||
const fieldErrors = asFieldErrors(envelope.data)
|
||||
throw new ApiError(apiErrorMessage(envelope.message, fieldErrors), envelope.code, undefined, fieldErrors, envelope.traceId, envelope.requestId)
|
||||
@@ -28,8 +37,8 @@ function mapError(error: unknown) {
|
||||
if (!axios.isAxiosError(error)) return new ApiError(error instanceof Error ? error.message : '请求失败')
|
||||
|
||||
const body = error.response?.data
|
||||
if (isApiEnvelope(body)) {
|
||||
const fieldErrors = asFieldErrors(body.data)
|
||||
if (isApiEnvelope(body) || isApiFailure(body)) {
|
||||
const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
|
||||
return new ApiError(
|
||||
apiErrorMessage(body.message, fieldErrors),
|
||||
body.code,
|
||||
@@ -44,9 +53,12 @@ function mapError(error: unknown) {
|
||||
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
|
||||
let refreshExchange: { identity: string; refreshToken: string; promise: Promise<TokenPair> } | null = null
|
||||
let logoutGeneration = 0
|
||||
let refreshPromise: Promise<string> | null = null
|
||||
let refreshIdentity: string | null = null
|
||||
let redirectingToLogin = false
|
||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/impersonations/exchange']
|
||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout', '/auth/impersonations/exchange']
|
||||
|
||||
function isPublicAuthRequest(url?: string) {
|
||||
return publicAuthPaths.some((path) => url?.endsWith(path))
|
||||
@@ -63,29 +75,46 @@ function redirectToLoginAfterSessionExpiry() {
|
||||
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
||||
}
|
||||
|
||||
function requireCurrentIdentity(identity: string | null | undefined, accessToken = getAccessToken()) {
|
||||
if (!identity || accessTokenIdentity(accessToken) !== identity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
}
|
||||
|
||||
export async function refreshAuthenticatedSession() {
|
||||
const observedIdentity = accessTokenIdentity(getAccessToken())
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const observedRefreshToken = getRefreshToken()
|
||||
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||
if (!refreshPromise) {
|
||||
refreshIdentity = observedIdentity
|
||||
refreshPromise = coordinateCrossTabRefresh({
|
||||
lockName: 'cc-client-auth-refresh',
|
||||
observedRefreshToken,
|
||||
currentRefreshToken: getRefreshToken,
|
||||
reuseCurrentSession: async () => {
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const currentAccessToken = getAccessToken()
|
||||
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||
return currentAccessToken
|
||||
},
|
||||
refresh: async (currentRefreshToken) => {
|
||||
const response = await transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken })
|
||||
const tokens = unwrap(response.data)
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
const exchange = { identity: observedIdentity!, refreshToken: currentRefreshToken, promise: transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }).then(response => unwrap(response.data)) }
|
||||
refreshExchange = exchange
|
||||
let tokens: TokenPair
|
||||
try { tokens = await exchange.promise } finally { if (refreshExchange === exchange) refreshExchange = null }
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
requireCurrentIdentity(observedIdentity, tokens.accessToken)
|
||||
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
||||
if (getRefreshToken() !== currentRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||
persistTokenPair(tokens)
|
||||
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('cc-client-session-updated'))
|
||||
return tokens.accessToken
|
||||
},
|
||||
})
|
||||
.catch((error) => {
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
if (error instanceof CrossTabRefreshTimeoutError) {
|
||||
if (getRefreshToken() && getRefreshToken() !== observedRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||
const expiredError = new ApiError(error.message, 'A0401', 401)
|
||||
clearSessionTokens()
|
||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||
@@ -96,33 +125,60 @@ export async function refreshAuthenticatedSession() {
|
||||
})
|
||||
.finally(() => {
|
||||
refreshPromise = null
|
||||
refreshIdentity = null
|
||||
})
|
||||
}
|
||||
return refreshPromise
|
||||
if (refreshIdentity !== observedIdentity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
const refreshed = await refreshPromise
|
||||
requireCurrentIdentity(observedIdentity)
|
||||
return refreshed
|
||||
}
|
||||
|
||||
transport.interceptors.request.use((config) => {
|
||||
const token = getAccessToken()
|
||||
if (token && !isPublicAuthRequest(config.url)) config.headers.Authorization = `Bearer ${token}`
|
||||
const request = config as RetryableRequest
|
||||
if (request._retriedAfterRefresh && !isPublicAuthRequest(config.url)) requireCurrentIdentity(request._sessionIdentity, token)
|
||||
if (token && !isPublicAuthRequest(config.url)) {
|
||||
if (!request._retriedAfterRefresh) {
|
||||
request._sessionIdentity = accessTokenIdentity(token)
|
||||
request._logoutGeneration = logoutGeneration
|
||||
}
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
transport.interceptors.response.use(
|
||||
(response) => response,
|
||||
(response) => {
|
||||
const request = response.config as RetryableRequest
|
||||
if (request._sessionIdentity) {
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
}
|
||||
return response
|
||||
},
|
||||
async (error: AxiosError) => {
|
||||
const request = error.config as RetryableRequest | undefined
|
||||
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
|
||||
throw mapError(error)
|
||||
}
|
||||
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
request._retriedAfterRefresh = true
|
||||
const refreshTokenBeforeRetry = getRefreshToken()
|
||||
try {
|
||||
const accessToken = await refreshAuthenticatedSession()
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
request.headers.Authorization = `Bearer ${accessToken}`
|
||||
return await transport.request(request)
|
||||
} catch (refreshError) {
|
||||
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||
requireCurrentIdentity(request._sessionIdentity)
|
||||
const mappedError = mapError(refreshError)
|
||||
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
||||
if (getRefreshToken() && getRefreshToken() !== refreshTokenBeforeRetry) throw mappedError
|
||||
clearSessionTokens()
|
||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||
redirectToLoginAfterSessionExpiry()
|
||||
@@ -132,6 +188,33 @@ transport.interceptors.response.use(
|
||||
},
|
||||
)
|
||||
|
||||
// Captured revocation never persists credentials or restores local login state.
|
||||
export async function revokeCapturedSession(accessToken: string, refreshToken: string) {
|
||||
logoutGeneration++
|
||||
const identity = accessTokenIdentity(accessToken)
|
||||
if (!identity || !refreshToken) throw new ApiError('服务器会话注销未确认', 'SESSION_CHANGED')
|
||||
const pending = refreshExchange?.identity === identity && refreshExchange.refreshToken === refreshToken ? refreshExchange.promise : null
|
||||
const revoke = (pair: Pick<TokenPair, 'accessToken' | 'refreshToken'>) => apiRequest<void>({
|
||||
method: 'POST', url: '/auth/logout', data: { refreshToken: pair.refreshToken },
|
||||
headers: { Authorization: `Bearer ${pair.accessToken}` },
|
||||
})
|
||||
const validate = (pair: TokenPair) => {
|
||||
if (accessTokenIdentity(pair.accessToken) !== identity || !pair.refreshToken) throw new ApiError('刷新身份不一致,服务器会话注销未确认', 'SESSION_CHANGED')
|
||||
return pair
|
||||
}
|
||||
// An already sent refresh can rotate the pair. Consume its actual result
|
||||
// without issuing a competing refresh or restoring it to local storage.
|
||||
if (pending) {
|
||||
await revoke(validate(await pending))
|
||||
return
|
||||
}
|
||||
try { await revoke({ accessToken, refreshToken }) } catch (error) {
|
||||
if (!(error instanceof ApiError) || error.status !== 401) throw error
|
||||
const pair = await apiRequest<TokenPair>({ method: 'POST', url: '/auth/refresh', data: { refreshToken } })
|
||||
await revoke(validate(pair))
|
||||
}
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<ApiEnvelope<T>>(config)
|
||||
@@ -170,8 +253,8 @@ async function throwBlobApiError(error: unknown, responseStatus?: number) {
|
||||
if (!blob || !blob.type.toLowerCase().includes('json')) return
|
||||
try {
|
||||
const body = JSON.parse(await blob.text()) as unknown
|
||||
if (!isApiEnvelope(body)) return
|
||||
const fieldErrors = asFieldErrors(body.data)
|
||||
if (!isApiEnvelope(body) && !isApiFailure(body)) return
|
||||
const fieldErrors = asFieldErrors(isApiEnvelope(body) ? body.data : undefined)
|
||||
throw new ApiError(
|
||||
apiErrorMessage(body.message, fieldErrors),
|
||||
body.code,
|
||||
|
||||
@@ -26,8 +26,8 @@ test('does not accept malformed or data-less successful responses', () => {
|
||||
assert.equal(isApiEnvelope({ code: '200', message: 'OK', data: [] }), true)
|
||||
})
|
||||
|
||||
test('overseas transport handles business-code and HTTP security failures', async () => {
|
||||
const transport = await readFile(new URL('./overseasHttp.ts', import.meta.url), 'utf8')
|
||||
assert.match(transport, /if \(isApiFailure\(response.data\)\)/)
|
||||
test('unified transport handles business-code and HTTP security failures', async () => {
|
||||
const transport = await readFile(new URL('./http.ts', import.meta.url), 'utf8')
|
||||
assert.match(transport, /if \(isApiFailure\(invalid\)\)/)
|
||||
assert.match(transport, /isApiEnvelope\(body\) \|\| isApiFailure\(body\)/)
|
||||
})
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
import axios, { type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||
import { ApiError, isApiEnvelope, isApiFailure } from '@/api/types'
|
||||
import { getOverseasAccessToken } from '@/api/session'
|
||||
import { refreshAuthenticatedSession } from '@/api/http'
|
||||
|
||||
interface RetryableRequest extends InternalAxiosRequestConfig { _retriedOverseasAuth?: boolean }
|
||||
|
||||
const transport = axios.create({
|
||||
baseURL: import.meta.env.VITE_OVERSEAS_API_BASE_URL || '/overseas-api',
|
||||
timeout: 15_000,
|
||||
transformResponse: [(data: unknown) => parseApiJsonResponse(data)],
|
||||
})
|
||||
|
||||
async function requireToken() {
|
||||
const current = getOverseasAccessToken()
|
||||
if (current) return current
|
||||
await refreshAuthenticatedSession()
|
||||
const refreshed = getOverseasAccessToken()
|
||||
if (!refreshed) throw new ApiError('当前环境未签发海外访问令牌', 'OVERSEAS_TOKEN_UNAVAILABLE')
|
||||
return refreshed
|
||||
}
|
||||
|
||||
transport.interceptors.request.use(async (config) => {
|
||||
config.headers.Authorization = `Bearer ${await requireToken()}`
|
||||
return config
|
||||
})
|
||||
|
||||
transport.interceptors.response.use((response) => response, async (error) => {
|
||||
const request = error.config as RetryableRequest | undefined
|
||||
if (error.response?.status !== 401 || !request || request._retriedOverseasAuth) throw error
|
||||
request._retriedOverseasAuth = true
|
||||
await refreshAuthenticatedSession()
|
||||
request.headers.Authorization = `Bearer ${await requireToken()}`
|
||||
return transport.request(request)
|
||||
})
|
||||
|
||||
export async function overseasApiRequest<T>(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<unknown>(config)
|
||||
if (isApiFailure(response.data)) {
|
||||
throw new ApiError(response.data.message, response.data.code, response.status, undefined,
|
||||
response.data.traceId, response.data.requestId)
|
||||
}
|
||||
if (!isApiEnvelope(response.data) || response.data.code !== '200') {
|
||||
throw new ApiError(
|
||||
isApiEnvelope(response.data) ? response.data.message : '海外接口响应格式错误',
|
||||
isApiEnvelope(response.data) ? response.data.code : 'INVALID_RESPONSE',
|
||||
undefined,
|
||||
undefined,
|
||||
isApiEnvelope(response.data) ? response.data.traceId : null,
|
||||
isApiEnvelope(response.data) ? response.data.requestId : null,
|
||||
)
|
||||
}
|
||||
return response.data.data as T
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error
|
||||
if (axios.isAxiosError(error)) {
|
||||
const body = error.response?.data
|
||||
if (isApiEnvelope(body) || isApiFailure(body)) {
|
||||
throw new ApiError(body.message, body.code, error.response?.status, undefined, body.traceId, body.requestId)
|
||||
}
|
||||
throw new ApiError(error.code === 'ERR_NETWORK' ? '无法连接海外服务' : error.message, error.code || 'OVERSEAS_HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
throw new ApiError(error instanceof Error ? error.message : '海外接口请求失败')
|
||||
}
|
||||
}
|
||||
|
||||
export async function overseasBlobRequest(config: AxiosRequestConfig) {
|
||||
try {
|
||||
const response = await transport.request<Blob>({ ...config, responseType: 'blob' })
|
||||
return response.data
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) throw error
|
||||
if (axios.isAxiosError(error)) {
|
||||
const body = error.response?.data
|
||||
if (body instanceof Blob && body.type.includes('json')) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(await body.text())
|
||||
if (isApiEnvelope(parsed) || isApiFailure(parsed)) {
|
||||
throw new ApiError(parsed.message, parsed.code, error.response?.status, undefined, parsed.traceId, parsed.requestId)
|
||||
}
|
||||
} catch (parseError) {
|
||||
if (parseError instanceof ApiError) throw parseError
|
||||
}
|
||||
}
|
||||
throw new ApiError(error.code === 'ERR_NETWORK' ? '无法连接海外服务' : error.message, error.code || 'OVERSEAS_HTTP_ERROR', error.response?.status)
|
||||
}
|
||||
throw new ApiError(error instanceof Error ? error.message : '海外文件下载失败')
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
accessTokenIdentity,
|
||||
ACCESS_TOKEN_KEY,
|
||||
REFRESH_TOKEN_KEY,
|
||||
REMEMBERED_LOGIN_ID_KEY,
|
||||
@@ -56,3 +57,34 @@ test('remembers only the login id and keeps it when session tokens are cleared',
|
||||
persistRememberedLoginId('merchant-user', false)
|
||||
assert.equal(getRememberedLoginId(), '')
|
||||
})
|
||||
|
||||
test('normal token rotation never removes either shared token between writes', () => {
|
||||
installStorage()
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, 'old-access')
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, 'old-refresh')
|
||||
const removed = []
|
||||
const remove = localStorage.removeItem
|
||||
localStorage.removeItem = key => { removed.push(key); remove(key) }
|
||||
persistTokenPair({ accessToken: 'new-access', refreshToken: 'new-refresh' })
|
||||
assert.ok(!removed.includes(ACCESS_TOKEN_KEY))
|
||||
assert.ok(!removed.includes(REFRESH_TOKEN_KEY))
|
||||
})
|
||||
|
||||
function rawIdentity(overrides = '') {
|
||||
return `test.${Buffer.from(`{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"${overrides}}`).toString('base64url')}.test`
|
||||
}
|
||||
test('identity preserves low digits of numeric 19 digit user customer and membership',()=>{
|
||||
const original=rawIdentity();const json=Buffer.from(original.split('.')[1],'base64url').toString();
|
||||
for(const field of ['user_id','tenant_id','membership_id']){
|
||||
const changed=json.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`)
|
||||
assert.notEqual(accessTokenIdentity(original),accessTokenIdentity(`test.${Buffer.from(changed).toString('base64url')}.test`))
|
||||
}
|
||||
})
|
||||
test('identity string and numeric integers are equivalent without changing other strings',()=>{
|
||||
const a=rawIdentity();const raw=Buffer.from(a.split('.')[1],'base64url').toString();
|
||||
const b=`test.${Buffer.from(raw.replaceAll(':2107003446494334978',':"2107003446494334978"')).toString('base64url')}.test`
|
||||
assert.equal(accessTokenIdentity(a),accessTokenIdentity(b))
|
||||
const decorated=rawIdentity(',"username":'+JSON.stringify('number 2107003446494334979 and "tenant_id":2107003446494334979')+',"note":"1234567890123456789"')
|
||||
assert.equal(accessTokenIdentity(a),accessTokenIdentity(decorated))
|
||||
assert.ok(accessTokenIdentity(a).includes('2107003446494334978'))
|
||||
})
|
||||
|
||||
+29
-20
@@ -1,7 +1,5 @@
|
||||
export const ACCESS_TOKEN_KEY = 'cc-client-access-token'
|
||||
export const REFRESH_TOKEN_KEY = 'cc-client-refresh-token'
|
||||
export const OVERSEAS_ACCESS_TOKEN_KEY = 'cc-client-overseas-access-token'
|
||||
export const OVERSEAS_EXPIRES_AT_KEY = 'cc-client-overseas-expires-at'
|
||||
export const REMEMBERED_LOGIN_ID_KEY = 'cc-client-remembered-login-id'
|
||||
|
||||
export interface TokenPair {
|
||||
@@ -10,14 +8,8 @@ export interface TokenPair {
|
||||
expiresIn: number
|
||||
refreshToken: string
|
||||
refreshExpiresIn: number
|
||||
overseasAccessToken?: string | null
|
||||
overseasExpiresIn?: number
|
||||
}
|
||||
|
||||
function activeStorage() {
|
||||
if (localStorage.getItem(ACCESS_TOKEN_KEY)) return localStorage
|
||||
return sessionStorage
|
||||
}
|
||||
|
||||
export function getAccessToken() {
|
||||
return localStorage.getItem(ACCESS_TOKEN_KEY) || sessionStorage.getItem(ACCESS_TOKEN_KEY) || ''
|
||||
@@ -27,21 +19,40 @@ export function getRefreshToken() {
|
||||
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
export function getOverseasAccessToken() {
|
||||
const storage = activeStorage()
|
||||
const expiresAt = Number(storage.getItem(OVERSEAS_EXPIRES_AT_KEY) || 0)
|
||||
if (expiresAt <= Date.now() + 30_000) return ''
|
||||
return storage.getItem(OVERSEAS_ACCESS_TOKEN_KEY) || ''
|
||||
// Only binds a retry to its original identity; never grants permissions. Expired
|
||||
// access tokens remain readable here because they are the normal refresh trigger.
|
||||
export function accessTokenIdentity(token: string): string | null {
|
||||
try {
|
||||
const encoded = token.split('.')[1]
|
||||
if (!encoded) return null
|
||||
const normalized = encoded.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const bytes = Uint8Array.from(atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')), character => character.charCodeAt(0))
|
||||
const json = new TextDecoder().decode(bytes)
|
||||
// Match whole JSON strings first so digits inside arbitrary string values
|
||||
// are never rewritten. Preserve integer identity claims before JSON.parse
|
||||
// can round them; number/string representations then share one identity.
|
||||
const exactIdentityJson = json.replace(/"(?:\\.|[^"\\])*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (part, offset: number) => {
|
||||
if (!/^-?\d+$/.test(part)) return part
|
||||
const key = json.slice(0, offset).match(/"(user_id|tenant_id|membership_id|operator_tenant_id)"\s*:\s*$/)
|
||||
return key ? JSON.stringify(part) : part
|
||||
})
|
||||
const value = JSON.parse(exactIdentityJson)
|
||||
if (!value?.user_id || !value.tenant_id || !value.membership_id || value.app_code !== 'MERCHANT') return null
|
||||
return JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type].map(item => item == null ? null : String(item)))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export function persistTokenPair(tokens: TokenPair) {
|
||||
clearSessionTokens()
|
||||
// Replace the pair without publishing a transient logout to other tabs.
|
||||
sessionStorage.removeItem(ACCESS_TOKEN_KEY)
|
||||
sessionStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||
sessionStorage.removeItem('cc-client-token')
|
||||
localStorage.removeItem('cc-client-token')
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
|
||||
if (tokens.overseasAccessToken && Number(tokens.overseasExpiresIn) > 0) {
|
||||
localStorage.setItem(OVERSEAS_ACCESS_TOKEN_KEY, tokens.overseasAccessToken)
|
||||
localStorage.setItem(OVERSEAS_EXPIRES_AT_KEY, String(Date.now() + Number(tokens.overseasExpiresIn) * 1000))
|
||||
}
|
||||
}
|
||||
|
||||
export function getRememberedLoginId() {
|
||||
@@ -62,8 +73,6 @@ export function clearSessionTokens() {
|
||||
for (const storage of [localStorage, sessionStorage]) {
|
||||
storage.removeItem(ACCESS_TOKEN_KEY)
|
||||
storage.removeItem(REFRESH_TOKEN_KEY)
|
||||
storage.removeItem(OVERSEAS_ACCESS_TOKEN_KEY)
|
||||
storage.removeItem(OVERSEAS_EXPIRES_AT_KEY)
|
||||
storage.removeItem('cc-client-token')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import axios from 'axios'
|
||||
|
||||
function compile(name, dependencies = {}) {
|
||||
const source = readFileSync(new URL(name, import.meta.url), 'utf8')
|
||||
.replace('import.meta.env.VITE_API_BASE_URL', "'/api'")
|
||||
const code = ts.transpileModule(source, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)((id) => {
|
||||
assert.ok(id in dependencies, `unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports)
|
||||
return exports
|
||||
}
|
||||
|
||||
function access(user, tenant = 1, membership = 1, nonce = 'original') {
|
||||
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, app_code: 'MERCHANT', nonce })).toString('base64url')}.test`
|
||||
}
|
||||
const oldAccess = access(1)
|
||||
const newAccess = access(1, 1, 1, 'rotated')
|
||||
const otherAccess = access(2, 2, 2)
|
||||
|
||||
function harness(adapter) {
|
||||
let token = oldAccess
|
||||
let refreshToken = 'old-refresh'
|
||||
const http = compile('./http.ts', {
|
||||
axios: { ...axios, create: (config) => axios.create({ ...config, adapter }) },
|
||||
'@chongchong/shared': { parseApiJsonResponse: (data) => data },
|
||||
'@/api/session': {
|
||||
accessTokenIdentity: compile('./session.ts').accessTokenIdentity,
|
||||
getAccessToken: () => token, getRefreshToken: () => refreshToken,
|
||||
persistTokenPair: (tokens) => { token = tokens.accessToken; refreshToken = tokens.refreshToken },
|
||||
clearSessionTokens: () => { token = ''; refreshToken = '' },
|
||||
},
|
||||
'@/api/errorDetails': compile('./errorDetails.ts'),
|
||||
'@/api/types': compile('./types.ts'),
|
||||
'@/api/crossTabRefresh': compile('./crossTabRefresh.ts'),
|
||||
})
|
||||
return { ...http, setSession: (access, refresh) => { token = access; refreshToken = refresh }, session: () => ({ token, refreshToken }) }
|
||||
}
|
||||
|
||||
test('order and lastleg 401s share one refresh and replay the unified access token', async () => {
|
||||
let refreshes = 0
|
||||
const calls = []
|
||||
const http = harness(async (config) => {
|
||||
calls.push({ url: config.url, base: config.baseURL, token: config.headers.Authorization })
|
||||
if (config.url === '/auth/refresh') {
|
||||
refreshes++
|
||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||
}
|
||||
if (config.headers.Authorization === `Bearer ${oldAccess}`) {
|
||||
throw new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||
}
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: config.url } }
|
||||
})
|
||||
const urls = ['/merchant/v1/orders', '/merchant/v1/last-leg/inbound-plans']
|
||||
assert.deepEqual(await Promise.all(urls.map((url) => http.apiRequest({ url }))), urls)
|
||||
assert.equal(refreshes, 1)
|
||||
assert.ok(calls.every((call) => call.base === '/api'))
|
||||
assert.equal(calls.find((call) => call.url === '/auth/refresh').token, undefined)
|
||||
assert.equal(calls.filter((call) => call.token === `Bearer ${newAccess}`).length, 2)
|
||||
})
|
||||
|
||||
test('successful order submit with explicit null data is accepted', async () => {
|
||||
const http = harness(async (config) => ({
|
||||
config, status: 200, headers: {}, data: { code: '200', message: 'success', data: null },
|
||||
}))
|
||||
assert.equal(await http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/order-1/submit' }), null)
|
||||
})
|
||||
|
||||
test('data-less security failures preserve diagnostics and malformed success is rejected', async () => {
|
||||
for (const data of [{ code: 'A0403', message: 'Denied', traceId: 'trace-1', requestId: 'request-1' }, { code: '200', message: 'OK' }]) {
|
||||
const http = harness(async (config) => ({ config, status: 200, headers: {}, data }))
|
||||
await assert.rejects(http.apiRequest({ url: '/merchant/v1/last-leg/inbound-plans' }), (error) => {
|
||||
assert.equal(error.code, data.code === '200' ? 'INVALID_RESPONSE' : 'A0403')
|
||||
if (data.code !== '200') { assert.equal(error.traceId, 'trace-1'); assert.equal(error.requestId, 'request-1') }
|
||||
return true
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
test('late refresh response cannot overwrite a session changed in another tab', async () => {
|
||||
let complete, started
|
||||
const ready = new Promise(resolve => { started = resolve })
|
||||
const response = new Promise(resolve => { complete = resolve })
|
||||
const http = harness(async config => { started(); await response; return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: oldAccess, refreshToken: 'stale-refresh' } } } })
|
||||
const pending = http.refreshAuthenticatedSession()
|
||||
await ready
|
||||
http.setSession(otherAccess, 'other-refresh')
|
||||
complete()
|
||||
await pending.catch(error => assert.equal(error.code, 'SESSION_CHANGED'))
|
||||
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'other-refresh' })
|
||||
})
|
||||
|
||||
function deferred() { let resolve; const promise = new Promise(yes => { resolve = yes }); return { promise, resolve } }
|
||||
|
||||
function unauthorized(config) {
|
||||
return new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||
}
|
||||
|
||||
test('late A write 401 after user, customer or membership switch never refreshes or replays under B', async () => {
|
||||
for (const next of [access(2), access(1, 2), access(1, 1, 2)]) {
|
||||
const sent = deferred(), release = deferred(), calls = []
|
||||
const http = harness(async config => {
|
||||
calls.push(config.url); sent.resolve(); await release.promise
|
||||
throw unauthorized(config)
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit', data: { expectedVersion: 1 } })
|
||||
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||
await sent.promise; http.setSession(next, 'refresh-b'); release.resolve(); await rejected
|
||||
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit'])
|
||||
assert.deepEqual(http.session(), { token: next, refreshToken: 'refresh-b' })
|
||||
}
|
||||
})
|
||||
|
||||
test('switch during in-flight refresh cannot reuse B token to replay an A write', async () => {
|
||||
const refreshing = deferred(), release = deferred(), calls = []
|
||||
const http = harness(async config => {
|
||||
calls.push(config.url)
|
||||
if (config.url === '/auth/refresh') {
|
||||
refreshing.resolve(); await release.promise
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||
}
|
||||
throw unauthorized(config)
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||
await refreshing.promise; http.setSession(otherAccess, 'refresh-b'); release.resolve(); await rejected
|
||||
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit', '/auth/refresh'])
|
||||
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'refresh-b' })
|
||||
})
|
||||
|
||||
test('refresh lock wait reuses same-identity rotation but rejects changed-identity reuse', async t => {
|
||||
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
|
||||
t.after(() => { if (originalNavigator) Object.defineProperty(globalThis, 'navigator', originalNavigator); else delete globalThis.navigator })
|
||||
for (const next of [newAccess, otherAccess]) {
|
||||
const waiting = deferred(), release = deferred(), calls = []
|
||||
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: { request: async (_name, _options, run) => {
|
||||
waiting.resolve(); await release.promise; return run()
|
||||
} } } })
|
||||
const http = harness(async config => {
|
||||
calls.push({ url: config.url, authorization: config.headers.Authorization })
|
||||
if (config.headers.Authorization === `Bearer ${oldAccess}`) throw unauthorized(config)
|
||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: null } }
|
||||
})
|
||||
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||
const outcome = next === otherAccess ? assert.rejects(pending, error => error.code === 'SESSION_CHANGED') : pending
|
||||
await waiting.promise; http.setSession(next, 'rotated-refresh'); release.resolve(); await outcome
|
||||
assert.equal(calls.some(call => call.url === '/auth/refresh'), false)
|
||||
assert.equal(calls.length, next === otherAccess ? 1 : 2)
|
||||
assert.deepEqual(http.session(), { token: next, refreshToken: 'rotated-refresh' })
|
||||
}
|
||||
})
|
||||
|
||||
function authApi(http) { return compile('../modules/auth/api/auth.ts', { '@/api/http': http }) }
|
||||
function ok(config, data = null) { return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data } } }
|
||||
test('logout after immediate local clear revokes captured Bearer and Refresh', async () => {
|
||||
const calls=[]; const http=harness(async c=>{calls.push(c);return ok(c)})
|
||||
http.setSession('', '');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||
assert.equal(calls.length,1);assert.equal(calls[0].headers.Authorization,`Bearer ${oldAccess}`)
|
||||
assert.deepEqual(JSON.parse(calls[0].data),{refreshToken:'old-refresh'});assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('only explicit logout401 refreshes once and revokes same-identity replacement without storing it', async () => {
|
||||
const calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'});if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||
http.setSession('','');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||
assert.deepEqual(calls.map(x=>x.url),['/auth/logout','/auth/refresh','/auth/logout']);assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[2].data).refreshToken,'new-refresh');assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('unknown logout failure never refreshes; changed identity cannot be revoked as replacement', async () => {
|
||||
for(const mode of ['network','wrongIdentity','second401']){const calls=[];const http=harness(async c=>{calls.push(c);if(mode==='network')throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c);if(c.url==='/auth/refresh')return ok(c,{accessToken:mode==='wrongIdentity'?otherAccess:newAccess,refreshToken:'replacement'});throw unauthorized(c)})
|
||||
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(oldAccess,'old-refresh'));assert.equal(calls.length,mode==='network'?1:mode==='wrongIdentity'?2:3);assert.deepEqual(http.session(),{token:'',refreshToken:''})}
|
||||
})
|
||||
test('logout consumes already inflight refresh once while old business caller cannot revive session',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}return ok(c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');release.resolve();await leaving;await rejected
|
||||
assert.deepEqual(calls.map(x=>x.url),['/auth/refresh','/auth/logout']);assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
test('late successful business response after logout rejects even after same-identity new login',async()=>{
|
||||
const started=deferred(),release=deferred();const http=harness(async c=>{if(c.url==='/merchant/v1/orders'){started.resolve();await release.promise}return ok(c,'old-data')})
|
||||
const pending=http.apiRequest({url:'/merchant/v1/orders'});const rejected=assert.rejects(pending,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||
await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected;assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||
})
|
||||
|
||||
test('inflight refresh unknown outcome stops logout without competing retry and preserves later login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);started.resolve();await release.promise;throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');const failure=assert.rejects(leaving,e=>e.code==='NETWORK_ERROR');http.setSession(otherAccess,'other-refresh');release.resolve();await failure;await rejected
|
||||
assert.equal(calls.length,1);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||
})
|
||||
test('logout401 refresh and replacement revocation cannot overwrite later login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');await started.promise;http.setSession(otherAccess,'other-refresh');release.resolve();await leaving
|
||||
assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||
})
|
||||
test('late old business401 after logout does not refresh or replay under same-identity new login',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/merchant/v1/orders/first-leg/one/submit'){started.resolve();await release.promise;throw unauthorized(c)}return ok(c)})
|
||||
const request=http.apiRequest({method:'POST',url:'/merchant/v1/orders/first-leg/one/submit'});const rejected=assert.rejects(request,e=>e.code==='SESSION_CHANGED');await started.promise;await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected
|
||||
assert.deepEqual(calls.map(x=>x.url),['/merchant/v1/orders/first-leg/one/submit','/auth/logout']);assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||
})
|
||||
|
||||
test('same identity new pair logout does not adopt another session inflight refresh',async()=>{
|
||||
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'old-session-rotated'})}return ok(c)})
|
||||
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise;http.setSession(newAccess,'new-login-refresh')
|
||||
const leaving=authApi(http).logoutMerchant(newAccess,'new-login-refresh');http.setSession('','');await leaving
|
||||
assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[1].data).refreshToken,'new-login-refresh');release.resolve();await rejected;assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||
})
|
||||
|
||||
test('logout rejects refreshed 19 digit identity differing only in low digit',async()=>{
|
||||
const raw='{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"}'
|
||||
const original=`test.${Buffer.from(raw).toString('base64url')}.test`
|
||||
for(const field of ['user_id','tenant_id','membership_id']){
|
||||
const changed=raw.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`),calls=[]
|
||||
const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:`test.${Buffer.from(changed).toString('base64url')}.test`,refreshToken:'replacement'});throw unauthorized(c)})
|
||||
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(original,'original-refresh'),e=>e.code==='SESSION_CHANGED');assert.equal(calls.length,2)
|
||||
}
|
||||
})
|
||||
@@ -1,9 +1,76 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { parse, compileScript } from 'vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./DataTable.vue', import.meta.url), 'utf8')
|
||||
|
||||
function paginationHarness(t) {
|
||||
const descriptor = parse(source).descriptor
|
||||
const compiled = compileScript(descriptor, { id: 'data-table-pagination-test' })
|
||||
const code = ts.transpileModule(compiled.content, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
const deps = { vue, '@lucide/vue': { ChevronLeft: {}, ChevronRight: {} }, './tableActions': {} }
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||
const component = exports.default
|
||||
component.render = () => null
|
||||
const state = vue.reactive({ page: 5, total: 5542, loading: false, error: false })
|
||||
const emitted = []
|
||||
const renderer = vue.createRenderer({
|
||||
createElement: tag => ({ tag }), createText: text => ({ text }), createComment: text => ({ text }),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const app = renderer.createApp({ render: () => vue.h(component, {
|
||||
data: [], columns: [], page: state.page, pageSize: 50, total: state.total, loading: state.loading,
|
||||
'onUpdate:page': value => { emitted.push(value); state.page = value },
|
||||
}, state.error ? { error: () => vue.h('div', 'Request failed') } : {}) })
|
||||
app.mount({})
|
||||
t.after(() => app.unmount())
|
||||
return { state, emitted }
|
||||
}
|
||||
|
||||
test('server-page loading must not reset the requested page when total temporarily clears', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.loading = true; state.total = 0
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
state.total = 5542; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
})
|
||||
|
||||
test('failed server page retains its page for explicit retry and emits no automatic fallback request', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.loading = true; state.total = 0
|
||||
await vue.nextTick()
|
||||
state.error = true; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
state.error = false; state.loading = true
|
||||
await vue.nextTick()
|
||||
state.total = 5542; state.loading = false
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 5)
|
||||
assert.deepEqual(emitted, [])
|
||||
})
|
||||
|
||||
test('settled successful totals still clamp out-of-range and empty pages', async t => {
|
||||
const { state, emitted } = paginationHarness(t)
|
||||
state.total = 120
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 3)
|
||||
state.total = 0
|
||||
await vue.nextTick()
|
||||
assert.equal(state.page, 1)
|
||||
assert.deepEqual(emitted, [3, 1])
|
||||
})
|
||||
|
||||
test('keeps action-only table toolbars on the left', () => {
|
||||
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
|
||||
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
|
||||
|
||||
@@ -88,7 +88,9 @@ watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
|
||||
page.value = 1
|
||||
}, { immediate: true })
|
||||
|
||||
watch([page, pageCount], ([value, count]) => {
|
||||
watch([page, pageCount, () => props.loading, () => Boolean(slots.error)], ([value, count, loading, hasError]) => {
|
||||
// A cleared total is not an authoritative page count while loading or showing a request error.
|
||||
if (loading || hasError) return
|
||||
const nextValue = normalizePage(value, count)
|
||||
if (value !== nextValue) page.value = nextValue
|
||||
}, { immediate: true })
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import test from 'node:test'
|
||||
|
||||
const script = (await readFile(new URL('../../scripts/deploy-production.sh', import.meta.url), 'utf8'))
|
||||
.replaceAll('\r\n', '\n')
|
||||
const compose = (await readFile(new URL('../../docker-compose.production.yml', import.meta.url), 'utf8'))
|
||||
.replaceAll('\r\n', '\n')
|
||||
|
||||
test('client production deployment switches healthy blue-green slots atomically', () => {
|
||||
const start = script.indexOf('compose run -d --no-deps --name "$candidate"')
|
||||
const health = script.indexOf('docker exec "$candidate" wget')
|
||||
const nginx = script.indexOf('nginx -t || ! nginx -s reload')
|
||||
const stop = script.indexOf('docker stop --time 30 "$active_container"')
|
||||
assert.ok(start >= 0 && start < health && health < nginx && nginx < stop)
|
||||
assert.match(script, /target_port=\$\(\(base_port \+ 20000\)\)/)
|
||||
assert.match(script, /target_port=\$\(\(base_port \+ 10000\)\)/)
|
||||
assert.match(script, /00-blue-green-admin-web\.conf/)
|
||||
assert.match(script, /00-blue-green-client-web\.conf/)
|
||||
assert.doesNotMatch(script, /nginx_config=\/www\/server\/panel\/vhost\/nginx\/(?:admin|app)\.buggoglobal\.com\.conf/)
|
||||
assert.match(script, /cp -f "\$backup" "\$nginx_config"/)
|
||||
})
|
||||
|
||||
test('client uses stable active gateway aliases on the routing network', () => {
|
||||
assert.match(compose, /API_UPSTREAM: "http:\/\/gateway-active:9000"/)
|
||||
assert.match(compose, /OVERSEAS_API_UPSTREAM: "http:\/\/gateway-overseas-active:9300"/)
|
||||
assert.match(compose, /name: firstleg-production-routing/)
|
||||
})
|
||||
@@ -1,67 +1,63 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { readFileSync, existsSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const config = readFileSync(new URL('../../nginx/default.conf.template', import.meta.url), 'utf8')
|
||||
const testCompose = readFileSync(new URL('../../docker-compose.test.yml', import.meta.url), 'utf8')
|
||||
const developmentCompose = readFileSync(new URL('../../docker-compose.development.yml', import.meta.url), 'utf8')
|
||||
const productionCompose = readFileSync(new URL('../../docker-compose.production.yml', import.meta.url), 'utf8')
|
||||
const jenkinsfile = readFileSync(new URL('../../Jenkinsfile', import.meta.url), 'utf8')
|
||||
const dockerfile = readFileSync(new URL('../../Dockerfile', import.meta.url), 'utf8')
|
||||
const root = new URL('../../', import.meta.url)
|
||||
const config = readFileSync(new URL('nginx/default.conf.template', root), 'utf8')
|
||||
const compose = readFileSync(new URL('docker-compose.test.yml', root), 'utf8')
|
||||
const jenkins = readFileSync(new URL('Jenkinsfile', root), 'utf8')
|
||||
const vite = readFileSync(new URL('vite.config.ts', root), 'utf8')
|
||||
|
||||
test('allows 50 MiB uploads with multipart overhead through both API proxies', () => {
|
||||
assert.match(config, /location \/api\/ \{[\s\S]*?client_max_body_size 55m;/)
|
||||
assert.match(config, /location \/overseas-api\/ \{[\s\S]*?client_max_body_size 55m;/)
|
||||
assert.equal(config.match(/client_max_body_size 55m;/g)?.length, 2)
|
||||
})
|
||||
|
||||
test('does not cache the SPA entry while keeping hashed assets immutable', () => {
|
||||
assert.match(config, /location = \/index\.html[\s\S]*no-store, no-cache, must-revalidate/)
|
||||
assert.match(config, /location \/assets\/[\s\S]*max-age=31536000, immutable/)
|
||||
assert.match(config, /location \/ \{[\s\S]*no-store, no-cache, must-revalidate[\s\S]*try_files \$uri \$uri\/ \/index\.html/)
|
||||
})
|
||||
|
||||
test('routes domestic and overseas browser APIs to their test gateways without duplicate api prefixes', () => {
|
||||
assert.match(testCompose, /- "host\.docker\.internal:host-gateway"/)
|
||||
assert.match(testCompose, /API_UPSTREAM: "\$\{API_UPSTREAM:-http:\/\/host\.docker\.internal:9000\}"/)
|
||||
assert.match(testCompose, /OVERSEAS_API_UPSTREAM: "\$\{OVERSEAS_API_UPSTREAM:-http:\/\/host\.docker\.internal:9300\}"/)
|
||||
assert.doesNotMatch(testCompose, /http:\/\/test-api-(?:cn|global)\.buggoglobal\.com/)
|
||||
assert.match(testCompose, /VITE_ADMIN_WEB_ORIGIN: "\$\{VITE_ADMIN_WEB_ORIGIN:-https:\/\/test-admin\.buggoglobal\.com\}"/)
|
||||
assert.match(config, /location \/overseas-api\/ \{[\s\S]*?rewrite \^\/overseas-api\/\(\.\*\)\$ \/api\/\$1 break;[\s\S]*?proxy_pass \$\{OVERSEAS_API_UPSTREAM\};/)
|
||||
test('all business traffic uses one Gateway without rewriting API paths', () => {
|
||||
assert.match(config, /location \/api\//)
|
||||
assert.match(config, /proxy_pass \$\{API_UPSTREAM\};/)
|
||||
assert.doesNotMatch(config, /overseas-api|OVERSEAS_API_UPSTREAM|rewrite/)
|
||||
assert.match(config, /client_max_body_size 55m;/)
|
||||
assert.match(config, /proxy_set_header Host \$proxy_host;/)
|
||||
assert.doesNotMatch(config, /\/api\/api/)
|
||||
assert.doesNotMatch(vite, /OVERSEAS_API|AUTH_API_PROXY_TARGET|IAM_API_PROXY_TARGET|WAREHOUSE_API_PROXY_TARGET/)
|
||||
})
|
||||
|
||||
test('connects the development client proxy to both development gateways', () => {
|
||||
assert.match(developmentCompose, /API_UPSTREAM: "http:\/\/firstleg-development-gateway:9000"/)
|
||||
assert.match(developmentCompose, /OVERSEAS_API_UPSTREAM: "http:\/\/firstleg-development-gateway-overseas:9300"/)
|
||||
assert.match(developmentCompose, /- development-backend/)
|
||||
assert.match(developmentCompose, /- development-overseas-backend/)
|
||||
assert.match(developmentCompose, /development-overseas-backend:[\s\S]*?external: true[\s\S]*?name: firstleg-development-overseas-network/)
|
||||
assert.doesNotMatch(developmentCompose, /test-api|prod(?:uction)?/i)
|
||||
test('test deployment requires an explicit shared network, Gateway and version', () => {
|
||||
for (const key of ['IMAGE_TAG']) {
|
||||
assert.ok(compose.includes('${' + key + ':?'))
|
||||
}
|
||||
assert.ok(compose.includes('${API_UPSTREAM:-http://gateway:9000}'))
|
||||
assert.ok(compose.includes('${TEST_NETWORK:-firstleg-test-network}'))
|
||||
assert.match(compose, /external: true/)
|
||||
assert.match(compose, /127\.0\.0\.1:/)
|
||||
assert.doesNotMatch(compose, /overseas|host\.docker\.internal|production|development/)
|
||||
assert.match(jenkins, /'java-builder' : 'java-test'/)
|
||||
assert.match(jenkins, /docker compose -f docker-compose\.test\.yml config --quiet/)
|
||||
assert.match(jenkins, /docker network inspect/)
|
||||
assert.match(jenkins, /scripts\/deploy-production\.sh/)
|
||||
assert.match(jenkins, /firstleg-production-ssh/)
|
||||
|
||||
})
|
||||
|
||||
test('keeps local environments on target nodes and uses credential-managed SSH for production', () => {
|
||||
assert.match(jenkinsfile, /env\.JOB_BASE_NAME\?\.endsWith\('-prod'\) \? 'java-builder'/)
|
||||
assert.match(jenkinsfile, /DEVELOPMENT_COMPOSE_PROJECT = 'client-web'/)
|
||||
assert.match(jenkinsfile, /docker compose -p "\$DEVELOPMENT_COMPOSE_PROJECT" -f "\$DEVELOPMENT_COMPOSE_FILE" up -d/)
|
||||
assert.doesNotMatch(jenkinsfile, /\/var\/jenkins_home\/\.ssh|docker save/)
|
||||
assert.match(jenkinsfile, /credentialsId: 'firstleg-production-ssh'/)
|
||||
assert.match(jenkinsfile, /git rev-parse origin\/main/)
|
||||
assert.match(productionCompose, /127\.0\.0\.1:\$\{HOST_PORT:-9002\}:80/)
|
||||
assert.match(productionCompose, /API_UPSTREAM: "http:\/\/gateway-active:9000"/)
|
||||
assert.match(productionCompose, /OVERSEAS_API_UPSTREAM: "http:\/\/gateway-overseas-active:9300"/)
|
||||
assert.match(productionCompose, /name: firstleg-production-routing/)
|
||||
assert.match(productionCompose, /name: firstleg-prod-infra-network/)
|
||||
test('application shell is revalidated and missing chunks remain 404', () => {
|
||||
assert.match(config, /location = \/index\.html/)
|
||||
assert.match(config, /no-store/)
|
||||
assert.match(config, /max-age=31536000, immutable/)
|
||||
assert.match(config, /try_files \$uri =404;/)
|
||||
assert.match(config, /try_files \$uri \$uri\/ \/index\.html;/)
|
||||
})
|
||||
|
||||
test('uses authenticated internal base images in CI', () => {
|
||||
assert.match(dockerfile, /ARG NODE_IMAGE=node:22-alpine/)
|
||||
assert.match(dockerfile, /ARG NGINX_IMAGE=nginx:1\.27-alpine/)
|
||||
assert.match(dockerfile, /FROM \$\{NODE_IMAGE\} AS build/)
|
||||
assert.match(dockerfile, /FROM \$\{NGINX_IMAGE\}/)
|
||||
assert.match(jenkinsfile, /NODE_BASE_IMAGE = '172\.31\.198\.7:10082\/java-project\/node:22-alpine'/)
|
||||
assert.match(jenkinsfile, /NGINX_BASE_IMAGE = '172\.31\.198\.7:10082\/java-project\/nginx:1\.27-alpine'/)
|
||||
assert.match(jenkinsfile, /withCredentials\(\[usernamePassword\(/)
|
||||
assert.match(jenkinsfile, /export DOCKER_CONFIG="\$\{WORKSPACE\}@tmp\/docker-auth"/)
|
||||
|
||||
test('container build excludes local environment values and waits for Nginx health', () => {
|
||||
const ignore = readFileSync(new URL('.dockerignore', root), 'utf8')
|
||||
assert.match(ignore, /^\.env$/m)
|
||||
assert.match(ignore, /^\.env\.\*$/m)
|
||||
assert.match(compose, /healthcheck:/)
|
||||
assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
|
||||
assert.match(jenkins, /up -d --wait --wait-timeout 120/)
|
||||
})
|
||||
|
||||
test('gray production is isolated from TEST and routes to the single Gateway', () => {
|
||||
const production = readFileSync(new URL('docker-compose.production.yml', root), 'utf8')
|
||||
assert.match(production, /name: firstleg-production-network/)
|
||||
assert.match(production, /API_UPSTREAM: "http:\/\/gateway:9000"/)
|
||||
assert.match(production, /127\.0\.0\.1:/)
|
||||
assert.match(production, /healthcheck:/)
|
||||
assert.doesNotMatch(production, /test-network|gateway-overseas|gateway-active|routing-network/)
|
||||
assert.doesNotMatch(jenkins, /wecom|sendProductionWeComNotification/)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
||||
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
||||
@@ -108,7 +110,7 @@ test('source contract: locks body scrolling while open and restores it on close
|
||||
})
|
||||
|
||||
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
|
||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*try \{/)
|
||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*const logoutToken = auth.token\s*try \{/)
|
||||
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
||||
})
|
||||
|
||||
@@ -148,3 +150,49 @@ test('source contract: routes denied pages to an explicit 403 state', () => {
|
||||
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
||||
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
||||
})
|
||||
|
||||
function logoutHarness(t) {
|
||||
const script = layoutSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('layout.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const nodes = ast.statements.filter(node => (ts.isFunctionDeclaration(node) && node.name?.text === 'handleLogout') || (ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes('() => auth.isAuthenticated')))
|
||||
const code = ts.transpileModule(nodes.map(node => node.getText(ast)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
let rejectLogout, confirm
|
||||
const remote = new Promise((_, no) => { rejectLogout = no })
|
||||
const confirmation = new Promise(yes => { confirm = yes })
|
||||
const calls = [], warnings = []
|
||||
const auth = vue.reactive({ token: 'A', isAuthenticated: true, logout: () => { calls.push('logout'); auth.token = ''; auth.isAuthenticated = false; return remote } })
|
||||
const scope = vue.effectScope(); t.after(() => scope.stop())
|
||||
const handler = scope.run(() => new Function('watch', 'auth', 'workspace', 'unsaved', 'router', 'ElMessageBox', 'ElMessage', code + ';return handleLogout')(vue.watch, auth, { clear: () => calls.push('workspace') }, { hasDirty: false, clear: () => calls.push('unsaved') }, { replace: path => { calls.push(path); return Promise.resolve() } }, { confirm: () => confirmation }, { warning: value => warnings.push(value) }))
|
||||
return { auth, handler, confirm, rejectLogout, calls, warnings }
|
||||
}
|
||||
|
||||
test('logout navigates before remote completion and late failure cannot affect a new login', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||
assert.deepEqual(h.calls, ['logout', 'workspace', 'unsaved', '/login'])
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
h.auth.token = 'B'; h.auth.isAuthenticated = true; await vue.nextTick()
|
||||
h.rejectLogout(new Error('SESSION_CHANGED')); await Promise.resolve(); await vue.nextTick()
|
||||
assert.equal(h.auth.token, 'B'); assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.calls.filter(item => item === '/login').length, 1)
|
||||
assert.equal(h.warnings.length, 0)
|
||||
})
|
||||
|
||||
test('cross-tab logout leaves protected route and stale confirmation never logs out a new identity', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler()
|
||||
h.auth.token = 'B'; h.confirm(); await clicked
|
||||
assert.equal(h.calls.length, 0)
|
||||
h.auth.token = ''; h.auth.isAuthenticated = false; await vue.nextTick()
|
||||
assert.deepEqual(h.calls, ['workspace', 'unsaved', '/login'])
|
||||
assert.match(layoutSource, /<div v-if="auth.isAuthenticated" class="client-shell"/)
|
||||
})
|
||||
|
||||
test('remote logout failure reports incomplete server revocation without leaving protected content visible', async t => {
|
||||
const h = logoutHarness(t)
|
||||
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||
h.rejectLogout(new Error('offline')); await Promise.resolve()
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.ok(h.calls.includes('/login'))
|
||||
assert.deepEqual(h.warnings, ['已退出本页,服务器会话注销未完成'])
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessageBox } from 'element-plus'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
||||
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
||||
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
||||
@@ -108,6 +108,7 @@ watch(
|
||||
watch(
|
||||
() => auth.permissionCodes.join('|'),
|
||||
() => {
|
||||
if (!auth.isAuthenticated) return
|
||||
const result = workspace.reconcile(isAllowedTab)
|
||||
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
||||
},
|
||||
@@ -119,6 +120,7 @@ watch(
|
||||
if (authenticated) return
|
||||
workspace.clear()
|
||||
unsaved.clear()
|
||||
void router.replace('/login')
|
||||
},
|
||||
)
|
||||
|
||||
@@ -163,6 +165,7 @@ function handleBeforeUnload(event: BeforeUnloadEvent) {
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
const logoutToken = auth.token
|
||||
try {
|
||||
await ElMessageBox.confirm(unsaved.hasDirty
|
||||
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
||||
@@ -176,15 +179,16 @@ async function handleLogout() {
|
||||
throw error
|
||||
}
|
||||
|
||||
workspace.clear()
|
||||
unsaved.clear()
|
||||
await auth.logout()
|
||||
await router.replace('/login')
|
||||
if (auth.token !== logoutToken) return
|
||||
void auth.logout().catch(() => {
|
||||
if (!auth.isAuthenticated) ElMessage.warning('已退出本页,服务器会话注销未完成')
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||
<div v-if="auth.isAuthenticated" class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, 'is-dashboard-route': route.path === '/' }">
|
||||
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
|
||||
<button
|
||||
ref="menuButtonRef"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiRequest } from '@/api/http'
|
||||
import { apiRequest, revokeCapturedSession } from '@/api/http'
|
||||
import type { TokenPair } from '@/api/session'
|
||||
|
||||
export interface RegisterMerchantRequest {
|
||||
@@ -35,8 +35,8 @@ export function registerMerchant(payload: RegisterMerchantRequest) {
|
||||
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
||||
}
|
||||
|
||||
export function logoutMerchant(refreshToken: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: '/auth/logout', data: { refreshToken } })
|
||||
export function logoutMerchant(accessToken: string, refreshToken: string) {
|
||||
return revokeCapturedSession(accessToken, refreshToken)
|
||||
}
|
||||
|
||||
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
||||
|
||||
+105
-99
@@ -61,18 +61,34 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
const permissionCodes = ref<string[]>([])
|
||||
const sessionRestored = ref(false)
|
||||
|
||||
let logoutRequest: { accessToken: string; refreshToken: string; promise: Promise<void> } | undefined
|
||||
let generation = 0
|
||||
let contextRequest: { generation: number; promise: Promise<void> } | undefined
|
||||
let restoreTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
function identity(value: MerchantJwtPayload | null) {
|
||||
return value ? JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type]) : ''
|
||||
}
|
||||
|
||||
function applyToken(accessToken: string) {
|
||||
const decoded = decodeMerchantToken(accessToken)
|
||||
const changedIdentity = identity(decoded) !== identity(payload.value)
|
||||
if (accessToken === token.value && payload.value && !changedIdentity) return
|
||||
generation++
|
||||
if (changedIdentity) {
|
||||
user.value = null
|
||||
profile.value = { ...emptyProfile }
|
||||
permissionCodes.value = mapPermissions()
|
||||
}
|
||||
payload.value = decoded
|
||||
token.value = accessToken
|
||||
user.value = currentUser(decoded, user.value?.tenantName)
|
||||
profile.value.username = decoded.username
|
||||
profile.value.realName = decoded.username
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
clearSessionTokens()
|
||||
function resetLocalSession() {
|
||||
generation++
|
||||
token.value = ''
|
||||
payload.value = null
|
||||
user.value = null
|
||||
@@ -81,137 +97,123 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
sessionRestored.value = true
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
clearSessionTokens()
|
||||
resetLocalSession()
|
||||
}
|
||||
|
||||
function applyStoredSession() {
|
||||
const storedToken = getAccessToken()
|
||||
if (!storedToken) {
|
||||
token.value = ''
|
||||
payload.value = null
|
||||
user.value = null
|
||||
permissionCodes.value = []
|
||||
profile.value = { ...emptyProfile }
|
||||
sessionRestored.value = true
|
||||
resetLocalSession()
|
||||
return
|
||||
}
|
||||
try {
|
||||
applyToken(storedToken)
|
||||
sessionRestored.value = false
|
||||
} catch {
|
||||
clearSession()
|
||||
}
|
||||
}
|
||||
|
||||
if (token.value) {
|
||||
try {
|
||||
applyToken(token.value)
|
||||
} catch (error) {
|
||||
if (!(error instanceof MerchantTokenExpiredError && getRefreshToken())) clearSession()
|
||||
resetLocalSession()
|
||||
if (error instanceof MerchantTokenExpiredError && getRefreshToken()) sessionRestored.value = false
|
||||
}
|
||||
}
|
||||
|
||||
applyStoredSession()
|
||||
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
||||
|
||||
async function loadSessionContext() {
|
||||
if (!payload.value) return
|
||||
const currentPermissionCodes = await getCurrentMerchantPermissionCodes()
|
||||
const currentAccessToken = getAccessToken()
|
||||
if (currentAccessToken && currentAccessToken !== token.value) applyToken(currentAccessToken)
|
||||
permissionCodes.value = mapPermissions(currentPermissionCodes)
|
||||
const [tenant, personalProfile] = await Promise.all([
|
||||
getTenantProfile(),
|
||||
getMerchantPersonalProfile(),
|
||||
])
|
||||
user.value = currentUser(payload.value, tenant.tenantName)
|
||||
profile.value = {
|
||||
...profile.value,
|
||||
realName: personalProfile.displayName || payload.value.username,
|
||||
phone: personalProfile.phone || '',
|
||||
email: personalProfile.email || '',
|
||||
tenantName: tenant.tenantName,
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreSession() {
|
||||
if (sessionRestored.value) return
|
||||
if (!isAuthenticated.value) {
|
||||
if (!getRefreshToken()) {
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
if (contextRequest?.generation === generation) return contextRequest.promise
|
||||
let requestGeneration = generation
|
||||
let requestAccessToken = getAccessToken()
|
||||
const isCurrent = () => requestGeneration === generation && getAccessToken() === requestAccessToken
|
||||
const promise = (async () => {
|
||||
try {
|
||||
applyToken(await refreshAuthenticatedSession())
|
||||
if (!isAuthenticated.value) {
|
||||
if (!getRefreshToken()) return
|
||||
const refreshedToken = await refreshAuthenticatedSession()
|
||||
if (requestGeneration !== generation) return restoreSession()
|
||||
applyToken(refreshedToken)
|
||||
requestAccessToken = refreshedToken
|
||||
requestGeneration = generation
|
||||
if (contextRequest) contextRequest.generation = generation
|
||||
}
|
||||
const requestPayload = payload.value
|
||||
if (!requestPayload) return
|
||||
const [codes, tenant, personalProfile] = await Promise.all([
|
||||
getCurrentMerchantPermissionCodes(), getTenantProfile(), getMerchantPersonalProfile(),
|
||||
])
|
||||
if (!isCurrent()) {
|
||||
applyStoredSession()
|
||||
return restoreSession()
|
||||
}
|
||||
permissionCodes.value = mapPermissions(codes)
|
||||
user.value = currentUser(requestPayload, tenant.tenantName)
|
||||
profile.value = {
|
||||
username: requestPayload.username,
|
||||
realName: personalProfile.displayName || requestPayload.username,
|
||||
phone: personalProfile.phone || '', email: personalProfile.email || '', tenantName: tenant.tenantName,
|
||||
}
|
||||
sessionRestored.value = true
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
sessionRestored.value = false
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
})()
|
||||
contextRequest = { generation: requestGeneration, promise }
|
||||
try { await promise } finally {
|
||||
if (contextRequest?.promise === promise) contextRequest = undefined
|
||||
}
|
||||
try {
|
||||
await loadSessionContext()
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
return
|
||||
}
|
||||
sessionRestored.value = true
|
||||
}
|
||||
|
||||
function synchronizeSession() {
|
||||
// Identity changes and logout revoke local rights immediately. Coalesce pair writes
|
||||
// before loading the new context; same-identity rotation retains confirmed rights.
|
||||
applyStoredSession()
|
||||
if (restoreTimer) clearTimeout(restoreTimer)
|
||||
restoreTimer = setTimeout(() => {
|
||||
restoreTimer = undefined
|
||||
void restoreSession().catch(() => {})
|
||||
}, 0)
|
||||
}
|
||||
|
||||
async function login(loginId: string, password: string, remember = false) {
|
||||
const attempt = ++generation
|
||||
const tokens = await loginMerchant(loginId, password)
|
||||
const decoded = decodeMerchantToken(tokens.accessToken)
|
||||
if (attempt !== generation) return
|
||||
decodeMerchantToken(tokens.accessToken)
|
||||
persistTokenPair(tokens)
|
||||
persistRememberedLoginId(loginId, remember)
|
||||
token.value = tokens.accessToken
|
||||
payload.value = decoded
|
||||
user.value = currentUser(decoded)
|
||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
try {
|
||||
await loadSessionContext()
|
||||
sessionRestored.value = true
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
sessionRestored.value = true
|
||||
}
|
||||
applyToken(tokens.accessToken)
|
||||
await restoreSession()
|
||||
}
|
||||
|
||||
async function acceptImpersonationCode(code: string) {
|
||||
const attempt = ++generation
|
||||
const exchanged = await exchangeImpersonationCode(code)
|
||||
const decoded = decodeMerchantToken(exchanged.accessToken)
|
||||
if (attempt !== generation) return
|
||||
decodeMerchantToken(exchanged.accessToken)
|
||||
persistTemporaryAccessToken(exchanged.accessToken)
|
||||
token.value = exchanged.accessToken
|
||||
payload.value = decoded
|
||||
user.value = currentUser(decoded)
|
||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
||||
permissionCodes.value = mapPermissions()
|
||||
sessionRestored.value = false
|
||||
try {
|
||||
await loadSessionContext()
|
||||
} catch (error) {
|
||||
if (isExpiredSessionError(error)) {
|
||||
clearSession()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
sessionRestored.value = true
|
||||
applyToken(exchanged.accessToken)
|
||||
await restoreSession()
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
function logout() {
|
||||
const accessToken = getAccessToken()
|
||||
const refreshToken = getRefreshToken()
|
||||
try {
|
||||
if (refreshToken) await logoutMerchant(refreshToken)
|
||||
} finally {
|
||||
clearSession()
|
||||
}
|
||||
if (logoutRequest && ((!accessToken && !refreshToken)
|
||||
|| (logoutRequest.accessToken === accessToken && logoutRequest.refreshToken === refreshToken))) return logoutRequest.promise
|
||||
const pending = accessToken || refreshToken
|
||||
? logoutMerchant(accessToken, refreshToken)
|
||||
: Promise.resolve()
|
||||
clearSession()
|
||||
const request = { accessToken, refreshToken, promise: pending.finally(() => {
|
||||
if (logoutRequest === request) logoutRequest = undefined
|
||||
}) }
|
||||
logoutRequest = request
|
||||
return request.promise
|
||||
}
|
||||
|
||||
function hasPermission(permission?: string) {
|
||||
@@ -224,10 +226,13 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
}
|
||||
|
||||
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
|
||||
const requestGeneration = generation
|
||||
const requestToken = getAccessToken()
|
||||
const updated = await updateMerchantPersonalProfile({
|
||||
displayName: next.realName.trim(),
|
||||
email: next.email.trim(),
|
||||
})
|
||||
if (requestGeneration !== generation || requestToken !== getAccessToken()) return
|
||||
updateProfile({
|
||||
realName: updated.displayName,
|
||||
phone: updated.phone || '',
|
||||
@@ -236,8 +241,9 @@ export const useAuthStore = defineStore('client-auth', () => {
|
||||
}
|
||||
|
||||
window.addEventListener('cc-client-session-expired', clearSession)
|
||||
window.addEventListener('cc-client-session-updated', synchronizeSession)
|
||||
window.addEventListener('storage', (event) => {
|
||||
if (event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token') applyStoredSession()
|
||||
if (event.storageArea === localStorage && (event.key === null || event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token')) synchronizeSession()
|
||||
})
|
||||
|
||||
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
function compile(path, dependencies = {}) {
|
||||
const code = ts.transpileModule(readFileSync(new URL(path, import.meta.url), 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function storage() {
|
||||
const values = new Map()
|
||||
return { getItem: key => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: key => values.delete(key) }
|
||||
}
|
||||
function token(user = 1, tenant = 1, membership = 1, nonce = 'a') {
|
||||
return `test.${Buffer.from(JSON.stringify({ user_id: user, tenant_id: tenant, membership_id: membership, username: `user-${user}`, app_code: 'MERCHANT', exp: 4102444800, nonce })).toString('base64url')}.test`
|
||||
}
|
||||
const flush = () => new Promise(resolve => setTimeout(resolve, 10))
|
||||
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
|
||||
function harness(t, expired = false) {
|
||||
globalThis.localStorage = storage(); globalThis.sessionStorage = storage()
|
||||
const listeners = new Map()
|
||||
globalThis.window = { addEventListener: (name, fn) => listeners.set(name, fn) }
|
||||
const session = compile('../../../api/session.ts')
|
||||
const initial = expired ? `test.${Buffer.from(JSON.stringify({ user_id: 1, tenant_id: 1, membership_id: 1, username: 'user-1', app_code: 'MERCHANT', exp: 1 })).toString('base64url')}.test` : token()
|
||||
session.persistTokenPair({ accessToken: initial, refreshToken: 'refresh-a' })
|
||||
let reads = 0
|
||||
const behavior = { permissions: async () => ['edit'], tenant: async () => ({ tenantName: 'company' }) }
|
||||
class ApiError extends Error { constructor(status) { super('failed'); this.status = status } }
|
||||
const module = compile('./auth.ts', {
|
||||
vue, pinia, '@/api/session': session,
|
||||
'@/modules/auth/api/auth': { logoutMerchant: async (access, refresh) => behavior.logout?.(refresh, access) },
|
||||
'@/modules/auth/utils/jwt': compile('../utils/jwt.ts'),
|
||||
'@/api/http': { ApiError, refreshAuthenticatedSession: async () => {
|
||||
session.persistTokenPair({ accessToken: token(1, 1, 1, 'refreshed'), refreshToken: 'refresh-new' })
|
||||
listeners.get('cc-client-session-updated')()
|
||||
return session.getAccessToken()
|
||||
} },
|
||||
'@/modules/tenant-management/public': {
|
||||
FRONTEND_TO_MERCHANT_PERMISSION_CODES: { 'order:first-leg:edit': 'edit' },
|
||||
hasMappedMerchantPermission: (_, codes) => codes.has('edit'),
|
||||
getCurrentMerchantPermissionCodes: () => { reads++; return behavior.permissions() },
|
||||
getTenantProfile: () => behavior.tenant(), getMerchantPersonalProfile: async () => ({}),
|
||||
},
|
||||
})
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(async () => { await flush(); pinia.disposePinia(context) })
|
||||
const auth = module.useAuthStore()
|
||||
const event = key => listeners.get('storage')({ key, storageArea: localStorage })
|
||||
function rotate(nextToken = token(1, 1, 1, 'b')) {
|
||||
session.persistTokenPair({ accessToken: nextToken, refreshToken: 'refresh-b' })
|
||||
event(session.ACCESS_TOKEN_KEY); event(session.REFRESH_TOKEN_KEY)
|
||||
}
|
||||
return { auth, session, event, rotate, behavior, listeners, ApiError, reads: () => reads }
|
||||
}
|
||||
|
||||
test('pair storage rotation retains same-identity rights and automatically reloads once without navigation', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
assert.equal(h.auth.sessionRestored, false)
|
||||
await flush()
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false, 'new server rights replace the retained snapshot')
|
||||
assert.equal(h.reads(), 2)
|
||||
h.listeners.get('cc-client-session-updated')()
|
||||
await flush()
|
||||
assert.equal(h.reads(), 2, 'already applied token does not reload twice')
|
||||
})
|
||||
|
||||
test('startup expired-token refresh waits for restored rights even when local rotation emits an event', async t => {
|
||||
const h = harness(t, true)
|
||||
await h.auth.restoreSession()
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.reads(), 1)
|
||||
})
|
||||
|
||||
test('logout storage event immediately clears rights and late context cannot restore them', async t => {
|
||||
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
const pending = h.auth.restoreSession()
|
||||
h.session.clearSessionTokens(); h.event(h.session.ACCESS_TOKEN_KEY)
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.deepEqual(h.auth.permissionCodes, [])
|
||||
old.resolve(['edit']); await pending; await flush()
|
||||
assert.equal(h.auth.user, null)
|
||||
assert.deepEqual(h.auth.permissionCodes, [])
|
||||
})
|
||||
|
||||
test('account, customer and membership switches revoke rights immediately and reject stale request results', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
h.rotate(); await flush()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate(token(2, 2, 2, 'new'))
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
await flush(); old.resolve(['edit']); await flush()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
h.behavior.permissions = async () => ['edit']; h.rotate(token(2, 3, 3, 'next')); await flush()
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
h.rotate(token(2, 3, 4, 'membership'))
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
})
|
||||
|
||||
test('context failure is not marked restored and explicit retry coalesces concurrent callers', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.permissions = async () => { throw new Error('offline') }
|
||||
await h.auth.restoreSession()
|
||||
assert.equal(h.auth.sessionRestored, false)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), false)
|
||||
const pending = deferred(); h.behavior.permissions = () => pending.promise
|
||||
const first = h.auth.restoreSession(), second = h.auth.restoreSession()
|
||||
assert.equal(h.reads(), 2)
|
||||
pending.resolve(['edit']); await Promise.all([first, second])
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
assert.equal(h.auth.hasPermission('order:first-leg:edit'), true)
|
||||
})
|
||||
|
||||
test('stale unauthorized context response cannot clear a newer account', async t => {
|
||||
const h = harness(t); const old = deferred(); h.behavior.permissions = () => old.promise
|
||||
const pending = h.auth.restoreSession()
|
||||
h.behavior.permissions = async () => []
|
||||
h.rotate(token(2, 2, 2)); await flush()
|
||||
old.reject(new h.ApiError(401)); await pending
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.auth.sessionRestored, true)
|
||||
})
|
||||
|
||||
test('store logout clears immediately and late revocation failure preserves a later cross-tab login', async t => {
|
||||
const h = harness(t); await h.auth.restoreSession()
|
||||
const remote = deferred(); let sentRefresh
|
||||
h.behavior.logout = refresh => { sentRefresh = refresh; return remote.promise }
|
||||
const pending = h.auth.logout()
|
||||
const rejected = assert.rejects(pending, /offline/)
|
||||
assert.equal(sentRefresh, 'refresh-a')
|
||||
assert.equal(h.auth.isAuthenticated, false)
|
||||
assert.equal(h.session.getAccessToken(), '')
|
||||
h.rotate(token(2, 2, 2)); await flush()
|
||||
remote.reject(new Error('offline')); await rejected
|
||||
assert.equal(h.auth.user.id, '2')
|
||||
assert.equal(h.auth.isAuthenticated, true)
|
||||
assert.equal(h.session.getRefreshToken(), 'refresh-b')
|
||||
})
|
||||
|
||||
test('duplicate logout joins captured pair revocation and does not send again',async t=>{
|
||||
const h=harness(t);const remote=deferred();let count=0,sent
|
||||
h.behavior.logout=(refresh,access)=>{count++;sent={refresh,access};return remote.promise}
|
||||
const a=h.auth.logout(),b=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(sent.access,token());assert.equal(sent.refresh,'refresh-a');assert.equal(count,1);remote.resolve();await Promise.all([a,b])
|
||||
})
|
||||
|
||||
test('B logout during A pending revokes B; A finally cannot release B deduplication',async t=>{
|
||||
const h=harness(t);const a=deferred(),b=deferred(),calls=[]
|
||||
h.behavior.logout=(refresh,access)=>{calls.push({refresh,access});return calls.length===1?a.promise:b.promise}
|
||||
const leavingA=h.auth.logout();h.rotate(token(2,2,2));await flush();assert.equal(h.auth.isAuthenticated,true)
|
||||
const leavingB=h.auth.logout();assert.equal(h.auth.isAuthenticated,false);assert.equal(h.session.getAccessToken(),'');assert.equal(calls.length,2);assert.equal(calls[1].access,token(2,2,2))
|
||||
a.resolve();await leavingA;const duplicateB=h.auth.logout();assert.equal(calls.length,2);let duplicateFinished=false;void duplicateB.then(()=>{duplicateFinished=true});await flush();assert.equal(duplicateFinished,false);b.resolve();await Promise.all([leavingB,duplicateB])
|
||||
})
|
||||
@@ -102,7 +102,8 @@ test('opens complete service and privacy documents from registration', () => {
|
||||
test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||
assert.match(authApiSource, /\/auth\/login/)
|
||||
assert.match(authApiSource, /\/auth\/register/)
|
||||
assert.match(authApiSource, /\/auth\/logout/)
|
||||
assert.match(authApiSource, /revokeCapturedSession\(accessToken, refreshToken\)/)
|
||||
assert.match(httpSource, /\/auth\/logout/)
|
||||
assert.match(httpSource, /refreshPromise/)
|
||||
assert.match(httpSource, /\/auth\/refresh/)
|
||||
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
||||
@@ -117,7 +118,8 @@ test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
||||
assert.match(authStoreSource, /decodeMerchantToken/)
|
||||
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
|
||||
assert.match(authStoreSource, /applyToken\(await refreshAuthenticatedSession\(\)\)/)
|
||||
assert.match(authStoreSource, /const refreshedToken = await refreshAuthenticatedSession\(\)/)
|
||||
assert.match(authStoreSource, /applyToken\(refreshedToken\)/)
|
||||
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
||||
})
|
||||
|
||||
@@ -152,7 +154,7 @@ test('shows a forced re-login notice after login identifiers change', () => {
|
||||
test('keeps a valid local session during temporary context and refresh outages', () => {
|
||||
assert.match(authStoreSource, /function isExpiredSessionError/)
|
||||
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
||||
assert.match(authStoreSource, /sessionRestored\.value = true\s+return/)
|
||||
assert.match(authStoreSource, /if \(!isCurrent\(\)\) return\s+sessionRestored\.value = false/)
|
||||
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
||||
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { overseasApiRequest } from '@/api/overseasHttp'
|
||||
import { apiRequest } from '@/api/http'
|
||||
|
||||
export interface PageResult<T> {
|
||||
records: T[]
|
||||
@@ -141,23 +141,23 @@ function normalizePage<T>(data: PageResult<T>): PageResult<T> {
|
||||
}
|
||||
|
||||
export function listBusinessOrders<T>(kind: CrossBorderBusinessKind, params: BusinessOrderQuery) {
|
||||
return overseasApiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage)
|
||||
return apiRequest<PageResult<T>>({ method: 'GET', url: endpointByKind[kind], params }).then(normalizePage)
|
||||
}
|
||||
|
||||
export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: string) {
|
||||
return overseasApiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
||||
return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
||||
}
|
||||
|
||||
export function createProcurement(payload: ProcurementCreate) {
|
||||
return overseasApiRequest<ProcurementDetail>({ method: 'POST', url: endpointByKind.procurement, data: payload })
|
||||
return apiRequest<ProcurementDetail>({ method: 'POST', url: endpointByKind.procurement, data: payload })
|
||||
}
|
||||
|
||||
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) {
|
||||
return overseasApiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
|
||||
return apiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
|
||||
}
|
||||
|
||||
export function updateTransport(kind: 'trucking' | 'looseboard', orderNo: string, payload: TransportUpdate) {
|
||||
return overseasApiRequest<TransportDetail>({
|
||||
return apiRequest<TransportDetail>({
|
||||
method: kind === 'trucking' ? 'PATCH' : 'PUT',
|
||||
url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}`,
|
||||
data: payload,
|
||||
|
||||
@@ -566,14 +566,19 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
|
||||
})
|
||||
}
|
||||
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload })
|
||||
export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) {
|
||||
export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
|
||||
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||
}
|
||||
|
||||
export function submitMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number }, idempotencyKey: string) {
|
||||
return apiRequest<void>({
|
||||
method: 'POST',
|
||||
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
||||
data: payload,
|
||||
headers: { 'Idempotency-Key': idempotencyKey },
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,9 +1,28 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('forwards optional tax mode and pagination through the current GET endpoint', async () => {
|
||||
const calls = []
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||
const api = {}
|
||||
new Function('require', 'exports', code)(id => {
|
||||
assert.equal(id, '@/api/http')
|
||||
return { apiRequest: async config => { calls.push(config); return { records: [] } } }
|
||||
}, api)
|
||||
await api.getMerchantUnifiedOrders({ page: 2, size: 200, taxMode: 'TAX_REFUND' })
|
||||
await api.getMerchantUnifiedOrders({ taxMode: 'BUY_DECLARATION' })
|
||||
await api.getMerchantUnifiedOrders()
|
||||
assert.deepEqual(calls, [
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 2, size: 200, taxMode: 'TAX_REFUND' } },
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200, taxMode: 'BUY_DECLARATION' } },
|
||||
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200 } },
|
||||
])
|
||||
})
|
||||
|
||||
test('keeps the merchant unified-order boundary and one-click palletization status', () => {
|
||||
assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
|
||||
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ApiError, apiRequest } from '@/api/http'
|
||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||
import { apiRequest } from '@/api/http'
|
||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||
|
||||
export type ApiUnifiedOrderMainStatus =
|
||||
| 'PENDING_REVIEW'
|
||||
@@ -60,11 +60,12 @@ export interface MerchantUnifiedTransportSummary {
|
||||
|
||||
export interface MerchantUnifiedOrderRow {
|
||||
orderId: number | string
|
||||
orderVersion: number
|
||||
tenantId: number | string
|
||||
orderNo: string | null
|
||||
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||
lxCode?: string | null
|
||||
mainStatus: ApiUnifiedOrderMainStatus
|
||||
mainStatus: ApiUnifiedOrderMainStatus | 'DRAFT' | 'CANCELLED'
|
||||
nextAction: string | null
|
||||
customerFeeConfirmationRequired: boolean
|
||||
internalOrderStatus: ApiFirstLegStatus | null
|
||||
@@ -83,6 +84,8 @@ export interface MerchantUnifiedOrderRow {
|
||||
actualGrossWeightKg: number | null
|
||||
actualVolumeCbm: number | null
|
||||
pickupMethod: ApiPickupMethod | null
|
||||
taxMode: ApiTaxMode | null
|
||||
customsInspection: boolean | null
|
||||
requestedPickupAt: string | null
|
||||
containerMode: ApiContainerMode | null
|
||||
destinationType: ApiDestinationType | null
|
||||
@@ -130,7 +133,25 @@ export interface MerchantUnifiedCustomNode {
|
||||
attachmentIds: Array<number | string>
|
||||
}
|
||||
|
||||
export interface MerchantTransportNode {
|
||||
standardNode: string
|
||||
nodeSequence: number
|
||||
providerCode: string | null
|
||||
estimatedAt: string | null
|
||||
actualAt: string | null
|
||||
locationCode: string | null
|
||||
locationName: string | null
|
||||
}
|
||||
|
||||
export interface MerchantTransportFragment {
|
||||
inboundCode: string | null
|
||||
cabinetNo: string | null
|
||||
containerNo: string | null
|
||||
nodes: MerchantTransportNode[]
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderDetail {
|
||||
transportFragments: MerchantTransportFragment[]
|
||||
summary: MerchantUnifiedOrderRow
|
||||
order: MerchantFirstLegOrderDetail
|
||||
timeline: MerchantUnifiedTimelineEvent[]
|
||||
@@ -139,6 +160,8 @@ export interface MerchantUnifiedOrderDetail {
|
||||
}
|
||||
|
||||
export interface MerchantUnifiedOrderQuery {
|
||||
taxMode?: ApiTaxMode
|
||||
loaded?: boolean
|
||||
keyword?: string
|
||||
fbaCode?: string
|
||||
orderNo?: string
|
||||
@@ -154,6 +177,31 @@ export interface MerchantUnifiedOrderQuery {
|
||||
|
||||
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
||||
|
||||
export interface MerchantOrderWorkbenchQuery {
|
||||
cargoKeyword?: string
|
||||
receivingWarehouseId?: string
|
||||
channelName?: string
|
||||
destinationType?: string
|
||||
trackingNumber?: string
|
||||
mainStatus?: string
|
||||
createdFrom?: string
|
||||
createdTo?: string
|
||||
queue?: 'all' | 'fee' | 'customs' | 'draft'
|
||||
page?: number
|
||||
size?: number
|
||||
}
|
||||
|
||||
export interface MerchantOrderWorkbench {
|
||||
page: PageResult<MerchantUnifiedOrderRow>
|
||||
queues: { all: number; fee: number; customs: number; draft: number }
|
||||
channelNames: string[]
|
||||
}
|
||||
|
||||
export function getMerchantOrderWorkbench(params: MerchantOrderWorkbenchQuery = {}) {
|
||||
return apiRequest<MerchantOrderWorkbench>({ method: 'GET', url: `${unifiedOrderBaseUrl}/workbench`,
|
||||
params: { ...params, page: params.page ?? 1, size: params.size ?? 10 } })
|
||||
}
|
||||
|
||||
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
||||
const { page, size, ...filters } = params
|
||||
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
||||
@@ -169,7 +217,3 @@ export function getMerchantUnifiedOrder(orderId: number | string) {
|
||||
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
||||
})
|
||||
}
|
||||
|
||||
export function isUnifiedOrderQueryUnavailable(error: unknown) {
|
||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||
function harness(t) {
|
||||
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const code = ts.transpileModule(source + '\nexport { loadDetail, detail, clearanceResults, loading, errorMessage, selectedInboundIds, clearanceError, clearanceLoading, retryClearanceResults, close }', { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const props = vue.reactive({ modelValue: false, orderId: 'A', canEdit: true }), requests = [], clearances = [], updates = [], view = {}
|
||||
const unmounts = []
|
||||
const dependencies = { vue: { ...vue, onBeforeUnmount: fn => unmounts.push(fn) }, 'element-plus': { ElMessage: {} }, '@/modules/first-leg/api/customs': {
|
||||
getMerchantCustomsForOrder: id => { const pending = deferred(); requests.push({ id, ...pending }); return pending.promise },
|
||||
getMerchantClearanceResults: id => { const pending = deferred(); clearances.push({ id, ...pending }); return pending.promise },
|
||||
merchantCustomsErrorMessage: error => error.message,
|
||||
} }
|
||||
const scope = vue.effectScope()
|
||||
scope.run(() => new Function('require', 'exports', 'defineProps', 'defineEmits', code)(id => {
|
||||
assert.ok(id in dependencies, id); return dependencies[id]
|
||||
}, view, () => props, () => (...args) => updates.push(args)))
|
||||
t.after(() => scope.stop())
|
||||
return { props, requests, clearances, updates, view, unmount: () => unmounts.forEach(fn => fn()) }
|
||||
}
|
||||
const detail = id => ({ loadingPlanId: id, inbounds: [{ orderId: id, inboundId: `IN-${id}`, taxMode: 'TAX_REFUND' }] })
|
||||
const tick = async () => { await Promise.resolve(); await vue.nextTick(); await Promise.resolve() }
|
||||
|
||||
test('result section stays pending while the refreshed detail is still loading', async t => {
|
||||
const h = harness(t)
|
||||
h.props.initialDetail = detail('A')
|
||||
h.props.modelValue = true
|
||||
await tick()
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'A')
|
||||
assert.equal(h.view.loading.value, true)
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
assert.equal(h.clearances.length, 0)
|
||||
const template = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||
assert.match(template, /v-else-if="loading \|\| clearanceLoading"/)
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.clearanceLoading.value, true)
|
||||
h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.view.loading.value, false)
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||
})
|
||||
|
||||
test('switching orders while open starts the new request and ignores stale detail', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.orderId = 'B'; await tick()
|
||||
assert.deepEqual(h.requests.map(r => r.id), ['A', 'B'])
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||
assert.deepEqual(h.view.selectedInboundIds.value, ['IN-B'])
|
||||
assert.deepEqual(h.clearances.map(r => r.id), ['B'])
|
||||
assert.equal(h.updates.length, 1)
|
||||
})
|
||||
|
||||
test('closing before detail response prevents stale data and events', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.modelValue = false; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.view.detail.value, null); assert.equal(h.view.loading.value, false)
|
||||
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0)
|
||||
})
|
||||
|
||||
test('closing and reopening ignores the previous clearance response', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
h.props.modelValue = false; await tick(); h.props.orderId = 'B'; h.props.modelValue = true; await tick()
|
||||
h.requests[1].resolve(detail('B')); await tick()
|
||||
h.clearances[1].resolve([{ kind: 'B' }]); await tick()
|
||||
h.clearances[0].resolve([{ kind: 'A' }]); await tick()
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ kind: 'B' }])
|
||||
assert.equal(h.view.detail.value.loadingPlanId, 'B'); assert.equal(h.updates.length, 1)
|
||||
})
|
||||
|
||||
test('stale detail failure cannot clear the next request loading or show an error', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.props.orderId = 'B'; await tick(); h.requests[0].reject(new Error('old failure')); await tick()
|
||||
assert.equal(h.view.loading.value, true); assert.equal(h.view.errorMessage.value, '')
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.view.loading.value, false); assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||
})
|
||||
|
||||
test('unmount invalidates pending detail requests', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick(); h.unmount()
|
||||
h.requests[0].resolve(detail('A')); await tick()
|
||||
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0); assert.equal(h.view.detail.value, null)
|
||||
})
|
||||
|
||||
test('result failure retains documents and exposes error; retry queries only results and deduplicates clicks', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve({ ...detail('A'), documents: [{ documentId: 'document-A' }] }); await tick()
|
||||
h.clearances[0].reject(new Error('结果服务暂不可用')); await tick()
|
||||
assert.equal(h.view.errorMessage.value, '')
|
||||
assert.equal(h.view.clearanceError.value, '结果服务暂不可用')
|
||||
assert.equal(h.view.detail.value.documents[0].documentId, 'document-A')
|
||||
assert.equal(h.view.loading.value, false)
|
||||
const retry = h.view.retryClearanceResults()
|
||||
await h.view.retryClearanceResults()
|
||||
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 2)
|
||||
assert.equal(h.view.clearanceLoading.value, true)
|
||||
h.clearances[1].resolve([{ id: 'result-A' }]); await retry
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'result-A' }])
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
})
|
||||
|
||||
test('normal open requests detail and results exactly once and distinguishes successful empty results', async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 1)
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.equal(h.view.clearanceLoading.value, false)
|
||||
})
|
||||
|
||||
for (const transition of ['switch', 'close', 'unmount']) {
|
||||
for (const outcome of ['resolve', 'reject']) {
|
||||
test(`${transition} ignores stale result retry ${outcome}`, async t => {
|
||||
const h = harness(t); h.props.modelValue = true; await tick()
|
||||
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].reject(new Error('first failure')); await tick()
|
||||
const retry = h.view.retryClearanceResults()
|
||||
if (transition === 'switch') { h.props.orderId = 'B'; await tick() }
|
||||
else if (transition === 'close') { h.view.close(); h.props.modelValue = false; await tick() }
|
||||
else h.unmount()
|
||||
if (outcome === 'resolve') h.clearances[1].resolve([{ id: 'old-A' }])
|
||||
else h.clearances[1].reject(new Error('old retry failure'))
|
||||
await retry
|
||||
assert.equal(h.view.clearanceError.value, '')
|
||||
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||
if (transition === 'switch') {
|
||||
h.requests[1].resolve(detail('B')); await tick(); h.clearances[2].resolve([{ id: 'B' }]); await tick()
|
||||
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'B' }])
|
||||
} else {
|
||||
await h.view.retryClearanceResults()
|
||||
assert.equal(h.clearances.length, 2)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
test('result error and retry reuse existing section error styling before the empty state', () => {
|
||||
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||
assert.match(source, /v-if="clearanceError" class="customs-error" role="alert"/)
|
||||
assert.match(source, /@click="retryClearanceResults"/)
|
||||
assert.match(source, /v-else-if="loading \|\| clearanceLoading"/)
|
||||
assert.match(source, /v-else-if="!clearanceResults.length"/)
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue'
|
||||
import {
|
||||
@@ -46,6 +46,12 @@ const replaceInput = ref<HTMLInputElement>()
|
||||
const mutating = ref(false)
|
||||
const downloadingKey = ref('')
|
||||
const clearanceResults = ref<MerchantClearanceResult[]>([])
|
||||
const clearanceError = ref('')
|
||||
const clearanceLoading = ref(false)
|
||||
let clearanceRequest = 0
|
||||
let disposed = false
|
||||
let detailRequest = 0
|
||||
onBeforeUnmount(() => { disposed = true; detailRequest += 1; resetClearanceResults() })
|
||||
|
||||
const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? [])
|
||||
const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED')
|
||||
@@ -66,32 +72,80 @@ function initializeSelection(value: MerchantCustomsContainer) {
|
||||
selectedInboundIds.value = currentOrderIds
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
if (!props.orderId) return
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
function resetClearanceResults() {
|
||||
clearanceRequest += 1
|
||||
clearanceResults.value = []
|
||||
clearanceError.value = ''
|
||||
clearanceLoading.value = false
|
||||
}
|
||||
|
||||
async function loadClearanceResults() {
|
||||
if (disposed || !props.modelValue || !props.orderId || !detail.value || clearanceLoading.value) return
|
||||
const request = ++clearanceRequest
|
||||
const parentRequest = detailRequest
|
||||
const orderId = props.orderId
|
||||
const isCurrent = () => !disposed && request === clearanceRequest && parentRequest === detailRequest && props.modelValue && props.orderId === orderId
|
||||
clearanceLoading.value = true
|
||||
clearanceError.value = ''
|
||||
try {
|
||||
const result = await getMerchantCustomsForOrder(props.orderId)
|
||||
detail.value = result
|
||||
initializeSelection(result)
|
||||
try { clearanceResults.value = await getMerchantClearanceResults(props.orderId) } catch { clearanceResults.value = [] }
|
||||
emit('updated', result)
|
||||
const results = await getMerchantClearanceResults(orderId)
|
||||
if (isCurrent()) clearanceResults.value = results
|
||||
} catch (error) {
|
||||
detail.value = null
|
||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||
if (isCurrent()) clearanceError.value = merchantCustomsErrorMessage(error, '海关申报结果加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (isCurrent()) clearanceLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, (open) => {
|
||||
async function retryClearanceResults() {
|
||||
if (loading.value) return
|
||||
await loadClearanceResults()
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
if (disposed || !props.modelValue || !props.orderId) return
|
||||
const request = ++detailRequest
|
||||
resetClearanceResults()
|
||||
const orderId = props.orderId
|
||||
const isCurrent = () => request === detailRequest && props.modelValue && props.orderId === orderId
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const result = await getMerchantCustomsForOrder(orderId)
|
||||
if (!isCurrent()) return
|
||||
detail.value = result
|
||||
initializeSelection(result)
|
||||
await loadClearanceResults()
|
||||
if (!isCurrent()) return
|
||||
emit('updated', result)
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
detail.value = null
|
||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||
} finally {
|
||||
if (isCurrent()) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => [props.modelValue, props.orderId] as const, ([open]) => {
|
||||
detailRequest += 1
|
||||
detail.value = null
|
||||
resetClearanceResults()
|
||||
selectedInboundIds.value = []
|
||||
editingDocument.value = null
|
||||
replacingDocument.value = null
|
||||
errorMessage.value = ''
|
||||
loading.value = false
|
||||
if (!open) return
|
||||
detail.value = props.initialDetail ?? null
|
||||
const initial = props.initialDetail
|
||||
detail.value = initial?.inbounds.some((item) => item.orderId === props.orderId) ? initial : null
|
||||
if (detail.value) initializeSelection(detail.value)
|
||||
void loadDetail()
|
||||
})
|
||||
}, { immediate: true })
|
||||
|
||||
function close() {
|
||||
detailRequest += 1
|
||||
resetClearanceResults()
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
@@ -303,7 +357,8 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
||||
|
||||
<div v-if="locked" class="customs-locked" role="status">
|
||||
<LockKeyhole :size="18" />
|
||||
<div><strong>{{ detail.brokerSubmittedAt ? '已发送报关行执行' : '报关资料已锁定' }}</strong><span>{{ detail.brokerSubmittedAt ? '平台已将客户确认后的回执发送给报关行,等待真实报关完税文件。' : '报关开始后仅可查看和下载,不提供退回或解锁。' }}</span></div>
|
||||
<div v-if="detail.status === 'COMPLETED'"><strong>报关已完成</strong><span>真实报关完税文件已齐全,可查看和下载资料、回执及完税文件。</span></div>
|
||||
<div v-else><strong>{{ detail.brokerSubmittedAt ? '已发送报关行执行' : '报关资料已锁定' }}</strong><span>{{ detail.brokerSubmittedAt ? '平台已将客户确认后的回执发送给报关行,等待真实报关完税文件。' : '客户原始资料已冻结,仍可确认或打回待确认的报关行回执。' }}</span></div>
|
||||
</div>
|
||||
|
||||
<section class="customs-section">
|
||||
@@ -325,7 +380,13 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
||||
<div class="customs-section-title">
|
||||
<div><h3>海关申报结果</h3><p>平台完成正式申报后,客户可查看与本订单相关的查验、补充资料和放行结果。</p></div>
|
||||
</div>
|
||||
<el-empty v-if="!clearanceResults.length" description="暂无海关结果" :image-size="48" />
|
||||
<div v-if="clearanceError" class="customs-error" role="alert">
|
||||
<strong>海关申报结果加载失败</strong>
|
||||
<span>{{ clearanceError }}</span>
|
||||
<el-button :loading="clearanceLoading" @click="retryClearanceResults">重新加载</el-button>
|
||||
</div>
|
||||
<el-skeleton v-else-if="loading || clearanceLoading" :rows="2" animated />
|
||||
<el-empty v-else-if="!clearanceResults.length" description="暂无海关结果" :image-size="48" />
|
||||
<div v-else class="clearance-result-list">
|
||||
<div v-for="item in clearanceResults" :key="item.id" class="clearance-result-row">
|
||||
<div><strong>{{ clearanceResultLabel(item) }}</strong><span>{{ formatDateTime(item.occurredAt) }} · 报关单号 {{ item.customsEntryNo || '—' }}</span></div>
|
||||
@@ -382,6 +443,9 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:global(.customs-documents-dialog.el-dialog) { display: flex; max-height: 70vh; flex-direction: column; overflow: hidden; }
|
||||
:global(.customs-documents-dialog .el-dialog__header), :global(.customs-documents-dialog .el-dialog__footer) { flex: 0 0 auto; }
|
||||
:global(.customs-documents-dialog .el-dialog__body) { min-height: 0; flex: 1 1 auto; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.customs-error { display: grid; gap: 10px; justify-items: start; padding: 22px; border: 1px solid #f1b8b8; background: #fff7f7; color: #9f2d2d; }
|
||||
.customs-error span { overflow-wrap: anywhere; font-size: 12px; }
|
||||
.customs-summary { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)) auto; align-items: center; gap: 18px; padding: 16px 18px; border: 1px solid var(--border); background: #f8faf9; }
|
||||
|
||||
@@ -26,14 +26,15 @@ function stageState(index: number) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ol class="progress-stages" aria-label="订单主状态阶段">
|
||||
<p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消,不再继续履约。</p>
|
||||
<ol v-else class="progress-stages" aria-label="订单主状态阶段">
|
||||
<li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined">
|
||||
<span class="stage-marker" aria-hidden="true"><Check v-if="index < currentIndex" :size="13" /><CircleDot v-else :size="13" /></span>
|
||||
<span class="stage-label">{{ stage.label }}</span>
|
||||
</li>
|
||||
</ol>
|
||||
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">订单提交后开始记录主状态进度。</p>
|
||||
<div class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||
<div v-if="order.status !== 'CANCELLED'" class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
import { customerTransportRows } from '../utils/transportFacts'
|
||||
|
||||
const props = defineProps<{ fragments: MerchantTransportFragment[] }>()
|
||||
const rows = computed(() => customerTransportRows(props.fragments))
|
||||
function time(value: string | null) { return value ? value.replace('T', ' ') : '—' }
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="transport-facts" aria-label="实际装载片段运输节点">
|
||||
<strong>运输节点</strong>
|
||||
<el-table v-if="rows.length" :data="rows" row-key="key" border size="small">
|
||||
<el-table-column prop="inboundCode" label="入仓码" min-width="155" />
|
||||
<el-table-column prop="cabinetNo" label="柜次" width="90" />
|
||||
<el-table-column prop="containerNo" label="集装箱号" min-width="145" />
|
||||
<el-table-column prop="nodeLabel" label="节点" min-width="150" />
|
||||
<el-table-column label="实际时间" min-width="175"><template #default="{ row }">{{ time(row.actualAt) }}</template></el-table-column>
|
||||
<el-table-column label="预计时间" min-width="175"><template #default="{ row }">{{ time(row.estimatedAt) }}</template></el-table-column>
|
||||
<el-table-column prop="location" label="地点" min-width="130" />
|
||||
<el-table-column prop="source" label="来源" width="105" />
|
||||
</el-table>
|
||||
<p v-else>暂无实际装载片段的运输节点。预计时间不表示实际发生。</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.transport-facts { margin-top: 9px; }
|
||||
.transport-facts > strong { display: block; padding: 7px 0 5px; color: var(--navy); font-size: 11px; }
|
||||
.transport-facts > p { color: var(--muted); font-size: 11px; }
|
||||
</style>
|
||||
@@ -0,0 +1,430 @@
|
||||
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 source = readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in dependencies, id); return dependencies[id] }, exports)
|
||||
return exports
|
||||
}
|
||||
function harness(t) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = []
|
||||
const behavior = { failWrite: false, failRead: false, version: 9, status: 'DRAFT' }
|
||||
const api = compile('../api/firstLeg.ts', { '@/api/http': { apiRequest: async config => {
|
||||
calls.push(structuredClone(config))
|
||||
if (config.method === 'GET') {
|
||||
if (behavior.failRead) throw new Error('读取失败')
|
||||
return { order: { id: 'one', orderNo: 'FL-ONE', version: behavior.version, status: behavior.status, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress, destinationCountryCode: 'US' }, cargoes: [] }
|
||||
}
|
||||
if (behavior.failWrite || (behavior.failSubmit && config.url.endsWith('/submit'))) throw new Error('响应丢失')
|
||||
if (config.url.endsWith('/submit') && behavior.failSubmitRead) behavior.failRead = true
|
||||
if (config.method === 'POST' && config.url === '/merchant/v1/orders/first-leg') return 'one'
|
||||
} } })
|
||||
const module = compile('./firstLegOrders.ts', {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': api,
|
||||
'@/modules/first-leg/api/unifiedOrders': {
|
||||
getMerchantUnifiedOrder: async () => ({ summary: { orderId: 'one', mainStatus: null }, order: { order: { id: 'one', status: behavior.status, version: behavior.version, receivingWarehouseId: 'warehouse', receivingWarehouseAddress: behavior.receivingWarehouseAddress } }, timeline: [] }),
|
||||
},
|
||||
'@/modules/first-leg/utils/firstLegOrder': { canClientEditFirstLegOrder: status => status === 'DRAFT', getFirstLegStatusLabel: value => value },
|
||||
'@/modules/first-leg/utils/warehousePagination': {},
|
||||
})
|
||||
const store = module.useFirstLegOrdersStore()
|
||||
store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC' }]
|
||||
const draft = { receivingWarehouseId: 'warehouse', destinationType: 'PRIVATE', destinationCountryCode: 'US', items: [], customerRemark: '原草稿' }
|
||||
return { store, api, calls, behavior, draft }
|
||||
}
|
||||
|
||||
function displayedWarehouseAddress(order) {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const expressions = [...view.matchAll(/\{\{ (detailOrder\.receivingWarehouseSnapshot\.(?:province|city|address)) \}\}/g)]
|
||||
assert.equal(expressions.length, 3)
|
||||
return expressions.map(([, expression]) => new Function('detailOrder', `return ${expression}`)(order)).join('')
|
||||
}
|
||||
|
||||
test('complete address is identical for cold unified, warm unified, raw detail and remark-only save', async t => {
|
||||
const h = harness(t)
|
||||
const fullAddress = 'CN 浙江省 义乌市 仓库路 8 号 322000'
|
||||
h.behavior.receivingWarehouseAddress = fullAddress
|
||||
h.store.warehouses = []
|
||||
const cold = await h.store.loadDetail('one')
|
||||
assert.equal(displayedWarehouseAddress(cold), fullAddress)
|
||||
h.store.warehouses = [{ id: 'warehouse', name: '国内仓', warehouseType: 'DOMESTIC', province: '浙江省', city: '义乌市', address: '主档已更新的地址' }]
|
||||
h.store.orders = []
|
||||
const warm = await h.store.loadDetail('one')
|
||||
const raw = await h.store.loadDraftDetail('one')
|
||||
for (const detail of [warm, raw]) {
|
||||
assert.equal(displayedWarehouseAddress(detail), fullAddress)
|
||||
assert.equal(detail.receivingWarehouseSnapshot.province, '')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.city, '')
|
||||
}
|
||||
const session = h.store.beginDraftEdit(raw)
|
||||
h.draft.customerRemark = '仅修改备注'
|
||||
const saved = await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
assert.equal(displayedWarehouseAddress(saved), fullAddress)
|
||||
const write = h.calls.find(call => call.method === 'PUT')
|
||||
assert.equal(write.data.draft.customerRemark, '仅修改备注')
|
||||
assert.equal(Object.hasOwn(write.data.draft, 'receivingWarehouseAddress'), false)
|
||||
assert.equal(h.behavior.receivingWarehouseAddress, fullAddress)
|
||||
assert.equal(h.store.warehouses[0].province, '浙江省')
|
||||
assert.equal(h.store.warehouses[0].address, '主档已更新的地址')
|
||||
})
|
||||
|
||||
test('structured master address stays structured when no order address snapshot exists', async t => {
|
||||
const h = harness(t)
|
||||
h.store.warehouses = [{ id: 'warehouse', name: '国内仓', province: '浙江省', city: '义乌市', address: '仓库路 8 号', warehouseType: 'DOMESTIC' }]
|
||||
const detail = await h.store.loadDetail('one')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.province, '浙江省')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.city, '义乌市')
|
||||
assert.equal(detail.receivingWarehouseSnapshot.address, '仓库路 8 号')
|
||||
assert.equal(displayedWarehouseAddress(detail), '浙江省义乌市仓库路 8 号')
|
||||
})
|
||||
|
||||
test('raw and unified cancelled detail remain CANCELLED even when unified mainStatus is null', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.status = 'CANCELLED'
|
||||
const raw = await h.store.loadDraftDetail('one')
|
||||
assert.equal(raw.status, 'CANCELLED')
|
||||
const unified = await h.store.loadDetail('one')
|
||||
assert.equal(unified.status, 'CANCELLED')
|
||||
h.behavior.status = 'APPROVED'
|
||||
const unknown = await h.store.loadDetail('one')
|
||||
assert.notEqual(unknown.status, 'CANCELLED', 'unknown summary must not be reclassified as cancellation')
|
||||
})
|
||||
|
||||
test('fresh direct draft detail preserves raw DRAFT with null unified summary and opens an edit session', async t => {
|
||||
const h = harness(t)
|
||||
assert.equal(h.store.orders.length, 0)
|
||||
const direct = await h.store.loadDetail('one')
|
||||
assert.equal(direct.status, 'DRAFT')
|
||||
assert.equal(h.store.beginDraftEdit(direct).expectedVersion, 9)
|
||||
h.store.orders = []
|
||||
const refreshed = await h.store.loadDetail('one')
|
||||
assert.equal(refreshed.status, 'DRAFT')
|
||||
h.store.orders = []
|
||||
h.behavior.status = 'APPROVED'
|
||||
const unknown = await h.store.loadDetail('one')
|
||||
assert.notEqual(unknown.status, 'DRAFT')
|
||||
assert.notEqual(unknown.status, 'CANCELLED')
|
||||
assert.throws(() => h.store.beginDraftEdit(unknown), /重新打开/)
|
||||
})
|
||||
|
||||
test('cancelled detail summary has no pending overseas synchronization entries', () => {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const script = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const declaration = ast.statements.flatMap(node => ts.isVariableStatement(node) ? [...node.declarationList.declarations] : []).find(node => node.name.getText(ast) === 'progressSummaryItems')
|
||||
const code = ts.transpileModule('const progressSummaryItems = ' + declaration.initializer.getText(ast), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const summary = new Function('computed', 'detailOrder', code + '; return progressSummaryItems.value')(vue.computed, { value: { status: 'CANCELLED' } })
|
||||
assert.deepEqual(summary, [])
|
||||
})
|
||||
|
||||
test('edit freezes detail version rather than cached list version and replays same key/body after uncertain result', async t => {
|
||||
const h = harness(t)
|
||||
const original = await h.store.loadDraftDetail('one')
|
||||
const session = h.store.beginDraftEdit(original)
|
||||
h.store.orders = [{ ...original, version: 0 }]
|
||||
h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '测试企业', 'one', session), /响应丢失/)
|
||||
const first = h.calls.find(call => call.method === 'PUT')
|
||||
assert.equal(first.data.expectedVersion, 9)
|
||||
assert.equal(first.data.draft.customerRemark, '原草稿')
|
||||
assert.ok(first.headers['Idempotency-Key'])
|
||||
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT'], 'no pre-save version refresh')
|
||||
h.behavior.failWrite = false; h.behavior.version = 10
|
||||
const result = await h.store.saveDraft(h.draft, '测试企业', 'one', session)
|
||||
const writes = h.calls.filter(call => call.method === 'PUT')
|
||||
assert.deepEqual(writes[1], first)
|
||||
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'PUT', 'GET', 'PUT', 'GET'])
|
||||
assert.equal(result.version, 10)
|
||||
})
|
||||
|
||||
test('changed retry payload or missing edit session fails closed without issuing a new write', async t => {
|
||||
const h = harness(t)
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one'), /重新打开/)
|
||||
assert.equal(h.calls.length, 0)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session))
|
||||
h.draft.customerRemark = '不同内容'
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /重试原内容/)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
assert.equal(session.expectedVersion, 9)
|
||||
assert.ok(Object.isFrozen(session))
|
||||
})
|
||||
|
||||
test('read failure after successful edit preserves the same command for retry', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
h.behavior.failRead = true
|
||||
await assert.rejects(h.store.saveDraft(h.draft, '客户', 'one', session), /读取失败/)
|
||||
h.behavior.failRead = false
|
||||
await h.store.saveDraft(h.draft, '客户', 'one', session)
|
||||
const writes = h.calls.filter(call => call.method === 'PUT')
|
||||
assert.deepEqual(writes[0], writes[1])
|
||||
})
|
||||
|
||||
test('cancel forwards version and reason without rejecting submitted orders locally; retry keeps key and body', async t => {
|
||||
const h = harness(t)
|
||||
h.behavior.status = 'SUBMITTED'
|
||||
h.store.orders = [{ id: 'one', status: 'PENDING_REVIEW', version: 0 }]
|
||||
h.behavior.failWrite = true
|
||||
await assert.rejects(h.store.cancelOrder('one', 12, '客户要求取消'), /响应丢失/)
|
||||
const first = h.calls[0]
|
||||
assert.equal(first.method, 'POST')
|
||||
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/cancel')
|
||||
assert.deepEqual(first.data, { expectedVersion: 12, reason: '客户要求取消' })
|
||||
await assert.rejects(h.store.cancelOrder('one', 13, '其他原因'), /原版本和原因/)
|
||||
assert.equal(h.calls.length, 1)
|
||||
h.behavior.failWrite = false
|
||||
await h.store.cancelOrder('one', 12, '客户要求取消')
|
||||
assert.deepEqual(h.calls[2], first)
|
||||
assert.equal(h.calls[1].method, 'GET')
|
||||
assert.equal(h.store.orders.length, 0)
|
||||
})
|
||||
|
||||
test('cancel requires a detail version and a nonempty reason', async t => {
|
||||
const h = harness(t)
|
||||
await assert.rejects(h.store.cancelOrder('one', undefined, '理由'))
|
||||
await assert.rejects(h.store.cancelOrder('one', 1, ' '))
|
||||
assert.equal(h.calls.length, 0)
|
||||
})
|
||||
|
||||
test('cancellation decision reads raw server status and version including SUBMITTED', async t => {
|
||||
const h = harness(t)
|
||||
for (const status of ['DRAFT', 'SUBMITTED', 'APPROVED', 'ACCEPTED', 'REJECTED']) {
|
||||
h.behavior.status = status
|
||||
const target = await h.store.prepareCancellation('one')
|
||||
assert.equal(target.expectedVersion, 9)
|
||||
assert.equal(target.businessNo, 'FL-ONE')
|
||||
}
|
||||
for (const status of ['PROCESSING', 'COMPLETED', 'CANCELLED']) {
|
||||
h.behavior.status = status
|
||||
await assert.rejects(h.store.prepareCancellation('one'), /不允许取消/)
|
||||
}
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
})
|
||||
|
||||
function cancellationViewHarness() {
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['canOfferCancellation', 'cancelOrder'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const calls = [], messages = [], prompts = []
|
||||
const canCancelOrder = vue.ref(true), cancellingOrderId = vue.ref(''), pendingCancellation = vue.shallowRef()
|
||||
class ApiError extends Error { constructor() { super('订单版本已变化'); this.code = 'A0409'; this.status = 409 } }
|
||||
const behavior = { error: null }
|
||||
const store = {
|
||||
prepareCancellation: async id => { calls.push(['prepare', id]); return { id, expectedVersion: 12, businessNo: 'FL-ONE', statusLabel: '审核中' } },
|
||||
cancelOrder: async (...args) => { calls.push(['cancel', ...args]); if (behavior.error) throw behavior.error },
|
||||
load: async query => calls.push(['load', query]),
|
||||
}
|
||||
const ElMessageBox = {
|
||||
prompt: async (message, title, options) => { prompts.push({ message, title, options }); return { value: '客户申请取消' } },
|
||||
confirm: async (...args) => calls.push(['confirm', ...args]),
|
||||
}
|
||||
const ElMessage = { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) }
|
||||
const globals = { canCancelOrder, cancellingOrderId, pendingCancellation, store, ElMessageBox, ElMessage, ApiError,
|
||||
loadOrderPage: async () => calls.push(['load']),
|
||||
isDetailPage: vue.ref(true), router: { push: async route => calls.push(['route', route]) } }
|
||||
const handler = new Function(...Object.keys(globals), code + '\nreturn cancelOrder')(...Object.values(globals))
|
||||
return { handler, calls, messages, prompts, canCancelOrder, pendingCancellation, behavior, ApiError }
|
||||
}
|
||||
|
||||
test('cancel UI uses mandatory-reason centered prompt and refreshes after successful submitted-order cancellation', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
await h.handler({ id: 'one', status: 'PENDING_REVIEW' })
|
||||
assert.match(h.prompts[0].message, /FL-ONE.*审核中/)
|
||||
const validate = h.prompts[0].options.inputValidator
|
||||
assert.notEqual(validate(' '), true)
|
||||
assert.notEqual(validate('x'.repeat(501)), true)
|
||||
assert.equal(validate('合理原因'), true)
|
||||
assert.deepEqual(h.calls.map(call => call[0]), ['prepare', 'cancel', 'load', 'route'])
|
||||
assert.deepEqual(h.calls[1], ['cancel', 'one', 12, '客户申请取消'])
|
||||
})
|
||||
|
||||
test('cancel UI keeps an uncertain command for explicit retry, but conflict requires a fresh decision', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
const order = { id: 'one', status: 'DRAFT' }
|
||||
h.behavior.error = new Error('网络无响应')
|
||||
await h.handler(order)
|
||||
assert.equal(h.pendingCancellation.value.expectedVersion, 12)
|
||||
h.behavior.error = null
|
||||
await h.handler(order)
|
||||
assert.equal(h.prompts.length, 1)
|
||||
assert.equal(h.calls.filter(call => call[0] === 'prepare').length, 1)
|
||||
assert.equal(h.calls.filter(call => call[0] === 'confirm').length, 1)
|
||||
assert.deepEqual(h.calls.filter(call => call[0] === 'cancel')[0], h.calls.filter(call => call[0] === 'cancel')[1])
|
||||
h.behavior.error = new h.ApiError()
|
||||
await h.handler(order)
|
||||
assert.equal(h.pendingCancellation.value, undefined)
|
||||
assert.match(h.messages.at(-1), /刷新订单后重新确认/)
|
||||
})
|
||||
|
||||
test('cancel UI blocks unavailable permission and irreversible visible stages before reads or writes', async () => {
|
||||
const h = cancellationViewHarness()
|
||||
h.canCancelOrder.value = false
|
||||
await h.handler({ id: 'one', status: 'DRAFT' })
|
||||
h.canCancelOrder.value = true
|
||||
await h.handler({ id: 'one', status: 'LOADED' })
|
||||
assert.equal(h.calls.length, 0)
|
||||
assert.equal(h.prompts.length, 0)
|
||||
})
|
||||
|
||||
test('both editor entry points capture detail sessions and both save paths pass them', () => {
|
||||
const view = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
assert.equal((view.match(/editingSession\.value = store\.beginDraftEdit\(detailedOrder\)/g) ?? []).length, 2)
|
||||
assert.equal((view.match(/store\.saveDraft(?:ForSubmission)?\(cloneDraft\(form\), tenantStore\.company\.companyName, editingId\.value, editingSession\.value\)/g) ?? []).length, 2)
|
||||
})
|
||||
|
||||
test('submit reads raw detail version rather than list zero and replays original key and version after timeout', async t => {
|
||||
const h = harness(t)
|
||||
h.store.orders = [{ id: 'one', status: 'DRAFT', version: 0 }]
|
||||
h.behavior.failSubmit = true
|
||||
await assert.rejects(h.store.submitSaved('one', 'ACTIVE'), /响应丢失/)
|
||||
const first = h.calls[1]
|
||||
assert.equal(first.url, '/merchant/v1/orders/first-leg/one/submit')
|
||||
assert.deepEqual(first.data, { expectedVersion: 9 })
|
||||
assert.ok(first.headers['Idempotency-Key'])
|
||||
h.behavior.version = 10; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
|
||||
await h.store.submitSaved('one', 'ACTIVE')
|
||||
assert.deepEqual(h.calls[3], first)
|
||||
assert.deepEqual(h.calls.map(call => call.method), ['GET', 'POST', 'GET', 'POST', 'GET'])
|
||||
assert.equal(h.store.hasPendingSubmission('one'), false)
|
||||
})
|
||||
|
||||
test('submit refuses missing version or non-draft first decision and preserves command after failed readback', async t => {
|
||||
const h = harness(t)
|
||||
for (const version of [undefined, -1, 1.5]) {
|
||||
h.behavior.version = version
|
||||
await assert.rejects(h.store.submitSaved('one'), /版本缺失/)
|
||||
}
|
||||
h.behavior.version = 0; h.behavior.status = 'SUBMITTED'
|
||||
await assert.rejects(h.store.submitSaved('one'), /不是草稿/)
|
||||
assert.ok(h.calls.every(call => call.method === 'GET'))
|
||||
h.behavior.status = 'DRAFT'; h.behavior.failSubmitRead = true
|
||||
await assert.rejects(h.store.submitSaved('one'), /读取失败/)
|
||||
assert.equal(h.store.hasPendingSubmission('one'), true)
|
||||
h.behavior.failRead = false; h.behavior.failSubmitRead = false
|
||||
await h.store.submitSaved('one')
|
||||
const posts = h.calls.filter(call => call.method === 'POST')
|
||||
assert.deepEqual(posts[0], posts[1])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 0 }, 'raw detail zero is valid')
|
||||
})
|
||||
|
||||
test('save then submit retries without another save and changed form requires an explicit new decision', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
h.behavior.failSubmit = true
|
||||
await assert.rejects(h.store.submitSaved('one'))
|
||||
const first = h.calls.find(call => call.url.endsWith('/submit'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
h.draft.customerRemark = '新决定'
|
||||
await assert.rejects(h.store.saveDraftForSubmission(h.draft, '客户', 'one', session), /重新编辑/)
|
||||
h.behavior.status = 'SUBMITTED'
|
||||
await assert.rejects(h.store.beginNewSubmissionEdit('one'), /不能重新编辑/)
|
||||
assert.equal(h.store.hasPendingSubmission('one'), true)
|
||||
h.behavior.status = 'DRAFT'; h.behavior.version = 12
|
||||
const newSession = await h.store.beginNewSubmissionEdit('one')
|
||||
assert.equal(newSession.expectedVersion, 12)
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', newSession)
|
||||
h.behavior.version = 13; h.behavior.failSubmit = false
|
||||
await h.store.submitSaved('one')
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.notEqual(posts[1].headers['Idempotency-Key'], first.headers['Idempotency-Key'])
|
||||
assert.deepEqual(posts[1].data, { expectedVersion: 13 })
|
||||
})
|
||||
|
||||
test('failed initial submit read does not resave the prepared draft on retry', async t => {
|
||||
const h = harness(t)
|
||||
const session = h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
h.behavior.failRead = true
|
||||
await assert.rejects(h.store.submitSaved('one'))
|
||||
await h.store.saveDraftForSubmission(h.draft, '客户', 'one', session)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
})
|
||||
|
||||
async function submissionViewHarness(t) {
|
||||
const h = harness(t)
|
||||
const source = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const functions = ast.statements.filter(node => ts.isFunctionDeclaration(node) && ['submitOrder', 'confirmSubmissionEdit', 'submitSelectedDraftOrders'].includes(node.name?.text)).map(node => node.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const messages = [], confirmations = []
|
||||
const globals = {
|
||||
store: h.store, saving: vue.ref(false), form: h.draft, cloneDraft: draft => structuredClone(draft),
|
||||
editingId: vue.ref('one'), editingSession: vue.shallowRef(h.store.beginDraftEdit(await h.store.loadDraftDetail('one'))),
|
||||
companySubmissionBlocked: vue.ref(false), companyAuditLoaded: vue.ref(true), tenantStore: { company: { companyName: '客户', auditStatus: 'ACTIVE' } },
|
||||
validateEditorForm: async () => true, markEditorClean: () => {}, editorOpen: vue.ref(true), isCreatePage: vue.ref(false), loadPageData: async () => {},
|
||||
batchSubmitting: vue.ref(false), selectedDraftOrders: vue.ref([{ id: 'one', version: 0 }]), pendingBatchSubmissionIds: vue.ref([]),
|
||||
searchOrders: async () => { globals.selectedDraftOrders.value = [] }, appliedFilters: vue.ref({}),
|
||||
ElMessageBox: { confirm: async message => { confirmations.push(message); if (h.behavior.cancelConfirm) throw 'cancel' } },
|
||||
ElMessage: { error: message => messages.push(message), warning: message => messages.push(message), success: message => messages.push(message) },
|
||||
}
|
||||
const handlers = new Function(...Object.keys(globals), code + '\nreturn {submitOrder, submitSelectedDraftOrders}')(...Object.values(globals))
|
||||
return { ...h, ...handlers, globals, messages, confirmations }
|
||||
}
|
||||
|
||||
test('real editor submit handler retries original submission without PUT and requires confirmation for changed form', async t => {
|
||||
const h = await submissionViewHarness(t)
|
||||
h.behavior.failSubmit = true
|
||||
await h.submitOrder()
|
||||
await h.submitOrder()
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.deepEqual(posts[0], posts[1])
|
||||
h.draft.customerRemark = '修改后的决定'
|
||||
h.behavior.cancelConfirm = true
|
||||
await h.submitOrder()
|
||||
assert.equal(h.confirmations.length, 1)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 1)
|
||||
h.behavior.cancelConfirm = false; h.behavior.failSubmit = false; h.behavior.version = 12
|
||||
await h.submitOrder()
|
||||
assert.equal(h.confirmations.length, 2)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 2)
|
||||
const last = h.calls.filter(call => call.url.endsWith('/submit')).at(-1)
|
||||
assert.deepEqual(last.data, { expectedVersion: 12 })
|
||||
assert.notEqual(last.headers['Idempotency-Key'], posts[0].headers['Idempotency-Key'])
|
||||
assert.equal(h.globals.saving.value, false)
|
||||
})
|
||||
|
||||
test('real batch handler retains uncertain IDs across list refresh and retries original commands even if now submitted', async t => {
|
||||
const h = await submissionViewHarness(t)
|
||||
h.behavior.failSubmit = true
|
||||
await h.submitSelectedDraftOrders()
|
||||
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, ['one'])
|
||||
assert.deepEqual(h.globals.selectedDraftOrders.value, [])
|
||||
h.behavior.failSubmit = false; h.behavior.status = 'SUBMITTED'; h.behavior.version = 10
|
||||
await h.submitSelectedDraftOrders()
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.equal(posts.length, 2)
|
||||
assert.deepEqual(posts[1], posts[0])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 9 })
|
||||
assert.deepEqual(h.globals.pendingBatchSubmissionIds.value, [])
|
||||
assert.equal(h.globals.batchSubmitting.value, false)
|
||||
})
|
||||
|
||||
test('real new-order handler creates once and retries the saved order submission with the original version', async t => {
|
||||
const h = await submissionViewHarness(t)
|
||||
h.globals.editingId.value = undefined; h.globals.editingSession.value = undefined
|
||||
h.behavior.version = 0; h.behavior.failSubmit = true
|
||||
await h.submitOrder()
|
||||
assert.equal(h.globals.editingId.value, 'one')
|
||||
h.behavior.version = 1; h.behavior.status = 'SUBMITTED'; h.behavior.failSubmit = false
|
||||
await h.submitOrder()
|
||||
assert.equal(h.calls.filter(call => call.method === 'POST' && call.url === '/merchant/v1/orders/first-leg').length, 1)
|
||||
assert.equal(h.calls.filter(call => call.method === 'PUT').length, 0)
|
||||
const posts = h.calls.filter(call => call.url.endsWith('/submit'))
|
||||
assert.deepEqual(posts[0], posts[1])
|
||||
assert.deepEqual(posts[0].data, { expectedVersion: 0 })
|
||||
})
|
||||
@@ -27,22 +27,10 @@ test('renders estimated sailing from the current API without substituting actual
|
||||
assert.equal(map({ transport: null }).estimatedPortArrivalAt, '')
|
||||
})
|
||||
|
||||
test('maps the first-leg aggregate list fields without loading detail rows', () => {
|
||||
assert.match(apiSource, /interface MerchantFirstLegOrderRow/)
|
||||
assert.match(apiSource, /skuNos: string \| string\[\] \| null/)
|
||||
assert.match(apiSource, /cargoes\?: Array<\{ skuNo\?: string \| null \}>/)
|
||||
assert.match(apiSource, /apiRequest<PageResult<MerchantFirstLegOrderRow>>/)
|
||||
assert.match(storeSource, /function mapFirstLegOrderRow/)
|
||||
for (const field of ['inboundId', 'inboundCode', 'channelName', 'destinationWarehouseName', 'pickupMethod', 'packageCount', 'expressCompany', 'trackingNo', 'totalGrossWeightKg', 'totalNetWeightKg', 'totalVolumeCbm', 'totalQuantity', 'remark', 'shipmentId', 'fulfillmentType', 'lxCode', 'referenceId', 'createdAt']) {
|
||||
assert.match(storeSource, new RegExp(`row\\.${field}`))
|
||||
}
|
||||
assert.match(storeSource, /row\.skuNos/)
|
||||
assert.match(storeSource, /row\.cargoes/)
|
||||
assert.match(storeSource, /chargeableWeightKg: null/)
|
||||
assert.match(storeSource, /chargeableVolumeCbm: null/)
|
||||
assert.match(apiSource, /pickupMethod: ApiPickupMethod \\| null/)
|
||||
assert.match(storeSource, /orderResult\.value\.records\.map\(mapFirstLegOrderRow\)/)
|
||||
assert.match(storeSource, /orderResult\.value\.records\.map\(\(item\) => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||
test('maps the current workbench row without loading detail rows', () => {
|
||||
assert.match(storeSource, /result\.page\.records\.map\(item => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||
assert.match(storeSource, /version: summary\.orderVersion/)
|
||||
assert.doesNotMatch(storeSource, /function mapFirstLegOrderRow/)
|
||||
})
|
||||
|
||||
test('declares the documented merchant warehouse and first-leg endpoints', () => {
|
||||
@@ -85,14 +73,10 @@ test('maps transport and status fields instead of treating container mode as tra
|
||||
assert.doesNotMatch(storeSource, /status === 'COMPLETED'\) return 'DELIVERED'/)
|
||||
})
|
||||
|
||||
test('prefers unified reads and only falls back to the real legacy API when C02 is unavailable', () => {
|
||||
test('uses only the formal workbench read and surfaces failures', () => {
|
||||
assert.match(storeSource, /getMerchantOrderWorkbench\(query\)/)
|
||||
assert.match(storeSource, /orders\.value = \[\]/)
|
||||
assert.match(storeSource, /warehouses\.value = \[\]/)
|
||||
assert.match(storeSource, /Promise\.allSettled\(\[getOrdersForClient\(query\), loadWarehouseType\('DOMESTIC', true\)\]\)/)
|
||||
assert.match(storeSource, /getMerchantUnifiedOrders\(unifiedQuery\)/)
|
||||
assert.match(storeSource, /isUnifiedOrderQueryUnavailable\(error\)/)
|
||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query\)\)/)
|
||||
assert.doesNotMatch(storeSource, /DEMO_PLATFORM_RECEIVING_WAREHOUSES|initialOrders/)
|
||||
assert.doesNotMatch(storeSource, /isUnifiedOrderQueryUnavailable|getOrdersForClient|getMerchantFirstLegOrders|initialOrders/)
|
||||
})
|
||||
|
||||
test('declares the final C02 row and detail contract in the API adapter', () => {
|
||||
@@ -107,13 +91,14 @@ test('declares the final C02 row and detail contract in the API adapter', () =>
|
||||
for (const field of ['pickupMethod', 'requestedPickupAt', 'containerMode', 'destinationType', 'destinationCode', 'skuNos', 'totalQuantity', 'totalNetWeightKg', 'chargeableVolumeCbm', 'inboundCompletedAt', 'shipmentId', 'referenceId']) {
|
||||
assert.match(unifiedApiSource, new RegExp(`${field}:`))
|
||||
}
|
||||
assert.match(unifiedApiSource, /taxMode: ApiTaxMode \| null/)
|
||||
assert.match(unifiedApiSource, /customsInspection: boolean \| null/)
|
||||
assert.match(unifiedApiSource, /loadingVersion: number/)
|
||||
assert.match(unifiedApiSource, /pickingVersion: number/)
|
||||
assert.match(unifiedApiSource, /summary: MerchantUnifiedOrderRow/)
|
||||
assert.match(unifiedApiSource, /order: MerchantFirstLegOrderDetail/)
|
||||
assert.match(unifiedApiSource, /timeline: MerchantUnifiedTimelineEvent\[\]/)
|
||||
assert.match(unifiedApiSource, /customNodes\?: MerchantUnifiedCustomNode\[\]/)
|
||||
assert.match(unifiedApiSource, /error\.status === 404 \|\| error\.code === 'A0404'/)
|
||||
})
|
||||
|
||||
test('keeps unified order pagination valid when the store omits page and size', () => {
|
||||
@@ -121,27 +106,18 @@ test('keeps unified order pagination valid when the store omits page and size',
|
||||
assert.match(unifiedApiSource, /params: \{ page: page \?\? 1, size: size \?\? 200, \.\.\.filters \}/)
|
||||
})
|
||||
|
||||
test('keeps drafts on the legacy read path without assigning a unified main status', () => {
|
||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query, 'DRAFT'\)\)/)
|
||||
assert.match(storeSource, /const listOrder = getById\(id\)/)
|
||||
assert.match(storeSource, /listOrder\?\.status === 'DRAFT' \? loadLegacyDetail\(id, listOrder\) : loadUnifiedDetail\(id\)/)
|
||||
assert.match(storeSource, /detail\.order\.lxCode == null && listOrder\?\.lxCode/)
|
||||
assert.match(storeSource, /return loadLegacyDetail\(String\(createdId\)\)/)
|
||||
assert.match(storeSource, /draftLoadError/)
|
||||
})
|
||||
|
||||
test('routes supported filters to C02 without sending DRAFT as a main status', () => {
|
||||
assert.match(storeSource, /interface ClientOrderReadQuery extends MerchantUnifiedOrderQuery/)
|
||||
assert.match(storeSource, /if \(query\.draftOnly\)/)
|
||||
assert.match(storeSource, /const unifiedQuery: MerchantUnifiedOrderQuery/)
|
||||
assert.match(storeSource, /inboundCode: query\.inboundCode/)
|
||||
assert.match(storeSource, /getMerchantUnifiedOrders\(unifiedQuery\)/)
|
||||
test('draft editing reads the order aggregate while navigation uses unified detail', () => {
|
||||
assert.match(storeSource, /return loadOrderAggregate\(id\)/)
|
||||
assert.match(storeSource, /const detail = await getMerchantUnifiedOrder\(id\)/)
|
||||
assert.doesNotMatch(storeSource, /loadLegacyDetail|draftOnly|includeDrafts/)
|
||||
})
|
||||
|
||||
test('maps C02 authoritative status, transport, cargo and pickup snapshots', () => {
|
||||
assert.match(storeSource, /id: String\(summary\.orderId\)/)
|
||||
assert.match(storeSource, /transportMode: unifiedTransport\(summary\.containerMode\)/)
|
||||
assert.match(storeSource, /status: summary\.mainStatus/)
|
||||
assert.match(storeSource, /taxMode: summary\.taxMode \?\? 'BUY_DECLARATION'/)
|
||||
assert.match(storeSource, /customsInspection: summary\.customsInspection \?\? false/)
|
||||
assert.match(storeSource, /fulfillmentType: summary\.fulfillmentType \?\? 'STANDARD'/)
|
||||
assert.match(storeSource, /lxCode: summary\.lxCode \?\? ''/)
|
||||
assert.match(storeSource, /mapped\.fulfillmentType = detail\.summary\.fulfillmentType \?\? mapped\.fulfillmentType/)
|
||||
@@ -191,7 +167,7 @@ test('separates domestic receiving warehouses from public destinations', () => {
|
||||
assert.match(apiSource, /warehouseType\?: MerchantWarehouseType/)
|
||||
assert.match(apiSource, /params: \{ page: 1, size: 200, status: 'ACTIVE', \.\.\.params \}/)
|
||||
assert.match(storeSource, /loadAllWarehouseRecords\(warehouseType, getMerchantWarehouses\)/)
|
||||
assert.match(storeSource, /loadWarehouseType\('DOMESTIC', true\)/)
|
||||
assert.match(storeSource, /loadWarehouseType\('DOMESTIC'\)/)
|
||||
assert.match(storeSource, /warehouse\.warehouseType !== 'DOMESTIC'/)
|
||||
assert.match(storeSource, /item\.warehouseType === draft\.destinationType/)
|
||||
assert.match(storeSource, /draft\.amazonWarehouseCode = draft\.destinationType === 'FBA' \? destinationWarehouse\.code : ''/)
|
||||
@@ -202,20 +178,20 @@ test('only blocks submission when a known company audit status is not active', (
|
||||
assert.match(storeSource, /if \(companyAuditStatus && companyAuditStatus !== 'ACTIVE'\)/)
|
||||
})
|
||||
|
||||
test('does not expose the out-of-scope cancellation write', () => {
|
||||
assert.doesNotMatch(storeSource, /cancelMerchant|function cancel|\/cancel/)
|
||||
assert.doesNotMatch(apiSource, /\/cancel/)
|
||||
test('uses the versioned merchant cancellation contract', () => {
|
||||
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
|
||||
})
|
||||
|
||||
test('sends an idempotency key for create and submit writes', () => {
|
||||
assert.match(apiSource, /'Idempotency-Key': createIdempotencyKey\('first-leg-create'\)/)
|
||||
assert.match(apiSource, /submitMerchantFirstLegOrder\(id: number \| string, idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /submitMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number \}, idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /'Idempotency-Key': idempotencyKey/)
|
||||
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
|
||||
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
||||
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
|
||||
assert.match(storeSource, /pendingSubmitKeys\.get\(id\) \?\? createIdempotencyKey\(`first-leg-submit-\$\{id\}`\)/)
|
||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, idempotencyKey\)/)
|
||||
assert.match(storeSource, /pendingSubmissions\.get\(id\)/)
|
||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||
})
|
||||
|
||||
test('does not expose the contradictory backend rejected state in the client model', () => {
|
||||
@@ -260,5 +236,5 @@ test('keeps failed order loads distinct from empty results', () => {
|
||||
assert.match(storeSource, /const loadError = ref\(''\)/)
|
||||
assert.match(storeSource, /orderResult\.reason instanceof Error/)
|
||||
assert.match(storeSource, /warehouseLoadError/)
|
||||
assert.match(storeSource, /return \{ orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError/)
|
||||
assert.match(storeSource, /return \{ orders, orderDetails, total, queueCounts, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError/)
|
||||
})
|
||||
|
||||
@@ -1,29 +1,27 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import {
|
||||
createMerchantFirstLegOrderBatch,
|
||||
createMerchantFirstLegOrder,
|
||||
createIdempotencyKey,
|
||||
getMerchantFirstLegOrder,
|
||||
getMerchantFirstLegOrders,
|
||||
getMerchantWarehouseDetail,
|
||||
getMerchantWarehouses,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantFirstLegOrder,
|
||||
cancelMerchantFirstLegOrder,
|
||||
type ApiFirstLegStatus,
|
||||
type FirstLegOrderSaveRequest,
|
||||
type MerchantFirstLegOrder,
|
||||
type MerchantFirstLegOrderRow,
|
||||
type MerchantFirstLegOrderDetail,
|
||||
type MerchantBatchDraftResponse,
|
||||
type MerchantWarehouse,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import {
|
||||
getMerchantUnifiedOrder,
|
||||
getMerchantUnifiedOrders,
|
||||
isUnifiedOrderQueryUnavailable,
|
||||
getMerchantOrderWorkbench,
|
||||
type MerchantUnifiedOrderDetail,
|
||||
type MerchantUnifiedOrderQuery,
|
||||
type MerchantOrderWorkbenchQuery,
|
||||
type MerchantUnifiedOrderRow,
|
||||
} from '@/modules/first-leg/api/unifiedOrders'
|
||||
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
|
||||
@@ -46,7 +44,7 @@ function clientStatus(status: ApiFirstLegStatus): FirstLegOrder['status'] {
|
||||
if (status === 'REJECTED') return 'PENDING_REVIEW'
|
||||
if (status === 'APPROVED' || status === 'ACCEPTED' || status === 'PROCESSING') return 'WAIT_MEASURE'
|
||||
if (status === 'COMPLETED') return 'COMPLETED'
|
||||
if (status === 'CANCELLED') return 'PENDING_REVIEW'
|
||||
if (status === 'CANCELLED') return 'CANCELLED'
|
||||
return 'PENDING_REVIEW'
|
||||
}
|
||||
|
||||
@@ -159,8 +157,10 @@ function orderWarehouseSnapshot(order: MerchantFirstLegOrder, warehouse?: Platfo
|
||||
id: String(order.receivingWarehouseId),
|
||||
code: warehouse?.code ?? '',
|
||||
name: order.receivingWarehouseName,
|
||||
province: warehouse?.province ?? '',
|
||||
city: warehouse?.city ?? '',
|
||||
// Order stores the complete formatted address, including province and city.
|
||||
// Do not prefix this snapshot with fields from the current warehouse master.
|
||||
province: '',
|
||||
city: '',
|
||||
address: order.receivingWarehouseAddress,
|
||||
}
|
||||
}
|
||||
@@ -198,6 +198,7 @@ function timeline(detail: MerchantFirstLegOrderDetail): FirstLegOrderTimelineIte
|
||||
|
||||
function businessSummary(summary?: MerchantUnifiedOrderRow): FirstLegOrder['businessSummary'] {
|
||||
return {
|
||||
transportFragments: [],
|
||||
customerFeeConfirmationRequired: summary?.customerFeeConfirmationRequired ?? false,
|
||||
totalPackageCount: summary?.totalPackageCount ?? null,
|
||||
actualGrossWeightKg: summary?.actualGrossWeightKg ?? null,
|
||||
@@ -339,54 +340,25 @@ function mapUnifiedOrderRow(summary: MerchantUnifiedOrderRow, warehouses: Platfo
|
||||
trackingNumber: summary.expressTrackingNo ?? summary.delivery?.trackingNo ?? '', skuNos: summary.skuNos ?? [], totalNetWeightKg: summary.totalNetWeightKg ?? null,
|
||||
totalQuantity: summary.totalQuantity ?? null, chargeableVolumeCbm: summary.chargeableVolumeCbm ?? null,
|
||||
inboundedAt: summary.inboundCompletedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: summary.customerRemark ?? '', operatorName: '',
|
||||
status: summary.mainStatus, version: 0, items: [], timeline: [], businessSummary: businessSummary(summary),
|
||||
status: summary.mainStatus, version: summary.orderVersion, items: [], timeline: [], businessSummary: businessSummary(summary),
|
||||
createdAt: summary.createdAt, updatedAt: summary.updatedAt, tradeTerm: '', destinationCountryCode: '',
|
||||
destinationWarehouseId: summary.destinationWarehouseId == null ? '' : String(summary.destinationWarehouseId),
|
||||
destinationWarehouseName: summary.destinationWarehouseName ?? '', pickupMethod: summary.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||
channelName: summary.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: 'BUY_DECLARATION', customsInspection: false,
|
||||
channelName: summary.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: summary.taxMode ?? 'BUY_DECLARATION', customsInspection: summary.customsInspection ?? false,
|
||||
destinationType: summary.destinationType ?? 'PRIVATE', amazonWarehouseCode: summary.destinationCode ?? '', shipmentId: summary.shipmentId ?? '',
|
||||
requestedPickupAt: summary.requestedPickupAt ?? '', receivingTime: '', submittedAt: '', completedAt: '',
|
||||
}
|
||||
}
|
||||
|
||||
function mapFirstLegOrderRow(row: MerchantFirstLegOrderRow): FirstLegOrder {
|
||||
const skuNos = Array.isArray(row.skuNos)
|
||||
? row.skuNos
|
||||
: (row.skuNos ?? '').split('、').map((value) => value.trim()).filter(Boolean)
|
||||
const resolvedSkuNos = skuNos.length ? skuNos : (row.cargoes ?? [])
|
||||
.map((cargo) => cargo.skuNo?.trim())
|
||||
.filter((value): value is string => Boolean(value))
|
||||
const uniqueSkuNos = [...new Set(resolvedSkuNos)]
|
||||
return {
|
||||
id: String(row.orderId), orderNo: row.orderNo, referenceNo: row.referenceId ?? '', transportMode: null,
|
||||
businessType: 'EXPORT', fulfillmentType: row.fulfillmentType ?? 'STANDARD', lxCode: row.lxCode ?? '', origin: '', destination: row.destinationWarehouseName ?? '', receivingWarehouseId: '',
|
||||
receivingWarehouseName: '', receivingWarehouseSnapshot: null, expectedDepartureDate: '', etd: '', eta: '',
|
||||
shipperPartyId: '', shipperPartySnapshot: null, shipper: '', consigneePartyId: '', consigneePartySnapshot: null,
|
||||
consignee: row.receivingCompanyName ?? '', expressCompanyName: row.expressCompany ?? '', trackingNumber: row.trackingNo ?? '',
|
||||
skuNos: uniqueSkuNos, totalNetWeightKg: row.totalNetWeightKg, totalQuantity: row.totalQuantity,
|
||||
chargeableVolumeCbm: null, inboundedAt: row.inboundedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: row.remark ?? '',
|
||||
operatorName: '', status: clientStatus(row.status), version: 0, items: [], timeline: [],
|
||||
businessSummary: {
|
||||
...businessSummary(), totalPackageCount: row.packageCount, actualGrossWeightKg: row.totalGrossWeightKg ?? row.weightKg,
|
||||
actualVolumeCbm: row.totalVolumeCbm, chargeableWeightKg: null,
|
||||
inboundId: row.inboundId == null ? '' : String(row.inboundId), inboundCode: row.inboundCode ?? '',
|
||||
},
|
||||
createdAt: row.createdAt, updatedAt: row.createdAt, tradeTerm: '', destinationCountryCode: '', destinationWarehouseId: '',
|
||||
destinationWarehouseName: row.destinationWarehouseName ?? '', pickupMethod: row.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||
channelName: row.channelName ?? '', pricingTaxMode: 'TAX_INCLUDED', carrierId: '', carrierName: '', taxMode: 'BUY_DECLARATION',
|
||||
customsInspection: false, destinationType: row.destinationType ?? 'PRIVATE', amazonWarehouseCode: '',
|
||||
shipmentId: row.shipmentId ?? row.internationalOrderNo ?? '', requestedPickupAt: '', receivingTime: '', submittedAt: '', completedAt: '',
|
||||
}
|
||||
}
|
||||
|
||||
function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: PlatformReceivingWarehouse[]): FirstLegOrder {
|
||||
if (!detail?.summary || !detail.order?.order) throw new Error('订单详情数据不完整,请刷新列表后重试')
|
||||
const mapped = mapOrder(detail.order.order, warehouses, detail.order)
|
||||
mapped.id = String(detail.summary.orderId)
|
||||
mapped.status = detail.summary.mainStatus
|
||||
const rawStatus = detail.order.order.status
|
||||
mapped.status = rawStatus === 'CANCELLED' || rawStatus === 'DRAFT' ? rawStatus : detail.summary.mainStatus
|
||||
mapped.fulfillmentType = detail.summary.fulfillmentType ?? mapped.fulfillmentType
|
||||
mapped.lxCode = detail.summary.lxCode ?? mapped.lxCode
|
||||
mapped.businessSummary = businessSummary(detail.summary)
|
||||
mapped.businessSummary = { ...businessSummary(detail.summary), transportFragments: detail.transportFragments }
|
||||
mapped.timeline = unifiedTimeline(detail)
|
||||
const summary = mapUnifiedOrderRow(detail.summary, warehouses)
|
||||
mapped.referenceNo = summary.referenceNo
|
||||
@@ -406,59 +378,6 @@ function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: P
|
||||
return mapped
|
||||
}
|
||||
|
||||
type OrderListReadResult =
|
||||
| { source: 'first-leg'; records: MerchantFirstLegOrderRow[] }
|
||||
| { source: 'unified'; records: MerchantUnifiedOrderRow[]; drafts: MerchantFirstLegOrderRow[] }
|
||||
|
||||
interface ClientOrderReadQuery extends MerchantUnifiedOrderQuery {
|
||||
fbaCode?: string
|
||||
draftOnly?: boolean
|
||||
includeDrafts?: boolean
|
||||
}
|
||||
|
||||
function legacyQuery(query: ClientOrderReadQuery, status?: ApiFirstLegStatus) {
|
||||
return {
|
||||
keyword: query.keyword,
|
||||
status,
|
||||
createdFrom: query.createdFrom,
|
||||
createdTo: query.createdTo,
|
||||
}
|
||||
}
|
||||
|
||||
async function getOrdersForClient(query: ClientOrderReadQuery = {}): Promise<OrderListReadResult> {
|
||||
if (query.draftOnly) {
|
||||
const response = await getMerchantFirstLegOrders(legacyQuery(query, 'DRAFT'))
|
||||
return { source: 'first-leg', records: response.records }
|
||||
}
|
||||
|
||||
const unifiedQuery: MerchantUnifiedOrderQuery = {
|
||||
keyword: query.keyword,
|
||||
orderNo: query.orderNo,
|
||||
mainStatus: query.mainStatus,
|
||||
receivingWarehouseId: query.receivingWarehouseId,
|
||||
destinationWarehouseId: query.destinationWarehouseId,
|
||||
inboundCode: query.inboundCode,
|
||||
createdFrom: query.createdFrom,
|
||||
createdTo: query.createdTo,
|
||||
fbaCode: query.fbaCode,
|
||||
page: query.page,
|
||||
size: query.size,
|
||||
}
|
||||
try {
|
||||
const [response, draftResponse] = await Promise.all([
|
||||
getMerchantUnifiedOrders(unifiedQuery),
|
||||
query.includeDrafts
|
||||
? getMerchantFirstLegOrders(legacyQuery(query, 'DRAFT'))
|
||||
: Promise.resolve({ records: [] as MerchantFirstLegOrderRow[] }),
|
||||
])
|
||||
return { source: 'unified', records: response.records, drafts: draftResponse.records }
|
||||
} catch (error) {
|
||||
if (!isUnifiedOrderQueryUnavailable(error)) throw error
|
||||
const response = await getMerchantFirstLegOrders(legacyQuery(query))
|
||||
return { source: 'first-leg', records: response.records }
|
||||
}
|
||||
}
|
||||
|
||||
function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
return {
|
||||
id: String(item.id), code: item.warehouseCode, name: item.warehouseName, province: '',
|
||||
@@ -468,21 +387,37 @@ function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||
}
|
||||
}
|
||||
|
||||
export interface DraftEditSession {
|
||||
readonly orderId: string
|
||||
readonly expectedVersion: number
|
||||
}
|
||||
|
||||
export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', () => {
|
||||
const orders = ref<FirstLegOrder[]>([])
|
||||
const pendingSubmitKeys = new Map<string, string>()
|
||||
const orderDetails = ref<Record<string, FirstLegOrder>>({})
|
||||
const total = ref(0)
|
||||
const queueCounts = ref({ all: 0, fee: 0, customs: 0, draft: 0 })
|
||||
const queryChannelNames = ref<string[]>([])
|
||||
let listRequest = 0
|
||||
const pendingSubmissions = new Map<string, { key: string; payload: { expectedVersion: number } }>()
|
||||
const submissionForms = new Map<string, { snapshot: string; order: FirstLegOrder }>()
|
||||
const submittingIds = new Set<string>()
|
||||
const pendingEdits = new WeakMap<DraftEditSession, { key: string; payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest } }>()
|
||||
const pendingCancellations = new Map<string, { key: string; payload: { expectedVersion: number; reason: string } }>()
|
||||
|
||||
function beginDraftEdit(detail: FirstLegOrder): DraftEditSession {
|
||||
if (!canClientEditFirstLegOrder(detail.status) || !Number.isSafeInteger(detail.version) || detail.version < 0) throw new Error('请重新打开草稿详情后编辑')
|
||||
return Object.freeze({ orderId: detail.id, expectedVersion: detail.version })
|
||||
}
|
||||
const warehouses = ref<ClientWarehouse[]>([])
|
||||
const loading = ref(false)
|
||||
const loadedFromApi = ref(false)
|
||||
const loadError = ref('')
|
||||
const warehouseLoadError = ref('')
|
||||
const draftLoadError = ref('')
|
||||
const loadedWarehouseTypes = ref<ClientWarehouseType[]>([])
|
||||
const warehouseTypeRequests = new Map<ClientWarehouseType, Promise<ClientWarehouse[]>>()
|
||||
const activeCount = computed(() => orders.value.filter((item) => item.status !== 'DRAFT' && item.status !== 'DELIVERED').length)
|
||||
const pendingCount = computed(() => orders.value.filter((item) => item.status === 'PENDING_REVIEW').length)
|
||||
|
||||
function getById(id: string) { return orders.value.find((item) => item.id === id) }
|
||||
function getById(id: string) { return orders.value.find((item) => item.id === id) ?? orderDetails.value[id] }
|
||||
|
||||
async function loadWarehouseType(warehouseType: ClientWarehouseType, force = false) {
|
||||
if (warehouseType === 'DOMESTIC' && force) warehouseLoadError.value = ''
|
||||
@@ -509,28 +444,40 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
}
|
||||
}
|
||||
|
||||
async function load(query: ClientOrderReadQuery = {}) {
|
||||
async function load(query: MerchantOrderWorkbenchQuery = {}) {
|
||||
const request = ++listRequest
|
||||
loading.value = true
|
||||
loadedFromApi.value = true
|
||||
loadError.value = ''
|
||||
warehouseLoadError.value = ''
|
||||
draftLoadError.value = ''
|
||||
loadedWarehouseTypes.value = []
|
||||
warehouseTypeRequests.clear()
|
||||
orders.value = []
|
||||
warehouses.value = []
|
||||
const [orderResult, warehouseResult] = await Promise.allSettled([getOrdersForClient(query), loadWarehouseType('DOMESTIC', true)])
|
||||
if (warehouseResult.status === 'rejected' && !warehouseLoadError.value) warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||
total.value = 0
|
||||
queueCounts.value = { all: 0, fee: 0, customs: 0, draft: 0 }
|
||||
const [orderResult, warehouseResult] = await Promise.allSettled([
|
||||
getMerchantOrderWorkbench(query), loadWarehouseType('DOMESTIC'),
|
||||
])
|
||||
if (request !== listRequest) return 0
|
||||
if (warehouseResult.status === 'rejected') warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||
if (orderResult.status === 'fulfilled') {
|
||||
orders.value = orderResult.value.source === 'unified'
|
||||
? [
|
||||
...orderResult.value.drafts.map(mapFirstLegOrderRow),
|
||||
...orderResult.value.records.map((item) => mapUnifiedOrderRow(item, warehouses.value)),
|
||||
]
|
||||
: orderResult.value.records.map(mapFirstLegOrderRow)
|
||||
} else {
|
||||
loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||
}
|
||||
try {
|
||||
const result = orderResult.value
|
||||
const expectedPage = query.page ?? 1, size = query.size ?? 10
|
||||
const count = Number(result.page.total), pages = Math.ceil(count / size)
|
||||
if (!Number.isSafeInteger(count) || count < 0 || Number(result.page.page) !== expectedPage
|
||||
|| Number(result.page.size) !== size || Number(result.page.pages) !== pages
|
||||
|| result.page.records.length !== Math.min(size, Math.max(0, count - (expectedPage - 1) * size))
|
||||
|| new Set(result.page.records.map(row => String(row.orderId))).size !== result.page.records.length
|
||||
|| ['all', 'fee', 'customs', 'draft'].some(key => { const value = result.queues[key as keyof typeof result.queues]; return !Number.isSafeInteger(Number(value)) || Number(value) < 0 })
|
||||
|| Number(result.queues[query.queue ?? 'all']) !== count
|
||||
|| !Array.isArray(result.channelNames)) {
|
||||
loadError.value = '订单分页数据不完整,请重新加载'
|
||||
} else {
|
||||
orders.value = result.page.records.map(item => mapUnifiedOrderRow(item, warehouses.value))
|
||||
total.value = count
|
||||
queueCounts.value = { all: Number(result.queues.all), fee: Number(result.queues.fee), customs: Number(result.queues.customs), draft: Number(result.queues.draft) }
|
||||
queryChannelNames.value = result.channelNames
|
||||
}
|
||||
} catch { loadError.value = '订单分页数据不完整,请重新加载' }
|
||||
} else loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||
loading.value = false
|
||||
return orders.value.length
|
||||
}
|
||||
@@ -538,38 +485,18 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
function upsertOrder(mapped: FirstLegOrder) {
|
||||
const index = orders.value.findIndex((item) => item.id === mapped.id)
|
||||
if (index >= 0) orders.value[index] = mapped
|
||||
else orders.value.unshift(mapped)
|
||||
orderDetails.value[mapped.id] = mapped
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function loadLegacyDetail(id: string, listOrder?: FirstLegOrder) {
|
||||
async function loadOrderAggregate(id: string) {
|
||||
const detail = await getMerchantFirstLegOrder(id)
|
||||
const mapped = mapOrder(detail.order, warehouses.value, detail)
|
||||
// Older detail responses may omit newly added dropship fields. Keep the
|
||||
// values already returned by the list row so editing a draft does not
|
||||
// clear the persisted LX code in the form.
|
||||
if (detail.order.fulfillmentType == null && listOrder?.fulfillmentType) {
|
||||
mapped.fulfillmentType = listOrder.fulfillmentType
|
||||
}
|
||||
if (detail.order.lxCode == null && listOrder?.lxCode) {
|
||||
mapped.lxCode = listOrder.lxCode
|
||||
}
|
||||
return upsertOrder(mapped)
|
||||
}
|
||||
|
||||
async function loadUnifiedDetail(id: string) {
|
||||
try {
|
||||
const detail = await getMerchantUnifiedOrder(id)
|
||||
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value))
|
||||
} catch (error) {
|
||||
if (!isUnifiedOrderQueryUnavailable(error)) throw error
|
||||
return loadLegacyDetail(id)
|
||||
}
|
||||
return upsertOrder(mapOrder(detail.order, warehouses.value, detail))
|
||||
}
|
||||
|
||||
async function loadDetail(id: string) {
|
||||
const listOrder = getById(id)
|
||||
return listOrder?.status === 'DRAFT' ? loadLegacyDetail(id, listOrder) : loadUnifiedDetail(id)
|
||||
const detail = await getMerchantUnifiedOrder(id)
|
||||
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value))
|
||||
}
|
||||
|
||||
async function loadWarehouseDetail(id: string) {
|
||||
@@ -588,16 +515,51 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
return mapped
|
||||
}
|
||||
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string) {
|
||||
async function saveDraft(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||
if (hasPendingSubmission(id)) throw new Error('上次提交结果未确认,请重试原提交,或确认重新编辑后再保存')
|
||||
const warehouse = prepareDraftForSave(draft, warehouses.value)
|
||||
if (id) {
|
||||
const order = getById(id)
|
||||
if (!order || !canClientEditFirstLegOrder(order.status)) throw new Error('当前订单状态不允许编辑')
|
||||
await updateMerchantFirstLegOrder(id, savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(id)
|
||||
if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑')
|
||||
const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) }
|
||||
let pending = pendingEdits.get(editSession)
|
||||
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次保存结果未确认,请重试原内容,或重新打开详情后编辑')
|
||||
// Observe an uncertain previous outcome without replacing its frozen version.
|
||||
if (pending) await getMerchantFirstLegOrder(id)
|
||||
if (!pending) {
|
||||
pending = { key: createIdempotencyKey(`first-leg-edit-${id}`), payload: JSON.parse(JSON.stringify(payload)) }
|
||||
pendingEdits.set(editSession, pending)
|
||||
}
|
||||
await updateMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||
const saved = await loadOrderAggregate(id)
|
||||
pendingEdits.delete(editSession)
|
||||
return saved
|
||||
}
|
||||
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
|
||||
return loadLegacyDetail(String(createdId))
|
||||
return loadOrderAggregate(String(createdId))
|
||||
}
|
||||
|
||||
async function cancelOrder(id: string, expectedVersion: number, reason: string) {
|
||||
if (!Number.isSafeInteger(expectedVersion) || expectedVersion < 0 || !reason.trim() || reason.trim().length > 500) throw new Error('取消订单需要详情版本及 1–500 字取消原因')
|
||||
const payload = { expectedVersion, reason: reason.trim() }
|
||||
let pending = pendingCancellations.get(id)
|
||||
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次取消结果未确认,请使用原版本和原因重试')
|
||||
if (pending) await getMerchantFirstLegOrder(id)
|
||||
if (!pending) {
|
||||
pending = { key: createIdempotencyKey(`first-leg-cancel-${id}`), payload }
|
||||
pendingCancellations.set(id, pending)
|
||||
}
|
||||
await cancelMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||
pendingCancellations.delete(id)
|
||||
orders.value = orders.value.filter(order => order.id !== id)
|
||||
}
|
||||
|
||||
async function prepareCancellation(id: string) {
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '审核中', APPROVED: '已审核', ACCEPTED: '已接单', REJECTED: '已退回' }
|
||||
if (!Object.hasOwn(labels, order.status)) throw new Error('当前订单状态不允许取消,请刷新订单查看最新进度')
|
||||
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
pendingCancellations.delete(id)
|
||||
return { id, expectedVersion: order.version, businessNo: order.orderNo || order.inboundCode || '—', statusLabel: labels[order.status] }
|
||||
}
|
||||
|
||||
async function saveDraftBatch(
|
||||
@@ -614,21 +576,58 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
||||
|
||||
async function submitSaved(id: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
if (companyAuditStatus && companyAuditStatus !== 'ACTIVE') throw new Error('企业资料尚未审核通过,请先完善企业资料并等待平台审核')
|
||||
const idempotencyKey = pendingSubmitKeys.get(id) ?? createIdempotencyKey(`first-leg-submit-${id}`)
|
||||
pendingSubmitKeys.set(id, idempotencyKey)
|
||||
await submitMerchantFirstLegOrder(id, idempotencyKey)
|
||||
pendingSubmitKeys.delete(id)
|
||||
return loadUnifiedDetail(id)
|
||||
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||
submittingIds.add(id)
|
||||
try {
|
||||
let pending = pendingSubmissions.get(id)
|
||||
// Always observe the raw detail; a retry must retain the original command.
|
||||
const { order } = await getMerchantFirstLegOrder(id)
|
||||
if (!pending) {
|
||||
if (order.status !== 'DRAFT') throw new Error('当前订单不是草稿,请刷新订单查看最新状态')
|
||||
if (!Number.isSafeInteger(order.version) || order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
pending = { key: createIdempotencyKey(`first-leg-submit-${id}`), payload: { expectedVersion: order.version } }
|
||||
pendingSubmissions.set(id, pending)
|
||||
}
|
||||
await submitMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||
const submitted = await loadOrderAggregate(id)
|
||||
pendingSubmissions.delete(id)
|
||||
submissionForms.delete(id)
|
||||
return submitted
|
||||
} finally {
|
||||
submittingIds.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(draft: FirstLegOrderDraft, customerName: string, id?: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||
const order = await saveDraft(draft, customerName, id)
|
||||
return submitSaved(order.id, companyAuditStatus)
|
||||
function hasPendingSubmission(id?: string) { return !!id && (pendingSubmissions.has(id) || submissionForms.has(id)) }
|
||||
|
||||
function isSubmissionRetry(id: string | undefined, draft: FirstLegOrderDraft) {
|
||||
return !!id && hasPendingSubmission(id) && submissionForms.get(id)?.snapshot === JSON.stringify(draft)
|
||||
}
|
||||
|
||||
async function beginNewSubmissionEdit(id: string) {
|
||||
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||
const detail = await getMerchantFirstLegOrder(id)
|
||||
if (detail.order.status !== 'DRAFT') throw new Error('订单已不在草稿状态,不能重新编辑,请刷新订单查看最新状态')
|
||||
if (!Number.isSafeInteger(detail.order.version) || detail.order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||
const order = mapOrder(detail.order, warehouses.value, detail)
|
||||
const session = beginDraftEdit(order)
|
||||
pendingSubmissions.delete(id)
|
||||
submissionForms.delete(id)
|
||||
upsertOrder(order)
|
||||
return session
|
||||
}
|
||||
|
||||
async function saveDraftForSubmission(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||
if (id && isSubmissionRetry(id, draft)) return submissionForms.get(id)!.order
|
||||
const snapshot = JSON.stringify(draft)
|
||||
const order = await saveDraft(JSON.parse(snapshot), customerName, id, editSession)
|
||||
submissionForms.set(order.id, { snapshot, order })
|
||||
return order
|
||||
}
|
||||
|
||||
async function loadDraftDetail(id: string) {
|
||||
return loadLegacyDetail(id, getById(id))
|
||||
return loadOrderAggregate(id)
|
||||
}
|
||||
|
||||
return { orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError, activeCount, pendingCount, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, saveDraft, saveDraftBatch, submitSaved, submit }
|
||||
return { orders, orderDetails, total, queueCounts, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved, hasPendingSubmission, isSubmissionRetry, beginNewSubmissionEdit, saveDraftForSubmission }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
|
||||
const source = readFileSync(new URL('./firstLegOrders.ts', import.meta.url), 'utf8')
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const row = (id, mainStatus = 'LOADED') => ({ orderId: String(id), orderNo: `FL-${id}`, mainStatus, orderVersion: 7 })
|
||||
function result(page = 1, size = 10, total = 215) {
|
||||
return {
|
||||
page: { page, size, total, pages: Math.ceil(total / size), records: Array.from({ length: Math.min(size, Math.max(0, total - (page - 1) * size)) }, (_, i) => row((page - 1) * size + i + 1)) },
|
||||
queues: { all: total, fee: 2, customs: 1, draft: 3 }, channelNames: ['AIR', 'SEA'],
|
||||
}
|
||||
}
|
||||
function deferred() { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b }); return { promise, resolve, reject } }
|
||||
function harness(t, read) {
|
||||
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||
t.after(() => pinia.disposePinia(context))
|
||||
const calls = [], details = [], warehouseCalls = []
|
||||
const deps = {
|
||||
vue, pinia,
|
||||
'@/modules/first-leg/api/firstLeg': {},
|
||||
'@/modules/first-leg/api/unifiedOrders': {
|
||||
getMerchantOrderWorkbench: query => { calls.push(structuredClone(query)); return read(query) },
|
||||
getMerchantUnifiedOrder: async id => {
|
||||
details.push(id)
|
||||
return { summary: row(id, 'DRAFT'), order: { order: { id, status: 'DRAFT', version: 7 } }, timeline: [] }
|
||||
},
|
||||
},
|
||||
'@/modules/first-leg/utils/firstLegOrder': { getFirstLegStatusLabel: value => value },
|
||||
'@/modules/first-leg/utils/warehousePagination': { loadAllWarehouseRecords: async type => { warehouseCalls.push(type); return [] } },
|
||||
}
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => { assert.ok(id in deps, id); return deps[id] }, exports)
|
||||
return { store: exports.useFirstLegOrdersStore(), calls, details, warehouseCalls }
|
||||
}
|
||||
|
||||
test('loads beyond 200 with server totals and forwards every filter using one request per page', async t => {
|
||||
const h = harness(t, q => result(q.page, q.size))
|
||||
const query = { page: 21, size: 10, cargoKeyword: 'SKU', channelName: 'SEA', receivingWarehouseId: '42', destinationType: 'FBA', trackingNumber: 'TRACK', mainStatus: 'LOADED', queue: 'all', createdFrom: '2026-10-01T00:00:00', createdTo: '2026-10-03T23:59:59.999' }
|
||||
assert.equal(await h.store.load(query), 10)
|
||||
assert.equal(h.store.orders[0].id, '201')
|
||||
assert.equal(h.store.total, 215)
|
||||
assert.deepEqual(h.calls, [query])
|
||||
assert.deepEqual(h.store.queueCounts, { all: 215, fee: 2, customs: 1, draft: 3 })
|
||||
assert.deepEqual(h.store.queryChannelNames, ['AIR', 'SEA'])
|
||||
await h.store.load({ page: 22, size: 10 })
|
||||
assert.deepEqual(h.store.orders.map(item => item.id), ['211', '212', '213', '214', '215'])
|
||||
assert.equal(h.calls.length, 2)
|
||||
assert.deepEqual(h.warehouseCalls, ['DOMESTIC'])
|
||||
})
|
||||
|
||||
test('late success cannot replace newer rows, counts, channels or loading state', async t => {
|
||||
const a = deferred(), b = deferred()
|
||||
const h = harness(t, q => q.page === 1 ? a.promise : b.promise)
|
||||
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||
b.resolve(result(2)); await second
|
||||
a.resolve(result(1, 10, 999)); await first
|
||||
assert.equal(h.store.orders[0].id, '11'); assert.equal(h.store.total, 215)
|
||||
assert.equal(h.store.queueCounts.all, 215); assert.equal(h.store.loading, false)
|
||||
})
|
||||
|
||||
test('late failure cannot clear the current page and an older completion cannot stop loading a newer page', async t => {
|
||||
const a = deferred(), b = deferred(), c = deferred()
|
||||
const h = harness(t, q => [a, b, c][q.page - 1].promise)
|
||||
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||
a.resolve(result(1)); await first
|
||||
assert.equal(h.store.loading, true); assert.equal(h.store.orders.length, 0)
|
||||
const third = h.store.load({ page: 3 })
|
||||
c.resolve(result(3)); await third
|
||||
b.reject(new Error('old failure')); await second
|
||||
assert.equal(h.store.orders[0].id, '21'); assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
test('current failure clears stale records and totals, never falls back, and retry restores the page', async t => {
|
||||
let fail = false
|
||||
const h = harness(t, () => fail ? Promise.reject(new Error('查询失败')) : result())
|
||||
await h.store.load(); fail = true; await h.store.load()
|
||||
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||
assert.equal(h.store.queueCounts.all, 0); assert.equal(h.store.loadError, '查询失败')
|
||||
assert.equal(h.store.loading, false)
|
||||
fail = false; await h.store.load(); assert.equal(h.store.orders.length, 10)
|
||||
assert.equal(h.calls.length, 3); assert.equal(h.store.loadError, '')
|
||||
})
|
||||
|
||||
test('rejects inconsistent metadata, truncated pages and duplicate rows without displaying partial data', async t => {
|
||||
let response
|
||||
const h = harness(t, () => response)
|
||||
const corruptions = [r => { r.page.total = -1 }, r => { r.page.pages = 1 }, r => { r.page.page = 2 }, r => { r.page.records.pop() }, r => { r.page.records[1] = r.page.records[0] }, r => { r.queues.all = 99 }, r => { delete r.queues }, r => { r.channelNames = null }]
|
||||
for (const corrupt of corruptions) {
|
||||
response = result(); corrupt(response); await h.store.load()
|
||||
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||
assert.match(h.store.loadError, /分页数据不完整/); assert.equal(h.store.loading, false)
|
||||
}
|
||||
})
|
||||
|
||||
test('draft and cancelled rows retain authoritative versions; off-page detail cannot inflate list or totals', async t => {
|
||||
const response = result(1, 10, 2)
|
||||
response.page.records = [row(1, 'DRAFT'), row(2, 'CANCELLED')]
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load()
|
||||
assert.deepEqual(h.store.orders.map(item => [item.status, item.version]), [['DRAFT', 7], ['CANCELLED', 7]])
|
||||
await h.store.loadDetail('900')
|
||||
assert.equal(h.store.orders.length, 2); assert.equal(h.store.total, 2)
|
||||
assert.equal(h.store.getById('900').status, 'DRAFT')
|
||||
})
|
||||
|
||||
test('queue total is checked against the selected queue rather than all orders', async t => {
|
||||
const response = result(1, 10, 2)
|
||||
response.queues = { all: 215, fee: 2, customs: 1, draft: 3 }
|
||||
const h = harness(t, () => response)
|
||||
await h.store.load({ queue: 'fee' })
|
||||
assert.equal(h.store.total, 2); assert.equal(h.store.queueCounts.all, 215)
|
||||
assert.equal(h.store.loadError, '')
|
||||
})
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
import type {
|
||||
FirstLegOrderStatus,
|
||||
FirstLegTransportMode,
|
||||
@@ -64,6 +65,7 @@ export interface FirstLegOrderTimelineItem {
|
||||
}
|
||||
|
||||
export interface FirstLegOrderBusinessSummary {
|
||||
transportFragments: MerchantTransportFragment[]
|
||||
customerFeeConfirmationRequired: boolean
|
||||
totalPackageCount: number | null
|
||||
actualGrossWeightKg: number | null
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { getMerchantUnifiedOrders } from '../api/unifiedOrders'
|
||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { isCustomsOrderCandidate } from './customsEligibility'
|
||||
|
||||
export interface CustomsDocumentRow {
|
||||
order: { id: string; orderNo: string | null; businessSummary: { inboundCode: string } }
|
||||
detail: MerchantCustomsContainer
|
||||
}
|
||||
|
||||
// Isolated from the shared order store: scan sequential pages, with at most
|
||||
// four document requests in flight. Inconsistent pagination must be visible.
|
||||
export async function readCustomsDocuments() {
|
||||
const records: CustomsDocumentRow[] = []
|
||||
const seen = new Set<string>()
|
||||
let expectedTotal: number | undefined
|
||||
let failedCount = 0
|
||||
const size = 200
|
||||
for (let page = 1; ; page += 1) {
|
||||
const response = await getMerchantUnifiedOrders({ page, size, taxMode: 'TAX_REFUND', loaded: true })
|
||||
const total = Number(response.total)
|
||||
const pages = Number(response.pages)
|
||||
if (!Number.isSafeInteger(total) || total < 0 || Number(response.page) !== page
|
||||
|| Number(response.size) !== size || pages !== Math.ceil(total / size)
|
||||
|| (expectedTotal !== undefined && total !== expectedTotal)
|
||||
|| response.records.length !== Math.min(size, Math.max(0, total - (page - 1) * size))) {
|
||||
throw new Error('订单分页数据不完整或已变化,请重新加载报关资料')
|
||||
}
|
||||
expectedTotal = total
|
||||
for (const row of response.records) {
|
||||
const id = String(row.orderId)
|
||||
if (seen.has(id)) throw new Error('订单分页存在重复记录,请重新加载报关资料')
|
||||
seen.add(id)
|
||||
}
|
||||
const candidates = response.records.filter(row => isCustomsOrderCandidate({ status: row.mainStatus, taxMode: row.taxMode ?? 'BUY_DECLARATION' }))
|
||||
for (let offset = 0; offset < candidates.length; offset += 4) {
|
||||
const results = await Promise.all(candidates.slice(offset, offset + 4).map(async row => {
|
||||
const id = String(row.orderId)
|
||||
try {
|
||||
const detail = await getMerchantCustomsForOrder(id)
|
||||
if (!detail.inbounds.some(item => item.orderId === id && item.taxMode === 'TAX_REFUND')) return null
|
||||
return { order: { id, orderNo: row.orderNo, businessSummary: { inboundCode: row.inboundCode ?? '' } }, detail }
|
||||
} catch (error) {
|
||||
if (!isMerchantCustomsUnavailable(error)) failedCount += 1
|
||||
return null
|
||||
}
|
||||
}))
|
||||
for (const result of results) if (result) records.push(result)
|
||||
}
|
||||
if (page >= pages) break
|
||||
}
|
||||
return { records, failedCount }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const source = readFileSync(new URL('./customsEligibility.ts', import.meta.url), 'utf8')
|
||||
const exports = {}
|
||||
new Function('exports', ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText)(exports)
|
||||
|
||||
test('upload queue contains only customer uploads still required, while completed documents stay accessible', () => {
|
||||
const states = [null, {}, { status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED' },
|
||||
{ status: 'READY_TO_START', merchantStatus: 'DOCUMENT_UPLOADED' },
|
||||
{ status: 'DECLARING', merchantStatus: 'DECLARING' }, { status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED' }]
|
||||
for (const detail of states) assert.equal(exports.needsCustomsUpload(detail), false)
|
||||
assert.equal(exports.needsCustomsUpload({ status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }), true)
|
||||
for (const status of ['LOADED', 'DELIVERED', 'COMPLETED']) assert.equal(exports.isCustomsOrderCandidate({ status, taxMode: 'TAX_REFUND' }), true)
|
||||
})
|
||||
|
||||
test('upload status changes refresh server counts while initial detail reads do not reload the list', async () => {
|
||||
const page = readFileSync(new URL('../views/FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const block = page.slice(page.indexOf('function updateCustomsDetail('), page.indexOf('const detailOrder ='))
|
||||
const js = ts.transpileModule(block, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const states = {}, id = ref('one'), create = ref(false), detail = ref(false)
|
||||
let reloads = 0
|
||||
const update = new Function('customsByOrder', 'customsDialogOrderId', 'isCreatePage', 'isDetailPage', 'loadOrderPage', js + ';return updateCustomsDetail')(states, id, create, detail, async () => reloads++)
|
||||
update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 0)
|
||||
update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 0)
|
||||
update({ merchantStatus: 'DOCUMENT_UPLOADED' }); assert.equal(reloads, 1)
|
||||
assert.equal(states.one.merchantStatus, 'DOCUMENT_UPLOADED')
|
||||
detail.value = true; update({ merchantStatus: 'WAITING_UPLOAD' }); assert.equal(reloads, 1)
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { FirstLegOrder } from '../types/firstLegOrder'
|
||||
import type { MerchantCustomsContainer } from '../api/customs'
|
||||
|
||||
export function isCustomsOrderCandidate(order: Pick<FirstLegOrder, 'status' | 'taxMode'>): boolean {
|
||||
return order.taxMode === 'TAX_REFUND'
|
||||
&& (order.status === 'LOADED' || order.status === 'DELIVERED' || order.status === 'COMPLETED')
|
||||
}
|
||||
|
||||
export function needsCustomsUpload(detail: MerchantCustomsContainer | null | undefined): boolean {
|
||||
return detail?.status === 'WAITING_CUSTOMER_DOCUMENTS' && detail.merchantStatus === 'WAITING_UPLOAD'
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
FIRST_LEG_PROGRESS_STAGES,
|
||||
getFirstLegProgressIndex,
|
||||
getFirstLegStatusLabel,
|
||||
getFirstLegPickingStatusLabel,
|
||||
getFirstLegStatusTone,
|
||||
getFirstLegTransportModeLabel,
|
||||
summarizeFirstLegCargo,
|
||||
@@ -59,7 +60,22 @@ function validDraft() {
|
||||
}
|
||||
}
|
||||
|
||||
test('keeps picking states distinct from order completion and hides unknown internal codes', () => {
|
||||
assert.equal(getFirstLegPickingStatusLabel('PENDING'), '待拣货')
|
||||
assert.equal(getFirstLegPickingStatusLabel('IN_PROGRESS'), '拣货中')
|
||||
assert.equal(getFirstLegPickingStatusLabel('COMPLETED'), '拣货完成')
|
||||
assert.equal(getFirstLegPickingStatusLabel('NEW_INTERNAL_STATE'), '未知状态')
|
||||
assert.equal(getFirstLegPickingStatusLabel(null), '待更新')
|
||||
assert.equal(getFirstLegPickingStatusLabel(''), '待更新')
|
||||
})
|
||||
|
||||
test('uses the confirmed status and transport labels', () => {
|
||||
assert.equal(getFirstLegStatusLabel('CANCELLED'), '已取消')
|
||||
assert.equal(getFirstLegStatusLabel('NOT_A_STATUS'), '未知状态')
|
||||
assert.equal(getFirstLegStatusTone('CANCELLED'), 'info')
|
||||
assert.equal(getFirstLegProgressIndex('CANCELLED'), -1)
|
||||
assert.equal(canClientEditFirstLegOrder('CANCELLED'), false)
|
||||
assert.equal(canClientCancelFirstLegOrder('CANCELLED'), false)
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_MEASURE'), '待测量数据')
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_PALLETIZE'), '待组托')
|
||||
assert.equal(getFirstLegStatusLabel('WAIT_SPLIT'), '待分柜')
|
||||
|
||||
@@ -19,6 +19,16 @@ export function getFirstLegStatusLabel(status: string) {
|
||||
return statusLabels.get(canonicalStatus as FirstLegOrderStatus) ?? '未知状态'
|
||||
}
|
||||
|
||||
export function getFirstLegPickingStatusLabel(status: string | null | undefined) {
|
||||
if (!status) return '待更新'
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
PENDING: '待拣货',
|
||||
IN_PROGRESS: '拣货中',
|
||||
COMPLETED: '拣货完成',
|
||||
}
|
||||
return labels[status] ?? '未知状态'
|
||||
}
|
||||
|
||||
export function getFirstLegTransportModeLabel(mode: FirstLegTransportMode | null) {
|
||||
if (!mode) return '运输方式待更新'
|
||||
return transportModeLabels.get(mode) ?? mode
|
||||
@@ -41,11 +51,11 @@ export function canClientCancelFirstLegOrder(status: FirstLegOrderStatus) {
|
||||
}
|
||||
|
||||
export const FIRST_LEG_PROGRESS_STAGES = FIRST_LEG_ORDER_STATUSES.filter(
|
||||
(item): item is (typeof FIRST_LEG_ORDER_STATUSES)[number] & { code: Exclude<FirstLegOrderStatus, 'DRAFT'> } => item.code !== 'DRAFT',
|
||||
(item): item is (typeof FIRST_LEG_ORDER_STATUSES)[number] & { code: Exclude<FirstLegOrderStatus, 'DRAFT' | 'CANCELLED'> } => item.code !== 'DRAFT' && item.code !== 'CANCELLED',
|
||||
)
|
||||
|
||||
export function getFirstLegProgressIndex(status: FirstLegOrderStatus) {
|
||||
if (status === 'DRAFT') return -1
|
||||
if (status === 'DRAFT' || status === 'CANCELLED') return -1
|
||||
return FIRST_LEG_PROGRESS_STAGES.findIndex((item) => item.code === status)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./transportFacts.ts', import.meta.url), 'utf8')
|
||||
const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
runInNewContext(javascript, { exports })
|
||||
const rows = exports.customerTransportRows
|
||||
|
||||
test('split inbound fragments retain separate cabinet facts and actual/estimated times', () => {
|
||||
const result = rows([
|
||||
{ inboundCode: 'NY-1', cabinetNo: 'D1', containerNo: 'TSTU0000001', nodes: [
|
||||
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-05T09:00:00', estimatedAt: null, providerCode: 'MANUAL' },
|
||||
{ standardNode: 'DEPARTED_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-07T08:00:00', providerCode: 'MATSON' },
|
||||
] },
|
||||
{ inboundCode: 'NY-2', cabinetNo: 'D2', containerNo: 'TSTU0000002', nodes: [
|
||||
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-06T10:00:00', estimatedAt: null, providerCode: 'MATSON' },
|
||||
] },
|
||||
])
|
||||
assert.equal(result.length, 3)
|
||||
assert.equal(result[0].nodeLabel, '已进港')
|
||||
assert.equal(result[0].source, '人工记录')
|
||||
assert.equal(result[1].nodeLabel, '预计开航')
|
||||
assert.equal(result[1].actualAt, null)
|
||||
assert.equal(result[1].estimatedAt, '2026-10-07T08:00:00')
|
||||
assert.equal(result[2].cabinetNo, 'D2')
|
||||
assert.equal(result[2].inboundCode, 'NY-2')
|
||||
assert.equal(result[2].actualAt, '2026-10-06T10:00:00')
|
||||
})
|
||||
|
||||
test('empty actual scope creates no invented nodes or database identifier fallback', () => {
|
||||
assert.equal(rows([]).length, 0)
|
||||
assert.equal(rows([{ inboundCode: 'NY-1', nodes: [] }]).length, 0)
|
||||
const [row] = rows([{ id: 'INTERNAL', nodes: [{ standardNode: 'AT_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-05T09:00:00' }] }])
|
||||
assert.equal(row.cabinetNo, '—')
|
||||
assert.equal(row.containerNo, '—')
|
||||
assert.equal(row.inboundCode, '—')
|
||||
assert.equal(row.actualAt, null)
|
||||
})
|
||||
|
||||
test('detail consumes the existing merchant detail API and displays times separately', () => {
|
||||
const store = readFileSync(new URL('../store/firstLegOrders.ts', import.meta.url), 'utf8')
|
||||
const table = readFileSync(new URL('../components/TransportFactsTable.vue', import.meta.url), 'utf8')
|
||||
assert.match(store, /transportFragments: detail\.transportFragments/)
|
||||
assert.match(table, /label="实际时间".*time\(row\.actualAt\)/)
|
||||
assert.match(table, /label="预计时间".*time\(row\.estimatedAt\)/)
|
||||
assert.doesNotMatch(table, /platform\/|fetch\(|actualAt\s*\|\|\s*.*estimatedAt/)
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||
|
||||
const labels: Readonly<Record<string, string>> = {
|
||||
DEPARTED_WAREHOUSE: '已离仓', AT_ORIGIN_PORT: '已进港', LOADED_ON_VESSEL: '已装船',
|
||||
DEPARTED_ORIGIN_PORT: '已开航', IN_TRANSIT: '海运途中', ARRIVED_DESTINATION_PORT: '船舶已到目的港',
|
||||
DISCHARGED_FROM_VESSEL: '已卸船', PICKUP_READY: '已清关、可提柜', PICKED_UP: '已提柜', EMPTY_RETURNED: '已还柜',
|
||||
}
|
||||
const estimatedLabels: Readonly<Record<string, string>> = {
|
||||
DEPARTED_WAREHOUSE: '预计离仓', AT_ORIGIN_PORT: '预计进港', LOADED_ON_VESSEL: '预计装船',
|
||||
DEPARTED_ORIGIN_PORT: '预计开航', IN_TRANSIT: '预计海运途中', ARRIVED_DESTINATION_PORT: '预计船舶到目的港',
|
||||
DISCHARGED_FROM_VESSEL: '预计卸船', PICKUP_READY: '预计可提柜', PICKED_UP: '预计提柜', EMPTY_RETURNED: '预计还柜',
|
||||
}
|
||||
|
||||
export function customerTransportRows(fragments: MerchantTransportFragment[]) {
|
||||
return fragments.flatMap((fragment, index) => fragment.nodes.map((node, nodeIndex) => ({
|
||||
key: `${index}-${nodeIndex}`,
|
||||
inboundCode: fragment.inboundCode || '—', cabinetNo: fragment.cabinetNo || '—',
|
||||
containerNo: fragment.containerNo || '—',
|
||||
nodeLabel: (node.actualAt ? labels : estimatedLabels)[node.standardNode] || '运输节点',
|
||||
actualAt: node.actualAt, estimatedAt: node.estimatedAt,
|
||||
location: [node.locationCode, node.locationName].filter(Boolean).join(' · ') || '—',
|
||||
source: node.providerCode === 'MANUAL' ? '人工记录' : node.providerCode === 'FIRSTLEG' ? '平台记录' : node.providerCode ? '承运轨迹' : '—',
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import ts from 'typescript'
|
||||
import * as vue from 'vue'
|
||||
|
||||
function evaluate(source, dependencies = {}) {
|
||||
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const exports = {}
|
||||
new Function('require', 'exports', code)(id => {
|
||||
assert.ok(id in dependencies, `Unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports)
|
||||
return exports
|
||||
}
|
||||
const eligibility = evaluate(readFileSync(new URL('../utils/customsEligibility.ts', import.meta.url), 'utf8'))
|
||||
const customsApi = evaluate(readFileSync(new URL('../api/customs.ts', import.meta.url), 'utf8'), {
|
||||
'@/api/http': {}, '@/modules/first-leg/api/firstLeg': {},
|
||||
})
|
||||
const order = (id, status = 'LOADED', taxMode = 'TAX_REFUND') => ({ id, status, taxMode, hasCompletedLoadingPlan: ['LOADED', 'DELIVERED', 'COMPLETED'].includes(status), orderNo: `ORDER-${id}`, businessSummary: { inboundCode: `IN-${id}` } })
|
||||
const detail = id => ({ status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED', inbounds: [{ orderId: id, taxMode: 'TAX_REFUND' }] })
|
||||
function harness(t, orders, getDetail = async id => detail(id)) {
|
||||
const store = { loadError: '', failPage: 0, transformPage: value => value }, calls = [], pageCalls = []
|
||||
const unifiedApi = evaluate(readFileSync(new URL('../api/unifiedOrders.ts', import.meta.url), 'utf8'), {
|
||||
'@/api/http': { apiRequest: async ({ method, url, params: { page, size, taxMode, loaded } }) => {
|
||||
assert.equal(method, 'GET')
|
||||
assert.equal(url, '/merchant/v1/orders')
|
||||
pageCalls.push({ page, size, taxMode, loaded })
|
||||
if (store.loadError || store.failPage === page) throw new Error(store.loadError || '第二页订单查询失败')
|
||||
// Model server filtering BEFORE pagination and COUNT, using the actual
|
||||
// request produced by the production API. Missing taxMode scans all rows.
|
||||
const filtered = orders.filter(row => (!taxMode || row.taxMode === taxMode)
|
||||
&& (loaded === undefined || row.hasCompletedLoadingPlan === loaded))
|
||||
return store.transformPage({ page, size, total: filtered.length, pages: Math.ceil(filtered.length / size),
|
||||
records: filtered.slice((page - 1) * size, page * size).map(row => ({ orderId: row.id, orderNo: row.orderNo, mainStatus: row.status, taxMode: row.taxMode, inboundCode: row.businessSummary.inboundCode })) })
|
||||
} },
|
||||
})
|
||||
const reader = evaluate(readFileSync(new URL('../utils/customsDocumentsReader.ts', import.meta.url), 'utf8'), {
|
||||
'./customsEligibility': eligibility,
|
||||
'../api/unifiedOrders': unifiedApi,
|
||||
'../api/customs': { getMerchantCustomsForOrder: id => { calls.push(id); return getDetail(id) }, isMerchantCustomsUnavailable: error => error?.code === 'A0404' },
|
||||
})
|
||||
const source = readFileSync(new URL('./CustomsDocumentsView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const scope = vue.effectScope()
|
||||
const view = scope.run(() => evaluate(source + '\nexport { load, records, loading, errorMessage, openDetail, selectedOrderId, selectedDetail, dialogOpen, search, queryModel, filteredRecords, pagedRecords, page, pageSize, queryFields, statusLabel, statusType, updateDetail }', {
|
||||
vue: { ...vue, onMounted() {} },
|
||||
'../utils/customsDocumentsReader': reader,
|
||||
'../api/customs': customsApi,
|
||||
}))
|
||||
t.after(() => scope.stop())
|
||||
return { view, store, calls, pageCalls }
|
||||
}
|
||||
|
||||
test('server-filtered request reaches five refund records originally on page 28 without scanning buy orders', async t => {
|
||||
const orders = Array.from({ length: 5528 }, (_, i) => order(`buy-${i}`, 'COMPLETED', 'BUY_DECLARATION'))
|
||||
orders.push(...Array.from({ length: 2613 }, (_, i) => order(`not-loaded-${i}`, 'WAIT_MEASURE')))
|
||||
orders.push(...Array.from({ length: 5 }, (_, i) => order(`historical-${i}`, 'COMPLETED')))
|
||||
const { view, calls, pageCalls } = harness(t, orders)
|
||||
await view.load()
|
||||
assert.deepEqual(calls, Array.from({ length: 5 }, (_, i) => `historical-${i}`))
|
||||
assert.equal(view.records.value.length, 5)
|
||||
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||
view.queryModel.value.inboundCode = 'historical-4'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 1)
|
||||
view.queryModel.value = { orderNo: '', inboundCode: '', containerNo: '', status: '' }; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 5)
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 5)
|
||||
})
|
||||
|
||||
test('second page failure is explicit and retry does not retain an incomplete result', async t => {
|
||||
const orders = Array.from({ length: 201 }, (_, i) => order(String(i)))
|
||||
const { view, store, pageCalls } = harness(t, orders)
|
||||
store.failPage = 2
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '第二页订单查询失败')
|
||||
store.failPage = 0
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 201)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
assert.equal(pageCalls.length, 4)
|
||||
})
|
||||
|
||||
test('display pagination reaches the final refund order without refetching or opening the wrong detail', async t => {
|
||||
const { view, calls, pageCalls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`, 'COMPLETED')))
|
||||
await view.load()
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
view.page.value = 2
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
view.openDetail(view.pagedRecords.value[0])
|
||||
assert.equal(view.selectedOrderId.value, 'refund-20')
|
||||
assert.deepEqual(view.selectedDetail.value.inbounds, [{ orderId: 'refund-20', taxMode: 'TAX_REFUND' }])
|
||||
view.pageSize.value = 10
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 10)
|
||||
view.page.value = 3
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 21)
|
||||
})
|
||||
|
||||
test('searching from a later display page resets pagination and clearing filters restores all documents', async t => {
|
||||
const { view, calls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||
await view.load()
|
||||
view.page.value = 2
|
||||
view.queryModel.value.inboundCode = 'IN-refund-20'
|
||||
view.search()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||
view.queryModel.value.inboundCode = 'does-not-exist'
|
||||
view.search()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 0)
|
||||
view.queryModel.value.inboundCode = ''
|
||||
view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 21)
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
assert.equal(calls.length, 21)
|
||||
})
|
||||
|
||||
test('refresh failure on a later page clears stale rows and retry returns to a valid page', async t => {
|
||||
const { view, store } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||
await view.load()
|
||||
view.page.value = 2
|
||||
store.loadError = '资料列表请求失败'
|
||||
await view.load()
|
||||
await vue.nextTick()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '资料列表请求失败')
|
||||
store.loadError = ''
|
||||
await view.load()
|
||||
assert.equal(view.page.value, 1)
|
||||
assert.equal(view.pagedRecords.value.length, 20)
|
||||
assert.equal(view.filteredRecords.value.length, 21)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('empty pages, duplicate records and changing totals cannot silently truncate history', async t => {
|
||||
for (const change of [
|
||||
response => response.page === 2 ? { ...response, records: [] } : response,
|
||||
response => response.page === 2 ? { ...response, records: [{ ...response.records[0], orderId: '0' }] } : response,
|
||||
response => response.page === 2 ? { ...response, total: 202 } : response,
|
||||
]) {
|
||||
const { view, store, pageCalls } = harness(t, Array.from({ length: 201 }, (_, i) => order(String(i), 'COMPLETED')))
|
||||
store.transformPage = change
|
||||
await view.load()
|
||||
assert.ok(view.errorMessage.value)
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(pageCalls.length, 2)
|
||||
}
|
||||
})
|
||||
|
||||
test('document fetch concurrency never exceeds four and each candidate is requested once', async t => {
|
||||
let active = 0, peak = 0
|
||||
const { view, calls, pageCalls } = harness(t, Array.from({ length: 205 }, (_, i) => order(String(i))), async id => {
|
||||
active += 1; peak = Math.max(peak, active)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
active -= 1
|
||||
return detail(id)
|
||||
})
|
||||
await view.load()
|
||||
assert.equal(peak, 4)
|
||||
assert.equal(new Set(calls).size, 205)
|
||||
assert.equal(calls.length, 205)
|
||||
assert.equal(pageCalls.length, 2)
|
||||
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }, { page: 2, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||
assert.equal(view.records.value.length, 205)
|
||||
})
|
||||
|
||||
test('empty result uses one page request and no document requests', async t => {
|
||||
const { view, calls, pageCalls } = harness(t, [])
|
||||
await view.load()
|
||||
assert.equal(pageCalls.length, 1)
|
||||
assert.equal(calls.length, 0)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('tax-refund documents remain accessible through delivered and completed orders; buy orders and preloading are excluded', async t => {
|
||||
const stages = ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE', 'WAIT_PALLETIZE', 'WAIT_SPLIT', 'LOADING', 'LOADED', 'DELIVERED', 'COMPLETED']
|
||||
const orders = stages.flatMap(status => [order(status, status), order(`BUY-${status}`, status, 'BUY_DECLARATION')])
|
||||
const { view, calls } = harness(t, orders)
|
||||
await view.load()
|
||||
assert.deepEqual(calls, ['LOADED', 'DELIVERED', 'COMPLETED'])
|
||||
assert.deepEqual(view.records.value.map(row => row.order.id), calls)
|
||||
const completed = view.records.value.find(row => row.order.id === 'COMPLETED')
|
||||
view.openDetail(completed)
|
||||
assert.equal(view.selectedOrderId.value, 'COMPLETED')
|
||||
assert.equal(view.selectedDetail.value.status, 'COMPLETED')
|
||||
assert.equal(view.dialogOpen.value, true)
|
||||
view.queryModel.value.status = 'CUSTOMS_COMPLETED'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 3)
|
||||
assert.equal(calls.length, 3, 'local filtering does not refetch documents')
|
||||
})
|
||||
|
||||
test('only matching server-returned tax-refund ownership is displayed', async t => {
|
||||
const { view } = harness(t, [order('one'), order('two')], async id => id === 'one' ? detail('someone-else') : { inbounds: [{ orderId: id, taxMode: 'BUY_DECLARATION' }] })
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
})
|
||||
|
||||
test('partial failures are visible and retry replaces the result; unavailable customs is not a transport failure', async t => {
|
||||
let fail = true
|
||||
const { view } = harness(t, [order('ok'), order('retry'), order('unavailable')], async id => {
|
||||
if (id === 'unavailable') throw Object.assign(new Error('not associated'), { code: 'A0404' })
|
||||
if (id === 'retry' && fail) throw new Error('network')
|
||||
return detail(id)
|
||||
})
|
||||
await view.load()
|
||||
assert.equal(view.records.value.length, 1)
|
||||
assert.equal(view.errorMessage.value, '1 票订单的报关资料加载失败,请重新加载')
|
||||
fail = false; await view.load()
|
||||
assert.equal(view.records.value.length, 2)
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('order query failure is shown instead of a successful empty result', async t => {
|
||||
const { view, store, calls } = harness(t, [order('old')])
|
||||
await view.load()
|
||||
store.loadError = '订单查询失败'; await view.load()
|
||||
assert.equal(view.records.value.length, 0)
|
||||
assert.equal(view.errorMessage.value, '订单查询失败')
|
||||
assert.equal(calls.length, 1)
|
||||
assert.equal(view.loading.value, false)
|
||||
})
|
||||
|
||||
test('repeated refresh during an active load does not duplicate requests', async t => {
|
||||
let resolve
|
||||
const pending = new Promise(done => { resolve = done })
|
||||
const { view, calls } = harness(t, [order('one')], () => pending)
|
||||
const first = view.load()
|
||||
await Promise.resolve()
|
||||
await view.load()
|
||||
assert.deepEqual(calls, ['one'])
|
||||
resolve(detail('one')); await first
|
||||
assert.equal(view.loading.value, false)
|
||||
})
|
||||
|
||||
test('mixed-container labels and filters use only the current customer status', async t => {
|
||||
const states = [
|
||||
['uploaded', 'WAITING_CUSTOMER_DOCUMENTS', 'DOCUMENT_UPLOADED', 1, '资料已上传', 'success'],
|
||||
['waiting', 'WAITING_CUSTOMER_DOCUMENTS', 'WAITING_UPLOAD', 0, '待上传资料', 'warning'],
|
||||
['declaring', 'DECLARING', 'DECLARING', 1, '报关中', 'primary'],
|
||||
['completed', 'COMPLETED', 'CUSTOMS_COMPLETED', 1, '报关完成', 'success'],
|
||||
]
|
||||
const { view, calls } = harness(t, states.map(([id]) => order(id)), async id => {
|
||||
const [, status, merchantStatus, coveredTaxRefundCount] = states.find(row => row[0] === id)
|
||||
return { ...detail(id), status, merchantStatus, coveredTaxRefundCount, taxRefundCount: 1 }
|
||||
})
|
||||
await view.load()
|
||||
for (const [id, , merchantStatus, , label, tone] of states) {
|
||||
const row = view.records.value.find(item => item.order.id === id)
|
||||
assert.equal(view.statusLabel(row.detail), label)
|
||||
assert.equal(view.statusType(row.detail), tone)
|
||||
view.queryModel.value.status = merchantStatus; view.search()
|
||||
assert.deepEqual(view.filteredRecords.value.map(item => item.order.id), [id])
|
||||
}
|
||||
assert.deepEqual(view.queryFields.find(field => field.key === 'status').options,
|
||||
states.map(([, , value, , label]) => ({ value, label })).sort((a, b) =>
|
||||
['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(a.value)
|
||||
- ['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(b.value)))
|
||||
view.queryModel.value.status = 'WAITING_CUSTOMER_DOCUMENTS'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 0, 'container statuses are not customer filter values')
|
||||
view.queryModel.value.status = ''; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 4)
|
||||
assert.equal(calls.length, 4, 'filtering does not requery or infer status from coverage')
|
||||
})
|
||||
|
||||
test('dialog update refreshes customer status and active filter without inferring from container status', async t => {
|
||||
const { view } = harness(t, [order('one')], async id => ({ ...detail(id), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }))
|
||||
await view.load(); view.openDetail(view.records.value[0])
|
||||
view.queryModel.value.status = 'WAITING_UPLOAD'; view.search()
|
||||
view.updateDetail({ ...detail('one'), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED', coveredTaxRefundCount: 1, taxRefundCount: 1 })
|
||||
assert.equal(view.filteredRecords.value.length, 0)
|
||||
view.queryModel.value.status = 'DOCUMENT_UPLOADED'; view.search()
|
||||
assert.equal(view.filteredRecords.value.length, 1)
|
||||
assert.equal(view.statusLabel(view.filteredRecords.value[0].detail), '资料已上传')
|
||||
assert.equal(view.statusLabel({ status: 'COMPLETED', coveredTaxRefundCount: 1, taxRefundCount: 1 }), '—')
|
||||
assert.equal(view.statusType({ status: 'COMPLETED' }), 'info')
|
||||
})
|
||||
@@ -1,47 +1,85 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { FileText, RefreshCcw } from '@lucide/vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useFirstLegOrdersStore } from '../public'
|
||||
import { getMerchantCustomsForOrder, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { RefreshCcw } from '@lucide/vue'
|
||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||
import type { TableAction } from '@/components/common/tableActions'
|
||||
import { MERCHANT_CUSTOMS_STATUS_LABELS, type MerchantCustomsContainer } from '../api/customs'
|
||||
import { readCustomsDocuments, type CustomsDocumentRow } from '../utils/customsDocumentsReader'
|
||||
import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue'
|
||||
import type { FirstLegOrder } from '../types/firstLegOrder'
|
||||
|
||||
const store = useFirstLegOrdersStore()
|
||||
const loading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const keyword = ref('')
|
||||
const records = ref<Array<{ order: FirstLegOrder; detail: MerchantCustomsContainer }>>([])
|
||||
const queryModel = ref<QueryModel>({ orderNo: '', inboundCode: '', containerNo: '', status: '' })
|
||||
const appliedQuery = ref<QueryModel>({ ...queryModel.value })
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const queryFields: QueryField[] = [
|
||||
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||
{ key: 'inboundCode', label: '入仓码', type: 'input', placeholder: '请输入入仓码' },
|
||||
{ key: 'containerNo', label: '柜号', type: 'input', placeholder: '请输入柜号' },
|
||||
{ key: 'status', label: '状态', type: 'select', placeholder: '全部', options: Object.entries(MERCHANT_CUSTOMS_STATUS_LABELS).map(([value, label]) => ({ label, value })) },
|
||||
]
|
||||
const columns: DataTableColumn[] = [
|
||||
{ label: '操作', slotName: 'actions', width: 120, fixed: 'left' },
|
||||
{ label: '订单号', slotName: 'orderNo', minWidth: 230 },
|
||||
{ label: '入仓码', slotName: 'inboundCode', minWidth: 190 },
|
||||
{ label: '柜号', slotName: 'containerNo', minWidth: 170 },
|
||||
{ label: '柜内退税箱数', prop: 'detail.actualBoxCount', width: 110, align: 'center' },
|
||||
{ label: '柜内资料覆盖', slotName: 'coverage', width: 110, align: 'center' },
|
||||
{ label: '状态', slotName: 'status', width: 130 },
|
||||
]
|
||||
const records = ref<CustomsDocumentRow[]>([])
|
||||
const dialogOpen = ref(false)
|
||||
const selectedOrderId = ref('')
|
||||
const selectedDetail = ref<MerchantCustomsContainer | null>(null)
|
||||
|
||||
const filteredRecords = computed(() => {
|
||||
const query = keyword.value.trim().toLowerCase()
|
||||
if (!query) return records.value
|
||||
return records.value.filter(({ order, detail }) => [order.orderNo, order.businessSummary.inboundCode, detail.containerNo, detail.cabinetNo].some((value) => String(value ?? '').toLowerCase().includes(query)))
|
||||
const query = appliedQuery.value
|
||||
const matches = (value: string | null | undefined, key: string) => String(value ?? '').toLowerCase().includes(String(query[key] || '').trim().toLowerCase())
|
||||
return records.value.filter(({ order, detail }) =>
|
||||
matches(order.orderNo, 'orderNo')
|
||||
&& matches(order.businessSummary.inboundCode, 'inboundCode')
|
||||
&& (matches(detail.containerNo, 'containerNo') || matches(detail.cabinetNo, 'containerNo'))
|
||||
&& (!query.status || detail.merchantStatus === query.status),
|
||||
)
|
||||
})
|
||||
const pagedRecords = computed(() => filteredRecords.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
const emptyText = computed(() => Object.values(appliedQuery.value).some((value) => String(value || '').trim()) ? '暂无匹配的报关资料,请调整查询条件' : '暂无报关资料')
|
||||
|
||||
function search() {
|
||||
appliedQuery.value = { ...queryModel.value }
|
||||
page.value = 1
|
||||
}
|
||||
watch(pageSize, () => { page.value = 1 })
|
||||
watch(() => filteredRecords.value.length, (total) => {
|
||||
page.value = Math.min(page.value, Math.max(1, Math.ceil(total / pageSize.value)))
|
||||
})
|
||||
function rowActions(row: object): TableAction[] {
|
||||
return [{ key: 'documents', label: '查看资料', disabled: loading.value, run: () => openDetail(row) }]
|
||||
}
|
||||
|
||||
function statusLabel(detail: MerchantCustomsContainer) {
|
||||
return ({ WAITING_CUSTOMER_DOCUMENTS: '待上传资料', READY_TO_START: '待报关', DECLARING: '报关中', COMPLETED: '报关完成' } as Record<string, string>)[detail.status] ?? detail.status
|
||||
return detail.merchantStatus ? MERCHANT_CUSTOMS_STATUS_LABELS[detail.merchantStatus] ?? '—' : '—'
|
||||
}
|
||||
function statusType(detail: MerchantCustomsContainer) {
|
||||
return detail.status === 'COMPLETED' ? 'success' : detail.status === 'DECLARING' ? 'primary' : 'warning'
|
||||
return detail.merchantStatus === 'CUSTOMS_COMPLETED' || detail.merchantStatus === 'DOCUMENT_UPLOADED'
|
||||
? 'success' : detail.merchantStatus === 'DECLARING' ? 'primary' : detail.merchantStatus === 'WAITING_UPLOAD' ? 'warning' : 'info'
|
||||
}
|
||||
async function load() {
|
||||
if (loading.value) return
|
||||
loading.value = true; errorMessage.value = ''
|
||||
try {
|
||||
await store.load()
|
||||
const candidates = store.orders.filter((order) => order.status === 'LOADED' && order.taxMode === 'TAX_REFUND')
|
||||
const results = await Promise.allSettled(candidates.map(async (order) => ({ order, detail: await getMerchantCustomsForOrder(order.id) })))
|
||||
records.value = results.flatMap((result) => result.status === 'fulfilled' && result.value.detail.inbounds.some((item) => item.orderId === result.value.order.id && item.taxMode === 'TAX_REFUND') ? [result.value] : [])
|
||||
const { records: loadedRecords, failedCount } = await readCustomsDocuments()
|
||||
records.value = loadedRecords
|
||||
if (failedCount) errorMessage.value = `${failedCount} 票订单的报关资料加载失败,请重新加载`
|
||||
} catch (error) {
|
||||
records.value = []
|
||||
errorMessage.value = error instanceof Error ? error.message : '报关资料加载失败,请稍后重试'
|
||||
} finally { loading.value = false }
|
||||
}
|
||||
function openDetail(item: unknown) {
|
||||
const value = item as { order: FirstLegOrder; detail: MerchantCustomsContainer }
|
||||
const value = item as CustomsDocumentRow
|
||||
selectedOrderId.value = value.order.id; selectedDetail.value = value.detail; dialogOpen.value = true
|
||||
}
|
||||
function updateDetail(value: MerchantCustomsContainer) {
|
||||
@@ -53,26 +91,25 @@ onMounted(() => { void load() })
|
||||
|
||||
<template>
|
||||
<div class="customs-page">
|
||||
<section class="customs-hero"><div><span class="eyebrow">CUSTOMS DOCUMENTS</span><h1>报关资料</h1><p>查看装柜后退税订单的资料清单、文件版本与报关行回执。</p></div><el-button :loading="loading" @click="load"><RefreshCcw :size="15" />刷新</el-button></section>
|
||||
<section class="customs-toolbar"><el-input v-model="keyword" clearable placeholder="搜索订单号、入仓码或柜号" /><span>共 {{ filteredRecords.length }} 个资料包</span></section>
|
||||
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" />
|
||||
<section class="customs-card">
|
||||
<el-skeleton v-if="loading" :rows="5" animated />
|
||||
<div v-else-if="errorMessage" class="state-error" role="alert"><p>{{ errorMessage }}</p><el-button @click="load">重试</el-button></div>
|
||||
<el-empty v-else-if="!filteredRecords.length" description="暂无待处理的报关资料" />
|
||||
<el-table v-else :data="filteredRecords" row-key="order.id" stripe>
|
||||
<el-table-column label="操作" width="120" fixed="left"><template #default="{ row }"><el-button link type="primary" @click="openDetail(row)"><FileText :size="15" />查看资料</el-button></template></el-table-column>
|
||||
<el-table-column label="订单号" min-width="160"><template #default="{ row }">{{ row.order.orderNo || '—' }}</template></el-table-column>
|
||||
<el-table-column label="入仓码" min-width="150"><template #default="{ row }">{{ row.order.businessSummary.inboundCode || '—' }}</template></el-table-column>
|
||||
<el-table-column label="柜号" min-width="140"><template #default="{ row }">{{ row.detail.containerNo || row.detail.cabinetNo || '—' }}</template></el-table-column>
|
||||
<el-table-column label="实际箱数" width="100" prop="detail.actualBoxCount" />
|
||||
<el-table-column label="资料覆盖" width="110"><template #default="{ row }">{{ row.detail.coveredTaxRefundCount }} / {{ row.detail.taxRefundCount }}</template></el-table-column>
|
||||
<el-table-column label="状态" width="120"><template #default="{ row }"><el-tag :type="statusType(row.detail)">{{ statusLabel(row.detail) }}</el-tag></template></el-table-column>
|
||||
</el-table>
|
||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRecords" :columns="columns" :loading="loading" :total="filteredRecords.length" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="order.id" :empty-text="emptyText">
|
||||
<template #toolbar><strong>资料列表</strong><span>统计为本客户同柜退税货物汇总,资料覆盖按入仓码计。</span></template>
|
||||
<template #toolbar-actions><el-button :loading="loading" @click="load"><RefreshCcw :size="16" />刷新</el-button></template>
|
||||
<template v-if="errorMessage" #error><div class="state-error" role="alert"><span>{{ errorMessage }}</span><el-button :loading="loading" @click="load">重新加载</el-button></div></template>
|
||||
<template #orderNo="{ row }">{{ row.order.orderNo || '—' }}</template>
|
||||
<template #inboundCode="{ row }">{{ row.order.businessSummary.inboundCode || '—' }}</template>
|
||||
<template #containerNo="{ row }">{{ row.detail.containerNo || row.detail.cabinetNo || '—' }}</template>
|
||||
<template #coverage="{ row }">{{ row.detail.coveredTaxRefundCount }} / {{ row.detail.taxRefundCount }}</template>
|
||||
<template #status="{ row }"><el-tag :type="statusType(row.detail)" effect="light" size="small">{{ statusLabel(row.detail) }}</el-tag></template>
|
||||
</DataTable>
|
||||
</section>
|
||||
<CustomsDocumentsDialog v-model="dialogOpen" :order-id="selectedOrderId" :can-edit="selectedDetail?.status !== 'COMPLETED'" :initial-detail="selectedDetail" @updated="updateDetail" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.customs-page { display:flex; flex-direction:column; gap:16px; }.customs-hero { display:flex; justify-content:space-between; align-items:flex-start; padding:0 2px 4px; }.eyebrow { color:#5b82c9; font-size:11px; font-weight:750; letter-spacing:.14em; }.customs-hero h1 { margin:6px 0 5px; color:#1f2f46; font-size:26px; line-height:1.25; letter-spacing:-.025em; }.customs-hero p { margin:0; color:#7d8da2; font-size:13px; }.customs-hero .el-button { margin-top:3px; border-color:#d9e3ef; border-radius:9px; background:#fff; color:#61738b; box-shadow:0 3px 8px rgba(26,55,91,.04); }.customs-toolbar { display:flex; min-height:82px; align-items:center; gap:16px; padding:16px 18px; border:1px solid #dce4ef; border-radius:16px; background:#fff; box-shadow:0 5px 16px rgba(31,56,88,.045); }.customs-toolbar .el-input { width:min(520px, 100%); }.customs-toolbar :deep(.el-input__wrapper) { min-height:42px; border-radius:10px; box-shadow:0 0 0 1px #d9e3ef inset; }.customs-toolbar span { color:#7d8da2; font-size:12px; }.customs-card { min-height:320px; padding:4px; overflow:hidden; border:1px solid #dce4ef; border-radius:16px; background:#fff; box-shadow:0 5px 16px rgba(31,56,88,.045); }.customs-card :deep(.el-table) { --el-table-header-bg-color:#f4f7fb; --el-table-row-hover-bg-color:#eaf2ff; --el-table-border-color:#edf1f6; color:#53647a; }.customs-card :deep(.el-table th.el-table__cell) { padding:13px 16px; color:#607089; font-size:12px; font-weight:750; }.customs-card :deep(.el-table td.el-table__cell) { height:58px; padding:13px 16px; font-size:13px; }.customs-card :deep(.el-table__row:nth-child(even)) { background:#f8fbff; }.state-error { display:flex; min-height:260px; flex-direction:column; align-items:center; justify-content:center; gap:10px; color:#b42318; }.state-error p { margin:0; }
|
||||
.customs-page { display: grid; gap: var(--client-section-gap); }
|
||||
.customs-card { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
|
||||
.state-error { display: flex; min-height: 84px; align-items: center; justify-content: center; gap: 12px; padding: 14px; color: #b42318; }
|
||||
</style>
|
||||
|
||||
@@ -35,17 +35,16 @@ test('opens order creation as a dedicated protected page while keeping draft edi
|
||||
assert.match(editorShellSource, /\.editor-page-footer :deep\(\.editor-actions\) \{[^}]*justify-content: center;/)
|
||||
})
|
||||
|
||||
test('exposes real list, draft, submit, and detail workflow entries without cancellation', () => {
|
||||
test('exposes real list, draft, submit, and detail workflow entries', () => {
|
||||
assert.match(source, /function openCreate\(\)/)
|
||||
assert.match(source, /async function saveDraft\(\)/)
|
||||
assert.match(source, /function submitOrder\(\)/)
|
||||
assert.match(source, /async function openDetail\(order: FirstLegOrder\)/)
|
||||
assert.match(source, /Promise\.allSettled\(\[/)
|
||||
assert.match(source, /const orderPageRequest = isCreatePage\.value \|\| isDetailPage\.value\s*\? store\.loadWarehouseType\('DOMESTIC', true\)\s*:\s*store\.load\(\{ includeDrafts: true \}\)/)
|
||||
assert.match(source, /const orderPageRequest = isCreatePage\.value \|\| isDetailPage\.value\s*\? store\.loadWarehouseType\('DOMESTIC', true\)\s*:\s*loadOrderPage\(\)/)
|
||||
assert.match(source, /Promise\.allSettled\(\[\s*orderPageRequest,\s*companyRequest/)
|
||||
assert.match(source, /tenantStore\.loadCompanyContext\(\)/)
|
||||
assert.match(source, /await store\.loadDetail\(orderId\)/)
|
||||
assert.doesNotMatch(source, /cancelOrder|取消订单/)
|
||||
})
|
||||
|
||||
test('returns edited submissions to the refreshed order list instead of opening detail', () => {
|
||||
@@ -67,7 +66,7 @@ test('copies an order into the dedicated create page without reusing order ident
|
||||
})
|
||||
|
||||
test('keeps create-page support errors scoped to create-page requests', () => {
|
||||
assert.match(source, /if \(!isCreatePage\.value && store\.draftLoadError\)/)
|
||||
assert.doesNotMatch(source, /store\.draftLoadError/)
|
||||
})
|
||||
|
||||
test('blocks order submission before company approval while preserving draft actions', () => {
|
||||
@@ -115,7 +114,7 @@ test('uses the shared query toolbar and data table without metric cards', () =>
|
||||
assert.match(source, /<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" \/>/)
|
||||
assert.match(source, /async function searchOrders\(model: QueryModel\)/)
|
||||
assert.match(source, /await store\.load\(\{/)
|
||||
assert.match(source, /<DataTable v-model:page="tablePage" v-model:page-size="tablePageSize" :data="pagedOrders" :columns="visibleOrderColumns"/)
|
||||
assert.match(source, /<DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns"/)
|
||||
assert.match(source, /\{ key: 'actions', label: '操作', width: 284, fixed: 'left', align: 'left', headerAlign: 'left', slotName: 'actions' \}/)
|
||||
assert.doesNotMatch(source, /order-metrics|订单概览/)
|
||||
})
|
||||
@@ -232,6 +231,9 @@ test('shows one unified progress line and C02 business summaries without detail
|
||||
assert.doesNotMatch(source, /<h3>报关回执<\/h3>/)
|
||||
assert.match(source, /船期摘要/)
|
||||
assert.match(source, /柜次明细/)
|
||||
assert.match(source, /pickingStatusLabel: getFirstLegPickingStatusLabel\(summary\.loadingStatus\)/)
|
||||
assert.match(source, /prop="pickingStatusLabel" label="拣货状态"/)
|
||||
assert.doesNotMatch(source, /label="当前节点"/)
|
||||
assert.match(source, /尚未分配柜次,后续柜次节点将在这里同步。/)
|
||||
assert.doesNotMatch(source, /暂无柜次分配信息/)
|
||||
assert.doesNotMatch(source, /summary\.sealNo \|\|/)
|
||||
@@ -245,9 +247,9 @@ test('uses only fields present on C02 rows before loading full detail', () => {
|
||||
assert.match(source, /displayListValue/)
|
||||
assert.doesNotMatch(source, /key: 'operator'/)
|
||||
assert.doesNotMatch(source, /key: 'transportMode', type: 'select'/)
|
||||
assert.match(source, /store\.draftLoadError/)
|
||||
assert.match(source, /mainStatus: statusValue && statusValue !== 'DRAFT' \? statusValue : undefined/)
|
||||
assert.match(source, /draftOnly: statusValue === 'DRAFT'/)
|
||||
assert.match(source, /:total="store\.total"/)
|
||||
assert.match(source, /mainStatus: text\('status'\)/)
|
||||
assert.match(source, /queue: activeOrderQueue\.value, page: requestedPage, size: tablePageSize\.value/)
|
||||
assert.match(source, /createdFrom: range\[0\] \? `\$\{range\[0\]\}T00:00:00`/)
|
||||
})
|
||||
|
||||
@@ -637,8 +639,8 @@ test('shows billing-weight confirmation only when the backend marks it pending',
|
||||
|
||||
test('submits only selected draft orders in one batch action', () => {
|
||||
assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/)
|
||||
assert.match(source, /Promise\.allSettled\(drafts\.map\(\(order\) => submitMerchantFirstLegOrder/)
|
||||
assert.match(source, /createIdempotencyKey\(`first-leg-batch-submit-\$\{order\.id\}`\)/)
|
||||
assert.match(source, /Promise\.allSettled\(ids\.map\(id => store\.submitSaved/)
|
||||
assert.doesNotMatch(source, /submitMerchantFirstLegOrder/)
|
||||
assert.match(source, /v-if="canSubmitOrder"[\s\S]*批量提交草稿/)
|
||||
})
|
||||
|
||||
@@ -684,8 +686,8 @@ test('opens the server-owned inbound-code association from the order detail', ()
|
||||
assert.doesNotMatch(source, /openInboundCodeAssociation\([^)]*\.id\)/)
|
||||
})
|
||||
|
||||
test('opens customer customs documents only for server-confirmed loaded tax-refund orders', () => {
|
||||
assert.match(source, /order\.status !== 'LOADED'/)
|
||||
test('opens customer customs documents only for server-confirmed tax-refund orders after loading', () => {
|
||||
assert.match(source, /!isCustomsOrderCandidate\(order\)/)
|
||||
assert.match(source, /item\.orderId === order\.id && item\.taxMode === 'TAX_REFUND'/)
|
||||
assert.match(source, /getMerchantCustomsForOrder\(order\.id\)/)
|
||||
assert.match(source, /if \(eligibleCustomsDetail\(order\)\) \{\s*actions\.push\(\{ key: 'customs', label: '报关资料'/)
|
||||
@@ -705,7 +707,9 @@ test('supports the frozen customs document workflow and customer-safe downloads'
|
||||
assert.match(customsApiSource, /MAX_CUSTOMS_FILE_SIZE = 50 \* 1024 \* 1024/)
|
||||
assert.match(customsApiSource, /data: \{ inboundIds, expectedVersion: document\.source\.version \}/)
|
||||
assert.match(customsApiSource, /requestId: error\.requestId/)
|
||||
assert.match(customsDialogSource, /报关开始后仅可查看和下载,不提供退回或解锁/)
|
||||
assert.match(customsDialogSource, /客户原始资料已冻结,仍可确认或打回待确认的报关行回执/)
|
||||
assert.match(customsDialogSource, /v-if="detail.status === 'COMPLETED'"[^>]*><strong>报关已完成/)
|
||||
assert.match(customsDialogSource, /真实报关完税文件已齐全/)
|
||||
assert.match(customsDialogSource, /item\.finalDocument/)
|
||||
assert.match(customsDialogSource, /资料版本历史/)
|
||||
assert.match(customsDialogSource, /尚未上传退税报关资料/)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormItemRule, type FormRules, type UploadRequestOptions } from 'element-plus'
|
||||
import { AlertTriangle, ChevronDown, ChevronUp, Download, FilePlus2, FileText, GripVertical, ImagePlus, MapPin, PackageCheck, Pencil, Plus, RotateCcw, Send, SlidersHorizontal, Trash2, Upload } from '@lucide/vue'
|
||||
@@ -12,9 +12,11 @@ import FirstLegOrderEditorShell from '@/modules/first-leg/components/FirstLegOrd
|
||||
import InboundBillingPanel from '@/modules/first-leg/components/InboundBillingPanel.vue'
|
||||
import InboundCodeAssociationDialog from '@/modules/first-leg/components/InboundCodeAssociationDialog.vue'
|
||||
import OrderProgressPanel from '@/modules/first-leg/components/OrderProgressPanel.vue'
|
||||
import TransportFactsTable from '@/modules/first-leg/components/TransportFactsTable.vue'
|
||||
import CustomsDocumentsDialog from '@/modules/first-leg/components/CustomsDocumentsDialog.vue'
|
||||
import { getMerchantInboundBilling } from '@/modules/first-leg/api/inboundBilling'
|
||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '@/modules/first-leg/api/customs'
|
||||
import { isCustomsOrderCandidate, needsCustomsUpload } from '../utils/customsEligibility'
|
||||
import {
|
||||
estimateMerchantFirstLegPrice,
|
||||
createIdempotencyKey,
|
||||
@@ -28,7 +30,6 @@ import {
|
||||
getMerchantOrderAddresses,
|
||||
getMerchantPricingChannels,
|
||||
importMerchantFirstLegOrders,
|
||||
submitMerchantFirstLegOrder,
|
||||
updateMerchantOrderAddress,
|
||||
uploadMerchantProductImage,
|
||||
type CustomerOrderAddress,
|
||||
@@ -40,7 +41,7 @@ import {
|
||||
type MerchantPricingChannel,
|
||||
type InboundCodePolicy,
|
||||
} from '@/modules/first-leg/api/firstLeg'
|
||||
import { useFirstLegOrdersStore } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useFirstLegOrdersStore, type DraftEditSession } from '@/modules/first-leg/store/firstLegOrders'
|
||||
import { useTenantAdministrationStore } from '@/modules/tenant-management/public'
|
||||
import { useAuthStore } from '@/modules/auth/public'
|
||||
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
|
||||
@@ -52,6 +53,7 @@ import {
|
||||
canClientEditFirstLegOrder,
|
||||
createEmptyCargoItem,
|
||||
getFirstLegStatusLabel,
|
||||
getFirstLegPickingStatusLabel,
|
||||
getFirstLegStatusTone,
|
||||
getFirstLegTransportModeLabel,
|
||||
summarizeFirstLegCargo,
|
||||
@@ -78,6 +80,53 @@ const companyAuditLoaded = ref(false)
|
||||
const companySubmissionBlocked = computed(() => companyAuditLoaded.value && tenantStore.company.auditStatus !== 'ACTIVE')
|
||||
const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create'))
|
||||
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel'))
|
||||
const cancellingOrderId = ref('')
|
||||
const pendingCancellation = shallowRef<{ id: string; expectedVersion: number; reason: string; businessNo: string; statusLabel: string }>()
|
||||
|
||||
function canOfferCancellation(order: FirstLegOrder) {
|
||||
return canCancelOrder.value && ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE'].includes(order.status)
|
||||
}
|
||||
|
||||
async function cancelOrder(order: FirstLegOrder) {
|
||||
if (!canOfferCancellation(order) || cancellingOrderId.value) return
|
||||
cancellingOrderId.value = order.id
|
||||
try {
|
||||
let command = pendingCancellation.value
|
||||
if (command && command.id !== order.id) {
|
||||
ElMessage.warning(`请先处理订单 ${command.businessNo} 未确认的取消结果`)
|
||||
return
|
||||
}
|
||||
if (!command) {
|
||||
const target = await store.prepareCancellation(order.id)
|
||||
const { value } = await ElMessageBox.prompt(`订单:${target.businessNo};当前状态:${target.statusLabel}。请填写取消原因。`, '取消订单', {
|
||||
type: 'warning', inputType: 'textarea', confirmButtonText: '确认取消订单', cancelButtonText: '返回',
|
||||
inputValidator: value => Boolean(value?.trim()) && value.trim().length <= 500 || '请填写 1–500 字取消原因',
|
||||
})
|
||||
command = { ...target, reason: value.trim() }
|
||||
pendingCancellation.value = command
|
||||
} else {
|
||||
await ElMessageBox.confirm(`订单:${command.businessNo};原状态:${command.statusLabel};原因:${command.reason}。将查询当前状态并重试原取消请求。`, '重试取消订单', {
|
||||
type: 'warning', confirmButtonText: '重试原请求', cancelButtonText: '返回',
|
||||
})
|
||||
}
|
||||
await store.cancelOrder(command.id, command.expectedVersion, command.reason)
|
||||
pendingCancellation.value = undefined
|
||||
ElMessage.success('订单已取消')
|
||||
await loadOrderPage()
|
||||
if (isDetailPage.value) await router.push({ name: 'first-leg-orders' })
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return
|
||||
if (error instanceof ApiError && (error.code === 'A0409' || error.status === 409)) {
|
||||
pendingCancellation.value = undefined
|
||||
ElMessage.error(`${error.message}。请刷新订单后重新确认取消。`)
|
||||
} else {
|
||||
ElMessage.error(error instanceof Error ? error.message : '取消失败,请重试原请求')
|
||||
}
|
||||
} finally {
|
||||
cancellingOrderId.value = ''
|
||||
}
|
||||
}
|
||||
const canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
|
||||
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||
const availableWarehouses = computed(() => store.warehouses.filter((warehouse) => warehouse.warehouseType === 'DOMESTIC'))
|
||||
@@ -87,9 +136,9 @@ const appliedFilters = ref<QueryModel>({ ...filters.value })
|
||||
const queryFields = computed<QueryField[]>(() => [
|
||||
{ key: 'cargoKeyword', label: '入仓码 / SKU', type: 'input', placeholder: '请输入入仓码或 SKU', props: { 'aria-label': '入仓码或 SKU' } },
|
||||
{ key: 'receivingWarehouseId', label: '收货仓', type: 'select', placeholder: '全部', options: availableWarehouses.value.map((item) => ({ label: item.name, value: item.id })), props: { 'aria-label': '收货仓' } },
|
||||
{ key: 'channelName', label: '渠道名称', type: 'select', placeholder: '全部', options: [...new Set(store.orders.map((item) => item.channelName).filter(Boolean))].map((name) => ({ label: name, value: name })), props: { 'aria-label': '渠道名称' } },
|
||||
{ key: 'channelName', label: '渠道名称', type: 'select', placeholder: '全部', options: store.queryChannelNames.map((name) => ({ label: name, value: name })), props: { 'aria-label': '渠道名称' } },
|
||||
{ key: 'createdRange', label: '创建时间', type: 'daterange', placeholder: '请选择创建时间', props: { 'aria-label': '创建时间' } },
|
||||
{ key: 'status', label: '当前状态', type: 'select', placeholder: '全部', options: FIRST_LEG_ORDER_STATUSES.map((item) => ({ label: item.label, value: item.code })), props: { 'aria-label': '当前状态' } },
|
||||
{ key: 'status', label: '当前状态', type: 'select', placeholder: '全部', options: FIRST_LEG_ORDER_STATUSES.filter(item => item.code !== 'CANCELLED').map((item) => ({ label: item.label, value: item.code })), props: { 'aria-label': '当前状态' } },
|
||||
{ key: 'destinationType', label: '目的仓类型', type: 'select', placeholder: '全部', options: [{ label: 'FBA 仓', value: 'FBA' }, { label: '海外仓', value: 'OVERSEAS' }, { label: '私人地址', value: 'PRIVATE' }], props: { 'aria-label': '目的仓类型' } },
|
||||
{ key: 'trackingNumber', label: '快递单号', type: 'input', placeholder: '请输入快递单号', props: { 'aria-label': '快递单号' } },
|
||||
])
|
||||
@@ -189,6 +238,7 @@ const tablePageSize = ref(10)
|
||||
const downloadingMarks = ref(false)
|
||||
const exportingOrders = ref(false)
|
||||
const batchSubmitting = ref(false)
|
||||
const pendingBatchSubmissionIds = ref<string[]>([])
|
||||
const selectedOrders = ref<FirstLegOrder[]>([])
|
||||
const selectedOrderCount = computed(() => selectedOrders.value.length)
|
||||
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
|
||||
@@ -198,6 +248,7 @@ const activeOrderQueue = ref<OrderQueue>('all')
|
||||
const editorOpen = ref(false)
|
||||
const orderFormRef = ref<FormInstance>()
|
||||
const editingId = ref<string>()
|
||||
const editingSession = shallowRef<DraftEditSession>()
|
||||
const openingEditor = ref(false)
|
||||
const copyingOrderId = ref('')
|
||||
const detailId = ref<string>()
|
||||
@@ -450,61 +501,59 @@ useUnsavedWorkRegistration({
|
||||
dirty: editorDirty,
|
||||
})
|
||||
|
||||
function matchesAppliedFilters(order: FirstLegOrder) {
|
||||
const statusValue = appliedFilters.value.status
|
||||
const createdRangeValue = appliedFilters.value.createdRange
|
||||
const textValue = (key: string) => typeof appliedFilters.value[key] === 'string' ? String(appliedFilters.value[key]).trim().toLowerCase() : ''
|
||||
const receivingWarehouseId = textValue('receivingWarehouseId')
|
||||
const channelName = textValue('channelName')
|
||||
const cargoKeyword = textValue('cargoKeyword')
|
||||
const destinationType = textValue('destinationType')
|
||||
const trackingNumber = textValue('trackingNumber')
|
||||
const status = typeof statusValue === 'string' ? statusValue as FirstLegOrderStatus | '' : ''
|
||||
const createdRange = Array.isArray(createdRangeValue) ? createdRangeValue.filter((value): value is string => typeof value === 'string') : []
|
||||
const matchesWarehouse = !receivingWarehouseId || order.receivingWarehouseId.toLowerCase() === receivingWarehouseId
|
||||
const matchesChannel = !channelName || order.channelName.toLowerCase() === channelName
|
||||
const matchesCargo = !cargoKeyword || [order.businessSummary.inboundCode, ...order.skuNos, ...order.items.map((item) => item.sku)]
|
||||
.filter(Boolean).some((value) => String(value).toLowerCase().includes(cargoKeyword))
|
||||
const matchesDestinationType = !destinationType || order.destinationType.toLowerCase() === destinationType
|
||||
const matchesTrackingNumber = !trackingNumber || order.trackingNumber.toLowerCase().includes(trackingNumber)
|
||||
const matchesStatus = !status || order.status === status
|
||||
const matchesDate = createdRange.length !== 2 || (order.createdAt.slice(0, 10) >= createdRange[0] && order.createdAt.slice(0, 10) <= createdRange[1])
|
||||
return matchesWarehouse && matchesChannel && matchesCargo && matchesDestinationType && matchesTrackingNumber && matchesStatus && matchesDate
|
||||
}
|
||||
const orderQueueCounts = computed(() => store.queueCounts)
|
||||
const pagedOrders = computed(() => store.orders)
|
||||
|
||||
const queryMatchedOrders = computed(() => store.orders.filter(matchesAppliedFilters))
|
||||
const orderQueueCounts = computed(() => ({
|
||||
all: queryMatchedOrders.value.length,
|
||||
fee: queryMatchedOrders.value.filter((order) => order.businessSummary.customerFeeConfirmationRequired).length,
|
||||
customs: queryMatchedOrders.value.filter((order) => Boolean(eligibleCustomsDetail(order))).length,
|
||||
draft: queryMatchedOrders.value.filter((order) => order.status === 'DRAFT').length,
|
||||
}))
|
||||
const filteredOrders = computed(() => queryMatchedOrders.value.filter((order) => {
|
||||
if (activeOrderQueue.value === 'fee') return order.businessSummary.customerFeeConfirmationRequired
|
||||
if (activeOrderQueue.value === 'customs') return Boolean(eligibleCustomsDetail(order))
|
||||
if (activeOrderQueue.value === 'draft') return order.status === 'DRAFT'
|
||||
return true
|
||||
}))
|
||||
const pagedOrders = computed(() => {
|
||||
const start = (tablePage.value - 1) * tablePageSize.value
|
||||
return filteredOrders.value.slice(start, start + tablePageSize.value)
|
||||
})
|
||||
|
||||
function selectOrderQueue(queue: OrderQueue) {
|
||||
async function selectOrderQueue(queue: OrderQueue) {
|
||||
activeOrderQueue.value = queue
|
||||
tablePage.value = 1
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
async function changeOrderPage(page: number) {
|
||||
tablePage.value = page
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
async function changeOrderPageSize(size: number) {
|
||||
tablePageSize.value = size
|
||||
tablePage.value = 1
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
let orderPageRequestVersion = 0
|
||||
async function loadOrderPage() {
|
||||
const requestVersion = ++orderPageRequestVersion
|
||||
const text = (key: string) => typeof appliedFilters.value[key] === 'string' ? String(appliedFilters.value[key]).trim() || undefined : undefined
|
||||
const range = Array.isArray(appliedFilters.value.createdRange) ? appliedFilters.value.createdRange : []
|
||||
const requestedPage = tablePage.value
|
||||
await store.load({
|
||||
cargoKeyword: text('cargoKeyword'), receivingWarehouseId: text('receivingWarehouseId'),
|
||||
channelName: text('channelName'), destinationType: text('destinationType'),
|
||||
trackingNumber: text('trackingNumber'), mainStatus: text('status'),
|
||||
createdFrom: range[0] ? `${range[0]}T00:00:00` : undefined,
|
||||
createdTo: range[1] ? `${range[1]}T23:59:59.999` : undefined,
|
||||
queue: activeOrderQueue.value, page: requestedPage, size: tablePageSize.value,
|
||||
})
|
||||
if (requestVersion !== orderPageRequestVersion) return
|
||||
const lastPage = Math.max(1, Math.ceil(store.total / tablePageSize.value))
|
||||
if (!store.loadError && requestedPage > lastPage) {
|
||||
tablePage.value = lastPage
|
||||
await loadOrderPage()
|
||||
return
|
||||
}
|
||||
selectedOrders.value = []
|
||||
orderTableVersion.value += 1
|
||||
}
|
||||
|
||||
function eligibleCustomsDetail(order: FirstLegOrder) {
|
||||
const value = customsByOrder[order.id]
|
||||
if (order.status !== 'LOADED' || !value?.merchantStatus) return null
|
||||
if (!isCustomsOrderCandidate(order) || !value?.merchantStatus) return null
|
||||
return value.inbounds.some((item) => item.orderId === order.id && item.taxMode === 'TAX_REFUND') ? value : null
|
||||
}
|
||||
|
||||
async function loadCustomsEligibility(order: FirstLegOrder) {
|
||||
if (order.status !== 'LOADED' || customsByOrder[order.id] !== undefined || customsEligibilityPending.has(order.id)) return
|
||||
if (!isCustomsOrderCandidate(order) || customsByOrder[order.id] !== undefined || customsEligibilityPending.has(order.id)) return
|
||||
customsEligibilityPending.add(order.id)
|
||||
try {
|
||||
customsByOrder[order.id] = await getMerchantCustomsForOrder(order.id)
|
||||
@@ -536,7 +585,9 @@ function openInboundCodeAssociation(inboundCode: string) {
|
||||
}
|
||||
|
||||
function updateCustomsDetail(value: MerchantCustomsContainer) {
|
||||
const previous = customsByOrder[customsDialogOrderId.value]
|
||||
if (customsDialogOrderId.value) customsByOrder[customsDialogOrderId.value] = value
|
||||
if (!isCreatePage.value && !isDetailPage.value && previous && previous.merchantStatus !== value.merchantStatus) void loadOrderPage()
|
||||
}
|
||||
|
||||
const detailOrder = computed(() => detailId.value ? store.getById(detailId.value) : undefined)
|
||||
@@ -548,7 +599,7 @@ const pagedDetailCargoItems = computed(() => {
|
||||
})
|
||||
const progressSummaryItems = computed(() => {
|
||||
const order = detailOrder.value
|
||||
if (!order) return []
|
||||
if (!order || order.status === 'CANCELLED') return []
|
||||
const inbound = inboundBilling.value?.inbound.summary
|
||||
const summary = order.businessSummary
|
||||
const formatMetric = (value: number | null | undefined, unit = '') => value == null ? '待更新' : `${value.toLocaleString()}${unit ? ` ${unit}` : ''}`
|
||||
@@ -572,7 +623,7 @@ const progressSummaryItems = computed(() => {
|
||||
const cabinetProgressItems = computed(() => {
|
||||
const summary = detailOrder.value?.businessSummary
|
||||
if (!summary || (!summary.cabinetNo && !summary.containerNo)) return []
|
||||
return [{ cabinetId: summary.cabinetNo || summary.containerNo, cabinetNo: summary.cabinetNo || summary.containerNo, status: summary.loadingStatus || '待更新', vesselName: summary.vesselName, voyageNo: summary.voyageNo, estimatedSailingAt: summary.estimatedSailingAt }]
|
||||
return [{ cabinetId: summary.cabinetNo || summary.containerNo, cabinetNo: summary.cabinetNo || summary.containerNo, pickingStatusLabel: getFirstLegPickingStatusLabel(summary.loadingStatus), vesselName: summary.vesselName, voyageNo: summary.voyageNo, estimatedSailingAt: summary.estimatedSailingAt }]
|
||||
})
|
||||
const selectedWarehouse = computed(() => availableWarehouses.value.find((item) => item.id === form.receivingWarehouseId))
|
||||
const selectedDestinationWarehouse = computed(() => store.warehouses.find((item) => item.id === form.destinationWarehouseId && item.warehouseType === form.destinationType))
|
||||
@@ -582,7 +633,13 @@ const hasActiveFilters = computed(() => {
|
||||
const values = appliedFilters.value
|
||||
return Object.values(values).some((value) => Array.isArray(value) ? value.length > 0 : Boolean(typeof value === 'string' ? value.trim() : value))
|
||||
})
|
||||
const emptyDescription = computed(() => hasActiveFilters.value ? '没有符合筛选条件的订单' : '还没有订单')
|
||||
const emptyDescription = computed(() => {
|
||||
if (hasActiveFilters.value) return '没有符合筛选条件的订单'
|
||||
if (activeOrderQueue.value === 'customs') return '暂无需要上传报关资料的订单'
|
||||
if (activeOrderQueue.value === 'fee') return '暂无需要确认计费重的订单'
|
||||
if (activeOrderQueue.value === 'draft') return '暂无草稿订单'
|
||||
return '还没有订单'
|
||||
})
|
||||
|
||||
async function loadPageData() {
|
||||
supportingDataLoading.value = true
|
||||
@@ -596,7 +653,7 @@ async function loadPageData() {
|
||||
: Promise.resolve()
|
||||
const orderPageRequest = isCreatePage.value || isDetailPage.value
|
||||
? store.loadWarehouseType('DOMESTIC', true)
|
||||
: store.load({ includeDrafts: true })
|
||||
: loadOrderPage()
|
||||
const addressRequest = isCreatePage.value ? loadOrderAddresses() : Promise.resolve()
|
||||
const [ordersResult, companyResult, destinationResult, policyResult, addressResult] = await Promise.allSettled([
|
||||
orderPageRequest,
|
||||
@@ -617,7 +674,6 @@ async function loadPageData() {
|
||||
}
|
||||
if (!isCreatePage.value && ordersResult.status === 'rejected' && !store.loadError) supportingDataErrors.value.push(`订单加载失败:${errorMessage(ordersResult.reason)}`)
|
||||
if (store.warehouseLoadError) supportingDataErrors.value.push(`公共仓库加载失败:${store.warehouseLoadError}`)
|
||||
if (!isCreatePage.value && store.draftLoadError) supportingDataErrors.value.push(`订单草稿加载失败:${store.draftLoadError}`)
|
||||
if (destinationResult.status === 'rejected') supportingDataErrors.value.push(`目的仓加载失败:${errorMessage(destinationResult.reason)}`)
|
||||
if (addressResult.status === 'rejected') supportingDataErrors.value.push(`企业地址簿加载失败:${errorMessage(addressResult.reason)}`)
|
||||
await autofillWarehouseSelections()
|
||||
@@ -633,6 +689,7 @@ async function loadRouteDraft(id: string) {
|
||||
const draft = draftFromOrder(detailedOrder)
|
||||
if (draft.destinationType !== 'PRIVATE') await loadDestinationWarehouses(draft.destinationType)
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (form.receivingWarehouseId) await loadSelectedWarehouse(form.receivingWarehouseId)
|
||||
@@ -1299,6 +1356,9 @@ function getOrderRowActions(row: object): TableAction[] {
|
||||
if (canEditOrder.value && canClientEditFirstLegOrder(order.status)) {
|
||||
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
|
||||
}
|
||||
if (canOfferCancellation(order)) {
|
||||
actions.push({ key: 'cancel', label: pendingCancellation.value?.id === order.id ? '重试取消' : '取消订单', loading: cancellingOrderId.value === order.id, disabled: Boolean(cancellingOrderId.value), run: () => cancelOrder(order) })
|
||||
}
|
||||
if (eligibleCustomsDetail(order)) {
|
||||
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
|
||||
}
|
||||
@@ -1361,6 +1421,7 @@ async function openEdit(order: FirstLegOrder) {
|
||||
}
|
||||
}
|
||||
editingId.value = detailedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||
replaceForm(draft)
|
||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||
if (warehouseAvailable) void loadSelectedWarehouse(detailedOrder.receivingWarehouseId)
|
||||
@@ -1385,7 +1446,8 @@ async function loadDetailPage(orderId: string) {
|
||||
detailError.value = ''
|
||||
try {
|
||||
const detailedOrder = await store.loadDetail(orderId)
|
||||
void loadInboundBilling(detailedOrder)
|
||||
if (detailedOrder.status === 'CANCELLED') resetInboundBillingState()
|
||||
else void loadInboundBilling(detailedOrder)
|
||||
// Load previews from the persisted file IDs after the store has replaced the detail row.
|
||||
await Promise.all((detailOrder.value?.items ?? detailedOrder.items).map(ensureProductImagePreview))
|
||||
} catch (error) {
|
||||
@@ -1466,6 +1528,7 @@ async function retryInboundBilling() {
|
||||
}
|
||||
|
||||
function handleInboundFeeConfirmed() {
|
||||
if (!isCreatePage.value && !isDetailPage.value) void loadOrderPage()
|
||||
if (!feeConfirmationOpen.value) void retryInboundBilling()
|
||||
}
|
||||
|
||||
@@ -1677,14 +1740,14 @@ function handleOrderSelectionChange(rows: FirstLegOrder[]) {
|
||||
}
|
||||
|
||||
async function submitSelectedDraftOrders() {
|
||||
const drafts = selectedDraftOrders.value
|
||||
if (batchSubmitting.value || !drafts.length) return
|
||||
const ids = [...new Set([...pendingBatchSubmissionIds.value, ...selectedDraftOrders.value.map(order => order.id)])]
|
||||
if (batchSubmitting.value || !ids.length) return
|
||||
if (companySubmissionBlocked.value) {
|
||||
ElMessage.warning('企业资料审核通过后才能提交订单')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认提交选中的 ${drafts.length} 条草稿订单吗?`, '批量提交订单', {
|
||||
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?${pendingBatchSubmissionIds.value.length ? '上次结果未确认的订单将使用原提交命令重试。' : ''}`, '批量提交订单', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '确认提交',
|
||||
cancelButtonText: '取消',
|
||||
@@ -1696,10 +1759,8 @@ async function submitSelectedDraftOrders() {
|
||||
|
||||
batchSubmitting.value = true
|
||||
try {
|
||||
const results = await Promise.allSettled(drafts.map((order) => submitMerchantFirstLegOrder(
|
||||
order.id,
|
||||
createIdempotencyKey(`first-leg-batch-submit-${order.id}`),
|
||||
)))
|
||||
const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined)))
|
||||
pendingBatchSubmissionIds.value = ids.filter((id, index) => results[index]?.status === 'rejected' && store.hasPendingSubmission(id))
|
||||
const successCount = results.filter((result) => result.status === 'fulfilled').length
|
||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
||||
await searchOrders(appliedFilters.value)
|
||||
@@ -1893,7 +1954,7 @@ async function submitBatchImport() {
|
||||
batchImportIdempotencyKey.value,
|
||||
)
|
||||
const result = batchImportResult.value.result
|
||||
if (result.succeeded && auth.hasPermission('order:first-leg:list')) await store.load({ includeDrafts: true })
|
||||
if (result.succeeded && auth.hasPermission('order:first-leg:list')) await loadOrderPage()
|
||||
if (result.failed) ElMessage.warning(`导入完成:成功 ${result.succeeded} 条,失败 ${result.failed} 条`)
|
||||
else ElMessage.success(`已成功导入 ${result.succeeded} 条订单草稿`)
|
||||
} catch (error) {
|
||||
@@ -1951,8 +2012,10 @@ async function saveDraft() {
|
||||
if (!await validateEditorForm()) return
|
||||
saving.value = true
|
||||
try {
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
if (!await confirmSubmissionEdit()) return
|
||||
const order = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = order.id
|
||||
editingSession.value = store.beginDraftEdit(order)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
if (isCreatePage.value) await router.push({ name: 'first-leg-orders' })
|
||||
@@ -1964,6 +2027,20 @@ async function saveDraft() {
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmSubmissionEdit() {
|
||||
if (!editingId.value || !store.hasPendingSubmission(editingId.value)) return true
|
||||
try {
|
||||
await ElMessageBox.confirm('上次提交结果尚未确认。确认重新读取订单并按当前表单重新编辑吗?只有服务端仍为草稿时才能开始新的提交决定。', '重新编辑订单', {
|
||||
type: 'warning', center: true, confirmButtonText: '确认重新编辑', cancelButtonText: '返回',
|
||||
})
|
||||
} catch (error) {
|
||||
if (error === 'cancel' || error === 'close') return false
|
||||
throw error
|
||||
}
|
||||
editingSession.value = await store.beginNewSubmissionEdit(editingId.value)
|
||||
return true
|
||||
}
|
||||
|
||||
async function submitOrder() {
|
||||
if (saving.value) return
|
||||
if (companySubmissionBlocked.value) {
|
||||
@@ -1982,13 +2059,16 @@ async function submitOrder() {
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!await validateEditorForm()) return
|
||||
const retry = store.isSubmissionRetry(editingId.value, cloneDraft(form))
|
||||
if (!retry && !await validateEditorForm()) return
|
||||
|
||||
try {
|
||||
saving.value = true
|
||||
if (!retry && !await confirmSubmissionEdit()) return
|
||||
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
|
||||
const savedOrder = await store.saveDraft(cloneDraft(form), tenantStore.company.companyName, editingId.value)
|
||||
const savedOrder = await store.saveDraftForSubmission(cloneDraft(form), tenantStore.company.companyName, editingId.value, editingSession.value)
|
||||
editingId.value = savedOrder.id
|
||||
editingSession.value = store.beginDraftEdit(savedOrder)
|
||||
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
|
||||
markEditorClean()
|
||||
editorOpen.value = false
|
||||
@@ -2008,37 +2088,13 @@ async function submitOrder() {
|
||||
}
|
||||
|
||||
async function searchOrders(model: QueryModel) {
|
||||
const createdRange = model.createdRange
|
||||
appliedFilters.value = {
|
||||
...model,
|
||||
createdRange: Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||
appliedFilters.value = { ...model,
|
||||
createdRange: Array.isArray(model.createdRange) ? model.createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||
}
|
||||
tablePage.value = 1
|
||||
try {
|
||||
const statusValue = typeof model.status === 'string' ? model.status as FirstLegOrderStatus | '' : ''
|
||||
const cargoKeyword = typeof model.cargoKeyword === 'string' ? model.cargoKeyword.trim() : ''
|
||||
const range = Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : []
|
||||
const query = {
|
||||
keyword: undefined,
|
||||
inboundCode: cargoKeyword || undefined,
|
||||
receivingWarehouseId: typeof model.receivingWarehouseId === 'string' && model.receivingWarehouseId ? model.receivingWarehouseId : undefined,
|
||||
mainStatus: statusValue && statusValue !== 'DRAFT' ? statusValue : undefined,
|
||||
draftOnly: statusValue === 'DRAFT',
|
||||
includeDrafts: !statusValue,
|
||||
createdFrom: range[0] ? `${range[0]}T00:00:00` : undefined,
|
||||
createdTo: range[1] ? `${range[1]}T23:59:59` : undefined,
|
||||
}
|
||||
await store.load(query)
|
||||
const cargoMatched = cargoKeyword && store.orders.some((order) => order.status !== 'DRAFT' && orderMatchesCargoKeyword(order, cargoKeyword))
|
||||
if (cargoKeyword && !cargoMatched && statusValue !== 'DRAFT') {
|
||||
await store.load({ ...query, keyword: undefined, inboundCode: undefined, fbaCode: cargoKeyword })
|
||||
}
|
||||
selectedOrders.value = []
|
||||
orderTableVersion.value += 1
|
||||
} catch {
|
||||
// Store keeps the recoverable error state rendered below the query toolbar.
|
||||
}
|
||||
await loadOrderPage()
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -2047,7 +2103,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" />
|
||||
|
||||
<div class="client-card order-table-card">
|
||||
<DataTable v-model:page="tablePage" v-model:page-size="tablePageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="filteredOrders.length" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange">
|
||||
<DataTable :page="tablePage" :page-size="tablePageSize" @update:page="changeOrderPage" @update:page-size="changeOrderPageSize" :data="pagedOrders" :columns="visibleOrderColumns" :key="orderTableVersion" :loading="store.loading" :total="store.total" :page-sizes="[10, 20, 50]" row-key="id" empty-text="暂无订单" class="prototype-order-table" :row-actions="getOrderRowActions" @selection-change="handleOrderSelectionChange">
|
||||
<template #toolbar>
|
||||
<nav class="order-queue-tabs" aria-label="订单事项分类">
|
||||
<button type="button" :class="{ active: activeOrderQueue === 'all' }" @click="selectOrderQueue('all')">全部</button>
|
||||
@@ -2086,7 +2142,7 @@ async function searchOrders(model: QueryModel) {
|
||||
</el-popover>
|
||||
<el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button>
|
||||
<el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button>
|
||||
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="selectedDraftOrders.length === 0 || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />批量提交草稿</el-button>
|
||||
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="(selectedDraftOrders.length === 0 && pendingBatchSubmissionIds.length === 0) || companySubmissionBlocked" @click="submitSelectedDraftOrders"><Send :size="17" />{{ pendingBatchSubmissionIds.length ? '重试批量提交' : '批量提交草稿' }}</el-button>
|
||||
<el-button v-if="auth.hasPermission('order:first-leg:create')" @click="openBatchImport"><Upload :size="17" />批量导入订单</el-button>
|
||||
<el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button>
|
||||
|
||||
@@ -2349,16 +2405,16 @@ async function searchOrders(model: QueryModel) {
|
||||
<div class="order-detail-heading">
|
||||
<div class="detail-heading-main">
|
||||
<el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button>
|
||||
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div>
|
||||
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === 'CANCELLED' ? (detailOrder.orderNo || '—') : detailOrder.status === 'DRAFT' ? '入仓码提交后生成' : '入仓码待生成') }}</h2><p v-if="detailOrder.status === 'CANCELLED'">订单已取消。</p><p v-else>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }} · {{ detailOrder.origin || '起运地待更新' }} → {{ detailOrder.destination || '目的地待更新' }}</p></div>
|
||||
</div>
|
||||
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button></div>
|
||||
<div class="detail-heading-actions"><el-tag :type="getFirstLegStatusTone(detailOrder.status)" effect="light">{{ getFirstLegStatusLabel(detailOrder.status) }}</el-tag><el-button v-if="canEditOrder && canClientEditFirstLegOrder(detailOrder.status)" type="primary" plain :loading="openingEditor" @click="openEdit(detailOrder)"><Pencil :size="16" />编辑草稿</el-button><el-button v-if="canOfferCancellation(detailOrder)" type="danger" plain :loading="cancellingOrderId === detailOrder.id" :disabled="!!cancellingOrderId" @click="cancelOrder(detailOrder)">{{ pendingCancellation?.id === detailOrder.id ? '重试取消' : '取消订单' }}</el-button></div>
|
||||
</div>
|
||||
<section class="detail-section">
|
||||
<h3>订单与运输</h3>
|
||||
<dl class="order-detail-grid">
|
||||
<div><dt>入仓码</dt><dd><button v-if="detailOrder.businessSummary.inboundCode" class="inbound-code-link table-code" type="button" @click="openInboundCodeAssociation(detailOrder.businessSummary.inboundCode)">{{ detailOrder.businessSummary.inboundCode }}</button><span v-else>{{ detailOrder.status === 'DRAFT' ? '提交后生成' : '待生成' }}</span></dd></div>
|
||||
<div><dt>入仓码</dt><dd><button v-if="detailOrder.businessSummary.inboundCode" class="inbound-code-link table-code" type="button" @click="openInboundCodeAssociation(detailOrder.businessSummary.inboundCode)">{{ detailOrder.businessSummary.inboundCode }}</button><span v-else>{{ detailOrder.status === 'CANCELLED' ? '—' : detailOrder.status === 'DRAFT' ? '提交后生成' : '待生成' }}</span></dd></div>
|
||||
<div><dt>创建时间</dt><dd>{{ formatDateTime(detailOrder.createdAt) }}</dd></div>
|
||||
<div><dt>运输方式</dt><dd>{{ getFirstLegTransportModeLabel(detailOrder.transportMode) }}</dd></div>
|
||||
<div><dt>运输方式</dt><dd>{{ detailOrder.status === 'CANCELLED' && !detailOrder.transportMode ? '—' : getFirstLegTransportModeLabel(detailOrder.transportMode) }}</dd></div>
|
||||
<div><dt>贸易条款</dt><dd>{{ displayValue(detailOrder.tradeTerm) }}</dd></div>
|
||||
<div><dt>发货方式</dt><dd>{{ pickupMethodLabels[detailOrder.pickupMethod] }}</dd></div>
|
||||
<div><dt>预约提货时间</dt><dd>{{ detailOrder.pickupMethod === 'PICKUP' && detailOrder.requestedPickupAt ? formatDateTime(detailOrder.requestedPickupAt) : '-' }}</dd></div>
|
||||
@@ -2383,7 +2439,7 @@ async function searchOrders(model: QueryModel) {
|
||||
</dl>
|
||||
<div v-if="detailOrder.customerRemark" class="customer-remark"><strong>客户备注</strong><p>{{ detailOrder.customerRemark }}</p></div>
|
||||
</section>
|
||||
<section v-if="detailOrder.status !== 'DRAFT'" class="detail-section">
|
||||
<section v-if="detailOrder.status !== 'DRAFT' && detailOrder.status !== 'CANCELLED'" class="detail-section">
|
||||
<h3>关键业务摘要</h3>
|
||||
<dl class="fulfillment-summary">
|
||||
<div v-for="item in progressSummaryItems" :key="item.label"><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>
|
||||
@@ -2397,15 +2453,16 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-table-column prop="cabinetNo" label="柜号 / 柜次" min-width="150"><template #default="{ row }"><span class="table-code">{{ row.cabinetNo || '—' }}</span></template></el-table-column>
|
||||
<el-table-column label="船名 / 航次" min-width="180"><template #default="{ row }">{{ [row.vesselName, row.voyageNo].filter(Boolean).join(' · ') || '待更新' }}</template></el-table-column>
|
||||
<el-table-column label="预计船期" width="170"><template #default="{ row }">{{ row.estimatedSailingAt ? formatDateTime(row.estimatedSailingAt) : '待更新' }}</template></el-table-column>
|
||||
<el-table-column prop="status" label="当前节点" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.status || '待更新' }}</el-tag></template></el-table-column>
|
||||
<el-table-column prop="pickingStatusLabel" label="拣货状态" width="120"><template #default="{ row }"><el-tag size="small" effect="plain">{{ row.pickingStatusLabel }}</el-tag></template></el-table-column>
|
||||
</el-table>
|
||||
<p v-else class="detail-inline-empty">尚未分配柜次,后续柜次节点将在这里同步。</p>
|
||||
<TransportFactsTable :fragments="detailOrder.businessSummary.transportFragments" />
|
||||
</div>
|
||||
</template>
|
||||
</OrderProgressPanel>
|
||||
<section class="detail-section">
|
||||
<section v-if="detailOrder.status !== 'CANCELLED' || detailOrder.expressCompanyName || detailOrder.trackingNumber" class="detail-section">
|
||||
<h3>履约快递信息</h3>
|
||||
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || '待平台补充' }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || '待平台补充' }}</dd></div></dl>
|
||||
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div><div><dt>快递单号</dt><dd class="table-code">{{ detailOrder.trackingNumber || (detailOrder.status === 'CANCELLED' ? '—' : '待平台补充') }}</dd></div></dl>
|
||||
<div v-else class="express-empty"><PackageCheck :size="20" /><div><strong>平台尚未维护快递信息</strong><span>快递公司和快递单号由平台后台维护,客户端仅只读展示。</span></div></div>
|
||||
</section>
|
||||
<section class="detail-section">
|
||||
@@ -2455,6 +2512,7 @@ async function searchOrders(model: QueryModel) {
|
||||
<el-empty v-else description="暂无货物明细" :image-size="56" />
|
||||
</section>
|
||||
<InboundBillingPanel
|
||||
v-if="detailOrder.status !== 'CANCELLED'"
|
||||
:data="inboundBilling"
|
||||
:loading="inboundBillingLoading"
|
||||
:unavailable="inboundBillingUnavailable"
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { ref } from 'vue'
|
||||
import ts from 'typescript'
|
||||
|
||||
const source = readFileSync(new URL('./FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||
const names = ['loadOrderPage', 'changeOrderPage', 'changeOrderPageSize', 'selectOrderQueue', 'searchOrders']
|
||||
const functions = ast.statements.filter(n => ts.isFunctionDeclaration(n) && names.includes(n.name?.text)).map(n => n.getText(ast)).join('\n')
|
||||
const code = ts.transpileModule('let orderPageRequestVersion = 0;\n' + functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
function harness() {
|
||||
const calls = []
|
||||
const values = {
|
||||
tablePage: ref(1), tablePageSize: ref(10), activeOrderQueue: ref('all'), appliedFilters: ref({}),
|
||||
selectedOrders: ref(['previous']), orderTableVersion: ref(0),
|
||||
store: { total: 215, loadError: '', load: async q => { calls.push(q) } },
|
||||
}
|
||||
const handlers = new Function(...Object.keys(values), code + ';return {' + names.join(',') + '}')(...Object.values(values))
|
||||
return { ...values, ...handlers, calls }
|
||||
}
|
||||
test('page events request server pages; size, queue and search reset to the first page', async () => {
|
||||
const h = harness()
|
||||
await h.changeOrderPage(21); assert.equal(h.calls.at(-1).page, 21)
|
||||
await h.changeOrderPageSize(50); assert.equal(h.calls.at(-1).page, 1); assert.equal(h.calls.at(-1).size, 50)
|
||||
await h.selectOrderQueue('customs'); assert.equal(h.calls.at(-1).queue, 'customs'); assert.equal(h.tablePage.value, 1)
|
||||
await h.searchOrders({ cargoKeyword: ' SKU ', status: 'DRAFT', createdRange: ['2026-10-01', '2026-10-03'] })
|
||||
assert.equal(h.calls.at(-1).cargoKeyword, 'SKU'); assert.equal(h.calls.at(-1).mainStatus, 'DRAFT')
|
||||
assert.equal(h.calls.at(-1).createdFrom, '2026-10-01T00:00:00')
|
||||
assert.equal(h.calls.at(-1).createdTo, '2026-10-03T23:59:59.999')
|
||||
assert.deepEqual(h.selectedOrders.value, [])
|
||||
})
|
||||
test('deletion on the last page clamps and reloads once; failed reads retain the requested page for retry', async () => {
|
||||
const h = harness(); h.store.total = 200
|
||||
await h.changeOrderPage(22)
|
||||
assert.deepEqual(h.calls.map(q => q.page), [22, 20]); assert.equal(h.tablePage.value, 20)
|
||||
h.store.total = 0; h.store.loadError = 'failed'
|
||||
await h.changeOrderPage(22)
|
||||
assert.equal(h.tablePage.value, 22); assert.equal(h.calls.length, 3)
|
||||
})
|
||||
test('old same-page response cannot clamp a newer query or clear its current selection', async () => {
|
||||
const h = harness(); let release
|
||||
h.store.load = () => new Promise(resolve => { release = resolve })
|
||||
const first = h.loadOrderPage(); const oldRelease = release
|
||||
const second = h.searchOrders({ cargoKeyword: 'new' })
|
||||
h.store.total = 215; release(); await second
|
||||
h.selectedOrders.value = ['new-selection']
|
||||
oldRelease(); await first
|
||||
assert.deepEqual(h.selectedOrders.value, ['new-selection'])
|
||||
assert.equal(h.orderTableVersion.value, 1)
|
||||
})
|
||||
@@ -70,7 +70,7 @@ async function placeOrder(channelCode: string, channelName: string) {
|
||||
},
|
||||
})
|
||||
}
|
||||
watch(originWarehouseId, () => { void loadChannels() }); onMounted(() => { void loadBase() })
|
||||
watch(originWarehouseId, (value, previous) => { if (!value || previous === '') return; void loadChannels() }); onMounted(() => { void loadBase() })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
|
||||
const firstLeg = readFileSync(new URL('./FirstLegOrdersView.vue', import.meta.url), 'utf8')
|
||||
const quickOrder = readFileSync(new URL('./QuickOrderView.vue', import.meta.url), 'utf8')
|
||||
@@ -18,7 +20,22 @@ test('uses business identifiers and names without visible internal-ID fallbacks'
|
||||
assert.doesNotMatch(quickOrder, />\{\{ result\.orderNo/)
|
||||
assert.doesNotMatch(customs, /detail\.planNo \|\| detail\.loadingPlanId/)
|
||||
assert.doesNotMatch(overseas, /overseasWarehouseName \|\| (?:item|candidate)\.overseasWarehouseId/)
|
||||
assert.doesNotMatch(overseas, /row\(\[[^\]]*(?:item\.overseasWarehouseId|item\.operatingWarehouseId)/)
|
||||
// Warehouse IDs may be inputs to a resolver, but must never be raw cells.
|
||||
assert.doesNotMatch(overseas, /row\(\[[^\]]*[,[]\s*item\.(?:overseasWarehouseId|operatingWarehouseId)\s*[,\]]/)
|
||||
})
|
||||
|
||||
test('warehouse labels never fall back to unknown internal IDs', () => {
|
||||
const source = overseas.slice(overseas.indexOf('function warehouseDisplay('), overseas.indexOf('function statusLabel('))
|
||||
const javascript = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const display = runInNewContext(`${javascript}; warehouseDisplay`, {
|
||||
operationWarehouses: { value: [{ id: '1234567890123456789', warehouseCode: 'LAX', warehouseName: '洛杉矶仓' }] },
|
||||
fbaWarehouses: { value: [] }, warehouseLabel: (warehouse) => warehouse.warehouseName,
|
||||
})
|
||||
assert.equal(display('1234567890123456789'), '洛杉矶仓')
|
||||
assert.equal(display('LAX'), '洛杉矶仓')
|
||||
assert.equal(display('9999999999999999999'), '—')
|
||||
assert.equal(display('1234567890123456789,9999999999999999999'), '洛杉矶仓、—')
|
||||
assert.equal(display(undefined), '—')
|
||||
})
|
||||
|
||||
test('keeps internal IDs only as non-rendered routing, selection, and request values', () => {
|
||||
|
||||
@@ -1,4 +1,31 @@
|
||||
import { overseasApiRequest } from '@/api/overseasHttp'
|
||||
import { apiBlobRequest, apiRequest } from '@/api/http'
|
||||
|
||||
export interface DeliveryReceiptFile {
|
||||
fileId: string
|
||||
fileName: string
|
||||
contentType: string | null
|
||||
sizeBytes: number
|
||||
uploadedAt: string
|
||||
}
|
||||
|
||||
export interface DeliveryReceipts {
|
||||
deliveryNo: string
|
||||
files: DeliveryReceiptFile[]
|
||||
}
|
||||
|
||||
export function getDeliveryReceipts(deliveryNo: string) {
|
||||
return apiRequest<DeliveryReceipts>({
|
||||
method: 'GET',
|
||||
url: `/merchant/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}/documents/receipt`,
|
||||
})
|
||||
}
|
||||
|
||||
export function downloadDeliveryReceipt(deliveryNo: string, fileId: string) {
|
||||
return apiBlobRequest({
|
||||
method: 'GET',
|
||||
url: `/merchant/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}/documents/receipt/files/${encodeURIComponent(fileId)}/download`,
|
||||
})
|
||||
}
|
||||
|
||||
export interface PageResult<T> {
|
||||
records: T[]
|
||||
@@ -22,6 +49,7 @@ export interface DeliveryRow {
|
||||
driverName: string | null
|
||||
palletCount: number
|
||||
packageCount: number
|
||||
signedPackages: number | null
|
||||
totalWeightKg: number | null
|
||||
totalVolumeCbm: number | null
|
||||
plannedDeliveryAt: string
|
||||
@@ -133,7 +161,7 @@ export interface DeliveryTransferPayload {
|
||||
}
|
||||
|
||||
export function listDeliveryOrders(params: DeliveryQuery) {
|
||||
return overseasApiRequest<PageResult<DeliveryRow>>({
|
||||
return apiRequest<PageResult<DeliveryRow>>({
|
||||
method: 'GET',
|
||||
url: '/merchant/v1/last-leg/delivery-orders',
|
||||
params,
|
||||
@@ -141,7 +169,7 @@ export function listDeliveryOrders(params: DeliveryQuery) {
|
||||
}
|
||||
|
||||
export function getDeliveryOrder(deliveryNo: string) {
|
||||
return overseasApiRequest<DeliveryOrderDetailResponse>({
|
||||
return apiRequest<DeliveryOrderDetailResponse>({
|
||||
method: 'GET',
|
||||
url: `/merchant/v1/last-leg/delivery-orders/${encodeURIComponent(deliveryNo)}`,
|
||||
params: { page: 1, size: 200 },
|
||||
@@ -154,7 +182,7 @@ export function getDeliveryOrder(deliveryNo: string) {
|
||||
|
||||
export function createDeliveryOrder(payload: DeliveryTransferPayload) {
|
||||
const { dispatchNo, ...request } = payload
|
||||
return overseasApiRequest<DeliveryTransferResult>({
|
||||
return apiRequest<DeliveryTransferResult>({
|
||||
method: 'POST',
|
||||
url: '/merchant/v1/last-leg/delivery-orders',
|
||||
params: { dispatchNo },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { overseasApiRequest } from '@/api/overseasHttp'
|
||||
import { apiRequest } from '@/api/http'
|
||||
|
||||
export interface PageResult<T> { records: T[]; page: number; size: number; total: number; pages: number }
|
||||
export interface InboundPlanQuery {
|
||||
@@ -66,10 +66,10 @@ export interface InboundPlanDetail {
|
||||
}
|
||||
|
||||
export async function listInboundPlans(params: InboundPlanQuery) {
|
||||
const result = await overseasApiRequest<PageResult<InboundPlanSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/inbound-plans', params })
|
||||
const result = await apiRequest<PageResult<InboundPlanSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/inbound-plans', params })
|
||||
return { ...result, page: Number(result.page), size: Number(result.size), total: Number(result.total), pages: Number(result.pages) }
|
||||
}
|
||||
|
||||
export function getInboundPlan(planNo: string) {
|
||||
return overseasApiRequest<InboundPlanDetail>({ method: 'GET', url: `/merchant/v1/last-leg/inbound-plans/${encodeURIComponent(planNo)}` })
|
||||
return apiRequest<InboundPlanDetail>({ method: 'GET', url: `/merchant/v1/last-leg/inbound-plans/${encodeURIComponent(planNo)}` })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
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 dayjs from 'dayjs'
|
||||
|
||||
function harness(t) {
|
||||
const source = readFileSync(new URL('./views/DeliveryOrdersView.vue', import.meta.url), 'utf8')
|
||||
.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
const code = ts.transpileModule(source + '\nexport { filters, queryFields, tableColumns, page, pageSize, search, reset, loadOrders, records, total, loading, errorMessage }', {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true },
|
||||
}).outputText
|
||||
const calls = [], mounted = []
|
||||
const dependencies = {
|
||||
vue: { ...vue, onMounted: callback => mounted.push(callback) }, dayjs,
|
||||
'vue-router': { useRouter: () => ({ push() {} }) },
|
||||
'@/modules/auth/public': { useAuthStore: () => ({ hasPermission: () => true }) },
|
||||
'../api/deliveryOrders': { listDeliveryOrders: query => new Promise((resolve, reject) => calls.push({ query, resolve, reject })) },
|
||||
}
|
||||
const scope = vue.effectScope(), view = {}
|
||||
scope.run(() => new Function('require', 'exports', code)(id => {
|
||||
assert.ok(id in dependencies, id)
|
||||
return dependencies[id]
|
||||
}, view))
|
||||
t.after(() => scope.stop())
|
||||
return { view, calls, mount: () => mounted.forEach(fn => fn()) }
|
||||
}
|
||||
const result = name => ({ records: [{ deliveryNo: name }], total: 1 })
|
||||
|
||||
test('formal delivery filters submit exact values and format each known method in Chinese', async t => {
|
||||
const { view, calls } = harness(t)
|
||||
const expected = { FBA_PICKUP: 'FBA 自提', CUSTOMER_PICKUP: '客户自提', TRUCK_PALLET: '卡派打托', TRUCK_FLOOR: '卡派地板', EXPRESS: '快递', OUTSOURCED: '外配', DEDICATED_TRUCK: '专车直送', LTL: '零担派送', TRUCK: '卡车派送' }
|
||||
const options = view.queryFields.find(f => f.key === 'deliveryMethod').options
|
||||
assert.deepEqual(Object.fromEntries(options.map(o => [o.value, o.label])), expected)
|
||||
const column = view.tableColumns.find(c => c.prop === 'deliveryMethod')
|
||||
for (const [value, label] of Object.entries(expected)) {
|
||||
view.filters.deliveryMethod = value
|
||||
const pending = view.loadOrders()
|
||||
assert.equal(calls.at(-1).query.deliveryMethod, value)
|
||||
calls.at(-1).resolve(result(value)); await pending
|
||||
assert.equal(column.formatter({}, {}, value), label)
|
||||
}
|
||||
assert.equal(column.formatter({}, {}, null), '—')
|
||||
})
|
||||
|
||||
test('newest result survives older success and older failure', async t => {
|
||||
for (const oldFailure of [false, true]) {
|
||||
const { view, calls } = harness(t)
|
||||
view.filters.documentNo = 'old'; const old = view.loadOrders()
|
||||
view.filters.documentNo = 'new'; const current = view.loadOrders()
|
||||
calls[1].resolve(result('new')); await current
|
||||
if (oldFailure) calls[0].reject(new Error('old failed'))
|
||||
else calls[0].resolve(result('old'))
|
||||
await old
|
||||
assert.equal(view.records.value[0].deliveryNo, 'new')
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
assert.equal(view.total.value, 1)
|
||||
assert.equal(calls.length, 2)
|
||||
}
|
||||
})
|
||||
|
||||
test('older completion cannot clear current loading; current failure can be retried', async t => {
|
||||
const { view, calls } = harness(t)
|
||||
const old = view.loadOrders(), current = view.loadOrders()
|
||||
calls[0].resolve(result('old')); await old
|
||||
assert.equal(view.loading.value, true)
|
||||
assert.equal(view.records.value.length, 0)
|
||||
calls[1].reject(new Error('current failed')); await current
|
||||
assert.equal(view.loading.value, false)
|
||||
assert.equal(view.errorMessage.value, 'current failed')
|
||||
const retry = view.loadOrders(); calls[2].resolve(result('retry')); await retry
|
||||
assert.equal(view.records.value[0].deliveryNo, 'retry')
|
||||
assert.equal(view.errorMessage.value, '')
|
||||
})
|
||||
|
||||
test('mount, search from later page, page-size change and reset each issue one request', async t => {
|
||||
const { view, calls, mount } = harness(t)
|
||||
mount(); await vue.nextTick(); assert.equal(calls.length, 1)
|
||||
view.page.value = 3; await vue.nextTick(); assert.equal(calls.length, 2)
|
||||
view.search(); await vue.nextTick(); assert.equal(calls.length, 3)
|
||||
assert.equal(calls[2].query.page, 1)
|
||||
view.page.value = 4; await vue.nextTick(); assert.equal(calls.length, 4)
|
||||
view.pageSize.value = 50; await vue.nextTick(); assert.equal(calls.length, 5)
|
||||
assert.equal(calls[4].query.page, 1); assert.equal(calls[4].query.size, 50)
|
||||
view.reset(); await vue.nextTick(); assert.equal(calls.length, 6)
|
||||
calls.forEach(call => call.resolve(result('resolved')))
|
||||
})
|
||||
@@ -18,22 +18,34 @@ async function importTypeScriptModule(source) {
|
||||
return import(`data:text/javascript;base64,${Buffer.from(compiled).toString('base64')}`)
|
||||
}
|
||||
|
||||
for (const signedPackages of [null, 0, 3]) test(`preserves actual signed quantity ${signedPackages} in merchant list and detail`, async () => {
|
||||
const api = await importTypeScriptModule(apiSource.replace(
|
||||
"import { apiBlobRequest, apiRequest } from '@/api/http'",
|
||||
`const apiBlobRequest = async () => new Blob([])
|
||||
const order = { deliveryNo: 'DL-1', packageCount: 9, signedPackages: ${JSON.stringify(signedPackages)} }
|
||||
const apiRequest = async (config) => config.url.endsWith('/DL-1')
|
||||
? { order, skus: [], fees: [] } : { records: [order], page: 1, size: 20, total: 1, pages: 1 }`,
|
||||
))
|
||||
assert.equal((await api.listDeliveryOrders({ page: 1, size: 20 })).records[0].signedPackages, signedPackages)
|
||||
assert.equal((await api.getDeliveryOrder('DL-1')).signedPackages, signedPackages)
|
||||
})
|
||||
|
||||
test('uses only authenticated merchant delivery endpoints without customer scope or mock fallback', () => {
|
||||
assert.match(apiSource, /method: 'GET'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/)
|
||||
assert.match(apiSource, /delivery-orders\/\$\{encodeURIComponent\(deliveryNo\)\}/)
|
||||
assert.match(apiSource, /method: 'POST'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/)
|
||||
assert.match(apiSource, /const \{ dispatchNo, \.\.\.request \} = payload/)
|
||||
assert.match(apiSource, /params: \{ dispatchNo \}/)
|
||||
assert.match(apiSource, /overseasApiRequest<DeliveryOrderDetailResponse>/)
|
||||
assert.match(apiSource, /apiRequest<DeliveryOrderDetailResponse>/)
|
||||
assert.match(apiSource, /\.then\(\(\{ order, skus, fees \}\) => \(\{[\s\S]*\.\.\.order,[\s\S]*fees,[\s\S]*items: skus/)
|
||||
assert.match(apiSource, /overseasApiRequest<DeliveryTransferResult>/)
|
||||
assert.match(apiSource, /apiRequest<DeliveryTransferResult>/)
|
||||
assert.doesNotMatch(apiSource, /customerId|tenantId|Record<string, unknown>|mock|fallback/i)
|
||||
})
|
||||
|
||||
test('keeps list, read-only detail and create permissions independent in active routes', () => {
|
||||
const listRoute = routesSource.match(/path: 'orders\/delivery',[\s\S]*?\n\s*},/)?.[0] ?? ''
|
||||
assert.match(listRoute, /permission: 'merchant:warehouse:delivery:list'/)
|
||||
assert.doesNotMatch(listRoute, /navigation:/)
|
||||
assert.match(listRoute, /navigation: \{ key: 'orders-delivery', icon: Truck \}/)
|
||||
assert.match(routesSource, /path: 'orders\/delivery\/create'[\s\S]*DeliveryOrderCreateView\.vue[\s\S]*permission: 'merchant:warehouse:delivery:create'/)
|
||||
assert.match(routesSource, /path: 'orders\/delivery\/:deliveryNo'[\s\S]*DeliveryOrderDetailView\.vue[\s\S]*props: true[\s\S]*permission: 'merchant:warehouse:delivery:list'/)
|
||||
assert.match(routesSource, /orders-delivery-create[\s\S]*keepAlive: false/)
|
||||
@@ -72,6 +84,32 @@ test('loads a typed detail route by delivery number and never exposes an interna
|
||||
assert.doesNotMatch(detailSource, /detail\?\.id|deliveryNo \|\| detail\?\.id|customerId|tenantId/)
|
||||
})
|
||||
|
||||
test('receipt list and binary download use the fixed merchant scope without category or revision escape', async () => {
|
||||
const api = await importTypeScriptModule(apiSource.replace(
|
||||
"import { apiBlobRequest, apiRequest } from '@/api/http'",
|
||||
`export const requests = []
|
||||
const apiRequest = async (config) => { requests.push(config); return { deliveryNo: 'DL/1', files: [] } }
|
||||
const apiBlobRequest = async (config) => { requests.push(config); return new Blob(['receipt-bytes']) }`,
|
||||
))
|
||||
assert.deepEqual(await api.getDeliveryReceipts('DL/1'), { deliveryNo: 'DL/1', files: [] })
|
||||
assert.equal(await (await api.downloadDeliveryReceipt('DL/1', '123')).text(), 'receipt-bytes')
|
||||
assert.deepEqual(api.requests, [
|
||||
{ method: 'GET', url: '/merchant/v1/last-leg/delivery-orders/DL%2F1/documents/receipt' },
|
||||
{ method: 'GET', url: '/merchant/v1/last-leg/delivery-orders/DL%2F1/documents/receipt/files/123/download' },
|
||||
])
|
||||
assert.match(detailSource, /empty-text="暂无签收资料"/)
|
||||
assert.match(detailSource, /receiptsError[\s\S]*@click="loadReceipts">重试/)
|
||||
assert.match(detailSource, /:loading="receiptsLoading"/)
|
||||
assert.match(detailSource, /downloadDeliveryReceipt\(props\.deliveryNo, file\.fileId\)/)
|
||||
assert.match(detailSource, /URL\.revokeObjectURL\(url\)/)
|
||||
assert.match(detailSource, /DELIVERING: '派送中'/)
|
||||
for (const status of ['WAIT_DELIVERY', 'DELIVERING', 'DELIVERED', 'REJECTED', 'RETURN_PENDING', 'RETURNED']) {
|
||||
assert.match(listSource, new RegExp(`value: '${status}'`))
|
||||
}
|
||||
assert.doesNotMatch(listSource, /value: '(?:PENDING|IN_TRANSIT|SIGNED)'/)
|
||||
assert.doesNotMatch(detailSource, /el-upload|revisionVersion|documents\/BOL/)
|
||||
})
|
||||
|
||||
test('renders a compact customer-readable delivery detail surface', () => {
|
||||
assert.match(detailSource, /<article class="delivery-detail-surface">/)
|
||||
assert.match(detailSource, /<el-button link type="primary" @click="backToList"><ArrowLeft[^>]*\/>返回列表<\/el-button>/)
|
||||
|
||||
@@ -6,7 +6,7 @@ import { overseasWarehouseLabel } from './inboundPlanDisplay.ts'
|
||||
const api = readFileSync(new URL('./api/inboundPlans.ts', import.meta.url), 'utf8')
|
||||
const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8')
|
||||
const view = readFileSync(new URL('./views/InboundOrdersView.vue', import.meta.url), 'utf8')
|
||||
const overseasHttp = readFileSync(new URL('../../api/overseasHttp.ts', import.meta.url), 'utf8')
|
||||
const overseasHttp = readFileSync(new URL('../../api/http.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('activates the customer-scoped overseas inbound list and detail', () => {
|
||||
assert.match(routes, /path: 'orders\/inbound'[\s\S]*?release: 'active'[\s\S]*?permission: 'merchant:warehouse:inbound:list'/)
|
||||
@@ -48,9 +48,9 @@ test('renders a dash when either formal receiving warehouse field is absent', ()
|
||||
})
|
||||
|
||||
test('preserves overseas API diagnostic metadata without rendering it as a business identifier', () => {
|
||||
assert.match(overseasHttp, /response\.data\.traceId/)
|
||||
assert.match(overseasHttp, /response\.data\.requestId/)
|
||||
assert.match(overseasHttp, /body\.traceId, body\.requestId/)
|
||||
assert.match(overseasHttp, /envelope\.traceId/)
|
||||
assert.match(overseasHttp, /envelope\.requestId/)
|
||||
assert.match(overseasHttp, /body\.traceId/)
|
||||
assert.doesNotMatch(view, /requestId|traceId/)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { readFile, stat } from 'node:fs/promises'
|
||||
import { basename } from 'node:path'
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
// Local-only verification. Expectations must come from this run's uploaded
|
||||
// fixture bytes, not from the downloaded file or a previous Downloads entry.
|
||||
export async function verifyReceiptFile(path, expected, startedAt) {
|
||||
const metadata = await stat(path)
|
||||
const bytes = await readFile(path)
|
||||
const sha256 = createHash('sha256').update(bytes).digest('hex')
|
||||
const checks = {
|
||||
currentRun: metadata.mtimeMs >= startedAt,
|
||||
fileName: basename(path) === expected.fileName,
|
||||
size: bytes.length === expected.sizeBytes,
|
||||
content: sha256 === expected.sha256,
|
||||
}
|
||||
return { passed: Object.values(checks).every(Boolean), checks, sizeBytes: bytes.length, sha256, savedFileName: basename(path) }
|
||||
}
|
||||
|
||||
// Run only inside the approved computer-use session, passing its existing Tab.
|
||||
// This module never connects to a browser, logs in, fetches HTTP or changes data.
|
||||
// Root supplies fresh fixture metadata and logs in through the normal page UI.
|
||||
// Example in cua_repl after reading the skill and selecting the customer tab:
|
||||
// const { acceptReceiptDownload } = await import('<absolute path to this module>')
|
||||
// const result = await acceptReceiptDownload(tab, expected)
|
||||
// expected = { deliveryNo, fileName, sizeBytes, sha256 } from the source fixture.
|
||||
// Save result with the current run ID/version; timeout is BLOCKED, not PASS.
|
||||
export async function acceptReceiptDownload(tab, expected) {
|
||||
if (!expected.deliveryNo || !expected.fileName || !Number.isSafeInteger(expected.sizeBytes)
|
||||
|| expected.sizeBytes < 0 || !/^[a-f0-9]{64}$/.test(expected.sha256)) {
|
||||
throw new Error('Fresh fixture delivery number, filename, byte length and SHA-256 are required')
|
||||
}
|
||||
const snapshot = await tab.playwright.domSnapshot()
|
||||
const heading = tab.playwright.getByRole('heading', { name: expected.deliveryNo, exact: true })
|
||||
if (!(await heading.isVisible())) throw new Error('Open the exact fixture delivery detail first')
|
||||
const row = tab.playwright.getByRole('row').filter({ hasText: expected.fileName })
|
||||
if (await row.count() !== 1) throw new Error('Expected exactly one receipt row')
|
||||
const startedAt = Date.now()
|
||||
const [download, click] = await Promise.allSettled([
|
||||
tab.playwright.waitForEvent('download', { timeoutMs: 20000 }).then(d => d.path({ timeoutMs: 10000 })),
|
||||
row.getByRole('button', { name: '下载', exact: true }).click({ timeoutMs: 15000 }),
|
||||
])
|
||||
const base = { deliveryNo: expected.deliveryNo, fileName: expected.fileName, startedAt,
|
||||
clickCompleted: click.status === 'fulfilled', receiptVisible: snapshot.includes(expected.fileName) }
|
||||
if (click.status !== 'fulfilled' || download.status !== 'fulfilled' || !download.value) {
|
||||
return { ...base, status: 'BLOCKED', reason: 'No completed browser save with a current local path', savedFileVerified: false }
|
||||
}
|
||||
const verification = await verifyReceiptFile(download.value, expected, startedAt)
|
||||
return { ...base, status: verification.passed ? 'PASS' : 'FAIL', verification }
|
||||
}
|
||||
|
||||
// Real isolation companion procedure (root-owned environment run):
|
||||
// 1. A logs in, opens fresh A delivery, runs acceptReceiptDownload; retain result.
|
||||
// 2. Log out via UI, log in as unrelated B, open the same A detail URL.
|
||||
// 3. Require denied detail/no receipt filename/no download control and record DOM.
|
||||
// 4. Root's HTTP suite must independently verify B->A binary endpoint rejection.
|
||||
// A hidden button alone is not server isolation. Do not insert tokens into DOM,
|
||||
// use raw CDP, reuse an old file, or replace missing UI save with HTTP success.
|
||||
// If tool paths have opaque basenames, filename check remains FAIL/unproven;
|
||||
// obtain browser download record plus original saved file through the user.
|
||||
@@ -0,0 +1,190 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import ts from 'typescript'
|
||||
import axios from 'axios'
|
||||
import { ref, computed } from 'vue'
|
||||
import { mkdtemp, writeFile, utimes, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { verifyReceiptFile, acceptReceiptDownload } from './receiptBrowserAcceptance.mjs'
|
||||
|
||||
// Execute production HTTP, API and SFC setup code. Only transport, browser saving
|
||||
// and UI feedback are replaced; this is not a browser/server isolation test.
|
||||
function compile(path, dependencies, globals = {}) {
|
||||
let source = readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||
if (path.endsWith('.vue')) {
|
||||
source = source.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||
+ '\nexport { downloadReceipt, loadReceipts, receiptFiles, downloadingFileId, receiptsError, feeColumns }'
|
||||
}
|
||||
source = source.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', ...Object.keys(globals), code)((id) => {
|
||||
assert.ok(id in dependencies, `Unexpected dependency ${id}`)
|
||||
return dependencies[id]
|
||||
}, exports, ...Object.values(globals))
|
||||
return exports
|
||||
}
|
||||
|
||||
const payload = Buffer.from([0, 255, 13, 10, 128, 1, 2, 3])
|
||||
const file = { fileId: 'file/1', fileName: '签收证明 #1.bin', sizeBytes: payload.length }
|
||||
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex')
|
||||
|
||||
test('delivery detail fee column renders formal fee names without changing unknown values', () => {
|
||||
const { component } = harness()
|
||||
const column = component.feeColumns.find(item => item.prop === 'feeType')
|
||||
for (const [input, expected] of [
|
||||
['DELIVERY_FEE', '派送费'], ['LOADING_FEE', '装车费'], ['APPOINTMENT_FEE', '预约费'],
|
||||
['', '—'], [null, '—'], [undefined, '—'], ['OTHER_FEE', 'OTHER_FEE'], ['特殊服务费', '特殊服务费'],
|
||||
]) assert.equal(column.formatter({}, {}, input), expected)
|
||||
})
|
||||
|
||||
function harness({ token = 'customer-A', rejectDownload, rejectList, pending, clickError } = {}) {
|
||||
const requests = [], saved = [], errors = [], revoked = [], urls = new Map()
|
||||
const http = compile('../../api/http.ts', {
|
||||
axios: { ...axios, create: config => axios.create({ ...config, adapter: async config => {
|
||||
requests.push({ url: config.url, authorization: config.headers.get('Authorization'), responseType: config.responseType })
|
||||
const binary = config.url.endsWith('/download')
|
||||
const status = binary ? rejectDownload : rejectList
|
||||
if (status) {
|
||||
const response = { status, data: new Blob([JSON.stringify({ code: String(status), message: '无权访问签收文件' })], { type: 'application/json' }), headers: {}, config }
|
||||
throw new axios.AxiosError('denied', 'ERR_BAD_REQUEST', config, null, response)
|
||||
}
|
||||
if (binary && pending) await pending
|
||||
return { status: 200, headers: {}, config, data: binary
|
||||
? new Blob([payload], { type: 'application/octet-stream' })
|
||||
: { code: '200', message: '成功', data: { deliveryNo: 'DL/A', files: [file] } } }
|
||||
} }) },
|
||||
'@chongchong/shared': { parseApiJsonResponse: value => value },
|
||||
'@/api/session': { getAccessToken: () => token, accessTokenIdentity: value => value, getRefreshToken: () => '', persistTokenPair() {}, clearSessionTokens() {} },
|
||||
'@/api/errorDetails': compile('../../api/errorDetails.ts', {}),
|
||||
'@/api/types': compile('../../api/types.ts', {}),
|
||||
'@/api/crossTabRefresh': compile('../../api/crossTabRefresh.ts', {}),
|
||||
})
|
||||
const api = compile('./api/deliveryOrders.ts', { '@/api/http': http })
|
||||
const component = compile('./views/DeliveryOrderDetailView.vue', {
|
||||
vue: { ref, computed, onMounted() {} },
|
||||
'vue-router': { useRouter: () => ({ push() {} }) },
|
||||
'element-plus': { ElMessage: { error: message => errors.push(message) } },
|
||||
dayjs: () => {}, '../api/deliveryOrders': api,
|
||||
}, {
|
||||
defineProps: () => ({ deliveryNo: 'DL/A' }),
|
||||
URL: { createObjectURL(blob) { const url = `blob:${urls.size}`; urls.set(url, blob); return url }, revokeObjectURL(url) { revoked.push(url); urls.delete(url) } },
|
||||
document: { createElement(tag) {
|
||||
assert.equal(tag, 'a')
|
||||
return { href: '', download: '', click() {
|
||||
if (clickError) throw clickError
|
||||
assert.ok(urls.has(this.href), 'blob must still exist when saving is requested')
|
||||
saved.push({ fileName: this.download, blob: urls.get(this.href) })
|
||||
} }
|
||||
} },
|
||||
})
|
||||
return { component, requests, saved, errors, revoked, urls }
|
||||
}
|
||||
|
||||
test('C63 real handler passes exact binary bytes and Unicode filename to browser save', async () => {
|
||||
const h = harness()
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.saved.length, 1)
|
||||
assert.equal(h.saved[0].fileName, file.fileName)
|
||||
const bytes = Buffer.from(await h.saved[0].blob.arrayBuffer())
|
||||
assert.deepEqual(bytes, payload)
|
||||
assert.equal(sha256(bytes), sha256(payload))
|
||||
const changed = Buffer.from(payload); changed[0] ^= 1
|
||||
assert.equal(changed.length, bytes.length)
|
||||
assert.notEqual(sha256(bytes), sha256(changed), 'same size is not content evidence')
|
||||
assert.deepEqual(h.requests.map(r => r.url), ['/merchant/v1/last-leg/delivery-orders/DL%2FA/documents/receipt', '/merchant/v1/last-leg/delivery-orders/DL%2FA/documents/receipt/files/file%2F1/download'])
|
||||
assert.equal(h.requests[1].responseType, 'blob')
|
||||
assert.equal(h.requests[1].authorization, 'Bearer customer-A')
|
||||
assert.equal(h.component.downloadingFileId.value, '')
|
||||
assert.equal(h.revoked.length, 1)
|
||||
assert.equal(h.urls.size, 0)
|
||||
assert.deepEqual(h.errors, [])
|
||||
})
|
||||
|
||||
for (const status of [403, 404, 500]) {
|
||||
test(`C63 HTTP ${status} never saves an error body and releases busy state`, async () => {
|
||||
const h = harness({ rejectDownload: status })
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.saved.length, 0)
|
||||
assert.equal(h.urls.size, 0)
|
||||
assert.equal(h.revoked.length, 0)
|
||||
assert.equal(h.errors.length, 1)
|
||||
assert.equal(h.component.downloadingFileId.value, '')
|
||||
})
|
||||
}
|
||||
|
||||
test('C63 unknown file and duplicate in-flight clicks do not issue another download', async () => {
|
||||
let finish
|
||||
const h = harness({ pending: new Promise(resolve => { finish = resolve }) })
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt('not-in-receipt-list')
|
||||
assert.equal(h.requests.length, 1)
|
||||
const first = h.component.downloadReceipt(file.fileId)
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
finish()
|
||||
await first
|
||||
assert.equal(h.requests.length, 2)
|
||||
assert.equal(h.saved.length, 1)
|
||||
})
|
||||
|
||||
test('C63 denied customer list clears prior file choices; denied download uses current customer session', async () => {
|
||||
const h = harness({ token: 'customer-B', rejectList: 403, rejectDownload: 403 })
|
||||
h.component.receiptFiles.value = [file]
|
||||
await h.component.loadReceipts()
|
||||
assert.equal(h.component.receiptFiles.value.length, 0)
|
||||
assert.ok(h.component.receiptsError.value)
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.requests.length, 1)
|
||||
// Simulate a stale visible choice: the real API must still use B's session.
|
||||
h.component.receiptFiles.value = [file]
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.ok(h.requests.every(r => r.authorization === 'Bearer customer-B'))
|
||||
assert.equal(h.saved.length, 0)
|
||||
assert.equal(h.errors.length, 1)
|
||||
})
|
||||
|
||||
test('C63 browser save exception releases object URL and permits retry', async () => {
|
||||
const h = harness({ clickError: new Error('save failed') })
|
||||
await h.component.loadReceipts()
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.saved.length, 0)
|
||||
assert.deepEqual(h.errors, ['save failed'])
|
||||
assert.equal(h.revoked.length, 1)
|
||||
assert.equal(h.component.downloadingFileId.value, '')
|
||||
await h.component.downloadReceipt(file.fileId)
|
||||
assert.equal(h.requests.length, 3)
|
||||
assert.equal(h.errors.length, 2)
|
||||
})
|
||||
|
||||
test('C63 disk evidence rejects same-size corruption, stale files and wrong filenames', async t => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'c63-download-'))
|
||||
t.after(() => rm(directory, { recursive: true, force: true }))
|
||||
const path = join(directory, file.fileName)
|
||||
const expected = { fileName: file.fileName, sizeBytes: payload.length, sha256: sha256(payload) }
|
||||
const startedAt = Date.now() - 1000
|
||||
await writeFile(path, payload)
|
||||
assert.equal((await verifyReceiptFile(path, expected, startedAt)).passed, true)
|
||||
const changed = Buffer.from(payload); changed[0] ^= 1
|
||||
await writeFile(path, changed)
|
||||
const corrupted = await verifyReceiptFile(path, expected, startedAt)
|
||||
assert.equal(corrupted.checks.size, true)
|
||||
assert.equal(corrupted.checks.content, false)
|
||||
assert.equal(corrupted.passed, false)
|
||||
await writeFile(path, payload)
|
||||
await utimes(path, new Date(0), new Date(0))
|
||||
assert.equal((await verifyReceiptFile(path, expected, startedAt)).checks.currentRun, false)
|
||||
const wrongPath = join(directory, 'wrong-name.bin')
|
||||
await writeFile(wrongPath, payload)
|
||||
assert.equal((await verifyReceiptFile(wrongPath, expected, startedAt)).checks.fileName, false)
|
||||
})
|
||||
|
||||
test('C63 browser evidence refuses missing fixture hash before interacting', async () => {
|
||||
await assert.rejects(acceptReceiptDownload({}, { deliveryNo: 'DL/A', fileName: file.fileName }), /SHA-256/)
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ClipboardList, ReceiptText } from '@lucide/vue'
|
||||
import { ClipboardList, ReceiptText, Truck, Warehouse } from '@lucide/vue'
|
||||
import type { ClientModuleManifest } from '../types.ts'
|
||||
|
||||
export const orderManagementModule = {
|
||||
@@ -19,6 +19,7 @@ export const orderManagementModule = {
|
||||
component: () => import('./views/InboundOrdersView.vue'),
|
||||
release: 'active',
|
||||
meta: { title: '入库订单列表', description: '查询海外仓入库订单', permission: 'merchant:warehouse:inbound:list' },
|
||||
navigation: { key: 'orders-inbound', icon: Warehouse },
|
||||
},
|
||||
{
|
||||
path: 'orders/inbound/:planNo/detail',
|
||||
@@ -34,6 +35,7 @@ export const orderManagementModule = {
|
||||
component: () => import('./views/DeliveryOrdersView.vue'),
|
||||
release: 'active',
|
||||
meta: { title: '派送订单列表', description: '查询海外仓派送订单', permission: 'merchant:warehouse:delivery:list' },
|
||||
navigation: { key: 'orders-delivery', icon: Truck },
|
||||
},
|
||||
{
|
||||
path: 'orders/delivery/create',
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ArrowLeft } from '@lucide/vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import dayjs from 'dayjs'
|
||||
import { getDeliveryOrder, type DeliveryOrderDetail, type DeliveryOrderItem } from '../api/deliveryOrders'
|
||||
import { getDeliveryOrder, getDeliveryReceipts, downloadDeliveryReceipt, type DeliveryReceiptFile, type DeliveryOrderDetail, type DeliveryOrderItem } from '../api/deliveryOrders'
|
||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||
|
||||
const props = defineProps<{ deliveryNo: string }>()
|
||||
@@ -11,7 +12,16 @@ const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const detail = ref<DeliveryOrderDetail | null>(null)
|
||||
const statusLabels: Record<string, string> = { PENDING: '待派送', IN_TRANSIT: '派送中', DELIVERED: '已送达', SIGNED: '已签收', CANCELLED: '已取消' }
|
||||
const receiptFiles = ref<DeliveryReceiptFile[]>([])
|
||||
const receiptsLoading = ref(false)
|
||||
const receiptsError = ref('')
|
||||
const downloadingFileId = ref('')
|
||||
const statusLabels: Record<string, string> = { WAIT_DELIVERY: '待派送', DELIVERING: '派送中', DELIVERED: '已签收', REJECTED: '已拒收', RETURN_PENDING: '待退回', RETURNED: '已退回', CANCELLED: '已取消' }
|
||||
const receiptColumns: DataTableColumn[] = [
|
||||
{ label: '操作', slotName: 'receiptActions', width: 100 },
|
||||
{ prop: 'fileName', label: '文件名称', minWidth: 260 },
|
||||
{ prop: 'uploadedAt', label: '上传时间', width: 180, formatter: (_row: object, _column: unknown, value: string) => formatDateTime(value) },
|
||||
]
|
||||
const deliveryMethodLabels: Record<string, string> = { FBA_PICKUP: 'FBA 自提', CUSTOMER_PICKUP: '客户自提', TRUCK_PALLET: '卡派打托', TRUCK_FLOOR: '卡派地板', EXPRESS: '快递', OUTSOURCED: '外配', DEDICATED_TRUCK: '专车直送', LTL: '零担派送' }
|
||||
const pickupMethodLabels: Record<string, string> = { ONE_PICKUP_ONE_DROP: '一提一卸', ONE_PICKUP_MULTI_DROP: '一提多卸', MULTI_PICKUP_ONE_DROP: '多提一卸', MULTI_PICKUP_MULTI_DROP: '多提多卸', WAREHOUSE_PICKUP: '仓库自提' }
|
||||
const loadingTypeLabels: Record<string, string> = { PALLET: '托盘', FLOOR: '地板', MIXED: '混装' }
|
||||
@@ -26,7 +36,7 @@ const itemColumns: DataTableColumn[] = [
|
||||
{ prop: 'volumeCbm', label: '体积(m³)', width: 120, align: 'right', headerAlign: 'right', formatter: tableValueFormatter },
|
||||
]
|
||||
const feeColumns: DataTableColumn[] = [
|
||||
{ prop: 'feeType', label: '费用类型', minWidth: 180, formatter: tableValueFormatter }, { prop: 'currency', label: '币种', width: 100, formatter: tableValueFormatter },
|
||||
{ prop: 'feeType', label: '费用类型', minWidth: 180, formatter: (_row: object, _column: unknown, value: string | null | undefined) => formatDeliveryFeeType(value) }, { prop: 'currency', label: '币种', width: 100, formatter: tableValueFormatter },
|
||||
{ prop: 'amount', label: '金额', width: 140, align: 'right', headerAlign: 'right', formatter: tableValueFormatter }, { prop: 'remark', label: '备注', minWidth: 240, formatter: tableValueFormatter },
|
||||
]
|
||||
|
||||
@@ -40,6 +50,11 @@ function display(value: string | number | null | undefined) {
|
||||
return value === null || value === undefined || value === '' ? '—' : String(value)
|
||||
}
|
||||
|
||||
function formatDeliveryFeeType(value: string | null | undefined) {
|
||||
const labels: Record<string, string> = { DELIVERY_FEE: '派送费', LOADING_FEE: '装车费', APPOINTMENT_FEE: '预约费' }
|
||||
return value ? labels[value] ?? value : '—'
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined) {
|
||||
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '—'
|
||||
}
|
||||
@@ -50,9 +65,9 @@ function formatQuantity(value: number | null | undefined, unit: string) {
|
||||
|
||||
function statusLabel(value: string) { return statusLabels[value] ?? display(value) }
|
||||
function statusTone(value: string) {
|
||||
if (value === 'DELIVERED' || value === 'SIGNED') return 'success'
|
||||
if (value === 'IN_TRANSIT') return 'primary'
|
||||
if (value === 'CANCELLED') return 'danger'
|
||||
if (value === 'DELIVERED') return 'success'
|
||||
if (value === 'DELIVERING') return 'primary'
|
||||
if (value === 'CANCELLED' || value === 'REJECTED') return 'danger'
|
||||
return 'warning'
|
||||
}
|
||||
function mappedLabel(value: string | null | undefined, labels: Record<string, string>) {
|
||||
@@ -64,6 +79,7 @@ async function loadDetail() {
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
detail.value = await getDeliveryOrder(props.deliveryNo)
|
||||
void loadReceipts()
|
||||
} catch (error) {
|
||||
detail.value = null
|
||||
errorMessage.value = error instanceof Error ? error.message : '派送单详情加载失败,请重试'
|
||||
@@ -72,6 +88,42 @@ async function loadDetail() {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadReceipts() {
|
||||
receiptsLoading.value = true
|
||||
receiptsError.value = ''
|
||||
receiptFiles.value = []
|
||||
try {
|
||||
receiptFiles.value = (await getDeliveryReceipts(props.deliveryNo)).files
|
||||
} catch (error) {
|
||||
receiptsError.value = error instanceof Error ? error.message : '签收资料加载失败,请重试'
|
||||
} finally {
|
||||
receiptsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadReceipt(fileId: unknown) {
|
||||
const file = receiptFiles.value.find(item => item.fileId === fileId)
|
||||
if (!file) return
|
||||
if (downloadingFileId.value) return
|
||||
downloadingFileId.value = file.fileId
|
||||
try {
|
||||
const blob = await downloadDeliveryReceipt(props.deliveryNo, file.fileId)
|
||||
const url = URL.createObjectURL(blob)
|
||||
try {
|
||||
const anchor = document.createElement('a')
|
||||
anchor.href = url
|
||||
anchor.download = file.fileName
|
||||
anchor.click()
|
||||
} finally {
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '签收文件下载失败,请重试')
|
||||
} finally {
|
||||
downloadingFileId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function backToList() {
|
||||
void router.push({ name: 'orders-delivery' })
|
||||
}
|
||||
@@ -135,6 +187,18 @@ onMounted(loadDetail)
|
||||
<DataTable :data="items" :columns="itemColumns" empty-text="暂无货物明细" />
|
||||
</section>
|
||||
|
||||
<section class="delivery-detail-section" aria-label="签收资料">
|
||||
<div class="delivery-detail-section-heading"><h3>签收资料</h3><span>共 {{ receiptFiles.length }} 个文件</span></div>
|
||||
<div v-if="receiptsError" class="delivery-state delivery-state--error" role="alert">
|
||||
<p>{{ receiptsError }}</p><el-button @click="loadReceipts">重试</el-button>
|
||||
</div>
|
||||
<DataTable v-else :data="receiptFiles" :columns="receiptColumns" :loading="receiptsLoading" empty-text="暂无签收资料">
|
||||
<template #receiptActions="{ row }">
|
||||
<el-button link type="primary" :loading="downloadingFileId === row.fileId" :disabled="!!downloadingFileId && downloadingFileId !== row.fileId" @click="downloadReceipt(row.fileId)">下载</el-button>
|
||||
</template>
|
||||
</DataTable>
|
||||
</section>
|
||||
|
||||
<section class="delivery-detail-section">
|
||||
<div class="delivery-detail-section-heading"><h3>费用明细</h3><span>共 {{ detail.fees.length }} 条</span></div>
|
||||
<DataTable :data="detail.fees" :columns="feeColumns" empty-text="暂无费用明细" />
|
||||
|
||||
@@ -19,12 +19,28 @@ const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const filters = reactive({ documentNo: '', dispatchNo: '', waybillNo: '', status: '', deliveryMethod: '', plannedRange: [] as string[] })
|
||||
const canCreate = computed(() => auth.hasPermission('merchant:warehouse:delivery:create'))
|
||||
let requestSequence = 0
|
||||
|
||||
const deliveryMethodOptions = [
|
||||
{ value: 'FBA_PICKUP', label: 'FBA 自提' },
|
||||
{ value: 'CUSTOMER_PICKUP', label: '客户自提' },
|
||||
{ value: 'TRUCK_PALLET', label: '卡派打托' },
|
||||
{ value: 'TRUCK_FLOOR', label: '卡派地板' },
|
||||
{ value: 'EXPRESS', label: '快递' },
|
||||
{ value: 'OUTSOURCED', label: '外配' },
|
||||
{ value: 'DEDICATED_TRUCK', label: '专车直送' },
|
||||
{ value: 'LTL', label: '零担派送' },
|
||||
{ value: 'TRUCK', label: '卡车派送' },
|
||||
]
|
||||
const deliveryMethodLabels: Record<string, string> = Object.fromEntries(deliveryMethodOptions.map(item => [item.value, item.label]))
|
||||
|
||||
const statusOptions = [
|
||||
{ value: 'PENDING', label: '待派送' },
|
||||
{ value: 'IN_TRANSIT', label: '派送中' },
|
||||
{ value: 'DELIVERED', label: '已送达' },
|
||||
{ value: 'SIGNED', label: '已签收' },
|
||||
{ value: 'WAIT_DELIVERY', label: '待派送' },
|
||||
{ value: 'DELIVERING', label: '派送中' },
|
||||
{ value: 'DELIVERED', label: '已签收' },
|
||||
{ value: 'REJECTED', label: '已拒收' },
|
||||
{ value: 'RETURN_PENDING', label: '待退回' },
|
||||
{ value: 'RETURNED', label: '已退回' },
|
||||
{ value: 'CANCELLED', label: '已取消' },
|
||||
]
|
||||
|
||||
@@ -35,14 +51,14 @@ const queryFields: QueryField[] = [
|
||||
{ key: 'dispatchNo', label: '排车单号', type: 'input', placeholder: '请输入排车单号' },
|
||||
{ key: 'waybillNo', label: '运单号', type: 'input', placeholder: '请输入运单号' },
|
||||
{ key: 'status', label: '派送状态', type: 'select', options: statusOptions },
|
||||
{ key: 'deliveryMethod', label: '派送方式', type: 'select', options: [{ label: '卡车派送', value: 'TRUCK' }, { label: '快递派送', value: 'COURIER' }, { label: '客户自提', value: 'SELF_PICKUP' }] },
|
||||
{ key: 'deliveryMethod', label: '派送方式', type: 'select', options: deliveryMethodOptions },
|
||||
{ key: 'plannedRange', label: '计划时间', type: 'daterange' },
|
||||
]
|
||||
const tableColumns: DataTableColumn[] = [
|
||||
{ key: 'actions', label: '操作', slotName: 'actions', width: 90, fixed: 'left' }, { prop: 'deliveryNo', label: '派送单号', minWidth: 180 },
|
||||
{ prop: 'dispatchNo', label: '排车单号', minWidth: 170 }, { prop: 'outboundNo', label: '出库单号', minWidth: 170 },
|
||||
{ key: 'status', label: '状态', slotName: 'status', width: 110 }, { prop: 'overseasWarehouseName', label: '海外仓', minWidth: 160 },
|
||||
{ prop: 'deliveryMethod', label: '派送方式', width: 120 }, { prop: 'waybillNo', label: '运单号', minWidth: 150 },
|
||||
{ prop: 'deliveryMethod', label: '派送方式', width: 120, formatter: (_row: object, _column: unknown, value: string | null | undefined) => value ? deliveryMethodLabels[value] ?? value : '—' }, { prop: 'waybillNo', label: '运单号', minWidth: 150 },
|
||||
{ prop: 'carrierName', label: '承运商', minWidth: 140 }, { key: 'planned', label: '计划派送', slotName: 'planned', width: 160 },
|
||||
{ key: 'arrival', label: '预计到达', slotName: 'arrival', width: 160 }, { key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 160 },
|
||||
]
|
||||
@@ -60,9 +76,10 @@ function statusLabel(status: string) {
|
||||
}
|
||||
|
||||
function statusType(status: string) {
|
||||
if (status === 'DELIVERED' || status === 'SIGNED') return 'success'
|
||||
if (status === 'DELIVERED') return 'success'
|
||||
if (status === 'CANCELLED') return 'info'
|
||||
if (status === 'IN_TRANSIT') return 'warning'
|
||||
if (status === 'DELIVERING' || status === 'RETURN_PENDING') return 'warning'
|
||||
if (status === 'REJECTED') return 'danger'
|
||||
return 'primary'
|
||||
}
|
||||
|
||||
@@ -81,18 +98,21 @@ function buildQuery(): DeliveryQuery {
|
||||
}
|
||||
|
||||
async function loadOrders() {
|
||||
const sequence = ++requestSequence
|
||||
loading.value = true
|
||||
errorMessage.value = ''
|
||||
try {
|
||||
const result = await listDeliveryOrders(buildQuery())
|
||||
if (sequence !== requestSequence) return
|
||||
records.value = result.records
|
||||
total.value = result.total
|
||||
} catch (error) {
|
||||
if (sequence !== requestSequence) return
|
||||
records.value = []
|
||||
total.value = 0
|
||||
errorMessage.value = error instanceof Error ? error.message : '派送单加载失败,请重试'
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (sequence === requestSequence) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { overseasApiRequest } from '@/api/overseasHttp'
|
||||
import { apiRequest } from '@/api/http'
|
||||
import type { PageResult } from './warehouseServices'
|
||||
|
||||
export interface ReturnInventoryItem {
|
||||
@@ -19,7 +19,7 @@ export interface ReturnInventoryCartonSummary {
|
||||
}
|
||||
|
||||
export function listReturnInventoryCartons(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<ReturnInventoryCartonSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/return-inventory/cartons', params })
|
||||
return apiRequest<PageResult<ReturnInventoryCartonSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/return-inventory/cartons', params })
|
||||
}
|
||||
|
||||
export interface ReturnInventoryCartonDetail {
|
||||
@@ -33,19 +33,19 @@ export interface ReturnInventoryLabel {
|
||||
}
|
||||
|
||||
export function listReturnInventory(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<ReturnInventoryItem>>({ method: 'GET', url: '/merchant/v1/last-leg/return-inventory', params })
|
||||
return apiRequest<PageResult<ReturnInventoryItem>>({ method: 'GET', url: '/merchant/v1/last-leg/return-inventory', params })
|
||||
}
|
||||
|
||||
export function listReturnInventorySummary(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<ReturnInventorySummaryItem>>({ method: 'GET', url: '/merchant/v1/last-leg/return-inventory/summary', params })
|
||||
return apiRequest<PageResult<ReturnInventorySummaryItem>>({ method: 'GET', url: '/merchant/v1/last-leg/return-inventory/summary', params })
|
||||
}
|
||||
|
||||
export function getReturnInventoryCarton(cartonMark: string) {
|
||||
return overseasApiRequest<ReturnInventoryCartonDetail>({ method: 'GET', url: `/merchant/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}` })
|
||||
return apiRequest<ReturnInventoryCartonDetail>({ method: 'GET', url: `/merchant/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}` })
|
||||
}
|
||||
|
||||
export function getReturnInventoryLabel(cartonMark: string) {
|
||||
return overseasApiRequest<ReturnInventoryLabel>({ method: 'GET', url: `/merchant/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}/label` })
|
||||
return apiRequest<ReturnInventoryLabel>({ method: 'GET', url: `/merchant/v1/last-leg/return-inventory/cartons/${encodeURIComponent(cartonMark)}/label` })
|
||||
}
|
||||
|
||||
export interface ReturnPackingPreview {
|
||||
@@ -55,14 +55,14 @@ export interface ReturnPackingPreview {
|
||||
}
|
||||
|
||||
export function getReturnPackingPreview(returnNo?: string) {
|
||||
return overseasApiRequest<ReturnPackingPreview>({ method: 'GET', url: '/pda/v1/last-leg/return-inventory/packing/orders', params: { returnNo: returnNo || undefined } })
|
||||
return apiRequest<ReturnPackingPreview>({ method: 'GET', url: '/pda/v1/last-leg/return-inventory/packing/orders', params: { returnNo: returnNo || undefined } })
|
||||
}
|
||||
|
||||
export function mergeReturnInventory(payload: {
|
||||
returnNos: string[]; items: Array<{ skuCode: string; quantity: number }>
|
||||
length: number; width: number; height: number; weight: number; idempotencyKey: string
|
||||
}) {
|
||||
return overseasApiRequest<{ cartonMark: string; skuCode: string; totalQuantity: number; label: ReturnInventoryLabel }>({
|
||||
return apiRequest<{ cartonMark: string; skuCode: string; totalQuantity: number; label: ReturnInventoryLabel }>({
|
||||
method: 'POST', url: '/pda/v1/last-leg/return-inventory/cartons/merge', data: payload,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { overseasApiRequest, overseasBlobRequest } from '@/api/overseasHttp'
|
||||
import { apiRequest, apiBlobRequest } from '@/api/http'
|
||||
import type { PageResult } from './warehouseServices'
|
||||
|
||||
export interface ReturnOrderSummary {
|
||||
@@ -10,10 +10,12 @@ export interface ReturnOrderItem {
|
||||
skuCode: string; productNameZh?: string; expectedQuantity: number; receivedQuantity: number
|
||||
}
|
||||
export interface ReturnReceipt {
|
||||
receiptNo: string; receiptBatchNo: string; palletCode: string; trackingNo?: string; startedBy: 'RETURN_NO' | 'SKU'
|
||||
receivedQuantity: number; operatorName?: string; signedAt: string
|
||||
receiptNo: string; receiptBatchNo: string; palletCode?: string; trackingNo?: string; startedBy: 'RETURN_NO' | 'SKU'
|
||||
receivedQuantity: number; operatorName?: string; signedAt: string; unitType: 'PALLET' | 'BOX' | 'PARCEL'; unitCode?: string; boxCount: number
|
||||
items: Array<{ skuCode: string; productNameZh?: string; quantity: number; boxCount: number }>; cartonMark?: string; printableHtml?: string
|
||||
labels?: Array<{ cartonMark: string; printableHtml: string }>
|
||||
}
|
||||
export interface ReturnPallet { palletCode: string; skuTypes: number; totalQuantity: number; items: Array<{ skuCode: string; productNameZh?: string; quantity: number }> }
|
||||
export interface ReturnPallet { palletCode: string; unitType: 'PALLET' | 'BOX'; unitCode: string; skuTypes: number; totalQuantity: number; totalBoxCount: number; items: Array<{ skuCode: string; productNameZh?: string; quantity: number; boxCount: number }> }
|
||||
export interface ReturnPhoto { fileId: number; fileName: string; contentType: string; sizeBytes: number }
|
||||
export interface ReturnOrderDetail { order: ReturnOrderSummary; remark?: string; items: ReturnOrderItem[]; receipts: ReturnReceipt[]; pallets: ReturnPallet[]; photos: ReturnPhoto[] }
|
||||
export interface ReturnOrderCreate {
|
||||
@@ -22,16 +24,16 @@ export interface ReturnOrderCreate {
|
||||
}
|
||||
|
||||
export function listReturnOrders(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<ReturnOrderSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/return-orders', params })
|
||||
return apiRequest<PageResult<ReturnOrderSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/return-orders', params })
|
||||
}
|
||||
export function getReturnOrder(returnNo: string) {
|
||||
return overseasApiRequest<ReturnOrderDetail>({ method: 'GET', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}` })
|
||||
return apiRequest<ReturnOrderDetail>({ method: 'GET', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}` })
|
||||
}
|
||||
export function createReturnOrder(payload: ReturnOrderCreate) {
|
||||
return overseasApiRequest<ReturnOrderDetail>({ method: 'POST', url: '/merchant/v1/last-leg/return-orders', data: payload })
|
||||
return apiRequest<ReturnOrderDetail>({ method: 'POST', url: '/merchant/v1/last-leg/return-orders', data: payload })
|
||||
}
|
||||
export function updateReturnOrder(returnNo: string, payload: ReturnOrderCreate) {
|
||||
return overseasApiRequest<ReturnOrderDetail>({ method: 'PUT', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}`, data: payload })
|
||||
return apiRequest<ReturnOrderDetail>({ method: 'PUT', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}`, data: payload })
|
||||
}
|
||||
export interface ReturnRelabelCreate {
|
||||
fileScope: 'CARTON_TOTAL' | 'SKU_TOTAL'; destinationFbaWarehouseId: string; destinationFbaWarehouseCode: string; cartonRemark?: string; idempotencyKey: string
|
||||
@@ -39,12 +41,12 @@ export interface ReturnRelabelCreate {
|
||||
}
|
||||
export interface ReturnRelabelCreated { relabelNo: string; relabelApplicationId: string; returnNo: string; skuCodes: string[]; status: string }
|
||||
export function createReturnRelabel(returnNo: string, payload: ReturnRelabelCreate) {
|
||||
return overseasApiRequest<ReturnRelabelCreated>({ method: 'POST', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}/relabel`, data: payload })
|
||||
return apiRequest<ReturnRelabelCreated>({ method: 'POST', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}/relabel`, data: payload })
|
||||
}
|
||||
export function uploadReturnRelabelFile(relabelNo: string, scope: 'CARTON_TOTAL' | 'SKU_TOTAL', file: File) {
|
||||
const data = new FormData(); data.append('file', file)
|
||||
return overseasApiRequest<unknown>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/files`, params: { scope }, data, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
return apiRequest<unknown>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/files`, params: { scope }, data, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
}
|
||||
export function downloadReturnPhoto(returnNo: string, fileId: string | number) {
|
||||
return overseasBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}/photos/files/${encodeURIComponent(String(fileId))}/download` })
|
||||
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/return-orders/${encodeURIComponent(returnNo)}/photos/files/${encodeURIComponent(String(fileId))}/download` })
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { overseasApiRequest, overseasBlobRequest } from '@/api/overseasHttp'
|
||||
import { apiRequest, apiBlobRequest } from '@/api/http'
|
||||
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
||||
|
||||
export type RelabelDeliveryMethod = 'TRUCK' | 'EXPRESS' | 'TRUCK_PICKUP' | 'EXPRESS_PICKUP'
|
||||
@@ -6,8 +6,8 @@ export type RelabelDeliveryMethod = 'TRUCK' | 'EXPRESS' | 'TRUCK_PICKUP' | 'EXPR
|
||||
export interface PageResult<T> { records: T[]; page: number; size: number; total: number; pages: number }
|
||||
export interface LastlegOrderSummary { id: string; orderNo: string; inboundCode: string; orderType: string; packageCount: number; overseasWarehouseId?: string }
|
||||
export interface HistoricalOrderSummary { id: string | null; orderNo: string; sourceOrderNo?: string; outboundOrderNo?: string; relabelOrderNo?: string; orderType?: string; status?: string; packageCount?: number }
|
||||
export interface TransferSummary { id: string; transferNo: string; inboundCode: string; lastlegOrderId: string; lastlegOrderNo: string; operatingWarehouseId: string; fbaWarehouseCode?: string; packageCount: number; deliveryMethod: string; needRelabel: boolean; relabelNo?: string; relabelStatus?: string; relabelFulfillmentStatus?: string; status: string; estimatedArrivalAt: string; estimatedShipAt?: string; actualShipAt?: string; createdAt: string }
|
||||
export interface RelabelSummary { id: string; relabelNo: string; lastlegOrderId: string; lastlegOrderNo: string; customerOrderNo: string; overseasWarehouseId: string; status: string; itemCount: number; totalPackageCount: number; notifiedPackageCount: number; skuCodes: string; createdAt: string; totalFileId?: string; totalFileName?: string; totalFileUrl?: string; cartonTotalFileId?: string; cartonTotalFileName?: string; cartonTotalFileUrl?: string; skuTotalFileId?: string; skuTotalFileName?: string; skuTotalFileUrl?: string; deliveryMethod?: RelabelDeliveryMethod; printShippingLabel?: boolean; shippingLabelFileId?: string; shippingLabelFileName?: string; shippingLabelFileUrl?: string; fulfillmentStatus?: string; outboundOrderNo?: string; customerConfirmedAt?: string; reviewChannel?: 'TAIL_ORDER' | 'RELABEL_ORDER'; reviewRemark?: string }
|
||||
export interface TransferSummary { id: string; transferNo: string; inboundCode: string; lastlegOrderId: string; lastlegOrderNo: string; operatingWarehouseId: string; fbaWarehouseCode?: string; packageCount: number; deliveryMethod: string; needRelabel: boolean; relabelNo?: string; relabelStatus?: string; relabelFulfillmentStatus?: string; status: string; estimatedArrivalAt: string; estimatedShipAt?: string; actualShipAt?: string; reviewedAt?: string; measuredAt?: string; outboundAt?: string; relabelCompletedAt?: string; createdAt: string }
|
||||
export interface RelabelSummary { id: string; relabelNo: string; lastlegOrderId: string; lastlegOrderNo: string; customerOrderNo: string; overseasWarehouseId: string; status: string; itemCount: number; totalPackageCount: number; notifiedPackageCount: number; skuCodes: string; createdAt: string; reviewedAt?: string; relabelCompletedAt?: string; outboundAt?: string; totalFileId?: string; totalFileName?: string; totalFileUrl?: string; cartonTotalFileId?: string; cartonTotalFileName?: string; cartonTotalFileUrl?: string; skuTotalFileId?: string; skuTotalFileName?: string; skuTotalFileUrl?: string; deliveryMethod?: RelabelDeliveryMethod; printShippingLabel?: boolean; shippingLabelFileId?: string; shippingLabelFileName?: string; shippingLabelFileUrl?: string; fulfillmentStatus?: string; outboundOrderNo?: string; customerConfirmedAt?: string; reviewChannel?: 'TAIL_ORDER' | 'RELABEL_ORDER'; reviewRemark?: string }
|
||||
export interface RelabelItemDetail {
|
||||
id: string; skuCode?: string; productNameZh: string; totalPackageCount: number; notifiedPackageCount: number
|
||||
shipmentNo: string; trackingCode?: string; newSkuCode?: string; labelRequirement?: string; remark?: string
|
||||
@@ -25,8 +25,8 @@ export interface RelabelDetail {
|
||||
tailOrders?: Array<{ id: string; orderNo: string; overseasWarehouseId: string; packageCount: number; status: string }>
|
||||
completionEvidence?: { taskId: string; photoFileIds: string[]; completionRemark?: string; reviewerName?: string; reviewRemark?: string; completedAt?: string }
|
||||
}
|
||||
export interface DiscardSummary { id: string; discardNo: string; inboundCodes: string; overseasWarehouseId: string; overseasWarehouseName: string; totalPackages: number; totalFee: number; currency: string; status: string; createdAt: string }
|
||||
export interface DiscardCandidate { orderId: string; inboundCode: string; inboundOrderNo: string; overseasWarehouseId: string; overseasWarehouseName: string; availablePackages: number; skus: Array<{ skuCode: string; productName: string; availablePackages: number }> }
|
||||
export interface DiscardSummary { id: string; discardNo: string; outboundNo?: string; inboundCodes: string; overseasWarehouseId: string; overseasWarehouseName: string; totalPackages: number; totalFee: number; currency: string; status: string; createdAt: string; completedAt?: string }
|
||||
export interface DiscardCandidate { orderId: string; sourceType?: 'DROPSHIP' | 'RETURN_CARTON'; returnCartonId?: string; cartonMark?: string; inboundCode: string; inboundOrderNo: string; overseasWarehouseId: string; overseasWarehouseName: string; availablePackages: number; skus: Array<{ skuCode: string; productName: string; availablePackages: number }> }
|
||||
export interface RelabelInventoryCandidate {
|
||||
inventoryBalanceId: string; inboundOrderId: string; inboundOrderNo?: string; inboundCode?: string
|
||||
overseasWarehouseId: string; overseasWarehouseCode?: string; overseasWarehouseName?: string
|
||||
@@ -38,7 +38,7 @@ export interface RelabelInventoryCandidate {
|
||||
}
|
||||
|
||||
export interface TransferCreate {
|
||||
inboundCode?: string; sourceLastlegOrderIds?: number[]; operatingWarehouseId: string; fbaWarehouseCode?: string; destinationType?: 'NONE' | 'FBA' | 'PRIVATE'
|
||||
inboundCode?: string; sourceLastlegOrderIds?: string[]; operatingWarehouseId: string; fbaWarehouseCode?: string; destinationType?: 'NONE' | 'FBA' | 'PRIVATE'
|
||||
destinationWarehouseId?: string; destinationWarehouseCode?: string; destinationWarehouseName?: string
|
||||
privateDestinationAddress?: string; privateDestinationPostalCode?: string; privateDestinationContactName?: string; privateDestinationContactPhone?: string
|
||||
deliveryAddress: string; packageCount: number; volumeCbm: number; deliveryMethod: string; estimatedArrivalAt: string; estimatedShipAt?: string
|
||||
@@ -55,78 +55,78 @@ export interface RelabelCreate {
|
||||
}
|
||||
|
||||
export function listRelabelHistoricalOrders(operationWarehouseId: string, keyword?: string) {
|
||||
return overseasApiRequest<HistoricalOrderSummary[]>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications/historical-orders', params: { operationWarehouseId, keyword: keyword || undefined } })
|
||||
return apiRequest<HistoricalOrderSummary[]>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications/historical-orders', params: { operationWarehouseId, keyword: keyword || undefined } })
|
||||
}
|
||||
export function listTransfers(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<TransferSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/warehouse-transfers', params })
|
||||
return apiRequest<PageResult<TransferSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/warehouse-transfers', params })
|
||||
}
|
||||
export function getTransfer(transferNo: string) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}` })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}` })
|
||||
}
|
||||
export function createTransfer(payload: TransferCreate) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'POST', url: '/merchant/v1/last-leg/warehouse-transfers', data: payload })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: '/merchant/v1/last-leg/warehouse-transfers', data: payload })
|
||||
}
|
||||
export function updateTransfer(transferNo: string, payload: TransferCreate) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/save-draft`, data: payload })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/save-draft`, data: payload })
|
||||
}
|
||||
export function submitTransfer(transferNo: string) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/submit` })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/submit` })
|
||||
}
|
||||
export function listRelabels(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<RelabelSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications', params })
|
||||
return apiRequest<PageResult<RelabelSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/relabel-applications', params })
|
||||
}
|
||||
export function getRelabel(relabelNo: string) {
|
||||
return overseasApiRequest<RelabelDetail>({ method: 'GET', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}` })
|
||||
return apiRequest<RelabelDetail>({ method: 'GET', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}` })
|
||||
}
|
||||
export function confirmTransferMeasurement(transferNo: string, remark?: string) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/confirm-measurement`, data: { idempotencyKey: createIdempotencyKey(), remark } })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/confirm-measurement`, data: { idempotencyKey: createIdempotencyKey(), remark } })
|
||||
}
|
||||
export interface TransferCartonLabel { transferNo: string; cartons: Array<{ cartonMark: string; customerCartonMark?: string; cartonIndex: number; totalCartons: number; status: string }>; printableHtml: string }
|
||||
export function getTransferCartonLabel(transferNo: string) {
|
||||
return overseasApiRequest<TransferCartonLabel>({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/carton-label` })
|
||||
return apiRequest<TransferCartonLabel>({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/carton-label` })
|
||||
}
|
||||
export function downloadTransferMeasurementPhoto(transferNo: string, fileId: string | number) {
|
||||
return overseasBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/measurement-photos/files/${encodeURIComponent(fileId)}/download` })
|
||||
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/warehouse-transfers/${encodeURIComponent(transferNo)}/measurement-photos/files/${encodeURIComponent(fileId)}/download` })
|
||||
}
|
||||
|
||||
export function listRelabelInventoryCandidates(operationWarehouseId: string, inboundCode?: string) {
|
||||
return overseasApiRequest<RelabelInventoryCandidate[]>({
|
||||
return apiRequest<RelabelInventoryCandidate[]>({
|
||||
method: 'GET', url: '/merchant/v1/last-leg/relabel-applications/inventory-candidates',
|
||||
params: { operationWarehouseId, inboundCode: inboundCode || undefined },
|
||||
})
|
||||
}
|
||||
export function createRelabel(payload: RelabelCreate) {
|
||||
return overseasApiRequest<RelabelDetail>({ method: 'POST', url: '/merchant/v1/last-leg/relabel-applications', data: payload })
|
||||
return apiRequest<RelabelDetail>({ method: 'POST', url: '/merchant/v1/last-leg/relabel-applications', data: payload })
|
||||
}
|
||||
export function resubmitRelabel(relabelNo: string, payload: { labelDeadline: string; contactName: string; contactPhone: string; remark?: string; idempotencyKey: string }) {
|
||||
return overseasApiRequest<RelabelDetail>({ method: 'PUT', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/resubmit`, data: payload })
|
||||
return apiRequest<RelabelDetail>({ method: 'PUT', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/resubmit`, data: payload })
|
||||
}
|
||||
export function uploadRelabelShippingLabel(relabelNo: string, file: File) {
|
||||
const data = new FormData(); data.append('file', file)
|
||||
return overseasApiRequest<RelabelDetail>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/shipping-label`, data, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
return apiRequest<RelabelDetail>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/shipping-label`, data, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
}
|
||||
export function uploadRelabelFile(relabelNo: string, scope: 'CARTON_TOTAL' | 'SKU_TOTAL' | 'ITEM', file: File, itemId?: string) {
|
||||
const data = new FormData(); data.append('file', file)
|
||||
return overseasApiRequest<RelabelDetail>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/files`, params: { scope, itemId }, data, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
return apiRequest<RelabelDetail>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/files`, params: { scope, itemId }, data, headers: { 'Content-Type': 'multipart/form-data' } })
|
||||
}
|
||||
export function confirmRelabelCompletion(relabelNo: string, remark?: string) {
|
||||
return overseasApiRequest<RelabelDetail>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/confirm-completion`, data: { idempotencyKey: createIdempotencyKey(), remark } })
|
||||
return apiRequest<RelabelDetail>({ method: 'POST', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/confirm-completion`, data: { idempotencyKey: createIdempotencyKey(), remark } })
|
||||
}
|
||||
export function downloadRelabelCompletionPhoto(relabelNo: string, fileId: string) {
|
||||
return overseasBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/completion-photos/${encodeURIComponent(fileId)}/download` })
|
||||
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(relabelNo)}/completion-photos/${encodeURIComponent(fileId)}/download` })
|
||||
}
|
||||
export function listDiscards(params: Record<string, unknown>) {
|
||||
return overseasApiRequest<PageResult<DiscardSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/cargo-discards', params })
|
||||
return apiRequest<PageResult<DiscardSummary>>({ method: 'GET', url: '/merchant/v1/last-leg/cargo-discards', params })
|
||||
}
|
||||
export function getDiscard(discardNo: string) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'GET', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}` })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'GET', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}` })
|
||||
}
|
||||
export function listDiscardCandidates(inboundCode?: string) {
|
||||
return overseasApiRequest<DiscardCandidate[]>({ method: 'GET', url: '/merchant/v1/last-leg/cargo-discards/inventory-candidates', params: { inboundCode: inboundCode || undefined } })
|
||||
return apiRequest<DiscardCandidate[]>({ method: 'GET', url: '/merchant/v1/last-leg/cargo-discards/inventory-candidates', params: { inboundCode: inboundCode || undefined } })
|
||||
}
|
||||
export function createDiscard(payload: { items: Array<{ orderId: string; skuCode: string; discardPackages: number }>; idempotencyKey: string; remark?: string }) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'POST', url: '/merchant/v1/last-leg/cargo-discards', data: payload })
|
||||
export function createDiscard(payload: { items: Array<{ orderId?: string; returnCartonId?: string; skuCode: string; discardPackages: number }>; idempotencyKey: string; remark?: string }) {
|
||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: '/merchant/v1/last-leg/cargo-discards', data: payload })
|
||||
}
|
||||
export function cancelDiscard(discardNo: string) {
|
||||
return overseasApiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/cancel` })
|
||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/cancel` })
|
||||
}
|
||||
|
||||
@@ -41,8 +41,8 @@ test('opens warehouse service and return receipt details as dedicated protected
|
||||
})
|
||||
|
||||
test('returns to the labeling list after a labeling application is submitted', () => {
|
||||
assert.match(services, /ElMessage\.success\(`\$\{config\.value\.title\}提交成功`\)[\s\S]*?router\.push\(\{ name: 'overseas-labeling' \}\)/)
|
||||
assert.match(services, /uploadReturnRelabelFile\([\s\S]*?router\.push\(\{ name: 'overseas-labeling' \}\)/)
|
||||
assert.match(services, /ElMessage\.success\(`\$\{config\.value\.title\}提交成功`\)[\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/)
|
||||
assert.match(services, /uploadReturnRelabelFile\([\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/)
|
||||
})
|
||||
|
||||
test('keeps overseas warehouse writes behind operation-specific button permissions', () => {
|
||||
|
||||
@@ -7,7 +7,7 @@ const api = readFileSync(new URL('../api/returnOrders.ts', import.meta.url), 'ut
|
||||
|
||||
test('退货签收照片通过客户鉴权下载接口加载并释放对象 URL', () => {
|
||||
assert.match(api, /\/return-orders\/\$\{encodeURIComponent\(returnNo\)\}\/photos\/files\/\$\{encodeURIComponent\(String\(fileId\)\)\}\/download/)
|
||||
assert.match(api, /overseasBlobRequest/)
|
||||
assert.match(api, /apiBlobRequest/)
|
||||
assert.match(view, /URL\.createObjectURL\(await downloadReturnPhoto\(detailReturnNo\.value, photo\.fileId\)\)/)
|
||||
assert.match(view, /URL\.revokeObjectURL\(url\)/)
|
||||
assert.match(view, /onBeforeUnmount\(clearPhotoUrls\)/)
|
||||
@@ -74,9 +74,17 @@ test('退货签收详情使用独立路由和紧凑连续页面', () => {
|
||||
assert.doesNotMatch(view, /class="return-detail-dialog"/)
|
||||
})
|
||||
|
||||
test('退货箱唛打印复用统一的紧凑单页模板并按箱分页', () => {
|
||||
assert.match(view, /@page\{size:100mm 100mm;margin:8mm\}/)
|
||||
assert.match(view, /\.label\{width:84mm;height:84mm;padding:8mm/)
|
||||
assert.match(view, /html\.slice\(contentStart, bodyEnd\)/)
|
||||
assert.match(view, /打印全部箱唛(\{\{ receipt\.labels\?\.length \|\| receipt\.boxCount \|\| 1 \}\} 箱)/)
|
||||
})
|
||||
|
||||
test('待审核退货可编辑,完成入库后从独立新增页发起贴标', () => {
|
||||
assert.match(view, /row\.status === 'PENDING_REVIEW'.*key: 'edit'/)
|
||||
assert.match(view, /await updateReturnOrder\(editingReturnNo\.value, payload\)/)
|
||||
assert.match(view, /if \(editingReturnNo\.value\) await updateReturnOrder\(editingReturnNo\.value, payload\)/)
|
||||
assert.match(view, /else await createReturnOrder\(payload\)/)
|
||||
assert.match(view, /order\.status === 'COMPLETED' && order\.needRelabel === true/)
|
||||
assert.match(view, /name: 'overseas-labeling-create'/)
|
||||
assert.match(view, /query: \{ returnNo: order\.returnNo, warehouseId: String\(order\.overseasWarehouseId\) \}/)
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useAuthStore } from '@/modules/auth/public'
|
||||
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public'
|
||||
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
||||
import { createReturnOrder, downloadReturnPhoto, getReturnOrder, listReturnOrders, updateReturnOrder, type ReturnOrderDetail, type ReturnOrderSummary, type ReturnReceipt } from '../api/returnOrders'
|
||||
import { getReturnInventoryLabel } from '../api/returnInventory'
|
||||
|
||||
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean; returnNo?: string }>(), { createPage: false, detailPage: false, returnNo: '' })
|
||||
const router = useRouter()
|
||||
@@ -54,19 +55,21 @@ const tableColumns: DataTableColumn[] = [
|
||||
{ key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 180 },
|
||||
]
|
||||
const itemColumns: DataTableColumn[] = [
|
||||
{ prop: 'skuCode', label: 'SKU', minWidth: 190 },
|
||||
{ prop: 'productNameZh', label: '中文品名', minWidth: 220 },
|
||||
{ prop: 'expectedQuantity', label: '预报数量', width: 110 },
|
||||
{ prop: 'receivedQuantity', label: '实收数量', width: 110 },
|
||||
{ prop: 'skuCode', label: 'SKU', minWidth: 150 },
|
||||
{ prop: 'productNameZh', label: '中文品名', minWidth: 180 },
|
||||
{ prop: 'expectedQuantity', label: '预报数量', width: 100 },
|
||||
{ prop: 'receivedQuantity', label: '实收数量', width: 100 },
|
||||
]
|
||||
const receiptColumns: DataTableColumn[] = [
|
||||
{ prop: 'receiptBatchNo', label: '批次号', minWidth: 170 },
|
||||
{ prop: 'receiptNo', label: '签收单号', minWidth: 170 },
|
||||
{ prop: 'palletCode', label: '托盘码', minWidth: 190 },
|
||||
{ key: 'trackingNo', label: '快递单号', slotName: 'trackingNo', minWidth: 160 },
|
||||
{ key: 'startedBy', label: '开始方式', slotName: 'startedBy', width: 110 },
|
||||
{ prop: 'receivedQuantity', label: '实收', width: 90 },
|
||||
{ key: 'signedAt', label: '签收时间', slotName: 'signedAt', minWidth: 180 },
|
||||
{ prop: 'receiptBatchNo', label: '批次号', minWidth: 145 },
|
||||
{ prop: 'receiptNo', label: '签收单号', minWidth: 145 },
|
||||
{ key: 'unitType', label: '实物类型', slotName: 'unitType', width: 90 },
|
||||
{ prop: 'unitCode', label: '实物编码', minWidth: 160 },
|
||||
{ key: 'trackingNo', label: '快递单号', slotName: 'trackingNo', minWidth: 140 },
|
||||
{ key: 'startedBy', label: '开始方式', slotName: 'startedBy', width: 100 },
|
||||
{ prop: 'receivedQuantity', label: '实收', width: 80 },
|
||||
{ prop: 'boxCount', label: '箱数', width: 70 },
|
||||
{ key: 'signedAt', label: '签收时间', slotName: 'signedAt', minWidth: 165 },
|
||||
]
|
||||
interface SkuDraft { id: number; skuCode: string; productNameZh: string; expectedQuantity: number }
|
||||
let skuSequence = 0
|
||||
@@ -172,6 +175,33 @@ function previewPhoto(fileId: string | number) {
|
||||
const url = photoUrls[String(fileId)]
|
||||
if (url) window.open(url, '_blank', 'noopener')
|
||||
}
|
||||
async function printReturnLabel(receipt: ReturnReceipt) {
|
||||
if (!receipt.cartonMark) return
|
||||
const popup = window.open('', '_blank')
|
||||
if (!popup) { ElMessage.warning('请允许浏览器打开打印窗口'); return }
|
||||
popup.opener = null
|
||||
try {
|
||||
const labels = receipt.labels?.length
|
||||
? receipt.labels
|
||||
: [{ cartonMark: receipt.cartonMark, printableHtml: receipt.printableHtml || (await getReturnInventoryLabel(receipt.cartonMark)).printableHtml }]
|
||||
const printStyle = '<style>@page{size:100mm 100mm;margin:8mm}*{box-sizing:border-box}html,body{margin:0;background:#fff;color:#111;font-family:Arial,\'Microsoft YaHei\',sans-serif}.label{width:84mm;height:84mm;padding:8mm;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;page-break-after:always}.label:last-child{page-break-after:auto}.mark{font:800 18px Arial,sans-serif;line-height:1.15;word-break:break-all;margin:0 0 6mm}.barcode{width:84mm;margin:0 0 5mm}.barcode svg{display:block;width:100%;height:auto}.line{display:flex;justify-content:center;align-items:baseline;width:100%;padding:2mm 0;font-size:15px}.sku{max-width:84mm;overflow-wrap:anywhere;font-weight:700}</style>'
|
||||
const printableHtml = `<!doctype html><html><head><meta charset="utf-8"><title>退货箱唛</title>${printStyle}</head><body>${labels.map((label) => {
|
||||
const html = label.printableHtml || ''
|
||||
const bodyStart = html.indexOf('<body')
|
||||
const contentStart = bodyStart < 0 ? 0 : html.indexOf('>', bodyStart) + 1
|
||||
const bodyEnd = html.lastIndexOf('</body>')
|
||||
return contentStart > 0 && bodyEnd > contentStart ? html.slice(contentStart, bodyEnd) : html
|
||||
}).join('')}</body></html>`
|
||||
popup.document.open()
|
||||
popup.document.write(printableHtml)
|
||||
popup.document.close()
|
||||
popup.focus()
|
||||
popup.print()
|
||||
} catch (error) {
|
||||
popup.close()
|
||||
ElMessage.error(error instanceof Error ? error.message : '箱唛加载失败')
|
||||
}
|
||||
}
|
||||
function openDetail(returnNo: string) { void router.push({ name: 'overseas-return-relabel-detail', params: { returnNo } }) }
|
||||
function returnToList() { void router.push({ name: 'overseas-return-relabel' }) }
|
||||
function cancelCreate() { resetForm(); void router.push({ name: 'overseas-return-relabel' }) }
|
||||
@@ -187,8 +217,9 @@ async function submit() {
|
||||
creating.value = true
|
||||
try {
|
||||
const payload = { overseasWarehouseId: form.overseasWarehouseId, warehouseContactName: form.warehouseContactName.trim(), warehouseContactPhone: form.warehouseContactPhone.trim(), customerReferenceNo: form.customerReferenceNo || undefined, remark: form.remark || undefined, needRelabel: form.needRelabel, idempotencyKey: createIdempotencyKey(), items: items.map(item => ({ ...item, productNameZh: item.productNameZh || undefined })) }
|
||||
const detail = editingReturnNo.value ? await updateReturnOrder(editingReturnNo.value, payload) : await createReturnOrder(payload)
|
||||
ElMessage.success(editingReturnNo.value ? '退货预报已更新' : '退货预报已创建'); showCreate.value = false; editingReturnNo.value = ''; resetForm(); await router.push({ name: 'overseas-return-relabel-detail', params: { returnNo: detail.order.returnNo } })
|
||||
if (editingReturnNo.value) await updateReturnOrder(editingReturnNo.value, payload)
|
||||
else await createReturnOrder(payload)
|
||||
ElMessage.success(editingReturnNo.value ? '退货预报已更新' : '退货预报已创建'); showCreate.value = false; editingReturnNo.value = ''; resetForm(); await router.push({ name: 'overseas-return-relabel' })
|
||||
} finally { creating.value = false }
|
||||
}
|
||||
function statusType(status: string, needRelabel = false) {
|
||||
@@ -315,9 +346,9 @@ onBeforeUnmount(clearPhotoUrls)
|
||||
<section class="return-detail-section">
|
||||
<h3>换标子单({{ selected.order.relabelApplications?.length || 0 }})</h3>
|
||||
<el-table :data="selected.order.relabelApplications || []" empty-text="暂无换标申请">
|
||||
<el-table-column prop="relabelNo" label="换标单号" min-width="220" />
|
||||
<el-table-column label="状态" min-width="130"><template #default="{ row }"><el-tag :type="relabelStatusType(row.status)">{{ relabelStatusLabel(row.status) }}</el-tag></template></el-table-column>
|
||||
<el-table-column prop="quantity" label="本次换标数量(件)" min-width="160" />
|
||||
<el-table-column prop="relabelNo" label="换标单号" min-width="180" />
|
||||
<el-table-column label="状态" min-width="110"><template #default="{ row }"><el-tag :type="relabelStatusType(row.status)">{{ relabelStatusLabel(row.status) }}</el-tag></template></el-table-column>
|
||||
<el-table-column prop="quantity" label="本次换标数量(件)" min-width="140" />
|
||||
</el-table>
|
||||
</section>
|
||||
<section class="return-detail-section">
|
||||
@@ -325,14 +356,15 @@ onBeforeUnmount(clearPhotoUrls)
|
||||
<DataTable :data="selected.items" :columns="itemColumns" row-key="skuCode" empty-text="暂无 SKU 明细" />
|
||||
</section>
|
||||
<section class="return-detail-section">
|
||||
<h3>打托明细({{ selected.pallets?.length || 0 }} 托)</h3>
|
||||
<h3 class="section-heading-with-action"><span>实物明细({{ selected.pallets?.length || 0 }} 个托盘/箱)</span><span v-if="selected.receipts?.some(item => item.unitType !== 'PARCEL' && item.cartonMark)" class="return-label-actions"><el-button v-for="receipt in selected.receipts.filter(item => item.unitType !== 'PARCEL' && item.cartonMark)" :key="receipt.receiptNo" type="primary" size="small" @click="printReturnLabel(receipt)">打印全部箱唛({{ receipt.labels?.length || receipt.boxCount || 1 }} 箱)</el-button></span></h3>
|
||||
<el-collapse v-if="selected.pallets?.length" class="return-pallet-list">
|
||||
<el-collapse-item v-for="pallet in selected.pallets" :key="pallet.palletCode" :name="pallet.palletCode">
|
||||
<template #title><strong>{{ pallet.palletCode }}</strong><span class="return-pallet-summary">{{ pallet.skuTypes }} 种 SKU · {{ pallet.totalQuantity }} 件</span></template>
|
||||
<template #title><strong>{{ pallet.unitType === 'BOX' ? '箱子' : '托盘' }} {{ pallet.unitCode || pallet.palletCode }}</strong><span class="return-pallet-summary">{{ pallet.skuTypes }} 种 SKU · {{ pallet.totalQuantity }} 件 · {{ pallet.totalBoxCount }} 箱</span></template>
|
||||
<el-table :data="pallet.items" size="small" border>
|
||||
<el-table-column prop="skuCode" label="SKU" min-width="180" />
|
||||
<el-table-column prop="productNameZh" label="中文品名" min-width="220"><template #default="{ row }">{{ row.productNameZh || '—' }}</template></el-table-column>
|
||||
<el-table-column prop="quantity" label="数量" width="100" />
|
||||
<el-table-column prop="skuCode" label="SKU" min-width="150" />
|
||||
<el-table-column prop="productNameZh" label="中文品名" min-width="180"><template #default="{ row }">{{ row.productNameZh || '—' }}</template></el-table-column>
|
||||
<el-table-column prop="quantity" label="数量" width="80" />
|
||||
<el-table-column prop="boxCount" label="箱数" width="80" />
|
||||
</el-table>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
@@ -352,10 +384,15 @@ onBeforeUnmount(clearPhotoUrls)
|
||||
<section class="return-detail-section">
|
||||
<h3>签收批次</h3>
|
||||
<DataTable :data="selected.receipts" :columns="receiptColumns" row-key="receiptNo" empty-text="暂无签收批次">
|
||||
<template #unitType="{ row }">{{ row.unitType === 'PALLET' ? '托盘' : row.unitType === 'BOX' ? '箱子' : '包裹' }}</template>
|
||||
<template #trackingNo="{ row }">{{ row.trackingNo || '无快递单号' }}</template>
|
||||
<template #startedBy="{ row }">{{ startedByLabel(row.startedBy) }}</template>
|
||||
<template #signedAt="{ row }">{{ formatDateTime(row.signedAt) }}</template>
|
||||
</DataTable>
|
||||
<div v-for="receipt in (selected.receipts || []).filter(item => item.unitType === 'PARCEL')" :key="`${receipt.receiptNo}-items`" class="return-parcel-items">
|
||||
<strong>包裹 {{ receipt.unitCode || receipt.trackingNo || receipt.receiptNo }} SKU 明细</strong>
|
||||
<span v-for="item in receipt.items" :key="item.skuCode">{{ item.skuCode }} × {{ item.quantity }}</span>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</article>
|
||||
@@ -388,7 +425,7 @@ onBeforeUnmount(clearPhotoUrls)
|
||||
.return-pagination-total { color:#526176; font-size:14px; }
|
||||
.return-page-size-select { width:112px; margin-left:8px; }
|
||||
.return-page-size-select :deep(.el-input__inner), .return-page-size-select :deep(.el-select__selected-item) { color:#526176 !important; opacity:1 !important; -webkit-text-fill-color:#526176; }
|
||||
.return-detail-surface { overflow:hidden; min-height:240px; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; }
|
||||
.return-detail-surface { width:min(100%, 1560px); margin:0; overflow:hidden; min-height:240px; border:1px solid var(--client-border); border-radius:8px; background:#fff; box-shadow:0 2px 10px rgba(31,45,69,.04); }
|
||||
.return-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); }
|
||||
.return-back { display:inline-flex; align-items:center; gap:5px; padding:5px 0; border:0; background:transparent; color:var(--el-color-primary); cursor:pointer; }
|
||||
.return-detail-title { display:flex; min-width:0; flex-direction:column; gap:3px; }
|
||||
@@ -396,14 +433,22 @@ onBeforeUnmount(clearPhotoUrls)
|
||||
.return-detail-title span { color:#7c899c; font-size:12px; }
|
||||
.return-detail-actions { display:flex; align-items:center; gap:8px; }
|
||||
.return-detail-section + .return-detail-section { border-top:1px solid var(--client-border); }
|
||||
.return-detail-section > h3 { min-height:40px; margin:0; padding:11px 16px 9px; color:#26364f; font-size:14px; }
|
||||
.return-detail-section > h3 { min-height:40px; margin:0; padding:9px 14px; color:#26364f; font-size:13px; }
|
||||
.section-heading-with-action { display:flex; align-items:center; justify-content:space-between; gap:12px; }
|
||||
.return-label-actions { display:flex; align-items:center; gap:6px; }
|
||||
.return-label-actions :deep(.el-button) { height:28px; margin:0; padding:0 12px; border-radius:6px; font-size:12px; box-shadow:0 2px 5px rgba(33,103,232,.14); }
|
||||
.return-detail-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); border-top:1px solid #edf1f5; }
|
||||
.return-detail-grid div { display:flex; min-width:0; min-height:48px; align-items:center; gap:10px; padding:8px 14px; border-right:1px solid #edf1f5; border-bottom:1px solid #edf1f5; }
|
||||
.return-detail-grid span,.return-detail-remark span { flex:0 0 92px; color:#8490a1; font-size:12px; }
|
||||
.return-detail-grid strong,.return-detail-remark strong { min-width:0; overflow-wrap:anywhere; color:#2c3c55; font-size:13px; }
|
||||
.return-detail-remark { display:flex; align-items:flex-start; gap:10px; padding:10px 14px; background:#f8fafc; }
|
||||
.return-detail-grid div { display:flex; min-width:0; min-height:40px; align-items:center; gap:6px; padding:6px 10px; border-right:1px solid #edf1f5; border-bottom:1px solid #edf1f5; }
|
||||
.return-detail-grid span,.return-detail-remark span { flex:0 0 82px; color:#8490a1; font-size:12px; }
|
||||
.return-detail-grid strong,.return-detail-remark strong { min-width:0; overflow-wrap:anywhere; color:#2c3c55; font-size:12px; }
|
||||
.return-detail-remark { display:flex; align-items:flex-start; gap:6px; padding:8px 10px; background:#f8fafc; }
|
||||
.return-detail-section :deep(.data-table) { border:0; border-radius:0; }
|
||||
.return-pallet-list { padding:0 16px 12px; }
|
||||
.return-detail-section :deep(.el-table) { font-size:12px; }
|
||||
.return-detail-section :deep(.el-table th.el-table__cell) { height:34px; padding:0; }
|
||||
.return-detail-section :deep(.el-table td.el-table__cell) { height:36px; padding:0; }
|
||||
.return-detail-section :deep(.el-table .cell) { padding:0 8px; line-height:18px; }
|
||||
.return-detail-section :deep(.el-table .el-tag) { font-size:12px; }
|
||||
.return-pallet-list { padding:0 14px 10px; }
|
||||
.return-pallet-summary { margin-left:12px; color:#7c899c; font-size:12px; font-weight:400; }
|
||||
.return-photo-grid { display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); gap:12px; padding:0 16px 16px; }
|
||||
.return-photo { min-width:0; overflow:hidden; padding:0; border:1px solid #dfe6ef; border-radius:6px; color:#526176; background:#fff; cursor:pointer; }
|
||||
|
||||
@@ -32,7 +32,7 @@ type ServiceType = 'labeling' | 'transfer' | 'disposal' | 'relabel'
|
||||
type PageMode = 'list' | 'create' | 'edit' | 'detail'
|
||||
type LabelingMode = 'carton' | 'sku' | 'carton_and_sku'
|
||||
type RelabelTemplateType = 'carton' | 'sku' | 'mixed'
|
||||
interface CargoRow { id: number; included?: boolean; sku: string; name: string; quantity: number; availableQuantity?: number; sourceOrderId?: string; sourceInventoryBalanceId?: string; sourceInventoryPositionId?: string; sourceInboundOrderId?: string; returnCartonId?: string; sourceInboundOrderNo?: string; sourceInboundCode?: string; sourceWarehouseName?: string; palletNo?: string; warehouseLocationCode?: string; fnsku: string; shipmentNo: string; newSkuCode: string; shippingMark: string; customerCartonMarks: string; cartonMark: string; fbaCartonMark: string; destinationWarehouseId: string; remark: string }
|
||||
interface CargoRow { id: number; included?: boolean; sku: string; name: string; quantity: number; availableQuantity?: number; sourceOrderId?: string; sourceType?: 'DROPSHIP' | 'RETURN_CARTON'; sourceInventoryBalanceId?: string; sourceInventoryPositionId?: string; sourceInboundOrderId?: string; returnCartonId?: string; sourceInboundOrderNo?: string; sourceInboundCode?: string; sourceWarehouseName?: string; palletNo?: string; warehouseLocationCode?: string; fnsku: string; shipmentNo: string; newSkuCode: string; shippingMark: string; customerCartonMarks: string; cartonMark: string; fbaCartonMark: string; destinationWarehouseId: string; remark: string }
|
||||
interface SkuRelabelRow { id: number; sourceRowId: number | null; cartonMark: string; originalSku: string; newSku: string; quantity: number; fbaCartonMark: string; destinationWarehouseId: string; remark: string }
|
||||
interface ImportedRelabelBinding extends SkuRelabelRow { templateType: RelabelTemplateType; selected: boolean; shipmentNo: string }
|
||||
interface ReturnRelabelSkuRow { skuCode: string; productNameZh: string; availableQuantity: number; selected: boolean; quantity: number }
|
||||
@@ -55,19 +55,27 @@ const canConfirmRelabel = computed(() => auth.hasPermission('merchant:overseas-w
|
||||
const canConfirmTransfer = computed(() => auth.hasPermission('merchant:overseas-warehouse:transfer:confirm'))
|
||||
const canCancelDiscard = computed(() => auth.hasPermission('merchant:overseas-warehouse:discard:cancel'))
|
||||
const configs: Record<ServiceType, ServiceConfig> = {
|
||||
labeling: { title: '贴标申请', createTitle: '新增贴标申请', numberLabel: '贴标申请单号', emptyText: '暂无贴标申请', columns: ['操作', '贴标申请单号', '客户单号', '海外操作仓', '贴标要求', 'SKU 数', '总箱数', '状态', '创建时间'] },
|
||||
transfer: { title: '仓储转运单', createTitle: '新增仓储转运单', numberLabel: '转运单号', emptyText: '暂无仓储转运订单', columns: ['操作', '转运单号', '箱数', '海外仓', 'FBA 目的仓', '入仓方式', '是否换标', '换标单号', '换标状态', '状态', '创建时间'] },
|
||||
disposal: { title: '货物废弃', createTitle: '新增货物废弃申请', numberLabel: '废弃申请单号', emptyText: '暂无货物废弃申请', columns: ['操作', '废弃申请单号', '进仓编号', '操作仓', 'SKU 汇总', '废弃数量', '预估费用', '状态', '创建时间'] },
|
||||
relabel: { title: '退货换标', createTitle: '新建退货换标单', numberLabel: '退货换标单号', emptyText: '暂无退货换标订单', columns: ['操作', '退货换标单号', '来源 FBA 仓', '目的 FBA 仓', 'SKU 汇总', '退件总数', '是否换标', '换标状态', '尾程状态', '创建时间'] },
|
||||
labeling: { title: '贴标申请', createTitle: '新增贴标申请', numberLabel: '贴标申请单号', emptyText: '暂无贴标申请', columns: ['操作', '贴标申请单号', '客户单号', '海外操作仓', '贴标要求', 'SKU 数', '总箱数', '状态', '审核时间', '贴标完成时间', '贴标出库时间', '创建时间'] },
|
||||
transfer: { title: '仓储转运单', createTitle: '新增仓储转运单', numberLabel: '转运单号', emptyText: '暂无仓储转运订单', columns: ['操作', '转运单号', '箱数', '海外仓', 'FBA 目的仓', '入仓方式', '是否换标', '换标单号', '换标状态', '状态', '审核时间', '测量时间', '出库时间', '创建时间'] },
|
||||
disposal: { title: '货物废弃', createTitle: '新增货物废弃申请', numberLabel: '废弃申请单号', emptyText: '暂无货物废弃申请', columns: ['操作', '废弃申请单号', '废弃出库单号', '进仓编号', '操作仓', 'SKU 汇总', '废弃数量', '预估费用', '状态', '废弃完成时间', '创建时间'] },
|
||||
relabel: { title: '退货换标', createTitle: '新建退货换标单', numberLabel: '退货换标单号', emptyText: '暂无退货换标订单', columns: ['操作', '退货换标单号', '来源 FBA 仓', '目的 FBA 仓', 'SKU 汇总', '退件总数', '是否换标', '换标状态', '尾程状态', '审核时间', '测量时间', '出库时间', '创建时间'] },
|
||||
}
|
||||
const config = computed(() => configs[props.service])
|
||||
const listQueryModel = computed<QueryModel>({
|
||||
get: () => ({ ...filters, createdDates: [filters.start, filters.end].filter(Boolean) }),
|
||||
get: () => ({ ...filters, createdDates: [filters.start, filters.end].filter(Boolean), reviewDates: [filters.reviewStart, filters.reviewEnd].filter(Boolean), completedDates: [filters.completedStart, filters.completedEnd].filter(Boolean), measuredDates: [filters.measuredStart, filters.measuredEnd].filter(Boolean), outboundDates: [filters.outboundStart, filters.outboundEnd].filter(Boolean) }),
|
||||
set: (value) => Object.assign(filters, {
|
||||
number: String(value.number || ''), inboundNo: String(value.inboundNo || ''), warehouse: String(value.warehouse || ''),
|
||||
destination: String(value.destination || ''), status: String(value.status || ''),
|
||||
start: Array.isArray(value.createdDates) ? String(value.createdDates[0] || '') : '',
|
||||
end: Array.isArray(value.createdDates) ? String(value.createdDates[1] || '') : '',
|
||||
reviewStart: Array.isArray(value.reviewDates) ? String(value.reviewDates[0] || '') : '',
|
||||
reviewEnd: Array.isArray(value.reviewDates) ? String(value.reviewDates[1] || '') : '',
|
||||
completedStart: Array.isArray(value.completedDates) ? String(value.completedDates[0] || '') : '',
|
||||
completedEnd: Array.isArray(value.completedDates) ? String(value.completedDates[1] || '') : '',
|
||||
measuredStart: Array.isArray(value.measuredDates) ? String(value.measuredDates[0] || '') : '',
|
||||
measuredEnd: Array.isArray(value.measuredDates) ? String(value.measuredDates[1] || '') : '',
|
||||
outboundStart: Array.isArray(value.outboundDates) ? String(value.outboundDates[0] || '') : '',
|
||||
outboundEnd: Array.isArray(value.outboundDates) ? String(value.outboundDates[1] || '') : '',
|
||||
}),
|
||||
})
|
||||
const statusOptions = computed(() => props.service === 'labeling'
|
||||
@@ -84,7 +92,7 @@ const statusOptions = computed(() => props.service === 'labeling'
|
||||
{ label: '审核驳回', value: 'REJECTED' }]
|
||||
: [{ label: '待审核', value: 'PENDING_REVIEW' }, { label: '已通过', value: 'APPROVED' }, { label: '待分配', value: 'PENDING_ASSIGNMENT' }, { label: '已分配', value: 'ALLOCATED' }, { label: '已出库', value: 'OUTBOUNDED' }, { label: '部分收货', value: 'PARTIALLY_RECEIVED' }, { label: '已收货', value: 'RECEIVED' }, { label: '已拒绝', value: 'REJECTED' }])
|
||||
const mode = ref<PageMode>(props.detailPage ? 'detail' : props.createPage ? 'create' : 'list')
|
||||
const filters = reactive({ number: '', inboundNo: '', warehouse: '', destination: '', status: '', start: '', end: '' })
|
||||
const filters = reactive({ number: '', inboundNo: '', warehouse: '', destination: '', status: '', start: '', end: '', reviewStart: '', reviewEnd: '', completedStart: '', completedEnd: '', measuredStart: '', measuredEnd: '', outboundStart: '', outboundEnd: '' })
|
||||
const form = reactive({ customerNo: '', inboundNo: '', sourceWarehouse: '', warehouse: '', destination: '', privateDestinationAddress: '', privateDestinationPostalCode: '', privateDestinationContact: '', privateDestinationPhone: '', address: '', contact: '', phone: '', pickupContact: '', pickupPhone: '', relabelContact: '', relabelPhone: '', deliveryMethod: '', relabelDeliveryMethod: '', trackingNo: '', reason: '', requirement: '', relabel: false, remark: '', labelDeadline: '', estimatedArrivalAt: '', estimatedShipAt: '', fbaShipmentNo: '', volumeCbm: 0.01 })
|
||||
const transferDestinationType = ref<'NONE' | 'FBA' | 'PRIVATE'>('NONE')
|
||||
const selectedOperationWarehouse = ref<MerchantWarehouseDetail | null>(null)
|
||||
@@ -120,6 +128,7 @@ interface ServiceDetail extends Record<string, unknown> {
|
||||
remark?: string; needRelabel?: boolean; labelDeadline?: string; relabelContactName?: string
|
||||
relabelContactPhone?: string; relabelDeliveryMethod?: string; relabelNo?: string
|
||||
relabelStatus?: string; relabelFulfillmentStatus?: string; createdAt?: string
|
||||
inboundCode?: string; sourceOrders?: Array<{ lastlegOrderId?: string | number }>
|
||||
items?: Array<{ skuCode?: string; productNameZh?: string; packageCount?: number; shippingMark?: string }>
|
||||
relabelBindings?: Array<{ operationType?: string; customerCartonMark?: string; originalSku?: string; newSku?: string; quantity?: number; fbaCartonMark?: string; destinationWarehouseCode?: string; remark?: string }>
|
||||
cartons?: TransferCarton[]; pallets?: TransferPallet[]; measurementPhotos?: TransferMeasurementPhoto[]; customerConfirmedAt?: string
|
||||
@@ -152,9 +161,22 @@ const listQueryFields = computed<QueryField[]>(() => {
|
||||
options: (props.service === 'relabel' ? fbaWarehouses.value : operationWarehouses.value).map((warehouse) => ({ label: warehouseLabel(warehouse), value: String(warehouse.id) })),
|
||||
})
|
||||
if (props.service === 'transfer' || props.service === 'relabel') fields.push({ key: 'destination', label: '目的 FBA 仓', type: 'input', placeholder: '请输入仓代码' })
|
||||
fields.push(
|
||||
{ key: 'status', label: '订单状态', type: 'select', options: statusOptions.value },
|
||||
{ key: 'createdDates', label: '创建时间', type: 'daterange' },
|
||||
fields.push({ key: 'status', label: '订单状态', type: 'select', options: statusOptions.value })
|
||||
fields.push({ key: 'createdDates', label: '创建时间', type: 'daterange' })
|
||||
if (props.service === 'labeling') fields.push(
|
||||
{ key: 'reviewDates', label: '审核时间', type: 'daterange' },
|
||||
{ key: 'completedDates', label: '贴标完成时间', type: 'daterange' },
|
||||
{ key: 'outboundDates', label: '贴标出库时间', type: 'daterange' },
|
||||
)
|
||||
if (props.service === 'relabel') fields.push(
|
||||
{ key: 'reviewDates', label: '审核时间', type: 'daterange' },
|
||||
{ key: 'measuredDates', label: '测量时间', type: 'daterange' },
|
||||
{ key: 'outboundDates', label: '出库时间', type: 'daterange' },
|
||||
)
|
||||
if (props.service === 'transfer') fields.push(
|
||||
{ key: 'reviewDates', label: '审核时间', type: 'daterange' },
|
||||
{ key: 'completedDates', label: '测量时间', type: 'daterange' },
|
||||
{ key: 'outboundDates', label: '出库时间', type: 'daterange' },
|
||||
)
|
||||
return fields
|
||||
})
|
||||
@@ -170,7 +192,9 @@ const selectedRelabelInboundOrderId = ref('')
|
||||
const relabelCandidatesLoading = ref(false)
|
||||
const transferInventoryCandidates = ref<RelabelInventoryCandidate[]>([])
|
||||
const selectedTransferInventory = ref('')
|
||||
const selectedTransferSourceOrderIds = ref<number[]>([])
|
||||
// Snowflake IDs exceed JavaScript's safe integer range. Keep them as strings
|
||||
// all the way to JSON so the backend receives the exact source order ID.
|
||||
const selectedTransferSourceOrderIds = ref<string[]>([])
|
||||
const returnRelabelSkuRows = ref<ReturnRelabelSkuRow[]>([])
|
||||
const isReturnRelabelSource = computed(() => props.service === 'labeling' && selectedRelabelInboundOrderId.value.startsWith('RETURN_ORDER:'))
|
||||
const selectedReturnOrderNo = computed(() => isReturnRelabelSource.value ? selectedRelabelInboundOrderId.value.slice('RETURN_ORDER:'.length) : '')
|
||||
@@ -267,7 +291,7 @@ onMounted(() => {
|
||||
void nextTick(refreshWarehouseMarkLabels)
|
||||
})
|
||||
onBeforeUnmount(() => { clearCompletionPhotos(); clearMeasurementPhotos() })
|
||||
function resetFilters() { Object.assign(filters, { number: '', inboundNo: '', warehouse: '', destination: '', status: '', start: '', end: '' }) }
|
||||
function resetFilters() { Object.assign(filters, { number: '', inboundNo: '', warehouse: '', destination: '', status: '', start: '', end: '', reviewStart: '', reviewEnd: '', completedStart: '', completedEnd: '', measuredStart: '', measuredEnd: '', outboundStart: '', outboundEnd: '' }) }
|
||||
function resetForm() {
|
||||
Object.assign(form, { customerNo: '', inboundNo: '', sourceWarehouse: '', warehouse: '', destination: '', privateDestinationAddress: '', privateDestinationPostalCode: '', privateDestinationContact: '', privateDestinationPhone: '', address: '', contact: '', phone: '', pickupContact: '', pickupPhone: '', relabelContact: '', relabelPhone: '', deliveryMethod: '', relabelDeliveryMethod: '', trackingNo: '', reason: '', requirement: '', relabel: false, remark: '', labelDeadline: '', estimatedArrivalAt: '', estimatedShipAt: '', fbaShipmentNo: '', volumeCbm: 0.01 })
|
||||
cargoRows.value = []
|
||||
@@ -314,19 +338,21 @@ async function openCreate() {
|
||||
|
||||
function returnToList() {
|
||||
if (props.createPage || props.detailPage) {
|
||||
const routeName = ({ labeling: 'overseas-labeling', transfer: 'overseas-storage-transfer', disposal: 'overseas-cargo-disposal', relabel: 'overseas-return-relabel' } as Record<ServiceType, string>)[props.service]
|
||||
void router.push({ name: routeName })
|
||||
void router.push({ name: serviceListRouteName(props.service) })
|
||||
return
|
||||
}
|
||||
mode.value = 'list'
|
||||
}
|
||||
function serviceListRouteName(service: ServiceType) {
|
||||
return ({ labeling: 'overseas-labeling', transfer: 'overseas-storage-transfer', disposal: 'overseas-cargo-disposal', relabel: 'overseas-return-relabel' } as Record<ServiceType, string>)[service]
|
||||
}
|
||||
|
||||
async function openEdit(transferNo: string) {
|
||||
try {
|
||||
resetForm()
|
||||
await loadWarehouses()
|
||||
const detail = await getTransfer(transferNo) as ServiceDetail
|
||||
if (detail.status !== 'DRAFT') throw new Error('只有草稿状态的转运单可以编辑')
|
||||
if (!['DRAFT', 'REJECTED'].includes(detail.status || '')) throw new Error('只有草稿或审核驳回状态的转运单可以编辑')
|
||||
editingTransferNo.value = transferNo
|
||||
Object.assign(form, {
|
||||
warehouse: detail.operatingWarehouseId || '', destination: detail.destinationWarehouseCode || detail.fbaWarehouseCode || '',
|
||||
@@ -362,6 +388,20 @@ async function openEdit(transferNo: string) {
|
||||
if (form.warehouse) {
|
||||
try { selectedOperationWarehouse.value = await getMerchantWarehouseDetail(form.warehouse) } catch { selectedOperationWarehouse.value = null }
|
||||
}
|
||||
// The warehouse selector loads inventory candidates for a new transfer, but
|
||||
// edit mode starts with an already populated warehouse and never emits the
|
||||
// selector change event. Load the same candidates explicitly so the source
|
||||
// inventory dropdown is usable when editing a draft.
|
||||
if (props.service === 'transfer' && form.warehouse) {
|
||||
await loadTransferInventoryCandidates(form.warehouse)
|
||||
const sourceInboundCode = String(detail.inboundCode || '')
|
||||
if (transferInventoryOptions.value.some((option) => option.value === sourceInboundCode)) {
|
||||
selectedTransferInventory.value = sourceInboundCode
|
||||
form.inboundNo = sourceInboundCode
|
||||
selectedTransferSourceOrderIds.value = (detail.sourceOrders || [])
|
||||
.map((item) => String(item.lastlegOrderId || '')).filter(Boolean)
|
||||
}
|
||||
}
|
||||
mode.value = 'edit'
|
||||
} catch (error) { ElMessage.error(error instanceof Error ? error.message : '草稿加载失败') }
|
||||
}
|
||||
@@ -375,11 +415,25 @@ async function selectDiscardWarehouse() {
|
||||
discardCandidatesLoading.value = true
|
||||
try {
|
||||
const inventory = await listRelabelInventoryCandidates(form.warehouse)
|
||||
const orderByInbound = new Map<string, string>()
|
||||
const inboundCodes = [...new Set(inventory.map((candidate) => String(candidate.inboundCode || '')).filter(Boolean))]
|
||||
const historicalGroups = await Promise.all(inboundCodes.map(async (inboundCode) => ({ inboundCode, orders: await listRelabelHistoricalOrders(form.warehouse, inboundCode) })))
|
||||
for (const { inboundCode, orders } of historicalGroups) {
|
||||
for (const order of orders) {
|
||||
if (order.id) orderByInbound.set(inboundCode, String(order.id))
|
||||
}
|
||||
}
|
||||
const grouped = new Map<string, import('../api/warehouseServices').DiscardCandidate>()
|
||||
for (const candidate of inventory) {
|
||||
const orderId = String(candidate.inboundOrderId || '')
|
||||
if (!orderId) continue
|
||||
const current = grouped.get(orderId) || { orderId, inboundCode: candidate.inboundCode || '', inboundOrderNo: candidate.inboundOrderNo || '', overseasWarehouseId: String(candidate.overseasWarehouseId || form.warehouse), overseasWarehouseName: candidate.overseasWarehouseName || '', availablePackages: 0, skus: [] }
|
||||
const returnCartonId = String(candidate.returnCartonId || '')
|
||||
const sourceType = candidate.sourceType === 'RETURN_CARTON' ? 'RETURN_CARTON' : 'DROPSHIP'
|
||||
const inboundCode = String(candidate.inboundCode || '')
|
||||
const orderId = sourceType === 'RETURN_CARTON' ? `return:${returnCartonId}` : (orderByInbound.get(inboundCode) || '')
|
||||
if (!orderId || (sourceType === 'RETURN_CARTON' && !returnCartonId)) continue
|
||||
const current = grouped.get(orderId) || { orderId, inboundCode, inboundOrderNo: candidate.inboundOrderNo || '', overseasWarehouseId: String(candidate.overseasWarehouseId || form.warehouse), overseasWarehouseName: candidate.overseasWarehouseName || '', availablePackages: 0, skus: [] }
|
||||
current.sourceType = sourceType
|
||||
current.returnCartonId = returnCartonId || undefined
|
||||
current.cartonMark = candidate.cartonMark || undefined
|
||||
const packages = inventoryQuantity(candidate.availablePackages)
|
||||
current.availablePackages += packages
|
||||
const skuCode = String(candidate.skuCode || '').trim()
|
||||
@@ -741,12 +795,13 @@ function importSelectedBindingsToDetails() {
|
||||
function selectDiscardInbound(orderId: string) {
|
||||
const candidate = discardCandidates.value.find((item) => item.orderId === orderId)
|
||||
if (!candidate) { cargoRows.value = []; return }
|
||||
form.inboundNo = candidate.inboundCode
|
||||
form.inboundNo = candidate.inboundCode || candidate.inboundOrderNo
|
||||
form.warehouse = candidate.overseasWarehouseId
|
||||
cargoRows.value = candidate.skus.map((sku) => ({
|
||||
id: ++cargoSequence, sku: sku.skuCode, name: sku.productName, quantity: 0,
|
||||
availableQuantity: sku.availablePackages, sourceOrderId: candidate.orderId,
|
||||
fnsku: '', shipmentNo: '', newSkuCode: '', shippingMark: '', customerCartonMarks: '', cartonMark: '', fbaCartonMark: '', destinationWarehouseId: '', remark: '',
|
||||
availableQuantity: sku.availablePackages, sourceOrderId: candidate.orderId, sourceType: candidate.sourceType,
|
||||
returnCartonId: candidate.returnCartonId, cartonMark: candidate.cartonMark || '',
|
||||
fnsku: '', shipmentNo: '', newSkuCode: '', shippingMark: '', customerCartonMarks: '', fbaCartonMark: '', destinationWarehouseId: '', remark: '',
|
||||
}))
|
||||
}
|
||||
function dateTime(value: string, end = false) { return value ? `${value}T${end ? '23:59:59' : '00:00:00'}` : undefined }
|
||||
@@ -755,7 +810,7 @@ function warehouseDisplay(value?: string) {
|
||||
if (!value) return '—'
|
||||
return value.split(',').map((code) => {
|
||||
const warehouse = [...operationWarehouses.value, ...fbaWarehouses.value].find((item) => String(item.id) === code || item.warehouseCode === code)
|
||||
return warehouse ? warehouseLabel(warehouse) : code
|
||||
return warehouse ? warehouseLabel(warehouse) : '—'
|
||||
}).join('、')
|
||||
}
|
||||
function statusLabel(value: string) {
|
||||
@@ -860,25 +915,25 @@ async function load() {
|
||||
loading.value = true
|
||||
try {
|
||||
if (props.service === 'labeling') {
|
||||
const result = await listRelabels({ page: page.value, size: pageSize.value, relabelNo: filters.number || undefined, overseasWarehouseId: filters.warehouse || undefined, status: filters.status || undefined, createdFrom: dateTime(filters.start), createdTo: dateTime(filters.end, true) })
|
||||
const result = await listRelabels({ page: page.value, size: pageSize.value, relabelNo: filters.number || undefined, overseasWarehouseId: filters.warehouse || undefined, status: filters.status || undefined, createdFrom: dateTime(filters.start), createdTo: dateTime(filters.end, true), reviewedFrom: dateTime(filters.reviewStart), reviewedTo: dateTime(filters.reviewEnd, true), completedFrom: dateTime(filters.completedStart), completedTo: dateTime(filters.completedEnd, true), outboundFrom: dateTime(filters.outboundStart), outboundTo: dateTime(filters.outboundEnd, true) })
|
||||
total.value = Number.isFinite(Number(result.total)) ? Number(result.total) : result.records.length
|
||||
submittedRows.value = result.records.map((item) => {
|
||||
const destinationWarehouses = warehouseDisplay(item.overseasWarehouseId)
|
||||
return { ...row([item.relabelNo, item.customerOrderNo, destinationWarehouses, '—', item.itemCount, item.totalPackageCount, statusLabel(item.status), formatDateTime(item.createdAt)]), __status: item.status, __confirmedAt: item.customerConfirmedAt || '' }
|
||||
return { ...row([item.relabelNo, item.customerOrderNo, destinationWarehouses, '—', item.itemCount, item.totalPackageCount, statusLabel(item.status), formatDateTime(item.reviewedAt), formatDateTime(item.relabelCompletedAt), formatDateTime(item.outboundAt), formatDateTime(item.createdAt)]), __status: item.status, __confirmedAt: item.customerConfirmedAt || '' }
|
||||
})
|
||||
} else if (props.service === 'disposal') {
|
||||
const result = await listDiscards({ page: page.value, size: pageSize.value, discardNo: filters.number || undefined, inboundCode: filters.inboundNo || undefined, overseasWarehouseId: filters.warehouse || undefined, status: filters.status || undefined, createdFrom: dateTime(filters.start), createdTo: dateTime(filters.end, true) })
|
||||
const result = await listDiscards({ page: page.value, size: pageSize.value, discardNo: filters.number || undefined, inboundCode: filters.inboundNo || undefined, overseasWarehouseId: filters.warehouse || undefined, status: filters.status || undefined, createdFrom: dateTime(filters.start), createdTo: dateTime(filters.end, true), completedFrom: dateTime(filters.completedStart), completedTo: dateTime(filters.completedEnd, true) })
|
||||
total.value = Number.isFinite(Number(result.total)) ? Number(result.total) : result.records.length
|
||||
submittedRows.value = result.records.map((item) => row([item.discardNo, item.inboundCodes, item.overseasWarehouseName || '—', '—', item.totalPackages, `${item.currency} ${item.totalFee}`, statusLabel(item.status), formatDateTime(item.createdAt)]))
|
||||
submittedRows.value = result.records.map((item) => row([item.discardNo, item.outboundNo || '—', item.inboundCodes, item.overseasWarehouseName || warehouseDisplay(item.overseasWarehouseId) || '—', '—', item.totalPackages, `${item.currency} ${item.totalFee}`, statusLabel(item.status), formatDateTime(item.completedAt), formatDateTime(item.createdAt)]))
|
||||
} else {
|
||||
const result = await listTransfers({ page: page.value, size: pageSize.value, transferNo: filters.number || undefined, inboundCode: filters.inboundNo || undefined, operatingWarehouseId: filters.warehouse || undefined, fbaWarehouseCode: filters.destination || undefined, status: filters.status || undefined, ...(props.service === 'relabel' ? { needRelabel: true } : {}), createdFrom: dateTime(filters.start), createdTo: dateTime(filters.end, true) })
|
||||
const result = await listTransfers({ page: page.value, size: pageSize.value, transferNo: filters.number || undefined, inboundCode: filters.inboundNo || undefined, operatingWarehouseId: filters.warehouse || undefined, fbaWarehouseCode: filters.destination || undefined, status: filters.status || undefined, ...(props.service === 'relabel' ? { needRelabel: true } : {}), createdFrom: dateTime(filters.start), createdTo: dateTime(filters.end, true), reviewedFrom: dateTime(filters.reviewStart), reviewedTo: dateTime(filters.reviewEnd, true), measuredFrom: props.service === 'relabel' ? dateTime(filters.measuredStart) : dateTime(filters.completedStart), measuredTo: props.service === 'relabel' ? dateTime(filters.measuredEnd, true) : dateTime(filters.completedEnd, true), outboundFrom: dateTime(filters.outboundStart), outboundTo: dateTime(filters.outboundEnd, true) })
|
||||
total.value = Number.isFinite(Number(result.total)) ? Number(result.total) : result.records.length
|
||||
submittedRows.value = result.records.map((item) => {
|
||||
const operationWarehouse = warehouseDisplay(item.operatingWarehouseId)
|
||||
const relabelStatus = transferRelabelStatus(item)
|
||||
return props.service === 'transfer'
|
||||
? { ...row([item.transferNo, item.packageCount, operationWarehouse, item.fbaWarehouseCode, deliveryMethodLabel(item.deliveryMethod), item.needRelabel ? '是' : '否', item.relabelNo, relabelStatus.label, statusLabel(item.status), formatDateTime(item.createdAt)]), __status: item.status, __statusLabel: statusLabel(item.status), __relabelStatus: relabelStatus.code, __relabelStatusLabel: relabelStatus.label }
|
||||
: row([item.transferNo, '—', item.fbaWarehouseCode, '—', item.packageCount, '是', item.relabelNo ? '已生成' : '待生成', statusLabel(item.status), formatDateTime(item.createdAt)])
|
||||
? { ...row([item.transferNo, item.packageCount, operationWarehouse, item.fbaWarehouseCode, deliveryMethodLabel(item.deliveryMethod), item.needRelabel ? '是' : '否', item.relabelNo, relabelStatus.label, statusLabel(item.status), formatDateTime(item.reviewedAt), formatDateTime(item.measuredAt), formatDateTime(item.outboundAt), formatDateTime(item.createdAt)]), __status: item.status, __statusLabel: statusLabel(item.status), __relabelStatus: relabelStatus.code, __relabelStatusLabel: relabelStatus.label }
|
||||
: row([item.transferNo, '—', item.fbaWarehouseCode, '—', item.packageCount, '是', item.relabelNo ? '已生成' : '待生成', statusLabel(item.status), formatDateTime(item.reviewedAt), formatDateTime(item.measuredAt), formatDateTime(item.outboundAt), formatDateTime(item.createdAt)])
|
||||
})
|
||||
}
|
||||
} catch (error) { submittedRows.value = []; total.value = 0; ElMessage.error(error instanceof Error ? error.message : '列表加载失败') }
|
||||
@@ -889,7 +944,7 @@ function resetListQuery() { resetFilters(); query() }
|
||||
function listRowActions(candidate: object): TableAction[] {
|
||||
const item = candidate as Record<string, string>
|
||||
const actions: TableAction[] = [{ key: 'detail', label: '详情', run: () => openDetail(item) }]
|
||||
if (canCreate.value && props.service === 'transfer' && item.__status === 'DRAFT') actions.push({ key: 'edit', label: '编辑', run: () => openEdit(item['0']) })
|
||||
if (canCreate.value && props.service === 'transfer' && ['DRAFT', 'REJECTED'].includes(item.__status)) actions.push({ key: 'edit', label: '编辑', run: () => openEdit(item['0']) })
|
||||
if (canConfirmTransfer.value && props.service === 'transfer' && item.__status === 'WAIT_CUSTOMER_CONFIRMATION') actions.push({ key: 'confirm-measurement', label: '确认测量', run: () => confirmTransferFromList(item['0']) })
|
||||
if (canConfirmRelabel.value && props.service === 'labeling' && item.__status === 'CUSTOMER_CONFIRM_PENDING' && !item.__confirmedAt) actions.push({ key: 'confirm-relabel', label: '确认换标', run: () => confirmRelabelFromList(item['0']) })
|
||||
return actions
|
||||
@@ -980,9 +1035,6 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
||||
if (props.service === 'transfer' && transferDestinationType.value === 'FBA' && !form.destination) {
|
||||
ElMessage.warning('请选择 FBA 目的仓'); return
|
||||
}
|
||||
if (props.service === 'transfer' && transferDestinationType.value === 'NONE') {
|
||||
ElMessage.warning('请选择 FBA 仓或私人仓'); return
|
||||
}
|
||||
if (props.service === 'transfer' && transferDestinationType.value === 'PRIVATE' && (!form.privateDestinationAddress || !form.privateDestinationPostalCode || !form.privateDestinationContact || !form.privateDestinationPhone)) {
|
||||
ElMessage.warning('请完整填写私人仓地址、邮编、联系人和电话'); return
|
||||
}
|
||||
@@ -1018,20 +1070,22 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
||||
if (shippingLabelFile.value) await uploadRelabelShippingLabel(created.application.relabelNo, shippingLabelFile.value)
|
||||
} catch (error) {
|
||||
// Creation already committed: return to the list even when an attachment still needs retrying.
|
||||
if (props.createPage) await router.push({ name: 'overseas-labeling' })
|
||||
if (props.createPage) await router.push({ name: serviceListRouteName(props.service) })
|
||||
else { mode.value = 'list'; await load(); await openDetail({ '0': created.application.relabelNo }) }
|
||||
await ElMessageBox.alert(`申请 ${created.application.relabelNo} 已创建,部分附件上传失败:${error instanceof Error ? error.message : '上传失败'}。请在原单详情补传失败附件,不要重复下单。`, '申请已创建,附件待补传', { confirmButtonText: '知道了' })
|
||||
return
|
||||
}
|
||||
ElMessage.success(`${config.value.title}提交成功`)
|
||||
await router.push({ name: 'overseas-labeling' })
|
||||
await router.push({ name: serviceListRouteName(props.service) })
|
||||
return
|
||||
} else if (props.service === 'disposal') {
|
||||
const items = cargoRows.value.filter((item) => item.quantity > 0).map((item) => {
|
||||
if (!item.sourceOrderId || item.sourceOrderId !== selectedDiscardOrderId.value || item.quantity > Number(item.availableQuantity || 0)) {
|
||||
throw new Error(`SKU ${item.sku} 的可废弃库存不足`)
|
||||
}
|
||||
return { orderId: item.sourceOrderId, skuCode: item.sku, discardPackages: item.quantity }
|
||||
return { orderId: item.sourceType === 'RETURN_CARTON' ? undefined : item.sourceOrderId,
|
||||
returnCartonId: item.sourceType === 'RETURN_CARTON' ? item.returnCartonId : undefined,
|
||||
skuCode: item.sku, discardPackages: item.quantity }
|
||||
})
|
||||
await createDiscard({ items, idempotencyKey, remark: [form.reason, form.remark].filter(Boolean).join(';') || undefined })
|
||||
} else {
|
||||
@@ -1057,7 +1111,7 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
||||
if (!relabelNo) {
|
||||
ElMessage.success('转运单已提交审核;PDA 入库确认后将自动生成关联换标单')
|
||||
await ElMessageBox.alert(`转运单 ${transferNo} 已提交。关联换标单会在 PDA 完成入库、客户确认实测库存后自动生成;届时请进入关联换标单详情上传贴标总文件。`, '转运单已提交', { confirmButtonText: '知道了' })
|
||||
await openDetail({ '0': transferNo })
|
||||
await router.push({ name: serviceListRouteName('transfer') })
|
||||
return
|
||||
}
|
||||
try {
|
||||
@@ -1070,13 +1124,12 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
||||
}
|
||||
}
|
||||
ElMessage.success('转运单已提交审核')
|
||||
await openDetail({ '0': transferNo })
|
||||
await router.push({ name: serviceListRouteName('transfer') })
|
||||
return
|
||||
}
|
||||
}
|
||||
ElMessage.success(props.service === 'transfer' ? '转运单草稿保存成功' : `${config.value.title}提交成功`)
|
||||
if (props.createPage) await router.push({ name: props.service === 'relabel' ? 'overseas-return-relabel' : 'overseas-labeling' })
|
||||
else { mode.value = 'list'; await load() }
|
||||
await router.push({ name: serviceListRouteName(props.service) })
|
||||
} catch (error) { ElMessage.error(error instanceof Error ? error.message : '提交失败') }
|
||||
finally { saving.value = false }
|
||||
}
|
||||
@@ -1220,6 +1273,16 @@ async function loadWarehouses() {
|
||||
} finally { fbaWarehousesLoading.value = false }
|
||||
}
|
||||
function warehouseLabel(value: MerchantWarehouse) { return `${value.warehouseName} · ${value.warehouseCode}` }
|
||||
async function loadTransferInventoryCandidates(warehouseId: string) {
|
||||
transferInventoryCandidates.value = []
|
||||
if (!warehouseId) return
|
||||
relabelCandidatesLoading.value = true
|
||||
try {
|
||||
transferInventoryCandidates.value = await listRelabelInventoryCandidates(warehouseId)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '当前海外仓库存来源加载失败')
|
||||
} finally { relabelCandidatesLoading.value = false }
|
||||
}
|
||||
async function selectTransferWarehouse() {
|
||||
selectedOperationWarehouse.value = null
|
||||
form.pickupContact = ''
|
||||
@@ -1235,7 +1298,7 @@ async function selectTransferWarehouse() {
|
||||
form.relabelContact = detail.warehouse.contactName || ''
|
||||
form.relabelPhone = detail.warehouse.contactPhone || ''
|
||||
if (form.deliveryMethod === 'CUSTOMER_DELIVERY') form.address = operationWarehouseAddress.value
|
||||
transferInventoryCandidates.value = await listRelabelInventoryCandidates(form.warehouse)
|
||||
await loadTransferInventoryCandidates(form.warehouse)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '中转仓联系信息加载失败')
|
||||
} finally { operationWarehouseDetailLoading.value = false }
|
||||
@@ -1264,6 +1327,7 @@ async function resubmitRejectedRelabel() {
|
||||
idempotencyKey: createIdempotencyKey(),
|
||||
})
|
||||
ElMessage.success('贴标单已重新提交审核')
|
||||
await router.push({ name: serviceListRouteName('labeling') })
|
||||
} catch (error) {
|
||||
if (error !== 'cancel' && error !== 'close') ElMessage.error(error instanceof Error ? error.message : '重新提交失败')
|
||||
}
|
||||
@@ -1302,7 +1366,7 @@ async function selectTransferInventory(value: string) {
|
||||
cargoRows.value = [...grouped.values()]
|
||||
try {
|
||||
const historical = await listRelabelHistoricalOrders(form.warehouse, value)
|
||||
const sourceIds = historical.map((item) => Number(item.id)).filter((id) => Number.isInteger(id) && id > 0)
|
||||
const sourceIds = historical.map((item) => String(item.id || '')).filter(Boolean)
|
||||
selectedTransferSourceOrderIds.value = sourceIds
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '库存来源订单加载失败')
|
||||
@@ -1405,11 +1469,11 @@ function selectRelabelInventory(inboundOrderId: string) {
|
||||
<form :class="{ 'warehouse-transfer-form': props.service === 'transfer', 'warehouse-transfer-form--relabel': props.service === 'transfer' && form.relabel }" @submit.prevent="submit('submit')">
|
||||
<div class="warehouse-card warehouse-form-section warehouse-transfer-main-card"><h3>{{ props.service === 'transfer' ? '转运信息' : props.service === 'relabel' ? '退货信息' : props.service === 'labeling' ? '订单信息' : '基础信息' }}</h3>
|
||||
<div class="warehouse-form-grid">
|
||||
<label v-if="props.service === 'disposal'" class="warehouse-span-2"><span><i>*</i>操作仓</span><el-select v-model="form.warehouse" filterable clearable :loading="fbaWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" @change="selectDiscardWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><small v-if="operationWarehousesError" class="warehouse-hint">{{ operationWarehousesError }}</small><small v-else class="warehouse-hint">请先选择本次废弃货物所在的海外仓。</small></label>
|
||||
<label v-if="props.service === 'disposal'" class="warehouse-span-2"><span><i>*</i>选择入库单</span><el-select v-model="selectedDiscardOrderId" filterable clearable :loading="discardCandidatesLoading" :disabled="!form.warehouse" no-data-text="当前海外仓暂无可废弃库存" placeholder="请先选择操作仓,再选择有可用库存的入库单" @change="selectDiscardInbound"><el-option v-for="candidate in discardCandidates" :key="candidate.orderId" :label="`${candidate.inboundOrderNo || candidate.inboundCode || '—'}|${candidate.inboundCode || '—'}|可用 ${candidate.availablePackages} 箱`" :value="candidate.orderId" /></el-select><small class="warehouse-hint">仅显示当前操作仓下一件代发中仍有可用箱数的入库单。</small></label>
|
||||
<label v-if="props.service === 'disposal'" class="warehouse-disposal-field"><span><i>*</i>操作仓</span><el-select v-model="form.warehouse" filterable clearable :loading="fbaWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" @change="selectDiscardWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><small v-if="operationWarehousesError" class="warehouse-hint">{{ operationWarehousesError }}</small><small v-else class="warehouse-hint">请先选择本次废弃货物所在的海外仓。</small></label>
|
||||
<label v-if="props.service === 'disposal'" class="warehouse-disposal-field"><span><i>*</i>选择入库单</span><el-select v-model="selectedDiscardOrderId" filterable clearable :loading="discardCandidatesLoading" :disabled="!form.warehouse" no-data-text="当前海外仓暂无可废弃库存" placeholder="请先选择操作仓,再选择有可用库存的入库单" @change="selectDiscardInbound"><el-option v-for="candidate in discardCandidates" :key="candidate.orderId" :label="candidate.sourceType === 'RETURN_CARTON' ? `退货|${candidate.inboundOrderNo || '—'}|${candidate.cartonMark || '—'}|可用 ${candidate.availablePackages}` : `${candidate.inboundOrderNo || candidate.inboundCode || '—'}|${candidate.inboundCode || '—'}|可用 ${candidate.availablePackages} 箱`" :value="candidate.orderId" /></el-select><small class="warehouse-hint">显示当前操作仓内有可用数量的普通入库库存和退货库存。</small></label>
|
||||
<label v-if="props.service === 'relabel'"><span><i>*</i>进仓编号</span><el-input v-model="form.inboundNo" placeholder="请输入已有入仓编号" /></label>
|
||||
<label v-if="props.service === 'relabel'"><span><i>*</i>来源 FBA 仓库</span><el-select v-model="form.sourceWarehouse" :loading="fbaWarehousesLoading" :disabled="Boolean(fbaWarehousesError)" placeholder="请选择平台维护的 FBA 仓"><el-option v-for="warehouse in fbaWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="warehouse.warehouseCode" /></el-select></label>
|
||||
<label v-else-if="props.service === 'disposal'"><span>进仓编号</span><el-input v-model="form.inboundNo" readonly /></label>
|
||||
<label v-else-if="props.service === 'disposal'" class="warehouse-disposal-field"><span><i>*</i>废弃原因</span><el-select v-model="form.reason" placeholder="请选择"><el-option label="客户退货" value="客户退货" /><el-option label="亚马逊移除" value="亚马逊移除" /><el-option label="残损不可售" value="残损不可售" /></el-select></label>
|
||||
<label v-else><span><i>*</i>{{ props.service === 'labeling' ? '海外操作仓(中转仓)' : props.service === 'transfer' ? '入库海外仓' : '操作仓' }}</span><el-select v-model="form.warehouse" :loading="fbaWarehousesLoading || operationWarehouseDetailLoading" :disabled="Boolean(operationWarehousesError)" clearable :placeholder="props.service === 'transfer' ? '请选择海外仓' : '请选择国外中转仓'" @change="props.service === 'labeling' ? selectOperationWarehouse() : props.service === 'transfer' && selectTransferWarehouse()"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><small v-if="operationWarehousesError" class="warehouse-hint">{{ operationWarehousesError }}</small></label>
|
||||
<label v-if="props.service === 'labeling'" class="warehouse-span-2"><span><i>*</i>选择有库存的入仓单或退货单</span><el-select v-model="selectedRelabelInboundOrderId" filterable clearable :loading="relabelCandidatesLoading" :disabled="!form.warehouse" no-data-text="当前中转仓暂无可用库存" placeholder="请选择当前仍有可用库存的入仓单或退货单" @change="selectRelabelInventory"><el-option v-for="option in relabelInboundOptions" :key="option.value" :label="`${option.inboundOrderNo}|${option.inboundCode}|可用 ${option.availablePackages} ${option.quantityUnit}${option.relabelledPackages > 0 ? `|已换标 ${option.relabelledPackages} ${option.quantityUnit}` : ''}`" :value="option.value" /></el-select></label>
|
||||
<label v-if="props.service === 'transfer'"><span>库存转运来源(可选)</span><el-select v-model="selectedTransferInventory" filterable clearable :loading="relabelCandidatesLoading" :disabled="!form.warehouse" no-data-text="当前海外仓暂无可用库存" placeholder="不选则按新货转运;选择后免 PDA 测量" @change="selectTransferInventory"><el-option v-for="option in transferInventoryOptions" :key="option.value" :label="`${option.label}|可用 ${option.packages} 箱`" :value="option.value" /></el-select><small class="warehouse-hint">库存转运可直接进入目的仓、换标和排车流程,PDA 可拆托、重打或同目的仓合托。</small></label>
|
||||
@@ -1426,7 +1490,7 @@ function selectRelabelInventory(inboundOrderId: string) {
|
||||
</div>
|
||||
<label v-if="props.service === 'relabel'"><span><i>*</i>目的 FBA 仓</span><el-select v-model="form.destination" :loading="fbaWarehousesLoading" :disabled="Boolean(fbaWarehousesError)" placeholder="请选择平台维护的 FBA 仓"><el-option v-for="warehouse in fbaWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="warehouse.warehouseCode" /></el-select></label>
|
||||
<label v-if="props.service === 'relabel'"><span><i>*</i>派送方式</span><el-select v-model="form.deliveryMethod" placeholder="请选择"><el-option label="卡车派送" value="卡车派送" /><el-option label="快递派送" value="快递派送" /></el-select></label>
|
||||
<label v-if="props.service === 'relabel' || props.service === 'disposal'"><span><i>*</i>{{ props.service === 'relabel' ? '退货原因' : '废弃原因' }}</span><el-select v-model="form.reason" placeholder="请选择"><el-option label="客户退货" value="客户退货" /><el-option label="亚马逊移除" value="亚马逊移除" /><el-option label="残损不可售" value="残损不可售" /></el-select></label>
|
||||
<label v-if="props.service === 'relabel'"><span><i>*</i>退货原因</span><el-select v-model="form.reason" placeholder="请选择"><el-option label="客户退货" value="客户退货" /><el-option label="亚马逊移除" value="亚马逊移除" /><el-option label="残损不可售" value="残损不可售" /></el-select></label>
|
||||
<label v-if="props.service === 'labeling'"><span><i>*</i>海外仓签收联系人<em v-if="form.warehouse && !form.contact" class="warehouse-unmaintained">未维护</em></span><el-input v-model="form.contact" placeholder="选择海外操作仓后自动带出" /></label>
|
||||
<label v-if="props.service === 'labeling'"><span><i>*</i>海外仓联系电话<em v-if="form.warehouse && !form.phone" class="warehouse-unmaintained">未维护</em></span><el-input v-model="form.phone" placeholder="选择海外操作仓后自动带出" /></label>
|
||||
<label v-if="props.service === 'labeling'"><span><i>*</i>贴标截止时间</span><el-date-picker v-model="form.labelDeadline" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="请选择截止时间" /></label>
|
||||
@@ -1437,7 +1501,7 @@ function selectRelabelInventory(inboundOrderId: string) {
|
||||
<label v-if="props.service === 'transfer' || props.service === 'relabel'"><span><i>*</i>{{ props.service === 'transfer' ? '预估体积(CBM)' : '预估总体积(CBM)' }}</span><el-input-number v-model="form.volumeCbm" :min="0" :precision="4" :step="0.0001" controls-position="right" placeholder="请输入预估总体积" /></label>
|
||||
<label v-if="props.service === 'transfer' || props.service === 'relabel'"><span><i>*</i>{{ props.service === 'transfer' ? '预计入仓时间' : '预计到达时间' }}</span><el-date-picker v-model="form.estimatedArrivalAt" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" :placeholder="props.service === 'transfer' ? '请选择预计入仓时间' : '请选择预计到达时间'" /></label>
|
||||
<label v-if="props.service === 'transfer'"><span>期望发货时间</span><el-date-picker v-model="form.estimatedShipAt" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="选填" /></label>
|
||||
<div v-if="props.service === 'transfer'" class="warehouse-choice-field warehouse-span-2"><span><i>*</i>目的去向</span><el-radio-group v-model="transferDestinationType" @change="selectTransferDestinationType"><el-radio-button value="NONE">暂未确定</el-radio-button><el-radio-button value="FBA">FBA 仓</el-radio-button><el-radio-button value="PRIVATE">私人仓</el-radio-button></el-radio-group></div>
|
||||
<div v-if="props.service === 'transfer'" class="warehouse-choice-field warehouse-span-2"><span>目的去向</span><el-radio-group v-model="transferDestinationType" @change="selectTransferDestinationType"><el-radio-button value="NONE">暂未确定</el-radio-button><el-radio-button value="FBA">FBA 仓</el-radio-button><el-radio-button value="PRIVATE">私人仓</el-radio-button></el-radio-group></div>
|
||||
<label v-if="props.service === 'transfer' && transferDestinationType === 'FBA'"><span><i>*</i>FBA 目的仓</span><el-select v-model="form.destination" :loading="fbaWarehousesLoading" :disabled="Boolean(fbaWarehousesError)" filterable placeholder="请选择 FBA 仓"><el-option v-for="warehouse in fbaWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="warehouse.warehouseCode" /></el-select></label>
|
||||
<label v-if="props.service === 'transfer' && transferDestinationType === 'FBA'"><span>FBA 货件编号</span><el-input v-model="form.fbaShipmentNo" placeholder="选填,可后续补充" /></label>
|
||||
<label v-if="props.service === 'transfer' && transferDestinationType === 'PRIVATE'"><span><i>*</i>私人仓地址</span><el-input v-model="form.privateDestinationAddress" maxlength="1000" placeholder="请输入私人仓完整地址" /></label>
|
||||
@@ -1539,7 +1603,7 @@ function selectRelabelInventory(inboundOrderId: string) {
|
||||
<header class="warehouse-detail-header">
|
||||
<button type="button" class="warehouse-detail-back" @click="returnToList"><ArrowLeft :size="16" />返回列表</button>
|
||||
<div class="warehouse-detail-title"><strong>{{ props.service === 'labeling' ? selectedRelabelDetail?.application.relabelNo : selectedDetail?.transferNo || selectedDetail?.['0'] || `${config.title}详情` }}</strong><span>{{ config.title }}详情</span></div>
|
||||
<div class="warehouse-detail-actions"><el-button v-if="canCreate && props.service === 'labeling' && selectedRelabelDetail?.application.status === 'REJECTED'" type="primary" @click="resubmitRejectedRelabel">修改后重新提交</el-button><el-button v-if="canConfirmRelabel && props.service === 'labeling' && selectedRelabelDetail?.application.status === 'CUSTOMER_CONFIRM_PENDING' && !selectedRelabelDetail?.application.customerConfirmedAt" type="primary" @click="confirmSelectedRelabel">确认换标完成</el-button><el-button v-if="canCancelDiscard && props.service === 'disposal' && selectedDetail?.status === 'PENDING_REVIEW'" type="danger" @click="cancelSelectedDiscard">取消申请</el-button><el-button v-if="canCreate && props.service === 'transfer' && selectedDetail?.status === 'DRAFT'" type="primary" @click="openEdit(String(selectedDetail?.transferNo || selectedDetail?.['0'] || ''))">编辑</el-button><el-button v-if="canConfirmTransfer && props.service === 'transfer' && selectedDetail?.status === 'WAIT_CUSTOMER_CONFIRMATION'" type="primary" @click="confirmTransferMeasurements">确认测量数据</el-button><el-tag :type="props.service === 'labeling' ? relabelStatusTagType(selectedRelabelDetail?.application.status || '') : undefined" effect="light">{{ statusLabel(props.service === 'labeling' ? selectedRelabelDetail?.application.status || '' : String(selectedDetail?.status || '')) }}</el-tag></div>
|
||||
<div class="warehouse-detail-actions"><el-button v-if="canCreate && props.service === 'labeling' && selectedRelabelDetail?.application.status === 'REJECTED'" type="primary" @click="resubmitRejectedRelabel">修改后重新提交</el-button><el-button v-if="canConfirmRelabel && props.service === 'labeling' && selectedRelabelDetail?.application.status === 'CUSTOMER_CONFIRM_PENDING' && !selectedRelabelDetail?.application.customerConfirmedAt" type="primary" @click="confirmSelectedRelabel">确认换标完成</el-button><el-button v-if="canCancelDiscard && props.service === 'disposal' && selectedDetail?.status === 'PENDING_REVIEW'" type="danger" @click="cancelSelectedDiscard">取消申请</el-button><el-button v-if="canCreate && props.service === 'transfer' && ['DRAFT', 'REJECTED'].includes(selectedDetail?.status || '')" type="primary" @click="openEdit(String(selectedDetail?.transferNo || selectedDetail?.['0'] || ''))">编辑</el-button><el-button v-if="canConfirmTransfer && props.service === 'transfer' && selectedDetail?.status === 'WAIT_CUSTOMER_CONFIRMATION'" type="primary" @click="confirmTransferMeasurements">确认测量数据</el-button><el-tag :type="props.service === 'labeling' ? relabelStatusTagType(selectedRelabelDetail?.application.status || '') : undefined" effect="light">{{ statusLabel(props.service === 'labeling' ? selectedRelabelDetail?.application.status || '' : String(selectedDetail?.status || '')) }}</el-tag></div>
|
||||
</header>
|
||||
<div v-if="detailError" class="warehouse-detail-error" role="alert"><strong>{{ detailError }}</strong><el-button @click="loadDetailPage">重新加载</el-button></div>
|
||||
<el-alert v-else-if="props.service === 'labeling' && selectedRelabelDetail?.application.status === 'REJECTED'" class="warehouse-rejected-alert" type="error" :closable="false" show-icon title="贴标单审核已驳回" :description="selectedRelabelDetail.application.reviewRemark || '平台未填写驳回备注'" />
|
||||
@@ -1628,6 +1692,7 @@ function selectRelabelInventory(inboundOrderId: string) {
|
||||
.warehouse-page-size-select { width: 112px; margin-left: 8px; }
|
||||
.warehouse-page-size-select :deep(.el-input__inner), .warehouse-page-size-select :deep(.el-select__selected-item) { color: #526176 !important; opacity: 1 !important; -webkit-text-fill-color: #526176; }
|
||||
.warehouse-list-actions { display: flex; align-items: center; gap: 8px; white-space: nowrap; }
|
||||
.warehouse-disposal-field { max-width: 520px; }
|
||||
@media (max-width: 720px) {
|
||||
.warehouse-pagination :deep(.el-pagination) { width: 100%; justify-content: flex-end; }
|
||||
.warehouse-transfer-main-card .warehouse-form-grid { grid-template-columns: minmax(0, 1fr); }
|
||||
|
||||
@@ -213,7 +213,7 @@ test('客户可在换标列表或详情确认完工且照片使用二进制下
|
||||
assert.match(view, /confirmRelabelFromList\(item\['0'\]\)/)
|
||||
assert.match(view, /selectedRelabelDetail\?\.application\.status === 'CUSTOMER_CONFIRM_PENDING'/)
|
||||
assert.match(view, /@click="confirmSelectedRelabel">确认换标完成/)
|
||||
assert.match(api, /overseasBlobRequest/)
|
||||
assert.match(api, /apiBlobRequest/)
|
||||
})
|
||||
|
||||
test('客户详情进入页面后直接回显完工照片并支持大图预览', () => {
|
||||
|
||||
@@ -319,7 +319,9 @@ test('仓储转运可在新建页直接提交,也可保存草稿后编辑提
|
||||
assert.match(api, /warehouse-transfers\/\$\{encodeURIComponent\(transferNo\)\}\/submit/)
|
||||
assert.match(view, /submit\('draft'\).*保存草稿/s)
|
||||
assert.match(view, /async function openEdit\(transferNo: string\)/)
|
||||
assert.match(view, /item\.__status === 'DRAFT'.*openEdit\(item\['0'\]\)/s)
|
||||
assert.match(view, /\['DRAFT', 'REJECTED'\]\.includes\(item\.__status\).*openEdit\(item\['0'\]\)/s)
|
||||
assert.match(view, /\['DRAFT', 'REJECTED'\]\.includes\(detail\.status \|\| ''\)/)
|
||||
assert.match(view, /\['DRAFT', 'REJECTED'\]\.includes\(selectedDetail\?\.status \|\| ''\)/)
|
||||
assert.match(view, /v-if="props\.service === 'transfer'"[^>]*type="primary"[^>]*native-type="submit"[^>]*>提交订单/)
|
||||
assert.match(view, /await updateTransfer\(editingTransferNo\.value, payload\)/)
|
||||
assert.match(view, /await submitTransfer\(transferNo\)/)
|
||||
@@ -332,6 +334,22 @@ test('仓储转运可在新建页直接提交,也可保存草稿后编辑提
|
||||
assert.doesNotMatch(view, /<h3>箱唛明细<\/h3>/)
|
||||
})
|
||||
|
||||
test('编辑仓储转运时加载库存转运来源候选', () => {
|
||||
assert.match(view, /async function loadTransferInventoryCandidates\(warehouseId: string\)/)
|
||||
assert.match(view, /if \(props\.service === 'transfer' && form\.warehouse\) \{[\s\S]*await loadTransferInventoryCandidates\(form\.warehouse\)/)
|
||||
assert.match(view, /transferInventoryCandidates\.value = await listRelabelInventoryCandidates\(warehouseId\)/)
|
||||
assert.match(view, /transferInventoryOptions\.value\.some\(\(option\) => option\.value === sourceInboundCode\)/)
|
||||
assert.match(view, /selectedTransferInventory\.value = sourceInboundCode/)
|
||||
assert.match(view, /detail\.sourceOrders \|\| \[\]/)
|
||||
})
|
||||
|
||||
test('仓储转运来源订单雪花 ID 按字符串传递,避免 Number 精度丢失', () => {
|
||||
assert.match(view, /const selectedTransferSourceOrderIds = ref<string\[\]>\(\[\]\)/)
|
||||
assert.match(view, /historical\.map\(\(item\) => String\(item\.id \|\| ''\)\)/)
|
||||
assert.match(api, /sourceLastlegOrderIds\?: string\[\]/)
|
||||
assert.doesNotMatch(view, /sourceLastlegOrderIds[\s\S]{0,160}Number\(/)
|
||||
})
|
||||
|
||||
test('转运贴标单在PDA确认库存前不误报附件上传失败', () => {
|
||||
assert.match(view, /if \(!relabelNo\) \{[\s\S]*PDA 入库确认后将自动生成关联换标单/)
|
||||
assert.match(view, /届时请进入关联换标单详情上传贴标总文件/)
|
||||
|
||||
@@ -52,7 +52,7 @@ test('keeps standalone business pages at the client sidebar root', () => {
|
||||
{ title: '首页', children: undefined },
|
||||
{
|
||||
title: '订单中心',
|
||||
children: ['头程订单', '海外采购', '美国本土卡', '美本土散板'],
|
||||
children: ['头程订单', '入库订单', '派送订单', '海外采购', '美国本土卡', '美本土散板'],
|
||||
},
|
||||
{ title: '报关资料', children: undefined },
|
||||
{ title: '船期价格', children: undefined },
|
||||
@@ -88,6 +88,8 @@ test('flattens visible leaves with unique paths', () => {
|
||||
assert.deepEqual(paths, [
|
||||
'/',
|
||||
'/orders/first-leg',
|
||||
'/orders/inbound',
|
||||
'/orders/delivery',
|
||||
'/cross-border/procurement',
|
||||
'/cross-border/domestic-trucking',
|
||||
'/cross-border/pallet-shipping',
|
||||
@@ -119,6 +121,24 @@ test('filters inaccessible leaves and empty navigation groups', () => {
|
||||
assert.equal(getFirstAccessiblePath([]), '/forbidden')
|
||||
})
|
||||
|
||||
test('exposes active inbound and delivery queries only with their existing read permissions', () => {
|
||||
const deliveryOnly = ['merchant:warehouse:delivery:list']
|
||||
const inboundOnly = ['merchant:warehouse:inbound:list']
|
||||
assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation, deliveryOnly))
|
||||
.map(({ title, path }) => ({ title, path })), [{ title: '派送订单', path: '/orders/delivery' }])
|
||||
assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation, inboundOnly))
|
||||
.map(({ title, path }) => ({ title, path })), [{ title: '入库订单', path: '/orders/inbound' }])
|
||||
assert.equal(getFirstAccessiblePath(deliveryOnly), '/orders/delivery')
|
||||
assert.equal(getFirstAccessiblePath(inboundOnly), '/orders/inbound')
|
||||
assert.deepEqual(getNavigationLeaves(filterNavigationByPermissions(clientNavigation,
|
||||
['merchant:warehouse:delivery:create'])), [])
|
||||
assert.deepEqual(getRouteBreadcrumbs('/orders/delivery/DL-1', '派送单详情'), [
|
||||
{ title: '首页', path: '/' }, { title: '订单中心' },
|
||||
{ title: '派送订单', path: '/orders/delivery' }, { title: '派送单详情' },
|
||||
])
|
||||
assert.deepEqual(getNavigationParentKeys(clientNavigation, '/orders/delivery'), ['order-center'])
|
||||
})
|
||||
|
||||
test('excludes entries marked for manual hiding without affecting other visible items', () => {
|
||||
const visible = filterNavigationByPermissions([
|
||||
{ key: 'shown', title: '显示入口', icon: LayoutGrid, path: '/shown', permission: 'shown:view' },
|
||||
@@ -339,7 +359,7 @@ test('keeps the dashboard route permission synchronized with navigation', () =>
|
||||
assert.match(dashboardRoute, /permission: 'dashboard:view'/)
|
||||
})
|
||||
|
||||
test('keeps internal operational pages routable without exposing them in customer navigation', () => {
|
||||
test('exposes customer business lists and keeps utility routes outside navigation', () => {
|
||||
const routerSource = [
|
||||
'first-leg',
|
||||
'cross-border',
|
||||
@@ -364,8 +384,6 @@ test('keeps internal operational pages routable without exposing them in custome
|
||||
|
||||
const hiddenActivePaths = new Set([
|
||||
'first-leg/quick-order',
|
||||
'orders/inbound',
|
||||
'orders/delivery',
|
||||
'overseas-warehouse/return-inventory',
|
||||
'overseas-warehouse/return-cartons',
|
||||
])
|
||||
|
||||
@@ -52,6 +52,8 @@ export const clientNavigation: ClientNavigationNode[] = [
|
||||
icon: ClipboardList,
|
||||
children: [
|
||||
requireLeaf('first-leg-orders', '头程订单'),
|
||||
requireLeaf('orders-inbound', '入库订单'),
|
||||
requireLeaf('orders-delivery', '派送订单'),
|
||||
requireLeaf('cross-border-procurement'),
|
||||
requireLeaf('cross-border-domestic-trucking'),
|
||||
requireLeaf('cross-border-pallet-shipping'),
|
||||
|
||||
@@ -8,7 +8,6 @@ import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), '')
|
||||
const proxyTarget = process.env.API_PROXY_TARGET || env.API_PROXY_TARGET || 'http://127.0.0.1:9000'
|
||||
const overseasProxyTarget = process.env.OVERSEAS_API_PROXY_TARGET || env.OVERSEAS_API_PROXY_TARGET || 'http://127.0.0.1:9300'
|
||||
|
||||
return {
|
||||
cacheDir: 'tmp/vite-cache',
|
||||
@@ -40,16 +39,6 @@ export default defineConfig(({ mode }) => {
|
||||
})
|
||||
},
|
||||
},
|
||||
'/overseas-api': {
|
||||
target: overseasProxyTarget,
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/overseas-api/, '/api'),
|
||||
configure(proxy) {
|
||||
proxy.on('proxyReq', (proxyRequest) => {
|
||||
proxyRequest.removeHeader('origin')
|
||||
})
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user