Compare commits
76
Commits
fa9bfd5f97
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5a6c7fd88 | ||
|
|
d67da9af82 | ||
|
|
d28408f678 | ||
|
|
90ef9893f3 | ||
|
|
aa68e93b08 | ||
|
|
c168afa1e1 | ||
|
|
6355bb69df | ||
|
|
15015d8bfc | ||
|
|
bd8f9433ed | ||
|
|
4db8700817 | ||
|
|
c72c819f95 | ||
|
|
a0e9ad808b | ||
|
|
cd06e264ff | ||
|
|
aaab5041f9 | ||
|
|
700074e983 | ||
|
|
06f91c8b91 | ||
|
|
6cb9b91435 | ||
|
|
6d0eb2a5f3 | ||
|
|
db44d24eb4 | ||
|
|
3692f9d27f | ||
|
|
90e1e646ec | ||
|
|
5751973c83 | ||
|
|
d7f8365ecc | ||
|
|
3cdd14a521 | ||
|
|
509dc677cb | ||
|
|
c0b151bc15 | ||
|
|
639b1ae22c | ||
|
|
33d86d2a64 | ||
|
|
9891ac3e29 | ||
|
|
d2bbd5024b | ||
|
|
07ba9fcb7c | ||
|
|
2aa20b7172 | ||
|
|
c63fb704a2 | ||
|
|
d39c1f4ea7 | ||
|
|
bc84686658 | ||
|
|
62cf7829d3 | ||
|
|
0be4088fa9 | ||
|
|
7759c7e9f3 | ||
|
|
19f060727b | ||
|
|
47385d46f2 | ||
|
|
a853b1e0c2 | ||
|
|
b7fcc14e59 | ||
|
|
b3f78207b8 | ||
|
|
3703d0a677 | ||
|
|
e139c5c87b | ||
|
|
f0777ba2db | ||
|
|
a0736239e4 | ||
|
|
40f6753cca | ||
|
|
78315873d7 | ||
|
|
fc32d0b390 | ||
|
|
1fe2cada15 | ||
|
|
8e5fa0bebc | ||
|
|
5c53eba31b | ||
|
|
b1f538b3ac | ||
|
|
81a2e6473d | ||
|
|
5f963f326e | ||
|
|
e564353a80 | ||
|
|
187deb5047 | ||
|
|
dae119a1e8 | ||
|
|
c06c105836 | ||
|
|
c3a213d039 | ||
|
|
2f1babae45 | ||
|
|
1bd1664e9c | ||
|
|
1e707f613c | ||
|
|
605388e666 | ||
|
|
c115f1c504 | ||
|
|
162e9a2336 | ||
|
|
d19b1b2f8c | ||
|
|
3c36c55809 | ||
|
|
ff0754810a | ||
|
|
fce1356cb6 | ||
|
|
706e3e871e | ||
|
|
6564d41285 | ||
|
|
6abb8b7388 | ||
|
|
151106250f | ||
|
|
d45cd19361 |
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
|
- 本项目是入驻企业及其成员使用的客户工作台,所有业务数据都处于企业租户上下文中。
|
||||||
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。
|
- 当前范围包括注册、业务总览、企业资料、企业成员、企业角色与权限、头程订单、客户资金账户、客户财务账单查询与客户确认,以及海外仓贴标、转运、废弃和退货换标自助服务。
|
||||||
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及海外 API、海外 Token 或跨区域事件时读取 `../../docs/统一认证与服务通信契约.md`。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
- 用户可见的“平台—客户”层级语义读取 `../../docs/平台客户层级与权限契约.md`;涉及统一 API、Token、会话撤销或可靠事件时按需读取 `../../docs/统一认证与服务通信契约.md` 对应章节。本文件中的 `tenant` 仅表示服务端隔离上下文,不扩展用户可见产品层级。
|
||||||
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
|
- 不在本项目实现平台内部运营管理、品牌官网、仓库 PDA 作业或仅属于原生移动端的能力。
|
||||||
|
|
||||||
## 技术基线
|
## 技术基线
|
||||||
@@ -54,7 +54,8 @@
|
|||||||
| 统一订单展示 | `src/modules/order-management/` | `src/modules/first-leg/` 与对应后端订单契约 |
|
| 统一订单展示 | `src/modules/order-management/` | `src/modules/first-leg/` 与对应后端订单契约 |
|
||||||
| 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `src/modules/finance/`;确认与明细入口 `views/FinanceBillsView.vue`、`api/finance.ts`,入仓码通过 `src/modules/first-leg/public.ts` 复用 `InboundCodeAssociationDialog` | Backend `finance/`;账单行只显示服务端 `inboundCode` 并按登录客户查询业务关系,缺失显示“—”,不得回退内部 ID。收款方式由服务端枚举映射中文。出账或已出账调整后为 `PENDING_CONFIRMATION`,客户确认提交登录成员、`expectedVersion` 和幂等键 |
|
| 客户财务账单、入仓码联查、收款、未收余额与客户确认 | `src/modules/finance/`;确认与明细入口 `views/FinanceBillsView.vue`、`api/finance.ts`,入仓码通过 `src/modules/first-leg/public.ts` 复用 `InboundCodeAssociationDialog` | Backend `finance/`;账单行只显示服务端 `inboundCode` 并按登录客户查询业务关系,缺失显示“—”,不得回退内部 ID。收款方式由服务端枚举映射中文。出账或已出账调整后为 `PENDING_CONFIRMATION`,客户确认提交登录成员、`expectedVersion` 和幂等键 |
|
||||||
| 客户资金账户、授信与充值申请 | `src/modules/finance/views/FinanceAccountView.vue`、`api/account.ts` | 显示当前企业 CNY 实际余额、冻结金额、授信额度、授信有效期、已用授信、冻结授信、总可用余额和不可变流水;数据加载前显示“—”,不得先伪装为零。授信到期日当天仍有效,次日已用授信并入实际余额,负数实际余额会阻止提交新订单。充值只展示服务端启用的平台统一静态收款码,客户上传 JPG/PNG 付款截图后进入待审核。客户范围只取登录态,无收款码时禁止提交,不模拟支付成功 |
|
| 客户资金账户、授信与充值申请 | `src/modules/finance/views/FinanceAccountView.vue`、`api/account.ts` | 显示当前企业 CNY 实际余额、冻结金额、授信额度、授信有效期、已用授信、冻结授信、总可用余额和不可变流水;数据加载前显示“—”,不得先伪装为零。授信到期日当天仍有效,次日已用授信并入实际余额,负数实际余额会阻止提交新订单。充值只展示服务端启用的平台统一静态收款码,客户上传 JPG/PNG 付款截图后进入待审核。客户范围只取登录态,无收款码时禁止提交,不模拟支付成功 |
|
||||||
| 海外采购、美国本土卡与美本土散板 | `src/modules/cross-border/routes.ts`、`components/BusinessOrdersView.vue`、`api/businessOrders.ts` | 三个路由均为 `active`,客户范围只取 Token;采购创建的 `customerName` 只取当前认证会话企业名称,不允许自由输入或冒用其他客户。Backend `lastleg-service/` 的 `procurement/`、`trucking/`、`looseboard/` 客户接口 |
|
| 海外采购 | `src/modules/cross-border/routes.ts`、`views/ProcurementView.vue`、`components/ProcurementDetailPanel.vue`、`api/procurement.ts` | 独立列表、新建及详情路由;客户范围只取 Token,创建的 `customerName` 只取认证会话企业名称。详情消费独立客户投影,展示履约、已确认箱明细、实际运单和费用结果,不开放内部文件或平台操作。Backend `lastleg-service/procurement/` |
|
||||||
|
| 美国本土卡与美本土散板 | `src/modules/cross-border/routes.ts`、`components/BusinessOrdersView.vue`、`api/businessOrders.ts` | 两个运输业务共用列表/表单组件,客户范围只取 Token;不消费采购字段或状态。Backend `lastleg-service/` 的 `trucking/`、`looseboard/` 客户接口 |
|
||||||
| 海外仓入库订单 | `src/modules/order-management/routes.ts`、`views/InboundOrdersView.vue`、`api/inboundPlans.ts` | `orders/inbound` 为只读列表/详情,权限 `merchant:warehouse:inbound:list`;不展示或提交内部 ID |
|
| 海外仓入库订单 | `src/modules/order-management/routes.ts`、`views/InboundOrdersView.vue`、`api/inboundPlans.ts` | `orders/inbound` 为只读列表/详情,权限 `merchant:warehouse:inbound:list`;不展示或提交内部 ID |
|
||||||
| 海外仓贴标、仓储转运、货物废弃 | `src/modules/overseas-warehouse/routes.ts`、`views/WarehouseServiceView.vue`、`api/warehouseServices.ts` | 三个路由均为 `active`;退货预报另见本节独立入口;贴标申请先选国外中转仓和有库存历史入仓单,换标类型为只换 SKU、只换箱唛、SKU+箱唛。涉及箱唛换标时,整张贴标申请只选择一个 FBA 目的仓,全部箱级明细统一提交该目的仓,模板和明细不再逐行选择目的仓。箱唛换标明细一行固定代表一箱,箱数不可编辑,提交也固定为 1。货物明细外层始终提供“SKU 关联”“箱号关联”“SKU 混箱换标”三套模板的下载、上传,不随换标类型切换;上传只进入待导入关系区,客户可勾选部分或全选后导入本次明细,只有进入明细的库存才随申请提交和冻结。明细也支持手动新增编辑,组合换标以仓库唛头连接旧/新 SKU 和新 FBA 箱唛关系。涉及箱唛换标时必须选择卡车、自提或快递;快递可选择打印面单并上传 PDF/图片。PDA 逐箱换标、上传照片并由仓库复核后,客户详情展示完工照片和“换标完成确认”;客户确认前不得继续出库,确认后卡车进入预排车,自提/快递进入换标出库待创建。历史库存位置不能解释成箱唛与具体托盘快照,客户页面不暴露托盘、库位和内部库存 ID |
|
| 海外仓贴标、仓储转运、货物废弃 | `src/modules/overseas-warehouse/routes.ts`、`views/WarehouseServiceView.vue`、`api/warehouseServices.ts` | 三个路由均为 `active`;退货预报另见本节独立入口;贴标申请先选国外中转仓和有库存历史入仓单,换标类型为只换 SKU、只换箱唛、SKU+箱唛。涉及箱唛换标时,整张贴标申请只选择一个 FBA 目的仓,全部箱级明细统一提交该目的仓,模板和明细不再逐行选择目的仓。箱唛换标明细一行固定代表一箱,箱数不可编辑,提交也固定为 1。货物明细外层始终提供“SKU 关联”“箱号关联”“SKU 混箱换标”三套模板的下载、上传,不随换标类型切换;上传只进入待导入关系区,客户可勾选部分或全选后导入本次明细,只有进入明细的库存才随申请提交和冻结。明细也支持手动新增编辑,组合换标以仓库唛头连接旧/新 SKU 和新 FBA 箱唛关系。涉及箱唛换标时必须选择卡车、自提或快递;快递可选择打印面单并上传 PDF/图片。PDA 逐箱换标、上传照片并由仓库复核后,客户详情展示完工照片和“换标完成确认”;客户确认前不得继续出库,确认后卡车进入预排车,自提/快递进入换标出库待创建。历史库存位置不能解释成箱唛与具体托盘快照,客户页面不暴露托盘、库位和内部库存 ID |
|
||||||
|
|
||||||
|
|||||||
Vendored
+28
-4
@@ -1,15 +1,16 @@
|
|||||||
pipeline {
|
pipeline {
|
||||||
agent { label 'java-test' }
|
agent { label "${env.JOB_BASE_NAME?.endsWith('-prod') ? 'java-builder' : 'java-test'}" }
|
||||||
options {
|
options {
|
||||||
timestamps()
|
timestamps()
|
||||||
disableConcurrentBuilds()
|
disableConcurrentBuilds()
|
||||||
}
|
}
|
||||||
stages {
|
stages {
|
||||||
stage('检查测试发布参数') {
|
stage('检查测试发布参数') {
|
||||||
|
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||||
steps {
|
steps {
|
||||||
script {
|
script {
|
||||||
if (env.JOB_BASE_NAME?.endsWith('-dev') || env.JOB_BASE_NAME?.endsWith('-prod')) {
|
if (env.JOB_BASE_NAME?.endsWith('-dev')) {
|
||||||
error('当前仅支持 test,请使用测试环境 Job')
|
error('此流水线仅支持 test 和本轮授权的 prod 灰度')
|
||||||
}
|
}
|
||||||
env.IMAGE_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()
|
||||||
}
|
}
|
||||||
@@ -23,6 +24,7 @@ pipeline {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
stage('构建并部署测试前端') {
|
stage('构建并部署测试前端') {
|
||||||
|
when { expression { !env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||||
steps {
|
steps {
|
||||||
sh '''set -eu
|
sh '''set -eu
|
||||||
docker compose -f docker-compose.test.yml build --pull=false
|
docker compose -f docker-compose.test.yml build --pull=false
|
||||||
@@ -31,8 +33,30 @@ pipeline {
|
|||||||
'''
|
'''
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
stage('发布临时生产灰度') {
|
||||||
|
when { expression { env.JOB_BASE_NAME?.endsWith('-prod') } }
|
||||||
|
steps {
|
||||||
|
lock(resource: 'firstleg-production-client-web-deploy') {
|
||||||
|
withCredentials([
|
||||||
|
usernamePassword(credentialsId: 'gitea-registry-token', usernameVariable: 'BUILD_REGISTRY_USER', passwordVariable: 'BUILD_REGISTRY_PASSWORD'),
|
||||||
|
usernamePassword(credentialsId: 'gitea-production-pull-token', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD'),
|
||||||
|
sshUserPrivateKey(credentialsId: 'firstleg-production-ssh', keyFileVariable: 'TARGET_SSH_KEY', usernameVariable: 'TARGET_SSH_USER'),
|
||||||
|
string(credentialsId: 'firstleg-production-host', variable: 'TARGET_SSH_HOST'),
|
||||||
|
file(credentialsId: 'firstleg-production-known-hosts', variable: 'TARGET_SSH_KNOWN_HOSTS')
|
||||||
|
]) {
|
||||||
|
sh 'sh scripts/deploy-production.sh'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
post {
|
post {
|
||||||
failure { sh 'docker compose -f docker-compose.test.yml logs --tail=100 || true' }
|
failure {
|
||||||
|
script {
|
||||||
|
if (!env.JOB_BASE_NAME?.endsWith('-prod')) {
|
||||||
|
sh 'docker compose -f docker-compose.test.yml logs --tail=100 || true'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
name: firstleg-prod-client-web
|
||||||
|
services:
|
||||||
|
client-web:
|
||||||
|
image: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}:${IMAGE_TAG:?IMAGE_TAG is required}"
|
||||||
|
container_name: firstleg-prod-client-web
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${HOST_PORT:-29012}:80"
|
||||||
|
environment:
|
||||||
|
API_UPSTREAM: "http://gateway:9000"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-qO-", "http://127.0.0.1/healthz"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 12
|
||||||
|
start_period: 5s
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
|
external: true
|
||||||
|
name: firstleg-production-network
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
set +x
|
||||||
|
: "${PUBLIC_WEB_ORIGIN:?PUBLIC_WEB_ORIGIN is required}"
|
||||||
|
: "${PRODUCTION_IMAGE_REPOSITORY:?PRODUCTION_IMAGE_REPOSITORY is required}"
|
||||||
|
: "${TARGET_SSH_KEY:?}"
|
||||||
|
: "${TARGET_SSH_USER:?}"
|
||||||
|
: "${TARGET_SSH_HOST:?}"
|
||||||
|
: "${TARGET_SSH_KNOWN_HOSTS:?}"
|
||||||
|
: "${BUILD_REGISTRY_USER:?}"
|
||||||
|
: "${BUILD_REGISTRY_PASSWORD:?}"
|
||||||
|
: "${REGISTRY_USER:?}"
|
||||||
|
: "${REGISTRY_PASSWORD:?}"
|
||||||
|
case "$PUBLIC_WEB_ORIGIN" in https://*) ;; *) echo 'prod requires HTTPS web origin' >&2; exit 2 ;; esac
|
||||||
|
# Only an origin (optionally a trailing slash) is accepted; no shell/env-file metacharacters.
|
||||||
|
printf '%s' "$PUBLIC_WEB_ORIGIN" | grep -Eq '^https://[A-Za-z0-9.-]+(:[0-9]+)?/?$'
|
||||||
|
printf '%s' "$PRODUCTION_IMAGE_REPOSITORY" | grep -Eq '^[A-Za-z0-9.-]+(:[0-9]+)?/[a-z0-9._/-]+$'
|
||||||
|
git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
|
||||||
|
test "$(git rev-parse HEAD)" = "$(git rev-parse origin/main)"
|
||||||
|
IMAGE_TAG=$(git rev-parse --short=12 HEAD)
|
||||||
|
registry=${PRODUCTION_IMAGE_REPOSITORY%%/*}
|
||||||
|
image="$PRODUCTION_IMAGE_REPOSITORY:$IMAGE_TAG"
|
||||||
|
TARGET_SSH_TARGET="$TARGET_SSH_USER@$TARGET_SSH_HOST"
|
||||||
|
remote_dir=/data/firstleg/deploy/gray-client-web
|
||||||
|
run_ssh() {
|
||||||
|
ssh -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||||
|
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$TARGET_SSH_TARGET" "$@"
|
||||||
|
}
|
||||||
|
run_scp() {
|
||||||
|
scp -i "$TARGET_SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=yes \
|
||||||
|
-o UserKnownHostsFile="$TARGET_SSH_KNOWN_HOSTS" -o ConnectTimeout=12 "$@"
|
||||||
|
}
|
||||||
|
export DOCKER_CONFIG
|
||||||
|
DOCKER_CONFIG=$(mktemp -d)
|
||||||
|
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
|
||||||
|
trap cleanup EXIT HUP INT TERM
|
||||||
|
printf '%s' "$BUILD_REGISTRY_PASSWORD" | docker login -u "$BUILD_REGISTRY_USER" --password-stdin "$registry"
|
||||||
|
docker build --build-arg NODE_IMAGE="${NODE_BASE_IMAGE:-node:22-alpine}" \
|
||||||
|
--build-arg NGINX_IMAGE="${NGINX_BASE_IMAGE:-nginx:1.27-alpine}" \
|
||||||
|
--build-arg VITE_ADMIN_WEB_ORIGIN="$PUBLIC_WEB_ORIGIN" -t "$image" .
|
||||||
|
docker push "$image"
|
||||||
|
run_ssh install -d -m 750 "$remote_dir"
|
||||||
|
run_scp docker-compose.production.yml "$TARGET_SSH_TARGET:$remote_dir/compose.yml"
|
||||||
|
# The remote env file contains only image coordinates and public web origin, never credentials.
|
||||||
|
printf 'PRODUCTION_IMAGE_REPOSITORY=%s\nIMAGE_TAG=%s\nPUBLIC_WEB_ORIGIN=%s\n' \
|
||||||
|
"$PRODUCTION_IMAGE_REPOSITORY" "$IMAGE_TAG" "$PUBLIC_WEB_ORIGIN" | run_ssh sh -c "'umask 077; cat > $remote_dir/release.env'"
|
||||||
|
# Registry credentials exist only in an isolated temporary Docker config, removed after pull.
|
||||||
|
printf '%s' "$REGISTRY_USER" | grep -Eq '^[A-Za-z0-9_.@-]+$'
|
||||||
|
run_scp scripts/pull-production-image.sh "$TARGET_SSH_TARGET:$remote_dir/pull-image.sh"
|
||||||
|
printf '%s' "$REGISTRY_PASSWORD" | run_ssh sh "$remote_dir/pull-image.sh" "$REGISTRY_USER" "$registry" "$image"
|
||||||
|
run_ssh sh -s -- "$remote_dir" <<'REMOTE'
|
||||||
|
set -eu
|
||||||
|
cd "$1"
|
||||||
|
docker network inspect firstleg-production-network >/dev/null
|
||||||
|
docker compose --env-file release.env -f compose.yml config --quiet
|
||||||
|
docker compose --env-file release.env -f compose.yml up -d --wait --wait-timeout 120
|
||||||
|
docker compose --env-file release.env -f compose.yml exec -T client-web wget -qO- http://127.0.0.1/healthz
|
||||||
|
REMOTE
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
set +x
|
||||||
|
export DOCKER_CONFIG
|
||||||
|
DOCKER_CONFIG=$(mktemp -d)
|
||||||
|
cleanup() { rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG" 2>/dev/null || true; }
|
||||||
|
trap cleanup EXIT HUP INT TERM
|
||||||
|
docker login -u "$1" --password-stdin "$2"
|
||||||
|
docker pull "$3"
|
||||||
@@ -92,6 +92,7 @@ export const FIRST_LEG_ORDER_STATUSES = [
|
|||||||
{ code: 'LOADED', label: '装柜完成' },
|
{ code: 'LOADED', label: '装柜完成' },
|
||||||
{ code: 'DELIVERED', label: '派送完成' },
|
{ code: 'DELIVERED', label: '派送完成' },
|
||||||
{ code: 'COMPLETED', label: '已完成' },
|
{ code: 'COMPLETED', label: '已完成' },
|
||||||
|
{ code: 'CANCELLED', label: '已取消' },
|
||||||
] as const
|
] as const
|
||||||
|
|
||||||
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
|
export type FirstLegOrderStatus = (typeof FIRST_LEG_ORDER_STATUSES)[number]['code']
|
||||||
|
|||||||
+83
-7
@@ -1,6 +1,6 @@
|
|||||||
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
import axios, { AxiosError, type AxiosRequestConfig, type InternalAxiosRequestConfig } from 'axios'
|
||||||
import { parseApiJsonResponse } from '@chongchong/shared'
|
import { parseApiJsonResponse } from '@chongchong/shared'
|
||||||
import { clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
import { accessTokenIdentity, clearSessionTokens, getAccessToken, getRefreshToken, persistTokenPair, type TokenPair } from '@/api/session'
|
||||||
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
import { apiErrorMessage, asFieldErrors } from '@/api/errorDetails'
|
||||||
import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
|
import { ApiError, isApiEnvelope, isApiFailure, type ApiEnvelope } from '@/api/types'
|
||||||
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
|
import { coordinateCrossTabRefresh, CrossTabRefreshTimeoutError } from '@/api/crossTabRefresh'
|
||||||
@@ -13,6 +13,8 @@ const transport = axios.create({
|
|||||||
|
|
||||||
interface RetryableRequest extends InternalAxiosRequestConfig {
|
interface RetryableRequest extends InternalAxiosRequestConfig {
|
||||||
_retriedAfterRefresh?: boolean
|
_retriedAfterRefresh?: boolean
|
||||||
|
_sessionIdentity?: string | null
|
||||||
|
_logoutGeneration?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
function unwrap<T>(envelope: ApiEnvelope<T>) {
|
||||||
@@ -51,9 +53,12 @@ function mapError(error: unknown) {
|
|||||||
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
return new ApiError(error.message || '请求失败', 'HTTP_ERROR', error.response?.status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let refreshExchange: { identity: string; refreshToken: string; promise: Promise<TokenPair> } | null = null
|
||||||
|
let logoutGeneration = 0
|
||||||
let refreshPromise: Promise<string> | null = null
|
let refreshPromise: Promise<string> | null = null
|
||||||
|
let refreshIdentity: string | null = null
|
||||||
let redirectingToLogin = false
|
let redirectingToLogin = false
|
||||||
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/impersonations/exchange']
|
const publicAuthPaths = ['/auth/login', '/auth/register', '/auth/refresh', '/auth/logout', '/auth/impersonations/exchange']
|
||||||
|
|
||||||
function isPublicAuthRequest(url?: string) {
|
function isPublicAuthRequest(url?: string) {
|
||||||
return publicAuthPaths.some((path) => url?.endsWith(path))
|
return publicAuthPaths.some((path) => url?.endsWith(path))
|
||||||
@@ -70,29 +75,46 @@ function redirectToLoginAfterSessionExpiry() {
|
|||||||
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
window.location.replace(`/login?redirect=${encodeURIComponent(redirect)}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function requireCurrentIdentity(identity: string | null | undefined, accessToken = getAccessToken()) {
|
||||||
|
if (!identity || accessTokenIdentity(accessToken) !== identity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
}
|
||||||
|
|
||||||
export async function refreshAuthenticatedSession() {
|
export async function refreshAuthenticatedSession() {
|
||||||
|
const observedIdentity = accessTokenIdentity(getAccessToken())
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
const observedRefreshToken = getRefreshToken()
|
const observedRefreshToken = getRefreshToken()
|
||||||
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
if (!observedRefreshToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||||
if (!refreshPromise) {
|
if (!refreshPromise) {
|
||||||
|
refreshIdentity = observedIdentity
|
||||||
refreshPromise = coordinateCrossTabRefresh({
|
refreshPromise = coordinateCrossTabRefresh({
|
||||||
lockName: 'cc-client-auth-refresh',
|
lockName: 'cc-client-auth-refresh',
|
||||||
observedRefreshToken,
|
observedRefreshToken,
|
||||||
currentRefreshToken: getRefreshToken,
|
currentRefreshToken: getRefreshToken,
|
||||||
reuseCurrentSession: async () => {
|
reuseCurrentSession: async () => {
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
const currentAccessToken = getAccessToken()
|
const currentAccessToken = getAccessToken()
|
||||||
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
if (!currentAccessToken) throw new ApiError('登录已过期,请重新登录', 'A0401', 401)
|
||||||
return currentAccessToken
|
return currentAccessToken
|
||||||
},
|
},
|
||||||
refresh: async (currentRefreshToken) => {
|
refresh: async (currentRefreshToken) => {
|
||||||
const response = await transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken })
|
requireCurrentIdentity(observedIdentity)
|
||||||
const tokens = unwrap(response.data)
|
const exchange = { identity: observedIdentity!, refreshToken: currentRefreshToken, promise: transport.post<ApiEnvelope<TokenPair>>('/auth/refresh', { refreshToken: currentRefreshToken }).then(response => unwrap(response.data)) }
|
||||||
|
refreshExchange = exchange
|
||||||
|
let tokens: TokenPair
|
||||||
|
try { tokens = await exchange.promise } finally { if (refreshExchange === exchange) refreshExchange = null }
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
|
requireCurrentIdentity(observedIdentity, tokens.accessToken)
|
||||||
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
if (!getRefreshToken()) throw new ApiError('登录已在其他标签页退出', 'A0401', 401)
|
||||||
|
if (getRefreshToken() !== currentRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
persistTokenPair(tokens)
|
persistTokenPair(tokens)
|
||||||
|
if (typeof window !== 'undefined') window.dispatchEvent(new CustomEvent('cc-client-session-updated'))
|
||||||
return tokens.accessToken
|
return tokens.accessToken
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
if (error instanceof CrossTabRefreshTimeoutError) {
|
if (error instanceof CrossTabRefreshTimeoutError) {
|
||||||
|
if (getRefreshToken() && getRefreshToken() !== observedRefreshToken) throw new ApiError('登录状态已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
const expiredError = new ApiError(error.message, 'A0401', 401)
|
const expiredError = new ApiError(error.message, 'A0401', 401)
|
||||||
clearSessionTokens()
|
clearSessionTokens()
|
||||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||||
@@ -103,33 +125,60 @@ export async function refreshAuthenticatedSession() {
|
|||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
refreshPromise = null
|
refreshPromise = null
|
||||||
|
refreshIdentity = null
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return refreshPromise
|
if (refreshIdentity !== observedIdentity) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
const refreshed = await refreshPromise
|
||||||
|
requireCurrentIdentity(observedIdentity)
|
||||||
|
return refreshed
|
||||||
}
|
}
|
||||||
|
|
||||||
transport.interceptors.request.use((config) => {
|
transport.interceptors.request.use((config) => {
|
||||||
const token = getAccessToken()
|
const token = getAccessToken()
|
||||||
if (token && !isPublicAuthRequest(config.url)) config.headers.Authorization = `Bearer ${token}`
|
const request = config as RetryableRequest
|
||||||
|
if (request._retriedAfterRefresh && !isPublicAuthRequest(config.url)) requireCurrentIdentity(request._sessionIdentity, token)
|
||||||
|
if (token && !isPublicAuthRequest(config.url)) {
|
||||||
|
if (!request._retriedAfterRefresh) {
|
||||||
|
request._sessionIdentity = accessTokenIdentity(token)
|
||||||
|
request._logoutGeneration = logoutGeneration
|
||||||
|
}
|
||||||
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
|
}
|
||||||
return config
|
return config
|
||||||
})
|
})
|
||||||
|
|
||||||
transport.interceptors.response.use(
|
transport.interceptors.response.use(
|
||||||
(response) => response,
|
(response) => {
|
||||||
|
const request = response.config as RetryableRequest
|
||||||
|
if (request._sessionIdentity) {
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
},
|
||||||
async (error: AxiosError) => {
|
async (error: AxiosError) => {
|
||||||
const request = error.config as RetryableRequest | undefined
|
const request = error.config as RetryableRequest | undefined
|
||||||
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
|
if (error.response?.status !== 401 || !request || request._retriedAfterRefresh || isPublicAuthRequest(request.url)) {
|
||||||
throw mapError(error)
|
throw mapError(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
request._retriedAfterRefresh = true
|
request._retriedAfterRefresh = true
|
||||||
|
const refreshTokenBeforeRetry = getRefreshToken()
|
||||||
try {
|
try {
|
||||||
const accessToken = await refreshAuthenticatedSession()
|
const accessToken = await refreshAuthenticatedSession()
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
request.headers.Authorization = `Bearer ${accessToken}`
|
request.headers.Authorization = `Bearer ${accessToken}`
|
||||||
return await transport.request(request)
|
return await transport.request(request)
|
||||||
} catch (refreshError) {
|
} catch (refreshError) {
|
||||||
|
if (request._logoutGeneration !== logoutGeneration) throw new ApiError('登录身份已变化,请重新操作', 'SESSION_CHANGED')
|
||||||
|
requireCurrentIdentity(request._sessionIdentity)
|
||||||
const mappedError = mapError(refreshError)
|
const mappedError = mapError(refreshError)
|
||||||
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
if (mappedError.status === 401 || mappedError.code === 'A0401') {
|
||||||
|
if (getRefreshToken() && getRefreshToken() !== refreshTokenBeforeRetry) throw mappedError
|
||||||
clearSessionTokens()
|
clearSessionTokens()
|
||||||
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
window.dispatchEvent(new CustomEvent('cc-client-session-expired'))
|
||||||
redirectToLoginAfterSessionExpiry()
|
redirectToLoginAfterSessionExpiry()
|
||||||
@@ -139,6 +188,33 @@ transport.interceptors.response.use(
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Captured revocation never persists credentials or restores local login state.
|
||||||
|
export async function revokeCapturedSession(accessToken: string, refreshToken: string) {
|
||||||
|
logoutGeneration++
|
||||||
|
const identity = accessTokenIdentity(accessToken)
|
||||||
|
if (!identity || !refreshToken) throw new ApiError('服务器会话注销未确认', 'SESSION_CHANGED')
|
||||||
|
const pending = refreshExchange?.identity === identity && refreshExchange.refreshToken === refreshToken ? refreshExchange.promise : null
|
||||||
|
const revoke = (pair: Pick<TokenPair, 'accessToken' | 'refreshToken'>) => apiRequest<void>({
|
||||||
|
method: 'POST', url: '/auth/logout', data: { refreshToken: pair.refreshToken },
|
||||||
|
headers: { Authorization: `Bearer ${pair.accessToken}` },
|
||||||
|
})
|
||||||
|
const validate = (pair: TokenPair) => {
|
||||||
|
if (accessTokenIdentity(pair.accessToken) !== identity || !pair.refreshToken) throw new ApiError('刷新身份不一致,服务器会话注销未确认', 'SESSION_CHANGED')
|
||||||
|
return pair
|
||||||
|
}
|
||||||
|
// An already sent refresh can rotate the pair. Consume its actual result
|
||||||
|
// without issuing a competing refresh or restoring it to local storage.
|
||||||
|
if (pending) {
|
||||||
|
await revoke(validate(await pending))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try { await revoke({ accessToken, refreshToken }) } catch (error) {
|
||||||
|
if (!(error instanceof ApiError) || error.status !== 401) throw error
|
||||||
|
const pair = await apiRequest<TokenPair>({ method: 'POST', url: '/auth/refresh', data: { refreshToken } })
|
||||||
|
await revoke(validate(pair))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
export async function apiRequest<T>(config: AxiosRequestConfig) {
|
||||||
try {
|
try {
|
||||||
const response = await transport.request<ApiEnvelope<T>>(config)
|
const response = await transport.request<ApiEnvelope<T>>(config)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
import {
|
import {
|
||||||
|
accessTokenIdentity,
|
||||||
ACCESS_TOKEN_KEY,
|
ACCESS_TOKEN_KEY,
|
||||||
REFRESH_TOKEN_KEY,
|
REFRESH_TOKEN_KEY,
|
||||||
REMEMBERED_LOGIN_ID_KEY,
|
REMEMBERED_LOGIN_ID_KEY,
|
||||||
@@ -56,3 +57,34 @@ test('remembers only the login id and keeps it when session tokens are cleared',
|
|||||||
persistRememberedLoginId('merchant-user', false)
|
persistRememberedLoginId('merchant-user', false)
|
||||||
assert.equal(getRememberedLoginId(), '')
|
assert.equal(getRememberedLoginId(), '')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('normal token rotation never removes either shared token between writes', () => {
|
||||||
|
installStorage()
|
||||||
|
localStorage.setItem(ACCESS_TOKEN_KEY, 'old-access')
|
||||||
|
localStorage.setItem(REFRESH_TOKEN_KEY, 'old-refresh')
|
||||||
|
const removed = []
|
||||||
|
const remove = localStorage.removeItem
|
||||||
|
localStorage.removeItem = key => { removed.push(key); remove(key) }
|
||||||
|
persistTokenPair({ accessToken: 'new-access', refreshToken: 'new-refresh' })
|
||||||
|
assert.ok(!removed.includes(ACCESS_TOKEN_KEY))
|
||||||
|
assert.ok(!removed.includes(REFRESH_TOKEN_KEY))
|
||||||
|
})
|
||||||
|
|
||||||
|
function rawIdentity(overrides = '') {
|
||||||
|
return `test.${Buffer.from(`{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"${overrides}}`).toString('base64url')}.test`
|
||||||
|
}
|
||||||
|
test('identity preserves low digits of numeric 19 digit user customer and membership',()=>{
|
||||||
|
const original=rawIdentity();const json=Buffer.from(original.split('.')[1],'base64url').toString();
|
||||||
|
for(const field of ['user_id','tenant_id','membership_id']){
|
||||||
|
const changed=json.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`)
|
||||||
|
assert.notEqual(accessTokenIdentity(original),accessTokenIdentity(`test.${Buffer.from(changed).toString('base64url')}.test`))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
test('identity string and numeric integers are equivalent without changing other strings',()=>{
|
||||||
|
const a=rawIdentity();const raw=Buffer.from(a.split('.')[1],'base64url').toString();
|
||||||
|
const b=`test.${Buffer.from(raw.replaceAll(':2107003446494334978',':"2107003446494334978"')).toString('base64url')}.test`
|
||||||
|
assert.equal(accessTokenIdentity(a),accessTokenIdentity(b))
|
||||||
|
const decorated=rawIdentity(',"username":'+JSON.stringify('number 2107003446494334979 and "tenant_id":2107003446494334979')+',"note":"1234567890123456789"')
|
||||||
|
assert.equal(accessTokenIdentity(a),accessTokenIdentity(decorated))
|
||||||
|
assert.ok(accessTokenIdentity(a).includes('2107003446494334978'))
|
||||||
|
})
|
||||||
|
|||||||
+30
-1
@@ -19,9 +19,38 @@ export function getRefreshToken() {
|
|||||||
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
return localStorage.getItem(REFRESH_TOKEN_KEY) || sessionStorage.getItem(REFRESH_TOKEN_KEY) || ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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) {
|
export function persistTokenPair(tokens: TokenPair) {
|
||||||
clearSessionTokens()
|
// Replace the pair without publishing a transient logout to other tabs.
|
||||||
|
sessionStorage.removeItem(ACCESS_TOKEN_KEY)
|
||||||
|
sessionStorage.removeItem(REFRESH_TOKEN_KEY)
|
||||||
|
sessionStorage.removeItem('cc-client-token')
|
||||||
|
localStorage.removeItem('cc-client-token')
|
||||||
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
|
localStorage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken)
|
||||||
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
|
localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,13 +18,21 @@ function compile(name, dependencies = {}) {
|
|||||||
return 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) {
|
function harness(adapter) {
|
||||||
let token = 'old-access'
|
let token = oldAccess
|
||||||
let refreshToken = 'old-refresh'
|
let refreshToken = 'old-refresh'
|
||||||
const http = compile('./http.ts', {
|
const http = compile('./http.ts', {
|
||||||
axios: { ...axios, create: (config) => axios.create({ ...config, adapter }) },
|
axios: { ...axios, create: (config) => axios.create({ ...config, adapter }) },
|
||||||
'@chongchong/shared': { parseApiJsonResponse: (data) => data },
|
'@chongchong/shared': { parseApiJsonResponse: (data) => data },
|
||||||
'@/api/session': {
|
'@/api/session': {
|
||||||
|
accessTokenIdentity: compile('./session.ts').accessTokenIdentity,
|
||||||
getAccessToken: () => token, getRefreshToken: () => refreshToken,
|
getAccessToken: () => token, getRefreshToken: () => refreshToken,
|
||||||
persistTokenPair: (tokens) => { token = tokens.accessToken; refreshToken = tokens.refreshToken },
|
persistTokenPair: (tokens) => { token = tokens.accessToken; refreshToken = tokens.refreshToken },
|
||||||
clearSessionTokens: () => { token = ''; refreshToken = '' },
|
clearSessionTokens: () => { token = ''; refreshToken = '' },
|
||||||
@@ -33,7 +41,7 @@ function harness(adapter) {
|
|||||||
'@/api/types': compile('./types.ts'),
|
'@/api/types': compile('./types.ts'),
|
||||||
'@/api/crossTabRefresh': compile('./crossTabRefresh.ts'),
|
'@/api/crossTabRefresh': compile('./crossTabRefresh.ts'),
|
||||||
})
|
})
|
||||||
return http
|
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 () => {
|
test('order and lastleg 401s share one refresh and replay the unified access token', async () => {
|
||||||
@@ -44,9 +52,9 @@ test('order and lastleg 401s share one refresh and replay the unified access tok
|
|||||||
if (config.url === '/auth/refresh') {
|
if (config.url === '/auth/refresh') {
|
||||||
refreshes++
|
refreshes++
|
||||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||||
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: 'new-access', refreshToken: 'new-refresh' } } }
|
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||||
}
|
}
|
||||||
if (config.headers.Authorization === 'Bearer old-access') {
|
if (config.headers.Authorization === `Bearer ${oldAccess}`) {
|
||||||
throw new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
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 } }
|
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: config.url } }
|
||||||
@@ -56,7 +64,14 @@ test('order and lastleg 401s share one refresh and replay the unified access tok
|
|||||||
assert.equal(refreshes, 1)
|
assert.equal(refreshes, 1)
|
||||||
assert.ok(calls.every((call) => call.base === '/api'))
|
assert.ok(calls.every((call) => call.base === '/api'))
|
||||||
assert.equal(calls.find((call) => call.url === '/auth/refresh').token, undefined)
|
assert.equal(calls.find((call) => call.url === '/auth/refresh').token, undefined)
|
||||||
assert.equal(calls.filter((call) => call.token === 'Bearer new-access').length, 2)
|
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 () => {
|
test('data-less security failures preserve diagnostics and malformed success is rejected', async () => {
|
||||||
@@ -69,3 +84,139 @@ test('data-less security failures preserve diagnostics and malformed success is
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('late refresh response cannot overwrite a session changed in another tab', async () => {
|
||||||
|
let complete, started
|
||||||
|
const ready = new Promise(resolve => { started = resolve })
|
||||||
|
const response = new Promise(resolve => { complete = resolve })
|
||||||
|
const http = harness(async config => { started(); await response; return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: oldAccess, refreshToken: 'stale-refresh' } } } })
|
||||||
|
const pending = http.refreshAuthenticatedSession()
|
||||||
|
await ready
|
||||||
|
http.setSession(otherAccess, 'other-refresh')
|
||||||
|
complete()
|
||||||
|
await pending.catch(error => assert.equal(error.code, 'SESSION_CHANGED'))
|
||||||
|
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'other-refresh' })
|
||||||
|
})
|
||||||
|
|
||||||
|
function deferred() { let resolve; const promise = new Promise(yes => { resolve = yes }); return { promise, resolve } }
|
||||||
|
|
||||||
|
function unauthorized(config) {
|
||||||
|
return new axios.AxiosError('Expired', 'ERR_BAD_REQUEST', config, null, { status: 401, data: { code: 'A0401', message: 'Expired' } })
|
||||||
|
}
|
||||||
|
|
||||||
|
test('late A write 401 after user, customer or membership switch never refreshes or replays under B', async () => {
|
||||||
|
for (const next of [access(2), access(1, 2), access(1, 1, 2)]) {
|
||||||
|
const sent = deferred(), release = deferred(), calls = []
|
||||||
|
const http = harness(async config => {
|
||||||
|
calls.push(config.url); sent.resolve(); await release.promise
|
||||||
|
throw unauthorized(config)
|
||||||
|
})
|
||||||
|
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit', data: { expectedVersion: 1 } })
|
||||||
|
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||||
|
await sent.promise; http.setSession(next, 'refresh-b'); release.resolve(); await rejected
|
||||||
|
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit'])
|
||||||
|
assert.deepEqual(http.session(), { token: next, refreshToken: 'refresh-b' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('switch during in-flight refresh cannot reuse B token to replay an A write', async () => {
|
||||||
|
const refreshing = deferred(), release = deferred(), calls = []
|
||||||
|
const http = harness(async config => {
|
||||||
|
calls.push(config.url)
|
||||||
|
if (config.url === '/auth/refresh') {
|
||||||
|
refreshing.resolve(); await release.promise
|
||||||
|
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: { accessToken: newAccess, refreshToken: 'new-refresh' } } }
|
||||||
|
}
|
||||||
|
throw unauthorized(config)
|
||||||
|
})
|
||||||
|
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||||
|
const rejected = assert.rejects(pending, error => error.code === 'SESSION_CHANGED')
|
||||||
|
await refreshing.promise; http.setSession(otherAccess, 'refresh-b'); release.resolve(); await rejected
|
||||||
|
assert.deepEqual(calls, ['/merchant/v1/orders/first-leg/one/submit', '/auth/refresh'])
|
||||||
|
assert.deepEqual(http.session(), { token: otherAccess, refreshToken: 'refresh-b' })
|
||||||
|
})
|
||||||
|
|
||||||
|
test('refresh lock wait reuses same-identity rotation but rejects changed-identity reuse', async t => {
|
||||||
|
const originalNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator')
|
||||||
|
t.after(() => { if (originalNavigator) Object.defineProperty(globalThis, 'navigator', originalNavigator); else delete globalThis.navigator })
|
||||||
|
for (const next of [newAccess, otherAccess]) {
|
||||||
|
const waiting = deferred(), release = deferred(), calls = []
|
||||||
|
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: { locks: { request: async (_name, _options, run) => {
|
||||||
|
waiting.resolve(); await release.promise; return run()
|
||||||
|
} } } })
|
||||||
|
const http = harness(async config => {
|
||||||
|
calls.push({ url: config.url, authorization: config.headers.Authorization })
|
||||||
|
if (config.headers.Authorization === `Bearer ${oldAccess}`) throw unauthorized(config)
|
||||||
|
return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data: null } }
|
||||||
|
})
|
||||||
|
const pending = http.apiRequest({ method: 'POST', url: '/merchant/v1/orders/first-leg/one/submit' })
|
||||||
|
const outcome = next === otherAccess ? assert.rejects(pending, error => error.code === 'SESSION_CHANGED') : pending
|
||||||
|
await waiting.promise; http.setSession(next, 'rotated-refresh'); release.resolve(); await outcome
|
||||||
|
assert.equal(calls.some(call => call.url === '/auth/refresh'), false)
|
||||||
|
assert.equal(calls.length, next === otherAccess ? 1 : 2)
|
||||||
|
assert.deepEqual(http.session(), { token: next, refreshToken: 'rotated-refresh' })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function authApi(http) { return compile('../modules/auth/api/auth.ts', { '@/api/http': http }) }
|
||||||
|
function ok(config, data = null) { return { config, status: 200, headers: {}, data: { code: '200', message: 'OK', data } } }
|
||||||
|
test('logout after immediate local clear revokes captured Bearer and Refresh', async () => {
|
||||||
|
const calls=[]; const http=harness(async c=>{calls.push(c);return ok(c)})
|
||||||
|
http.setSession('', '');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||||
|
assert.equal(calls.length,1);assert.equal(calls[0].headers.Authorization,`Bearer ${oldAccess}`)
|
||||||
|
assert.deepEqual(JSON.parse(calls[0].data),{refreshToken:'old-refresh'});assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||||
|
})
|
||||||
|
test('only explicit logout401 refreshes once and revokes same-identity replacement without storing it', async () => {
|
||||||
|
const calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'});if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||||
|
http.setSession('','');await authApi(http).logoutMerchant(oldAccess,'old-refresh')
|
||||||
|
assert.deepEqual(calls.map(x=>x.url),['/auth/logout','/auth/refresh','/auth/logout']);assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[2].data).refreshToken,'new-refresh');assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||||
|
})
|
||||||
|
test('unknown logout failure never refreshes; changed identity cannot be revoked as replacement', async () => {
|
||||||
|
for(const mode of ['network','wrongIdentity','second401']){const calls=[];const http=harness(async c=>{calls.push(c);if(mode==='network')throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c);if(c.url==='/auth/refresh')return ok(c,{accessToken:mode==='wrongIdentity'?otherAccess:newAccess,refreshToken:'replacement'});throw unauthorized(c)})
|
||||||
|
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(oldAccess,'old-refresh'));assert.equal(calls.length,mode==='network'?1:mode==='wrongIdentity'?2:3);assert.deepEqual(http.session(),{token:'',refreshToken:''})}
|
||||||
|
})
|
||||||
|
test('logout consumes already inflight refresh once while old business caller cannot revive session',async()=>{
|
||||||
|
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}return ok(c)})
|
||||||
|
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||||
|
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');release.resolve();await leaving;await rejected
|
||||||
|
assert.deepEqual(calls.map(x=>x.url),['/auth/refresh','/auth/logout']);assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||||
|
})
|
||||||
|
test('late successful business response after logout rejects even after same-identity new login',async()=>{
|
||||||
|
const started=deferred(),release=deferred();const http=harness(async c=>{if(c.url==='/merchant/v1/orders'){started.resolve();await release.promise}return ok(c,'old-data')})
|
||||||
|
const pending=http.apiRequest({url:'/merchant/v1/orders'});const rejected=assert.rejects(pending,e=>e.code==='SESSION_CHANGED');await started.promise
|
||||||
|
await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected;assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('inflight refresh unknown outcome stops logout without competing retry and preserves later login',async()=>{
|
||||||
|
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);started.resolve();await release.promise;throw new axios.AxiosError('offline',axios.AxiosError.ERR_NETWORK,c)})
|
||||||
|
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise
|
||||||
|
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');const failure=assert.rejects(leaving,e=>e.code==='NETWORK_ERROR');http.setSession(otherAccess,'other-refresh');release.resolve();await failure;await rejected
|
||||||
|
assert.equal(calls.length,1);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||||
|
})
|
||||||
|
test('logout401 refresh and replacement revocation cannot overwrite later login',async()=>{
|
||||||
|
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'new-refresh'})}if(c.headers.Authorization===`Bearer ${oldAccess}`)throw unauthorized(c);return ok(c)})
|
||||||
|
const leaving=authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession('','');await started.promise;http.setSession(otherAccess,'other-refresh');release.resolve();await leaving
|
||||||
|
assert.equal(calls[2].headers.Authorization,`Bearer ${newAccess}`);assert.deepEqual(http.session(),{token:otherAccess,refreshToken:'other-refresh'})
|
||||||
|
})
|
||||||
|
test('late old business401 after logout does not refresh or replay under same-identity new login',async()=>{
|
||||||
|
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/merchant/v1/orders/first-leg/one/submit'){started.resolve();await release.promise;throw unauthorized(c)}return ok(c)})
|
||||||
|
const request=http.apiRequest({method:'POST',url:'/merchant/v1/orders/first-leg/one/submit'});const rejected=assert.rejects(request,e=>e.code==='SESSION_CHANGED');await started.promise;await authApi(http).logoutMerchant(oldAccess,'old-refresh');http.setSession(newAccess,'new-login-refresh');release.resolve();await rejected
|
||||||
|
assert.deepEqual(calls.map(x=>x.url),['/merchant/v1/orders/first-leg/one/submit','/auth/logout']);assert.equal(http.session().refreshToken,'new-login-refresh')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('same identity new pair logout does not adopt another session inflight refresh',async()=>{
|
||||||
|
const started=deferred(),release=deferred(),calls=[];const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh'){started.resolve();await release.promise;return ok(c,{accessToken:newAccess,refreshToken:'old-session-rotated'})}return ok(c)})
|
||||||
|
const refreshing=http.refreshAuthenticatedSession();const rejected=assert.rejects(refreshing);await started.promise;http.setSession(newAccess,'new-login-refresh')
|
||||||
|
const leaving=authApi(http).logoutMerchant(newAccess,'new-login-refresh');http.setSession('','');await leaving
|
||||||
|
assert.equal(calls[1].headers.Authorization,`Bearer ${newAccess}`);assert.equal(JSON.parse(calls[1].data).refreshToken,'new-login-refresh');release.resolve();await rejected;assert.deepEqual(http.session(),{token:'',refreshToken:''})
|
||||||
|
})
|
||||||
|
|
||||||
|
test('logout rejects refreshed 19 digit identity differing only in low digit',async()=>{
|
||||||
|
const raw='{"user_id":2107003446494334978,"tenant_id":2107003446494334978,"membership_id":2107003446494334978,"app_code":"MERCHANT"}'
|
||||||
|
const original=`test.${Buffer.from(raw).toString('base64url')}.test`
|
||||||
|
for(const field of ['user_id','tenant_id','membership_id']){
|
||||||
|
const changed=raw.replace(`"${field}":2107003446494334978`,`"${field}":2107003446494334979`),calls=[]
|
||||||
|
const http=harness(async c=>{calls.push(c);if(c.url==='/auth/refresh')return ok(c,{accessToken:`test.${Buffer.from(changed).toString('base64url')}.test`,refreshToken:'replacement'});throw unauthorized(c)})
|
||||||
|
http.setSession('','');await assert.rejects(authApi(http).logoutMerchant(original,'original-refresh'),e=>e.code==='SESSION_CHANGED');assert.equal(calls.length,2)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|||||||
Vendored
+1
@@ -42,6 +42,7 @@ declare module 'vue' {
|
|||||||
ElRadio: typeof import('element-plus/es')['ElRadio']
|
ElRadio: typeof import('element-plus/es')['ElRadio']
|
||||||
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
||||||
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
||||||
|
ElResult: typeof import('element-plus/es')['ElResult']
|
||||||
ElSelect: typeof import('element-plus/es')['ElSelect']
|
ElSelect: typeof import('element-plus/es')['ElSelect']
|
||||||
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
|
ElSkeleton: typeof import('element-plus/es')['ElSkeleton']
|
||||||
ElSwitch: typeof import('element-plus/es')['ElSwitch']
|
ElSwitch: typeof import('element-plus/es')['ElSwitch']
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref, watch } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue'
|
import ClientSidebarMenuNode from '@/components/ClientSidebarMenuNode.vue'
|
||||||
import {
|
import {
|
||||||
clientNavigation,
|
clientNavigation,
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
getNavigationParentKeys,
|
getNavigationParentKeys,
|
||||||
} from '@/navigation/clientNavigation'
|
} from '@/navigation/clientNavigation'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import { useCustomsPendingStore } from '@/modules/first-leg/public'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
activePath: string
|
activePath: string
|
||||||
@@ -16,6 +17,28 @@ const emit = defineEmits<{
|
|||||||
navigate: [path: string]
|
navigate: [path: string]
|
||||||
}>()
|
}>()
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
|
const customsPending = useCustomsPendingStore()
|
||||||
|
const badges = computed(() => ({ 'first-leg-customs-documents': { count: customsPending.count, error: customsPending.error } }))
|
||||||
|
watch(() => auth.isAuthenticated && auth.hasPermission('order:first-leg:customs-list') ? auth.user?.id ?? '' : '', scope => {
|
||||||
|
customsPending.setScope(scope)
|
||||||
|
if (scope) void customsPending.refresh()
|
||||||
|
}, { immediate: true, flush: 'sync' })
|
||||||
|
function refreshCustomsPending() {
|
||||||
|
if (document.visibilityState === 'visible') void customsPending.refresh()
|
||||||
|
}
|
||||||
|
let refreshTimer: ReturnType<typeof setInterval> | undefined
|
||||||
|
onMounted(() => {
|
||||||
|
refreshTimer = setInterval(refreshCustomsPending, 60_000)
|
||||||
|
window.addEventListener('focus', refreshCustomsPending)
|
||||||
|
document.addEventListener('visibilitychange', refreshCustomsPending)
|
||||||
|
})
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
clearInterval(refreshTimer)
|
||||||
|
window.removeEventListener('focus', refreshCustomsPending)
|
||||||
|
document.removeEventListener('visibilitychange', refreshCustomsPending)
|
||||||
|
customsPending.setScope('')
|
||||||
|
})
|
||||||
|
|
||||||
const visibleNavigation = computed(() => filterNavigationByPermissions(clientNavigation, auth.permissionCodes))
|
const visibleNavigation = computed(() => filterNavigationByPermissions(clientNavigation, auth.permissionCodes))
|
||||||
|
|
||||||
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath)))
|
const activeParentKeys = computed(() => new Set(getNavigationParentKeys(visibleNavigation.value, props.activePath)))
|
||||||
@@ -47,6 +70,7 @@ function handleSelect(path: string) {
|
|||||||
v-for="node in visibleNavigation"
|
v-for="node in visibleNavigation"
|
||||||
:key="node.key"
|
:key="node.key"
|
||||||
:node="node"
|
:node="node"
|
||||||
|
:badges="badges"
|
||||||
:active-path="activePath"
|
:active-path="activePath"
|
||||||
:opened-keys="openedKeys"
|
:opened-keys="openedKeys"
|
||||||
:active-parent-keys="activeParentKeys"
|
:active-parent-keys="activeParentKeys"
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const props = defineProps<{
|
|||||||
activePath: string
|
activePath: string
|
||||||
openedKeys: ReadonlySet<string>
|
openedKeys: ReadonlySet<string>
|
||||||
activeParentKeys: ReadonlySet<string>
|
activeParentKeys: ReadonlySet<string>
|
||||||
|
badges?: Readonly<Record<string, { count: number | null; error: string }>>
|
||||||
level?: number
|
level?: number
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
@@ -16,6 +17,9 @@ const emit = defineEmits<{
|
|||||||
toggle: [key: string]
|
toggle: [key: string]
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
|
const badge = computed(() => props.badges?.[props.node.key])
|
||||||
|
const badgeTitle = computed(() => badge.value?.error || `${badge.value?.count ?? 0} 个柜次待上传资料或确认回执`)
|
||||||
|
|
||||||
const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -54,6 +58,7 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
|||||||
v-for="child in node.children"
|
v-for="child in node.children"
|
||||||
:key="child.key"
|
:key="child.key"
|
||||||
:node="child"
|
:node="child"
|
||||||
|
:badges="badges"
|
||||||
:active-path="activePath"
|
:active-path="activePath"
|
||||||
:opened-keys="openedKeys"
|
:opened-keys="openedKeys"
|
||||||
:active-parent-keys="activeParentKeys"
|
:active-parent-keys="activeParentKeys"
|
||||||
@@ -78,6 +83,14 @@ const groupId = computed(() => `client-nav-group-${props.node.key}`)
|
|||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
<span>{{ node.title }}</span>
|
<span>{{ node.title }}</span>
|
||||||
|
<span v-if="badge?.error || (badge?.count != null && badge.count > 0)" class="client-nav-badge"
|
||||||
|
:title="badgeTitle" :aria-label="badgeTitle" role="status">
|
||||||
|
{{ badge?.error ? '!' : badge!.count! > 99 ? '99+' : badge?.count }}
|
||||||
|
</span>
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
</li>
|
</li>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.client-sidebar-link .client-nav-badge { display: inline-flex; flex: 0 0 auto; min-width: 23px; height: 23px; align-items: center; justify-content: center; margin-left: auto; padding: 0 5px; border: 2px solid #fff; border-radius: 999px; background: #ef4444; color: #fff; box-shadow: 0 3px 9px rgb(239 68 68 / 24%); font-size: 12px; font-weight: 700; line-height: 1; }
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -1,9 +1,76 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
import { 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')
|
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', () => {
|
test('keeps action-only table toolbars on the left', () => {
|
||||||
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
|
assert.match(source, /'data-table__toolbar--actions-only': !\$slots\.toolbar/)
|
||||||
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
|
assert.match(source, /v-if="\$slots\.toolbar" class="data-table__toolbar-heading"/)
|
||||||
|
|||||||
@@ -88,7 +88,9 @@ watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
|
|||||||
page.value = 1
|
page.value = 1
|
||||||
}, { immediate: true })
|
}, { immediate: true })
|
||||||
|
|
||||||
watch([page, pageCount], ([value, count]) => {
|
watch([page, pageCount, () => props.loading, () => Boolean(slots.error)], ([value, count, loading, hasError]) => {
|
||||||
|
// A cleared total is not an authoritative page count while loading or showing a request error.
|
||||||
|
if (loading || hasError) return
|
||||||
const nextValue = normalizePage(value, count)
|
const nextValue = normalizePage(value, count)
|
||||||
if (value !== nextValue) page.value = nextValue
|
if (value !== nextValue) page.value = nextValue
|
||||||
}, { immediate: true })
|
}, { immediate: true })
|
||||||
|
|||||||
@@ -26,13 +26,12 @@ test('test deployment requires an explicit shared network, Gateway and version',
|
|||||||
assert.match(compose, /external: true/)
|
assert.match(compose, /external: true/)
|
||||||
assert.match(compose, /127\.0\.0\.1:/)
|
assert.match(compose, /127\.0\.0\.1:/)
|
||||||
assert.doesNotMatch(compose, /overseas|host\.docker\.internal|production|development/)
|
assert.doesNotMatch(compose, /overseas|host\.docker\.internal|production|development/)
|
||||||
assert.match(jenkins, /label 'java-test'/)
|
assert.match(jenkins, /'java-builder' : 'java-test'/)
|
||||||
assert.match(jenkins, /docker compose -f docker-compose\.test\.yml config --quiet/)
|
assert.match(jenkins, /docker compose -f docker-compose\.test\.yml config --quiet/)
|
||||||
assert.match(jenkins, /docker network inspect/)
|
assert.match(jenkins, /docker network inspect/)
|
||||||
assert.doesNotMatch(jenkins, /docker-compose\.(production|development)|deploy-production|sshUserPrivateKey/)
|
assert.match(jenkins, /scripts\/deploy-production\.sh/)
|
||||||
for (const file of ['docker-compose.production.yml', 'docker-compose.development.yml', 'scripts/deploy-production.sh']) {
|
assert.match(jenkins, /firstleg-production-ssh/)
|
||||||
assert.equal(existsSync(new URL(file, root)), false)
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('application shell is revalidated and missing chunks remain 404', () => {
|
test('application shell is revalidated and missing chunks remain 404', () => {
|
||||||
@@ -52,3 +51,13 @@ test('container build excludes local environment values and waits for Nginx heal
|
|||||||
assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
|
assert.match(compose, /http:\/\/127\.0\.0\.1\/healthz/)
|
||||||
assert.match(jenkins, /up -d --wait --wait-timeout 120/)
|
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 assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
|
||||||
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
const layoutSource = readFileSync(new URL('./AppLayout.vue', import.meta.url), 'utf8')
|
||||||
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
const shellStyles = readFileSync(new URL('../styles/shell.css', import.meta.url), 'utf8')
|
||||||
@@ -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', () => {
|
test('source contract: handles confirmation cancellation but rethrows unexpected logout errors', () => {
|
||||||
assert.match(layoutSource, /async function handleLogout\(\) \{\s*try \{/)
|
assert.match(layoutSource, /async function handleLogout\(\) \{\s*const logoutToken = auth.token\s*try \{/)
|
||||||
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
assert.match(layoutSource, /\} catch \(error\) \{\s*if \(error === 'cancel' \|\| error === 'close'\) return\s*throw error\s*\}/)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -148,3 +150,49 @@ test('source contract: routes denied pages to an explicit 403 state', () => {
|
|||||||
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
assert.match(routerSource, /!auth\.hasPermission\(permission\)/)
|
||||||
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
assert.match(routerSource, /getFirstAccessiblePath\(auth\.permissionCodes\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function logoutHarness(t) {
|
||||||
|
const script = layoutSource.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||||
|
const ast = ts.createSourceFile('layout.ts', script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||||
|
const nodes = ast.statements.filter(node => (ts.isFunctionDeclaration(node) && node.name?.text === 'handleLogout') || (ts.isExpressionStatement(node) && node.getText(ast).startsWith('watch(') && node.getText(ast).includes('() => auth.isAuthenticated')))
|
||||||
|
const code = ts.transpileModule(nodes.map(node => node.getText(ast)).join('\n'), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
let rejectLogout, confirm
|
||||||
|
const remote = new Promise((_, no) => { rejectLogout = no })
|
||||||
|
const confirmation = new Promise(yes => { confirm = yes })
|
||||||
|
const calls = [], warnings = []
|
||||||
|
const auth = vue.reactive({ token: 'A', isAuthenticated: true, logout: () => { calls.push('logout'); auth.token = ''; auth.isAuthenticated = false; return remote } })
|
||||||
|
const scope = vue.effectScope(); t.after(() => scope.stop())
|
||||||
|
const handler = scope.run(() => new Function('watch', 'auth', 'workspace', 'unsaved', 'router', 'ElMessageBox', 'ElMessage', code + ';return handleLogout')(vue.watch, auth, { clear: () => calls.push('workspace') }, { hasDirty: false, clear: () => calls.push('unsaved') }, { replace: path => { calls.push(path); return Promise.resolve() } }, { confirm: () => confirmation }, { warning: value => warnings.push(value) }))
|
||||||
|
return { auth, handler, confirm, rejectLogout, calls, warnings }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('logout navigates before remote completion and late failure cannot affect a new login', async t => {
|
||||||
|
const h = logoutHarness(t)
|
||||||
|
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||||
|
assert.deepEqual(h.calls, ['logout', 'workspace', 'unsaved', '/login'])
|
||||||
|
assert.equal(h.auth.isAuthenticated, false)
|
||||||
|
h.auth.token = 'B'; h.auth.isAuthenticated = true; await vue.nextTick()
|
||||||
|
h.rejectLogout(new Error('SESSION_CHANGED')); await Promise.resolve(); await vue.nextTick()
|
||||||
|
assert.equal(h.auth.token, 'B'); assert.equal(h.auth.isAuthenticated, true)
|
||||||
|
assert.equal(h.calls.filter(item => item === '/login').length, 1)
|
||||||
|
assert.equal(h.warnings.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('cross-tab logout leaves protected route and stale confirmation never logs out a new identity', async t => {
|
||||||
|
const h = logoutHarness(t)
|
||||||
|
const clicked = h.handler()
|
||||||
|
h.auth.token = 'B'; h.confirm(); await clicked
|
||||||
|
assert.equal(h.calls.length, 0)
|
||||||
|
h.auth.token = ''; h.auth.isAuthenticated = false; await vue.nextTick()
|
||||||
|
assert.deepEqual(h.calls, ['workspace', 'unsaved', '/login'])
|
||||||
|
assert.match(layoutSource, /<div v-if="auth.isAuthenticated" class="client-shell"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('remote logout failure reports incomplete server revocation without leaving protected content visible', async t => {
|
||||||
|
const h = logoutHarness(t)
|
||||||
|
const clicked = h.handler(); h.confirm(); await clicked; await vue.nextTick()
|
||||||
|
h.rejectLogout(new Error('offline')); await Promise.resolve()
|
||||||
|
assert.equal(h.auth.isAuthenticated, false)
|
||||||
|
assert.ok(h.calls.includes('/login'))
|
||||||
|
assert.deepEqual(h.warnings, ['已退出本页,服务器会话注销未完成'])
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
import { Bell, LogOut, Menu, X } from '@lucide/vue'
|
||||||
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
import baiyueLogoDark from '@/assets/brand/baiyue-logo-dark.png'
|
||||||
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
import ClientSidebarMenu from '@/components/ClientSidebarMenu.vue'
|
||||||
@@ -108,6 +108,7 @@ watch(
|
|||||||
watch(
|
watch(
|
||||||
() => auth.permissionCodes.join('|'),
|
() => auth.permissionCodes.join('|'),
|
||||||
() => {
|
() => {
|
||||||
|
if (!auth.isAuthenticated) return
|
||||||
const result = workspace.reconcile(isAllowedTab)
|
const result = workspace.reconcile(isAllowedTab)
|
||||||
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
if (result.closedActive) void router.replace(result.fallbackPath ?? getFirstAccessiblePath(auth.permissionCodes))
|
||||||
},
|
},
|
||||||
@@ -119,6 +120,7 @@ watch(
|
|||||||
if (authenticated) return
|
if (authenticated) return
|
||||||
workspace.clear()
|
workspace.clear()
|
||||||
unsaved.clear()
|
unsaved.clear()
|
||||||
|
void router.replace('/login')
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -163,6 +165,7 @@ function handleBeforeUnload(event: BeforeUnloadEvent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleLogout() {
|
async function handleLogout() {
|
||||||
|
const logoutToken = auth.token
|
||||||
try {
|
try {
|
||||||
await ElMessageBox.confirm(unsaved.hasDirty
|
await ElMessageBox.confirm(unsaved.hasDirty
|
||||||
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
? '当前还有未保存的修改,退出后这些内容将丢失。确定继续吗?'
|
||||||
@@ -176,15 +179,16 @@ async function handleLogout() {
|
|||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
|
|
||||||
workspace.clear()
|
if (auth.token !== logoutToken) return
|
||||||
unsaved.clear()
|
void auth.logout().catch(() => {
|
||||||
await auth.logout()
|
if (!auth.isAuthenticated) ElMessage.warning('已退出本页,服务器会话注销未完成')
|
||||||
await router.replace('/login')
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="client-shell" :class="{ 'mobile-menu-open': mobileMenuOpen, '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">
|
<header class="top-header" :inert="mobileMenuOpen" :aria-hidden="mobileMenuOpen ? 'true' : undefined">
|
||||||
<button
|
<button
|
||||||
ref="menuButtonRef"
|
ref="menuButtonRef"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { apiRequest } from '@/api/http'
|
import { apiRequest, revokeCapturedSession } from '@/api/http'
|
||||||
import type { TokenPair } from '@/api/session'
|
import type { TokenPair } from '@/api/session'
|
||||||
|
|
||||||
export interface RegisterMerchantRequest {
|
export interface RegisterMerchantRequest {
|
||||||
@@ -35,8 +35,8 @@ export function registerMerchant(payload: RegisterMerchantRequest) {
|
|||||||
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
return apiRequest<RegisterMerchantResult>({ method: 'POST', url: '/auth/register', data: payload })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function logoutMerchant(refreshToken: string) {
|
export function logoutMerchant(accessToken: string, refreshToken: string) {
|
||||||
return apiRequest<void>({ method: 'POST', url: '/auth/logout', data: { refreshToken } })
|
return revokeCapturedSession(accessToken, refreshToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
export function changeCurrentPassword(oldPassword: string, newPassword: string) {
|
||||||
|
|||||||
+103
-97
@@ -61,18 +61,34 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
const permissionCodes = ref<string[]>([])
|
const permissionCodes = ref<string[]>([])
|
||||||
const sessionRestored = ref(false)
|
const sessionRestored = ref(false)
|
||||||
|
|
||||||
|
let logoutRequest: { accessToken: string; refreshToken: string; promise: Promise<void> } | undefined
|
||||||
|
let generation = 0
|
||||||
|
let contextRequest: { generation: number; promise: Promise<void> } | undefined
|
||||||
|
let restoreTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
function identity(value: MerchantJwtPayload | null) {
|
||||||
|
return value ? JSON.stringify([value.user_id, value.tenant_id, value.membership_id, value.operator_tenant_id, value.app_code, value.client_type]) : ''
|
||||||
|
}
|
||||||
|
|
||||||
function applyToken(accessToken: string) {
|
function applyToken(accessToken: string) {
|
||||||
const decoded = decodeMerchantToken(accessToken)
|
const decoded = decodeMerchantToken(accessToken)
|
||||||
|
const changedIdentity = identity(decoded) !== identity(payload.value)
|
||||||
|
if (accessToken === token.value && payload.value && !changedIdentity) return
|
||||||
|
generation++
|
||||||
|
if (changedIdentity) {
|
||||||
|
user.value = null
|
||||||
|
profile.value = { ...emptyProfile }
|
||||||
|
permissionCodes.value = mapPermissions()
|
||||||
|
}
|
||||||
payload.value = decoded
|
payload.value = decoded
|
||||||
token.value = accessToken
|
token.value = accessToken
|
||||||
user.value = currentUser(decoded, user.value?.tenantName)
|
user.value = currentUser(decoded, user.value?.tenantName)
|
||||||
profile.value.username = decoded.username
|
profile.value.username = decoded.username
|
||||||
profile.value.realName = decoded.username
|
sessionRestored.value = false
|
||||||
permissionCodes.value = mapPermissions()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearSession() {
|
function resetLocalSession() {
|
||||||
clearSessionTokens()
|
generation++
|
||||||
token.value = ''
|
token.value = ''
|
||||||
payload.value = null
|
payload.value = null
|
||||||
user.value = null
|
user.value = null
|
||||||
@@ -81,137 +97,123 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
sessionRestored.value = true
|
sessionRestored.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clearSession() {
|
||||||
|
clearSessionTokens()
|
||||||
|
resetLocalSession()
|
||||||
|
}
|
||||||
|
|
||||||
function applyStoredSession() {
|
function applyStoredSession() {
|
||||||
const storedToken = getAccessToken()
|
const storedToken = getAccessToken()
|
||||||
if (!storedToken) {
|
if (!storedToken) {
|
||||||
token.value = ''
|
resetLocalSession()
|
||||||
payload.value = null
|
|
||||||
user.value = null
|
|
||||||
permissionCodes.value = []
|
|
||||||
profile.value = { ...emptyProfile }
|
|
||||||
sessionRestored.value = true
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
applyToken(storedToken)
|
applyToken(storedToken)
|
||||||
sessionRestored.value = false
|
|
||||||
} catch {
|
|
||||||
clearSession()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.value) {
|
|
||||||
try {
|
|
||||||
applyToken(token.value)
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!(error instanceof MerchantTokenExpiredError && getRefreshToken())) clearSession()
|
resetLocalSession()
|
||||||
|
if (error instanceof MerchantTokenExpiredError && getRefreshToken()) sessionRestored.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
applyStoredSession()
|
||||||
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
const isAuthenticated = computed(() => Boolean(token.value && payload.value))
|
||||||
|
|
||||||
async function loadSessionContext() {
|
|
||||||
if (!payload.value) return
|
|
||||||
const currentPermissionCodes = await getCurrentMerchantPermissionCodes()
|
|
||||||
const currentAccessToken = getAccessToken()
|
|
||||||
if (currentAccessToken && currentAccessToken !== token.value) applyToken(currentAccessToken)
|
|
||||||
permissionCodes.value = mapPermissions(currentPermissionCodes)
|
|
||||||
const [tenant, personalProfile] = await Promise.all([
|
|
||||||
getTenantProfile(),
|
|
||||||
getMerchantPersonalProfile(),
|
|
||||||
])
|
|
||||||
user.value = currentUser(payload.value, tenant.tenantName)
|
|
||||||
profile.value = {
|
|
||||||
...profile.value,
|
|
||||||
realName: personalProfile.displayName || payload.value.username,
|
|
||||||
phone: personalProfile.phone || '',
|
|
||||||
email: personalProfile.email || '',
|
|
||||||
tenantName: tenant.tenantName,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function restoreSession() {
|
async function restoreSession() {
|
||||||
if (sessionRestored.value) return
|
if (sessionRestored.value) return
|
||||||
|
if (contextRequest?.generation === generation) return contextRequest.promise
|
||||||
|
let requestGeneration = generation
|
||||||
|
let requestAccessToken = getAccessToken()
|
||||||
|
const isCurrent = () => requestGeneration === generation && getAccessToken() === requestAccessToken
|
||||||
|
const promise = (async () => {
|
||||||
|
try {
|
||||||
if (!isAuthenticated.value) {
|
if (!isAuthenticated.value) {
|
||||||
if (!getRefreshToken()) {
|
if (!getRefreshToken()) return
|
||||||
sessionRestored.value = true
|
const refreshedToken = await refreshAuthenticatedSession()
|
||||||
return
|
if (requestGeneration !== generation) return restoreSession()
|
||||||
|
applyToken(refreshedToken)
|
||||||
|
requestAccessToken = refreshedToken
|
||||||
|
requestGeneration = generation
|
||||||
|
if (contextRequest) contextRequest.generation = generation
|
||||||
}
|
}
|
||||||
try {
|
const requestPayload = payload.value
|
||||||
applyToken(await refreshAuthenticatedSession())
|
if (!requestPayload) return
|
||||||
|
const [codes, tenant, personalProfile] = await Promise.all([
|
||||||
|
getCurrentMerchantPermissionCodes(), getTenantProfile(), getMerchantPersonalProfile(),
|
||||||
|
])
|
||||||
|
if (!isCurrent()) {
|
||||||
|
applyStoredSession()
|
||||||
|
return restoreSession()
|
||||||
|
}
|
||||||
|
permissionCodes.value = mapPermissions(codes)
|
||||||
|
user.value = currentUser(requestPayload, tenant.tenantName)
|
||||||
|
profile.value = {
|
||||||
|
username: requestPayload.username,
|
||||||
|
realName: personalProfile.displayName || requestPayload.username,
|
||||||
|
phone: personalProfile.phone || '', email: personalProfile.email || '', tenantName: tenant.tenantName,
|
||||||
|
}
|
||||||
|
sessionRestored.value = true
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!isCurrent()) return
|
||||||
|
sessionRestored.value = false
|
||||||
if (isExpiredSessionError(error)) {
|
if (isExpiredSessionError(error)) {
|
||||||
clearSession()
|
clearSession()
|
||||||
throw error
|
throw error
|
||||||
}
|
}
|
||||||
sessionRestored.value = true
|
}
|
||||||
return
|
})()
|
||||||
|
contextRequest = { generation: requestGeneration, promise }
|
||||||
|
try { await promise } finally {
|
||||||
|
if (contextRequest?.promise === promise) contextRequest = undefined
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
await loadSessionContext()
|
function synchronizeSession() {
|
||||||
} catch (error) {
|
// Identity changes and logout revoke local rights immediately. Coalesce pair writes
|
||||||
if (isExpiredSessionError(error)) {
|
// before loading the new context; same-identity rotation retains confirmed rights.
|
||||||
clearSession()
|
applyStoredSession()
|
||||||
throw error
|
if (restoreTimer) clearTimeout(restoreTimer)
|
||||||
}
|
restoreTimer = setTimeout(() => {
|
||||||
sessionRestored.value = true
|
restoreTimer = undefined
|
||||||
return
|
void restoreSession().catch(() => {})
|
||||||
}
|
}, 0)
|
||||||
sessionRestored.value = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function login(loginId: string, password: string, remember = false) {
|
async function login(loginId: string, password: string, remember = false) {
|
||||||
|
const attempt = ++generation
|
||||||
const tokens = await loginMerchant(loginId, password)
|
const tokens = await loginMerchant(loginId, password)
|
||||||
const decoded = decodeMerchantToken(tokens.accessToken)
|
if (attempt !== generation) return
|
||||||
|
decodeMerchantToken(tokens.accessToken)
|
||||||
persistTokenPair(tokens)
|
persistTokenPair(tokens)
|
||||||
persistRememberedLoginId(loginId, remember)
|
persistRememberedLoginId(loginId, remember)
|
||||||
token.value = tokens.accessToken
|
applyToken(tokens.accessToken)
|
||||||
payload.value = decoded
|
await restoreSession()
|
||||||
user.value = currentUser(decoded)
|
|
||||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
|
||||||
permissionCodes.value = mapPermissions()
|
|
||||||
sessionRestored.value = false
|
|
||||||
try {
|
|
||||||
await loadSessionContext()
|
|
||||||
sessionRestored.value = true
|
|
||||||
} catch (error) {
|
|
||||||
if (isExpiredSessionError(error)) {
|
|
||||||
clearSession()
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
sessionRestored.value = true
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function acceptImpersonationCode(code: string) {
|
async function acceptImpersonationCode(code: string) {
|
||||||
|
const attempt = ++generation
|
||||||
const exchanged = await exchangeImpersonationCode(code)
|
const exchanged = await exchangeImpersonationCode(code)
|
||||||
const decoded = decodeMerchantToken(exchanged.accessToken)
|
if (attempt !== generation) return
|
||||||
|
decodeMerchantToken(exchanged.accessToken)
|
||||||
persistTemporaryAccessToken(exchanged.accessToken)
|
persistTemporaryAccessToken(exchanged.accessToken)
|
||||||
token.value = exchanged.accessToken
|
applyToken(exchanged.accessToken)
|
||||||
payload.value = decoded
|
await restoreSession()
|
||||||
user.value = currentUser(decoded)
|
|
||||||
profile.value = { ...emptyProfile, username: decoded.username, realName: decoded.username }
|
|
||||||
permissionCodes.value = mapPermissions()
|
|
||||||
sessionRestored.value = false
|
|
||||||
try {
|
|
||||||
await loadSessionContext()
|
|
||||||
} catch (error) {
|
|
||||||
if (isExpiredSessionError(error)) {
|
|
||||||
clearSession()
|
|
||||||
throw error
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sessionRestored.value = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function logout() {
|
function logout() {
|
||||||
|
const accessToken = getAccessToken()
|
||||||
const refreshToken = getRefreshToken()
|
const refreshToken = getRefreshToken()
|
||||||
try {
|
if (logoutRequest && ((!accessToken && !refreshToken)
|
||||||
if (refreshToken) await logoutMerchant(refreshToken)
|
|| (logoutRequest.accessToken === accessToken && logoutRequest.refreshToken === refreshToken))) return logoutRequest.promise
|
||||||
} finally {
|
const pending = accessToken || refreshToken
|
||||||
|
? logoutMerchant(accessToken, refreshToken)
|
||||||
|
: Promise.resolve()
|
||||||
clearSession()
|
clearSession()
|
||||||
}
|
const request = { accessToken, refreshToken, promise: pending.finally(() => {
|
||||||
|
if (logoutRequest === request) logoutRequest = undefined
|
||||||
|
}) }
|
||||||
|
logoutRequest = request
|
||||||
|
return request.promise
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasPermission(permission?: string) {
|
function hasPermission(permission?: string) {
|
||||||
@@ -224,10 +226,13 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
|
async function savePersonalProfile(next: Pick<ClientAccountProfile, 'realName' | 'email'>) {
|
||||||
|
const requestGeneration = generation
|
||||||
|
const requestToken = getAccessToken()
|
||||||
const updated = await updateMerchantPersonalProfile({
|
const updated = await updateMerchantPersonalProfile({
|
||||||
displayName: next.realName.trim(),
|
displayName: next.realName.trim(),
|
||||||
email: next.email.trim(),
|
email: next.email.trim(),
|
||||||
})
|
})
|
||||||
|
if (requestGeneration !== generation || requestToken !== getAccessToken()) return
|
||||||
updateProfile({
|
updateProfile({
|
||||||
realName: updated.displayName,
|
realName: updated.displayName,
|
||||||
phone: updated.phone || '',
|
phone: updated.phone || '',
|
||||||
@@ -236,8 +241,9 @@ export const useAuthStore = defineStore('client-auth', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('cc-client-session-expired', clearSession)
|
window.addEventListener('cc-client-session-expired', clearSession)
|
||||||
|
window.addEventListener('cc-client-session-updated', synchronizeSession)
|
||||||
window.addEventListener('storage', (event) => {
|
window.addEventListener('storage', (event) => {
|
||||||
if (event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token') applyStoredSession()
|
if (event.storageArea === localStorage && (event.key === null || event.key === 'cc-client-access-token' || event.key === 'cc-client-refresh-token')) synchronizeSession()
|
||||||
})
|
})
|
||||||
|
|
||||||
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
|
return { token, user, profile, permissionCodes, isAuthenticated, sessionRestored, hasPermission, login, logout, clearSession, restoreSession, acceptImpersonationCode, updateProfile, savePersonalProfile }
|
||||||
|
|||||||
@@ -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', () => {
|
test('uses real auth endpoints and single-flight refresh handling', () => {
|
||||||
assert.match(authApiSource, /\/auth\/login/)
|
assert.match(authApiSource, /\/auth\/login/)
|
||||||
assert.match(authApiSource, /\/auth\/register/)
|
assert.match(authApiSource, /\/auth\/register/)
|
||||||
assert.match(authApiSource, /\/auth\/logout/)
|
assert.match(authApiSource, /revokeCapturedSession\(accessToken, refreshToken\)/)
|
||||||
|
assert.match(httpSource, /\/auth\/logout/)
|
||||||
assert.match(httpSource, /refreshPromise/)
|
assert.match(httpSource, /refreshPromise/)
|
||||||
assert.match(httpSource, /\/auth\/refresh/)
|
assert.match(httpSource, /\/auth\/refresh/)
|
||||||
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
assert.match(httpSource, /persistTokenPair\(tokens\)/)
|
||||||
@@ -117,7 +118,8 @@ test('uses real auth endpoints and single-flight refresh handling', () => {
|
|||||||
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
assert.match(httpSource, /window\.location\.replace\(`\/login\?redirect=\$\{encodeURIComponent\(redirect\)\}`\)/)
|
||||||
assert.match(authStoreSource, /decodeMerchantToken/)
|
assert.match(authStoreSource, /decodeMerchantToken/)
|
||||||
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
|
assert.match(authStoreSource, /MerchantTokenExpiredError && getRefreshToken\(\)/)
|
||||||
assert.match(authStoreSource, /applyToken\(await refreshAuthenticatedSession\(\)\)/)
|
assert.match(authStoreSource, /const refreshedToken = await refreshAuthenticatedSession\(\)/)
|
||||||
|
assert.match(authStoreSource, /applyToken\(refreshedToken\)/)
|
||||||
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
assert.doesNotMatch(authStoreSource, /mock-client:/)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -152,7 +154,7 @@ test('shows a forced re-login notice after login identifiers change', () => {
|
|||||||
test('keeps a valid local session during temporary context and refresh outages', () => {
|
test('keeps a valid local session during temporary context and refresh outages', () => {
|
||||||
assert.match(authStoreSource, /function isExpiredSessionError/)
|
assert.match(authStoreSource, /function isExpiredSessionError/)
|
||||||
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
assert.match(authStoreSource, /if \(isExpiredSessionError\(error\)\)/)
|
||||||
assert.match(authStoreSource, /sessionRestored\.value = true\s+return/)
|
assert.match(authStoreSource, /if \(!isCurrent\(\)\) return\s+sessionRestored\.value = false/)
|
||||||
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
assert.match(httpSource, /if \(mappedError\.status === 401 \|\| mappedError\.code === 'A0401'\)/)
|
||||||
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
assert.doesNotMatch(httpSource, /catch \(refreshError\) \{\s+clearSessionTokens\(\)/)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ export interface PageResult<T> {
|
|||||||
pages: number
|
pages: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CrossBorderBusinessKind = 'procurement' | 'trucking' | 'looseboard'
|
export type CrossBorderBusinessKind = 'trucking' | 'looseboard'
|
||||||
|
|
||||||
export interface BusinessOrderQuery {
|
export interface BusinessOrderQuery {
|
||||||
page: number
|
page: number
|
||||||
@@ -16,8 +16,6 @@ export interface BusinessOrderQuery {
|
|||||||
orderNo?: string
|
orderNo?: string
|
||||||
status?: string
|
status?: string
|
||||||
routeKeyword?: string
|
routeKeyword?: string
|
||||||
productName?: string
|
|
||||||
purchaseCategory?: string
|
|
||||||
transportType?: string
|
transportType?: string
|
||||||
transportMode?: string
|
transportMode?: string
|
||||||
requestedFrom?: string
|
requestedFrom?: string
|
||||||
@@ -26,59 +24,12 @@ export interface BusinessOrderQuery {
|
|||||||
createdTo?: string
|
createdTo?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ProcurementSummary {
|
|
||||||
orderNo: string
|
|
||||||
purchaseCategory: string
|
|
||||||
productName: string
|
|
||||||
productSpecification: string | null
|
|
||||||
purchaseQuantity: number
|
|
||||||
budgetUnitPrice: number | null
|
|
||||||
currency: string | null
|
|
||||||
inboundQuantity: number
|
|
||||||
outboundQuantity: number
|
|
||||||
inventoryQuantity: number
|
|
||||||
status: string
|
|
||||||
version: number
|
|
||||||
createdAt: string
|
|
||||||
updatedAt: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ProcurementDetail {
|
|
||||||
summary: ProcurementSummary
|
|
||||||
productUrl: string | null
|
|
||||||
receivingAddress: string | null
|
|
||||||
contactName: string
|
|
||||||
contactPhone: string
|
|
||||||
domesticCarrier: string | null
|
|
||||||
domesticTrackingNo: string | null
|
|
||||||
overseasCarrier: string | null
|
|
||||||
overseasTrackingNo: string | null
|
|
||||||
estimatedArrivalAt: string | null
|
|
||||||
remark: string | null
|
|
||||||
reviewRemark: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ProcurementCreate {
|
|
||||||
customerName: string
|
|
||||||
purchaseCategory: string
|
|
||||||
productName: string
|
|
||||||
productSpecification?: string
|
|
||||||
productUrl?: string
|
|
||||||
purchaseQuantity: number
|
|
||||||
budgetUnitPrice?: number
|
|
||||||
currency?: string
|
|
||||||
receivingAddress?: string
|
|
||||||
contactName: string
|
|
||||||
contactPhone: string
|
|
||||||
remark?: string
|
|
||||||
idempotencyKey: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TransportSummary {
|
export interface TransportSummary {
|
||||||
|
fleetArrangement: import('../fleetArrangement').FleetArrangement | null
|
||||||
orderNo: string
|
orderNo: string
|
||||||
transportType: string
|
transportType: string
|
||||||
transportMode?: string
|
transportMode?: string
|
||||||
palletRequired?: string
|
palletRequired?: string | null
|
||||||
origin: string
|
origin: string
|
||||||
destination: string
|
destination: string
|
||||||
containerType: string | null
|
containerType: string | null
|
||||||
@@ -131,7 +82,6 @@ export interface TransportUpdate extends Omit<TransportCreate, 'idempotencyKey'>
|
|||||||
}
|
}
|
||||||
|
|
||||||
const endpointByKind: Record<CrossBorderBusinessKind, string> = {
|
const endpointByKind: Record<CrossBorderBusinessKind, string> = {
|
||||||
procurement: '/merchant/v1/last-leg/overseas-procurements',
|
|
||||||
trucking: '/merchant/v1/last-leg/us-truck-orders',
|
trucking: '/merchant/v1/last-leg/us-truck-orders',
|
||||||
looseboard: '/merchant/v1/last-leg/local-looseboard-orders',
|
looseboard: '/merchant/v1/last-leg/local-looseboard-orders',
|
||||||
}
|
}
|
||||||
@@ -148,10 +98,6 @@ export function getBusinessOrder<T>(kind: CrossBorderBusinessKind, orderNo: stri
|
|||||||
return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
return apiRequest<T>({ method: 'GET', url: `${endpointByKind[kind]}/${encodeURIComponent(orderNo)}` })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createProcurement(payload: ProcurementCreate) {
|
|
||||||
return apiRequest<ProcurementDetail>({ method: 'POST', url: endpointByKind.procurement, data: payload })
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) {
|
export function createTransport(kind: 'trucking' | 'looseboard', payload: TransportCreate) {
|
||||||
return apiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
|
return apiRequest<TransportDetail>({ method: 'POST', url: endpointByKind[kind], data: payload })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { apiRequest } from '@/api/http'
|
||||||
|
import type { PageResult } from './businessOrders'
|
||||||
|
|
||||||
|
export type Amount = number | string
|
||||||
|
export interface ProcurementSummary {
|
||||||
|
orderNo: string
|
||||||
|
purchaseCategory: string
|
||||||
|
productName: string
|
||||||
|
productSpecification: string | null
|
||||||
|
purchaseQuantity: number
|
||||||
|
budgetUnitPrice: Amount | null
|
||||||
|
currency: string | null
|
||||||
|
status: string
|
||||||
|
version: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
export interface ProcurementOrder extends ProcurementSummary {
|
||||||
|
productUrl: string | null
|
||||||
|
receivingAddress: string
|
||||||
|
contactName: string
|
||||||
|
contactPhone: string
|
||||||
|
estimatedArrivalAt: string | null
|
||||||
|
plannedWarehouseName: string | null
|
||||||
|
actualWarehouseCode: string | null
|
||||||
|
actualWarehouseName: string | null
|
||||||
|
}
|
||||||
|
export interface ProcurementFee {
|
||||||
|
feeNo: string
|
||||||
|
purpose: string
|
||||||
|
name: string
|
||||||
|
version: number | null
|
||||||
|
active: boolean
|
||||||
|
determination: string
|
||||||
|
amount: Amount
|
||||||
|
currency: string
|
||||||
|
originalAmount: Amount | null
|
||||||
|
originalCurrency: string | null
|
||||||
|
exchangeRate: Amount | null
|
||||||
|
exchangeRateMonth: string | null
|
||||||
|
businessDate: string | null
|
||||||
|
parentFeeNo: string | null
|
||||||
|
walletStatus: string | null
|
||||||
|
sourceLinked: boolean
|
||||||
|
}
|
||||||
|
export interface ProcurementBox {
|
||||||
|
cartonNo: string
|
||||||
|
quantity: number
|
||||||
|
lengthCm: Amount
|
||||||
|
widthCm: Amount
|
||||||
|
heightCm: Amount
|
||||||
|
grossWeightKg: Amount
|
||||||
|
}
|
||||||
|
export interface ProcurementShipment {
|
||||||
|
shipmentNo: string
|
||||||
|
leg: 'OVERSEAS' | 'DOMESTIC'
|
||||||
|
shippedAt: string
|
||||||
|
cartonNo: string
|
||||||
|
quantity: number
|
||||||
|
carrier: string
|
||||||
|
trackingNo: string
|
||||||
|
}
|
||||||
|
export interface ProcurementDetail {
|
||||||
|
order: ProcurementOrder
|
||||||
|
budget: { totalAmount: Amount | null; currency: string; authorizedAt: string | null }
|
||||||
|
purchased: boolean
|
||||||
|
purchaseConfirmed: boolean
|
||||||
|
purchaseNeedsAttention: boolean
|
||||||
|
progress: { key: string; title: string; completedAt: string | null }[]
|
||||||
|
boxes: ProcurementBox[]
|
||||||
|
shipments: ProcurementShipment[]
|
||||||
|
fees: ProcurementFee[]
|
||||||
|
exceptionSummaries: string[]
|
||||||
|
}
|
||||||
|
export interface ProcurementCreate {
|
||||||
|
customerName: string
|
||||||
|
purchaseCategory: string
|
||||||
|
productName: string
|
||||||
|
productSpecification?: string
|
||||||
|
productUrl?: string
|
||||||
|
purchaseQuantity: number
|
||||||
|
budgetUnitPrice: number
|
||||||
|
currency: 'CNY' | 'USD'
|
||||||
|
receivingAddress: string
|
||||||
|
contactName: string
|
||||||
|
contactPhone: string
|
||||||
|
remark?: string
|
||||||
|
idempotencyKey: string
|
||||||
|
}
|
||||||
|
export interface ProcurementQuery {
|
||||||
|
page: number
|
||||||
|
size: number
|
||||||
|
orderNo?: string
|
||||||
|
productName?: string
|
||||||
|
purchaseCategory?: string
|
||||||
|
status?: string
|
||||||
|
}
|
||||||
|
const endpoint = '/merchant/v1/last-leg/overseas-procurements'
|
||||||
|
export async function listProcurements(params: ProcurementQuery) {
|
||||||
|
const result = await apiRequest<PageResult<ProcurementSummary>>({ method: 'GET', url: endpoint, params })
|
||||||
|
return { ...result, page: Number(result.page), size: Number(result.size), total: Number(result.total), pages: Number(result.pages) }
|
||||||
|
}
|
||||||
|
export function getProcurement(orderNo: string) {
|
||||||
|
return apiRequest<ProcurementDetail>({ method: 'GET', url: `${endpoint}/${encodeURIComponent(orderNo)}` })
|
||||||
|
}
|
||||||
|
export function createProcurement(data: ProcurementCreate) {
|
||||||
|
return apiRequest<ProcurementDetail>({ method: 'POST', url: endpoint, data })
|
||||||
|
}
|
||||||
@@ -1,10 +1,39 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
import { runInNewContext } from 'node:vm'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
const api = readFileSync(new URL('./api/businessOrders.ts', import.meta.url), 'utf8')
|
const api = readFileSync(new URL('./api/businessOrders.ts', import.meta.url), 'utf8')
|
||||||
const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8')
|
const routes = readFileSync(new URL('./routes.ts', import.meta.url), 'utf8')
|
||||||
const view = readFileSync(new URL('./components/BusinessOrdersView.vue', import.meta.url), 'utf8')
|
const view = readFileSync(new URL('./components/BusinessOrdersView.vue', import.meta.url), 'utf8')
|
||||||
|
const procurementApi = readFileSync(new URL('./api/procurement.ts', import.meta.url), 'utf8')
|
||||||
|
const procurementView = readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
test('renders unknown pallet service and container type as dashes while preserving explicit values', () => {
|
||||||
|
const helpers = view.slice(view.indexOf('function read('), view.indexOf('function idempotencyKey('))
|
||||||
|
const compiled = ts.transpileModule(helpers, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const { displayCell, yesNo, text } = runInNewContext(`${compiled}\n({ displayCell, yesNo, text })`)
|
||||||
|
assert.equal(displayCell({ palletRequired: null }, 'palletRequired'), '—')
|
||||||
|
assert.equal(displayCell({ palletRequired: 'NO' }, 'palletRequired'), '否')
|
||||||
|
assert.equal(displayCell({ palletRequired: 'YES' }, 'palletRequired'), '是')
|
||||||
|
assert.equal(displayCell({ containerType: null }, 'containerType'), '—')
|
||||||
|
assert.equal(displayCell({ containerType: '40HQ' }, 'containerType'), '40HQ')
|
||||||
|
assert.equal(yesNo(null), '—')
|
||||||
|
assert.equal(text(null), '—')
|
||||||
|
assert.match(api, /palletRequired\?: string \| null/)
|
||||||
|
const create = api.slice(api.indexOf('export interface TransportCreate'), api.indexOf('export interface TransportUpdate'))
|
||||||
|
assert.doesNotMatch(create, /palletRequired\?: string \| null/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('shows merchant-owned arrangement facts without a pool request or editable status control', () => {
|
||||||
|
assert.match(api, /fleetArrangement: import\('\.\.\/fleetArrangement'\)\.FleetArrangement \| null/)
|
||||||
|
assert.match(view, /aria-label="承运安排"/)
|
||||||
|
for (const field of ['signedPackages', 'unsignedPackages', 'returnedPackages', 'readOnlyReason']) assert.ok(view.includes(`fleetArrangement.${field}`))
|
||||||
|
assert.doesNotMatch(api, /capacity-offers|fleet\/trips/)
|
||||||
|
assert.match(view, /if \(query\.page !== 1\) query\.page = 1\s+else void load\(\)/)
|
||||||
|
assert.match(view, /if \(reloadDirectly\) void load\(\)/)
|
||||||
|
})
|
||||||
|
|
||||||
test('activates all three customer cross-border pages with frozen permissions', () => {
|
test('activates all three customer cross-border pages with frozen permissions', () => {
|
||||||
for (const [path, permission] of [
|
for (const [path, permission] of [
|
||||||
@@ -15,14 +44,15 @@ test('activates all three customer cross-border pages with frozen permissions',
|
|||||||
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?release: 'active'[\\s\\S]*?permission: '${permission}'`))
|
assert.match(routes, new RegExp(`path: '${path}'[\\s\\S]*?release: 'active'[\\s\\S]*?permission: '${permission}'`))
|
||||||
}
|
}
|
||||||
assert.doesNotMatch(view, /PrototypeFeatureView|mock|customerId|tenantId/i)
|
assert.doesNotMatch(view, /PrototypeFeatureView|mock|customerId|tenantId/i)
|
||||||
assert.match(view, /merchant:cross-border:procurement:create/)
|
assert.match(procurementView, /merchant:cross-border:procurement:create/)
|
||||||
assert.match(view, /merchant:cross-border:domestic-trucking:create/)
|
assert.match(view, /merchant:cross-border:domestic-trucking:create/)
|
||||||
assert.match(view, /merchant:cross-border:pallet-shipping:create/)
|
assert.match(view, /merchant:cross-border:pallet-shipping:create/)
|
||||||
assert.match(view, /v-if="canCreate"[^>]*type="primary"/)
|
assert.match(view, /v-if="canCreate"[^>]*type="primary"/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('uses only merchant overseas endpoints and keeps retry idempotency stable', () => {
|
test('uses only merchant overseas endpoints and keeps retry idempotency stable', () => {
|
||||||
assert.match(api, /overseas-procurements/)
|
assert.match(procurementApi, /overseas-procurements/)
|
||||||
|
assert.doesNotMatch(api, /overseas-procurements|ProcurementSummary|ProcurementDetail/)
|
||||||
assert.match(api, /us-truck-orders/)
|
assert.match(api, /us-truck-orders/)
|
||||||
assert.match(api, /local-looseboard-orders/)
|
assert.match(api, /local-looseboard-orders/)
|
||||||
assert.doesNotMatch(api, /\/platform\/|\/internal\/|customerId|tenantId/)
|
assert.doesNotMatch(api, /\/platform\/|\/internal\/|customerId|tenantId/)
|
||||||
@@ -42,11 +72,9 @@ test('covers list detail create loading error empty pagination and actions-first
|
|||||||
assert.match(view, /<DataTable[^>]*:row-actions="getRowActions"/)
|
assert.match(view, /<DataTable[^>]*:row-actions="getRowActions"/)
|
||||||
assert.match(view, /key: 'actions', label: '操作', width: 90, fixed: 'left'/)
|
assert.match(view, /key: 'actions', label: '操作', width: 90, fixed: 'left'/)
|
||||||
assert.match(view, /class="business-table-card"/)
|
assert.match(view, /class="business-table-card"/)
|
||||||
assert.match(view, /PENDING_OUTBOUND: '待出库'/)
|
assert.doesNotMatch(procurementView, /inventoryQuantity|outboundQuantity|reviewRemark/)
|
||||||
assert.match(view, /PARTIALLY_OUTBOUND: '部分出库'/)
|
assert.match(procurementView, /procurementStatuses/)
|
||||||
assert.match(view, /OUTBOUNDED: '全部出库'/)
|
assert.match(procurementView, /ProcurementDetailPanel/)
|
||||||
assert.match(view, /\['入库量', read\(summary, 'inboundQuantity'\)\]/)
|
|
||||||
assert.match(view, /\['审核备注', current\.reviewRemark\]/)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('opens every dashboard cross-border action on a dedicated protected create page', () => {
|
test('opens every dashboard cross-border action on a dedicated protected create page', () => {
|
||||||
@@ -73,7 +101,7 @@ test('opens all cross-border details on dedicated protected routes', () => {
|
|||||||
assert.match(view, /class="business-detail-error"/)
|
assert.match(view, /class="business-detail-error"/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('keeps procurement filters, details and forms readable at PDA width', () => {
|
test('preserves the existing transport responsive rules without adding a narrow-screen procurement acceptance gate', () => {
|
||||||
assert.match(view, /@media \(max-width: 767px\)/)
|
assert.match(view, /@media \(max-width: 767px\)/)
|
||||||
assert.match(view, /queryFields/)
|
assert.match(view, /queryFields/)
|
||||||
assert.match(view, /\.detail-grid \{ grid-template-columns: 1fr; \}/)
|
assert.match(view, /\.detail-grid \{ grid-template-columns: 1fr; \}/)
|
||||||
|
|||||||
@@ -7,17 +7,15 @@ import QueryToolbar, { type QueryField, type QueryModel } from '@/components/com
|
|||||||
import type { TableAction } from '@/components/common/tableActions'
|
import type { TableAction } from '@/components/common/tableActions'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
import {
|
import {
|
||||||
createProcurement,
|
|
||||||
createTransport,
|
createTransport,
|
||||||
getBusinessOrder,
|
getBusinessOrder,
|
||||||
listBusinessOrders,
|
listBusinessOrders,
|
||||||
type CrossBorderBusinessKind,
|
type CrossBorderBusinessKind,
|
||||||
type ProcurementDetail,
|
|
||||||
type ProcurementSummary,
|
|
||||||
type TransportDetail,
|
type TransportDetail,
|
||||||
type TransportSummary,
|
type TransportSummary,
|
||||||
} from '../api/businessOrders'
|
} from '../api/businessOrders'
|
||||||
import { CONTAINER_SPECIFICATIONS, DEFAULT_CONTAINER_TYPE } from '../containerSpecifications'
|
import { CONTAINER_SPECIFICATIONS, DEFAULT_CONTAINER_TYPE } from '../containerSpecifications'
|
||||||
|
import { poolOrderStatusLabels } from '../fleetArrangement'
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
|
const props = withDefaults(defineProps<{ kind: CrossBorderBusinessKind; createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
|
||||||
const auth = useAuthStore()
|
const auth = useAuthStore()
|
||||||
@@ -25,23 +23,17 @@ const router = useRouter()
|
|||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const detailOrderNo = computed(() => String(route.params.orderNo || ''))
|
const detailOrderNo = computed(() => String(route.params.orderNo || ''))
|
||||||
const canCreate = computed(() => auth.hasPermission(({
|
const canCreate = computed(() => auth.hasPermission(({
|
||||||
procurement: 'merchant:cross-border:procurement:create',
|
|
||||||
trucking: 'merchant:cross-border:domestic-trucking:create',
|
trucking: 'merchant:cross-border:domestic-trucking:create',
|
||||||
looseboard: 'merchant:cross-border:pallet-shipping:create',
|
looseboard: 'merchant:cross-border:pallet-shipping:create',
|
||||||
} as Record<CrossBorderBusinessKind, string>)[props.kind]))
|
} as Record<CrossBorderBusinessKind, string>)[props.kind]))
|
||||||
|
|
||||||
type BusinessRow = ProcurementSummary | TransportSummary
|
type BusinessRow = TransportSummary
|
||||||
type BusinessDetail = ProcurementDetail | TransportDetail
|
type BusinessDetail = TransportDetail
|
||||||
type PageMode = 'list' | 'create' | 'detail'
|
type PageMode = 'list' | 'create' | 'detail'
|
||||||
|
|
||||||
interface ColumnDefinition { key: string; label: string; width?: number }
|
interface ColumnDefinition { key: string; label: string; width?: number }
|
||||||
|
|
||||||
interface BusinessForm {
|
interface BusinessForm {
|
||||||
purchaseCategory: string
|
|
||||||
productName: string
|
|
||||||
productSpecification: string
|
|
||||||
productUrl: string
|
|
||||||
purchaseQuantity: number
|
|
||||||
transportMode: string
|
transportMode: string
|
||||||
palletRequired: string
|
palletRequired: string
|
||||||
transportType: string
|
transportType: string
|
||||||
@@ -59,28 +51,10 @@ interface BusinessForm {
|
|||||||
contactName: string
|
contactName: string
|
||||||
contactInfo: string
|
contactInfo: string
|
||||||
requestedDate: string
|
requestedDate: string
|
||||||
receivingAddress: string
|
|
||||||
remark: string
|
remark: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const configuration = computed(() => ({
|
const configuration = computed(() => ({
|
||||||
procurement: {
|
|
||||||
title: '海外采购',
|
|
||||||
description: '查询并管理海外采购订单',
|
|
||||||
columns: [
|
|
||||||
{ key: 'orderNo', label: '订单号', width: 180 },
|
|
||||||
{ key: 'purchaseCategory', label: '采购品类', width: 130 },
|
|
||||||
{ key: 'productName', label: '商品名称', width: 160 },
|
|
||||||
{ key: 'productSpecification', label: '商品规格', width: 160 },
|
|
||||||
{ key: 'purchaseQuantity', label: '采购数量', width: 100 },
|
|
||||||
{ key: 'budgetUnitPrice', label: '预算单价', width: 110 },
|
|
||||||
{ key: 'inboundQuantity', label: '入库量', width: 90 },
|
|
||||||
{ key: 'outboundQuantity', label: '出库量', width: 90 },
|
|
||||||
{ key: 'inventoryQuantity', label: '库存量', width: 90 },
|
|
||||||
{ key: 'status', label: '状态', width: 120 },
|
|
||||||
{ key: 'createdAt', label: '创建时间', width: 170 },
|
|
||||||
] satisfies ColumnDefinition[],
|
|
||||||
},
|
|
||||||
trucking: {
|
trucking: {
|
||||||
title: '美国本土卡',
|
title: '美国本土卡',
|
||||||
description: '查询并管理美国本土卡订单',
|
description: '查询并管理美国本土卡订单',
|
||||||
@@ -105,6 +79,7 @@ function transportColumns(looseboard: boolean): ColumnDefinition[] {
|
|||||||
{ key: 'budgetAmount', label: '预算总价', width: 110 },
|
{ key: 'budgetAmount', label: '预算总价', width: 110 },
|
||||||
{ key: 'requestedDate', label: '要求时间', width: 120 },
|
{ key: 'requestedDate', label: '要求时间', width: 120 },
|
||||||
{ key: 'status', label: '状态', width: 130 },
|
{ key: 'status', label: '状态', width: 130 },
|
||||||
|
{ key: 'fleetArrangement', label: '承运安排', width: 190 },
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,22 +90,19 @@ const submitKey = ref('')
|
|||||||
const error = ref('')
|
const error = ref('')
|
||||||
const rows = ref<BusinessRow[]>([])
|
const rows = ref<BusinessRow[]>([])
|
||||||
const detail = ref<BusinessDetail | null>(null)
|
const detail = ref<BusinessDetail | null>(null)
|
||||||
|
const fleetArrangement = computed(() => detail.value ? (detail.value as TransportDetail).summary.fleetArrangement : null)
|
||||||
const formRef = ref<FormInstance>()
|
const formRef = ref<FormInstance>()
|
||||||
const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' })
|
const query = reactive({ page: 1, size: 20, orderNo: '', routeKeyword: '', status: '' })
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
|
|
||||||
const queryModel = computed<QueryModel>({
|
const queryModel = computed<QueryModel>({
|
||||||
get: () => ({
|
get: () => ({
|
||||||
orderNo: query.orderNo,
|
orderNo: query.orderNo,
|
||||||
purchaseCategory: query.purchaseCategory,
|
|
||||||
productName: query.productName,
|
|
||||||
routeKeyword: query.routeKeyword,
|
routeKeyword: query.routeKeyword,
|
||||||
status: query.status,
|
status: query.status,
|
||||||
}),
|
}),
|
||||||
set: (value) => {
|
set: (value) => {
|
||||||
query.orderNo = String(value.orderNo || '')
|
query.orderNo = String(value.orderNo || '')
|
||||||
query.purchaseCategory = String(value.purchaseCategory || '')
|
|
||||||
query.productName = String(value.productName || '')
|
|
||||||
query.routeKeyword = String(value.routeKeyword || '')
|
query.routeKeyword = String(value.routeKeyword || '')
|
||||||
query.status = String(value.status || '')
|
query.status = String(value.status || '')
|
||||||
},
|
},
|
||||||
@@ -138,12 +110,7 @@ const queryModel = computed<QueryModel>({
|
|||||||
|
|
||||||
const queryFields = computed<QueryField[]>(() => [
|
const queryFields = computed<QueryField[]>(() => [
|
||||||
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||||
...(props.kind === 'procurement'
|
{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: '请输入起运地或目的地' },
|
||||||
? [
|
|
||||||
{ key: 'purchaseCategory', label: '采购品类', type: 'input', placeholder: '请输入采购品类' } as QueryField,
|
|
||||||
{ key: 'productName', label: '商品名称', type: 'input', placeholder: '请输入商品名称' } as QueryField,
|
|
||||||
]
|
|
||||||
: [{ key: 'routeKeyword', label: '运输路线', type: 'input', placeholder: '请输入起运地或目的地' } as QueryField]),
|
|
||||||
{
|
{
|
||||||
key: 'status',
|
key: 'status',
|
||||||
label: '状态',
|
label: '状态',
|
||||||
@@ -153,10 +120,8 @@ const queryFields = computed<QueryField[]>(() => [
|
|||||||
{ label: '待审核', value: 'PENDING_REVIEW' },
|
{ label: '待审核', value: 'PENDING_REVIEW' },
|
||||||
{ label: '已通过', value: 'APPROVED' },
|
{ label: '已通过', value: 'APPROVED' },
|
||||||
{ label: '已拒绝', value: 'REJECTED' },
|
{ label: '已拒绝', value: 'REJECTED' },
|
||||||
{ label: '待出库', value: 'PENDING_OUTBOUND' },
|
|
||||||
{ label: '部分出库', value: 'PARTIALLY_OUTBOUND' },
|
|
||||||
{ label: '全部出库', value: 'OUTBOUNDED' },
|
|
||||||
{ label: '待接单', value: 'PENDING_ACCEPTANCE' },
|
{ label: '待接单', value: 'PENDING_ACCEPTANCE' },
|
||||||
|
...Object.entries(poolOrderStatusLabels).filter(([value]) => !['IN_TRANSIT', 'COMPLETED', 'CANCELLED'].includes(value)).map(([value, label]) => ({ value, label })),
|
||||||
{ label: '处理中', value: 'PROCESSING' },
|
{ label: '处理中', value: 'PROCESSING' },
|
||||||
{ label: '运输中', value: 'IN_TRANSIT' },
|
{ label: '运输中', value: 'IN_TRANSIT' },
|
||||||
{ label: '已完成', value: 'COMPLETED' },
|
{ label: '已完成', value: 'COMPLETED' },
|
||||||
@@ -167,9 +132,6 @@ const queryFields = computed<QueryField[]>(() => [
|
|||||||
|
|
||||||
const form = reactive<BusinessForm>(emptyForm())
|
const form = reactive<BusinessForm>(emptyForm())
|
||||||
const rules: FormRules<BusinessForm> = {
|
const rules: FormRules<BusinessForm> = {
|
||||||
purchaseCategory: [{ required: true, message: '请输入采购品类', trigger: 'blur' }],
|
|
||||||
productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
|
|
||||||
purchaseQuantity: [{ required: true, type: 'number', min: 1, message: '采购数量至少为 1', trigger: 'change' }],
|
|
||||||
origin: [{ required: true, message: '请输入起运地', trigger: 'blur' }],
|
origin: [{ required: true, message: '请输入起运地', trigger: 'blur' }],
|
||||||
destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
|
destination: [{ required: true, message: '请输入目的地', trigger: 'blur' }],
|
||||||
palletCount: [{ required: true, type: 'number', min: 1, message: '托盘数至少为 1', trigger: 'change' }],
|
palletCount: [{ required: true, type: 'number', min: 1, message: '托盘数至少为 1', trigger: 'change' }],
|
||||||
@@ -181,24 +143,9 @@ const rules: FormRules<BusinessForm> = {
|
|||||||
const detailFields = computed(() => {
|
const detailFields = computed(() => {
|
||||||
if (!detail.value) return []
|
if (!detail.value) return []
|
||||||
const summary = detail.value.summary
|
const summary = detail.value.summary
|
||||||
if (props.kind === 'procurement') {
|
|
||||||
const current = detail.value as ProcurementDetail
|
|
||||||
return [
|
|
||||||
['采购品类', read(summary, 'purchaseCategory')],
|
|
||||||
['商品名称', read(summary, 'productName')], ['商品规格', read(summary, 'productSpecification')],
|
|
||||||
['采购数量', read(summary, 'purchaseQuantity')], ['预算单价', money(read(summary, 'budgetUnitPrice'), read(summary, 'currency'))],
|
|
||||||
['入库量', read(summary, 'inboundQuantity')], ['出库量', read(summary, 'outboundQuantity')],
|
|
||||||
['库存量', read(summary, 'inventoryQuantity')], ['预计到达时间', dateTime(current.estimatedArrivalAt)],
|
|
||||||
['联系人', current.contactName], ['联系电话', current.contactPhone],
|
|
||||||
['收货地址', current.receivingAddress], ['商品链接', current.productUrl],
|
|
||||||
['国内运单', joinText(current.domesticCarrier, current.domesticTrackingNo)],
|
|
||||||
['海外运单', joinText(current.overseasCarrier, current.overseasTrackingNo)],
|
|
||||||
['审核备注', current.reviewRemark], ['备注', current.remark],
|
|
||||||
]
|
|
||||||
}
|
|
||||||
const current = detail.value as TransportDetail
|
const current = detail.value as TransportDetail
|
||||||
return [
|
return [
|
||||||
['运输方式', read(summary, 'transportMode')],
|
['运输方式', transportModeLabel(read(summary, 'transportMode'))],
|
||||||
['是否打盘', yesNo(read(summary, 'palletRequired'))], ['运输类型', transportTypeLabel(read(summary, 'transportType'))],
|
['是否打盘', yesNo(read(summary, 'palletRequired'))], ['运输类型', transportTypeLabel(read(summary, 'transportType'))],
|
||||||
['起运地', read(summary, 'origin')], ['起运地址', current.originAddress],
|
['起运地', read(summary, 'origin')], ['起运地址', current.originAddress],
|
||||||
['目的地', read(summary, 'destination')], ['目的地址', current.destinationAddress],
|
['目的地', read(summary, 'destination')], ['目的地址', current.destinationAddress],
|
||||||
@@ -215,7 +162,7 @@ const tableColumns = computed<DataTableColumn[]>(() => [
|
|||||||
...configuration.value.columns.map((column) => ({
|
...configuration.value.columns.map((column) => ({
|
||||||
...column,
|
...column,
|
||||||
prop: column.key,
|
prop: column.key,
|
||||||
slotName: ['orderNo', 'status'].includes(column.key) ? column.key : undefined,
|
slotName: ['orderNo', 'status', 'fleetArrangement'].includes(column.key) ? column.key : undefined,
|
||||||
formatter: (row: object) => displayCell(row, column.key),
|
formatter: (row: object) => displayCell(row, column.key),
|
||||||
})),
|
})),
|
||||||
])
|
])
|
||||||
@@ -224,28 +171,27 @@ const detailStatus = computed(() => detail.value ? statusLabel(detail.value.summ
|
|||||||
|
|
||||||
function emptyForm(): BusinessForm {
|
function emptyForm(): BusinessForm {
|
||||||
return {
|
return {
|
||||||
purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: 1,
|
|
||||||
transportMode: 'SHARED_TRUCK', palletRequired: 'NO', transportType: 'PORT_PICKUP', origin: '', originAddress: '',
|
transportMode: 'SHARED_TRUCK', palletRequired: 'NO', transportType: 'PORT_PICKUP', origin: '', originAddress: '',
|
||||||
destination: '', destinationAddress: '', containerType: DEFAULT_CONTAINER_TYPE, palletCount: 1, packageCount: 0,
|
destination: '', destinationAddress: '', containerType: DEFAULT_CONTAINER_TYPE, palletCount: 1, packageCount: 0,
|
||||||
totalWeightKg: 0, totalVolumeCbm: 0, currency: 'USD', contactName: '', contactInfo: '', requestedDate: '',
|
totalWeightKg: 0, totalVolumeCbm: 0, currency: 'USD', contactName: '', contactInfo: '', requestedDate: '',
|
||||||
receivingAddress: '', remark: '',
|
remark: '',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetForm() { Object.assign(form, emptyForm()); submitKey.value = ''; formRef.value?.clearValidate() }
|
function resetForm() { Object.assign(form, emptyForm()); submitKey.value = ''; formRef.value?.clearValidate() }
|
||||||
function read(source: object, key: string) { return Reflect.get(source, key) as unknown }
|
function read(source: object, key: string) { return Reflect.get(source, key) as unknown }
|
||||||
function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
|
function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
|
||||||
function joinText(...values: unknown[]) { const result = values.filter(Boolean).join(' / '); return result || '—' }
|
|
||||||
function money(amount: unknown, currency: unknown) { return amount === null || amount === undefined ? '—' : `${text(currency)} ${Number(amount).toFixed(2)}` }
|
function money(amount: unknown, currency: unknown) { return amount === null || amount === undefined ? '—' : `${text(currency)} ${Number(amount).toFixed(2)}` }
|
||||||
function dateTime(value: unknown) { return value ? new Date(String(value)).toLocaleString('zh-CN', { hour12: false }) : '—' }
|
function dateTime(value: unknown) { return value ? new Date(String(value)).toLocaleString('zh-CN', { hour12: false }) : '—' }
|
||||||
function yesNo(value: unknown) { return value === 'YES' ? '是' : value === 'NO' ? '否' : text(value) }
|
function yesNo(value: unknown) { return value === 'YES' ? '是' : value === 'NO' ? '否' : text(value) }
|
||||||
function transportTypeLabel(value: unknown) { return ({ PORT_PICKUP: '港口提柜', WAREHOUSE_TO_WAREHOUSE: '仓到仓', WAREHOUSE_TO_DOOR: '仓到门' } as Record<string, string>)[String(value)] || text(value) }
|
function transportTypeLabel(value: unknown) { return ({ PORT_PICKUP: '港口提柜', WAREHOUSE_TO_WAREHOUSE: '仓到仓', WAREHOUSE_TO_DOOR: '仓到门' } as Record<string, string>)[String(value)] || text(value) }
|
||||||
function transportModeLabel(value: unknown) { return ({ SHARED_TRUCK: '拼车', PRIORITY_CONSOLIDATION: '优先拼载' } as Record<string, string>)[String(value)] || text(value) }
|
function transportModeLabel(value: unknown) { return ({ SHARED_TRUCK: '拼车', PRIORITY_CONSOLIDATION: '优先拼载' } as Record<string, string>)[String(value)] || text(value) }
|
||||||
function statusLabel(value: unknown) {
|
function statusLabel(value: unknown) {
|
||||||
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_OUTBOUND: '待出库', PARTIALLY_OUTBOUND: '部分出库', OUTBOUNDED: '全部出库', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
|
if (poolOrderStatusLabels[String(value)]) return poolOrderStatusLabels[String(value)]
|
||||||
|
return ({ PENDING_REVIEW: '待审核', APPROVED: '已通过', REJECTED: '已拒绝', PENDING_ACCEPTANCE: '待接单', PROCESSING: '处理中', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消' } as Record<string, string>)[String(value)] || text(value)
|
||||||
}
|
}
|
||||||
function statusTone(value: unknown) {
|
function statusTone(value: unknown) {
|
||||||
return ({ APPROVED: 'success', COMPLETED: 'success', OUTBOUNDED: 'success', REJECTED: 'danger', CANCELLED: 'info', PENDING_REVIEW: 'warning', PENDING_ACCEPTANCE: 'warning', PROCESSING: 'primary', IN_TRANSIT: 'primary' } as Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'>)[String(value)] || 'info'
|
return ({ APPROVED: 'success', COMPLETED: 'success', REJECTED: 'danger', CANCELLED: 'info', PENDING_REVIEW: 'warning', PENDING_ACCEPTANCE: 'warning', PROCESSING: 'primary', IN_TRANSIT: 'primary' } as Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'>)[String(value)] || 'info'
|
||||||
}
|
}
|
||||||
function displayCell(candidate: unknown, key: string) {
|
function displayCell(candidate: unknown, key: string) {
|
||||||
const row = candidate as BusinessRow
|
const row = candidate as BusinessRow
|
||||||
@@ -255,7 +201,7 @@ function displayCell(candidate: unknown, key: string) {
|
|||||||
if (key === 'transportMode') return transportModeLabel(value)
|
if (key === 'transportMode') return transportModeLabel(value)
|
||||||
if (key === 'palletRequired') return yesNo(value)
|
if (key === 'palletRequired') return yesNo(value)
|
||||||
if (key === 'createdAt') return dateTime(value)
|
if (key === 'createdAt') return dateTime(value)
|
||||||
if (key === 'budgetUnitPrice' || key === 'budgetAmount') return money(value, read(row, 'currency'))
|
if (key === 'budgetAmount') return money(value, read(row, 'currency'))
|
||||||
return text(value)
|
return text(value)
|
||||||
}
|
}
|
||||||
function idempotencyKey() { return globalThis.crypto?.randomUUID?.() || `client-${Date.now()}-${Math.random().toString(16).slice(2)}` }
|
function idempotencyKey() { return globalThis.crypto?.randomUUID?.() || `client-${Date.now()}-${Math.random().toString(16).slice(2)}` }
|
||||||
@@ -267,12 +213,9 @@ async function load() {
|
|||||||
try {
|
try {
|
||||||
const params = {
|
const params = {
|
||||||
page: query.page, size: query.size, orderNo: query.orderNo || undefined, status: query.status || undefined,
|
page: query.page, size: query.size, orderNo: query.orderNo || undefined, status: query.status || undefined,
|
||||||
routeKeyword: query.routeKeyword || undefined, productName: query.productName || undefined,
|
routeKeyword: query.routeKeyword || undefined,
|
||||||
purchaseCategory: query.purchaseCategory || undefined,
|
|
||||||
}
|
}
|
||||||
const result = props.kind === 'procurement'
|
const result = await listBusinessOrders<TransportSummary>(props.kind, params)
|
||||||
? await listBusinessOrders<ProcurementSummary>('procurement', params)
|
|
||||||
: await listBusinessOrders<TransportSummary>(props.kind, params)
|
|
||||||
rows.value = result.records
|
rows.value = result.records
|
||||||
total.value = result.total
|
total.value = result.total
|
||||||
} catch (cause) {
|
} catch (cause) {
|
||||||
@@ -283,13 +226,14 @@ async function load() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resetQuery() {
|
function resetQuery() {
|
||||||
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '', productName: '', purchaseCategory: '' })
|
const reloadDirectly = query.page === 1
|
||||||
void load()
|
Object.assign(query, { page: 1, orderNo: '', routeKeyword: '', status: '' })
|
||||||
|
if (reloadDirectly) void load()
|
||||||
}
|
}
|
||||||
|
|
||||||
function searchOrders() {
|
function searchOrders() {
|
||||||
query.page = 1
|
if (query.page !== 1) query.page = 1
|
||||||
void load()
|
else void load()
|
||||||
}
|
}
|
||||||
|
|
||||||
function getRowActions(candidate: object): TableAction[] {
|
function getRowActions(candidate: object): TableAction[] {
|
||||||
@@ -297,16 +241,14 @@ function getRowActions(candidate: object): TableAction[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function detailFieldClass(label: unknown) {
|
function detailFieldClass(label: unknown) {
|
||||||
return ['收货地址', '商品链接', '国内运单', '海外运单', '审核备注', '备注', '起运地址', '目的地址'].includes(String(label)) ? 'is-wide' : ''
|
return ['备注', '起运地址', '目的地址'].includes(String(label)) ? 'is-wide' : ''
|
||||||
}
|
}
|
||||||
|
|
||||||
const listRouteName = computed(() => ({
|
const listRouteName = computed(() => ({
|
||||||
procurement: 'cross-border-procurement',
|
|
||||||
trucking: 'cross-border-domestic-trucking',
|
trucking: 'cross-border-domestic-trucking',
|
||||||
looseboard: 'cross-border-pallet-shipping',
|
looseboard: 'cross-border-pallet-shipping',
|
||||||
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
||||||
const detailRouteName = computed(() => ({
|
const detailRouteName = computed(() => ({
|
||||||
procurement: 'cross-border-procurement-detail',
|
|
||||||
trucking: 'cross-border-domestic-trucking-detail',
|
trucking: 'cross-border-domestic-trucking-detail',
|
||||||
looseboard: 'cross-border-pallet-shipping-detail',
|
looseboard: 'cross-border-pallet-shipping-detail',
|
||||||
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
} as Record<CrossBorderBusinessKind, string>)[props.kind])
|
||||||
@@ -328,9 +270,7 @@ async function loadDetail() {
|
|||||||
loading.value = true
|
loading.value = true
|
||||||
error.value = ''
|
error.value = ''
|
||||||
try {
|
try {
|
||||||
detail.value = props.kind === 'procurement'
|
detail.value = await getBusinessOrder<TransportDetail>(props.kind, detailOrderNo.value)
|
||||||
? await getBusinessOrder<ProcurementDetail>('procurement', detailOrderNo.value)
|
|
||||||
: await getBusinessOrder<TransportDetail>(props.kind, detailOrderNo.value)
|
|
||||||
mode.value = 'detail'
|
mode.value = 'detail'
|
||||||
} catch (cause) { detail.value = null; error.value = errorMessage(cause); ElMessage.error(error.value) }
|
} catch (cause) { detail.value = null; error.value = errorMessage(cause); ElMessage.error(error.value) }
|
||||||
finally { loading.value = false }
|
finally { loading.value = false }
|
||||||
@@ -342,17 +282,6 @@ async function submit() {
|
|||||||
const stableSubmitKey = submitKey.value || idempotencyKey()
|
const stableSubmitKey = submitKey.value || idempotencyKey()
|
||||||
submitKey.value = stableSubmitKey
|
submitKey.value = stableSubmitKey
|
||||||
try {
|
try {
|
||||||
if (props.kind === 'procurement') {
|
|
||||||
await createProcurement({
|
|
||||||
customerName: auth.user?.tenantName || '',
|
|
||||||
purchaseCategory: form.purchaseCategory, productName: form.productName,
|
|
||||||
productSpecification: form.productSpecification || undefined, productUrl: form.productUrl || undefined,
|
|
||||||
purchaseQuantity: form.purchaseQuantity, budgetUnitPrice: form.budgetAmount,
|
|
||||||
currency: form.currency || undefined, receivingAddress: form.receivingAddress || undefined,
|
|
||||||
contactName: form.contactName, contactPhone: form.contactInfo, remark: form.remark || undefined,
|
|
||||||
idempotencyKey: stableSubmitKey,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
const base = {
|
const base = {
|
||||||
transportType: form.transportType, origin: form.origin, originAddress: form.originAddress || undefined,
|
transportType: form.transportType, origin: form.origin, originAddress: form.originAddress || undefined,
|
||||||
destination: form.destination, destinationAddress: form.destinationAddress || undefined,
|
destination: form.destination, destinationAddress: form.destinationAddress || undefined,
|
||||||
@@ -366,7 +295,6 @@ async function submit() {
|
|||||||
await createTransport(props.kind, props.kind === 'trucking'
|
await createTransport(props.kind, props.kind === 'trucking'
|
||||||
? { ...base, palletCount: form.palletCount }
|
? { ...base, palletCount: form.palletCount }
|
||||||
: { ...base, transportMode: form.transportMode, palletRequired: form.palletRequired })
|
: { ...base, transportMode: form.transportMode, palletRequired: form.palletRequired })
|
||||||
}
|
|
||||||
ElMessage.success('订单提交成功')
|
ElMessage.success('订单提交成功')
|
||||||
resetForm()
|
resetForm()
|
||||||
if (props.createPage) await router.push({ name: listRouteName.value })
|
if (props.createPage) await router.push({ name: listRouteName.value })
|
||||||
@@ -397,6 +325,7 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
|||||||
<template v-if="error" #error><div class="business-load-error" role="alert"><span>{{ error }}</span><el-button size="small" @click="load">重新加载</el-button></div></template>
|
<template v-if="error" #error><div class="business-load-error" role="alert"><span>{{ error }}</span><el-button size="small" @click="load">重新加载</el-button></div></template>
|
||||||
<template #orderNo="{ row }"><button class="business-order-link" type="button" @click="openDetail(row)">{{ (row as BusinessRow).orderNo }}</button></template>
|
<template #orderNo="{ row }"><button class="business-order-link" type="button" @click="openDetail(row)">{{ (row as BusinessRow).orderNo }}</button></template>
|
||||||
<template #status="{ row }"><el-tag :type="statusTone((row as BusinessRow).status)" effect="light" size="small">{{ statusLabel((row as BusinessRow).status) }}</el-tag></template>
|
<template #status="{ row }"><el-tag :type="statusTone((row as BusinessRow).status)" effect="light" size="small">{{ statusLabel((row as BusinessRow).status) }}</el-tag></template>
|
||||||
|
<template #fleetArrangement="{ row }"><template v-if="(row as TransportSummary).fleetArrangement"><div>{{ poolOrderStatusLabels[(row as TransportSummary).fleetArrangement!.fulfillmentStage] || '待核对履约进度' }}</div><small>{{ dateTime((row as TransportSummary).fleetArrangement!.plannedDepartureAt) }}</small></template><span v-else>—</span></template>
|
||||||
</DataTable>
|
</DataTable>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -413,19 +342,28 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
|||||||
<div v-for="field in detailFields" :key="String(field[0])" :class="detailFieldClass(field[0])"><dt>{{ field[0] }}</dt><dd>{{ text(field[1]) }}</dd></div>
|
<div v-for="field in detailFields" :key="String(field[0])" :class="detailFieldClass(field[0])"><dt>{{ field[0] }}</dt><dd>{{ text(field[1]) }}</dd></div>
|
||||||
</dl>
|
</dl>
|
||||||
</section>
|
</section>
|
||||||
|
<section v-if="!error && fleetArrangement" class="business-detail-section" aria-label="承运安排">
|
||||||
|
<h3>承运安排</h3><p>{{ fleetArrangement.readOnlyReason }}</p>
|
||||||
|
<dl class="detail-grid arrangement-grid">
|
||||||
|
<div><dt>预订号</dt><dd>{{ fleetArrangement.bookingNo }}</dd></div>
|
||||||
|
<div><dt>计划发车</dt><dd>{{ dateTime(fleetArrangement.plannedDepartureAt) }}</dd></div>
|
||||||
|
<div><dt>起运仓</dt><dd>{{ text(fleetArrangement.originWarehouseName) }}</dd></div>
|
||||||
|
<div><dt>目的地</dt><dd>{{ text(fleetArrangement.destinationLabel) }}</dd></div>
|
||||||
|
<div><dt>交货方式</dt><dd>{{ fleetArrangement.deliveryMode === 'SELF_DELIVERY' ? '自行送至起运仓' : '线下安排提货至起运仓' }}</dd></div>
|
||||||
|
<div><dt>履约进度</dt><dd>{{ poolOrderStatusLabels[fleetArrangement.fulfillmentStage] || '待核对履约进度' }}</dd></div>
|
||||||
|
<div><dt>更新时间</dt><dd>{{ dateTime(fleetArrangement.stageOccurredAt) }}</dd></div>
|
||||||
|
<div><dt>约定运费(非实收)</dt><dd>{{ money(fleetArrangement.agreedFreightAmount, fleetArrangement.currency) }}</dd></div>
|
||||||
|
<div><dt>来货单号</dt><dd>{{ text(fleetArrangement.incomingNo) }}</dd></div>
|
||||||
|
<div><dt>派送单号</dt><dd>{{ text(fleetArrangement.deliveryNo) }}</dd></div>
|
||||||
|
<div><dt>已签 / 未签 / 退回箱数</dt><dd>{{ fleetArrangement.signedPackages ?? '—' }} / {{ fleetArrangement.unsignedPackages ?? '—' }} / {{ fleetArrangement.returnedPackages ?? '—' }}</dd></div>
|
||||||
|
<div class="is-wide"><dt>交货说明</dt><dd>{{ text(fleetArrangement.deliveryInstructions) }}</dd></div>
|
||||||
|
<div v-if="fleetArrangement.exceptionSummary" class="is-wide"><dt>履约说明</dt><dd>{{ fleetArrangement.exceptionSummary }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<el-card v-else shadow="never" class="form-card">
|
<el-card v-else shadow="never" class="form-card">
|
||||||
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
|
<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
|
||||||
<template v-if="kind === 'procurement'">
|
|
||||||
<el-form-item label="采购品类" prop="purchaseCategory"><el-input v-model.trim="form.purchaseCategory" maxlength="128" placeholder="请输入采购品类" /></el-form-item>
|
|
||||||
<el-form-item label="商品名称" prop="productName"><el-input v-model.trim="form.productName" maxlength="255" placeholder="请输入商品名称" /></el-form-item>
|
|
||||||
<el-form-item label="商品规格"><el-input v-model.trim="form.productSpecification" maxlength="500" placeholder="请输入规格、型号等信息" /></el-form-item>
|
|
||||||
<el-form-item label="商品链接"><el-input v-model.trim="form.productUrl" maxlength="2000" placeholder="请输入商品链接" /></el-form-item>
|
|
||||||
<el-form-item label="采购数量" prop="purchaseQuantity"><el-input-number v-model="form.purchaseQuantity" :min="1" placeholder="请输入数量" /></el-form-item>
|
|
||||||
<el-form-item label="收货地址"><el-input v-model.trim="form.receivingAddress" maxlength="1000" placeholder="请输入收货地址" /></el-form-item>
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<el-form-item v-if="kind === 'looseboard'" label="运输方式"><el-radio-group v-model="form.transportMode"><el-radio-button value="SHARED_TRUCK">拼车</el-radio-button><el-radio-button value="PRIORITY_CONSOLIDATION">优先拼载</el-radio-button></el-radio-group></el-form-item>
|
<el-form-item v-if="kind === 'looseboard'" label="运输方式"><el-radio-group v-model="form.transportMode"><el-radio-button value="SHARED_TRUCK">拼车</el-radio-button><el-radio-button value="PRIORITY_CONSOLIDATION">优先拼载</el-radio-button></el-radio-group></el-form-item>
|
||||||
<el-form-item v-if="kind === 'looseboard'" label="是否打盘"><el-radio-group v-model="form.palletRequired"><el-radio-button value="NO">否</el-radio-button><el-radio-button value="YES">是</el-radio-button></el-radio-group></el-form-item>
|
<el-form-item v-if="kind === 'looseboard'" label="是否打盘"><el-radio-group v-model="form.palletRequired"><el-radio-button value="NO">否</el-radio-button><el-radio-button value="YES">是</el-radio-button></el-radio-group></el-form-item>
|
||||||
<el-form-item label="运输类型"><el-select v-model="form.transportType"><el-option label="港口提柜" value="PORT_PICKUP" /><el-option label="仓到仓" value="WAREHOUSE_TO_WAREHOUSE" /><el-option label="仓到门" value="WAREHOUSE_TO_DOOR" /></el-select></el-form-item>
|
<el-form-item label="运输类型"><el-select v-model="form.transportType"><el-option label="港口提柜" value="PORT_PICKUP" /><el-option label="仓到仓" value="WAREHOUSE_TO_WAREHOUSE" /><el-option label="仓到门" value="WAREHOUSE_TO_DOOR" /></el-select></el-form-item>
|
||||||
@@ -439,8 +377,7 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
|||||||
<el-form-item label="总重量(kg)"><el-input-number v-model="form.totalWeightKg" :min="0" :precision="2" placeholder="请输入总重量" /></el-form-item>
|
<el-form-item label="总重量(kg)"><el-input-number v-model="form.totalWeightKg" :min="0" :precision="2" placeholder="请输入总重量" /></el-form-item>
|
||||||
<el-form-item label="总体积(m³)"><el-input-number v-model="form.totalVolumeCbm" :min="0" :precision="3" placeholder="请输入总体积" /></el-form-item>
|
<el-form-item label="总体积(m³)"><el-input-number v-model="form.totalVolumeCbm" :min="0" :precision="3" placeholder="请输入总体积" /></el-form-item>
|
||||||
<el-form-item label="要求时间" :prop="kind === 'trucking' ? 'requestedDate' : undefined"><el-date-picker v-model="form.requestedDate" type="date" value-format="YYYY-MM-DD" /></el-form-item>
|
<el-form-item label="要求时间" :prop="kind === 'trucking' ? 'requestedDate' : undefined"><el-date-picker v-model="form.requestedDate" type="date" value-format="YYYY-MM-DD" /></el-form-item>
|
||||||
</template>
|
<el-form-item class="budget-form-item" label="预算金额"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2" placeholder="请输入预算金额" /><el-select v-model="form.currency" class="currency"><el-option label="USD" value="USD" /><el-option label="CNY" value="CNY" /></el-select></el-form-item>
|
||||||
<el-form-item class="budget-form-item" :label="kind === 'procurement' ? '预算单价' : '预算金额'"><el-input-number v-model="form.budgetAmount" :min="0" :precision="2" placeholder="请输入预算金额" /><el-select v-model="form.currency" class="currency"><el-option label="USD" value="USD" /><el-option label="CNY" value="CNY" /></el-select></el-form-item>
|
|
||||||
<el-form-item label="联系人" prop="contactName"><el-input v-model.trim="form.contactName" maxlength="128" placeholder="请输入联系人" /></el-form-item>
|
<el-form-item label="联系人" prop="contactName"><el-input v-model.trim="form.contactName" maxlength="128" placeholder="请输入联系人" /></el-form-item>
|
||||||
<el-form-item label="联系方式" prop="contactInfo"><el-input v-model.trim="form.contactInfo" maxlength="128" placeholder="请输入电话、微信或邮箱" /></el-form-item>
|
<el-form-item label="联系方式" prop="contactInfo"><el-input v-model.trim="form.contactInfo" maxlength="128" placeholder="请输入电话、微信或邮箱" /></el-form-item>
|
||||||
<el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请输入其他要求" /></el-form-item>
|
<el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请输入其他要求" /></el-form-item>
|
||||||
@@ -472,6 +409,8 @@ onMounted(() => { if (props.detailPage) void loadDetail(); else if (!props.creat
|
|||||||
.detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 76px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
.detail-grid div { display: grid; min-width: 0; min-height: 34px; grid-template-columns: 76px minmax(0, 1fr); align-items: center; gap: 7px; padding: 3px 8px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); }
|
||||||
.detail-grid div.is-wide { grid-column: span 2; }
|
.detail-grid div.is-wide { grid-column: span 2; }
|
||||||
.detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
|
.detail-grid dt { color: var(--muted); font-size: 10px; white-space: nowrap; }
|
||||||
|
.arrangement-grid div { grid-template-columns: 124px minmax(0, 1fr); }
|
||||||
|
.arrangement-grid dt { white-space: normal; overflow-wrap: anywhere; }
|
||||||
.detail-grid dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--navy); font-size: 12px; font-weight: 600; line-height: 1.4; }
|
.detail-grid dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--navy); font-size: 12px; font-weight: 600; line-height: 1.4; }
|
||||||
.form-card :deep(.el-form) { max-width: 860px; }
|
.form-card :deep(.el-form) { max-width: 860px; }
|
||||||
.form-card :deep(.el-input), .form-card :deep(.el-textarea), .form-card :deep(.el-select) { width: 100%; }
|
.form-card :deep(.el-input), .form-card :deep(.el-textarea), .form-card :deep(.el-select) { width: 100%; }
|
||||||
|
|||||||
@@ -0,0 +1,106 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import type { ProcurementDetail, ProcurementFee } from '../api/procurement'
|
||||||
|
import { dateTime, feePurposes, feeStatus, feeTone, feeTotals, measurement, money, productHref, text } from '../procurementPresentation'
|
||||||
|
|
||||||
|
const props = defineProps<{ detail: ProcurementDetail }>()
|
||||||
|
const totals = computed(() => feeTotals(props.detail.fees))
|
||||||
|
const progress = computed(() => props.detail.progress.filter(step => step.key !== 'closed_at' || step.completedAt))
|
||||||
|
const ended = computed(() => ['REJECTED', 'CANCELLED', 'EXCEPTION_CLOSED', 'SHIPPED_TO_CUSTOMER'].includes(props.detail.order.status))
|
||||||
|
const hasPending = computed(() => props.detail.fees.some(f => f.walletStatus?.endsWith('_PENDING') || f.walletStatus?.endsWith('_FAILED')))
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="procurement-section" aria-label="采购履约进度">
|
||||||
|
<h3>履约进度</h3>
|
||||||
|
<ol class="procurement-progress">
|
||||||
|
<li v-for="step in progress" :key="step.key" :class="{ 'is-complete': step.completedAt }">
|
||||||
|
<strong>{{ step.title }}</strong><span>{{ step.completedAt ? dateTime(step.completedAt) : ended ? '未执行' : '待处理' }}</span>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
<p v-if="detail.purchaseNeedsAttention" class="procurement-note">购买资料正在核对,客服将协助处理。已发生的收货与费用结果仍保留在本单。</p>
|
||||||
|
</section>
|
||||||
|
<section class="procurement-section" aria-label="商品与收件信息">
|
||||||
|
<h3>商品与收件信息</h3>
|
||||||
|
<dl class="procurement-grid">
|
||||||
|
<div><dt>采购品类</dt><dd>{{ detail.order.purchaseCategory }}</dd></div>
|
||||||
|
<div><dt>商品名称</dt><dd>{{ detail.order.productName }}</dd></div>
|
||||||
|
<div><dt>商品规格</dt><dd>{{ text(detail.order.productSpecification) }}</dd></div>
|
||||||
|
<div><dt>采购数量</dt><dd>{{ detail.order.purchaseQuantity }} 件</dd></div>
|
||||||
|
<div><dt>下单预算单价</dt><dd>{{ money(detail.order.budgetUnitPrice, detail.order.currency) }}</dd></div>
|
||||||
|
<div><dt>货款预算总上限</dt><dd>{{ money(detail.budget.totalAmount, detail.budget.currency) }}</dd></div>
|
||||||
|
<div><dt>预算核验时间</dt><dd>{{ dateTime(detail.budget.authorizedAt) }}</dd></div>
|
||||||
|
<div><dt>预计到海外仓</dt><dd>{{ dateTime(detail.order.estimatedArrivalAt) }}</dd></div>
|
||||||
|
<div><dt>收件人</dt><dd>{{ detail.order.contactName }}</dd></div>
|
||||||
|
<div><dt>联系电话</dt><dd>{{ detail.order.contactPhone }}</dd></div>
|
||||||
|
<div class="wide"><dt>下单收货地址</dt><dd>{{ detail.order.receivingAddress }}</dd></div>
|
||||||
|
<div class="wide"><dt>实际海外仓</dt><dd>{{ text(detail.order.actualWarehouseName) }}<span v-if="detail.order.actualWarehouseCode">({{ detail.order.actualWarehouseCode }})</span></dd></div>
|
||||||
|
<div class="wide"><dt>商品链接</dt><dd><a v-if="productHref(detail.order.productUrl)" :href="productHref(detail.order.productUrl)" target="_blank" rel="noopener noreferrer">{{ detail.order.productUrl }}</a><span v-else>{{ text(detail.order.productUrl) }}</span></dd></div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
<section class="procurement-section" aria-label="已确认海外装箱清单">
|
||||||
|
<h3>已确认海外装箱清单</h3>
|
||||||
|
<el-table :data="detail.boxes" border stripe empty-text="尚无已确认的装箱清单" row-key="cartonNo">
|
||||||
|
<el-table-column prop="cartonNo" label="箱号" min-width="170" />
|
||||||
|
<el-table-column label="箱内商品" min-width="200"><template #default>{{ detail.order.productName }}</template></el-table-column>
|
||||||
|
<el-table-column label="规格" min-width="180"><template #default>{{ text(detail.order.productSpecification) }}</template></el-table-column>
|
||||||
|
<el-table-column prop="quantity" label="数量(件)" width="120" />
|
||||||
|
<el-table-column label="外箱长 × 宽 × 高(cm)" min-width="240"><template #default="{ row }">{{ measurement(row.lengthCm, 2) }} × {{ measurement(row.widthCm, 2) }} × {{ measurement(row.heightCm, 2) }}</template></el-table-column>
|
||||||
|
<el-table-column label="封箱毛重(kg)" width="170"><template #default="{ row }">{{ measurement(row.grossWeightKg, 3) }}</template></el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</section>
|
||||||
|
<section class="procurement-section" aria-label="两段实际运输">
|
||||||
|
<h3>两段实际运输</h3>
|
||||||
|
<el-table :data="detail.shipments" border stripe empty-text="尚无实际交寄记录">
|
||||||
|
<el-table-column label="运输段" width="150"><template #default="{ row }">{{ row.leg === 'OVERSEAS' ? '国际段 · 海外交寄' : '国内段 · 寄客户' }}</template></el-table-column>
|
||||||
|
<el-table-column prop="shipmentNo" label="交寄编号" min-width="270" />
|
||||||
|
<el-table-column prop="cartonNo" label="原箱号" min-width="150" />
|
||||||
|
<el-table-column prop="quantity" label="实际件数" width="110" />
|
||||||
|
<el-table-column prop="carrier" label="承运商" min-width="140" />
|
||||||
|
<el-table-column prop="trackingNo" label="运单号" min-width="230" />
|
||||||
|
<el-table-column label="实际交寄时间" width="185"><template #default="{ row }">{{ dateTime(row.shippedAt) }}</template></el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<p class="procurement-note">这里显示已实际交给承运方的记录;国内寄客户后,本单履约完成。</p>
|
||||||
|
</section>
|
||||||
|
<section class="procurement-section" aria-label="采购费用与资金结果">
|
||||||
|
<h3>费用与资金结果</h3>
|
||||||
|
<dl class="procurement-grid money-grid">
|
||||||
|
<div><dt>累计成功扣款</dt><dd>{{ money(totals?.paid) }}</dd></div>
|
||||||
|
<div><dt>累计成功退款</dt><dd>{{ money(totals?.refunded) }}</dd></div>
|
||||||
|
<div><dt>净实扣</dt><dd>{{ money(totals?.net) }}</dd></div>
|
||||||
|
<div><dt>预估国际运费占款</dt><dd>{{ money(totals?.estimatedHold) }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
<p class="procurement-note">预算上限仅包含样品货款。预估国际运费只冻结、不直接扣款,最终以实际费用结算;表内保留原费用、追加及退款记录。</p>
|
||||||
|
<el-table :data="detail.fees" border stripe empty-text="尚无已核定费用" row-key="feeNo">
|
||||||
|
<el-table-column prop="feeNo" label="费用编号" min-width="270" />
|
||||||
|
<el-table-column label="费用用途" min-width="145"><template #default="{ row }">{{ feePurposes[row.purpose] || '待核定' }}</template></el-table-column>
|
||||||
|
<el-table-column prop="name" label="费用名称" min-width="145" />
|
||||||
|
<el-table-column label="原币金额" min-width="130"><template #default="{ row }">{{ money(row.originalAmount, row.originalCurrency) }}</template></el-table-column>
|
||||||
|
<el-table-column label="汇率 / 月份" min-width="150"><template #default="{ row }">{{ measurement(row.exchangeRate, 6) }}<br /><small>{{ text(row.exchangeRateMonth) }}</small></template></el-table-column>
|
||||||
|
<el-table-column label="人民币金额" min-width="130"><template #default="{ row }">{{ money(row.amount) }}</template></el-table-column>
|
||||||
|
<el-table-column label="处理结果" min-width="190"><template #default="{ row }"><el-tag :type="feeTone(row as ProcurementFee)" size="small">{{ feeStatus(row as ProcurementFee) }}</el-tag><small v-if="row.purpose !== 'INTERNATIONAL_ESTIMATE' && row.walletStatus === 'SETTLED' && !row.sourceLinked" class="fee-sync">费用结果同步中</small></template></el-table-column>
|
||||||
|
<el-table-column prop="parentFeeNo" label="关联原费用 / 预估" min-width="270"><template #default="{ row }">{{ text(row.parentFeeNo) }}</template></el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<p v-if="hasPending" class="procurement-note">部分资金处理尚未完成,可点击页面“刷新”查看最新结果;如需协助请联系客户服务。</p>
|
||||||
|
</section>
|
||||||
|
<section v-if="detail.exceptionSummaries.length" class="procurement-section" aria-label="客服处理说明">
|
||||||
|
<h3>客服处理说明</h3><ul class="procurement-summaries"><li v-for="(summary, index) in detail.exceptionSummaries" :key="index">{{ summary }}</li></ul>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.procurement-section { margin-top: 18px; min-width: 0; }
|
||||||
|
h3 { margin: 0 0 10px; padding-bottom: 7px; border-bottom: 1px solid var(--border); color: var(--navy); font-size: 14px; }
|
||||||
|
.procurement-progress { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0; padding: 0; margin: 0; list-style: none; border-top: 1px solid var(--border); border-left: 1px solid var(--border); }
|
||||||
|
.procurement-progress li { display: grid; gap: 7px; padding: 12px; border-bottom: 1px solid var(--border); border-right: 1px solid var(--border); color: var(--muted); }
|
||||||
|
.procurement-progress strong { font-size: 13px; font-weight: 600; }.procurement-progress span { font-size: 12px; }.procurement-progress .is-complete strong { color: var(--navy); }
|
||||||
|
.procurement-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin: 0; border-left: 1px solid var(--border); border-top: 1px solid var(--border); }
|
||||||
|
.procurement-grid > div { display: grid; grid-template-columns: 110px minmax(0, 1fr); align-items: center; gap: 8px; padding: 9px 12px; border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); min-width: 0; }
|
||||||
|
.procurement-grid dt { font-size: 12px; color: var(--muted); }.procurement-grid dd { margin: 0; font-size: 13px; line-height: 1.6; color: var(--navy); overflow-wrap: anywhere; }
|
||||||
|
.procurement-grid .wide { grid-column: span 2; }.money-grid > div { grid-template-columns: minmax(0, 1fr); }.money-grid dd { font-size: 16px; font-weight: 600; }
|
||||||
|
a { color: var(--client-action); } .procurement-note { margin: 10px 0; color: var(--muted); font-size: 12px; line-height: 1.7; }
|
||||||
|
.fee-sync { display: block; padding-top: 5px; color: var(--muted); }.procurement-summaries { margin: 0; padding-left: 22px; line-height: 1.8; color: var(--navy); font-size: 13px; white-space: pre-wrap; }
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
.procurement-progress, .procurement-grid { grid-template-columns: 1fr; }.procurement-grid .wide { grid-column: auto; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
export interface FleetArrangement {
|
||||||
|
sourceType: 'FLEET_CAPACITY_OFFER'
|
||||||
|
businessType: 'LOCAL_LOOSEBOARD' | 'US_TRUCK'
|
||||||
|
businessOrderNo: string
|
||||||
|
bookingNo: string
|
||||||
|
tripNo: string
|
||||||
|
plannedDepartureAt: string | null
|
||||||
|
originWarehouseName: string
|
||||||
|
destinationLabel: string
|
||||||
|
deliveryMode: 'SELF_DELIVERY' | 'MANUAL_PICKUP_TO_WAREHOUSE'
|
||||||
|
deliveryInstructions: string | null
|
||||||
|
fulfillmentStage: string
|
||||||
|
stageOccurredAt: string | null
|
||||||
|
agreedFreightAmount: number | null
|
||||||
|
currency: string | null
|
||||||
|
incomingNo: string | null
|
||||||
|
dispatchNo: string | null
|
||||||
|
deliveryNo: string | null
|
||||||
|
signedPackages: number | null
|
||||||
|
unsignedPackages: number | null
|
||||||
|
returnedPackages: number | null
|
||||||
|
exceptionSummary: string | null
|
||||||
|
readOnlyReason: string
|
||||||
|
}
|
||||||
|
export const poolOrderStatusLabels: Record<string, string> = {
|
||||||
|
WAITING_INBOUND: '待入仓', RECEIVING: '收货中', WAITING_CONSOLIDATION: '待合托',
|
||||||
|
PENDING_DISPATCH: '待派车', IN_TRANSIT: '运输中', COMPLETED: '已完成', CANCELLED: '已取消',
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { runInNewContext } from 'node:vm'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
import { parse, compileScript } from 'vue/compiler-sfc'
|
||||||
|
|
||||||
|
let nextKey = 0
|
||||||
|
const crypto = { randomUUID: () => `test-key-${++nextKey}` }
|
||||||
|
function moduleFrom(source, require = () => { throw new Error('unexpected import') }) {
|
||||||
|
const context = { exports: {}, require, URL, Error, crypto }
|
||||||
|
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||||
|
runInNewContext(code, context)
|
||||||
|
return context.exports
|
||||||
|
}
|
||||||
|
const presentation = moduleFrom(readFileSync(new URL('./procurementPresentation.ts', import.meta.url), 'utf8'))
|
||||||
|
const submission = moduleFrom(readFileSync(new URL('./procurementSubmission.ts', import.meta.url), 'utf8'), name => {
|
||||||
|
if (name === './procurementPresentation') return presentation
|
||||||
|
throw new Error(`unexpected import ${name}`)
|
||||||
|
})
|
||||||
|
const normalized = value => JSON.parse(JSON.stringify(value))
|
||||||
|
const draft = () => ({ ...presentation.emptyProcurementDraft(), purchaseCategory: 'Sample', productName: 'Test product', productSpecification: 'A',
|
||||||
|
purchaseQuantity: '3', budgetUnitPrice: '0.29', receivingAddress: '测试省测试市测试街 1 号', contactName: '测试收件人', contactPhone: '13800000000' })
|
||||||
|
const fee = (purpose, walletStatus, amount) => ({ purpose, walletStatus, amount, currency: 'CNY' })
|
||||||
|
|
||||||
|
test('budget distinguishes unknown from zero, preserves cents, and requires a real telephone/address', () => {
|
||||||
|
assert.equal(presentation.draftBudgetTotal(draft()), '0.87')
|
||||||
|
const valid = presentation.buildProcurementCreate(draft(), 'Authenticated Company', 'same-key')
|
||||||
|
assert.equal(valid.customerName, 'Authenticated Company')
|
||||||
|
assert.equal(valid.budgetUnitPrice, 0.29)
|
||||||
|
for (const value of ['', '-1', '1.001', '90071992547409.91']) assert.throws(() => presentation.buildProcurementCreate({ ...draft(), budgetUnitPrice: value }, 'Company', 'key'), /预算/)
|
||||||
|
assert.equal(presentation.buildProcurementCreate({ ...draft(), budgetUnitPrice: '0' }, 'Company', 'key').budgetUnitPrice, 0)
|
||||||
|
for (const patch of [{ contactPhone: 'wechat-name' }, { contactPhone: 'a@test.invalid' }, { receivingAddress: '' }, { purchaseQuantity: '1.5' }]) {
|
||||||
|
assert.throws(() => presentation.buildProcurementCreate({ ...draft(), ...patch }, 'Company', 'key'))
|
||||||
|
}
|
||||||
|
assert.equal(presentation.measurement(20, 2), '20.00')
|
||||||
|
assert.equal(presentation.measurement('5.125', 3), '5.125')
|
||||||
|
assert.equal(presentation.measurement('1.234', 2), '待核对')
|
||||||
|
assert.equal(presentation.money(null), '—')
|
||||||
|
assert.equal(presentation.money(0), 'CNY 0.00')
|
||||||
|
assert.equal(presentation.productHref('javascript:alert(1)'), undefined)
|
||||||
|
assert.equal(presentation.productHref('https://example.com/item'), 'https://example.com/item')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('successful net debit excludes the original estimate and counts only successful refunds and differences', () => {
|
||||||
|
const result = presentation.feeTotals([fee('INTERNATIONAL_ESTIMATE', 'SETTLED', '100'), fee('INTERNATIONAL_FREIGHT', 'SETTLED', '100'),
|
||||||
|
fee('ADJUSTMENT', 'SETTLED', '20'), fee('ADJUSTMENT', 'SETTLED', '10'), fee('REFUND', 'REFUNDED', '20'), fee('REFUND', 'REFUND_PENDING', '5')])
|
||||||
|
assert.deepEqual(normalized(result), { paid: '130.00', refunded: '20.00', net: '110.00', estimatedHold: '0.00' })
|
||||||
|
assert.equal(presentation.feeTotals([fee('INTERNATIONAL_ESTIMATE', 'RELEASE_PENDING', '100')]).estimatedHold, '100.00')
|
||||||
|
assert.equal(presentation.feeTotals([fee('DUTY', 'SETTLED', 'unknown')]), null)
|
||||||
|
assert.equal(presentation.feeStatus(fee('INTERNATIONAL_ESTIMATE', 'FROZEN', 100)), '已冻结,未扣款')
|
||||||
|
assert.equal(presentation.feeStatus(fee('INTERNATIONAL_ESTIMATE', 'SETTLED', 100)), '原预估已结清')
|
||||||
|
assert.equal(presentation.feeStatus(fee('DUTY', null, 100)), '待核定')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('request recovery preserves content and identity while malformed recovery cannot create a replacement', () => {
|
||||||
|
const original = presentation.buildProcurementCreate(draft(), 'Company', 'fixed-key')
|
||||||
|
assert.deepEqual(normalized(submission.restoreProcurementSubmission(JSON.stringify(original))), normalized(original))
|
||||||
|
assert.throws(() => submission.restoreProcurementSubmission('{}'))
|
||||||
|
assert.throws(() => submission.restoreProcurementSubmission(JSON.stringify({ ...original, currency: 'EUR' })))
|
||||||
|
assert.equal(submission.definitelyRejected({ code: 'TIMEOUT' }), false)
|
||||||
|
assert.equal(submission.definitelyRejected({ status: 500 }), false)
|
||||||
|
assert.equal(submission.definitelyRejected({ status: 409 }), false)
|
||||||
|
assert.equal(submission.definitelyRejected({ status: 400 }), true)
|
||||||
|
assert.equal(submission.procurementRequestKey({ getRandomValues: target => { target.set([1, 2, 3, 4]); return target } }), 'proc-00000001000000020000000300000004')
|
||||||
|
})
|
||||||
|
|
||||||
|
class ApiError extends Error { constructor(message, code, status) { super(message); this.code = code; this.status = status } }
|
||||||
|
const flush = async () => { await vue.nextTick(); await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
|
||||||
|
function viewHarness({ createPage = false, detailPage = false, api = {}, storage = new Map() } = {}) {
|
||||||
|
const props = vue.reactive({ createPage, detailPage })
|
||||||
|
const route = vue.reactive({ params: { orderNo: detailPage ? 'PO-1' : '' } })
|
||||||
|
const auth = vue.reactive({ token: 'identity-A', user: { tenantName: 'Company' }, profile: { tenantName: 'Company' }, hasPermission: () => true })
|
||||||
|
const pushes = [], dispose = []
|
||||||
|
const defaults = { listProcurements: async () => ({ records: [], total: 0 }), getProcurement: async orderNo => ({ order: { orderNo } }), createProcurement: async () => ({ order: { orderNo: 'PO-CREATED' } }) }
|
||||||
|
const { descriptor } = parse(readFileSync(new URL('./views/ProcurementView.vue', import.meta.url), 'utf8'))
|
||||||
|
const source = compileScript(descriptor, { id: 'procurement-test' }).content
|
||||||
|
const context = { exports: {}, Error, crypto, sessionStorage: { getItem: key => storage.get(key) || null, setItem: (key, value) => storage.set(key, value), removeItem: key => storage.delete(key) },
|
||||||
|
require(name) {
|
||||||
|
if (name === 'vue') return { ...vue, onBeforeUnmount: callback => dispose.push(callback), watch: (...args) => { const stop = vue.watch(...args); dispose.push(stop); return stop } }
|
||||||
|
if (name === 'vue-router') return { useRoute: () => route, useRouter: () => ({ push: async target => pushes.push(target) }) }
|
||||||
|
if (name === 'element-plus') return { ElMessage: { success: () => {} } }
|
||||||
|
if (name === '@/api/types') return { ApiError }
|
||||||
|
if (name === '@/api/session') return { accessTokenIdentity: token => token }
|
||||||
|
if (name === '@/modules/auth/public') return { useAuthStore: () => auth }
|
||||||
|
if (name === '../api/procurement') return { ...defaults, ...api }
|
||||||
|
if (name === '../procurementPresentation') return presentation
|
||||||
|
if (name === '../procurementSubmission') return submission
|
||||||
|
if (name.endsWith('.vue')) return { default: {} }
|
||||||
|
throw new Error(`unexpected view import ${name}`)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
runInNewContext(ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText, context)
|
||||||
|
const state = context.exports.default.setup(props, { expose: () => {} })
|
||||||
|
return { state, props, route, auth, pushes, storage, dispose: () => dispose.forEach(callback => callback()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('detail has one in-flight request and an older response cannot overwrite another order', async () => {
|
||||||
|
const calls = [], pending = new Map()
|
||||||
|
const harness = viewHarness({ detailPage: true, api: { getProcurement: orderNo => { calls.push(orderNo); return new Promise(resolve => pending.set(orderNo, resolve)) } } })
|
||||||
|
try {
|
||||||
|
assert.deepEqual(calls, ['PO-1'])
|
||||||
|
await harness.state.loadDetail(); assert.equal(calls.length, 1)
|
||||||
|
harness.route.params.orderNo = 'PO-2'; await flush(); assert.deepEqual(calls, ['PO-1', 'PO-2'])
|
||||||
|
pending.get('PO-1')({ order: { orderNo: 'PO-1' } }); await flush(); assert.equal(harness.state.detail.value, null)
|
||||||
|
pending.get('PO-2')({ order: { orderNo: 'PO-2' } }); await flush(); assert.equal(harness.state.detail.value.order.orderNo, 'PO-2')
|
||||||
|
assert.equal(harness.state.loading.value, false)
|
||||||
|
} finally { harness.dispose() }
|
||||||
|
})
|
||||||
|
|
||||||
|
test('timeout retries the exact original body after reload and does not accept changed form data', async () => {
|
||||||
|
const storage = new Map(), calls = []
|
||||||
|
const first = viewHarness({ createPage: true, storage, api: { createProcurement: async payload => { calls.push(normalized(payload)); throw new ApiError('timeout', 'TIMEOUT') } } })
|
||||||
|
try {
|
||||||
|
Object.assign(first.state.form, draft()); await first.state.submit(); assert.equal(calls.length, 1); assert.ok(first.state.pending.value)
|
||||||
|
first.state.form.productName = 'changed'; await first.state.submit(); assert.deepEqual(calls[1], calls[0])
|
||||||
|
} finally { first.dispose() }
|
||||||
|
const recovered = viewHarness({ createPage: true, storage, api: { createProcurement: async payload => { calls.push(normalized(payload)); return { order: { orderNo: 'PO-SAME' } } } } })
|
||||||
|
try {
|
||||||
|
assert.equal(recovered.state.form.productName, 'Test product'); await recovered.state.submit(); assert.deepEqual(calls[2], calls[0])
|
||||||
|
assert.equal(storage.size, 0); assert.equal(recovered.pushes[0].params.orderNo, 'PO-SAME')
|
||||||
|
} finally { recovered.dispose() }
|
||||||
|
})
|
||||||
|
|
||||||
|
test('submission double-click sends once and definitive validation rejection permits correction', async () => {
|
||||||
|
let reject, calls = 0
|
||||||
|
const harness = viewHarness({ createPage: true, api: { createProcurement: () => { calls++; return new Promise((_, failure) => { reject = failure }) } } })
|
||||||
|
try {
|
||||||
|
Object.assign(harness.state.form, draft()); const first = harness.state.submit(); await harness.state.submit(); assert.equal(calls, 1)
|
||||||
|
reject(new ApiError('invalid', 'A0422')); await first
|
||||||
|
assert.equal(harness.state.pending.value, null); assert.equal(harness.storage.size, 0)
|
||||||
|
} finally { harness.dispose() }
|
||||||
|
})
|
||||||
|
|
||||||
|
test('pagination batches one request and switching account clears old rows before the new response', async () => {
|
||||||
|
const calls = []; let resolveSecond
|
||||||
|
const harness = viewHarness({ api: { listProcurements: async params => {
|
||||||
|
calls.push(normalized(params)); if (calls.length < 3) return { records: [{ orderNo: 'PO-A' }], total: 100 }
|
||||||
|
return new Promise(resolve => { resolveSecond = resolve })
|
||||||
|
} } })
|
||||||
|
try {
|
||||||
|
await flush(); assert.equal(calls.length, 1)
|
||||||
|
harness.state.query.page = 2; harness.state.query.size = 50; await flush(); assert.equal(calls.length, 2)
|
||||||
|
harness.auth.token = 'identity-B'; await vue.nextTick(); assert.equal(harness.state.rows.value.length, 0); assert.equal(harness.state.total.value, 0)
|
||||||
|
resolveSecond({ records: [{ orderNo: 'PO-B' }], total: 1 }); await flush(); assert.equal(harness.state.rows.value[0].orderNo, 'PO-B')
|
||||||
|
assert.ok(calls.every(params => !('customerId' in params) && !('tenantId' in params)))
|
||||||
|
} finally { harness.dispose() }
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test('replay rejection cannot discard an earlier unknown creation outcome', async () => {
|
||||||
|
const calls = []; let attempt = 0
|
||||||
|
const harness = viewHarness({ createPage: true, api: { createProcurement: async payload => {
|
||||||
|
calls.push(normalized(payload)); attempt++
|
||||||
|
if (attempt === 1) throw new ApiError('timeout', 'TIMEOUT')
|
||||||
|
throw new ApiError('permission revoked', 'A0403')
|
||||||
|
} } })
|
||||||
|
try {
|
||||||
|
Object.assign(harness.state.form, draft()); await harness.state.submit()
|
||||||
|
const saved = [...harness.storage.values()][0]; await harness.state.submit()
|
||||||
|
assert.equal([...harness.storage.values()][0], saved); assert.ok(harness.state.pending.value)
|
||||||
|
assert.deepEqual(calls[1], calls[0])
|
||||||
|
} finally { harness.dispose() }
|
||||||
|
})
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import type { Amount, ProcurementCreate, ProcurementFee } from './api/procurement'
|
||||||
|
|
||||||
|
export const procurementStatuses: Record<string, string> = {
|
||||||
|
PENDING_REVIEW: '待审核', WAIT_PURCHASE: '待购买', WAIT_OVERSEAS_RECEIPT: '待海外到仓', OVERSEAS_RECEIVING: '海外收货中',
|
||||||
|
WAIT_PACKING: '待装箱', WAIT_LABELS: '待面单及预估处理', WAIT_OVERSEAS_SHIPMENT: '待海外交寄', INTERNATIONAL_TRANSIT: '国际运输中',
|
||||||
|
DOMESTIC_RECEIVING: '国内收货中', WAIT_CHARGES: '待国内核费', WAIT_CUSTOMER_SHIPMENT: '待寄客户', SHIPPED_TO_CUSTOMER: '已寄客户',
|
||||||
|
REJECTED: '已拒绝', CANCELLED: '已取消', EXCEPTION_CLOSED: '异常关闭',
|
||||||
|
}
|
||||||
|
export const feePurposes: Record<string, string> = {
|
||||||
|
SAMPLE_PAYMENT: '样品货款', INTERNATIONAL_ESTIMATE: '预估国际运费', INTERNATIONAL_FREIGHT: '实际国际运费',
|
||||||
|
DUTY: '关税', DOMESTIC_FREIGHT: '国内运费', OTHER: '其他费用', ADJUSTMENT: '追加费用', REFUND: '退款',
|
||||||
|
}
|
||||||
|
export function statusLabel(status: string | null | undefined) { return status ? procurementStatuses[status] || '待核对进度' : '—' }
|
||||||
|
export function statusTone(status: string | null | undefined): 'success' | 'warning' | 'danger' | 'info' | 'primary' {
|
||||||
|
if (status === 'SHIPPED_TO_CUSTOMER') return 'success'
|
||||||
|
if (status === 'REJECTED' || status === 'EXCEPTION_CLOSED') return 'danger'
|
||||||
|
if (status === 'CANCELLED') return 'info'
|
||||||
|
if (status === 'INTERNATIONAL_TRANSIT') return 'primary'
|
||||||
|
return 'warning'
|
||||||
|
}
|
||||||
|
function cents(value: Amount | null | undefined): bigint | null {
|
||||||
|
if (value === null || value === undefined) return null
|
||||||
|
const match = /^(-?)(\d+)(?:\.(\d{1,2}))?$/.exec(String(value).trim())
|
||||||
|
if (!match) return null
|
||||||
|
const result = BigInt(match[2]) * 100n + BigInt((match[3] || '').padEnd(2, '0'))
|
||||||
|
return match[1] ? -result : result
|
||||||
|
}
|
||||||
|
function decimal(value: bigint) {
|
||||||
|
const absolute = value < 0n ? -value : value
|
||||||
|
return `${value < 0n ? '-' : ''}${absolute / 100n}.${String(absolute % 100n).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
export function money(value: Amount | null | undefined, currency: string | null | undefined = 'CNY') {
|
||||||
|
const amount = cents(value)
|
||||||
|
return amount === null ? '—' : `${currency || '—'} ${decimal(amount)}`
|
||||||
|
}
|
||||||
|
export function dateTime(value: string | null | undefined) { return value ? value.replace('T', ' ').replace(/\.\d+$/, '') : '—' }
|
||||||
|
export function measurement(value: Amount | null | undefined, scale: number) {
|
||||||
|
if (value === null || value === undefined) return '—'
|
||||||
|
const parts = /^(\d+)(?:\.(\d+))?$/.exec(String(value))
|
||||||
|
if (!parts || (parts[2] || '').length > scale) return '待核对'
|
||||||
|
return `${parts[1]}.${(parts[2] || '').padEnd(scale, '0')}`
|
||||||
|
}
|
||||||
|
export function text(value: unknown) { return value === null || value === undefined || value === '' ? '—' : String(value) }
|
||||||
|
export function productHref(value: string | null | undefined) {
|
||||||
|
if (!value) return undefined
|
||||||
|
try { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) ? url.href : undefined } catch { return undefined }
|
||||||
|
}
|
||||||
|
export function feeStatus(fee: ProcurementFee) {
|
||||||
|
if (fee.purpose === 'INTERNATIONAL_ESTIMATE') {
|
||||||
|
const label: Record<string, string> = { FROZEN: '已冻结,未扣款', ZERO: '零预估已确认', SETTLED: '原预估已结清', RELEASED: '预估已释放' }
|
||||||
|
if (fee.walletStatus && label[fee.walletStatus]) return label[fee.walletStatus]
|
||||||
|
}
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
FREEZE_PENDING: '冻结处理中', FREEZE_FAILED: '冻结未成功', FROZEN: '等待扣款', SETTLE_PENDING: '扣款处理中', SETTLE_ACTUAL_PENDING: '实际费用结算中',
|
||||||
|
SETTLE_FAILED: '扣款未成功', SETTLE_ACTUAL_FAILED: '实际费用未结清', SETTLED: '已扣款', RELEASE_PENDING: '释放处理中', RELEASE_FAILED: '释放未成功',
|
||||||
|
RELEASED: '已释放冻结', REFUND_PENDING: '退款处理中', REFUND_FAILED: '退款未成功', REFUNDED: '已退款', ZERO: '已确认零元', NOT_APPLICABLE: '不适用', TERMINATED: '已终止',
|
||||||
|
}
|
||||||
|
return fee.walletStatus ? labels[fee.walletStatus] || '待核定' : '待核定'
|
||||||
|
}
|
||||||
|
export function feeTone(fee: ProcurementFee): 'success' | 'warning' | 'danger' | 'info' {
|
||||||
|
if (fee.walletStatus?.endsWith('_FAILED')) return 'danger'
|
||||||
|
if (['SETTLED', 'REFUNDED', 'ZERO', 'NOT_APPLICABLE', 'RELEASED'].includes(fee.walletStatus || '')) return 'success'
|
||||||
|
if (fee.walletStatus === 'TERMINATED') return 'info'
|
||||||
|
return 'warning'
|
||||||
|
}
|
||||||
|
export function feeTotals(fees: ProcurementFee[]) {
|
||||||
|
let paid = 0n, refunded = 0n, estimatedHold = 0n
|
||||||
|
for (const fee of fees) {
|
||||||
|
const estimate = fee.purpose === 'INTERNATIONAL_ESTIMATE'
|
||||||
|
const include = (!estimate && fee.walletStatus === 'SETTLED') || fee.walletStatus === 'REFUNDED'
|
||||||
|
|| (estimate && ['FROZEN', 'RELEASE_PENDING', 'RELEASE_FAILED'].includes(fee.walletStatus || ''))
|
||||||
|
if (!include) continue
|
||||||
|
const amount = cents(fee.amount)
|
||||||
|
if (amount === null || amount < 0n || fee.currency !== 'CNY') return null
|
||||||
|
if (estimate) estimatedHold += amount
|
||||||
|
else if (fee.walletStatus === 'REFUNDED') refunded += amount
|
||||||
|
else paid += amount
|
||||||
|
}
|
||||||
|
return { paid: decimal(paid), refunded: decimal(refunded), net: decimal(paid - refunded), estimatedHold: decimal(estimatedHold) }
|
||||||
|
}
|
||||||
|
export interface ProcurementDraft {
|
||||||
|
purchaseCategory: string
|
||||||
|
productName: string
|
||||||
|
productSpecification: string
|
||||||
|
productUrl: string
|
||||||
|
purchaseQuantity: string
|
||||||
|
budgetUnitPrice: string
|
||||||
|
currency: 'CNY' | 'USD'
|
||||||
|
receivingAddress: string
|
||||||
|
contactName: string
|
||||||
|
contactPhone: string
|
||||||
|
remark: string
|
||||||
|
}
|
||||||
|
export function emptyProcurementDraft(): ProcurementDraft {
|
||||||
|
return { purchaseCategory: '', productName: '', productSpecification: '', productUrl: '', purchaseQuantity: '1', budgetUnitPrice: '', currency: 'USD', receivingAddress: '', contactName: '', contactPhone: '', remark: '' }
|
||||||
|
}
|
||||||
|
export function draftBudgetTotal(draft: ProcurementDraft) {
|
||||||
|
const price = cents(draft.budgetUnitPrice)
|
||||||
|
if (price === null || price < 0n || !/^\d+$/.test(draft.purchaseQuantity)) return null
|
||||||
|
return decimal(price * BigInt(draft.purchaseQuantity))
|
||||||
|
}
|
||||||
|
export function buildProcurementCreate(draft: ProcurementDraft, customerName: string, key: string): ProcurementCreate {
|
||||||
|
for (const [field, label, max] of [
|
||||||
|
['purchaseCategory', '采购品类', 128], ['productName', '商品名称', 255], ['receivingAddress', '完整国内收货地址', 1000],
|
||||||
|
['contactName', '最终收件人', 128], ['contactPhone', '联系电话', 64],
|
||||||
|
] as const) {
|
||||||
|
if (!draft[field].trim() || draft[field].trim().length > max) throw new Error(`请填写有效的${label}`)
|
||||||
|
}
|
||||||
|
if (!customerName.trim()) throw new Error('当前企业信息尚未加载,请刷新登录信息后重试')
|
||||||
|
if (!/^\d+$/.test(draft.purchaseQuantity) || !Number.isSafeInteger(Number(draft.purchaseQuantity)) || Number(draft.purchaseQuantity) <= 0) throw new Error('采购数量必须为正整数')
|
||||||
|
const price = cents(draft.budgetUnitPrice)
|
||||||
|
if (price === null || price < 0n) throw new Error('请明确填写非负预算单价,最多两位小数;免费样品填写 0')
|
||||||
|
if (price > BigInt(Number.MAX_SAFE_INTEGER) || cents(Number(decimal(price))) !== price) throw new Error('预算金额过大,无法准确表示,请核对金额')
|
||||||
|
if (!['CNY', 'USD'].includes(draft.currency)) throw new Error('预算币种只支持 CNY 或 USD')
|
||||||
|
if (!/^[+0-9][0-9 ()-]{5,63}$/.test(draft.contactPhone.trim())) throw new Error('请填写快递可联系的电话号码,微信或邮箱不能代替电话')
|
||||||
|
if (draft.productUrl && (!productHref(draft.productUrl.trim()) || draft.productUrl.trim().length > 2000)) throw new Error('商品链接须为有效的 http 或 https 地址')
|
||||||
|
if (draft.productSpecification.length > 500 || draft.remark.length > 1000) throw new Error('商品规格或备注超过长度限制')
|
||||||
|
return { customerName: customerName.trim(), purchaseCategory: draft.purchaseCategory.trim(), productName: draft.productName.trim(),
|
||||||
|
productSpecification: draft.productSpecification.trim() || undefined, productUrl: draft.productUrl.trim() || undefined,
|
||||||
|
purchaseQuantity: Number(draft.purchaseQuantity), budgetUnitPrice: Number(decimal(price)), currency: draft.currency,
|
||||||
|
receivingAddress: draft.receivingAddress.trim(), contactName: draft.contactName.trim(), contactPhone: draft.contactPhone.trim(),
|
||||||
|
remark: draft.remark.trim() || undefined, idempotencyKey: key }
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { ProcurementCreate } from './api/procurement'
|
||||||
|
import { buildProcurementCreate, emptyProcurementDraft } from './procurementPresentation'
|
||||||
|
|
||||||
|
/** Restore the exact request; an unknown result cannot become a new order. */
|
||||||
|
export function restoreProcurementSubmission(raw: string): ProcurementCreate {
|
||||||
|
const saved: unknown = JSON.parse(raw)
|
||||||
|
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) throw new Error('提交记录格式错误')
|
||||||
|
const value = saved as Record<string, unknown>
|
||||||
|
for (const key of ['customerName', 'purchaseCategory', 'productName', 'currency', 'receivingAddress', 'contactName', 'contactPhone', 'idempotencyKey']) if (typeof value[key] !== 'string') throw new Error('提交记录不完整')
|
||||||
|
if (typeof value.purchaseQuantity !== 'number' || typeof value.budgetUnitPrice !== 'number' || !String(value.idempotencyKey).trim() || String(value.idempotencyKey).length > 255) throw new Error('提交记录不完整')
|
||||||
|
for (const key of ['productSpecification', 'productUrl', 'remark']) if (value[key] !== undefined && typeof value[key] !== 'string') throw new Error('提交记录不完整')
|
||||||
|
if (value.currency !== 'CNY' && value.currency !== 'USD') throw new Error('提交记录币种无效')
|
||||||
|
return buildProcurementCreate({ ...emptyProcurementDraft(), purchaseCategory: String(value.purchaseCategory), productName: String(value.productName),
|
||||||
|
productSpecification: String(value.productSpecification || ''), productUrl: String(value.productUrl || ''), purchaseQuantity: String(value.purchaseQuantity),
|
||||||
|
budgetUnitPrice: String(value.budgetUnitPrice), currency: value.currency, receivingAddress: String(value.receivingAddress), contactName: String(value.contactName),
|
||||||
|
contactPhone: String(value.contactPhone), remark: String(value.remark || '') }, String(value.customerName), String(value.idempotencyKey))
|
||||||
|
}
|
||||||
|
export function definitelyRejected(error: { code?: string; status?: number }) {
|
||||||
|
return ['A0400', 'A0401', 'A0403', 'A0422'].includes(error.code || '') || [400, 401, 403, 422].includes(error.status || 0)
|
||||||
|
}
|
||||||
|
export function procurementRequestKey(provider: Pick<Crypto, 'getRandomValues'> & Partial<Pick<Crypto, 'randomUUID'>> = globalThis.crypto) {
|
||||||
|
if (provider.randomUUID) return provider.randomUUID()
|
||||||
|
return `proc-${Array.from(provider.getRandomValues(new Uint32Array(4)), value => value.toString(16).padStart(8, '0')).join('')}`
|
||||||
|
}
|
||||||
@@ -1,6 +1,187 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import BusinessOrdersView from '../components/BusinessOrdersView.vue'
|
import { computed, onBeforeUnmount, reactive, ref, shallowRef, watch } from 'vue'
|
||||||
defineProps<{ createPage?: boolean; detailPage?: boolean }>()
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { ApiError } from '@/api/types'
|
||||||
|
import { accessTokenIdentity } from '@/api/session'
|
||||||
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
|
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||||
|
import type { TableAction } from '@/components/common/tableActions'
|
||||||
|
import ProcurementDetailPanel from '../components/ProcurementDetailPanel.vue'
|
||||||
|
import { createProcurement, getProcurement, listProcurements, type ProcurementCreate, type ProcurementDetail, type ProcurementSummary } from '../api/procurement'
|
||||||
|
import { buildProcurementCreate, dateTime, draftBudgetTotal, emptyProcurementDraft, money, procurementStatuses, statusLabel, statusTone } from '../procurementPresentation'
|
||||||
|
import { definitelyRejected, procurementRequestKey, restoreProcurementSubmission } from '../procurementSubmission'
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean }>(), { createPage: false, detailPage: false })
|
||||||
|
const auth = useAuthStore(), route = useRoute(), router = useRouter()
|
||||||
|
const mode = computed(() => props.detailPage ? 'detail' : props.createPage ? 'create' : 'list')
|
||||||
|
const orderNo = computed(() => typeof route.params.orderNo === 'string' ? route.params.orderNo : '')
|
||||||
|
const canCreate = computed(() => auth.hasPermission('merchant:cross-border:procurement:create'))
|
||||||
|
const canList = computed(() => auth.hasPermission('merchant:cross-border:procurement:list'))
|
||||||
|
const identity = computed(() => auth.token ? accessTokenIdentity(auth.token) : null)
|
||||||
|
const storageKey = computed(() => identity.value ? `cc-procurement-submit:${encodeURIComponent(identity.value)}` : null)
|
||||||
|
const companyName = computed(() => auth.profile.tenantName || (auth.user?.tenantName && !/^企业租户 \d+$/.test(auth.user.tenantName) ? auth.user.tenantName : ''))
|
||||||
|
const form = reactive(emptyProcurementDraft())
|
||||||
|
const pending = shallowRef<ProcurementCreate | null>(null)
|
||||||
|
const recoveryError = ref(''), submitError = ref(''), submittedOrder = ref('')
|
||||||
|
const submitting = ref(false), loading = ref(false), error = ref('')
|
||||||
|
const detail = shallowRef<ProcurementDetail | null>(null)
|
||||||
|
const rows = ref<ProcurementSummary[]>([]), total = ref(0)
|
||||||
|
const query = reactive({ page: 1, size: 20, orderNo: '', purchaseCategory: '', productName: '', status: '' })
|
||||||
|
let requestSequence = 0, active = true, inFlight = ''
|
||||||
|
const queryModel = computed<QueryModel>({
|
||||||
|
get: () => ({ orderNo: query.orderNo, purchaseCategory: query.purchaseCategory, productName: query.productName, status: query.status }),
|
||||||
|
set: value => { for (const key of ['orderNo', 'purchaseCategory', 'productName', 'status'] as const) query[key] = String(value[key] || '') },
|
||||||
|
})
|
||||||
|
const queryFields: QueryField[] = [
|
||||||
|
{ key: 'orderNo', label: '采购单号', type: 'input' }, { key: 'purchaseCategory', label: '采购品类', type: 'input' },
|
||||||
|
{ key: 'productName', label: '商品名称', type: 'input' },
|
||||||
|
{ key: 'status', label: '履约进度', type: 'select', options: Object.entries(procurementStatuses).map(([value, label]) => ({ value, label })) },
|
||||||
|
]
|
||||||
|
const columns: DataTableColumn[] = [
|
||||||
|
{ key: 'actions', label: '操作', width: 90, fixed: 'left', slotName: 'actions' },
|
||||||
|
{ prop: 'orderNo', label: '采购单号', minWidth: 250, slotName: 'orderNo' },
|
||||||
|
{ prop: 'purchaseCategory', label: '采购品类', width: 120 }, { prop: 'productName', label: '商品名称', minWidth: 200 },
|
||||||
|
{ prop: 'productSpecification', label: '商品规格', minWidth: 160 }, { prop: 'purchaseQuantity', label: '采购数量(件)', width: 135 },
|
||||||
|
{ prop: 'budgetUnitPrice', label: '预算单价', width: 155, slotName: 'budget' },
|
||||||
|
{ prop: 'status', label: '履约进度', width: 180, slotName: 'status' }, { prop: 'createdAt', label: '下单时间', width: 185, slotName: 'createdAt' },
|
||||||
|
]
|
||||||
|
function rowActions(row: object): TableAction[] { return [{ key: 'detail', label: '详情', run: () => openDetail(row as ProcurementSummary) }] }
|
||||||
|
function openDetail(row: ProcurementSummary) { if (row.orderNo) void router.push({ name: 'cross-border-procurement-detail', params: { orderNo: row.orderNo } }) }
|
||||||
|
function returnToList() { if (canList.value) void router.push({ name: 'cross-border-procurement' }) }
|
||||||
|
function message(cause: unknown) {
|
||||||
|
if (cause instanceof ApiError && ((cause.status || 0) >= 500 || cause.code.startsWith('B'))) return '服务暂不可用,请稍后重试'
|
||||||
|
return cause instanceof Error ? cause.message : '请求失败,请稍后重试'
|
||||||
|
}
|
||||||
|
async function loadList() {
|
||||||
|
const params = { page: query.page, size: query.size, orderNo: query.orderNo || undefined, productName: query.productName || undefined, purchaseCategory: query.purchaseCategory || undefined, status: query.status || undefined }
|
||||||
|
const key = JSON.stringify([identity.value, params])
|
||||||
|
if (inFlight === key) return
|
||||||
|
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''
|
||||||
|
try { const result = await listProcurements(params); if (sequence === requestSequence) { rows.value = result.records; total.value = result.total } }
|
||||||
|
catch (cause) { if (sequence === requestSequence) { rows.value = []; total.value = 0; error.value = message(cause) } }
|
||||||
|
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
|
||||||
|
}
|
||||||
|
async function loadDetail() {
|
||||||
|
if (!orderNo.value) { error.value = '采购单号缺失'; return }
|
||||||
|
const key = JSON.stringify([identity.value, orderNo.value])
|
||||||
|
if (inFlight === key) return
|
||||||
|
const sequence = ++requestSequence; inFlight = key; loading.value = true; error.value = ''; detail.value = null
|
||||||
|
try { const result = await getProcurement(orderNo.value); if (sequence === requestSequence) detail.value = result }
|
||||||
|
catch (cause) { if (sequence === requestSequence) error.value = message(cause) }
|
||||||
|
finally { if (sequence === requestSequence) { loading.value = false; inFlight = '' } }
|
||||||
|
}
|
||||||
|
function search() { if (query.page === 1) void loadList(); else query.page = 1 }
|
||||||
|
function resetQuery() { const reload = query.page === 1; Object.assign(query, { page: 1, orderNo: '', purchaseCategory: '', productName: '', status: '' }); if (reload) void loadList() }
|
||||||
|
function populate(payload: ProcurementCreate) {
|
||||||
|
Object.assign(form, { purchaseCategory: payload.purchaseCategory, productName: payload.productName, productSpecification: payload.productSpecification || '', productUrl: payload.productUrl || '',
|
||||||
|
purchaseQuantity: String(payload.purchaseQuantity), budgetUnitPrice: String(payload.budgetUnitPrice), currency: payload.currency, receivingAddress: payload.receivingAddress,
|
||||||
|
contactName: payload.contactName, contactPhone: payload.contactPhone, remark: payload.remark || '' })
|
||||||
|
}
|
||||||
|
function restorePending() {
|
||||||
|
pending.value = null; recoveryError.value = ''; submitError.value = ''; submittedOrder.value = ''; Object.assign(form, emptyProcurementDraft())
|
||||||
|
if (!storageKey.value) return
|
||||||
|
try { const saved = sessionStorage.getItem(storageKey.value); if (saved) { pending.value = Object.freeze(restoreProcurementSubmission(saved)); populate(pending.value) } }
|
||||||
|
catch { recoveryError.value = '上次提交记录暂无法恢复,请先在订单列表或通过客服核对提交结果,避免重复下单。' }
|
||||||
|
}
|
||||||
|
async function submit() {
|
||||||
|
if (submitting.value || !canCreate.value || recoveryError.value || !storageKey.value) return
|
||||||
|
submitError.value = ''; const owner = identity.value, key = storageKey.value; const resuming = Boolean(pending.value)
|
||||||
|
let started = false
|
||||||
|
try {
|
||||||
|
if (!pending.value) {
|
||||||
|
const payload = buildProcurementCreate(form, companyName.value, procurementRequestKey())
|
||||||
|
try { sessionStorage.setItem(key, JSON.stringify(payload)) } catch { throw new Error('浏览器暂无法保留提交信息,请允许会话存储后重试') }
|
||||||
|
pending.value = Object.freeze(payload)
|
||||||
|
}
|
||||||
|
submitting.value = true; started = true
|
||||||
|
const result = await createProcurement(pending.value)
|
||||||
|
sessionStorage.removeItem(key)
|
||||||
|
if (!active || owner !== identity.value) return
|
||||||
|
pending.value = null; submittedOrder.value = result.order.orderNo; ElMessage.success('采购订单已提交')
|
||||||
|
if (canList.value) await router.push({ name: 'cross-border-procurement-detail', params: { orderNo: result.order.orderNo } })
|
||||||
|
} catch (cause) {
|
||||||
|
if (!active || owner !== identity.value) return
|
||||||
|
if (!resuming && cause instanceof ApiError && definitelyRejected(cause)) { sessionStorage.removeItem(key); pending.value = null }
|
||||||
|
submitError.value = started && pending.value ? `${message(cause)}。提交结果尚未确认,请再次确认上次提交结果。` : message(cause)
|
||||||
|
} finally { submitting.value = false }
|
||||||
|
}
|
||||||
|
watch(() => [mode.value, orderNo.value, query.page, query.size, identity.value], (values, previous) => {
|
||||||
|
if (values[4] !== previous?.[4]) { rows.value = []; total.value = 0 }
|
||||||
|
++requestSequence; inFlight = ''; loading.value = false; error.value = ''; detail.value = null
|
||||||
|
if (mode.value === 'create') restorePending()
|
||||||
|
else if (mode.value === 'detail') void loadDetail()
|
||||||
|
else void loadList()
|
||||||
|
}, { immediate: true })
|
||||||
|
onBeforeUnmount(() => { active = false; ++requestSequence })
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template><BusinessOrdersView kind="procurement" :create-page="createPage" :detail-page="detailPage" /></template>
|
<template>
|
||||||
|
<section class="procurement-page client-ui" :aria-busy="loading || submitting">
|
||||||
|
<template v-if="mode === 'list'">
|
||||||
|
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="采购订单查询条件" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetQuery" />
|
||||||
|
<div class="procurement-table-card">
|
||||||
|
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="columns" :row-actions="rowActions" :loading="loading" :total="total" :page-sizes="[10, 20, 50, 100]" row-key="orderNo" empty-text="暂无采购订单">
|
||||||
|
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="router.push({ name: 'cross-border-procurement-create' })">新增下单</el-button></template>
|
||||||
|
<template v-if="error" #error><div class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadList">重新加载</el-button></div></template>
|
||||||
|
<template #orderNo="{ row }"><button class="procurement-link" type="button" @click="openDetail(row as ProcurementSummary)">{{ (row as ProcurementSummary).orderNo || '—' }}</button></template>
|
||||||
|
<template #budget="{ row }">{{ money((row as ProcurementSummary).budgetUnitPrice, (row as ProcurementSummary).currency) }}</template>
|
||||||
|
<template #status="{ row }"><el-tag :type="statusTone((row as ProcurementSummary).status)" size="small">{{ statusLabel((row as ProcurementSummary).status) }}</el-tag></template>
|
||||||
|
<template #createdAt="{ row }">{{ dateTime((row as ProcurementSummary).createdAt) }}</template>
|
||||||
|
</DataTable>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<section v-else-if="mode === 'detail'" v-loading="loading" class="procurement-detail" aria-label="采购订单详情">
|
||||||
|
<header class="procurement-heading"><div><el-button link type="primary" @click="returnToList">← 返回列表</el-button><h2>{{ detail?.order.orderNo || '采购订单详情' }}</h2></div><div><el-tag v-if="detail" :type="statusTone(detail.order.status)">{{ statusLabel(detail.order.status) }}</el-tag><el-button :disabled="loading" @click="loadDetail">刷新</el-button></div></header>
|
||||||
|
<div v-if="error" class="procurement-error" role="alert"><span>{{ error }}</span><el-button :disabled="loading" @click="loadDetail">重新加载</el-button></div>
|
||||||
|
<ProcurementDetailPanel v-else-if="detail" :detail="detail" /><el-skeleton v-else :rows="8" animated />
|
||||||
|
</section>
|
||||||
|
<section v-else class="procurement-create" aria-label="采购下单">
|
||||||
|
<header class="procurement-heading"><div><h2>海外采购下单</h2><p>一单一个商品及规格;预算仅授权样品货款,运费及关税另行核定。</p></div><el-button v-if="canList" @click="returnToList">返回列表</el-button></header>
|
||||||
|
<el-result v-if="!canCreate" icon="warning" title="没有采购下单权限" sub-title="请联系企业管理员配置权限" />
|
||||||
|
<el-result v-else-if="submittedOrder" icon="success" title="采购订单已提交" :sub-title="submittedOrder"><template #extra><el-button @click="restorePending">新建另一单</el-button></template></el-result>
|
||||||
|
<template v-else>
|
||||||
|
<el-alert v-if="recoveryError" :title="recoveryError" type="error" :closable="false" />
|
||||||
|
<el-alert v-else-if="pending" title="已保留本次提交内容。请再次确认上次提交结果,确认前不修改订单信息。" type="warning" :closable="false" />
|
||||||
|
<el-alert v-if="submitError" class="submit-error" :title="submitError" type="error" :closable="false" />
|
||||||
|
<el-form :model="form" label-position="top" :disabled="submitting || Boolean(pending) || Boolean(recoveryError)" @submit.prevent="submit">
|
||||||
|
<h3>商品与预算</h3><div class="procurement-form-grid">
|
||||||
|
<el-form-item label="采购品类" required><el-input v-model.trim="form.purchaseCategory" maxlength="128" placeholder="请输入采购品类" /></el-form-item>
|
||||||
|
<el-form-item label="商品名称" required><el-input v-model.trim="form.productName" maxlength="255" placeholder="请输入商品名称" /></el-form-item>
|
||||||
|
<el-form-item label="商品规格"><el-input v-model.trim="form.productSpecification" maxlength="500" placeholder="规格、型号" /></el-form-item>
|
||||||
|
<el-form-item label="采购数量(件)" required><el-input v-model.trim="form.purchaseQuantity" inputmode="numeric" maxlength="18" placeholder="正整数" /></el-form-item>
|
||||||
|
<el-form-item label="预算单价" required><el-input v-model.trim="form.budgetUnitPrice" inputmode="decimal" maxlength="20" placeholder="请明确填写;免费样品填 0" /></el-form-item>
|
||||||
|
<el-form-item label="预算币种" required><el-select v-model="form.currency"><el-option label="美元 USD" value="USD" /><el-option label="人民币 CNY" value="CNY" /></el-select></el-form-item>
|
||||||
|
<el-form-item class="full" label="商品链接"><el-input v-model.trim="form.productUrl" maxlength="2000" placeholder="https://…" /></el-form-item>
|
||||||
|
</div><p class="procurement-hint">货款预算总上限:<strong>{{ money(draftBudgetTotal(form), form.currency) }}</strong>。零预算仅授权免费样品;实际货款按供应商实付核定。</p>
|
||||||
|
<h3>最终国内收件资料</h3><div class="procurement-form-grid">
|
||||||
|
<el-form-item label="收件人" required><el-input v-model.trim="form.contactName" maxlength="128" placeholder="实际收件人姓名" /></el-form-item>
|
||||||
|
<el-form-item label="联系电话" required><el-input v-model.trim="form.contactPhone" maxlength="64" type="tel" placeholder="快递可联系的电话" /></el-form-item>
|
||||||
|
<el-form-item label="下单企业"><el-input :model-value="companyName" disabled /></el-form-item>
|
||||||
|
<el-form-item class="full" label="完整国内地址" required><el-input v-model.trim="form.receivingAddress" maxlength="1000" placeholder="省、市、区县、街道及详细门牌" /></el-form-item>
|
||||||
|
<el-form-item class="full" label="采购要求"><el-input v-model="form.remark" type="textarea" :rows="3" maxlength="1000" show-word-limit placeholder="其他采购要求(选填)" /></el-form-item>
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
<footer class="procurement-form-actions"><el-button v-if="canList" :disabled="submitting" @click="returnToList">返回列表</el-button><el-button type="primary" :loading="submitting" :disabled="Boolean(recoveryError) || (!pending && !companyName) || !identity" @click="submit">{{ pending ? '确认上次提交结果' : '提交采购订单' }}</el-button></footer>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.procurement-page { display: grid; gap: var(--client-section-gap); min-width: 0; }
|
||||||
|
.procurement-table-card, .procurement-detail, .procurement-create { min-width: 0; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; }
|
||||||
|
.procurement-table-card { overflow: hidden; }.procurement-detail, .procurement-create { padding: 16px 20px 24px; }
|
||||||
|
.procurement-heading { display: flex; justify-content: space-between; align-items: center; gap: 20px; min-height: 54px; border-bottom: 1px solid var(--border); padding-bottom: 12px; }
|
||||||
|
.procurement-heading > div { display: flex; align-items: center; gap: 14px; min-width: 0; }.procurement-heading h2 { margin: 0; color: var(--navy); font-size: 18px; overflow-wrap: anywhere; }
|
||||||
|
.procurement-create .procurement-heading > div { display: block; }.procurement-heading p { margin: 7px 0 0; font-size: 13px; color: var(--muted); }
|
||||||
|
.procurement-link { padding: 0; border: 0; background: transparent; color: var(--client-action); font: inherit; cursor: pointer; text-align: left; }.procurement-link:hover { text-decoration: underline; }
|
||||||
|
.procurement-error { min-height: 160px; display: flex; justify-content: center; align-items: center; gap: 16px; color: #b42318; }.procurement-error span { max-width: 900px; overflow-wrap: anywhere; }
|
||||||
|
.procurement-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 24px; }.procurement-form-grid .full { grid-column: 1 / -1; }.procurement-form-grid :deep(.el-select) { width: 100%; }
|
||||||
|
.procurement-create h3 { margin: 22px 0 16px; color: var(--navy); font-size: 14px; }.procurement-hint { margin: 0 0 20px; line-height: 1.8; font-size: 13px; color: var(--muted); }.procurement-hint strong { color: var(--navy); }
|
||||||
|
.procurement-form-actions { display: flex; justify-content: flex-end; gap: 12px; padding-top: 16px; border-top: 1px solid var(--border); }.submit-error { margin: 12px 0; }
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
.procurement-form-grid { grid-template-columns: 1fr; }.procurement-heading, .procurement-heading > div { flex-wrap: wrap; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed } from 'vue'
|
import { computed } from 'vue'
|
||||||
import { ArrowRight, Forklift, RefreshCcw, Ship, ShoppingCart, Tags, Truck } from '@lucide/vue'
|
import { ArrowRight, Forklift, PackageOpen, RefreshCcw, Ship, ShoppingCart, Tags, Truck, Warehouse } from '@lucide/vue'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
import { FirstLegOrdersView } from '@/modules/first-leg/public'
|
import { FirstLegOrdersView } from '@/modules/first-leg/public'
|
||||||
|
|
||||||
@@ -13,6 +13,8 @@ const primaryActions = computed(() => [
|
|||||||
{ title: '美本土散板', description: '拼车拼载 · 打盘服务 · 灵活派送', icon: Forklift, route: '/cross-border/pallet-shipping/create', permission: 'merchant:cross-border:pallet-shipping:create', tone: 'cyan', featured: false },
|
{ title: '美本土散板', description: '拼车拼载 · 打盘服务 · 灵活派送', icon: Forklift, route: '/cross-border/pallet-shipping/create', permission: 'merchant:cross-border:pallet-shipping:create', tone: 'cyan', featured: false },
|
||||||
{ title: '海外采购', description: '采购代购 · 验货质检 · 集中发货', icon: ShoppingCart, route: '/cross-border/procurement/create', permission: 'merchant:cross-border:procurement:create', tone: 'orange', featured: false },
|
{ title: '海外采购', description: '采购代购 · 验货质检 · 集中发货', icon: ShoppingCart, route: '/cross-border/procurement/create', permission: 'merchant:cross-border:procurement:create', tone: 'orange', featured: false },
|
||||||
{ title: '贴标申请', description: '产品建档 · 标签上传 · 批量贴标', icon: Tags, route: '/overseas-warehouse/labeling/create', permission: 'merchant:overseas-warehouse:relabel:create', tone: 'rose', featured: false },
|
{ title: '贴标申请', description: '产品建档 · 标签上传 · 批量贴标', icon: Tags, route: '/overseas-warehouse/labeling/create', permission: 'merchant:overseas-warehouse:relabel:create', tone: 'rose', featured: false },
|
||||||
|
{ title: '仓储转运', description: '仓储管理 · 货物转运', icon: Warehouse, route: '/overseas-warehouse/storage-transfer', permission: 'merchant:overseas-warehouse:transfer:list', tone: 'teal', featured: false, actionLabel: '开始办理' },
|
||||||
|
{ title: '货物废弃', description: '废弃申请 · 处理进度', icon: PackageOpen, route: '/overseas-warehouse/cargo-disposal', permission: 'merchant:overseas-warehouse:discard:list', tone: 'brown', featured: false, actionLabel: '开始办理' },
|
||||||
].filter((action) => auth.hasPermission(action.permission)))
|
].filter((action) => auth.hasPermission(action.permission)))
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
@@ -28,7 +30,7 @@ const primaryActions = computed(() => [
|
|||||||
<RouterLink v-for="(action, index) in primaryActions" :key="action.route" :to="action.route" class="quick-action" :class="[`quick-action--${action.tone}`, { 'quick-action--featured': action.featured }]" :style="{ '--entry-index': index }">
|
<RouterLink v-for="(action, index) in primaryActions" :key="action.route" :to="action.route" class="quick-action" :class="[`quick-action--${action.tone}`, { 'quick-action--featured': action.featured }]" :style="{ '--entry-index': index }">
|
||||||
<span class="action-icon"><component :is="action.icon" :size="25" :stroke-width="2.2" aria-hidden="true" /></span>
|
<span class="action-icon"><component :is="action.icon" :size="25" :stroke-width="2.2" aria-hidden="true" /></span>
|
||||||
<span class="action-copy"><strong>{{ action.title }}</strong><small>{{ action.description }}</small></span>
|
<span class="action-copy"><strong>{{ action.title }}</strong><small>{{ action.description }}</small></span>
|
||||||
<span class="action-enter"><span>开始下单</span><ArrowRight :size="15" aria-hidden="true" /></span>
|
<span class="action-enter"><span>{{ action.actionLabel ?? '开始下单' }}</span><ArrowRight :size="15" aria-hidden="true" /></span>
|
||||||
</RouterLink>
|
</RouterLink>
|
||||||
<p v-if="!primaryActions.length" class="no-actions">当前账号暂无常用业务权限,请通过已授权菜单办理业务,或联系企业管理员。</p>
|
<p v-if="!primaryActions.length" class="no-actions">当前账号暂无常用业务权限,请通过已授权菜单办理业务,或联系企业管理员。</p>
|
||||||
</section>
|
</section>
|
||||||
@@ -46,7 +48,7 @@ const primaryActions = computed(() => [
|
|||||||
.business-intro { padding-top: 0; }
|
.business-intro { padding-top: 0; }
|
||||||
.business-intro h1 { margin: 0; color: #172033; font-size: 27px; font-weight: 750; letter-spacing: -.5px; line-height: 1.3; }
|
.business-intro h1 { margin: 0; color: #172033; font-size: 27px; font-weight: 750; letter-spacing: -.5px; line-height: 1.3; }
|
||||||
.business-intro p { margin: 5px 0 0; color: #7a8495; font-size: 13px; line-height: 1.55; }
|
.business-intro p { margin: 5px 0 0; color: #7a8495; font-size: 13px; line-height: 1.55; }
|
||||||
.quick-actions { display: grid; grid-template-columns: repeat(6, minmax(188px, 1fr)); gap: 10px; overflow-x: auto; padding: 0 0 6px; scroll-snap-type: x proximity; scrollbar-color: #bdc9dc transparent; scrollbar-width: thin; }
|
.quick-actions { display: grid; grid-template-columns: repeat(8, minmax(150px, 1fr)); gap: 10px; overflow-x: auto; padding: 0 0 6px; scroll-snap-type: x proximity; scrollbar-color: #bdc9dc transparent; scrollbar-width: thin; }
|
||||||
.quick-actions::-webkit-scrollbar { height: 7px; }
|
.quick-actions::-webkit-scrollbar { height: 7px; }
|
||||||
.quick-actions::-webkit-scrollbar-thumb { border-radius: 999px; background: #bdc9dc; }
|
.quick-actions::-webkit-scrollbar-thumb { border-radius: 999px; background: #bdc9dc; }
|
||||||
.quick-actions::-webkit-scrollbar-track { background: transparent; }
|
.quick-actions::-webkit-scrollbar-track { background: transparent; }
|
||||||
@@ -60,6 +62,8 @@ const primaryActions = computed(() => [
|
|||||||
.quick-action--cyan { --action-a: #0891b2; --action-b: #0e7490; --action-soft: rgba(8, 145, 178, .18); }
|
.quick-action--cyan { --action-a: #0891b2; --action-b: #0e7490; --action-soft: rgba(8, 145, 178, .18); }
|
||||||
.quick-action--orange { --action-a: #f59e0b; --action-b: #dc6b12; --action-soft: rgba(245, 158, 11, .2); }
|
.quick-action--orange { --action-a: #f59e0b; --action-b: #dc6b12; --action-soft: rgba(245, 158, 11, .2); }
|
||||||
.quick-action--rose { --action-a: #e11d48; --action-b: #be185d; --action-soft: rgba(225, 29, 72, .17); }
|
.quick-action--rose { --action-a: #e11d48; --action-b: #be185d; --action-soft: rgba(225, 29, 72, .17); }
|
||||||
|
.quick-action--teal { --action-a: #0f766e; --action-b: #0e7490; --action-soft: rgba(15, 118, 110, .18); }
|
||||||
|
.quick-action--brown { --action-a: #b45309; --action-b: #c2410c; --action-soft: rgba(180, 83, 9, .18); }
|
||||||
.quick-action:hover { border-color: color-mix(in srgb, var(--action-a) 35%, transparent); box-shadow: 0 24px 54px rgba(15, 23, 42, .14), 0 0 0 1px color-mix(in srgb, var(--action-a) 16%, transparent); transform: translateY(-9px); }
|
.quick-action:hover { border-color: color-mix(in srgb, var(--action-a) 35%, transparent); box-shadow: 0 24px 54px rgba(15, 23, 42, .14), 0 0 0 1px color-mix(in srgb, var(--action-a) 16%, transparent); transform: translateY(-9px); }
|
||||||
.quick-action:hover::before { transform: scale(1.25); }
|
.quick-action:hover::before { transform: scale(1.25); }
|
||||||
.quick-action:hover::after { right: 12%; left: 12%; opacity: 1; transform: scaleX(1); }
|
.quick-action:hover::after { right: 12%; left: 12%; opacity: 1; transform: scaleX(1); }
|
||||||
@@ -93,8 +97,8 @@ const primaryActions = computed(() => [
|
|||||||
@keyframes action-enter { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: translateY(0); } }
|
@keyframes action-enter { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: translateY(0); } }
|
||||||
@keyframes featured-aura { 0%, 100% { opacity: .86; transform: translate3d(0, 0, 0) scale(1); } 50% { opacity: 1; transform: translate3d(-10px, 9px, 0) scale(1.08); } }
|
@keyframes featured-aura { 0%, 100% { opacity: .86; transform: translate3d(0, 0, 0) scale(1); } 50% { opacity: 1; transform: translate3d(-10px, 9px, 0) scale(1.08); } }
|
||||||
@keyframes featured-shine { 0%, 55% { left: -55%; opacity: 0; } 65% { opacity: 1; } 88%, 100% { left: 125%; opacity: 0; } }
|
@keyframes featured-shine { 0%, 55% { left: -55%; opacity: 0; } 65% { opacity: 1; } 88%, 100% { left: 125%; opacity: 0; } }
|
||||||
@container dashboard-content (max-width: 1180px) { .quick-actions { grid-template-columns: repeat(6, minmax(178px, 1fr)); } }
|
@container dashboard-content (max-width: 1180px) { .quick-actions { grid-template-columns: repeat(8, minmax(178px, 1fr)); } }
|
||||||
@media (max-width: 720px) { .client-dashboard { padding: 0; gap: 16px; } .business-intro h1 { font-size: 25px; } .quick-actions { grid-template-columns: repeat(2, minmax(150px, 1fr)); } }
|
@media (max-width: 720px) { .client-dashboard { padding: 0; gap: 16px; } .business-intro h1 { font-size: 25px; } .quick-actions { grid-template-columns: repeat(2, minmax(150px, 1fr)); } }
|
||||||
@media (max-width: 420px) { .quick-actions { grid-template-columns: repeat(6, minmax(168px, 1fr)); } }
|
@media (max-width: 420px) { .quick-actions { grid-template-columns: repeat(8, minmax(168px, 1fr)); } }
|
||||||
@media (prefers-reduced-motion: reduce) { .client-dashboard, .quick-action, .quick-action--featured::before, .quick-action--featured .action-enter::before { animation: none; } .quick-action, .quick-action::before, .quick-action::after, .action-icon, .action-enter svg { transition: none; } }
|
@media (prefers-reduced-motion: reduce) { .client-dashboard, .quick-action, .quick-action--featured::before, .quick-action--featured .action-enter::before { animation: none; } .quick-action, .quick-action::before, .quick-action::after, .action-icon, .action-enter svg { transition: none; } }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -283,3 +283,11 @@ export function merchantCustomsErrorMessage(error: unknown, fallback: string) {
|
|||||||
export function isMerchantCustomsUnavailable(error: unknown) {
|
export function isMerchantCustomsUnavailable(error: unknown) {
|
||||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export async function getMerchantCustomsPendingCount() {
|
||||||
|
const result = await apiRequest<{ pendingCount: string | number }>({ method: 'GET', url: '/merchant/v1/customs/pending-summary' })
|
||||||
|
const count = Number(result.pendingCount)
|
||||||
|
if (result.pendingCount == null || result.pendingCount === '' || !Number.isSafeInteger(count) || count < 0) throw new Error('报关待办数量返回不完整')
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|||||||
@@ -566,14 +566,19 @@ export function createMerchantFirstLegOrderBatch(items: MerchantBatchDraftItem[]
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function updateMerchantFirstLegOrder(id: number | string, payload: FirstLegOrderSaveRequest) {
|
export function updateMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; draft: FirstLegOrderSaveRequest }, idempotencyKey: string) {
|
||||||
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload })
|
return apiRequest<void>({ method: 'PUT', url: `/merchant/v1/orders/first-leg/${id}`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||||
}
|
}
|
||||||
|
|
||||||
export function submitMerchantFirstLegOrder(id: number | string, idempotencyKey: string) {
|
export function cancelMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number; reason: string }, idempotencyKey: string) {
|
||||||
|
return apiRequest<void>({ method: 'POST', url: `/merchant/v1/orders/first-leg/${id}/cancel`, data: payload, headers: { 'Idempotency-Key': idempotencyKey } })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function submitMerchantFirstLegOrder(id: number | string, payload: { expectedVersion: number }, idempotencyKey: string) {
|
||||||
return apiRequest<void>({
|
return apiRequest<void>({
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
url: `/merchant/v1/orders/first-leg/${id}/submit`,
|
||||||
|
data: payload,
|
||||||
headers: { 'Idempotency-Key': idempotencyKey },
|
headers: { 'Idempotency-Key': idempotencyKey },
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,28 @@
|
|||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import test from 'node:test'
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
const source = readFileSync(new URL('./unifiedOrders.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
test('forwards optional tax mode and pagination through the current GET endpoint', async () => {
|
||||||
|
const calls = []
|
||||||
|
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||||
|
const api = {}
|
||||||
|
new Function('require', 'exports', code)(id => {
|
||||||
|
assert.equal(id, '@/api/http')
|
||||||
|
return { apiRequest: async config => { calls.push(config); return { records: [] } } }
|
||||||
|
}, api)
|
||||||
|
await api.getMerchantUnifiedOrders({ page: 2, size: 200, taxMode: 'TAX_REFUND' })
|
||||||
|
await api.getMerchantUnifiedOrders({ taxMode: 'BUY_DECLARATION' })
|
||||||
|
await api.getMerchantUnifiedOrders()
|
||||||
|
assert.deepEqual(calls, [
|
||||||
|
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 2, size: 200, taxMode: 'TAX_REFUND' } },
|
||||||
|
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200, taxMode: 'BUY_DECLARATION' } },
|
||||||
|
{ method: 'GET', url: '/merchant/v1/orders', params: { page: 1, size: 200 } },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
test('keeps the merchant unified-order boundary and one-click palletization status', () => {
|
test('keeps the merchant unified-order boundary and one-click palletization status', () => {
|
||||||
assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
|
assert.match(source, /const unifiedOrderBaseUrl = '\/merchant\/v1\/orders'/)
|
||||||
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
|
assert.match(source, /ApiUnifiedOrderMainStatus[\s\S]*?'WAIT_PALLETIZE'/)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ApiError, apiRequest } from '@/api/http'
|
import { apiRequest } from '@/api/http'
|
||||||
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
import type { ApiContainerMode, ApiDestinationType, ApiFirstLegStatus, ApiPickupMethod, ApiTaxMode, MerchantFirstLegOrderDetail, PageResult } from '@/modules/first-leg/api/firstLeg'
|
||||||
|
|
||||||
export type ApiUnifiedOrderMainStatus =
|
export type ApiUnifiedOrderMainStatus =
|
||||||
@@ -60,11 +60,12 @@ export interface MerchantUnifiedTransportSummary {
|
|||||||
|
|
||||||
export interface MerchantUnifiedOrderRow {
|
export interface MerchantUnifiedOrderRow {
|
||||||
orderId: number | string
|
orderId: number | string
|
||||||
|
orderVersion: number
|
||||||
tenantId: number | string
|
tenantId: number | string
|
||||||
orderNo: string | null
|
orderNo: string | null
|
||||||
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
fulfillmentType?: 'STANDARD' | 'ONE_CLICK_DROPSHIP' | null
|
||||||
lxCode?: string | null
|
lxCode?: string | null
|
||||||
mainStatus: ApiUnifiedOrderMainStatus
|
mainStatus: ApiUnifiedOrderMainStatus | 'DRAFT' | 'CANCELLED'
|
||||||
nextAction: string | null
|
nextAction: string | null
|
||||||
customerFeeConfirmationRequired: boolean
|
customerFeeConfirmationRequired: boolean
|
||||||
internalOrderStatus: ApiFirstLegStatus | null
|
internalOrderStatus: ApiFirstLegStatus | null
|
||||||
@@ -132,7 +133,25 @@ export interface MerchantUnifiedCustomNode {
|
|||||||
attachmentIds: Array<number | string>
|
attachmentIds: Array<number | string>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MerchantTransportNode {
|
||||||
|
standardNode: string
|
||||||
|
nodeSequence: number
|
||||||
|
providerCode: string | null
|
||||||
|
estimatedAt: string | null
|
||||||
|
actualAt: string | null
|
||||||
|
locationCode: string | null
|
||||||
|
locationName: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantTransportFragment {
|
||||||
|
inboundCode: string | null
|
||||||
|
cabinetNo: string | null
|
||||||
|
containerNo: string | null
|
||||||
|
nodes: MerchantTransportNode[]
|
||||||
|
}
|
||||||
|
|
||||||
export interface MerchantUnifiedOrderDetail {
|
export interface MerchantUnifiedOrderDetail {
|
||||||
|
transportFragments: MerchantTransportFragment[]
|
||||||
summary: MerchantUnifiedOrderRow
|
summary: MerchantUnifiedOrderRow
|
||||||
order: MerchantFirstLegOrderDetail
|
order: MerchantFirstLegOrderDetail
|
||||||
timeline: MerchantUnifiedTimelineEvent[]
|
timeline: MerchantUnifiedTimelineEvent[]
|
||||||
@@ -141,6 +160,8 @@ export interface MerchantUnifiedOrderDetail {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface MerchantUnifiedOrderQuery {
|
export interface MerchantUnifiedOrderQuery {
|
||||||
|
taxMode?: ApiTaxMode
|
||||||
|
loaded?: boolean
|
||||||
keyword?: string
|
keyword?: string
|
||||||
fbaCode?: string
|
fbaCode?: string
|
||||||
orderNo?: string
|
orderNo?: string
|
||||||
@@ -156,6 +177,37 @@ export interface MerchantUnifiedOrderQuery {
|
|||||||
|
|
||||||
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
const unifiedOrderBaseUrl = '/merchant/v1/orders'
|
||||||
|
|
||||||
|
export type OrderQueue = 'all' | 'fee' | 'customs' | 'draft' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
|
||||||
|
export type OrderProgressStage = 'none' | 'loaded' | 'declared' | 'cleared' | 'scheduled' | 'delivering' | 'delivered'
|
||||||
|
export interface MerchantOrderProgress { orderId: string | number; stage: OrderProgressStage; partial: boolean }
|
||||||
|
export type OrderQueueCounts = Record<OrderQueue, number>
|
||||||
|
|
||||||
|
export interface MerchantOrderWorkbenchQuery {
|
||||||
|
cargoKeyword?: string
|
||||||
|
receivingWarehouseId?: string
|
||||||
|
channelName?: string
|
||||||
|
destinationType?: string
|
||||||
|
trackingNumber?: string
|
||||||
|
mainStatus?: string
|
||||||
|
createdFrom?: string
|
||||||
|
createdTo?: string
|
||||||
|
queue?: OrderQueue
|
||||||
|
page?: number
|
||||||
|
size?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MerchantOrderWorkbench {
|
||||||
|
page: PageResult<MerchantUnifiedOrderRow>
|
||||||
|
queues: OrderQueueCounts
|
||||||
|
progress: MerchantOrderProgress[]
|
||||||
|
channelNames: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMerchantOrderWorkbench(params: MerchantOrderWorkbenchQuery = {}) {
|
||||||
|
return apiRequest<MerchantOrderWorkbench>({ method: 'GET', url: `${unifiedOrderBaseUrl}/workbench`,
|
||||||
|
params: { ...params, page: params.page ?? 1, size: params.size ?? 10 } })
|
||||||
|
}
|
||||||
|
|
||||||
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
export function getMerchantUnifiedOrders(params: MerchantUnifiedOrderQuery = {}) {
|
||||||
const { page, size, ...filters } = params
|
const { page, size, ...filters } = params
|
||||||
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
return apiRequest<PageResult<MerchantUnifiedOrderRow>>({
|
||||||
@@ -171,7 +223,3 @@ export function getMerchantUnifiedOrder(orderId: number | string) {
|
|||||||
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
url: `${unifiedOrderBaseUrl}/${orderId}`,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isUnifiedOrderQueryUnavailable(error: unknown) {
|
|
||||||
return error instanceof ApiError && (error.status === 404 || error.code === 'A0404')
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
|
||||||
|
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no }); return { promise, resolve, reject } }
|
||||||
|
function harness(t) {
|
||||||
|
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||||
|
const code = ts.transpileModule(source + '\nexport { loadDetail, detail, clearanceResults, loading, errorMessage, selectedInboundIds, clearanceError, clearanceLoading, retryClearanceResults, close }', { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const props = vue.reactive({ modelValue: false, orderId: 'A', canEdit: true }), requests = [], clearances = [], updates = [], view = {}
|
||||||
|
const unmounts = []
|
||||||
|
const dependencies = { '../store/customsPending': { useCustomsPendingStore: () => ({ refresh: async () => {} }) }, vue: { ...vue, onBeforeUnmount: fn => unmounts.push(fn) }, 'element-plus': { ElMessage: {} }, '@/modules/first-leg/api/customs': {
|
||||||
|
getMerchantCustomsForOrder: id => { const pending = deferred(); requests.push({ id, ...pending }); return pending.promise },
|
||||||
|
getMerchantClearanceResults: id => { const pending = deferred(); clearances.push({ id, ...pending }); return pending.promise },
|
||||||
|
merchantCustomsErrorMessage: error => error.message,
|
||||||
|
} }
|
||||||
|
const scope = vue.effectScope()
|
||||||
|
scope.run(() => new Function('require', 'exports', 'defineProps', 'defineEmits', code)(id => {
|
||||||
|
assert.ok(id in dependencies, id); return dependencies[id]
|
||||||
|
}, view, () => props, () => (...args) => updates.push(args)))
|
||||||
|
t.after(() => scope.stop())
|
||||||
|
return { props, requests, clearances, updates, view, unmount: () => unmounts.forEach(fn => fn()) }
|
||||||
|
}
|
||||||
|
const detail = id => ({ loadingPlanId: id, inbounds: [{ orderId: id, inboundId: `IN-${id}`, taxMode: 'TAX_REFUND' }] })
|
||||||
|
const tick = async () => { await Promise.resolve(); await vue.nextTick(); await Promise.resolve() }
|
||||||
|
|
||||||
|
test('result section stays pending while the refreshed detail is still loading', async t => {
|
||||||
|
const h = harness(t)
|
||||||
|
h.props.initialDetail = detail('A')
|
||||||
|
h.props.modelValue = true
|
||||||
|
await tick()
|
||||||
|
assert.equal(h.view.detail.value.loadingPlanId, 'A')
|
||||||
|
assert.equal(h.view.loading.value, true)
|
||||||
|
assert.equal(h.view.clearanceLoading.value, false)
|
||||||
|
assert.equal(h.clearances.length, 0)
|
||||||
|
const template = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||||
|
assert.match(template, /v-else-if="loading \|\| clearanceLoading"/)
|
||||||
|
h.requests[0].resolve(detail('A')); await tick()
|
||||||
|
assert.equal(h.view.clearanceLoading.value, true)
|
||||||
|
h.clearances[0].resolve([]); await tick()
|
||||||
|
assert.equal(h.view.loading.value, false)
|
||||||
|
assert.equal(h.view.clearanceLoading.value, false)
|
||||||
|
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('switching orders while open starts the new request and ignores stale detail', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.props.orderId = 'B'; await tick()
|
||||||
|
assert.deepEqual(h.requests.map(r => r.id), ['A', 'B'])
|
||||||
|
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||||
|
h.requests[0].resolve(detail('A')); await tick()
|
||||||
|
assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||||
|
assert.deepEqual(h.view.selectedInboundIds.value, ['IN-B'])
|
||||||
|
assert.deepEqual(h.clearances.map(r => r.id), ['B'])
|
||||||
|
assert.equal(h.updates.length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('closing before detail response prevents stale data and events', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.props.modelValue = false; await tick()
|
||||||
|
h.requests[0].resolve(detail('A')); await tick()
|
||||||
|
assert.equal(h.view.detail.value, null); assert.equal(h.view.loading.value, false)
|
||||||
|
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('closing and reopening ignores the previous clearance response', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.requests[0].resolve(detail('A')); await tick()
|
||||||
|
h.props.modelValue = false; await tick(); h.props.orderId = 'B'; h.props.modelValue = true; await tick()
|
||||||
|
h.requests[1].resolve(detail('B')); await tick()
|
||||||
|
h.clearances[1].resolve([{ kind: 'B' }]); await tick()
|
||||||
|
h.clearances[0].resolve([{ kind: 'A' }]); await tick()
|
||||||
|
assert.deepEqual(h.view.clearanceResults.value, [{ kind: 'B' }])
|
||||||
|
assert.equal(h.view.detail.value.loadingPlanId, 'B'); assert.equal(h.updates.length, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('stale detail failure cannot clear the next request loading or show an error', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.props.orderId = 'B'; await tick(); h.requests[0].reject(new Error('old failure')); await tick()
|
||||||
|
assert.equal(h.view.loading.value, true); assert.equal(h.view.errorMessage.value, '')
|
||||||
|
h.requests[1].resolve(detail('B')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||||
|
assert.equal(h.view.loading.value, false); assert.equal(h.view.detail.value.loadingPlanId, 'B')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('unmount invalidates pending detail requests', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick(); h.unmount()
|
||||||
|
h.requests[0].resolve(detail('A')); await tick()
|
||||||
|
assert.equal(h.clearances.length, 0); assert.equal(h.updates.length, 0); assert.equal(h.view.detail.value, null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('result failure retains documents and exposes error; retry queries only results and deduplicates clicks', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.requests[0].resolve({ ...detail('A'), documents: [{ documentId: 'document-A' }] }); await tick()
|
||||||
|
h.clearances[0].reject(new Error('结果服务暂不可用')); await tick()
|
||||||
|
assert.equal(h.view.errorMessage.value, '')
|
||||||
|
assert.equal(h.view.clearanceError.value, '结果服务暂不可用')
|
||||||
|
assert.equal(h.view.detail.value.documents[0].documentId, 'document-A')
|
||||||
|
assert.equal(h.view.loading.value, false)
|
||||||
|
const retry = h.view.retryClearanceResults()
|
||||||
|
await h.view.retryClearanceResults()
|
||||||
|
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 2)
|
||||||
|
assert.equal(h.view.clearanceLoading.value, true)
|
||||||
|
h.clearances[1].resolve([{ id: 'result-A' }]); await retry
|
||||||
|
assert.equal(h.view.clearanceError.value, '')
|
||||||
|
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'result-A' }])
|
||||||
|
assert.equal(h.view.clearanceLoading.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('normal open requests detail and results exactly once and distinguishes successful empty results', async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].resolve([]); await tick()
|
||||||
|
assert.equal(h.requests.length, 1); assert.equal(h.clearances.length, 1)
|
||||||
|
assert.equal(h.view.clearanceError.value, '')
|
||||||
|
assert.equal(h.view.clearanceLoading.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
for (const transition of ['switch', 'close', 'unmount']) {
|
||||||
|
for (const outcome of ['resolve', 'reject']) {
|
||||||
|
test(`${transition} ignores stale result retry ${outcome}`, async t => {
|
||||||
|
const h = harness(t); h.props.modelValue = true; await tick()
|
||||||
|
h.requests[0].resolve(detail('A')); await tick(); h.clearances[0].reject(new Error('first failure')); await tick()
|
||||||
|
const retry = h.view.retryClearanceResults()
|
||||||
|
if (transition === 'switch') { h.props.orderId = 'B'; await tick() }
|
||||||
|
else if (transition === 'close') { h.view.close(); h.props.modelValue = false; await tick() }
|
||||||
|
else h.unmount()
|
||||||
|
if (outcome === 'resolve') h.clearances[1].resolve([{ id: 'old-A' }])
|
||||||
|
else h.clearances[1].reject(new Error('old retry failure'))
|
||||||
|
await retry
|
||||||
|
assert.equal(h.view.clearanceError.value, '')
|
||||||
|
assert.deepEqual(h.view.clearanceResults.value, [])
|
||||||
|
if (transition === 'switch') {
|
||||||
|
h.requests[1].resolve(detail('B')); await tick(); h.clearances[2].resolve([{ id: 'B' }]); await tick()
|
||||||
|
assert.deepEqual(h.view.clearanceResults.value, [{ id: 'B' }])
|
||||||
|
} else {
|
||||||
|
await h.view.retryClearanceResults()
|
||||||
|
assert.equal(h.clearances.length, 2)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
test('result error and retry reuse existing section error styling before the empty state', () => {
|
||||||
|
const source = readFileSync(new URL('./CustomsDocumentsDialog.vue', import.meta.url), 'utf8')
|
||||||
|
assert.match(source, /v-if="clearanceError" class="customs-error" role="alert"/)
|
||||||
|
assert.match(source, /@click="retryClearanceResults"/)
|
||||||
|
assert.match(source, /v-else-if="loading \|\| clearanceLoading"/)
|
||||||
|
assert.match(source, /v-else-if="!clearanceResults.length"/)
|
||||||
|
})
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, ref, watch } from 'vue'
|
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
|
||||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue'
|
import { Download, FileText, LockKeyhole, Pencil, Trash2, Upload } from '@lucide/vue'
|
||||||
import {
|
import {
|
||||||
@@ -22,6 +22,9 @@ import {
|
|||||||
type MerchantClearanceResult,
|
type MerchantClearanceResult,
|
||||||
} from '@/modules/first-leg/api/customs'
|
} from '@/modules/first-leg/api/customs'
|
||||||
|
|
||||||
|
import { useCustomsPendingStore } from '../store/customsPending'
|
||||||
|
|
||||||
|
const customsPending = useCustomsPendingStore()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
modelValue: boolean
|
modelValue: boolean
|
||||||
orderId: string
|
orderId: string
|
||||||
@@ -46,6 +49,12 @@ const replaceInput = ref<HTMLInputElement>()
|
|||||||
const mutating = ref(false)
|
const mutating = ref(false)
|
||||||
const downloadingKey = ref('')
|
const downloadingKey = ref('')
|
||||||
const clearanceResults = ref<MerchantClearanceResult[]>([])
|
const clearanceResults = ref<MerchantClearanceResult[]>([])
|
||||||
|
const clearanceError = ref('')
|
||||||
|
const clearanceLoading = ref(false)
|
||||||
|
let clearanceRequest = 0
|
||||||
|
let disposed = false
|
||||||
|
let detailRequest = 0
|
||||||
|
onBeforeUnmount(() => { disposed = true; detailRequest += 1; resetClearanceResults() })
|
||||||
|
|
||||||
const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? [])
|
const taxRefundInbounds = computed(() => detail.value?.inbounds.filter((item) => item.taxMode === 'TAX_REFUND') ?? [])
|
||||||
const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED')
|
const locked = computed(() => Boolean(detail.value?.startedAt) || detail.value?.status === 'DECLARING' || detail.value?.status === 'COMPLETED')
|
||||||
@@ -66,32 +75,81 @@ function initializeSelection(value: MerchantCustomsContainer) {
|
|||||||
selectedInboundIds.value = currentOrderIds
|
selectedInboundIds.value = currentOrderIds
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadDetail() {
|
function resetClearanceResults() {
|
||||||
if (!props.orderId) return
|
clearanceRequest += 1
|
||||||
loading.value = true
|
clearanceResults.value = []
|
||||||
errorMessage.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 {
|
try {
|
||||||
const result = await getMerchantCustomsForOrder(props.orderId)
|
const results = await getMerchantClearanceResults(orderId)
|
||||||
detail.value = result
|
if (isCurrent()) clearanceResults.value = results
|
||||||
initializeSelection(result)
|
|
||||||
try { clearanceResults.value = await getMerchantClearanceResults(props.orderId) } catch { clearanceResults.value = [] }
|
|
||||||
emit('updated', result)
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
detail.value = null
|
if (isCurrent()) clearanceError.value = merchantCustomsErrorMessage(error, '海关申报结果加载失败')
|
||||||
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
if (isCurrent()) clearanceLoading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(() => props.modelValue, (open) => {
|
async function retryClearanceResults() {
|
||||||
|
if (loading.value) return
|
||||||
|
await loadClearanceResults()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDetail() {
|
||||||
|
if (disposed || !props.modelValue || !props.orderId) return
|
||||||
|
void customsPending.refresh(true)
|
||||||
|
const request = ++detailRequest
|
||||||
|
resetClearanceResults()
|
||||||
|
const orderId = props.orderId
|
||||||
|
const isCurrent = () => request === detailRequest && props.modelValue && props.orderId === orderId
|
||||||
|
loading.value = true
|
||||||
|
errorMessage.value = ''
|
||||||
|
try {
|
||||||
|
const result = await getMerchantCustomsForOrder(orderId)
|
||||||
|
if (!isCurrent()) return
|
||||||
|
detail.value = result
|
||||||
|
initializeSelection(result)
|
||||||
|
await loadClearanceResults()
|
||||||
|
if (!isCurrent()) return
|
||||||
|
emit('updated', result)
|
||||||
|
} catch (error) {
|
||||||
|
if (!isCurrent()) return
|
||||||
|
detail.value = null
|
||||||
|
errorMessage.value = merchantCustomsErrorMessage(error, '退税报关资料加载失败')
|
||||||
|
} finally {
|
||||||
|
if (isCurrent()) loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => [props.modelValue, props.orderId] as const, ([open]) => {
|
||||||
|
detailRequest += 1
|
||||||
|
detail.value = null
|
||||||
|
resetClearanceResults()
|
||||||
|
selectedInboundIds.value = []
|
||||||
|
editingDocument.value = null
|
||||||
|
replacingDocument.value = null
|
||||||
|
errorMessage.value = ''
|
||||||
|
loading.value = false
|
||||||
if (!open) return
|
if (!open) return
|
||||||
detail.value = props.initialDetail ?? null
|
const initial = props.initialDetail
|
||||||
|
detail.value = initial?.inbounds.some((item) => item.orderId === props.orderId) ? initial : null
|
||||||
if (detail.value) initializeSelection(detail.value)
|
if (detail.value) initializeSelection(detail.value)
|
||||||
void loadDetail()
|
void loadDetail()
|
||||||
})
|
}, { immediate: true })
|
||||||
|
|
||||||
function close() {
|
function close() {
|
||||||
|
detailRequest += 1
|
||||||
|
resetClearanceResults()
|
||||||
emit('update:modelValue', false)
|
emit('update:modelValue', false)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,7 +384,13 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
|||||||
<div class="customs-section-title">
|
<div class="customs-section-title">
|
||||||
<div><h3>海关申报结果</h3><p>平台完成正式申报后,客户可查看与本订单相关的查验、补充资料和放行结果。</p></div>
|
<div><h3>海关申报结果</h3><p>平台完成正式申报后,客户可查看与本订单相关的查验、补充资料和放行结果。</p></div>
|
||||||
</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-else class="clearance-result-list">
|
||||||
<div v-for="item in clearanceResults" :key="item.id" class="clearance-result-row">
|
<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>
|
<div><strong>{{ clearanceResultLabel(item) }}</strong><span>{{ formatDateTime(item.occurredAt) }} · 报关单号 {{ item.customsEntryNo || '—' }}</span></div>
|
||||||
@@ -383,6 +447,9 @@ function clearanceResultStatusLabel(value: MerchantClearanceResult) {
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
:global(.customs-documents-dialog.el-dialog) { display: flex; max-height: 70vh; flex-direction: column; overflow: hidden; }
|
||||||
|
:global(.customs-documents-dialog .el-dialog__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 { display: grid; gap: 10px; justify-items: start; padding: 22px; border: 1px solid #f1b8b8; background: #fff7f7; color: #9f2d2d; }
|
||||||
.customs-error span { overflow-wrap: anywhere; font-size: 12px; }
|
.customs-error span { overflow-wrap: anywhere; font-size: 12px; }
|
||||||
.customs-summary { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)) auto; align-items: center; gap: 18px; padding: 16px 18px; border: 1px solid var(--border); background: #f8faf9; }
|
.customs-summary { display: grid; grid-template-columns: 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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ol class="progress-stages" aria-label="订单主状态阶段">
|
<p v-if="order.status === 'CANCELLED'" class="draft-progress-note">订单已取消,不再继续履约。</p>
|
||||||
|
<ol v-else class="progress-stages" aria-label="订单主状态阶段">
|
||||||
<li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined">
|
<li v-for="(stage, index) in FIRST_LEG_PROGRESS_STAGES" :key="stage.code" :class="stageState(index)" :aria-current="index === currentIndex ? 'step' : undefined">
|
||||||
<span class="stage-marker" aria-hidden="true"><Check v-if="index < currentIndex" :size="13" /><CircleDot v-else :size="13" /></span>
|
<span class="stage-marker" aria-hidden="true"><Check v-if="index < currentIndex" :size="13" /><CircleDot v-else :size="13" /></span>
|
||||||
<span class="stage-label">{{ stage.label }}</span>
|
<span class="stage-label">{{ stage.label }}</span>
|
||||||
</li>
|
</li>
|
||||||
</ol>
|
</ol>
|
||||||
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">订单提交后开始记录主状态进度。</p>
|
<p v-if="order.status === 'DRAFT'" class="draft-progress-note">订单提交后开始记录主状态进度。</p>
|
||||||
<div class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
<div v-if="order.status !== 'CANCELLED'" class="progress-cabinet-detail"><slot name="cabinet" /></div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||||
|
import { customerTransportRows } from '../utils/transportFacts'
|
||||||
|
|
||||||
|
const props = defineProps<{ fragments: MerchantTransportFragment[] }>()
|
||||||
|
const rows = computed(() => customerTransportRows(props.fragments))
|
||||||
|
function time(value: string | null) { return value ? value.replace('T', ' ') : '—' }
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="transport-facts" aria-label="实际装载片段运输节点">
|
||||||
|
<strong>运输节点</strong>
|
||||||
|
<el-table v-if="rows.length" :data="rows" row-key="key" border size="small">
|
||||||
|
<el-table-column prop="inboundCode" label="入仓码" min-width="155" />
|
||||||
|
<el-table-column prop="cabinetNo" label="柜次" width="90" />
|
||||||
|
<el-table-column prop="containerNo" label="集装箱号" min-width="145" />
|
||||||
|
<el-table-column prop="nodeLabel" label="节点" min-width="150" />
|
||||||
|
<el-table-column label="实际时间" min-width="175"><template #default="{ row }">{{ time(row.actualAt) }}</template></el-table-column>
|
||||||
|
<el-table-column label="预计时间" min-width="175"><template #default="{ row }">{{ time(row.estimatedAt) }}</template></el-table-column>
|
||||||
|
<el-table-column prop="location" label="地点" min-width="130" />
|
||||||
|
<el-table-column prop="source" label="来源" width="105" />
|
||||||
|
</el-table>
|
||||||
|
<p v-else>暂无实际装载片段的运输节点。预计时间不表示实际发生。</p>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.transport-facts { margin-top: 9px; }
|
||||||
|
.transport-facts > strong { display: block; padding: 7px 0 5px; color: var(--navy); font-size: 11px; }
|
||||||
|
.transport-facts > p { color: var(--muted); font-size: 11px; }
|
||||||
|
</style>
|
||||||
@@ -5,3 +5,4 @@ export { getMerchantWarehouses, type MerchantWarehouse } from './api/firstLeg'
|
|||||||
export { getFirstLegStatusLabel, getFirstLegStatusTone } from './utils/firstLegOrder'
|
export { getFirstLegStatusLabel, getFirstLegStatusTone } from './utils/firstLegOrder'
|
||||||
export { default as InboundCodeAssociationDialog } from './components/InboundCodeAssociationDialog.vue'
|
export { default as InboundCodeAssociationDialog } from './components/InboundCodeAssociationDialog.vue'
|
||||||
export { default as FirstLegOrdersView } from './views/FirstLegOrdersView.vue'
|
export { default as FirstLegOrdersView } from './views/FirstLegOrdersView.vue'
|
||||||
|
export { useCustomsPendingStore } from './store/customsPending'
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
import * as pinia from 'pinia'
|
||||||
|
const source = readFileSync(new URL('./customsPending.ts', import.meta.url), 'utf8')
|
||||||
|
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
function deferred() { let resolve, reject; const promise = new Promise((a,b) => { resolve=a; reject=b }); return { promise, resolve, reject } }
|
||||||
|
function harness(t, read) {
|
||||||
|
const context=pinia.createPinia();pinia.setActivePinia(context);t.after(()=>pinia.disposePinia(context))
|
||||||
|
const deps={vue,pinia,'../api/customs':{getMerchantCustomsPendingCount:read}}, exports={}
|
||||||
|
new Function('require','exports',code)(id=>{assert.ok(id in deps,id);return deps[id]},exports)
|
||||||
|
return exports.useCustomsPendingStore()
|
||||||
|
}
|
||||||
|
test('does not request without a permitted identity; preserves counts while refreshing and accepts zero',async t=>{
|
||||||
|
const pending=deferred();let calls=0
|
||||||
|
const store=harness(t,()=>++calls===1?Promise.resolve(2):pending.promise)
|
||||||
|
await store.refresh();assert.equal(calls,0)
|
||||||
|
store.setScope('customer-a');await store.refresh();assert.equal(store.count,2)
|
||||||
|
const load=store.refresh();await store.refresh();assert.equal(calls,2);assert.equal(store.count,2)
|
||||||
|
pending.resolve(0);await load;assert.equal(store.count,0);assert.equal(store.loading,false)
|
||||||
|
})
|
||||||
|
test('logout, permission removal and account switches discard old in-flight responses',async t=>{
|
||||||
|
const pending=deferred();const store=harness(t,()=>pending.promise)
|
||||||
|
store.setScope('a');const load=store.refresh();store.setScope('')
|
||||||
|
pending.resolve(9);await load;assert.equal(store.count,null);assert.equal(store.error,'')
|
||||||
|
store.setScope('b');assert.equal(store.count,null)
|
||||||
|
})
|
||||||
|
test('successful mutation can force a newer refresh without being overwritten by an older query',async t=>{
|
||||||
|
const a=deferred(),b=deferred();let calls=0;const store=harness(t,()=>++calls===1?a.promise:b.promise)
|
||||||
|
store.setScope('a');const first=store.refresh();const second=store.refresh(true)
|
||||||
|
b.resolve(1);await second;a.resolve(2);await first;assert.equal(store.count,1)
|
||||||
|
})
|
||||||
|
test('failure is distinguishable from zero and retry restores authoritative count',async t=>{
|
||||||
|
let fail=true;const store=harness(t,()=>fail?Promise.reject(new Error('offline')):Promise.resolve(3))
|
||||||
|
store.setScope('a');await store.refresh();assert.equal(store.count,null);assert.notEqual(store.error,'')
|
||||||
|
fail=false;await store.refresh();assert.equal(store.count,3);assert.equal(store.error,'')
|
||||||
|
})
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { ref } from 'vue'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { getMerchantCustomsPendingCount } from '../api/customs'
|
||||||
|
|
||||||
|
export const useCustomsPendingStore = defineStore('client-customs-pending', () => {
|
||||||
|
const count = ref<number | null>(null)
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
let scope = ''
|
||||||
|
let requestVersion = 0
|
||||||
|
|
||||||
|
function setScope(value: string) {
|
||||||
|
if (scope === value) return
|
||||||
|
scope = value
|
||||||
|
requestVersion++
|
||||||
|
count.value = null
|
||||||
|
error.value = ''
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh(force = false) {
|
||||||
|
if (!scope || (loading.value && !force)) return
|
||||||
|
const request = ++requestVersion
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const result = await getMerchantCustomsPendingCount()
|
||||||
|
if (request !== requestVersion) return
|
||||||
|
count.value = result
|
||||||
|
error.value = ''
|
||||||
|
} catch {
|
||||||
|
if (request !== requestVersion) return
|
||||||
|
count.value = null
|
||||||
|
error.value = '报关待办数量加载失败,请进入报关资料刷新'
|
||||||
|
} finally {
|
||||||
|
if (request === requestVersion) loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { count, loading, error, setScope, refresh }
|
||||||
|
})
|
||||||
@@ -0,0 +1,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, '')
|
assert.equal(map({ transport: null }).estimatedPortArrivalAt, '')
|
||||||
})
|
})
|
||||||
|
|
||||||
test('maps the first-leg aggregate list fields without loading detail rows', () => {
|
test('maps the current workbench row without loading detail rows', () => {
|
||||||
assert.match(apiSource, /interface MerchantFirstLegOrderRow/)
|
assert.match(storeSource, /result\.page\.records\.map\(item => mapUnifiedOrderRow\(item, warehouses\.value\)\)/)
|
||||||
assert.match(apiSource, /skuNos: string \| string\[\] \| null/)
|
assert.match(storeSource, /version: summary\.orderVersion/)
|
||||||
assert.match(apiSource, /cargoes\?: Array<\{ skuNo\?: string \| null \}>/)
|
assert.doesNotMatch(storeSource, /function mapFirstLegOrderRow/)
|
||||||
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('declares the documented merchant warehouse and first-leg endpoints', () => {
|
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'/)
|
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, /orders\.value = \[\]/)
|
||||||
assert.match(storeSource, /warehouses\.value = \[\]/)
|
assert.doesNotMatch(storeSource, /isUnifiedOrderQueryUnavailable|getOrdersForClient|getMerchantFirstLegOrders|initialOrders/)
|
||||||
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/)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('declares the final C02 row and detail contract in the API adapter', () => {
|
test('declares the final C02 row and detail contract in the API adapter', () => {
|
||||||
@@ -115,7 +99,6 @@ test('declares the final C02 row and detail contract in the API adapter', () =>
|
|||||||
assert.match(unifiedApiSource, /order: MerchantFirstLegOrderDetail/)
|
assert.match(unifiedApiSource, /order: MerchantFirstLegOrderDetail/)
|
||||||
assert.match(unifiedApiSource, /timeline: MerchantUnifiedTimelineEvent\[\]/)
|
assert.match(unifiedApiSource, /timeline: MerchantUnifiedTimelineEvent\[\]/)
|
||||||
assert.match(unifiedApiSource, /customNodes\?: MerchantUnifiedCustomNode\[\]/)
|
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', () => {
|
test('keeps unified order pagination valid when the store omits page and size', () => {
|
||||||
@@ -123,21 +106,10 @@ test('keeps unified order pagination valid when the store omits page and size',
|
|||||||
assert.match(unifiedApiSource, /params: \{ page: page \?\? 1, size: size \?\? 200, \.\.\.filters \}/)
|
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', () => {
|
test('draft editing reads the order aggregate while navigation uses unified detail', () => {
|
||||||
assert.match(storeSource, /getMerchantFirstLegOrders\(legacyQuery\(query, 'DRAFT'\)\)/)
|
assert.match(storeSource, /return loadOrderAggregate\(id\)/)
|
||||||
assert.match(storeSource, /const listOrder = getById\(id\)/)
|
assert.match(storeSource, /const detail = await getMerchantUnifiedOrder\(id\)/)
|
||||||
assert.match(storeSource, /listOrder\?\.status === 'DRAFT' \? loadLegacyDetail\(id, listOrder\) : loadUnifiedDetail\(id\)/)
|
assert.doesNotMatch(storeSource, /loadLegacyDetail|draftOnly|includeDrafts/)
|
||||||
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('maps C02 authoritative status, transport, cargo and pickup snapshots', () => {
|
test('maps C02 authoritative status, transport, cargo and pickup snapshots', () => {
|
||||||
@@ -195,7 +167,7 @@ test('separates domestic receiving warehouses from public destinations', () => {
|
|||||||
assert.match(apiSource, /warehouseType\?: MerchantWarehouseType/)
|
assert.match(apiSource, /warehouseType\?: MerchantWarehouseType/)
|
||||||
assert.match(apiSource, /params: \{ page: 1, size: 200, status: 'ACTIVE', \.\.\.params \}/)
|
assert.match(apiSource, /params: \{ page: 1, size: 200, status: 'ACTIVE', \.\.\.params \}/)
|
||||||
assert.match(storeSource, /loadAllWarehouseRecords\(warehouseType, getMerchantWarehouses\)/)
|
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, /warehouse\.warehouseType !== 'DOMESTIC'/)
|
||||||
assert.match(storeSource, /item\.warehouseType === draft\.destinationType/)
|
assert.match(storeSource, /item\.warehouseType === draft\.destinationType/)
|
||||||
assert.match(storeSource, /draft\.amazonWarehouseCode = draft\.destinationType === 'FBA' \? destinationWarehouse\.code : ''/)
|
assert.match(storeSource, /draft\.amazonWarehouseCode = draft\.destinationType === 'FBA' \? destinationWarehouse\.code : ''/)
|
||||||
@@ -206,20 +178,20 @@ test('only blocks submission when a known company audit status is not active', (
|
|||||||
assert.match(storeSource, /if \(companyAuditStatus && companyAuditStatus !== 'ACTIVE'\)/)
|
assert.match(storeSource, /if \(companyAuditStatus && companyAuditStatus !== 'ACTIVE'\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('does not expose the out-of-scope cancellation write', () => {
|
test('uses the versioned merchant cancellation contract', () => {
|
||||||
assert.doesNotMatch(storeSource, /cancelMerchant|function cancel|\/cancel/)
|
assert.match(storeSource, /cancelMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||||
assert.doesNotMatch(apiSource, /\/cancel/)
|
assert.match(apiSource, /cancelMerchantFirstLegOrder\(id: number \| string, payload: \{ expectedVersion: number; reason: string \}, idempotencyKey: string\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('sends an idempotency key for create and submit writes', () => {
|
test('sends an idempotency key for create and submit writes', () => {
|
||||||
assert.match(apiSource, /'Idempotency-Key': createIdempotencyKey\('first-leg-create'\)/)
|
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, /'Idempotency-Key': idempotencyKey/)
|
||||||
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
|
assert.match(apiSource, /createMerchantFirstLegOrderBatch\(items: MerchantBatchDraftItem\[\], idempotencyKey: string\)/)
|
||||||
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
assert.match(apiSource, /headers: \{ 'Idempotency-Key': idempotencyKey \}/)
|
||||||
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
|
assert.match(storeSource, /createMerchantFirstLegOrderBatch\(items, idempotencyKey\)/)
|
||||||
assert.match(storeSource, /pendingSubmitKeys\.get\(id\) \?\? createIdempotencyKey\(`first-leg-submit-\$\{id\}`\)/)
|
assert.match(storeSource, /pendingSubmissions\.get\(id\)/)
|
||||||
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, idempotencyKey\)/)
|
assert.match(storeSource, /submitMerchantFirstLegOrder\(id, pending\.payload, pending\.key\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('does not expose the contradictory backend rejected state in the client model', () => {
|
test('does not expose the contradictory backend rejected state in the client model', () => {
|
||||||
@@ -264,5 +236,5 @@ test('keeps failed order loads distinct from empty results', () => {
|
|||||||
assert.match(storeSource, /const loadError = ref\(''\)/)
|
assert.match(storeSource, /const loadError = ref\(''\)/)
|
||||||
assert.match(storeSource, /orderResult\.reason instanceof Error/)
|
assert.match(storeSource, /orderResult\.reason instanceof Error/)
|
||||||
assert.match(storeSource, /warehouseLoadError/)
|
assert.match(storeSource, /warehouseLoadError/)
|
||||||
assert.match(storeSource, /return \{ orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError/)
|
assert.match(storeSource, /return \{ orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError/)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,29 +1,29 @@
|
|||||||
import { computed, ref } from 'vue'
|
import { ref } from 'vue'
|
||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import {
|
import {
|
||||||
createMerchantFirstLegOrderBatch,
|
createMerchantFirstLegOrderBatch,
|
||||||
createMerchantFirstLegOrder,
|
createMerchantFirstLegOrder,
|
||||||
createIdempotencyKey,
|
createIdempotencyKey,
|
||||||
getMerchantFirstLegOrder,
|
getMerchantFirstLegOrder,
|
||||||
getMerchantFirstLegOrders,
|
|
||||||
getMerchantWarehouseDetail,
|
getMerchantWarehouseDetail,
|
||||||
getMerchantWarehouses,
|
getMerchantWarehouses,
|
||||||
submitMerchantFirstLegOrder,
|
submitMerchantFirstLegOrder,
|
||||||
updateMerchantFirstLegOrder,
|
updateMerchantFirstLegOrder,
|
||||||
|
cancelMerchantFirstLegOrder,
|
||||||
type ApiFirstLegStatus,
|
type ApiFirstLegStatus,
|
||||||
type FirstLegOrderSaveRequest,
|
type FirstLegOrderSaveRequest,
|
||||||
type MerchantFirstLegOrder,
|
type MerchantFirstLegOrder,
|
||||||
type MerchantFirstLegOrderRow,
|
|
||||||
type MerchantFirstLegOrderDetail,
|
type MerchantFirstLegOrderDetail,
|
||||||
type MerchantBatchDraftResponse,
|
type MerchantBatchDraftResponse,
|
||||||
type MerchantWarehouse,
|
type MerchantWarehouse,
|
||||||
} from '@/modules/first-leg/api/firstLeg'
|
} from '@/modules/first-leg/api/firstLeg'
|
||||||
import {
|
import {
|
||||||
getMerchantUnifiedOrder,
|
getMerchantUnifiedOrder,
|
||||||
getMerchantUnifiedOrders,
|
getMerchantOrderWorkbench,
|
||||||
isUnifiedOrderQueryUnavailable,
|
|
||||||
type MerchantUnifiedOrderDetail,
|
type MerchantUnifiedOrderDetail,
|
||||||
type MerchantUnifiedOrderQuery,
|
type MerchantOrderWorkbenchQuery,
|
||||||
|
type MerchantOrderProgress,
|
||||||
|
type OrderQueueCounts,
|
||||||
type MerchantUnifiedOrderRow,
|
type MerchantUnifiedOrderRow,
|
||||||
} from '@/modules/first-leg/api/unifiedOrders'
|
} from '@/modules/first-leg/api/unifiedOrders'
|
||||||
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
|
import type { MerchantTenantStatus } from '@/modules/tenant-management/public'
|
||||||
@@ -46,7 +46,7 @@ function clientStatus(status: ApiFirstLegStatus): FirstLegOrder['status'] {
|
|||||||
if (status === 'REJECTED') return 'PENDING_REVIEW'
|
if (status === 'REJECTED') return 'PENDING_REVIEW'
|
||||||
if (status === 'APPROVED' || status === 'ACCEPTED' || status === 'PROCESSING') return 'WAIT_MEASURE'
|
if (status === 'APPROVED' || status === 'ACCEPTED' || status === 'PROCESSING') return 'WAIT_MEASURE'
|
||||||
if (status === 'COMPLETED') return 'COMPLETED'
|
if (status === 'COMPLETED') return 'COMPLETED'
|
||||||
if (status === 'CANCELLED') return 'PENDING_REVIEW'
|
if (status === 'CANCELLED') return 'CANCELLED'
|
||||||
return 'PENDING_REVIEW'
|
return 'PENDING_REVIEW'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,8 +159,10 @@ function orderWarehouseSnapshot(order: MerchantFirstLegOrder, warehouse?: Platfo
|
|||||||
id: String(order.receivingWarehouseId),
|
id: String(order.receivingWarehouseId),
|
||||||
code: warehouse?.code ?? '',
|
code: warehouse?.code ?? '',
|
||||||
name: order.receivingWarehouseName,
|
name: order.receivingWarehouseName,
|
||||||
province: warehouse?.province ?? '',
|
// Order stores the complete formatted address, including province and city.
|
||||||
city: warehouse?.city ?? '',
|
// Do not prefix this snapshot with fields from the current warehouse master.
|
||||||
|
province: '',
|
||||||
|
city: '',
|
||||||
address: order.receivingWarehouseAddress,
|
address: order.receivingWarehouseAddress,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -198,6 +200,7 @@ function timeline(detail: MerchantFirstLegOrderDetail): FirstLegOrderTimelineIte
|
|||||||
|
|
||||||
function businessSummary(summary?: MerchantUnifiedOrderRow): FirstLegOrder['businessSummary'] {
|
function businessSummary(summary?: MerchantUnifiedOrderRow): FirstLegOrder['businessSummary'] {
|
||||||
return {
|
return {
|
||||||
|
transportFragments: [],
|
||||||
customerFeeConfirmationRequired: summary?.customerFeeConfirmationRequired ?? false,
|
customerFeeConfirmationRequired: summary?.customerFeeConfirmationRequired ?? false,
|
||||||
totalPackageCount: summary?.totalPackageCount ?? null,
|
totalPackageCount: summary?.totalPackageCount ?? null,
|
||||||
actualGrossWeightKg: summary?.actualGrossWeightKg ?? null,
|
actualGrossWeightKg: summary?.actualGrossWeightKg ?? null,
|
||||||
@@ -339,7 +342,7 @@ function mapUnifiedOrderRow(summary: MerchantUnifiedOrderRow, warehouses: Platfo
|
|||||||
trackingNumber: summary.expressTrackingNo ?? summary.delivery?.trackingNo ?? '', skuNos: summary.skuNos ?? [], totalNetWeightKg: summary.totalNetWeightKg ?? null,
|
trackingNumber: summary.expressTrackingNo ?? summary.delivery?.trackingNo ?? '', skuNos: summary.skuNos ?? [], totalNetWeightKg: summary.totalNetWeightKg ?? null,
|
||||||
totalQuantity: summary.totalQuantity ?? null, chargeableVolumeCbm: summary.chargeableVolumeCbm ?? null,
|
totalQuantity: summary.totalQuantity ?? null, chargeableVolumeCbm: summary.chargeableVolumeCbm ?? null,
|
||||||
inboundedAt: summary.inboundCompletedAt ?? '', businessDate: '', priority: 'NORMAL', customerRemark: summary.customerRemark ?? '', operatorName: '',
|
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: '',
|
createdAt: summary.createdAt, updatedAt: summary.updatedAt, tradeTerm: '', destinationCountryCode: '',
|
||||||
destinationWarehouseId: summary.destinationWarehouseId == null ? '' : String(summary.destinationWarehouseId),
|
destinationWarehouseId: summary.destinationWarehouseId == null ? '' : String(summary.destinationWarehouseId),
|
||||||
destinationWarehouseName: summary.destinationWarehouseName ?? '', pickupMethod: summary.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
destinationWarehouseName: summary.destinationWarehouseName ?? '', pickupMethod: summary.pickupMethod ?? 'SELF_EXPRESS', channelCode: '',
|
||||||
@@ -349,44 +352,15 @@ function mapUnifiedOrderRow(summary: MerchantUnifiedOrderRow, warehouses: Platfo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: PlatformReceivingWarehouse[]): FirstLegOrder {
|
||||||
if (!detail?.summary || !detail.order?.order) throw new Error('订单详情数据不完整,请刷新列表后重试')
|
if (!detail?.summary || !detail.order?.order) throw new Error('订单详情数据不完整,请刷新列表后重试')
|
||||||
const mapped = mapOrder(detail.order.order, warehouses, detail.order)
|
const mapped = mapOrder(detail.order.order, warehouses, detail.order)
|
||||||
mapped.id = String(detail.summary.orderId)
|
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.fulfillmentType = detail.summary.fulfillmentType ?? mapped.fulfillmentType
|
||||||
mapped.lxCode = detail.summary.lxCode ?? mapped.lxCode
|
mapped.lxCode = detail.summary.lxCode ?? mapped.lxCode
|
||||||
mapped.businessSummary = businessSummary(detail.summary)
|
mapped.businessSummary = { ...businessSummary(detail.summary), transportFragments: detail.transportFragments }
|
||||||
mapped.timeline = unifiedTimeline(detail)
|
mapped.timeline = unifiedTimeline(detail)
|
||||||
const summary = mapUnifiedOrderRow(detail.summary, warehouses)
|
const summary = mapUnifiedOrderRow(detail.summary, warehouses)
|
||||||
mapped.referenceNo = summary.referenceNo
|
mapped.referenceNo = summary.referenceNo
|
||||||
@@ -406,59 +380,6 @@ function mapUnifiedOrderDetail(detail: MerchantUnifiedOrderDetail, warehouses: P
|
|||||||
return mapped
|
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 {
|
function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
||||||
return {
|
return {
|
||||||
id: String(item.id), code: item.warehouseCode, name: item.warehouseName, province: '',
|
id: String(item.id), code: item.warehouseCode, name: item.warehouseName, province: '',
|
||||||
@@ -468,21 +389,38 @@ function mapWarehouse(item: MerchantWarehouse): ClientWarehouse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DraftEditSession {
|
||||||
|
readonly orderId: string
|
||||||
|
readonly expectedVersion: number
|
||||||
|
}
|
||||||
|
|
||||||
export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', () => {
|
export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', () => {
|
||||||
const orders = ref<FirstLegOrder[]>([])
|
const orders = ref<FirstLegOrder[]>([])
|
||||||
const pendingSubmitKeys = new Map<string, string>()
|
const orderDetails = ref<Record<string, FirstLegOrder>>({})
|
||||||
|
const total = ref(0)
|
||||||
|
const queueCounts = ref<OrderQueueCounts>({ all: 0, fee: 0, customs: 0, draft: 0, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 })
|
||||||
|
const orderProgress = ref<Record<string, MerchantOrderProgress>>({})
|
||||||
|
const queryChannelNames = ref<string[]>([])
|
||||||
|
let listRequest = 0
|
||||||
|
const 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 warehouses = ref<ClientWarehouse[]>([])
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const loadedFromApi = ref(false)
|
const loadedFromApi = ref(false)
|
||||||
const loadError = ref('')
|
const loadError = ref('')
|
||||||
const warehouseLoadError = ref('')
|
const warehouseLoadError = ref('')
|
||||||
const draftLoadError = ref('')
|
|
||||||
const loadedWarehouseTypes = ref<ClientWarehouseType[]>([])
|
const loadedWarehouseTypes = ref<ClientWarehouseType[]>([])
|
||||||
const warehouseTypeRequests = new Map<ClientWarehouseType, Promise<ClientWarehouse[]>>()
|
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) {
|
async function loadWarehouseType(warehouseType: ClientWarehouseType, force = false) {
|
||||||
if (warehouseType === 'DOMESTIC' && force) warehouseLoadError.value = ''
|
if (warehouseType === 'DOMESTIC' && force) warehouseLoadError.value = ''
|
||||||
@@ -509,27 +447,48 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function load(query: ClientOrderReadQuery = {}) {
|
async function load(query: MerchantOrderWorkbenchQuery = {}) {
|
||||||
|
const request = ++listRequest
|
||||||
loading.value = true
|
loading.value = true
|
||||||
loadedFromApi.value = true
|
loadedFromApi.value = true
|
||||||
loadError.value = ''
|
loadError.value = ''
|
||||||
warehouseLoadError.value = ''
|
|
||||||
draftLoadError.value = ''
|
|
||||||
loadedWarehouseTypes.value = []
|
|
||||||
warehouseTypeRequests.clear()
|
|
||||||
orders.value = []
|
orders.value = []
|
||||||
warehouses.value = []
|
total.value = 0
|
||||||
const [orderResult, warehouseResult] = await Promise.allSettled([getOrdersForClient(query), loadWarehouseType('DOMESTIC', true)])
|
// Keep the last confirmed category counts while refreshing; replace them only after validation.
|
||||||
if (warehouseResult.status === 'rejected' && !warehouseLoadError.value) warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
orderProgress.value = {}
|
||||||
|
const [orderResult, warehouseResult] = await Promise.allSettled([
|
||||||
|
getMerchantOrderWorkbench(query), loadWarehouseType('DOMESTIC'),
|
||||||
|
])
|
||||||
|
if (request !== listRequest) return 0
|
||||||
|
if (warehouseResult.status === 'rejected') warehouseLoadError.value = warehouseResult.reason instanceof Error ? warehouseResult.reason.message : '公共仓库数据加载失败'
|
||||||
if (orderResult.status === 'fulfilled') {
|
if (orderResult.status === 'fulfilled') {
|
||||||
orders.value = orderResult.value.source === 'unified'
|
try {
|
||||||
? [
|
const result = orderResult.value
|
||||||
...orderResult.value.drafts.map(mapFirstLegOrderRow),
|
const expectedPage = query.page ?? 1, size = query.size ?? 10
|
||||||
...orderResult.value.records.map((item) => mapUnifiedOrderRow(item, warehouses.value)),
|
const count = Number(result.page.total), pages = Math.ceil(count / size)
|
||||||
]
|
if (!Number.isSafeInteger(count) || count < 0 || Number(result.page.page) !== expectedPage
|
||||||
: orderResult.value.records.map(mapFirstLegOrderRow)
|
|| Number(result.page.size) !== size || Number(result.page.pages) !== pages
|
||||||
|
|| result.page.records.length !== Math.min(size, Math.max(0, count - (expectedPage - 1) * size))
|
||||||
|
|| new Set(result.page.records.map(row => String(row.orderId))).size !== result.page.records.length
|
||||||
|
|| ['all', 'fee', 'customs', 'draft', 'loaded', 'declared', 'cleared', 'scheduled', 'delivering', 'delivered'].some(key => { const value = result.queues[key as keyof typeof result.queues]; return !Number.isSafeInteger(Number(value)) || Number(value) < 0 })
|
||||||
|
|| Number(result.queues[query.queue ?? 'all']) !== count
|
||||||
|
|| !Array.isArray(result.progress) || result.progress.length !== result.page.records.length
|
||||||
|
|| new Set(result.progress.map(p => String(p.orderId))).size !== result.progress.length
|
||||||
|
|| result.progress.some(p => !result.page.records.some(row => String(row.orderId) === String(p.orderId))
|
||||||
|
|| !['none', 'loaded', 'declared', 'cleared', 'scheduled', 'delivering', 'delivered'].includes(p.stage) || typeof p.partial !== 'boolean')
|
||||||
|
|| !Array.isArray(result.channelNames)) {
|
||||||
|
loadError.value = '订单分页数据不完整,请重新加载'
|
||||||
} else {
|
} else {
|
||||||
loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
orders.value = result.page.records.map(item => mapUnifiedOrderRow(item, warehouses.value))
|
||||||
|
total.value = count
|
||||||
|
queueCounts.value = Object.fromEntries(Object.entries(result.queues).map(([key, value]) => [key, Number(value)])) as OrderQueueCounts
|
||||||
|
orderProgress.value = Object.fromEntries(result.progress.map(p => [String(p.orderId), p]))
|
||||||
|
queryChannelNames.value = result.channelNames
|
||||||
|
}
|
||||||
|
} catch { loadError.value = '订单分页数据不完整,请重新加载' }
|
||||||
|
} else loadError.value = orderResult.reason instanceof Error ? orderResult.reason.message : '订单数据加载失败'
|
||||||
|
if (loadError.value) {
|
||||||
|
queueCounts.value = { all: 0, fee: 0, customs: 0, draft: 0, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 }
|
||||||
}
|
}
|
||||||
loading.value = false
|
loading.value = false
|
||||||
return orders.value.length
|
return orders.value.length
|
||||||
@@ -538,38 +497,18 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
|||||||
function upsertOrder(mapped: FirstLegOrder) {
|
function upsertOrder(mapped: FirstLegOrder) {
|
||||||
const index = orders.value.findIndex((item) => item.id === mapped.id)
|
const index = orders.value.findIndex((item) => item.id === mapped.id)
|
||||||
if (index >= 0) orders.value[index] = mapped
|
if (index >= 0) orders.value[index] = mapped
|
||||||
else orders.value.unshift(mapped)
|
orderDetails.value[mapped.id] = mapped
|
||||||
return mapped
|
return mapped
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadLegacyDetail(id: string, listOrder?: FirstLegOrder) {
|
async function loadOrderAggregate(id: string) {
|
||||||
const detail = await getMerchantFirstLegOrder(id)
|
const detail = await getMerchantFirstLegOrder(id)
|
||||||
const mapped = mapOrder(detail.order, warehouses.value, detail)
|
return upsertOrder(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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadDetail(id: string) {
|
async function loadDetail(id: string) {
|
||||||
const listOrder = getById(id)
|
const detail = await getMerchantUnifiedOrder(id)
|
||||||
return listOrder?.status === 'DRAFT' ? loadLegacyDetail(id, listOrder) : loadUnifiedDetail(id)
|
return upsertOrder(mapUnifiedOrderDetail(detail, warehouses.value))
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadWarehouseDetail(id: string) {
|
async function loadWarehouseDetail(id: string) {
|
||||||
@@ -588,16 +527,51 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
|||||||
return mapped
|
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)
|
const warehouse = prepareDraftForSave(draft, warehouses.value)
|
||||||
if (id) {
|
if (id) {
|
||||||
const order = getById(id)
|
if (!editSession || editSession.orderId !== id) throw new Error('请重新打开草稿详情后编辑')
|
||||||
if (!order || !canClientEditFirstLegOrder(order.status)) throw new Error('当前订单状态不允许编辑')
|
const payload = { expectedVersion: editSession.expectedVersion, draft: savePayload(draft, warehouse, customerName) }
|
||||||
await updateMerchantFirstLegOrder(id, savePayload(draft, warehouse, customerName))
|
let pending = pendingEdits.get(editSession)
|
||||||
return loadLegacyDetail(id)
|
if (pending && JSON.stringify(pending.payload) !== JSON.stringify(payload)) throw new Error('上次保存结果未确认,请重试原内容,或重新打开详情后编辑')
|
||||||
|
// Observe an uncertain previous outcome without replacing its frozen version.
|
||||||
|
if (pending) await getMerchantFirstLegOrder(id)
|
||||||
|
if (!pending) {
|
||||||
|
pending = { key: createIdempotencyKey(`first-leg-edit-${id}`), payload: JSON.parse(JSON.stringify(payload)) }
|
||||||
|
pendingEdits.set(editSession, pending)
|
||||||
|
}
|
||||||
|
await updateMerchantFirstLegOrder(id, pending.payload, pending.key)
|
||||||
|
const saved = await loadOrderAggregate(id)
|
||||||
|
pendingEdits.delete(editSession)
|
||||||
|
return saved
|
||||||
}
|
}
|
||||||
const createdId = await createMerchantFirstLegOrder(savePayload(draft, warehouse, customerName))
|
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(
|
async function saveDraftBatch(
|
||||||
@@ -614,21 +588,58 @@ export const useFirstLegOrdersStore = defineStore('client-first-leg-orders', ()
|
|||||||
|
|
||||||
async function submitSaved(id: string, companyAuditStatus?: MerchantTenantStatus) {
|
async function submitSaved(id: string, companyAuditStatus?: MerchantTenantStatus) {
|
||||||
if (companyAuditStatus && companyAuditStatus !== 'ACTIVE') throw new Error('企业资料尚未审核通过,请先完善企业资料并等待平台审核')
|
if (companyAuditStatus && companyAuditStatus !== 'ACTIVE') throw new Error('企业资料尚未审核通过,请先完善企业资料并等待平台审核')
|
||||||
const idempotencyKey = pendingSubmitKeys.get(id) ?? createIdempotencyKey(`first-leg-submit-${id}`)
|
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||||
pendingSubmitKeys.set(id, idempotencyKey)
|
submittingIds.add(id)
|
||||||
await submitMerchantFirstLegOrder(id, idempotencyKey)
|
try {
|
||||||
pendingSubmitKeys.delete(id)
|
let pending = pendingSubmissions.get(id)
|
||||||
return loadUnifiedDetail(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) {
|
function hasPendingSubmission(id?: string) { return !!id && (pendingSubmissions.has(id) || submissionForms.has(id)) }
|
||||||
const order = await saveDraft(draft, customerName, id)
|
|
||||||
return submitSaved(order.id, companyAuditStatus)
|
function isSubmissionRetry(id: string | undefined, draft: FirstLegOrderDraft) {
|
||||||
|
return !!id && hasPendingSubmission(id) && submissionForms.get(id)?.snapshot === JSON.stringify(draft)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function beginNewSubmissionEdit(id: string) {
|
||||||
|
if (submittingIds.has(id)) throw new Error('订单正在提交,请稍候')
|
||||||
|
const detail = await getMerchantFirstLegOrder(id)
|
||||||
|
if (detail.order.status !== 'DRAFT') throw new Error('订单已不在草稿状态,不能重新编辑,请刷新订单查看最新状态')
|
||||||
|
if (!Number.isSafeInteger(detail.order.version) || detail.order.version < 0) throw new Error('订单版本缺失,请重新加载详情')
|
||||||
|
const order = mapOrder(detail.order, warehouses.value, detail)
|
||||||
|
const session = beginDraftEdit(order)
|
||||||
|
pendingSubmissions.delete(id)
|
||||||
|
submissionForms.delete(id)
|
||||||
|
upsertOrder(order)
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveDraftForSubmission(draft: FirstLegOrderDraft, customerName: string, id?: string, editSession?: DraftEditSession) {
|
||||||
|
if (id && isSubmissionRetry(id, draft)) return submissionForms.get(id)!.order
|
||||||
|
const snapshot = JSON.stringify(draft)
|
||||||
|
const order = await saveDraft(JSON.parse(snapshot), customerName, id, editSession)
|
||||||
|
submissionForms.set(order.id, { snapshot, order })
|
||||||
|
return order
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadDraftDetail(id: string) {
|
async function loadDraftDetail(id: string) {
|
||||||
return loadLegacyDetail(id, getById(id))
|
return loadOrderAggregate(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
return { orders, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, draftLoadError, activeCount, pendingCount, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, saveDraft, saveDraftBatch, submitSaved, submit }
|
return { orders, orderDetails, total, queueCounts, orderProgress, queryChannelNames, warehouses, loading, loadedFromApi, loadError, warehouseLoadError, getById, load, loadDetail, loadDraftDetail, loadWarehouseDetail, loadWarehouseType, beginDraftEdit, saveDraft, prepareCancellation, cancelOrder, saveDraftBatch, submitSaved, hasPendingSubmission, isSubmissionRetry, beginNewSubmissionEdit, saveDraftForSubmission }
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
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, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 }, channelNames: ['AIR', 'SEA'],
|
||||||
|
progress: Array.from({ length: Math.min(size, Math.max(0, total - (page - 1) * size)) }, (_, i) => ({ orderId: String((page - 1) * size + i + 1), stage: 'loaded', partial: false })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function deferred() { let resolve, reject; const promise = new Promise((a, b) => { resolve = a; reject = b }); return { promise, resolve, reject } }
|
||||||
|
function harness(t, read) {
|
||||||
|
const context = pinia.createPinia(); pinia.setActivePinia(context)
|
||||||
|
t.after(() => pinia.disposePinia(context))
|
||||||
|
const calls = [], details = [], warehouseCalls = []
|
||||||
|
const deps = {
|
||||||
|
vue, pinia,
|
||||||
|
'@/modules/first-leg/api/firstLeg': {},
|
||||||
|
'@/modules/first-leg/api/unifiedOrders': {
|
||||||
|
getMerchantOrderWorkbench: query => { calls.push(structuredClone(query)); return read(query) },
|
||||||
|
getMerchantUnifiedOrder: async id => {
|
||||||
|
details.push(id)
|
||||||
|
return { 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, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 })
|
||||||
|
assert.deepEqual(h.store.queryChannelNames, ['AIR', 'SEA'])
|
||||||
|
await h.store.load({ page: 22, size: 10 })
|
||||||
|
assert.deepEqual(h.store.orders.map(item => item.id), ['211', '212', '213', '214', '215'])
|
||||||
|
assert.equal(h.calls.length, 2)
|
||||||
|
assert.deepEqual(h.warehouseCalls, ['DOMESTIC'])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('late success cannot replace newer rows, counts, channels or loading state', async t => {
|
||||||
|
const a = deferred(), b = deferred()
|
||||||
|
const h = harness(t, q => q.page === 1 ? a.promise : b.promise)
|
||||||
|
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||||
|
b.resolve(result(2)); await second
|
||||||
|
a.resolve(result(1, 10, 999)); await first
|
||||||
|
assert.equal(h.store.orders[0].id, '11'); assert.equal(h.store.total, 215)
|
||||||
|
assert.equal(h.store.queueCounts.all, 215); assert.equal(h.store.loading, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('late failure cannot clear the current page and an older completion cannot stop loading a newer page', async t => {
|
||||||
|
const a = deferred(), b = deferred(), c = deferred()
|
||||||
|
const h = harness(t, q => [a, b, c][q.page - 1].promise)
|
||||||
|
const first = h.store.load({ page: 1 }), second = h.store.load({ page: 2 })
|
||||||
|
a.resolve(result(1)); await first
|
||||||
|
assert.equal(h.store.loading, true); assert.equal(h.store.orders.length, 0)
|
||||||
|
const third = h.store.load({ page: 3 })
|
||||||
|
c.resolve(result(3)); await third
|
||||||
|
b.reject(new Error('old failure')); await second
|
||||||
|
assert.equal(h.store.orders[0].id, '21'); assert.equal(h.store.loadError, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('current failure clears stale records and totals, never falls back, and retry restores the page', async t => {
|
||||||
|
let fail = false
|
||||||
|
const h = harness(t, () => fail ? Promise.reject(new Error('查询失败')) : result())
|
||||||
|
await h.store.load(); fail = true; await h.store.load()
|
||||||
|
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||||
|
assert.equal(h.store.queueCounts.all, 0); assert.equal(h.store.loadError, '查询失败')
|
||||||
|
assert.equal(h.store.loading, false)
|
||||||
|
fail = false; await h.store.load(); assert.equal(h.store.orders.length, 10)
|
||||||
|
assert.equal(h.calls.length, 3); assert.equal(h.store.loadError, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('rejects inconsistent metadata, truncated pages and duplicate rows without displaying partial data', async t => {
|
||||||
|
let response
|
||||||
|
const h = harness(t, () => response)
|
||||||
|
const corruptions = [r => { r.page.total = -1 }, r => { r.page.pages = 1 }, r => { r.page.page = 2 }, r => { r.page.records.pop() }, r => { r.page.records[1] = r.page.records[0] }, r => { r.queues.all = 99 }, r => { delete r.queues }, r => { r.channelNames = null }]
|
||||||
|
for (const corrupt of corruptions) {
|
||||||
|
response = result(); corrupt(response); await h.store.load()
|
||||||
|
assert.equal(h.store.orders.length, 0); assert.equal(h.store.total, 0)
|
||||||
|
assert.match(h.store.loadError, /分页数据不完整/); assert.equal(h.store.loading, false)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('draft and cancelled rows retain authoritative versions; off-page detail cannot inflate list or totals', async t => {
|
||||||
|
const response = result(1, 10, 2)
|
||||||
|
response.page.records = [row(1, 'DRAFT'), row(2, 'CANCELLED')]
|
||||||
|
const h = harness(t, () => response)
|
||||||
|
await h.store.load()
|
||||||
|
assert.deepEqual(h.store.orders.map(item => [item.status, item.version]), [['DRAFT', 7], ['CANCELLED', 7]])
|
||||||
|
await h.store.loadDetail('900')
|
||||||
|
assert.equal(h.store.orders.length, 2); assert.equal(h.store.total, 2)
|
||||||
|
assert.equal(h.store.getById('900').status, 'DRAFT')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('queue total is checked against the selected queue rather than all orders', async t => {
|
||||||
|
const response = result(1, 10, 2)
|
||||||
|
response.queues = { all: 215, fee: 2, customs: 1, draft: 3, loaded: 0, declared: 0, cleared: 0, scheduled: 0, delivering: 0, delivered: 0 }
|
||||||
|
const h = harness(t, () => response)
|
||||||
|
await h.store.load({ queue: 'fee' })
|
||||||
|
assert.equal(h.store.total, 2); assert.equal(h.store.queueCounts.all, 215)
|
||||||
|
assert.equal(h.store.loadError, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test('retains server progress and rejects missing or foreign progress without inferring milestones', async t => {
|
||||||
|
let response = result()
|
||||||
|
response.progress[0] = { orderId: '1', stage: 'scheduled', partial: true }
|
||||||
|
const h = harness(t, () => response)
|
||||||
|
await h.store.load()
|
||||||
|
assert.deepEqual(h.store.orderProgress['1'], response.progress[0])
|
||||||
|
response = result(); response.progress[0].orderId = 'foreign'
|
||||||
|
await h.store.load()
|
||||||
|
assert.match(h.store.loadError, /分页数据不完整/)
|
||||||
|
assert.deepEqual(h.store.orderProgress, {})
|
||||||
|
response = result(); delete response.queues.cleared
|
||||||
|
await h.store.load(); assert.match(h.store.loadError, /分页数据不完整/)
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test('category counts remain visible throughout refresh and update together after the response is validated', async t => {
|
||||||
|
const pending = deferred()
|
||||||
|
let refreshing = false
|
||||||
|
const h = harness(t, () => refreshing ? pending.promise : result())
|
||||||
|
await h.store.load()
|
||||||
|
const counts = h.store.queueCounts
|
||||||
|
refreshing = true
|
||||||
|
const request = h.store.load({ queue: 'fee' })
|
||||||
|
assert.equal(h.store.loading, true)
|
||||||
|
assert.equal(h.store.queueCounts, counts)
|
||||||
|
assert.equal(h.store.queueCounts.fee, 2)
|
||||||
|
const updated = result(1, 10, 3)
|
||||||
|
updated.queues = { ...updated.queues, all: 216, fee: 3 }
|
||||||
|
pending.resolve(updated)
|
||||||
|
await request
|
||||||
|
assert.equal(h.store.queueCounts.all, 216)
|
||||||
|
assert.equal(h.store.queueCounts.fee, 3)
|
||||||
|
assert.equal(h.store.loading, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('rapid category switches preserve counts and ignore an older response while the newest request is pending', async t => {
|
||||||
|
const older = deferred(), latest = deferred()
|
||||||
|
const h = harness(t, q => q.queue === 'fee' ? older.promise : q.queue === 'customs' ? latest.promise : result())
|
||||||
|
await h.store.load()
|
||||||
|
const oldRequest = h.store.load({ queue: 'fee' })
|
||||||
|
const newRequest = h.store.load({ queue: 'customs' })
|
||||||
|
const oldResult = result(1, 10, 2); oldResult.queues.all = 999
|
||||||
|
older.resolve(oldResult); await oldRequest
|
||||||
|
assert.equal(h.store.queueCounts.all, 215)
|
||||||
|
assert.equal(h.store.loading, true)
|
||||||
|
const newResult = result(1, 10, 1); newResult.queues.all = 216
|
||||||
|
latest.resolve(newResult); await newRequest
|
||||||
|
assert.equal(h.store.queueCounts.all, 216)
|
||||||
|
assert.equal(h.store.total, 1)
|
||||||
|
})
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||||
import type {
|
import type {
|
||||||
FirstLegOrderStatus,
|
FirstLegOrderStatus,
|
||||||
FirstLegTransportMode,
|
FirstLegTransportMode,
|
||||||
@@ -64,6 +65,7 @@ export interface FirstLegOrderTimelineItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface FirstLegOrderBusinessSummary {
|
export interface FirstLegOrderBusinessSummary {
|
||||||
|
transportFragments: MerchantTransportFragment[]
|
||||||
customerFeeConfirmationRequired: boolean
|
customerFeeConfirmationRequired: boolean
|
||||||
totalPackageCount: number | null
|
totalPackageCount: number | null
|
||||||
actualGrossWeightKg: 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,
|
FIRST_LEG_PROGRESS_STAGES,
|
||||||
getFirstLegProgressIndex,
|
getFirstLegProgressIndex,
|
||||||
getFirstLegStatusLabel,
|
getFirstLegStatusLabel,
|
||||||
|
getFirstLegPickingStatusLabel,
|
||||||
getFirstLegStatusTone,
|
getFirstLegStatusTone,
|
||||||
getFirstLegTransportModeLabel,
|
getFirstLegTransportModeLabel,
|
||||||
summarizeFirstLegCargo,
|
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', () => {
|
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_MEASURE'), '待测量数据')
|
||||||
assert.equal(getFirstLegStatusLabel('WAIT_PALLETIZE'), '待组托')
|
assert.equal(getFirstLegStatusLabel('WAIT_PALLETIZE'), '待组托')
|
||||||
assert.equal(getFirstLegStatusLabel('WAIT_SPLIT'), '待分柜')
|
assert.equal(getFirstLegStatusLabel('WAIT_SPLIT'), '待分柜')
|
||||||
|
|||||||
@@ -19,6 +19,16 @@ export function getFirstLegStatusLabel(status: string) {
|
|||||||
return statusLabels.get(canonicalStatus as FirstLegOrderStatus) ?? '未知状态'
|
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) {
|
export function getFirstLegTransportModeLabel(mode: FirstLegTransportMode | null) {
|
||||||
if (!mode) return '运输方式待更新'
|
if (!mode) return '运输方式待更新'
|
||||||
return transportModeLabels.get(mode) ?? mode
|
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(
|
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) {
|
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)
|
return FIRST_LEG_PROGRESS_STAGES.findIndex((item) => item.code === status)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import ts from 'typescript'
|
||||||
|
const source = readFileSync(new URL('./orderProgress.ts', import.meta.url), 'utf8')
|
||||||
|
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS } }).outputText
|
||||||
|
const exports = {}
|
||||||
|
new Function('exports', code)(exports)
|
||||||
|
test('prototype queues preserve order and distinguish partial progress from completion', () => {
|
||||||
|
assert.deepEqual(exports.ORDER_QUEUES.slice(0, 7).map(q => q.key), ['all','fee','loaded','declared','cleared','scheduled','delivering'])
|
||||||
|
assert.equal(exports.orderProgressLabel({ stage: 'scheduled', partial: true }), '部分已排车')
|
||||||
|
assert.equal(exports.orderProgressLabel({ stage: 'cleared', partial: false }), '已清关')
|
||||||
|
assert.equal(exports.orderProgressLabel({ stage: 'none', partial: false }), '—')
|
||||||
|
assert.equal(exports.orderProgressLabel(), '—')
|
||||||
|
})
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import type { MerchantOrderProgress, OrderQueue } from '../api/unifiedOrders'
|
||||||
|
|
||||||
|
export const ORDER_QUEUES: ReadonlyArray<{ key: OrderQueue; label: string; todo?: boolean }> = [
|
||||||
|
{ key: 'all', label: '全部' },
|
||||||
|
{ key: 'fee', label: '确认计费重', todo: true },
|
||||||
|
{ key: 'loaded', label: '装柜完成' },
|
||||||
|
{ key: 'declared', label: '已报关' },
|
||||||
|
{ key: 'cleared', label: '已清关' },
|
||||||
|
{ key: 'scheduled', label: '已排车' },
|
||||||
|
{ key: 'delivering', label: '派送中' },
|
||||||
|
{ key: 'delivered', label: '派送完成' },
|
||||||
|
{ key: 'customs', label: '上传资料', todo: true },
|
||||||
|
{ key: 'draft', label: '草稿' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function orderProgressLabel(progress?: MerchantOrderProgress) {
|
||||||
|
if (!progress || progress.stage === 'none') return '—'
|
||||||
|
const label = ORDER_QUEUES.find(q => q.key === progress.stage)?.label ?? '—'
|
||||||
|
return `${progress.partial ? '部分' : ''}${label}`
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { runInNewContext } from 'node:vm'
|
||||||
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
|
const source = readFileSync(new URL('./transportFacts.ts', import.meta.url), 'utf8')
|
||||||
|
const javascript = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const exports = {}
|
||||||
|
runInNewContext(javascript, { exports })
|
||||||
|
const rows = exports.customerTransportRows
|
||||||
|
|
||||||
|
test('split inbound fragments retain separate cabinet facts and actual/estimated times', () => {
|
||||||
|
const result = rows([
|
||||||
|
{ inboundCode: 'NY-1', cabinetNo: 'D1', containerNo: 'TSTU0000001', nodes: [
|
||||||
|
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-05T09:00:00', estimatedAt: null, providerCode: 'MANUAL' },
|
||||||
|
{ standardNode: 'DEPARTED_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-07T08:00:00', providerCode: 'MATSON' },
|
||||||
|
] },
|
||||||
|
{ inboundCode: 'NY-2', cabinetNo: 'D2', containerNo: 'TSTU0000002', nodes: [
|
||||||
|
{ standardNode: 'AT_ORIGIN_PORT', actualAt: '2026-10-06T10:00:00', estimatedAt: null, providerCode: 'MATSON' },
|
||||||
|
] },
|
||||||
|
])
|
||||||
|
assert.equal(result.length, 3)
|
||||||
|
assert.equal(result[0].nodeLabel, '已进港')
|
||||||
|
assert.equal(result[0].source, '人工记录')
|
||||||
|
assert.equal(result[1].nodeLabel, '预计开航')
|
||||||
|
assert.equal(result[1].actualAt, null)
|
||||||
|
assert.equal(result[1].estimatedAt, '2026-10-07T08:00:00')
|
||||||
|
assert.equal(result[2].cabinetNo, 'D2')
|
||||||
|
assert.equal(result[2].inboundCode, 'NY-2')
|
||||||
|
assert.equal(result[2].actualAt, '2026-10-06T10:00:00')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('empty actual scope creates no invented nodes or database identifier fallback', () => {
|
||||||
|
assert.equal(rows([]).length, 0)
|
||||||
|
assert.equal(rows([{ inboundCode: 'NY-1', nodes: [] }]).length, 0)
|
||||||
|
const [row] = rows([{ id: 'INTERNAL', nodes: [{ standardNode: 'AT_ORIGIN_PORT', actualAt: null, estimatedAt: '2026-10-05T09:00:00' }] }])
|
||||||
|
assert.equal(row.cabinetNo, '—')
|
||||||
|
assert.equal(row.containerNo, '—')
|
||||||
|
assert.equal(row.inboundCode, '—')
|
||||||
|
assert.equal(row.actualAt, null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('detail consumes the existing merchant detail API and displays times separately', () => {
|
||||||
|
const store = readFileSync(new URL('../store/firstLegOrders.ts', import.meta.url), 'utf8')
|
||||||
|
const table = readFileSync(new URL('../components/TransportFactsTable.vue', import.meta.url), 'utf8')
|
||||||
|
assert.match(store, /transportFragments: detail\.transportFragments/)
|
||||||
|
assert.match(table, /label="实际时间".*time\(row\.actualAt\)/)
|
||||||
|
assert.match(table, /label="预计时间".*time\(row\.estimatedAt\)/)
|
||||||
|
assert.doesNotMatch(table, /platform\/|fetch\(|actualAt\s*\|\|\s*.*estimatedAt/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import type { MerchantTransportFragment } from '../api/unifiedOrders'
|
||||||
|
|
||||||
|
const labels: Readonly<Record<string, string>> = {
|
||||||
|
DEPARTED_WAREHOUSE: '已离仓', AT_ORIGIN_PORT: '已进港', LOADED_ON_VESSEL: '已装船',
|
||||||
|
DEPARTED_ORIGIN_PORT: '已开航', IN_TRANSIT: '海运途中', ARRIVED_DESTINATION_PORT: '船舶已到目的港',
|
||||||
|
DISCHARGED_FROM_VESSEL: '已卸船', PICKUP_READY: '已清关、可提柜', PICKED_UP: '已提柜', EMPTY_RETURNED: '已还柜',
|
||||||
|
}
|
||||||
|
const estimatedLabels: Readonly<Record<string, string>> = {
|
||||||
|
DEPARTED_WAREHOUSE: '预计离仓', AT_ORIGIN_PORT: '预计进港', LOADED_ON_VESSEL: '预计装船',
|
||||||
|
DEPARTED_ORIGIN_PORT: '预计开航', IN_TRANSIT: '预计海运途中', ARRIVED_DESTINATION_PORT: '预计船舶到目的港',
|
||||||
|
DISCHARGED_FROM_VESSEL: '预计卸船', PICKUP_READY: '预计可提柜', PICKED_UP: '预计提柜', EMPTY_RETURNED: '预计还柜',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function customerTransportRows(fragments: MerchantTransportFragment[]) {
|
||||||
|
return fragments.flatMap((fragment, index) => fragment.nodes.map((node, nodeIndex) => ({
|
||||||
|
key: `${index}-${nodeIndex}`,
|
||||||
|
inboundCode: fragment.inboundCode || '—', cabinetNo: fragment.cabinetNo || '—',
|
||||||
|
containerNo: fragment.containerNo || '—',
|
||||||
|
nodeLabel: (node.actualAt ? labels : estimatedLabels)[node.standardNode] || '运输节点',
|
||||||
|
actualAt: node.actualAt, estimatedAt: node.estimatedAt,
|
||||||
|
location: [node.locationCode, node.locationName].filter(Boolean).join(' · ') || '—',
|
||||||
|
source: node.providerCode === 'MANUAL' ? '人工记录' : node.providerCode === 'FIRSTLEG' ? '平台记录' : node.providerCode ? '承运轨迹' : '—',
|
||||||
|
})))
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import * as vue from 'vue'
|
||||||
|
|
||||||
|
function evaluate(source, dependencies = {}) {
|
||||||
|
const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const exports = {}
|
||||||
|
new Function('require', 'exports', code)(id => {
|
||||||
|
assert.ok(id in dependencies, `Unexpected dependency ${id}`)
|
||||||
|
return dependencies[id]
|
||||||
|
}, exports)
|
||||||
|
return exports
|
||||||
|
}
|
||||||
|
const eligibility = evaluate(readFileSync(new URL('../utils/customsEligibility.ts', import.meta.url), 'utf8'))
|
||||||
|
const customsApi = evaluate(readFileSync(new URL('../api/customs.ts', import.meta.url), 'utf8'), {
|
||||||
|
'@/api/http': {}, '@/modules/first-leg/api/firstLeg': {},
|
||||||
|
})
|
||||||
|
const order = (id, status = 'LOADED', taxMode = 'TAX_REFUND') => ({ id, status, taxMode, hasCompletedLoadingPlan: ['LOADED', 'DELIVERED', 'COMPLETED'].includes(status), orderNo: `ORDER-${id}`, businessSummary: { inboundCode: `IN-${id}` } })
|
||||||
|
const detail = id => ({ status: 'COMPLETED', merchantStatus: 'CUSTOMS_COMPLETED', inbounds: [{ orderId: id, taxMode: 'TAX_REFUND' }] })
|
||||||
|
function harness(t, orders, getDetail = async id => detail(id)) {
|
||||||
|
const store = { loadError: '', failPage: 0, transformPage: value => value }, calls = [], pageCalls = []
|
||||||
|
const unifiedApi = evaluate(readFileSync(new URL('../api/unifiedOrders.ts', import.meta.url), 'utf8'), {
|
||||||
|
'@/api/http': { apiRequest: async ({ method, url, params: { page, size, taxMode, loaded } }) => {
|
||||||
|
assert.equal(method, 'GET')
|
||||||
|
assert.equal(url, '/merchant/v1/orders')
|
||||||
|
pageCalls.push({ page, size, taxMode, loaded })
|
||||||
|
if (store.loadError || store.failPage === page) throw new Error(store.loadError || '第二页订单查询失败')
|
||||||
|
// Model server filtering BEFORE pagination and COUNT, using the actual
|
||||||
|
// request produced by the production API. Missing taxMode scans all rows.
|
||||||
|
const filtered = orders.filter(row => (!taxMode || row.taxMode === taxMode)
|
||||||
|
&& (loaded === undefined || row.hasCompletedLoadingPlan === loaded))
|
||||||
|
return store.transformPage({ page, size, total: filtered.length, pages: Math.ceil(filtered.length / size),
|
||||||
|
records: filtered.slice((page - 1) * size, page * size).map(row => ({ orderId: row.id, orderNo: row.orderNo, mainStatus: row.status, taxMode: row.taxMode, inboundCode: row.businessSummary.inboundCode })) })
|
||||||
|
} },
|
||||||
|
})
|
||||||
|
const reader = evaluate(readFileSync(new URL('../utils/customsDocumentsReader.ts', import.meta.url), 'utf8'), {
|
||||||
|
'./customsEligibility': eligibility,
|
||||||
|
'../api/unifiedOrders': unifiedApi,
|
||||||
|
'../api/customs': { getMerchantCustomsForOrder: id => { calls.push(id); return getDetail(id) }, isMerchantCustomsUnavailable: error => error?.code === 'A0404' },
|
||||||
|
})
|
||||||
|
const source = readFileSync(new URL('./CustomsDocumentsView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||||
|
const scope = vue.effectScope()
|
||||||
|
const view = scope.run(() => evaluate(source + '\nexport { load, records, loading, errorMessage, openDetail, selectedOrderId, selectedDetail, dialogOpen, search, queryModel, filteredRecords, pagedRecords, page, pageSize, queryFields, statusLabel, statusType, updateDetail }', {
|
||||||
|
vue: { ...vue, onMounted() {} },
|
||||||
|
'../utils/customsDocumentsReader': reader,
|
||||||
|
'../api/customs': customsApi,
|
||||||
|
'../store/customsPending': { useCustomsPendingStore: () => ({ refresh: async () => {} }) },
|
||||||
|
}))
|
||||||
|
t.after(() => scope.stop())
|
||||||
|
return { view, store, calls, pageCalls }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('server-filtered request reaches five refund records originally on page 28 without scanning buy orders', async t => {
|
||||||
|
const orders = Array.from({ length: 5528 }, (_, i) => order(`buy-${i}`, 'COMPLETED', 'BUY_DECLARATION'))
|
||||||
|
orders.push(...Array.from({ length: 2613 }, (_, i) => order(`not-loaded-${i}`, 'WAIT_MEASURE')))
|
||||||
|
orders.push(...Array.from({ length: 5 }, (_, i) => order(`historical-${i}`, 'COMPLETED')))
|
||||||
|
const { view, calls, pageCalls } = harness(t, orders)
|
||||||
|
await view.load()
|
||||||
|
assert.deepEqual(calls, Array.from({ length: 5 }, (_, i) => `historical-${i}`))
|
||||||
|
assert.equal(view.records.value.length, 5)
|
||||||
|
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||||
|
view.queryModel.value.inboundCode = 'historical-4'; view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 1)
|
||||||
|
view.queryModel.value = { orderNo: '', inboundCode: '', containerNo: '', status: '' }; view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 5)
|
||||||
|
assert.equal(pageCalls.length, 1)
|
||||||
|
assert.equal(calls.length, 5)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('second page failure is explicit and retry does not retain an incomplete result', async t => {
|
||||||
|
const orders = Array.from({ length: 201 }, (_, i) => order(String(i)))
|
||||||
|
const { view, store, pageCalls } = harness(t, orders)
|
||||||
|
store.failPage = 2
|
||||||
|
await view.load()
|
||||||
|
assert.equal(view.records.value.length, 0)
|
||||||
|
assert.equal(view.errorMessage.value, '第二页订单查询失败')
|
||||||
|
store.failPage = 0
|
||||||
|
await view.load()
|
||||||
|
assert.equal(view.records.value.length, 201)
|
||||||
|
assert.equal(view.errorMessage.value, '')
|
||||||
|
assert.equal(pageCalls.length, 4)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('display pagination reaches the final refund order without refetching or opening the wrong detail', async t => {
|
||||||
|
const { view, calls, pageCalls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`, 'COMPLETED')))
|
||||||
|
await view.load()
|
||||||
|
assert.equal(view.pagedRecords.value.length, 20)
|
||||||
|
view.page.value = 2
|
||||||
|
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||||
|
view.openDetail(view.pagedRecords.value[0])
|
||||||
|
assert.equal(view.selectedOrderId.value, 'refund-20')
|
||||||
|
assert.deepEqual(view.selectedDetail.value.inbounds, [{ orderId: 'refund-20', taxMode: 'TAX_REFUND' }])
|
||||||
|
view.pageSize.value = 10
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(view.page.value, 1)
|
||||||
|
assert.equal(view.pagedRecords.value.length, 10)
|
||||||
|
view.page.value = 3
|
||||||
|
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||||
|
assert.equal(pageCalls.length, 1)
|
||||||
|
assert.equal(calls.length, 21)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('searching from a later display page resets pagination and clearing filters restores all documents', async t => {
|
||||||
|
const { view, calls } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||||
|
await view.load()
|
||||||
|
view.page.value = 2
|
||||||
|
view.queryModel.value.inboundCode = 'IN-refund-20'
|
||||||
|
view.search()
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(view.page.value, 1)
|
||||||
|
assert.deepEqual(view.pagedRecords.value.map(row => row.order.id), ['refund-20'])
|
||||||
|
view.queryModel.value.inboundCode = 'does-not-exist'
|
||||||
|
view.search()
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(view.page.value, 1)
|
||||||
|
assert.equal(view.pagedRecords.value.length, 0)
|
||||||
|
view.queryModel.value.inboundCode = ''
|
||||||
|
view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 21)
|
||||||
|
assert.equal(view.pagedRecords.value.length, 20)
|
||||||
|
assert.equal(calls.length, 21)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('refresh failure on a later page clears stale rows and retry returns to a valid page', async t => {
|
||||||
|
const { view, store } = harness(t, Array.from({ length: 21 }, (_, i) => order(`refund-${i}`)))
|
||||||
|
await view.load()
|
||||||
|
view.page.value = 2
|
||||||
|
store.loadError = '资料列表请求失败'
|
||||||
|
await view.load()
|
||||||
|
await vue.nextTick()
|
||||||
|
assert.equal(view.page.value, 1)
|
||||||
|
assert.equal(view.pagedRecords.value.length, 0)
|
||||||
|
assert.equal(view.errorMessage.value, '资料列表请求失败')
|
||||||
|
store.loadError = ''
|
||||||
|
await view.load()
|
||||||
|
assert.equal(view.page.value, 1)
|
||||||
|
assert.equal(view.pagedRecords.value.length, 20)
|
||||||
|
assert.equal(view.filteredRecords.value.length, 21)
|
||||||
|
assert.equal(view.errorMessage.value, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('empty pages, duplicate records and changing totals cannot silently truncate history', async t => {
|
||||||
|
for (const change of [
|
||||||
|
response => response.page === 2 ? { ...response, records: [] } : response,
|
||||||
|
response => response.page === 2 ? { ...response, records: [{ ...response.records[0], orderId: '0' }] } : response,
|
||||||
|
response => response.page === 2 ? { ...response, total: 202 } : response,
|
||||||
|
]) {
|
||||||
|
const { view, store, pageCalls } = harness(t, Array.from({ length: 201 }, (_, i) => order(String(i), 'COMPLETED')))
|
||||||
|
store.transformPage = change
|
||||||
|
await view.load()
|
||||||
|
assert.ok(view.errorMessage.value)
|
||||||
|
assert.equal(view.records.value.length, 0)
|
||||||
|
assert.equal(pageCalls.length, 2)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('document fetch concurrency never exceeds four and each candidate is requested once', async t => {
|
||||||
|
let active = 0, peak = 0
|
||||||
|
const { view, calls, pageCalls } = harness(t, Array.from({ length: 205 }, (_, i) => order(String(i))), async id => {
|
||||||
|
active += 1; peak = Math.max(peak, active)
|
||||||
|
await new Promise(resolve => setImmediate(resolve))
|
||||||
|
active -= 1
|
||||||
|
return detail(id)
|
||||||
|
})
|
||||||
|
await view.load()
|
||||||
|
assert.equal(peak, 4)
|
||||||
|
assert.equal(new Set(calls).size, 205)
|
||||||
|
assert.equal(calls.length, 205)
|
||||||
|
assert.equal(pageCalls.length, 2)
|
||||||
|
assert.deepEqual(pageCalls, [{ page: 1, size: 200, taxMode: 'TAX_REFUND', loaded: true }, { page: 2, size: 200, taxMode: 'TAX_REFUND', loaded: true }])
|
||||||
|
assert.equal(view.records.value.length, 205)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('empty result uses one page request and no document requests', async t => {
|
||||||
|
const { view, calls, pageCalls } = harness(t, [])
|
||||||
|
await view.load()
|
||||||
|
assert.equal(pageCalls.length, 1)
|
||||||
|
assert.equal(calls.length, 0)
|
||||||
|
assert.equal(view.errorMessage.value, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('tax-refund documents remain accessible through delivered and completed orders; buy orders and preloading are excluded', async t => {
|
||||||
|
const stages = ['DRAFT', 'PENDING_REVIEW', 'WAIT_MEASURE', 'WAIT_PALLETIZE', 'WAIT_SPLIT', 'LOADING', 'LOADED', 'DELIVERED', 'COMPLETED']
|
||||||
|
const orders = stages.flatMap(status => [order(status, status), order(`BUY-${status}`, status, 'BUY_DECLARATION')])
|
||||||
|
const { view, calls } = harness(t, orders)
|
||||||
|
await view.load()
|
||||||
|
assert.deepEqual(calls, ['LOADED', 'DELIVERED', 'COMPLETED'])
|
||||||
|
assert.deepEqual(view.records.value.map(row => row.order.id), calls)
|
||||||
|
const completed = view.records.value.find(row => row.order.id === 'COMPLETED')
|
||||||
|
view.openDetail(completed)
|
||||||
|
assert.equal(view.selectedOrderId.value, 'COMPLETED')
|
||||||
|
assert.equal(view.selectedDetail.value.status, 'COMPLETED')
|
||||||
|
assert.equal(view.dialogOpen.value, true)
|
||||||
|
view.queryModel.value.status = 'CUSTOMS_COMPLETED'; view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 3)
|
||||||
|
assert.equal(calls.length, 3, 'local filtering does not refetch documents')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('only matching server-returned tax-refund ownership is displayed', async t => {
|
||||||
|
const { view } = harness(t, [order('one'), order('two')], async id => id === 'one' ? detail('someone-else') : { inbounds: [{ orderId: id, taxMode: 'BUY_DECLARATION' }] })
|
||||||
|
await view.load()
|
||||||
|
assert.equal(view.records.value.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('partial failures are visible and retry replaces the result; unavailable customs is not a transport failure', async t => {
|
||||||
|
let fail = true
|
||||||
|
const { view } = harness(t, [order('ok'), order('retry'), order('unavailable')], async id => {
|
||||||
|
if (id === 'unavailable') throw Object.assign(new Error('not associated'), { code: 'A0404' })
|
||||||
|
if (id === 'retry' && fail) throw new Error('network')
|
||||||
|
return detail(id)
|
||||||
|
})
|
||||||
|
await view.load()
|
||||||
|
assert.equal(view.records.value.length, 1)
|
||||||
|
assert.equal(view.errorMessage.value, '1 票订单的报关资料加载失败,请重新加载')
|
||||||
|
fail = false; await view.load()
|
||||||
|
assert.equal(view.records.value.length, 2)
|
||||||
|
assert.equal(view.errorMessage.value, '')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('order query failure is shown instead of a successful empty result', async t => {
|
||||||
|
const { view, store, calls } = harness(t, [order('old')])
|
||||||
|
await view.load()
|
||||||
|
store.loadError = '订单查询失败'; await view.load()
|
||||||
|
assert.equal(view.records.value.length, 0)
|
||||||
|
assert.equal(view.errorMessage.value, '订单查询失败')
|
||||||
|
assert.equal(calls.length, 1)
|
||||||
|
assert.equal(view.loading.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('repeated refresh during an active load does not duplicate requests', async t => {
|
||||||
|
let resolve
|
||||||
|
const pending = new Promise(done => { resolve = done })
|
||||||
|
const { view, calls } = harness(t, [order('one')], () => pending)
|
||||||
|
const first = view.load()
|
||||||
|
await Promise.resolve()
|
||||||
|
await view.load()
|
||||||
|
assert.deepEqual(calls, ['one'])
|
||||||
|
resolve(detail('one')); await first
|
||||||
|
assert.equal(view.loading.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('mixed-container labels and filters use only the current customer status', async t => {
|
||||||
|
const states = [
|
||||||
|
['uploaded', 'WAITING_CUSTOMER_DOCUMENTS', 'DOCUMENT_UPLOADED', 1, '资料已上传', 'success'],
|
||||||
|
['waiting', 'WAITING_CUSTOMER_DOCUMENTS', 'WAITING_UPLOAD', 0, '待上传资料', 'warning'],
|
||||||
|
['declaring', 'DECLARING', 'DECLARING', 1, '报关中', 'primary'],
|
||||||
|
['completed', 'COMPLETED', 'CUSTOMS_COMPLETED', 1, '报关完成', 'success'],
|
||||||
|
]
|
||||||
|
const { view, calls } = harness(t, states.map(([id]) => order(id)), async id => {
|
||||||
|
const [, status, merchantStatus, coveredTaxRefundCount] = states.find(row => row[0] === id)
|
||||||
|
return { ...detail(id), status, merchantStatus, coveredTaxRefundCount, taxRefundCount: 1 }
|
||||||
|
})
|
||||||
|
await view.load()
|
||||||
|
for (const [id, , merchantStatus, , label, tone] of states) {
|
||||||
|
const row = view.records.value.find(item => item.order.id === id)
|
||||||
|
assert.equal(view.statusLabel(row.detail), label)
|
||||||
|
assert.equal(view.statusType(row.detail), tone)
|
||||||
|
view.queryModel.value.status = merchantStatus; view.search()
|
||||||
|
assert.deepEqual(view.filteredRecords.value.map(item => item.order.id), [id])
|
||||||
|
}
|
||||||
|
assert.deepEqual(view.queryFields.find(field => field.key === 'status').options,
|
||||||
|
states.map(([, , value, , label]) => ({ value, label })).sort((a, b) =>
|
||||||
|
['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(a.value)
|
||||||
|
- ['WAITING_UPLOAD', 'DOCUMENT_UPLOADED', 'DECLARING', 'CUSTOMS_COMPLETED'].indexOf(b.value)))
|
||||||
|
view.queryModel.value.status = 'WAITING_CUSTOMER_DOCUMENTS'; view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 0, 'container statuses are not customer filter values')
|
||||||
|
view.queryModel.value.status = ''; view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 4)
|
||||||
|
assert.equal(calls.length, 4, 'filtering does not requery or infer status from coverage')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('dialog update refreshes customer status and active filter without inferring from container status', async t => {
|
||||||
|
const { view } = harness(t, [order('one')], async id => ({ ...detail(id), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'WAITING_UPLOAD' }))
|
||||||
|
await view.load(); view.openDetail(view.records.value[0])
|
||||||
|
view.queryModel.value.status = 'WAITING_UPLOAD'; view.search()
|
||||||
|
view.updateDetail({ ...detail('one'), status: 'WAITING_CUSTOMER_DOCUMENTS', merchantStatus: 'DOCUMENT_UPLOADED', coveredTaxRefundCount: 1, taxRefundCount: 1 })
|
||||||
|
assert.equal(view.filteredRecords.value.length, 0)
|
||||||
|
view.queryModel.value.status = 'DOCUMENT_UPLOADED'; view.search()
|
||||||
|
assert.equal(view.filteredRecords.value.length, 1)
|
||||||
|
assert.equal(view.statusLabel(view.filteredRecords.value[0].detail), '资料已上传')
|
||||||
|
assert.equal(view.statusLabel({ status: 'COMPLETED', coveredTaxRefundCount: 1, taxRefundCount: 1 }), '—')
|
||||||
|
assert.equal(view.statusType({ status: 'COMPLETED' }), 'info')
|
||||||
|
})
|
||||||
@@ -4,12 +4,13 @@ import { RefreshCcw } from '@lucide/vue'
|
|||||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||||
import type { TableAction } from '@/components/common/tableActions'
|
import type { TableAction } from '@/components/common/tableActions'
|
||||||
import { useFirstLegOrdersStore } from '../public'
|
import { MERCHANT_CUSTOMS_STATUS_LABELS, type MerchantCustomsContainer } from '../api/customs'
|
||||||
import { getMerchantCustomsForOrder, type MerchantCustomsContainer } from '../api/customs'
|
import { readCustomsDocuments, type CustomsDocumentRow } from '../utils/customsDocumentsReader'
|
||||||
import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue'
|
import CustomsDocumentsDialog from '../components/CustomsDocumentsDialog.vue'
|
||||||
import type { FirstLegOrder } from '../types/firstLegOrder'
|
|
||||||
|
|
||||||
const store = useFirstLegOrdersStore()
|
import { useCustomsPendingStore } from '../store/customsPending'
|
||||||
|
|
||||||
|
const customsPending = useCustomsPendingStore()
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const errorMessage = ref('')
|
const errorMessage = ref('')
|
||||||
const queryModel = ref<QueryModel>({ orderNo: '', inboundCode: '', containerNo: '', status: '' })
|
const queryModel = ref<QueryModel>({ orderNo: '', inboundCode: '', containerNo: '', status: '' })
|
||||||
@@ -20,23 +21,18 @@ const queryFields: QueryField[] = [
|
|||||||
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
{ key: 'orderNo', label: '订单号', type: 'input', placeholder: '请输入订单号' },
|
||||||
{ key: 'inboundCode', label: '入仓码', type: 'input', placeholder: '请输入入仓码' },
|
{ key: 'inboundCode', label: '入仓码', type: 'input', placeholder: '请输入入仓码' },
|
||||||
{ key: 'containerNo', label: '柜号', type: 'input', placeholder: '请输入柜号' },
|
{ key: 'containerNo', label: '柜号', type: 'input', placeholder: '请输入柜号' },
|
||||||
{ key: 'status', label: '状态', type: 'select', placeholder: '全部', options: [
|
{ key: 'status', label: '状态', type: 'select', placeholder: '全部', options: Object.entries(MERCHANT_CUSTOMS_STATUS_LABELS).map(([value, label]) => ({ label, value })) },
|
||||||
{ label: '待上传资料', value: 'WAITING_CUSTOMER_DOCUMENTS' },
|
|
||||||
{ label: '待报关', value: 'READY_TO_START' },
|
|
||||||
{ label: '报关中', value: 'DECLARING' },
|
|
||||||
{ label: '报关完成', value: 'COMPLETED' },
|
|
||||||
] },
|
|
||||||
]
|
]
|
||||||
const columns: DataTableColumn[] = [
|
const columns: DataTableColumn[] = [
|
||||||
{ label: '操作', slotName: 'actions', width: 120, fixed: 'left' },
|
{ label: '操作', slotName: 'actions', width: 120, fixed: 'left' },
|
||||||
{ label: '订单号', slotName: 'orderNo', minWidth: 230 },
|
{ label: '订单号', slotName: 'orderNo', minWidth: 230 },
|
||||||
{ label: '入仓码', slotName: 'inboundCode', minWidth: 190 },
|
{ label: '入仓码', slotName: 'inboundCode', minWidth: 190 },
|
||||||
{ label: '柜号', slotName: 'containerNo', minWidth: 170 },
|
{ label: '柜号', slotName: 'containerNo', minWidth: 170 },
|
||||||
{ label: '实际箱数', prop: 'detail.actualBoxCount', width: 110, align: 'center' },
|
{ label: '柜内退税箱数', prop: 'detail.actualBoxCount', width: 110, align: 'center' },
|
||||||
{ label: '资料覆盖', slotName: 'coverage', width: 110, align: 'center' },
|
{ label: '柜内资料覆盖', slotName: 'coverage', width: 110, align: 'center' },
|
||||||
{ label: '状态', slotName: 'status', width: 130 },
|
{ label: '状态', slotName: 'status', width: 130 },
|
||||||
]
|
]
|
||||||
const records = ref<Array<{ order: FirstLegOrder; detail: MerchantCustomsContainer }>>([])
|
const records = ref<CustomsDocumentRow[]>([])
|
||||||
const dialogOpen = ref(false)
|
const dialogOpen = ref(false)
|
||||||
const selectedOrderId = ref('')
|
const selectedOrderId = ref('')
|
||||||
const selectedDetail = ref<MerchantCustomsContainer | null>(null)
|
const selectedDetail = ref<MerchantCustomsContainer | null>(null)
|
||||||
@@ -48,7 +44,7 @@ const filteredRecords = computed(() => {
|
|||||||
matches(order.orderNo, 'orderNo')
|
matches(order.orderNo, 'orderNo')
|
||||||
&& matches(order.businessSummary.inboundCode, 'inboundCode')
|
&& matches(order.businessSummary.inboundCode, 'inboundCode')
|
||||||
&& (matches(detail.containerNo, 'containerNo') || matches(detail.cabinetNo, 'containerNo'))
|
&& (matches(detail.containerNo, 'containerNo') || matches(detail.cabinetNo, 'containerNo'))
|
||||||
&& (!query.status || detail.status === query.status),
|
&& (!query.status || detail.merchantStatus === query.status),
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
const pagedRecords = computed(() => filteredRecords.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
const pagedRecords = computed(() => filteredRecords.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||||
@@ -67,26 +63,27 @@ function rowActions(row: object): TableAction[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function statusLabel(detail: MerchantCustomsContainer) {
|
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) {
|
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() {
|
async function load() {
|
||||||
if (loading.value) return
|
if (loading.value) return
|
||||||
|
void customsPending.refresh(true)
|
||||||
loading.value = true; errorMessage.value = ''
|
loading.value = true; errorMessage.value = ''
|
||||||
try {
|
try {
|
||||||
await store.load()
|
const { records: loadedRecords, failedCount } = await readCustomsDocuments()
|
||||||
const candidates = store.orders.filter((order) => order.status === 'LOADED' && order.taxMode === 'TAX_REFUND')
|
records.value = loadedRecords
|
||||||
const results = await Promise.allSettled(candidates.map(async (order) => ({ order, detail: await getMerchantCustomsForOrder(order.id) })))
|
if (failedCount) errorMessage.value = `${failedCount} 票订单的报关资料加载失败,请重新加载`
|
||||||
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] : [])
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
records.value = []
|
records.value = []
|
||||||
errorMessage.value = error instanceof Error ? error.message : '报关资料加载失败,请稍后重试'
|
errorMessage.value = error instanceof Error ? error.message : '报关资料加载失败,请稍后重试'
|
||||||
} finally { loading.value = false }
|
} finally { loading.value = false }
|
||||||
}
|
}
|
||||||
function openDetail(item: unknown) {
|
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
|
selectedOrderId.value = value.order.id; selectedDetail.value = value.detail; dialogOpen.value = true
|
||||||
}
|
}
|
||||||
function updateDetail(value: MerchantCustomsContainer) {
|
function updateDetail(value: MerchantCustomsContainer) {
|
||||||
@@ -101,7 +98,7 @@ onMounted(() => { void load() })
|
|||||||
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" />
|
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="报关资料查询条件" :fields="queryFields" @search="search" />
|
||||||
<section class="customs-card">
|
<section class="customs-card">
|
||||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRecords" :columns="columns" :loading="loading" :total="filteredRecords.length" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="order.id" :empty-text="emptyText">
|
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="pagedRecords" :columns="columns" :loading="loading" :total="filteredRecords.length" :page-sizes="[10, 20, 50, 100]" :row-actions="rowActions" row-key="order.id" :empty-text="emptyText">
|
||||||
<template #toolbar><strong>资料列表</strong></template>
|
<template #toolbar><strong>资料列表</strong><span>统计为本客户同柜退税货物汇总,资料覆盖按入仓码计。</span></template>
|
||||||
<template #toolbar-actions><el-button :loading="loading" @click="load"><RefreshCcw :size="16" />刷新</el-button></template>
|
<template #toolbar-actions><el-button :loading="loading" @click="load"><RefreshCcw :size="16" />刷新</el-button></template>
|
||||||
<template v-if="errorMessage" #error><div class="state-error" role="alert"><span>{{ errorMessage }}</span><el-button :loading="loading" @click="load">重新加载</el-button></div></template>
|
<template v-if="errorMessage" #error><div class="state-error" role="alert"><span>{{ errorMessage }}</span><el-button :loading="loading" @click="load">重新加载</el-button></div></template>
|
||||||
<template #orderNo="{ row }">{{ row.order.orderNo || '—' }}</template>
|
<template #orderNo="{ row }">{{ row.order.orderNo || '—' }}</template>
|
||||||
|
|||||||
@@ -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;/)
|
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, /function openCreate\(\)/)
|
||||||
assert.match(source, /async function saveDraft\(\)/)
|
assert.match(source, /async function saveDraft\(\)/)
|
||||||
assert.match(source, /function submitOrder\(\)/)
|
assert.match(source, /function submitOrder\(\)/)
|
||||||
assert.match(source, /async function openDetail\(order: FirstLegOrder\)/)
|
assert.match(source, /async function openDetail\(order: FirstLegOrder\)/)
|
||||||
assert.match(source, /Promise\.allSettled\(\[/)
|
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, /Promise\.allSettled\(\[\s*orderPageRequest,\s*companyRequest/)
|
||||||
assert.match(source, /tenantStore\.loadCompanyContext\(\)/)
|
assert.match(source, /tenantStore\.loadCompanyContext\(\)/)
|
||||||
assert.match(source, /await store\.loadDetail\(orderId\)/)
|
assert.match(source, /await store\.loadDetail\(orderId\)/)
|
||||||
assert.doesNotMatch(source, /cancelOrder|取消订单/)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
test('returns edited submissions to the refreshed order list instead of opening detail', () => {
|
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', () => {
|
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', () => {
|
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, /<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, /async function searchOrders\(model: QueryModel\)/)
|
||||||
assert.match(source, /await store\.load\(\{/)
|
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.match(source, /\{ key: 'actions', label: '操作', width: 284, fixed: 'left', align: 'left', headerAlign: 'left', slotName: 'actions' \}/)
|
||||||
assert.doesNotMatch(source, /order-metrics|订单概览/)
|
assert.doesNotMatch(source, /order-metrics|订单概览/)
|
||||||
})
|
})
|
||||||
@@ -177,7 +176,7 @@ test('exports every visible order field with normalized dates', () => {
|
|||||||
test('matches the prototype with selectable dense order-list columns', () => {
|
test('matches the prototype with selectable dense order-list columns', () => {
|
||||||
assert.match(source, /aria-label="设置订单列表显示列"/)
|
assert.match(source, /aria-label="设置订单列表显示列"/)
|
||||||
assert.match(source, /显示字段筛选/)
|
assert.match(source, /显示字段筛选/)
|
||||||
assert.match(source, /const defaultVisibleColumnKeys = \['status', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt'\]/)
|
assert.match(source, /const defaultVisibleColumnKeys = \['status', 'progress', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt'\]/)
|
||||||
assert.match(source, /key: 'inboundCode', label: '入仓码', width: 230, fixed: 'left'/)
|
assert.match(source, /key: 'inboundCode', label: '入仓码', width: 230, fixed: 'left'/)
|
||||||
assert.match(source, /<SlidersHorizontal :size="18"/)
|
assert.match(source, /<SlidersHorizontal :size="18"/)
|
||||||
assert.match(source, /<el-checkbox-group v-model="visibleColumnKeys"/)
|
assert.match(source, /<el-checkbox-group v-model="visibleColumnKeys"/)
|
||||||
@@ -232,6 +231,9 @@ test('shows one unified progress line and C02 business summaries without detail
|
|||||||
assert.doesNotMatch(source, /<h3>报关回执<\/h3>/)
|
assert.doesNotMatch(source, /<h3>报关回执<\/h3>/)
|
||||||
assert.match(source, /船期摘要/)
|
assert.match(source, /船期摘要/)
|
||||||
assert.match(source, /柜次明细/)
|
assert.match(source, /柜次明细/)
|
||||||
|
assert.match(source, /pickingStatusLabel: getFirstLegPickingStatusLabel\(summary\.loadingStatus\)/)
|
||||||
|
assert.match(source, /prop="pickingStatusLabel" label="拣货状态"/)
|
||||||
|
assert.doesNotMatch(source, /label="当前节点"/)
|
||||||
assert.match(source, /尚未分配柜次,后续柜次节点将在这里同步。/)
|
assert.match(source, /尚未分配柜次,后续柜次节点将在这里同步。/)
|
||||||
assert.doesNotMatch(source, /暂无柜次分配信息/)
|
assert.doesNotMatch(source, /暂无柜次分配信息/)
|
||||||
assert.doesNotMatch(source, /summary\.sealNo \|\|/)
|
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.match(source, /displayListValue/)
|
||||||
assert.doesNotMatch(source, /key: 'operator'/)
|
assert.doesNotMatch(source, /key: 'operator'/)
|
||||||
assert.doesNotMatch(source, /key: 'transportMode', type: 'select'/)
|
assert.doesNotMatch(source, /key: 'transportMode', type: 'select'/)
|
||||||
assert.match(source, /store\.draftLoadError/)
|
assert.match(source, /:total="store\.total"/)
|
||||||
assert.match(source, /mainStatus: statusValue && statusValue !== 'DRAFT' \? statusValue : undefined/)
|
assert.match(source, /mainStatus: text\('status'\)/)
|
||||||
assert.match(source, /draftOnly: statusValue === 'DRAFT'/)
|
assert.match(source, /queue: activeOrderQueue\.value, page: requestedPage, size: tablePageSize\.value/)
|
||||||
assert.match(source, /createdFrom: range\[0\] \? `\$\{range\[0\]\}T00:00:00`/)
|
assert.match(source, /createdFrom: range\[0\] \? `\$\{range\[0\]\}T00:00:00`/)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -270,7 +272,7 @@ test('keeps all progress stages and business summary usable on mobile', () => {
|
|||||||
test('keeps the first viewport compact and moves create into the table toolbar', () => {
|
test('keeps the first viewport compact and moves create into the table toolbar', () => {
|
||||||
const tableToolbarSource = source.slice(source.indexOf('#toolbar-actions'), source.indexOf('class="order-eligibility is-pending"'))
|
const tableToolbarSource = source.slice(source.indexOf('#toolbar-actions'), source.indexOf('class="order-eligibility is-pending"'))
|
||||||
assert.match(source, /#toolbar-actions/)
|
assert.match(source, /#toolbar-actions/)
|
||||||
assert.match(source, /class="order-queue-tabs"[\s\S]*确认计费重[\s\S]*上传资料[\s\S]*草稿/)
|
assert.match(source, /class="order-queue-tabs"[\s\S]*v-for="queue in ORDER_QUEUES"[\s\S]*orderQueueCounts\[queue.key\]/)
|
||||||
assert.match(source, /activeOrderQueue\.value === 'draft'[\s\S]*order\.status === 'DRAFT'/)
|
assert.match(source, /activeOrderQueue\.value === 'draft'[\s\S]*order\.status === 'DRAFT'/)
|
||||||
assert.doesNotMatch(source, /共 \{\{ filteredOrders\.length \}\} 条/)
|
assert.doesNotMatch(source, /共 \{\{ filteredOrders\.length \}\} 条/)
|
||||||
assert.match(source, /#toolbar-actions[\s\S]*order:first-leg:create[\s\S]*创建订单[\s\S]*class="order-eligibility is-pending"/)
|
assert.match(source, /#toolbar-actions[\s\S]*order:first-leg:create[\s\S]*创建订单[\s\S]*class="order-eligibility is-pending"/)
|
||||||
@@ -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', () => {
|
test('submits only selected draft orders in one batch action', () => {
|
||||||
assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/)
|
assert.match(source, /selectedDraftOrders = computed\(\(\) => selectedOrders\.value\.filter\(\(order\) => order\.status === 'DRAFT'\)\)/)
|
||||||
assert.match(source, /Promise\.allSettled\(drafts\.map\(\(order\) => submitMerchantFirstLegOrder/)
|
assert.match(source, /Promise\.allSettled\(ids\.map\(id => store\.submitSaved/)
|
||||||
assert.match(source, /createIdempotencyKey\(`first-leg-batch-submit-\$\{order\.id\}`\)/)
|
assert.doesNotMatch(source, /submitMerchantFirstLegOrder/)
|
||||||
assert.match(source, /v-if="canSubmitOrder"[\s\S]*批量提交草稿/)
|
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\)/)
|
assert.doesNotMatch(source, /openInboundCodeAssociation\([^)]*\.id\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('opens customer customs documents only for server-confirmed loaded tax-refund orders', () => {
|
test('opens customer customs documents only for server-confirmed tax-refund orders after loading', () => {
|
||||||
assert.match(source, /order\.status !== 'LOADED'/)
|
assert.match(source, /!isCustomsOrderCandidate\(order\)/)
|
||||||
assert.match(source, /item\.orderId === order\.id && item\.taxMode === 'TAX_REFUND'/)
|
assert.match(source, /item\.orderId === order\.id && item\.taxMode === 'TAX_REFUND'/)
|
||||||
assert.match(source, /getMerchantCustomsForOrder\(order\.id\)/)
|
assert.match(source, /getMerchantCustomsForOrder\(order\.id\)/)
|
||||||
assert.match(source, /if \(eligibleCustomsDetail\(order\)\) \{\s*actions\.push\(\{ key: 'customs', label: '报关资料'/)
|
assert.match(source, /if \(eligibleCustomsDetail\(order\)\) \{\s*actions\.push\(\{ key: 'customs', label: '报关资料'/)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<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 { useRoute, useRouter } from 'vue-router'
|
||||||
import { ElMessage, ElMessageBox, type FormInstance, type FormItemRule, type FormRules, type UploadRequestOptions } from 'element-plus'
|
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'
|
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 InboundBillingPanel from '@/modules/first-leg/components/InboundBillingPanel.vue'
|
||||||
import InboundCodeAssociationDialog from '@/modules/first-leg/components/InboundCodeAssociationDialog.vue'
|
import InboundCodeAssociationDialog from '@/modules/first-leg/components/InboundCodeAssociationDialog.vue'
|
||||||
import OrderProgressPanel from '@/modules/first-leg/components/OrderProgressPanel.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 CustomsDocumentsDialog from '@/modules/first-leg/components/CustomsDocumentsDialog.vue'
|
||||||
import { getMerchantInboundBilling } from '@/modules/first-leg/api/inboundBilling'
|
import { getMerchantInboundBilling } from '@/modules/first-leg/api/inboundBilling'
|
||||||
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '@/modules/first-leg/api/customs'
|
import { getMerchantCustomsForOrder, isMerchantCustomsUnavailable, type MerchantCustomsContainer } from '@/modules/first-leg/api/customs'
|
||||||
|
import { isCustomsOrderCandidate, needsCustomsUpload } from '../utils/customsEligibility'
|
||||||
import {
|
import {
|
||||||
estimateMerchantFirstLegPrice,
|
estimateMerchantFirstLegPrice,
|
||||||
createIdempotencyKey,
|
createIdempotencyKey,
|
||||||
@@ -28,7 +30,6 @@ import {
|
|||||||
getMerchantOrderAddresses,
|
getMerchantOrderAddresses,
|
||||||
getMerchantPricingChannels,
|
getMerchantPricingChannels,
|
||||||
importMerchantFirstLegOrders,
|
importMerchantFirstLegOrders,
|
||||||
submitMerchantFirstLegOrder,
|
|
||||||
updateMerchantOrderAddress,
|
updateMerchantOrderAddress,
|
||||||
uploadMerchantProductImage,
|
uploadMerchantProductImage,
|
||||||
type CustomerOrderAddress,
|
type CustomerOrderAddress,
|
||||||
@@ -40,7 +41,7 @@ import {
|
|||||||
type MerchantPricingChannel,
|
type MerchantPricingChannel,
|
||||||
type InboundCodePolicy,
|
type InboundCodePolicy,
|
||||||
} from '@/modules/first-leg/api/firstLeg'
|
} 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 { useTenantAdministrationStore } from '@/modules/tenant-management/public'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
|
import { useUnsavedWorkRegistration } from '@/navigation/workspace-tabs/unsavedWork'
|
||||||
@@ -52,11 +53,14 @@ import {
|
|||||||
canClientEditFirstLegOrder,
|
canClientEditFirstLegOrder,
|
||||||
createEmptyCargoItem,
|
createEmptyCargoItem,
|
||||||
getFirstLegStatusLabel,
|
getFirstLegStatusLabel,
|
||||||
|
getFirstLegPickingStatusLabel,
|
||||||
getFirstLegStatusTone,
|
getFirstLegStatusTone,
|
||||||
getFirstLegTransportModeLabel,
|
getFirstLegTransportModeLabel,
|
||||||
summarizeFirstLegCargo,
|
summarizeFirstLegCargo,
|
||||||
validateFirstLegOrderDraft,
|
validateFirstLegOrderDraft,
|
||||||
} from '@/modules/first-leg/utils/firstLegOrder'
|
} from '@/modules/first-leg/utils/firstLegOrder'
|
||||||
|
import { ORDER_QUEUES, orderProgressLabel } from '../utils/orderProgress'
|
||||||
|
import type { OrderQueue } from '../api/unifiedOrders'
|
||||||
import { validateProductImageFile } from '@/modules/first-leg/utils/productImage'
|
import { validateProductImageFile } from '@/modules/first-leg/utils/productImage'
|
||||||
import { createPriceEstimateBreakdown } from '@/modules/first-leg/utils/priceEstimate'
|
import { createPriceEstimateBreakdown } from '@/modules/first-leg/utils/priceEstimate'
|
||||||
|
|
||||||
@@ -78,6 +82,53 @@ const companyAuditLoaded = ref(false)
|
|||||||
const companySubmissionBlocked = computed(() => companyAuditLoaded.value && tenantStore.company.auditStatus !== 'ACTIVE')
|
const companySubmissionBlocked = computed(() => companyAuditLoaded.value && tenantStore.company.auditStatus !== 'ACTIVE')
|
||||||
const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create'))
|
const canCreateOrder = computed(() => auth.hasPermission('order:first-leg:create'))
|
||||||
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
|
const canEditOrder = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||||
|
const canCancelOrder = computed(() => auth.hasPermission('order:first-leg:cancel'))
|
||||||
|
const 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 canSubmitOrder = computed(() => auth.hasPermission('order:first-leg:submit'))
|
||||||
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
|
const canConfirmInboundFee = computed(() => auth.hasPermission('order:first-leg:edit'))
|
||||||
const availableWarehouses = computed(() => store.warehouses.filter((warehouse) => warehouse.warehouseType === 'DOMESTIC'))
|
const availableWarehouses = computed(() => store.warehouses.filter((warehouse) => warehouse.warehouseType === 'DOMESTIC'))
|
||||||
@@ -87,9 +138,9 @@ const appliedFilters = ref<QueryModel>({ ...filters.value })
|
|||||||
const queryFields = computed<QueryField[]>(() => [
|
const queryFields = computed<QueryField[]>(() => [
|
||||||
{ key: 'cargoKeyword', label: '入仓码 / SKU', type: 'input', placeholder: '请输入入仓码或 SKU', props: { 'aria-label': '入仓码或 SKU' } },
|
{ 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: '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: '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: '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': '快递单号' } },
|
{ key: 'trackingNumber', label: '快递单号', type: 'input', placeholder: '请输入快递单号', props: { 'aria-label': '快递单号' } },
|
||||||
])
|
])
|
||||||
@@ -119,6 +170,7 @@ const fixedOrderColumns: DataTableColumn[] = [
|
|||||||
]
|
]
|
||||||
const selectableOrderColumns: DataTableColumn[] = [
|
const selectableOrderColumns: DataTableColumn[] = [
|
||||||
{ key: 'status', label: '当前订单状态', width: 126, align: 'center', headerAlign: 'center', slotName: 'status' },
|
{ key: 'status', label: '当前订单状态', width: 126, align: 'center', headerAlign: 'center', slotName: 'status' },
|
||||||
|
{ key: 'progress', label: '履约进度', width: 142, align: 'center', headerAlign: 'center', slotName: 'progress' },
|
||||||
{ key: 'channel', label: '渠道', width: 150, align: 'left', headerAlign: 'left', showOverflowTooltip: true, slotName: 'channel' },
|
{ key: 'channel', label: '渠道', width: 150, align: 'left', headerAlign: 'left', showOverflowTooltip: true, slotName: 'channel' },
|
||||||
{ key: 'transportMode', label: '运输方式', width: 104, align: 'center', headerAlign: 'center', slotName: 'transportMode' },
|
{ key: 'transportMode', label: '运输方式', width: 104, align: 'center', headerAlign: 'center', slotName: 'transportMode' },
|
||||||
{ key: 'pickupMethod', label: '交货方式', width: 112, align: 'center', headerAlign: 'center', slotName: 'pickupMethod' },
|
{ key: 'pickupMethod', label: '交货方式', width: 112, align: 'center', headerAlign: 'center', slotName: 'pickupMethod' },
|
||||||
@@ -149,7 +201,7 @@ const selectableOrderColumns: DataTableColumn[] = [
|
|||||||
{ key: 'updatedAt', label: '更新时间', width: 164, align: 'center', headerAlign: 'center', slotName: 'updatedAt' },
|
{ key: 'updatedAt', label: '更新时间', width: 164, align: 'center', headerAlign: 'center', slotName: 'updatedAt' },
|
||||||
]
|
]
|
||||||
const allSelectableColumnKeys = selectableOrderColumns.map((column) => String(column.key))
|
const allSelectableColumnKeys = selectableOrderColumns.map((column) => String(column.key))
|
||||||
const defaultVisibleColumnKeys = ['status', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt']
|
const defaultVisibleColumnKeys = ['status', 'progress', 'channel', 'transportMode', 'pickupMethod', 'receivingWarehouse', 'createdAt']
|
||||||
const visibleColumnKeys = ref<string[]>([...defaultVisibleColumnKeys])
|
const visibleColumnKeys = ref<string[]>([...defaultVisibleColumnKeys])
|
||||||
const orderedColumnKeys = ref<string[]>([...allSelectableColumnKeys])
|
const orderedColumnKeys = ref<string[]>([...allSelectableColumnKeys])
|
||||||
const draggedColumnKey = ref('')
|
const draggedColumnKey = ref('')
|
||||||
@@ -189,15 +241,16 @@ const tablePageSize = ref(10)
|
|||||||
const downloadingMarks = ref(false)
|
const downloadingMarks = ref(false)
|
||||||
const exportingOrders = ref(false)
|
const exportingOrders = ref(false)
|
||||||
const batchSubmitting = ref(false)
|
const batchSubmitting = ref(false)
|
||||||
|
const pendingBatchSubmissionIds = ref<string[]>([])
|
||||||
const selectedOrders = ref<FirstLegOrder[]>([])
|
const selectedOrders = ref<FirstLegOrder[]>([])
|
||||||
const selectedOrderCount = computed(() => selectedOrders.value.length)
|
const selectedOrderCount = computed(() => selectedOrders.value.length)
|
||||||
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
|
const selectedDraftOrders = computed(() => selectedOrders.value.filter((order) => order.status === 'DRAFT'))
|
||||||
const orderTableVersion = ref(0)
|
const orderTableVersion = ref(0)
|
||||||
type OrderQueue = 'all' | 'fee' | 'customs' | 'draft'
|
|
||||||
const activeOrderQueue = ref<OrderQueue>('all')
|
const activeOrderQueue = ref<OrderQueue>('all')
|
||||||
const editorOpen = ref(false)
|
const editorOpen = ref(false)
|
||||||
const orderFormRef = ref<FormInstance>()
|
const orderFormRef = ref<FormInstance>()
|
||||||
const editingId = ref<string>()
|
const editingId = ref<string>()
|
||||||
|
const editingSession = shallowRef<DraftEditSession>()
|
||||||
const openingEditor = ref(false)
|
const openingEditor = ref(false)
|
||||||
const copyingOrderId = ref('')
|
const copyingOrderId = ref('')
|
||||||
const detailId = ref<string>()
|
const detailId = ref<string>()
|
||||||
@@ -450,61 +503,60 @@ useUnsavedWorkRegistration({
|
|||||||
dirty: editorDirty,
|
dirty: editorDirty,
|
||||||
})
|
})
|
||||||
|
|
||||||
function matchesAppliedFilters(order: FirstLegOrder) {
|
const orderQueueCounts = computed(() => store.queueCounts)
|
||||||
const statusValue = appliedFilters.value.status
|
const pagedOrders = computed(() => store.orders)
|
||||||
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 queryMatchedOrders = computed(() => store.orders.filter(matchesAppliedFilters))
|
async function selectOrderQueue(queue: OrderQueue) {
|
||||||
const orderQueueCounts = computed(() => ({
|
if (activeOrderQueue.value === queue && !store.loadError) return
|
||||||
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) {
|
|
||||||
activeOrderQueue.value = queue
|
activeOrderQueue.value = queue
|
||||||
tablePage.value = 1
|
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 = []
|
selectedOrders.value = []
|
||||||
orderTableVersion.value += 1
|
orderTableVersion.value += 1
|
||||||
}
|
}
|
||||||
|
|
||||||
function eligibleCustomsDetail(order: FirstLegOrder) {
|
function eligibleCustomsDetail(order: FirstLegOrder) {
|
||||||
const value = customsByOrder[order.id]
|
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
|
return value.inbounds.some((item) => item.orderId === order.id && item.taxMode === 'TAX_REFUND') ? value : null
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadCustomsEligibility(order: FirstLegOrder) {
|
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)
|
customsEligibilityPending.add(order.id)
|
||||||
try {
|
try {
|
||||||
customsByOrder[order.id] = await getMerchantCustomsForOrder(order.id)
|
customsByOrder[order.id] = await getMerchantCustomsForOrder(order.id)
|
||||||
@@ -536,7 +588,9 @@ function openInboundCodeAssociation(inboundCode: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateCustomsDetail(value: MerchantCustomsContainer) {
|
function updateCustomsDetail(value: MerchantCustomsContainer) {
|
||||||
|
const previous = customsByOrder[customsDialogOrderId.value]
|
||||||
if (customsDialogOrderId.value) customsByOrder[customsDialogOrderId.value] = 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)
|
const detailOrder = computed(() => detailId.value ? store.getById(detailId.value) : undefined)
|
||||||
@@ -548,7 +602,7 @@ const pagedDetailCargoItems = computed(() => {
|
|||||||
})
|
})
|
||||||
const progressSummaryItems = computed(() => {
|
const progressSummaryItems = computed(() => {
|
||||||
const order = detailOrder.value
|
const order = detailOrder.value
|
||||||
if (!order) return []
|
if (!order || order.status === 'CANCELLED') return []
|
||||||
const inbound = inboundBilling.value?.inbound.summary
|
const inbound = inboundBilling.value?.inbound.summary
|
||||||
const summary = order.businessSummary
|
const summary = order.businessSummary
|
||||||
const formatMetric = (value: number | null | undefined, unit = '') => value == null ? '待更新' : `${value.toLocaleString()}${unit ? ` ${unit}` : ''}`
|
const formatMetric = (value: number | null | undefined, unit = '') => value == null ? '待更新' : `${value.toLocaleString()}${unit ? ` ${unit}` : ''}`
|
||||||
@@ -572,7 +626,7 @@ const progressSummaryItems = computed(() => {
|
|||||||
const cabinetProgressItems = computed(() => {
|
const cabinetProgressItems = computed(() => {
|
||||||
const summary = detailOrder.value?.businessSummary
|
const summary = detailOrder.value?.businessSummary
|
||||||
if (!summary || (!summary.cabinetNo && !summary.containerNo)) return []
|
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 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))
|
const selectedDestinationWarehouse = computed(() => store.warehouses.find((item) => item.id === form.destinationWarehouseId && item.warehouseType === form.destinationType))
|
||||||
@@ -582,7 +636,14 @@ const hasActiveFilters = computed(() => {
|
|||||||
const values = appliedFilters.value
|
const values = appliedFilters.value
|
||||||
return Object.values(values).some((value) => Array.isArray(value) ? value.length > 0 : Boolean(typeof value === 'string' ? value.trim() : value))
|
return Object.values(values).some((value) => Array.isArray(value) ? value.length > 0 : Boolean(typeof value === 'string' ? value.trim() : value))
|
||||||
})
|
})
|
||||||
const emptyDescription = computed(() => hasActiveFilters.value ? '没有符合筛选条件的订单' : '还没有订单')
|
const emptyDescription = computed(() => {
|
||||||
|
if (hasActiveFilters.value) return '没有符合筛选条件的订单'
|
||||||
|
if (activeOrderQueue.value === 'customs') return '暂无需要上传报关资料的订单'
|
||||||
|
if (activeOrderQueue.value === 'fee') return '暂无需要确认计费重的订单'
|
||||||
|
if (activeOrderQueue.value === 'draft') return '暂无草稿订单'
|
||||||
|
if (activeOrderQueue.value !== 'all') return `暂无${ORDER_QUEUES.find(q => q.key === activeOrderQueue.value)?.label ?? ''}的订单`
|
||||||
|
return '还没有订单'
|
||||||
|
})
|
||||||
|
|
||||||
async function loadPageData() {
|
async function loadPageData() {
|
||||||
supportingDataLoading.value = true
|
supportingDataLoading.value = true
|
||||||
@@ -596,7 +657,7 @@ async function loadPageData() {
|
|||||||
: Promise.resolve()
|
: Promise.resolve()
|
||||||
const orderPageRequest = isCreatePage.value || isDetailPage.value
|
const orderPageRequest = isCreatePage.value || isDetailPage.value
|
||||||
? store.loadWarehouseType('DOMESTIC', true)
|
? store.loadWarehouseType('DOMESTIC', true)
|
||||||
: store.load({ includeDrafts: true })
|
: loadOrderPage()
|
||||||
const addressRequest = isCreatePage.value ? loadOrderAddresses() : Promise.resolve()
|
const addressRequest = isCreatePage.value ? loadOrderAddresses() : Promise.resolve()
|
||||||
const [ordersResult, companyResult, destinationResult, policyResult, addressResult] = await Promise.allSettled([
|
const [ordersResult, companyResult, destinationResult, policyResult, addressResult] = await Promise.allSettled([
|
||||||
orderPageRequest,
|
orderPageRequest,
|
||||||
@@ -617,7 +678,6 @@ async function loadPageData() {
|
|||||||
}
|
}
|
||||||
if (!isCreatePage.value && ordersResult.status === 'rejected' && !store.loadError) supportingDataErrors.value.push(`订单加载失败:${errorMessage(ordersResult.reason)}`)
|
if (!isCreatePage.value && ordersResult.status === 'rejected' && !store.loadError) supportingDataErrors.value.push(`订单加载失败:${errorMessage(ordersResult.reason)}`)
|
||||||
if (store.warehouseLoadError) supportingDataErrors.value.push(`公共仓库加载失败:${store.warehouseLoadError}`)
|
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 (destinationResult.status === 'rejected') supportingDataErrors.value.push(`目的仓加载失败:${errorMessage(destinationResult.reason)}`)
|
||||||
if (addressResult.status === 'rejected') supportingDataErrors.value.push(`企业地址簿加载失败:${errorMessage(addressResult.reason)}`)
|
if (addressResult.status === 'rejected') supportingDataErrors.value.push(`企业地址簿加载失败:${errorMessage(addressResult.reason)}`)
|
||||||
await autofillWarehouseSelections()
|
await autofillWarehouseSelections()
|
||||||
@@ -633,6 +693,7 @@ async function loadRouteDraft(id: string) {
|
|||||||
const draft = draftFromOrder(detailedOrder)
|
const draft = draftFromOrder(detailedOrder)
|
||||||
if (draft.destinationType !== 'PRIVATE') await loadDestinationWarehouses(draft.destinationType)
|
if (draft.destinationType !== 'PRIVATE') await loadDestinationWarehouses(draft.destinationType)
|
||||||
editingId.value = detailedOrder.id
|
editingId.value = detailedOrder.id
|
||||||
|
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||||
replaceForm(draft)
|
replaceForm(draft)
|
||||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||||
if (form.receivingWarehouseId) await loadSelectedWarehouse(form.receivingWarehouseId)
|
if (form.receivingWarehouseId) await loadSelectedWarehouse(form.receivingWarehouseId)
|
||||||
@@ -1299,6 +1360,9 @@ function getOrderRowActions(row: object): TableAction[] {
|
|||||||
if (canEditOrder.value && canClientEditFirstLegOrder(order.status)) {
|
if (canEditOrder.value && canClientEditFirstLegOrder(order.status)) {
|
||||||
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
|
actions.push({ key: 'edit', label: '编辑', loading: openingEditor.value, run: () => openEdit(order) })
|
||||||
}
|
}
|
||||||
|
if (canOfferCancellation(order)) {
|
||||||
|
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)) {
|
if (eligibleCustomsDetail(order)) {
|
||||||
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
|
actions.push({ key: 'customs', label: '报关资料', run: () => openCustomsDocuments(order) })
|
||||||
}
|
}
|
||||||
@@ -1361,6 +1425,7 @@ async function openEdit(order: FirstLegOrder) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
editingId.value = detailedOrder.id
|
editingId.value = detailedOrder.id
|
||||||
|
editingSession.value = store.beginDraftEdit(detailedOrder)
|
||||||
replaceForm(draft)
|
replaceForm(draft)
|
||||||
await Promise.all(form.items.map(ensureProductImagePreview))
|
await Promise.all(form.items.map(ensureProductImagePreview))
|
||||||
if (warehouseAvailable) void loadSelectedWarehouse(detailedOrder.receivingWarehouseId)
|
if (warehouseAvailable) void loadSelectedWarehouse(detailedOrder.receivingWarehouseId)
|
||||||
@@ -1385,7 +1450,8 @@ async function loadDetailPage(orderId: string) {
|
|||||||
detailError.value = ''
|
detailError.value = ''
|
||||||
try {
|
try {
|
||||||
const detailedOrder = await store.loadDetail(orderId)
|
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.
|
// 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))
|
await Promise.all((detailOrder.value?.items ?? detailedOrder.items).map(ensureProductImagePreview))
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -1466,6 +1532,7 @@ async function retryInboundBilling() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleInboundFeeConfirmed() {
|
function handleInboundFeeConfirmed() {
|
||||||
|
if (!isCreatePage.value && !isDetailPage.value) void loadOrderPage()
|
||||||
if (!feeConfirmationOpen.value) void retryInboundBilling()
|
if (!feeConfirmationOpen.value) void retryInboundBilling()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1677,14 +1744,14 @@ function handleOrderSelectionChange(rows: FirstLegOrder[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function submitSelectedDraftOrders() {
|
async function submitSelectedDraftOrders() {
|
||||||
const drafts = selectedDraftOrders.value
|
const ids = [...new Set([...pendingBatchSubmissionIds.value, ...selectedDraftOrders.value.map(order => order.id)])]
|
||||||
if (batchSubmitting.value || !drafts.length) return
|
if (batchSubmitting.value || !ids.length) return
|
||||||
if (companySubmissionBlocked.value) {
|
if (companySubmissionBlocked.value) {
|
||||||
ElMessage.warning('企业资料审核通过后才能提交订单')
|
ElMessage.warning('企业资料审核通过后才能提交订单')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
await ElMessageBox.confirm(`确认提交选中的 ${drafts.length} 条草稿订单吗?`, '批量提交订单', {
|
await ElMessageBox.confirm(`确认提交 ${ids.length} 条草稿订单吗?${pendingBatchSubmissionIds.value.length ? '上次结果未确认的订单将使用原提交命令重试。' : ''}`, '批量提交订单', {
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
confirmButtonText: '确认提交',
|
confirmButtonText: '确认提交',
|
||||||
cancelButtonText: '取消',
|
cancelButtonText: '取消',
|
||||||
@@ -1696,10 +1763,8 @@ async function submitSelectedDraftOrders() {
|
|||||||
|
|
||||||
batchSubmitting.value = true
|
batchSubmitting.value = true
|
||||||
try {
|
try {
|
||||||
const results = await Promise.allSettled(drafts.map((order) => submitMerchantFirstLegOrder(
|
const results = await Promise.allSettled(ids.map(id => store.submitSaved(id, companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined)))
|
||||||
order.id,
|
pendingBatchSubmissionIds.value = ids.filter((id, index) => results[index]?.status === 'rejected' && store.hasPendingSubmission(id))
|
||||||
createIdempotencyKey(`first-leg-batch-submit-${order.id}`),
|
|
||||||
)))
|
|
||||||
const successCount = results.filter((result) => result.status === 'fulfilled').length
|
const successCount = results.filter((result) => result.status === 'fulfilled').length
|
||||||
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
|
||||||
await searchOrders(appliedFilters.value)
|
await searchOrders(appliedFilters.value)
|
||||||
@@ -1751,6 +1816,7 @@ function exportOrderInformation() {
|
|||||||
displayListValue(order.destinationWarehouseName),
|
displayListValue(order.destinationWarehouseName),
|
||||||
destinationTypeLabels[order.destinationType],
|
destinationTypeLabels[order.destinationType],
|
||||||
getFirstLegStatusLabel(order.status),
|
getFirstLegStatusLabel(order.status),
|
||||||
|
orderProgressLabel(store.orderProgress[order.id]),
|
||||||
formatListMetric(orderPackageCount(order)),
|
formatListMetric(orderPackageCount(order)),
|
||||||
displayListValue(order.expressCompanyName),
|
displayListValue(order.expressCompanyName),
|
||||||
displayListValue(order.trackingNumber),
|
displayListValue(order.trackingNumber),
|
||||||
@@ -1769,7 +1835,7 @@ function exportOrderInformation() {
|
|||||||
formatExportDateTime(order.createdAt),
|
formatExportDateTime(order.createdAt),
|
||||||
])
|
])
|
||||||
downloadCsv('订单信息.csv', [[
|
downloadCsv('订单信息.csv', [[
|
||||||
'入仓码', '渠道', '运输方式', '交货方式', '预约提货时间', '目的仓', '目的仓类型', '当前订单状态', '箱数', '快递公司', '快递单号', 'SKUS',
|
'入仓码', '渠道', '运输方式', '交货方式', '预约提货时间', '目的仓', '目的仓类型', '当前订单状态', '履约进度', '箱数', '快递公司', '快递单号', 'SKUS',
|
||||||
'总毛重', '总净重', '总体积', '总数量', '计费单价', '计费体积', '计费重量', '备注',
|
'总毛重', '总净重', '总体积', '总数量', '计费单价', '计费体积', '计费重量', '备注',
|
||||||
'货件编号', '跟踪编号', '国内仓入库时间', '创建时间',
|
'货件编号', '跟踪编号', '国内仓入库时间', '创建时间',
|
||||||
], ...rows])
|
], ...rows])
|
||||||
@@ -1893,7 +1959,7 @@ async function submitBatchImport() {
|
|||||||
batchImportIdempotencyKey.value,
|
batchImportIdempotencyKey.value,
|
||||||
)
|
)
|
||||||
const result = batchImportResult.value.result
|
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} 条`)
|
if (result.failed) ElMessage.warning(`导入完成:成功 ${result.succeeded} 条,失败 ${result.failed} 条`)
|
||||||
else ElMessage.success(`已成功导入 ${result.succeeded} 条订单草稿`)
|
else ElMessage.success(`已成功导入 ${result.succeeded} 条订单草稿`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -1951,8 +2017,10 @@ async function saveDraft() {
|
|||||||
if (!await validateEditorForm()) return
|
if (!await validateEditorForm()) return
|
||||||
saving.value = true
|
saving.value = true
|
||||||
try {
|
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
|
editingId.value = order.id
|
||||||
|
editingSession.value = store.beginDraftEdit(order)
|
||||||
markEditorClean()
|
markEditorClean()
|
||||||
editorOpen.value = false
|
editorOpen.value = false
|
||||||
if (isCreatePage.value) await router.push({ name: 'first-leg-orders' })
|
if (isCreatePage.value) await router.push({ name: 'first-leg-orders' })
|
||||||
@@ -1964,6 +2032,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() {
|
async function submitOrder() {
|
||||||
if (saving.value) return
|
if (saving.value) return
|
||||||
if (companySubmissionBlocked.value) {
|
if (companySubmissionBlocked.value) {
|
||||||
@@ -1982,13 +2064,16 @@ async function submitOrder() {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!await validateEditorForm()) return
|
const retry = store.isSubmissionRetry(editingId.value, cloneDraft(form))
|
||||||
|
if (!retry && !await validateEditorForm()) return
|
||||||
|
|
||||||
try {
|
try {
|
||||||
saving.value = true
|
saving.value = true
|
||||||
|
if (!retry && !await confirmSubmissionEdit()) return
|
||||||
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
|
const knownCompanyAuditStatus = companyAuditLoaded.value ? tenantStore.company.auditStatus : undefined
|
||||||
const savedOrder = await store.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
|
editingId.value = savedOrder.id
|
||||||
|
editingSession.value = store.beginDraftEdit(savedOrder)
|
||||||
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
|
await store.submitSaved(savedOrder.id, knownCompanyAuditStatus)
|
||||||
markEditorClean()
|
markEditorClean()
|
||||||
editorOpen.value = false
|
editorOpen.value = false
|
||||||
@@ -2008,37 +2093,13 @@ async function submitOrder() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function searchOrders(model: QueryModel) {
|
async function searchOrders(model: QueryModel) {
|
||||||
const createdRange = model.createdRange
|
appliedFilters.value = { ...model,
|
||||||
appliedFilters.value = {
|
createdRange: Array.isArray(model.createdRange) ? model.createdRange.filter((value): value is string => typeof value === 'string') : [],
|
||||||
...model,
|
|
||||||
createdRange: Array.isArray(createdRange) ? createdRange.filter((value): value is string => typeof value === 'string') : [],
|
|
||||||
}
|
}
|
||||||
tablePage.value = 1
|
tablePage.value = 1
|
||||||
try {
|
await loadOrderPage()
|
||||||
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.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -2047,13 +2108,15 @@ async function searchOrders(model: QueryModel) {
|
|||||||
<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" />
|
<QueryToolbar v-model="filters" class="first-leg-query-toolbar" layout="grid" :fields="queryFields" ariaLabel="订单查询" @search="searchOrders" />
|
||||||
|
|
||||||
<div class="client-card order-table-card">
|
<div class="client-card order-table-card">
|
||||||
<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>
|
<template #toolbar>
|
||||||
<nav class="order-queue-tabs" aria-label="订单事项分类">
|
<nav class="order-queue-tabs" aria-label="订单事项分类">
|
||||||
<button type="button" :class="{ active: activeOrderQueue === 'all' }" @click="selectOrderQueue('all')">全部</button>
|
<button v-for="queue in ORDER_QUEUES" :key="queue.key" type="button"
|
||||||
<button type="button" :class="{ active: activeOrderQueue === 'fee' }" @click="selectOrderQueue('fee')">确认计费重<span v-if="orderQueueCounts.fee" class="queue-count">{{ orderQueueCounts.fee }}</span></button>
|
:class="{ active: activeOrderQueue === queue.key }" :aria-pressed="activeOrderQueue === queue.key"
|
||||||
<button type="button" :class="{ active: activeOrderQueue === 'customs' }" @click="selectOrderQueue('customs')">上传资料<span v-if="orderQueueCounts.customs" class="queue-count">{{ orderQueueCounts.customs }}</span></button>
|
@click="selectOrderQueue(queue.key)">
|
||||||
<button type="button" :class="{ active: activeOrderQueue === 'draft' }" @click="selectOrderQueue('draft')">草稿<span v-if="orderQueueCounts.draft" class="queue-count">{{ orderQueueCounts.draft }}</span></button>
|
{{ queue.label }}<span v-if="queue.key !== 'all' && orderQueueCounts[queue.key]"
|
||||||
|
:class="queue.todo ? 'queue-count' : 'queue-stage-count'">{{ queue.todo ? orderQueueCounts[queue.key] : `(${orderQueueCounts[queue.key]})` }}</span>
|
||||||
|
</button>
|
||||||
</nav>
|
</nav>
|
||||||
<span v-if="selectedOrderCount">已选 {{ selectedOrderCount }} 条</span>
|
<span v-if="selectedOrderCount">已选 {{ selectedOrderCount }} 条</span>
|
||||||
</template>
|
</template>
|
||||||
@@ -2086,7 +2149,7 @@ async function searchOrders(model: QueryModel) {
|
|||||||
</el-popover>
|
</el-popover>
|
||||||
<el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button>
|
<el-button :loading="downloadingMarks" :disabled="selectedOrderCount === 0" @click="downloadShippingMarks"><Download :size="16" />下载唛头</el-button>
|
||||||
<el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button>
|
<el-button :loading="exportingOrders" :disabled="selectedOrderCount === 0" @click="exportOrderInformation"><Download :size="16" />导出订单信息</el-button>
|
||||||
<el-button v-if="canSubmitOrder" :loading="batchSubmitting" :disabled="selectedDraftOrders.length === 0 || 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="auth.hasPermission('order:first-leg:create')" @click="openBatchImport"><Upload :size="17" />批量导入订单</el-button>
|
||||||
<el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button>
|
<el-button v-if="props.showCreateAction && auth.hasPermission('order:first-leg:create')" type="primary" :loading="pageDataLoading" :disabled="pageDataLoading || availableWarehouses.length === 0" @click="openCreate"><FilePlus2 :size="17" />创建订单</el-button>
|
||||||
|
|
||||||
@@ -2129,6 +2192,7 @@ async function searchOrders(model: QueryModel) {
|
|||||||
<template #receivingWarehouse="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).receivingWarehouseName)">{{ displayListValue((row as FirstLegOrder).receivingWarehouseName) }}</span></template>
|
<template #receivingWarehouse="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).receivingWarehouseName)">{{ displayListValue((row as FirstLegOrder).receivingWarehouseName) }}</span></template>
|
||||||
<template #destinationWarehouse="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).destinationWarehouseName)">{{ displayListValue((row as FirstLegOrder).destinationWarehouseName) }}</span></template>
|
<template #destinationWarehouse="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).destinationWarehouseName)">{{ displayListValue((row as FirstLegOrder).destinationWarehouseName) }}</span></template>
|
||||||
<template #destinationType="{ row }">{{ destinationTypeLabels[(row as FirstLegOrder).destinationType] }}</template>
|
<template #destinationType="{ row }">{{ destinationTypeLabels[(row as FirstLegOrder).destinationType] }}</template>
|
||||||
|
<template #progress="{ row }">{{ orderProgressLabel(store.orderProgress[row.id]) }}</template>
|
||||||
<template #status="{ row }"><span class="client-status" :data-tone="getFirstLegStatusTone((row as FirstLegOrder).status)">{{ getFirstLegStatusLabel((row as FirstLegOrder).status) }}</span></template>
|
<template #status="{ row }"><span class="client-status" :data-tone="getFirstLegStatusTone((row as FirstLegOrder).status)">{{ getFirstLegStatusLabel((row as FirstLegOrder).status) }}</span></template>
|
||||||
<template #packageCount="{ row }">{{ formatListMetric(orderPackageCount(row as FirstLegOrder)) }}</template>
|
<template #packageCount="{ row }">{{ formatListMetric(orderPackageCount(row as FirstLegOrder)) }}</template>
|
||||||
<template #expressCompany="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).expressCompanyName)">{{ displayListValue((row as FirstLegOrder).expressCompanyName) }}</span></template>
|
<template #expressCompany="{ row }"><span class="table-ellipsis" :title="displayListValue((row as FirstLegOrder).expressCompanyName)">{{ displayListValue((row as FirstLegOrder).expressCompanyName) }}</span></template>
|
||||||
@@ -2349,16 +2413,16 @@ async function searchOrders(model: QueryModel) {
|
|||||||
<div class="order-detail-heading">
|
<div class="order-detail-heading">
|
||||||
<div class="detail-heading-main">
|
<div class="detail-heading-main">
|
||||||
<el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button>
|
<el-button link type="primary" class="detail-back-action" @click="router.push({ name: 'first-leg-orders' })">← 返回列表</el-button>
|
||||||
<div><h2>{{ detailOrder.businessSummary.inboundCode || (detailOrder.status === '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>
|
||||||
<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>
|
</div>
|
||||||
<section class="detail-section">
|
<section class="detail-section">
|
||||||
<h3>订单与运输</h3>
|
<h3>订单与运输</h3>
|
||||||
<dl class="order-detail-grid">
|
<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>{{ 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>{{ displayValue(detailOrder.tradeTerm) }}</dd></div>
|
||||||
<div><dt>发货方式</dt><dd>{{ pickupMethodLabels[detailOrder.pickupMethod] }}</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>
|
<div><dt>预约提货时间</dt><dd>{{ detailOrder.pickupMethod === 'PICKUP' && detailOrder.requestedPickupAt ? formatDateTime(detailOrder.requestedPickupAt) : '-' }}</dd></div>
|
||||||
@@ -2383,7 +2447,7 @@ async function searchOrders(model: QueryModel) {
|
|||||||
</dl>
|
</dl>
|
||||||
<div v-if="detailOrder.customerRemark" class="customer-remark"><strong>客户备注</strong><p>{{ detailOrder.customerRemark }}</p></div>
|
<div v-if="detailOrder.customerRemark" class="customer-remark"><strong>客户备注</strong><p>{{ detailOrder.customerRemark }}</p></div>
|
||||||
</section>
|
</section>
|
||||||
<section v-if="detailOrder.status !== 'DRAFT'" class="detail-section">
|
<section v-if="detailOrder.status !== 'DRAFT' && detailOrder.status !== 'CANCELLED'" class="detail-section">
|
||||||
<h3>关键业务摘要</h3>
|
<h3>关键业务摘要</h3>
|
||||||
<dl class="fulfillment-summary">
|
<dl class="fulfillment-summary">
|
||||||
<div v-for="item in progressSummaryItems" :key="item.label"><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>
|
<div v-for="item in progressSummaryItems" :key="item.label"><dt>{{ item.label }}</dt><dd>{{ item.value }}</dd></div>
|
||||||
@@ -2397,15 +2461,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 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="船名 / 航次" 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 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>
|
</el-table>
|
||||||
<p v-else class="detail-inline-empty">尚未分配柜次,后续柜次节点将在这里同步。</p>
|
<p v-else class="detail-inline-empty">尚未分配柜次,后续柜次节点将在这里同步。</p>
|
||||||
|
<TransportFactsTable :fragments="detailOrder.businessSummary.transportFragments" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</OrderProgressPanel>
|
</OrderProgressPanel>
|
||||||
<section class="detail-section">
|
<section v-if="detailOrder.status !== 'CANCELLED' || detailOrder.expressCompanyName || detailOrder.trackingNumber" class="detail-section">
|
||||||
<h3>履约快递信息</h3>
|
<h3>履约快递信息</h3>
|
||||||
<dl v-if="detailOrder.expressCompanyName || detailOrder.trackingNumber" class="express-information"><div><dt>快递公司</dt><dd>{{ detailOrder.expressCompanyName || '待平台补充' }}</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>
|
<div v-else class="express-empty"><PackageCheck :size="20" /><div><strong>平台尚未维护快递信息</strong><span>快递公司和快递单号由平台后台维护,客户端仅只读展示。</span></div></div>
|
||||||
</section>
|
</section>
|
||||||
<section class="detail-section">
|
<section class="detail-section">
|
||||||
@@ -2455,6 +2520,7 @@ async function searchOrders(model: QueryModel) {
|
|||||||
<el-empty v-else description="暂无货物明细" :image-size="56" />
|
<el-empty v-else description="暂无货物明细" :image-size="56" />
|
||||||
</section>
|
</section>
|
||||||
<InboundBillingPanel
|
<InboundBillingPanel
|
||||||
|
v-if="detailOrder.status !== 'CANCELLED'"
|
||||||
:data="inboundBilling"
|
:data="inboundBilling"
|
||||||
:loading="inboundBillingLoading"
|
:loading="inboundBillingLoading"
|
||||||
:unavailable="inboundBillingUnavailable"
|
:unavailable="inboundBillingUnavailable"
|
||||||
@@ -2512,7 +2578,12 @@ async function searchOrders(model: QueryModel) {
|
|||||||
.supporting-data-error span { overflow-wrap: anywhere; color: var(--muted); font-size: 11px; line-height: 1.55; }
|
.supporting-data-error span { overflow-wrap: anywhere; color: var(--muted); font-size: 11px; line-height: 1.55; }
|
||||||
.order-row-actions, .editor-actions { display: flex; justify-content: flex-end; gap: 8px; }
|
.order-row-actions, .editor-actions { display: flex; justify-content: flex-end; gap: 8px; }
|
||||||
.order-table-card { padding: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); box-shadow: none; }
|
.order-table-card { padding: 0; overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); box-shadow: none; }
|
||||||
.order-queue-tabs { display: flex; align-items: center; gap: 4px; }
|
.prototype-order-table :deep(.data-table__toolbar) { flex-wrap: nowrap; }
|
||||||
|
.prototype-order-table :deep(.data-table__toolbar-heading) { min-width: 0; flex: 1; flex-wrap: nowrap; }
|
||||||
|
.prototype-order-table :deep(.data-table__toolbar-actions) { flex-shrink: 0; }
|
||||||
|
.order-queue-tabs { display: flex; min-width: 0; align-items: center; gap: 4px; overflow-x: auto; padding: 7px 0 10px; scrollbar-width: thin; }
|
||||||
|
.order-queue-tabs button { flex-shrink: 0; white-space: nowrap; }
|
||||||
|
.queue-stage-count { margin-left: 3px; }
|
||||||
.order-queue-tabs button { position: relative; min-height: 34px; padding: 0 12px; border: 1px solid transparent; border-radius: 7px; background: transparent; color: #667085; cursor: pointer; font: inherit; font-weight: 600; }
|
.order-queue-tabs button { position: relative; min-height: 34px; padding: 0 12px; border: 1px solid transparent; border-radius: 7px; background: transparent; color: #667085; cursor: pointer; font: inherit; font-weight: 600; }
|
||||||
.order-queue-tabs button:hover { color: var(--client-action); }
|
.order-queue-tabs button:hover { color: var(--client-action); }
|
||||||
.order-queue-tabs button.active { border-color: #cfe0ff; background: #f3f7ff; color: var(--client-action); }
|
.order-queue-tabs button.active { border-color: #cfe0ff; background: #f3f7ff; color: var(--client-action); }
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import ts from 'typescript'
|
||||||
|
|
||||||
|
const source = readFileSync(new URL('./FirstLegOrdersView.vue', import.meta.url), 'utf8').match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
||||||
|
const ast = ts.createSourceFile('view.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
|
||||||
|
const names = ['loadOrderPage', 'changeOrderPage', 'changeOrderPageSize', 'selectOrderQueue', 'searchOrders']
|
||||||
|
const functions = ast.statements.filter(n => ts.isFunctionDeclaration(n) && names.includes(n.name?.text)).map(n => n.getText(ast)).join('\n')
|
||||||
|
const code = ts.transpileModule('let orderPageRequestVersion = 0;\n' + functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
function harness() {
|
||||||
|
const calls = []
|
||||||
|
const values = {
|
||||||
|
tablePage: ref(1), tablePageSize: ref(10), activeOrderQueue: ref('all'), appliedFilters: ref({}),
|
||||||
|
selectedOrders: ref(['previous']), orderTableVersion: ref(0),
|
||||||
|
store: { total: 215, loadError: '', load: async q => { calls.push(q) } },
|
||||||
|
}
|
||||||
|
const handlers = new Function(...Object.keys(values), code + ';return {' + names.join(',') + '}')(...Object.values(values))
|
||||||
|
return { ...values, ...handlers, calls }
|
||||||
|
}
|
||||||
|
test('page events request server pages; size, queue and search reset to the first page', async () => {
|
||||||
|
const h = harness()
|
||||||
|
await h.changeOrderPage(21); assert.equal(h.calls.at(-1).page, 21)
|
||||||
|
await h.changeOrderPageSize(50); assert.equal(h.calls.at(-1).page, 1); assert.equal(h.calls.at(-1).size, 50)
|
||||||
|
await h.selectOrderQueue('customs'); assert.equal(h.calls.at(-1).queue, 'customs'); assert.equal(h.tablePage.value, 1)
|
||||||
|
await h.searchOrders({ cargoKeyword: ' SKU ', status: 'DRAFT', createdRange: ['2026-10-01', '2026-10-03'] })
|
||||||
|
assert.equal(h.calls.at(-1).cargoKeyword, 'SKU'); assert.equal(h.calls.at(-1).mainStatus, 'DRAFT')
|
||||||
|
assert.equal(h.calls.at(-1).createdFrom, '2026-10-01T00:00:00')
|
||||||
|
assert.equal(h.calls.at(-1).createdTo, '2026-10-03T23:59:59.999')
|
||||||
|
assert.deepEqual(h.selectedOrders.value, [])
|
||||||
|
})
|
||||||
|
test('deletion on the last page clamps and reloads once; failed reads retain the requested page for retry', async () => {
|
||||||
|
const h = harness(); h.store.total = 200
|
||||||
|
await h.changeOrderPage(22)
|
||||||
|
assert.deepEqual(h.calls.map(q => q.page), [22, 20]); assert.equal(h.tablePage.value, 20)
|
||||||
|
h.store.total = 0; h.store.loadError = 'failed'
|
||||||
|
await h.changeOrderPage(22)
|
||||||
|
assert.equal(h.tablePage.value, 22); assert.equal(h.calls.length, 3)
|
||||||
|
})
|
||||||
|
test('old same-page response cannot clamp a newer query or clear its current selection', async () => {
|
||||||
|
const h = harness(); let release
|
||||||
|
h.store.load = () => new Promise(resolve => { release = resolve })
|
||||||
|
const first = h.loadOrderPage(); const oldRelease = release
|
||||||
|
const second = h.searchOrders({ cargoKeyword: 'new' })
|
||||||
|
h.store.total = 215; release(); await second
|
||||||
|
h.selectedOrders.value = ['new-selection']
|
||||||
|
oldRelease(); await first
|
||||||
|
assert.deepEqual(h.selectedOrders.value, ['new-selection'])
|
||||||
|
assert.equal(h.orderTableVersion.value, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
test('clicking the current category does not reload or reset its page, but an error can be retried', async () => {
|
||||||
|
const h = harness(); h.tablePage.value = 3
|
||||||
|
await h.selectOrderQueue('all')
|
||||||
|
assert.equal(h.calls.length, 0); assert.equal(h.tablePage.value, 3)
|
||||||
|
h.store.loadError = 'failed'
|
||||||
|
await h.selectOrderQueue('all')
|
||||||
|
assert.equal(h.calls.length, 1); assert.equal(h.tablePage.value, 1)
|
||||||
|
})
|
||||||
@@ -36,7 +36,7 @@ test('keeps customer message actions first and covers the requested local states
|
|||||||
assert.match(source, /notification-state--error/)
|
assert.match(source, /notification-state--error/)
|
||||||
assert.match(source, /暂无消息/)
|
assert.match(source, /暂无消息/)
|
||||||
assert.doesNotMatch(source, /清空已读|删除消息/)
|
assert.doesNotMatch(source, /清空已读|删除消息/)
|
||||||
assert.match(source, /Promise\.all\(\[load\(\), notifications\.refreshUnreadCount\(\)\]\)/)
|
assert.match(source, /Promise\.all\(\[load\(\), notifications\.refreshUnreadCount\(true\)\]\)/)
|
||||||
assert.match(source, /auth\.hasPermission\('merchant:notification:read'\)/)
|
assert.match(source, /auth\.hasPermission\('merchant:notification:read'\)/)
|
||||||
assert.match(source, /auth\.hasPermission\('merchant:notification:read-all'\)/)
|
assert.match(source, /auth\.hasPermission\('merchant:notification:read-all'\)/)
|
||||||
assert.match(source, /v-if="canMarkAllRead"/)
|
assert.match(source, /v-if="canMarkAllRead"/)
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const requests = []
|
||||||
|
const source = readFileSync(new URL('./notifications.ts', import.meta.url), 'utf8').replace(/^import [^\r\n]*\r?\n/gm, '').replace('export const', 'const')
|
||||||
|
const code = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const store = new Function('computed', 'ref', 'defineStore', 'getMyUnreadNotificationCount', code + '\nreturn useNotificationsStore()')(computed, ref, (_id, factory) => factory, () => new Promise((resolve, reject) => requests.push({ resolve, reject })))
|
||||||
|
return { store, requests }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('shell and page concurrent reads share one pending request', async () => {
|
||||||
|
const { store, requests } = setup()
|
||||||
|
const a = store.refreshUnreadCount(), b = store.refreshUnreadCount()
|
||||||
|
assert.equal(requests.length, 1)
|
||||||
|
requests[0].resolve(5)
|
||||||
|
await Promise.all([a, b])
|
||||||
|
assert.equal(store.unreadCount.value, 5)
|
||||||
|
assert.equal(store.loading.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('post-mutation refresh reads again after a pending pre-mutation read', async () => {
|
||||||
|
const { store, requests } = setup()
|
||||||
|
const a = store.refreshUnreadCount(), b = store.refreshUnreadCount(true)
|
||||||
|
assert.equal(requests.length, 1)
|
||||||
|
requests[0].resolve(5)
|
||||||
|
await a
|
||||||
|
await Promise.resolve()
|
||||||
|
assert.equal(requests.length, 2)
|
||||||
|
requests[1].resolve(0)
|
||||||
|
await b
|
||||||
|
assert.equal(store.unreadCount.value, 0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('failed request releases the pending guard for retry', async () => {
|
||||||
|
const { store, requests } = setup()
|
||||||
|
const a = store.refreshUnreadCount()
|
||||||
|
requests[0].reject(new Error('network'))
|
||||||
|
await a
|
||||||
|
const b = store.refreshUnreadCount()
|
||||||
|
assert.equal(requests.length, 2)
|
||||||
|
requests[1].resolve(2)
|
||||||
|
await b
|
||||||
|
assert.equal(store.unreadCount.value, 2)
|
||||||
|
assert.equal(store.errorMessage.value, '')
|
||||||
|
})
|
||||||
@@ -9,7 +9,19 @@ export const useNotificationsStore = defineStore('client-notifications', () => {
|
|||||||
|
|
||||||
const hasUnread = computed(() => (unreadCount.value ?? 0) > 0)
|
const hasUnread = computed(() => (unreadCount.value ?? 0) > 0)
|
||||||
|
|
||||||
async function refreshUnreadCount() {
|
let pending: Promise<void> | null = null
|
||||||
|
|
||||||
|
async function refreshUnreadCount(afterMutation = false): Promise<void> {
|
||||||
|
if (pending) {
|
||||||
|
if (!afterMutation) return pending
|
||||||
|
await pending
|
||||||
|
return refreshUnreadCount()
|
||||||
|
}
|
||||||
|
pending = loadUnreadCount().finally(() => { pending = null })
|
||||||
|
return pending
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUnreadCount() {
|
||||||
loading.value = true
|
loading.value = true
|
||||||
errorMessage.value = ''
|
errorMessage.value = ''
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import type { NotificationDetail } from '../contracts'
|
|||||||
import { notificationCategoryLabel, notificationSentAt } from '../presentation'
|
import { notificationCategoryLabel, notificationSentAt } from '../presentation'
|
||||||
const route = useRoute(); const router = useRouter(); const auth = useAuthStore(); const notifications = useNotificationsStore(); const detail = ref<NotificationDetail | null>(null); const loading = ref(false); const errorMessage = ref(''); const readErrorMessage = ref('')
|
const route = useRoute(); const router = useRouter(); const auth = useAuthStore(); const notifications = useNotificationsStore(); const detail = ref<NotificationDetail | null>(null); const loading = ref(false); const errorMessage = ref(''); const readErrorMessage = ref('')
|
||||||
const canMarkRead = computed(() => auth.hasPermission('merchant:notification:read'))
|
const canMarkRead = computed(() => auth.hasPermission('merchant:notification:read'))
|
||||||
async function markReadIfAllowed(){if(!detail.value||detail.value.status!=='UNREAD'||!canMarkRead.value)return;try{await markMyNotificationRead(detail.value.id);detail.value={...detail.value,status:'READ'};await notifications.refreshUnreadCount()}catch(error){readErrorMessage.value=error instanceof ApiError?error.message:'消息已加载,但自动标记已读失败'}}
|
async function markReadIfAllowed(){if(!detail.value||detail.value.status!=='UNREAD'||!canMarkRead.value)return;try{await markMyNotificationRead(detail.value.id);detail.value={...detail.value,status:'READ'};await notifications.refreshUnreadCount(true)}catch(error){readErrorMessage.value=error instanceof ApiError?error.message:'消息已加载,但自动标记已读失败'}}
|
||||||
async function load(){loading.value=true;errorMessage.value='';readErrorMessage.value='';try{detail.value=await getMyNotification(String(route.params.notificationId));await markReadIfAllowed()}catch(error){detail.value=null;errorMessage.value=error instanceof ApiError?error.message:'消息加载失败,请稍后重试'}finally{loading.value=false}}
|
async function load(){loading.value=true;errorMessage.value='';readErrorMessage.value='';try{detail.value=await getMyNotification(String(route.params.notificationId));await markReadIfAllowed()}catch(error){detail.value=null;errorMessage.value=error instanceof ApiError?error.message:'消息加载失败,请稍后重试'}finally{loading.value=false}}
|
||||||
onMounted(()=>{void load()})
|
onMounted(()=>{void load()})
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ async function markRead(row: NotificationSummary) {
|
|||||||
if (!canMarkRead.value) return
|
if (!canMarkRead.value) return
|
||||||
try {
|
try {
|
||||||
await markMyNotificationRead(row.id)
|
await markMyNotificationRead(row.id)
|
||||||
await Promise.all([load(), notifications.refreshUnreadCount()])
|
await Promise.all([load(), notifications.refreshUnreadCount(true)])
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorMessage.value = messageOf(error)
|
errorMessage.value = messageOf(error)
|
||||||
}
|
}
|
||||||
@@ -89,7 +89,7 @@ async function markAllRead() {
|
|||||||
markingAll.value = true
|
markingAll.value = true
|
||||||
try {
|
try {
|
||||||
await markAllMyNotificationsRead()
|
await markAllMyNotificationsRead()
|
||||||
await Promise.all([load(), notifications.refreshUnreadCount()])
|
await Promise.all([load(), notifications.refreshUnreadCount(true)])
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorMessage.value = messageOf(error)
|
errorMessage.value = messageOf(error)
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,4 +1,31 @@
|
|||||||
import { apiRequest } from '@/api/http'
|
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> {
|
export interface PageResult<T> {
|
||||||
records: T[]
|
records: T[]
|
||||||
@@ -22,6 +49,7 @@ export interface DeliveryRow {
|
|||||||
driverName: string | null
|
driverName: string | null
|
||||||
palletCount: number
|
palletCount: number
|
||||||
packageCount: number
|
packageCount: number
|
||||||
|
signedPackages: number | null
|
||||||
totalWeightKg: number | null
|
totalWeightKg: number | null
|
||||||
totalVolumeCbm: number | null
|
totalVolumeCbm: number | null
|
||||||
plannedDeliveryAt: string
|
plannedDeliveryAt: string
|
||||||
|
|||||||
@@ -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,6 +18,18 @@ async function importTypeScriptModule(source) {
|
|||||||
return import(`data:text/javascript;base64,${Buffer.from(compiled).toString('base64')}`)
|
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', () => {
|
test('uses only authenticated merchant delivery endpoints without customer scope or mock fallback', () => {
|
||||||
assert.match(apiSource, /method: 'GET'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/)
|
assert.match(apiSource, /method: 'GET'[\s\S]*url: '\/merchant\/v1\/last-leg\/delivery-orders'/)
|
||||||
assert.match(apiSource, /delivery-orders\/\$\{encodeURIComponent\(deliveryNo\)\}/)
|
assert.match(apiSource, /delivery-orders\/\$\{encodeURIComponent\(deliveryNo\)\}/)
|
||||||
@@ -33,7 +45,7 @@ test('uses only authenticated merchant delivery endpoints without customer scope
|
|||||||
test('keeps list, read-only detail and create permissions independent in active routes', () => {
|
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] ?? ''
|
const listRoute = routesSource.match(/path: 'orders\/delivery',[\s\S]*?\n\s*},/)?.[0] ?? ''
|
||||||
assert.match(listRoute, /permission: 'merchant:warehouse:delivery:list'/)
|
assert.match(listRoute, /permission: 'merchant:warehouse:delivery:list'/)
|
||||||
assert.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\/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, /path: 'orders\/delivery\/:deliveryNo'[\s\S]*DeliveryOrderDetailView\.vue[\s\S]*props: true[\s\S]*permission: 'merchant:warehouse:delivery:list'/)
|
||||||
assert.match(routesSource, /orders-delivery-create[\s\S]*keepAlive: false/)
|
assert.match(routesSource, /orders-delivery-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/)
|
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', () => {
|
test('renders a compact customer-readable delivery detail surface', () => {
|
||||||
assert.match(detailSource, /<article class="delivery-detail-surface">/)
|
assert.match(detailSource, /<article class="delivery-detail-surface">/)
|
||||||
assert.match(detailSource, /<el-button link type="primary" @click="backToList"><ArrowLeft[^>]*\/>返回列表<\/el-button>/)
|
assert.match(detailSource, /<el-button link type="primary" @click="backToList"><ArrowLeft[^>]*\/>返回列表<\/el-button>/)
|
||||||
|
|||||||
@@ -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'
|
import type { ClientModuleManifest } from '../types.ts'
|
||||||
|
|
||||||
export const orderManagementModule = {
|
export const orderManagementModule = {
|
||||||
@@ -19,6 +19,7 @@ export const orderManagementModule = {
|
|||||||
component: () => import('./views/InboundOrdersView.vue'),
|
component: () => import('./views/InboundOrdersView.vue'),
|
||||||
release: 'active',
|
release: 'active',
|
||||||
meta: { title: '入库订单列表', description: '查询海外仓入库订单', permission: 'merchant:warehouse:inbound:list' },
|
meta: { title: '入库订单列表', description: '查询海外仓入库订单', permission: 'merchant:warehouse:inbound:list' },
|
||||||
|
navigation: { key: 'orders-inbound', icon: Warehouse },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'orders/inbound/:planNo/detail',
|
path: 'orders/inbound/:planNo/detail',
|
||||||
@@ -34,6 +35,7 @@ export const orderManagementModule = {
|
|||||||
component: () => import('./views/DeliveryOrdersView.vue'),
|
component: () => import('./views/DeliveryOrdersView.vue'),
|
||||||
release: 'active',
|
release: 'active',
|
||||||
meta: { title: '派送订单列表', description: '查询海外仓派送订单', permission: 'merchant:warehouse:delivery:list' },
|
meta: { title: '派送订单列表', description: '查询海外仓派送订单', permission: 'merchant:warehouse:delivery:list' },
|
||||||
|
navigation: { key: 'orders-delivery', icon: Truck },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'orders/delivery/create',
|
path: 'orders/delivery/create',
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
import { computed, onMounted, ref } from 'vue'
|
import { computed, onMounted, ref } from 'vue'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { ArrowLeft } from '@lucide/vue'
|
import { ArrowLeft } from '@lucide/vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
import dayjs from 'dayjs'
|
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'
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
|
|
||||||
const props = defineProps<{ deliveryNo: string }>()
|
const props = defineProps<{ deliveryNo: string }>()
|
||||||
@@ -11,7 +12,16 @@ const router = useRouter()
|
|||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const errorMessage = ref('')
|
const errorMessage = ref('')
|
||||||
const detail = ref<DeliveryOrderDetail | null>(null)
|
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 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 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: '混装' }
|
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 },
|
{ prop: 'volumeCbm', label: '体积(m³)', width: 120, align: 'right', headerAlign: 'right', formatter: tableValueFormatter },
|
||||||
]
|
]
|
||||||
const feeColumns: DataTableColumn[] = [
|
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 },
|
{ 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)
|
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) {
|
function formatDateTime(value: string | null | undefined) {
|
||||||
return value ? dayjs(value).format('YYYY-MM-DD HH:mm') : '—'
|
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 statusLabel(value: string) { return statusLabels[value] ?? display(value) }
|
||||||
function statusTone(value: string) {
|
function statusTone(value: string) {
|
||||||
if (value === 'DELIVERED' || value === 'SIGNED') return 'success'
|
if (value === 'DELIVERED') return 'success'
|
||||||
if (value === 'IN_TRANSIT') return 'primary'
|
if (value === 'DELIVERING') return 'primary'
|
||||||
if (value === 'CANCELLED') return 'danger'
|
if (value === 'CANCELLED' || value === 'REJECTED') return 'danger'
|
||||||
return 'warning'
|
return 'warning'
|
||||||
}
|
}
|
||||||
function mappedLabel(value: string | null | undefined, labels: Record<string, string>) {
|
function mappedLabel(value: string | null | undefined, labels: Record<string, string>) {
|
||||||
@@ -64,6 +79,7 @@ async function loadDetail() {
|
|||||||
errorMessage.value = ''
|
errorMessage.value = ''
|
||||||
try {
|
try {
|
||||||
detail.value = await getDeliveryOrder(props.deliveryNo)
|
detail.value = await getDeliveryOrder(props.deliveryNo)
|
||||||
|
void loadReceipts()
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
detail.value = null
|
detail.value = null
|
||||||
errorMessage.value = error instanceof Error ? error.message : '派送单详情加载失败,请重试'
|
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() {
|
function backToList() {
|
||||||
void router.push({ name: 'orders-delivery' })
|
void router.push({ name: 'orders-delivery' })
|
||||||
}
|
}
|
||||||
@@ -135,6 +187,18 @@ onMounted(loadDetail)
|
|||||||
<DataTable :data="items" :columns="itemColumns" empty-text="暂无货物明细" />
|
<DataTable :data="items" :columns="itemColumns" empty-text="暂无货物明细" />
|
||||||
</section>
|
</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">
|
<section class="delivery-detail-section">
|
||||||
<div class="delivery-detail-section-heading"><h3>费用明细</h3><span>共 {{ detail.fees.length }} 条</span></div>
|
<div class="delivery-detail-section-heading"><h3>费用明细</h3><span>共 {{ detail.fees.length }} 条</span></div>
|
||||||
<DataTable :data="detail.fees" :columns="feeColumns" empty-text="暂无费用明细" />
|
<DataTable :data="detail.fees" :columns="feeColumns" empty-text="暂无费用明细" />
|
||||||
|
|||||||
@@ -19,12 +19,28 @@ const page = ref(1)
|
|||||||
const pageSize = ref(20)
|
const pageSize = ref(20)
|
||||||
const filters = reactive({ documentNo: '', dispatchNo: '', waybillNo: '', status: '', deliveryMethod: '', plannedRange: [] as string[] })
|
const filters = reactive({ documentNo: '', dispatchNo: '', waybillNo: '', status: '', deliveryMethod: '', plannedRange: [] as string[] })
|
||||||
const canCreate = computed(() => auth.hasPermission('merchant:warehouse:delivery:create'))
|
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 = [
|
const statusOptions = [
|
||||||
{ value: 'PENDING', label: '待派送' },
|
{ value: 'WAIT_DELIVERY', label: '待派送' },
|
||||||
{ value: 'IN_TRANSIT', label: '派送中' },
|
{ value: 'DELIVERING', label: '派送中' },
|
||||||
{ value: 'DELIVERED', label: '已送达' },
|
{ value: 'DELIVERED', label: '已签收' },
|
||||||
{ value: 'SIGNED', label: '已签收' },
|
{ value: 'REJECTED', label: '已拒收' },
|
||||||
|
{ value: 'RETURN_PENDING', label: '待退回' },
|
||||||
|
{ value: 'RETURNED', label: '已退回' },
|
||||||
{ value: 'CANCELLED', label: '已取消' },
|
{ value: 'CANCELLED', label: '已取消' },
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -35,14 +51,14 @@ const queryFields: QueryField[] = [
|
|||||||
{ key: 'dispatchNo', label: '排车单号', type: 'input', placeholder: '请输入排车单号' },
|
{ key: 'dispatchNo', label: '排车单号', type: 'input', placeholder: '请输入排车单号' },
|
||||||
{ key: 'waybillNo', label: '运单号', type: 'input', placeholder: '请输入运单号' },
|
{ key: 'waybillNo', label: '运单号', type: 'input', placeholder: '请输入运单号' },
|
||||||
{ key: 'status', label: '派送状态', type: 'select', options: statusOptions },
|
{ 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' },
|
{ key: 'plannedRange', label: '计划时间', type: 'daterange' },
|
||||||
]
|
]
|
||||||
const tableColumns: DataTableColumn[] = [
|
const tableColumns: DataTableColumn[] = [
|
||||||
{ key: 'actions', label: '操作', slotName: 'actions', width: 90, fixed: 'left' }, { prop: 'deliveryNo', label: '派送单号', minWidth: 180 },
|
{ key: 'actions', label: '操作', slotName: 'actions', width: 90, fixed: 'left' }, { prop: 'deliveryNo', label: '派送单号', minWidth: 180 },
|
||||||
{ prop: 'dispatchNo', label: '排车单号', minWidth: 170 }, { prop: 'outboundNo', label: '出库单号', minWidth: 170 },
|
{ prop: 'dispatchNo', label: '排车单号', minWidth: 170 }, { prop: 'outboundNo', label: '出库单号', minWidth: 170 },
|
||||||
{ key: 'status', label: '状态', slotName: 'status', width: 110 }, { prop: 'overseasWarehouseName', label: '海外仓', minWidth: 160 },
|
{ 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 },
|
{ 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 },
|
{ 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) {
|
function statusType(status: string) {
|
||||||
if (status === 'DELIVERED' || status === 'SIGNED') return 'success'
|
if (status === 'DELIVERED') return 'success'
|
||||||
if (status === 'CANCELLED') return 'info'
|
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'
|
return 'primary'
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,18 +98,21 @@ function buildQuery(): DeliveryQuery {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadOrders() {
|
async function loadOrders() {
|
||||||
|
const sequence = ++requestSequence
|
||||||
loading.value = true
|
loading.value = true
|
||||||
errorMessage.value = ''
|
errorMessage.value = ''
|
||||||
try {
|
try {
|
||||||
const result = await listDeliveryOrders(buildQuery())
|
const result = await listDeliveryOrders(buildQuery())
|
||||||
|
if (sequence !== requestSequence) return
|
||||||
records.value = result.records
|
records.value = result.records
|
||||||
total.value = result.total
|
total.value = result.total
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (sequence !== requestSequence) return
|
||||||
records.value = []
|
records.value = []
|
||||||
total.value = 0
|
total.value = 0
|
||||||
errorMessage.value = error instanceof Error ? error.message : '派送单加载失败,请重试'
|
errorMessage.value = error instanceof Error ? error.message : '派送单加载失败,请重试'
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false
|
if (sequence === requestSequence) loading.value = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,17 +4,25 @@ import type { PageResult } from './warehouseServices'
|
|||||||
export interface ReturnInventoryItem {
|
export interface ReturnInventoryItem {
|
||||||
overseasWarehouseId: string; cartonMark: string; sourceBatchNo?: string; status: string; skuCode: string
|
overseasWarehouseId: string; cartonMark: string; sourceBatchNo?: string; status: string; skuCode: string
|
||||||
productNameZh?: string; quantity: number; cartonSkuTypes: number; cartonTotalQuantity: number; receivedAt: string
|
productNameZh?: string; quantity: number; cartonSkuTypes: number; cartonTotalQuantity: number; receivedAt: string
|
||||||
|
relabelledQuantity: number; remainingRelabelQuantity: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ReturnInventorySummaryItem {
|
export interface ReturnInventorySummaryItem {
|
||||||
overseasWarehouseId: string; skuCode: string; productNameZh?: string
|
overseasWarehouseId: string; skuCode: string; productNameZh?: string
|
||||||
availableQuantity: number; cartonQuantity: number; updatedAt: string
|
totalQuantity: number; availableQuantity: number; relabelLockedQuantity: number; cartonQuantity: number; updatedAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ReturnInventoryCartonItem { skuCode: string; productNameZh?: string; quantity: number }
|
export interface ReturnSkuConversion {
|
||||||
|
relabelNo: string; cartonMark: string; oldSkuCode: string; newSkuCode: string; quantity: number
|
||||||
|
status: 'APPLIED' | 'CONFIRMED' | 'REVERSED'; completedAt: string
|
||||||
|
}
|
||||||
|
export interface ReturnInventoryCartonItem {
|
||||||
|
skuCode: string; productNameZh?: string; quantity: number; availableQuantity: number
|
||||||
|
relabelledQuantity: number; remainingRelabelQuantity: number
|
||||||
|
}
|
||||||
|
|
||||||
export interface ReturnInventoryCartonSummary {
|
export interface ReturnInventoryCartonSummary {
|
||||||
cartonMark: string; overseasWarehouseId: string; sourceBatchNo?: string; sourceReturnNo?: string; status: string
|
cartonMark: string; overseasWarehouseId: string; sourceBatchNo?: string; sourceReturnNo?: string; relabelStatus?: string; relabelledQuantity?: number; relabelReservedQuantity?: number; status: string
|
||||||
skuTypes: number; totalQuantity: number; length?: number; width?: number; height?: number; weight?: number; createdAt: string
|
skuTypes: number; totalQuantity: number; length?: number; width?: number; height?: number; weight?: number; createdAt: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +31,8 @@ export function listReturnInventoryCartons(params: Record<string, unknown>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ReturnInventoryCartonDetail {
|
export interface ReturnInventoryCartonDetail {
|
||||||
cartonMark: string; overseasWarehouseId: string; sourceBatchNo?: string; sourceReturnNo?: string; status: string
|
skuConversions: ReturnSkuConversion[]
|
||||||
|
cartonMark: string; overseasWarehouseId: string; sourceBatchNo?: string; sourceReturnNo?: string; relabelStatus?: string; relabelledQuantity?: number; relabelReservedQuantity?: number; status: string
|
||||||
skuTypes: number; totalQuantity: number; length?: number; width?: number; height?: number; weight?: number; receivedAt: string; items: ReturnInventoryCartonItem[]
|
skuTypes: number; totalQuantity: number; length?: number; width?: number; height?: number; weight?: number; receivedAt: string; items: ReturnInventoryCartonItem[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,6 +63,11 @@ export interface ReturnPackingPreview {
|
|||||||
skus: Array<{ skuCode: string; productNameZh?: string; availableQuantity: number }>
|
skus: Array<{ skuCode: string; productNameZh?: string; availableQuantity: number }>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ReturnPackingPlan {
|
||||||
|
planNo: string; customerId: string; overseasWarehouseId: string; returnNos: string[]; mode: string; status: string
|
||||||
|
boxes: Array<{ boxNo?: number; items: Array<{ skuCode: string; quantity: number }>; length: number; width: number; height: number; weight: number }>; remark?: string
|
||||||
|
}
|
||||||
|
|
||||||
export function getReturnPackingPreview(returnNo?: string) {
|
export function getReturnPackingPreview(returnNo?: string) {
|
||||||
return apiRequest<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 } })
|
||||||
}
|
}
|
||||||
@@ -66,3 +80,11 @@ export function mergeReturnInventory(payload: {
|
|||||||
method: 'POST', url: '/pda/v1/last-leg/return-inventory/cartons/merge', data: payload,
|
method: 'POST', url: '/pda/v1/last-leg/return-inventory/cartons/merge', data: payload,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function listReturnPackingPlans(params: Record<string, unknown> = {}) {
|
||||||
|
return apiRequest<PageResult<ReturnPackingPlan>>({ method: 'GET', url: '/merchant/v1/last-leg/return-packing-plans', params })
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createReturnPackingPlan(payload: { returnNos: string[]; mode: string; boxes: ReturnPackingPlan['boxes']; remark?: string; idempotencyKey: string }) {
|
||||||
|
return apiRequest<ReturnPackingPlan>({ method: 'POST', url: '/merchant/v1/last-leg/return-packing-plans', data: payload })
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { apiRequest, apiBlobRequest } from '@/api/http'
|
|||||||
import type { PageResult } from './warehouseServices'
|
import type { PageResult } from './warehouseServices'
|
||||||
|
|
||||||
export interface ReturnOrderSummary {
|
export interface ReturnOrderSummary {
|
||||||
relabelApplications?: Array<{ relabelNo: string; status: string; quantity: number; createdAt: string }>
|
relabelApplications?: Array<{ relabelNo: string; status: string; quantity: number; quantityUnit?: string; createdAt: string }>
|
||||||
returnNo: string; overseasWarehouseId: string; warehouseContactName?: string; warehouseContactPhone?: string; customerReferenceNo?: string; status: string
|
returnNo: string; overseasWarehouseId: string; warehouseContactName?: string; warehouseContactPhone?: string; customerReferenceNo?: string; status: string
|
||||||
skuTypes: number; expectedQuantity: number; receivedQuantity: number; needRelabel: boolean; relabelNo?: string; relabelStatus?: string; createdAt: string
|
skuTypes: number; expectedQuantity: number; receivedQuantity: number; needRelabel: boolean; relabelNo?: string; relabelStatus?: string; createdAt: string
|
||||||
}
|
}
|
||||||
@@ -10,12 +10,18 @@ export interface ReturnOrderItem {
|
|||||||
skuCode: string; productNameZh?: string; expectedQuantity: number; receivedQuantity: number
|
skuCode: string; productNameZh?: string; expectedQuantity: number; receivedQuantity: number
|
||||||
}
|
}
|
||||||
export interface ReturnReceipt {
|
export interface ReturnReceipt {
|
||||||
receiptNo: string; receiptBatchNo: string; palletCode: string; trackingNo?: string; startedBy: 'RETURN_NO' | 'SKU'
|
receiptNo: string; receiptBatchNo: string; palletCode?: string; trackingNo?: string; startedBy: 'RETURN_NO' | 'SKU'
|
||||||
receivedQuantity: number; operatorName?: string; signedAt: string
|
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 }>; length?: number | null; width?: number | null; height?: number | null; weight?: number | null
|
||||||
|
labelRepairRequired?: boolean
|
||||||
}
|
}
|
||||||
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; length?: number; width?: number; height?: number; weight?: number; volumeCbm?: number; items: Array<{ skuCode: string; productNameZh?: string; quantity: number; boxCount: number }> }
|
||||||
export interface ReturnPhoto { fileId: number; fileName: string; contentType: string; sizeBytes: 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 ReturnPackingDetail { planNo?: string; sourceCartonMark: string; targetCartonMark: string; returnNo: string; skuCode: string; quantity: number; createdAt: string }
|
||||||
|
export interface CurrentReturnCarton { carton: import('./returnInventory').ReturnInventoryCartonDetail; ownership: Array<{ returnNo: string; skuCode: string; quantity: number }>; orderQuantity: number; labelStatus: string; canRelabel: boolean; blockReason?: string }
|
||||||
|
export interface ReturnReceiptCarton { receiptNo: string; palletCode?: string; cartonMark: string; countStatus: 'PENDING' | 'CONFIRMED' | 'UNRECORDED'; countedAt?: string; items: ReturnReceipt['items']; length?: number | null; width?: number | null; height?: number | null; weight?: number | null }
|
||||||
|
export interface ReturnOrderDetail { order: ReturnOrderSummary; remark?: string; items: ReturnOrderItem[]; receipts: ReturnReceipt[]; pallets: ReturnPallet[]; photos: ReturnPhoto[]; packingDetails?: ReturnPackingDetail[]; cartons?: ReturnReceiptCarton[]; currentCartons?: CurrentReturnCarton[] }
|
||||||
export interface ReturnOrderCreate {
|
export interface ReturnOrderCreate {
|
||||||
overseasWarehouseId: string; warehouseContactName: string; warehouseContactPhone: string; customerReferenceNo?: string; remark?: string; needRelabel: boolean; idempotencyKey: string
|
overseasWarehouseId: string; warehouseContactName: string; warehouseContactPhone: string; customerReferenceNo?: string; remark?: string; needRelabel: boolean; idempotencyKey: string
|
||||||
items: Array<{ skuCode: string; productNameZh?: string; expectedQuantity: number }>
|
items: Array<{ skuCode: string; productNameZh?: string; expectedQuantity: number }>
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export interface PageResult<T> { records: T[]; page: number; size: number; total
|
|||||||
export interface LastlegOrderSummary { id: string; orderNo: string; inboundCode: string; orderType: string; packageCount: number; overseasWarehouseId?: string }
|
export interface LastlegOrderSummary { id: string; orderNo: string; inboundCode: string; orderType: string; packageCount: number; overseasWarehouseId?: string }
|
||||||
export interface HistoricalOrderSummary { id: string | null; orderNo: string; sourceOrderNo?: string; outboundOrderNo?: string; relabelOrderNo?: string; orderType?: string; status?: string; packageCount?: number }
|
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; reviewedAt?: string; measuredAt?: string; outboundAt?: string; relabelCompletedAt?: string; createdAt: 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 RelabelSummary { relatedBusinessOrderNos?: string[]; operationTypes?: Array<'CARTON_LABEL' | 'SKU_LABEL' | 'CARTON_AND_SKU' | 'RETURN_BULK_SKU_LABEL'>; 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 {
|
export interface RelabelItemDetail {
|
||||||
id: string; skuCode?: string; productNameZh: string; totalPackageCount: number; notifiedPackageCount: number
|
id: string; skuCode?: string; productNameZh: string; totalPackageCount: number; notifiedPackageCount: number
|
||||||
shipmentNo: string; trackingCode?: string; newSkuCode?: string; labelRequirement?: string; remark?: string
|
shipmentNo: string; trackingCode?: string; newSkuCode?: string; labelRequirement?: string; remark?: string
|
||||||
@@ -28,13 +28,16 @@ export interface RelabelDetail {
|
|||||||
export interface DiscardSummary { id: string; discardNo: string; outboundNo?: string; inboundCodes: string; overseasWarehouseId: string; overseasWarehouseName: string; totalPackages: number; totalFee: number; currency: string; status: string; createdAt: string; completedAt?: string }
|
export interface DiscardSummary { id: string; discardNo: string; outboundNo?: string; inboundCodes: string; overseasWarehouseId: string; overseasWarehouseName: string; totalPackages: number; totalFee: number; currency: string; status: string; createdAt: string; completedAt?: string }
|
||||||
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 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 {
|
export interface RelabelInventoryCandidate {
|
||||||
|
cartonSkuItems: Array<{ skuCode: string; quantity: number }>; cartonAvailablePackages: number | string
|
||||||
|
skuConversions?: import('./returnInventory').ReturnSkuConversion[]
|
||||||
|
stockQuantity?: number; inventoryStatus?: string; occupiedRelabelNo?: string; mergedIntoCartonMarks?: string[]; hasOutbound?: boolean
|
||||||
inventoryBalanceId: string; inboundOrderId: string; inboundOrderNo?: string; inboundCode?: string
|
inventoryBalanceId: string; inboundOrderId: string; inboundOrderNo?: string; inboundCode?: string
|
||||||
overseasWarehouseId: string; overseasWarehouseCode?: string; overseasWarehouseName?: string
|
overseasWarehouseId: string; overseasWarehouseCode?: string; overseasWarehouseName?: string
|
||||||
destinationFbaWarehouseCode?: string; destinationFbaWarehouseName?: string; skuCode?: string; productNameZh?: string
|
destinationFbaWarehouseCode?: string; destinationFbaWarehouseName?: string; skuCode?: string; productNameZh?: string
|
||||||
availablePackages: number | string; version: number
|
availablePackages: number | string; version: number
|
||||||
positions: Array<{ positionId: string; palletNo?: string; batchNo?: string; warehouseLocationCode?: string; availablePackages: number }>
|
positions: Array<{ positionId: string; palletNo?: string; batchNo?: string; warehouseLocationCode?: string; availablePackages: number }>
|
||||||
sourceType?: 'INBOUND' | 'RETURN_CARTON'; returnCartonId?: string; cartonMark?: string
|
sourceType?: 'INBOUND' | 'RETURN_CARTON' | 'RETURN_PARCEL'; returnCartonId?: string; cartonMark?: string
|
||||||
skuItems?: Array<{ skuCode: string; newSkuCode?: string; quantity: number; remark?: string }>; relabelledPackages?: number
|
skuItems?: Array<{ skuCode: string; newSkuCode?: string; quantity: number; remark?: string }>; relabelledPackages?: number; relabelledQuantity?: number; relabelReservedQuantity?: number; relabelStatus?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TransferCreate {
|
export interface TransferCreate {
|
||||||
@@ -130,3 +133,8 @@ export function createDiscard(payload: { items: Array<{ orderId?: string; return
|
|||||||
export function cancelDiscard(discardNo: string) {
|
export function cancelDiscard(discardNo: string) {
|
||||||
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/cancel` })
|
return apiRequest<Record<string, unknown>>({ method: 'POST', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/cancel` })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DiscardPhoto { fileId: string; palletNo: string; fileName: string; createdAt: string; submittedAt: string }
|
||||||
|
export function downloadDiscardPhoto(discardNo: string, fileId: string) {
|
||||||
|
return apiBlobRequest({ method: 'GET', url: `/merchant/v1/last-leg/cargo-discards/${encodeURIComponent(discardNo)}/photos/files/${encodeURIComponent(fileId)}/download` })
|
||||||
|
}
|
||||||
|
|||||||
@@ -42,7 +42,10 @@ test('opens warehouse service and return receipt details as dedicated protected
|
|||||||
|
|
||||||
test('returns to the labeling list after a labeling application is submitted', () => {
|
test('returns to the labeling list after a labeling application is submitted', () => {
|
||||||
assert.match(services, /ElMessage\.success\(`\$\{config\.value\.title\}提交成功`\)[\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/)
|
assert.match(services, /ElMessage\.success\(`\$\{config\.value\.title\}提交成功`\)[\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/)
|
||||||
assert.match(services, /uploadReturnRelabelFile\([\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/)
|
// Return-carton sources use the unified relabel application and its file endpoint.
|
||||||
|
assert.match(services, /returnCartonId: item\.returnCartonId/)
|
||||||
|
assert.match(services, /uploadRelabelFile\(created\.application\.relabelNo,[\s\S]*?router\.push\(\{ name: serviceListRouteName\(props\.service\) \}\)/)
|
||||||
|
assert.match(services, /申请已创建,附件待补传/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('keeps overseas warehouse writes behind operation-specific button permissions', () => {
|
test('keeps overseas warehouse writes behind operation-specific button permissions', () => {
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
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('./relabelSkuDisplay.ts', import.meta.url), 'utf8')
|
||||||
|
const js = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const { relabelSkuCodes, relabelSkuCount } = await import(`data:text/javascript;base64,${Buffer.from(js).toString('base64')}`)
|
||||||
|
test('one box with two SKU mappings shows both and counts unique SKUs across boxes', () => {
|
||||||
|
const item = { skuCode: 'FIRST', skuItems: [{ skuCode: 'FIRST' }, { skuCode: 'SECOND' }] }
|
||||||
|
assert.deepEqual(relabelSkuCodes(item), ['FIRST', 'SECOND'])
|
||||||
|
assert.equal(relabelSkuCount([item, { skuCode: 'SECOND' }]), 2)
|
||||||
|
assert.deepEqual(relabelSkuCodes({ skuCode: 'FIRST,SECOND', skuItems: [] }), ['FIRST', 'SECOND'])
|
||||||
|
})
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
interface RelabelSkuSource {
|
||||||
|
skuCode?: string | null
|
||||||
|
skuItems?: Array<{ skuCode: string }> | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function relabelSkuCodes(item: RelabelSkuSource): string[] {
|
||||||
|
const codes = item.skuItems?.length ? item.skuItems.map(line => line.skuCode) : (item.skuCode || '').split(',')
|
||||||
|
return [...new Set(codes.map(code => code.trim()).filter(Boolean))]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function relabelSkuCount(items: RelabelSkuSource[]): number {
|
||||||
|
return new Set(items.flatMap(relabelSkuCodes)).size
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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('./returnReceiptDisplay.ts', import.meta.url), 'utf8')
|
||||||
|
const compiled = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||||
|
const exports = {}
|
||||||
|
new Function('exports', compiled)(exports)
|
||||||
|
|
||||||
|
test('多次签收的字符串箱数按数值累计:三箱加四箱等于七箱', () => {
|
||||||
|
assert.equal(exports.receiptPrintableBoxCount([{ boxCount: '3' }, { boxCount: '4' }]), 7)
|
||||||
|
assert.equal(exports.receiptPrintableBoxCount([{ boxCount: '3', labels: [{}, {}, {}] }, { boxCount: '4', labels: [{}, {}, {}, {}] }]), 7)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('签收箱号只包含箱子和托盘签收,包裹实物记录不重复展示为箱子', () => {
|
||||||
|
const receipts = [{ receiptNo: 'PARCEL-1', unitType: 'PARCEL' }, { receiptNo: 'BOX-1', unitType: 'BOX' }, { receiptNo: 'PALLET-1', unitType: 'PALLET' }]
|
||||||
|
const cartons = [{ receiptNo: 'PARCEL-1', cartonMark: 'RP-1' }, { receiptNo: 'BOX-1', cartonMark: 'RC-1' }, { receiptNo: 'PALLET-1', cartonMark: 'RC-2' }, { receiptNo: 'UNKNOWN', cartonMark: 'RP-UNKNOWN' }]
|
||||||
|
assert.deepEqual(exports.receiptBoxDetails(receipts, cartons).map(item => item.cartonMark), ['RC-1', 'RC-2'])
|
||||||
|
assert.deepEqual(exports.receiptBoxDetails(receipts.slice(0, 1), cartons), [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('volume rounds upward to exactly three decimal places without increasing exact thousandths', () => {
|
||||||
|
for (const [input, expected] of [[0.186624, '0.187'], [0.15, '0.150'], [1.001, '1.001'], [1.00100001, '1.002'], [0.0000001, '0.001'], [0, '0.000'], [null, '—'], [NaN, '—']]) {
|
||||||
|
assert.equal(exports.formatReturnVolume(input), expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('箱子在签收箱号明细展示一次,真实托盘和缺少箱号明细的实物仍保留', () => {
|
||||||
|
const boxes = Array.from({ length: 6 }, (_, index) => ({ cartonMark: `RC-${index}` }))
|
||||||
|
const units = boxes.map(box => ({ unitType: 'BOX', unitCode: box.cartonMark, palletCode: 'PLT-SHARED' }))
|
||||||
|
assert.deepEqual(exports.receiptPhysicalDetails(units, boxes), [])
|
||||||
|
const pallet = { unitType: 'PALLET', unitCode: 'PLT-SHARED', palletCode: 'PLT-SHARED' }
|
||||||
|
const unmatchedBox = { unitType: 'BOX', unitCode: 'RC-UNKNOWN', palletCode: 'PLT-SHARED' }
|
||||||
|
assert.deepEqual(exports.receiptPhysicalDetails([...units, pallet, unmatchedBox], boxes), [pallet, unmatchedBox])
|
||||||
|
assert.deepEqual(exports.receiptPhysicalDetails(units, []), units)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('parcel waybills appear as tracking numbers while generated parcel codes remain physical codes', () => {
|
||||||
|
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'sf561626' }), 'sf561626')
|
||||||
|
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK0123456789ABCDEF' }), '')
|
||||||
|
assert.equal(exports.receiptTrackingNo({ unitType: 'PARCEL', unitCode: 'PK0123456789ABCDEF', trackingNo: ' SF123 ' }), 'SF123')
|
||||||
|
assert.equal(exports.receiptTrackingNo({ unitType: 'PALLET', unitCode: 'PLT123' }), '')
|
||||||
|
})
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { ReturnPallet, ReturnReceipt, ReturnReceiptCarton } from '../api/returnOrders'
|
||||||
|
|
||||||
|
export function receiptPrintableBoxCount(receipts: ReturnReceipt[]) {
|
||||||
|
return receipts.reduce((total, receipt) => total + Number(receipt.labels?.length || receipt.boxCount || 1), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function receiptPhysicalDetails(pallets: ReturnPallet[], boxes: ReturnReceiptCarton[]) {
|
||||||
|
const signedBoxMarks = new Set(boxes.map(box => box.cartonMark))
|
||||||
|
return pallets.filter(unit => unit.unitType !== 'BOX' || !signedBoxMarks.has(unit.unitCode || unit.palletCode))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function receiptBoxDetails(receipts: Pick<ReturnReceipt, 'receiptNo' | 'unitType'>[], cartons: ReturnReceiptCarton[]) {
|
||||||
|
const boxReceiptNos = new Set(receipts.filter(receipt => receipt.unitType === 'BOX' || receipt.unitType === 'PALLET').map(receipt => receipt.receiptNo))
|
||||||
|
return cartons.filter(carton => boxReceiptNos.has(carton.receiptNo))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function receiptTrackingNo(receipt: Pick<ReturnReceipt, 'trackingNo' | 'unitCode' | 'unitType'> | Record<string, unknown>) {
|
||||||
|
const trackingNo = typeof receipt.trackingNo === 'string' ? receipt.trackingNo.trim() : ''
|
||||||
|
if (trackingNo) return trackingNo
|
||||||
|
const code = typeof receipt.unitCode === 'string' ? receipt.unitCode.trim() : ''
|
||||||
|
return receipt.unitType === 'PARCEL' && code && !/^PK[0-9A-F]{16}$/.test(code) ? code : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatReturnVolume(value?: number | null) {
|
||||||
|
if (value == null || !Number.isFinite(value) || value < 0) return '—'
|
||||||
|
// Shift the decimal in text to avoid floating-point over-rounding exact thousandths.
|
||||||
|
const [coefficient, exponent = '0'] = String(value).toLowerCase().split('e')
|
||||||
|
const [integer, fraction = ''] = coefficient!.split('.')
|
||||||
|
const digits = integer! + fraction
|
||||||
|
const cutoff = integer!.length + Number(exponent) + 3
|
||||||
|
const scaled = cutoff <= 0 ? '0' : digits.slice(0, cutoff).padEnd(cutoff, '0')
|
||||||
|
const remainder = cutoff < 0 ? digits : digits.slice(Math.max(0, cutoff))
|
||||||
|
const rounded = BigInt(scaled) + (/[1-9]/.test(remainder) ? 1n : 0n)
|
||||||
|
return `${rounded / 1000n}.${String(rounded % 1000n).padStart(3, '0')}`
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
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('./returnRelabelCandidates.ts', import.meta.url), 'utf8')
|
||||||
|
const js = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const { returnRelabelCandidate } = await import(`data:text/javascript;base64,${Buffer.from(js).toString('base64')}`)
|
||||||
|
const converted = {
|
||||||
|
returnCartonId: '20', cartonMark: 'NEW-BOX', availablePackages: 0, skuItems: [],
|
||||||
|
cartonAvailablePackages: 1, cartonSkuItems: [{ skuCode: 'NEW-A', quantity: 10 }, { skuCode: 'NEW-B', quantity: 5 }],
|
||||||
|
}
|
||||||
|
|
||||||
|
test('carton labeling selects the current box and both converted SKUs', () => {
|
||||||
|
const candidate = returnRelabelCandidate(converted, 'carton')
|
||||||
|
assert.equal(candidate.cartonMark, 'NEW-BOX')
|
||||||
|
assert.equal(candidate.availablePackages, 1)
|
||||||
|
assert.equal(candidate.skuCode, 'NEW-A,NEW-B')
|
||||||
|
assert.deepEqual(candidate.skuItems, converted.cartonSkuItems)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('SKU and combined labeling still exclude completed SKU quantities', () => {
|
||||||
|
for (const mode of ['sku', 'carton_and_sku']) {
|
||||||
|
assert.equal(returnRelabelCandidate(converted, mode).availablePackages, 0)
|
||||||
|
assert.deepEqual(returnRelabelCandidate(converted, mode).skuItems, [])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('an occupied box cannot be selected for carton labeling', () => {
|
||||||
|
assert.equal(returnRelabelCandidate({ ...converted, cartonAvailablePackages: 0 }, 'carton').availablePackages, 0)
|
||||||
|
})
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { RelabelInventoryCandidate } from '../api/warehouseServices'
|
||||||
|
|
||||||
|
export function returnRelabelCandidate(candidate: RelabelInventoryCandidate, mode: string): RelabelInventoryCandidate {
|
||||||
|
if (!candidate.returnCartonId || mode !== 'carton') return candidate
|
||||||
|
return {
|
||||||
|
...candidate,
|
||||||
|
availablePackages: candidate.cartonAvailablePackages,
|
||||||
|
skuItems: candidate.cartonSkuItems,
|
||||||
|
skuCode: candidate.cartonSkuItems.map(item => item.skuCode).join(','),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export function returnRelabelStatusLabel(status?: string) {
|
||||||
|
const labels: Record<string, string> = { UNLABELLED: '未换标', BOUND: '处理中', PROCESSING: '处理中', PARTIALLY_COMPLETED: '部分完成', COMPLETED: '全部完成' }
|
||||||
|
return status ? labels[status] || '—' : '—'
|
||||||
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { returnRelabelStatusLabel } from '../utils/returnRelabelProgress'
|
||||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import { ArrowLeft, Printer } from '@lucide/vue'
|
import { ArrowLeft, Printer, Plus } from '@lucide/vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
import type { TableAction } from '@/components/common/tableActions'
|
import type { TableAction } from '@/components/common/tableActions'
|
||||||
import { ApiError } from '@/api/types'
|
import { ApiError } from '@/api/types'
|
||||||
|
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
||||||
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public'
|
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public'
|
||||||
import {
|
import {
|
||||||
getReturnInventoryCarton,
|
getReturnInventoryCarton,
|
||||||
@@ -18,9 +20,12 @@ import {
|
|||||||
type ReturnInventoryCartonDetail,
|
type ReturnInventoryCartonDetail,
|
||||||
type ReturnInventoryItem,
|
type ReturnInventoryItem,
|
||||||
type ReturnInventorySummaryItem,
|
type ReturnInventorySummaryItem,
|
||||||
|
createReturnPackingPlan,
|
||||||
|
listReturnPackingPlans,
|
||||||
|
type ReturnPackingPlan,
|
||||||
} from '../api/returnInventory'
|
} from '../api/returnInventory'
|
||||||
|
|
||||||
const activeTab = ref<'summary' | 'cartons'>('summary')
|
const activeTab = ref<'summary' | 'cartons' | 'plans'>('summary')
|
||||||
const props = defineProps<{ cartonOnly?: boolean; detailPage?: boolean }>()
|
const props = defineProps<{ cartonOnly?: boolean; detailPage?: boolean }>()
|
||||||
const route = useRoute()
|
const route = useRoute()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
@@ -33,7 +38,7 @@ const warehouses = ref<MerchantWarehouse[]>([])
|
|||||||
const warehouseError = ref('')
|
const warehouseError = ref('')
|
||||||
const warehousesLoading = ref(false)
|
const warehousesLoading = ref(false)
|
||||||
function formatInventoryTime(value?: string) { return value ? value.replace('T', ' ').slice(0, 19) : '—' }
|
function formatInventoryTime(value?: string) { return value ? value.replace('T', ' ').slice(0, 19) : '—' }
|
||||||
function cartonStatusLabel(value: string) { return ({ AVAILABLE: '可用', MERGED: '已合箱', OUTBOUNDED: '已出库' } as Record<string, string>)[value] || '—' }
|
function cartonStatusLabel(value: string) { return ({ PENDING_COUNT: '箱内待清点', AVAILABLE: '可用', MERGED: '已合箱', OUTBOUNDED: '已出库' } as Record<string, string>)[value] || '—' }
|
||||||
function warehouseLabel(warehouseId: string) {
|
function warehouseLabel(warehouseId: string) {
|
||||||
const warehouse = warehouses.value.find(item => String(item.id) === String(warehouseId))
|
const warehouse = warehouses.value.find(item => String(item.id) === String(warehouseId))
|
||||||
return warehouse ? `${warehouse.warehouseName} · ${warehouse.warehouseCode}` : '—'
|
return warehouse ? `${warehouse.warehouseName} · ${warehouse.warehouseCode}` : '—'
|
||||||
@@ -57,6 +62,11 @@ async function loadWarehouses() {
|
|||||||
const summaryRows = ref<ReturnInventorySummaryItem[]>([])
|
const summaryRows = ref<ReturnInventorySummaryItem[]>([])
|
||||||
const cartonRows = ref<ReturnInventoryItem[]>([])
|
const cartonRows = ref<ReturnInventoryItem[]>([])
|
||||||
const cartonSummaryRows = ref<ReturnInventoryCartonSummary[]>([])
|
const cartonSummaryRows = ref<ReturnInventoryCartonSummary[]>([])
|
||||||
|
const packingPlans = ref<ReturnPackingPlan[]>([])
|
||||||
|
const packingPlanTotal = ref(0)
|
||||||
|
const showPackingCreate = ref(false)
|
||||||
|
const packingSaving = ref(false)
|
||||||
|
const packingForm = reactive({ returnNos: '', selectedSkus: {} as Record<string, number>, length: 1, width: 1, height: 1, weight: 1, remark: '' })
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
const cartonDetail = ref<ReturnInventoryCartonDetail>()
|
const cartonDetail = ref<ReturnInventoryCartonDetail>()
|
||||||
const query = reactive({ page: 1, size: 20, overseasWarehouseId: '', skuCode: '', cartonMark: '', status: 'AVAILABLE', returnNo: '' })
|
const query = reactive({ page: 1, size: 20, overseasWarehouseId: '', skuCode: '', cartonMark: '', status: 'AVAILABLE', returnNo: '' })
|
||||||
@@ -72,7 +82,7 @@ const queryFields = computed<QueryField[]>(() => {
|
|||||||
if (activeTab.value === 'cartons') fields.push(
|
if (activeTab.value === 'cartons') fields.push(
|
||||||
{ key: 'cartonMark', label: '箱号 / 箱唛', type: 'input', placeholder: '请输入箱号或箱唛' },
|
{ key: 'cartonMark', label: '箱号 / 箱唛', type: 'input', placeholder: '请输入箱号或箱唛' },
|
||||||
{ key: 'returnNo', label: '退货单号', type: 'input', placeholder: '请输入退货单号' },
|
{ key: 'returnNo', label: '退货单号', type: 'input', placeholder: '请输入退货单号' },
|
||||||
{ key: 'status', label: '箱状态', type: 'select', options: [{ label: '可用', value: 'AVAILABLE' }, { label: '已合箱', value: 'MERGED' }] },
|
{ key: 'status', label: '箱状态', type: 'select', options: [{ label: '箱内待清点', value: 'PENDING_COUNT' }, { label: '可用', value: 'AVAILABLE' }, { label: '已合箱', value: 'MERGED' }] },
|
||||||
)
|
)
|
||||||
return fields
|
return fields
|
||||||
})
|
})
|
||||||
@@ -80,18 +90,36 @@ const summaryColumns: DataTableColumn[] = [
|
|||||||
{ key: 'actions', label: '操作', slotName: 'actions', width: 110, fixed: 'left' },
|
{ key: 'actions', label: '操作', slotName: 'actions', width: 110, fixed: 'left' },
|
||||||
{ key: 'warehouse', label: '海外仓', slotName: 'warehouse', minWidth: 190 },
|
{ key: 'warehouse', label: '海外仓', slotName: 'warehouse', minWidth: 190 },
|
||||||
{ prop: 'skuCode', label: 'SKU', minWidth: 190 }, { prop: 'productNameZh', label: '中文品名', minWidth: 190 },
|
{ prop: 'skuCode', label: 'SKU', minWidth: 190 }, { prop: 'productNameZh', label: '中文品名', minWidth: 190 },
|
||||||
{ prop: 'availableQuantity', label: '可用库存', width: 110, align: 'right' }, { prop: 'cartonQuantity', label: '所在箱数', width: 110, align: 'right' },
|
{ prop: 'totalQuantity', label: '在仓总库存(件)', width: 150, align: 'right' },
|
||||||
|
{ prop: 'availableQuantity', label: '可用库存', width: 110, align: 'right' },
|
||||||
|
{ prop: 'relabelLockedQuantity', label: '换标占用(件)', width: 140, align: 'right' },
|
||||||
|
{ prop: 'cartonQuantity', label: '所在箱数', width: 110, align: 'right' },
|
||||||
{ key: 'time', label: '库存更新时间', slotName: 'time', width: 180 },
|
{ key: 'time', label: '库存更新时间', slotName: 'time', width: 180 },
|
||||||
]
|
]
|
||||||
const cartonItemColumns: DataTableColumn[] = [
|
const cartonItemColumns: DataTableColumn[] = [
|
||||||
{ prop: 'skuCode', label: 'SKU', minWidth: 200 },
|
{ prop: 'skuCode', label: 'SKU', minWidth: 200 },
|
||||||
{ prop: 'productNameZh', label: '中文品名', minWidth: 240 },
|
{ prop: 'productNameZh', label: '中文品名', minWidth: 240 },
|
||||||
{ prop: 'quantity', label: '数量', width: 110, align: 'right', headerAlign: 'right' },
|
{ prop: 'quantity', label: '数量', width: 110, align: 'right', headerAlign: 'right' },
|
||||||
|
{ prop: 'availableQuantity', label: '可用数量(件)', width: 150, align: 'right' },
|
||||||
|
{ prop: 'relabelledQuantity', label: '已换标数量(件)', width: 160, align: 'right' },
|
||||||
|
{ prop: 'remainingRelabelQuantity', label: '剩余可换(件)', width: 150, align: 'right' },
|
||||||
]
|
]
|
||||||
|
const conversionColumns: DataTableColumn[] = [
|
||||||
|
{ prop: 'cartonMark', label: '包裹 / 箱识别码', minWidth: 220 },
|
||||||
|
{ prop: 'relabelNo', label: '换标单号', minWidth: 200 },
|
||||||
|
{ prop: 'oldSkuCode', label: '旧 SKU', minWidth: 180 },
|
||||||
|
{ prop: 'newSkuCode', label: '新 SKU', minWidth: 180 },
|
||||||
|
{ prop: 'quantity', label: '实际换标数量(件)', width: 170, align: 'right' },
|
||||||
|
{ key: 'conversionStatus', label: '状态', slotName: 'conversionStatus', width: 140 },
|
||||||
|
]
|
||||||
|
function conversionStatusLabel(status: string) {
|
||||||
|
return ({ APPLIED: '已换标,待确认', CONFIRMED: '已确认', REVERSED: '已退回冲回' } as Record<string, string>)[status] || '—'
|
||||||
|
}
|
||||||
const cartonSummaryColumns: DataTableColumn[] = [
|
const cartonSummaryColumns: DataTableColumn[] = [
|
||||||
{ key: 'actions', label: '操作', slotName: 'actions', width: 150, fixed: 'left' }, { prop: 'cartonMark', label: '箱号', minWidth: 220 },
|
{ key: 'actions', label: '操作', slotName: 'actions', width: 150, fixed: 'left' }, { prop: 'cartonMark', label: '箱号', minWidth: 220 },
|
||||||
{ key: 'warehouse', label: '海外仓', slotName: 'warehouse', minWidth: 190 }, { prop: 'skuTypes', label: 'SKU 种类', width: 110, align: 'right' },
|
{ key: 'warehouse', label: '海外仓', slotName: 'warehouse', minWidth: 190 }, { prop: 'skuTypes', label: 'SKU 种类', width: 110, align: 'right' },
|
||||||
{ prop: 'totalQuantity', label: '总件数', width: 100, align: 'right' }, { prop: 'sourceReturnNo', label: '来源退货单', minWidth: 210 },
|
{ prop: 'totalQuantity', label: '总件数', width: 100, align: 'right' }, { prop: 'sourceReturnNo', label: '来源退货单', minWidth: 210 },
|
||||||
|
{ key: 'relabelProgress', label: '换标进度', minWidth: 290, slotName: 'relabelProgress' },
|
||||||
{ prop: 'sourceBatchNo', label: '签收批次', minWidth: 180 }, { key: 'dimensions', label: '箱规', slotName: 'dimensions', width: 170 },
|
{ prop: 'sourceBatchNo', label: '签收批次', minWidth: 180 }, { key: 'dimensions', label: '箱规', slotName: 'dimensions', width: 170 },
|
||||||
{ key: 'weight', label: '重量', slotName: 'weight', width: 100 }, { key: 'time', label: '生成时间', slotName: 'time', width: 180 },
|
{ key: 'weight', label: '重量', slotName: 'weight', width: 100 }, { key: 'time', label: '生成时间', slotName: 'time', width: 180 },
|
||||||
]
|
]
|
||||||
@@ -100,6 +128,8 @@ const cartonColumns: DataTableColumn[] = [
|
|||||||
{ key: 'warehouse', label: '海外仓', slotName: 'warehouse', minWidth: 190 }, { prop: 'skuCode', label: 'SKU', minWidth: 180 },
|
{ key: 'warehouse', label: '海外仓', slotName: 'warehouse', minWidth: 190 }, { prop: 'skuCode', label: 'SKU', minWidth: 180 },
|
||||||
{ prop: 'productNameZh', label: '中文品名', minWidth: 180 }, { prop: 'quantity', label: '本箱数量', width: 110, align: 'right' },
|
{ prop: 'productNameZh', label: '中文品名', minWidth: 180 }, { prop: 'quantity', label: '本箱数量', width: 110, align: 'right' },
|
||||||
{ prop: 'cartonSkuTypes', label: 'SKU 种类', width: 110, align: 'right' }, { prop: 'cartonTotalQuantity', label: '总件数', width: 100, align: 'right' },
|
{ prop: 'cartonSkuTypes', label: 'SKU 种类', width: 110, align: 'right' }, { prop: 'cartonTotalQuantity', label: '总件数', width: 100, align: 'right' },
|
||||||
|
{ prop: 'relabelledQuantity', label: '已换标数量(件)', width: 160, align: 'right' },
|
||||||
|
{ prop: 'remainingRelabelQuantity', label: '剩余可换(件)', width: 150, align: 'right' },
|
||||||
{ key: 'status', label: '箱状态', slotName: 'status', width: 100 }, { prop: 'sourceBatchNo', label: '签收批次', minWidth: 180 },
|
{ key: 'status', label: '箱状态', slotName: 'status', width: 100 }, { prop: 'sourceBatchNo', label: '签收批次', minWidth: 180 },
|
||||||
{ key: 'time', label: '生成时间', slotName: 'time', width: 180 },
|
{ key: 'time', label: '生成时间', slotName: 'time', width: 180 },
|
||||||
]
|
]
|
||||||
@@ -122,6 +152,10 @@ async function load() {
|
|||||||
loading.value = true
|
loading.value = true
|
||||||
loadError.value = ''
|
loadError.value = ''
|
||||||
try {
|
try {
|
||||||
|
if (activeTab.value === 'plans') {
|
||||||
|
const page = await listReturnPackingPlans({ page: query.page, size: query.size })
|
||||||
|
packingPlans.value = page.records; packingPlanTotal.value = Number(page.total); total.value = packingPlanTotal.value; return
|
||||||
|
}
|
||||||
if (props.cartonOnly) {
|
if (props.cartonOnly) {
|
||||||
const page = await listReturnInventoryCartons(params(true))
|
const page = await listReturnInventoryCartons(params(true))
|
||||||
cartonSummaryRows.value = page.records
|
cartonSummaryRows.value = page.records
|
||||||
@@ -155,6 +189,18 @@ async function load() {
|
|||||||
function search() { if (query.page === 1) void load(); else query.page = 1 }
|
function search() { if (query.page === 1) void load(); else query.page = 1 }
|
||||||
function resetSearch() { query.status = 'AVAILABLE'; search() }
|
function resetSearch() { query.status = 'AVAILABLE'; search() }
|
||||||
function changeTab() { query.page = 1; void load() }
|
function changeTab() { query.page = 1; void load() }
|
||||||
|
function openPackingCreate() { packingForm.returnNos = ''; packingForm.selectedSkus = {}; packingForm.length = 1; packingForm.width = 1; packingForm.height = 1; packingForm.weight = 1; packingForm.remark = ''; showPackingCreate.value = true }
|
||||||
|
function togglePackingSku(skuCode: string, checked: boolean) { if (checked) packingForm.selectedSkus[skuCode] = 1; else delete packingForm.selectedSkus[skuCode] }
|
||||||
|
async function submitPackingPlan() {
|
||||||
|
const returnNos = packingForm.returnNos.split(/[\s,,]+/).map(item => item.trim()).filter(Boolean)
|
||||||
|
const items = Object.entries(packingForm.selectedSkus).filter(([, quantity]) => Number(quantity) > 0).map(([skuCode, quantity]) => ({ skuCode, quantity: Number(quantity) }))
|
||||||
|
if (!returnNos.length || !items.length) { ElMessage.warning('请填写已完成退货单号并至少选择一个 SKU'); return }
|
||||||
|
packingSaving.value = true
|
||||||
|
try {
|
||||||
|
await createReturnPackingPlan({ returnNos, mode: 'MERGE', boxes: [{ items, length: Number(packingForm.length), width: Number(packingForm.width), height: Number(packingForm.height), weight: Number(packingForm.weight) }], remark: packingForm.remark || undefined, idempotencyKey: createIdempotencyKey() })
|
||||||
|
ElMessage.success('合箱计划已提交审核'); showPackingCreate.value = false; activeTab.value = 'plans'; query.page = 1; await load()
|
||||||
|
} catch (error) { ElMessage.error(error instanceof Error ? error.message : '合箱计划创建失败') } finally { packingSaving.value = false }
|
||||||
|
}
|
||||||
function openSkuCartons(skuCode: string) {
|
function openSkuCartons(skuCode: string) {
|
||||||
query.skuCode = skuCode
|
query.skuCode = skuCode
|
||||||
activeTab.value = 'cartons'
|
activeTab.value = 'cartons'
|
||||||
@@ -217,25 +263,36 @@ onMounted(() => { if (props.detailPage) void Promise.all([loadCartonDetail(), lo
|
|||||||
<template>
|
<template>
|
||||||
<section class="return-inventory-page">
|
<section class="return-inventory-page">
|
||||||
<template v-if="!props.detailPage">
|
<template v-if="!props.detailPage">
|
||||||
<el-tabs v-if="!props.cartonOnly" v-model="activeTab" @tab-change="changeTab"><el-tab-pane label="SKU 汇总库存" name="summary" /><el-tab-pane label="箱号明细" name="cartons" /></el-tabs>
|
<div class="inventory-toolbar"><el-tabs v-if="!props.cartonOnly" v-model="activeTab" @tab-change="changeTab"><el-tab-pane label="SKU 汇总库存" name="summary" /><el-tab-pane label="箱号明细" name="cartons" /><el-tab-pane label="合箱计划" name="plans" /></el-tabs><el-button type="primary" @click="openPackingCreate"><Plus :size="15" />创建合箱计划</el-button></div>
|
||||||
<QueryToolbar v-model="queryModel" layout="grid" :ariaLabel="`${props.cartonOnly ? '退货箱号' : '退货库存'}筛选`" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetSearch" />
|
<QueryToolbar v-model="queryModel" layout="grid" :ariaLabel="`${props.cartonOnly ? '退货箱号' : '退货库存'}筛选`" :fields="queryFields" :search-on-reset="false" @search="search" @reset="resetSearch" />
|
||||||
<el-alert v-if="loadError" :title="loadError" type="error" show-icon :closable="false" />
|
<el-alert v-if="loadError" :title="loadError" type="error" show-icon :closable="false" />
|
||||||
<el-alert v-if="warehouseError" :title="warehouseError" type="warning" show-icon :closable="false"><el-button link type="primary" @click="loadWarehouses">重试加载海外仓</el-button></el-alert>
|
<el-alert v-if="warehouseError" :title="warehouseError" type="warning" show-icon :closable="false"><el-button link type="primary" @click="loadWarehouses">重试加载海外仓</el-button></el-alert>
|
||||||
<div class="return-inventory-table">
|
<div v-if="activeTab === 'plans'" class="return-inventory-table">
|
||||||
|
<el-table :data="packingPlans" v-loading="loading" size="small">
|
||||||
|
<el-table-column prop="planNo" label="计划号" min-width="220" />
|
||||||
|
<el-table-column prop="status" label="状态" width="150"><template #default="{ row }"><el-tag>{{ row.status === 'PENDING_REVIEW' ? '等待平台审核' : row.status === 'READY' ? '待作业' : row.status === 'COMPLETED' ? '已完成' : row.status === 'CANCELLED' ? '已取消' : row.status }}</el-tag></template></el-table-column>
|
||||||
|
<el-table-column prop="returnNos" label="退货单" min-width="300"><template #default="{ row }">{{ row.returnNos.join('、') }}</template></el-table-column>
|
||||||
|
</el-table>
|
||||||
|
<div class="plan-pagination"><el-pagination v-model:current-page="query.page" v-model:page-size="query.size" :total="packingPlanTotal" layout="total, sizes, prev, pager, next" :page-sizes="[20, 50, 100]" /></div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="return-inventory-table">
|
||||||
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="currentRows" :columns="currentColumns" :loading="loading" :total="total" :page-sizes="[20, 50, 100]" :row-actions="rowActions" :empty-text="loadError ? '库存加载失败,请核对权限或重试' : '暂无数据'">
|
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="currentRows" :columns="currentColumns" :loading="loading" :total="total" :page-sizes="[20, 50, 100]" :row-actions="rowActions" :empty-text="loadError ? '库存加载失败,请核对权限或重试' : '暂无数据'">
|
||||||
<template #warehouse="{ row }">{{ warehouseLabel(row.overseasWarehouseId) }}</template>
|
<template #warehouse="{ row }">{{ warehouseLabel(row.overseasWarehouseId) }}</template>
|
||||||
|
<template #relabelProgress="{ row }">{{ returnRelabelStatusLabel(row.relabelStatus) }}|实际完成 {{ row.relabelledQuantity ?? '—' }} 件|处理中占用 {{ row.relabelReservedQuantity ?? '—' }} 件</template>
|
||||||
<template #status="{ row }"><el-tag effect="light">{{ cartonStatusLabel(row.status) }}</el-tag></template>
|
<template #status="{ row }"><el-tag effect="light">{{ cartonStatusLabel(row.status) }}</el-tag></template>
|
||||||
<template #dimensions="{ row }">{{ row.length && row.width && row.height ? `${row.length} × ${row.width} × ${row.height} cm` : '—' }}</template>
|
<template #dimensions="{ row }">{{ row.length && row.width && row.height ? `${row.length} × ${row.width} × ${row.height} cm` : '—' }}</template>
|
||||||
<template #weight="{ row }">{{ row.weight ? `${row.weight} kg` : '—' }}</template>
|
<template #weight="{ row }">{{ row.weight ? `${row.weight} kg` : '—' }}</template>
|
||||||
<template #time="{ row }"><span class="inventory-time">{{ formatInventoryTime(row.updatedAt || row.createdAt || row.receivedAt) }}</span></template>
|
<template #time="{ row }"><span class="inventory-time">{{ formatInventoryTime(row.updatedAt || row.createdAt || row.receivedAt) }}</span></template>
|
||||||
</DataTable>
|
</DataTable>
|
||||||
</div>
|
</div>
|
||||||
|
<el-dialog v-model="showPackingCreate" title="创建合箱计划" width="720px" destroy-on-close><el-form label-width="110px"><el-form-item label="已完成退货单"><el-input v-model="packingForm.returnNos" type="textarea" :rows="2" placeholder="输入退货单号,多个用空格或逗号分隔" /></el-form-item><el-form-item label="合箱 SKU"><div class="packing-sku-grid"><div v-for="item in summaryRows" :key="item.skuCode" class="packing-sku-row"><el-checkbox :model-value="packingForm.selectedSkus[item.skuCode] !== undefined" @change="togglePackingSku(item.skuCode, Boolean($event))">{{ item.skuCode }}</el-checkbox><span>可用 {{ item.availableQuantity }}</span><el-input-number v-if="packingForm.selectedSkus[item.skuCode] !== undefined" v-model="packingForm.selectedSkus[item.skuCode]" :min="1" :max="item.availableQuantity" :controls="false" placeholder="数量" /></div></div></el-form-item><el-form-item label="箱规"><div class="packing-dimensions"><el-input-number v-model="packingForm.length" :min="1" placeholder="长 cm" /><el-input-number v-model="packingForm.width" :min="1" placeholder="宽 cm" /><el-input-number v-model="packingForm.height" :min="1" placeholder="高 cm" /><el-input-number v-model="packingForm.weight" :min="1" placeholder="重量 kg" /></div></el-form-item><el-form-item label="备注"><el-input v-model="packingForm.remark" placeholder="可填写合箱说明" /></el-form-item></el-form><template #footer><el-button @click="showPackingCreate = false">取消</el-button><el-button type="primary" :loading="packingSaving" @click="submitPackingPlan">提交审核</el-button></template></el-dialog>
|
||||||
</template>
|
</template>
|
||||||
<article v-else v-loading="loading" class="carton-detail-surface">
|
<article v-else v-loading="loading" class="carton-detail-surface">
|
||||||
<template v-if="cartonDetail">
|
<template v-if="cartonDetail">
|
||||||
<header class="carton-detail-header"><button type="button" class="carton-detail-back" @click="returnToCartons"><ArrowLeft :size="16" />返回列表</button><div><strong>{{ cartonDetail.cartonMark }}</strong><span>{{ warehouseLabel(cartonDetail.overseasWarehouseId) }} · 退货箱明细</span></div><div class="carton-detail-actions"><el-tag effect="light">{{ cartonStatusLabel(cartonDetail.status) }}</el-tag><el-button type="primary" @click="printLabel(cartonDetail.cartonMark)"><Printer :size="16" />打印箱唛</el-button></div></header>
|
<header class="carton-detail-header"><button type="button" class="carton-detail-back" @click="returnToCartons"><ArrowLeft :size="16" />返回列表</button><div><strong>{{ cartonDetail.cartonMark }}</strong><span>{{ warehouseLabel(cartonDetail.overseasWarehouseId) }} · 退货箱明细</span></div><div class="carton-detail-actions"><el-tag effect="light">{{ cartonStatusLabel(cartonDetail.status) }}</el-tag><el-button type="primary" @click="printLabel(cartonDetail.cartonMark)"><Printer :size="16" />打印箱唛</el-button></div></header>
|
||||||
<section class="carton-detail-section"><h3>箱号概览</h3><dl class="carton-detail-grid"><div><dt>来源退货单</dt><dd>{{ cartonDetail.sourceReturnNo || '—' }}</dd></div><div><dt>签收批次</dt><dd>{{ cartonDetail.sourceBatchNo || '—' }}</dd></div><div><dt>SKU 种类</dt><dd>{{ cartonDetail.skuTypes }}</dd></div><div><dt>箱内总件数</dt><dd>{{ cartonDetail.totalQuantity }}</dd></div><div><dt>箱规</dt><dd>{{ cartonDetail.length && cartonDetail.width && cartonDetail.height ? `${cartonDetail.length} × ${cartonDetail.width} × ${cartonDetail.height} cm` : '—' }}</dd></div><div><dt>重量</dt><dd>{{ cartonDetail.weight ? `${cartonDetail.weight} kg` : '—' }}</dd></div><div><dt>签收时间</dt><dd>{{ formatInventoryTime(cartonDetail.receivedAt) }}</dd></div></dl></section>
|
<section class="carton-detail-section"><h3>箱号概览</h3><dl class="carton-detail-grid"><div><dt>来源退货单</dt><dd>{{ cartonDetail.sourceReturnNo || '—' }}</dd></div><div><dt>签收批次</dt><dd>{{ cartonDetail.sourceBatchNo || '—' }}</dd></div><div><dt>SKU 种类</dt><dd>{{ cartonDetail.skuTypes }}</dd></div><div><dt>箱内总件数</dt><dd>{{ cartonDetail.totalQuantity }}</dd></div><div><dt>箱规</dt><dd>{{ cartonDetail.length && cartonDetail.width && cartonDetail.height ? `${cartonDetail.length} × ${cartonDetail.width} × ${cartonDetail.height} cm` : '—' }}</dd></div><div><dt>重量</dt><dd>{{ cartonDetail.weight ? `${cartonDetail.weight} kg` : '—' }}</dd></div><div><dt>换标进度</dt><dd>{{ returnRelabelStatusLabel(cartonDetail.relabelStatus) }}</dd></div><div><dt>实际完成(件)</dt><dd>{{ cartonDetail.relabelledQuantity ?? '—' }}</dd></div><div><dt>处理中占用(件)</dt><dd>{{ cartonDetail.relabelReservedQuantity ?? '—' }}</dd></div><div><dt>签收时间</dt><dd>{{ formatInventoryTime(cartonDetail.receivedAt) }}</dd></div></dl></section>
|
||||||
<section class="carton-detail-section"><h3>箱内 SKU</h3><DataTable :data="cartonDetail.items" :columns="cartonItemColumns" row-key="skuCode" empty-text="暂无箱内 SKU" /></section>
|
<section class="carton-detail-section"><h3>箱内 SKU</h3><DataTable :data="cartonDetail.items" :columns="cartonItemColumns" row-key="skuCode" empty-text="暂无箱内 SKU" /></section>
|
||||||
|
<section class="carton-detail-section"><h3>SKU 换标明细</h3><DataTable :data="cartonDetail.skuConversions" :columns="conversionColumns" empty-text="暂无 SKU 换标记录"><template #conversionStatus="{ row }">{{ conversionStatusLabel(row.status) }}</template></DataTable></section>
|
||||||
</template>
|
</template>
|
||||||
<div v-else class="carton-detail-error" role="alert"><strong>{{ detailError || '箱号详情加载失败' }}</strong><el-button @click="loadCartonDetail">重新加载</el-button></div>
|
<div v-else class="carton-detail-error" role="alert"><strong>{{ detailError || '箱号详情加载失败' }}</strong><el-button @click="loadCartonDetail">重新加载</el-button></div>
|
||||||
</article>
|
</article>
|
||||||
@@ -243,7 +300,7 @@ onMounted(() => { if (props.detailPage) void Promise.all([loadCartonDetail(), lo
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
.return-inventory-page { display: grid; gap: 12px; } .return-inventory-page :deep(.el-tabs__header) { margin: 0; } .return-inventory-table { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; } .inventory-time { white-space: nowrap; }
|
.return-inventory-page { display: grid; gap: 12px; } .return-inventory-page :deep(.el-tabs__header) { margin: 0; } .inventory-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px}.return-inventory-table { overflow: hidden; border: 1px solid var(--client-border); border-radius: var(--client-radius); background: #fff; } .inventory-time { white-space: nowrap; }.plan-pagination{display:flex;justify-content:flex-end;padding:10px}.packing-sku-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px;width:100%}.packing-sku-row{display:grid;grid-template-columns:minmax(0,1fr) auto 92px;align-items:center;gap:8px;padding:6px 8px;border:1px solid var(--client-border);border-radius:6px}.packing-sku-row>span{color:var(--client-muted);font-size:12px}.packing-dimensions{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;width:100%}
|
||||||
.carton-detail-surface{overflow:hidden;min-height:240px;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff}.carton-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)}.carton-detail-back{display:inline-flex;align-items:center;gap:5px;padding:5px 0;border:0;background:transparent;color:var(--el-color-primary);cursor:pointer}.carton-detail-header>div:nth-child(2){display:flex;min-width:0;flex-direction:column;gap:3px}.carton-detail-header strong{overflow:hidden;color:#1f2d45;font-size:18px;text-overflow:ellipsis;white-space:nowrap}.carton-detail-header span{color:#7c899c;font-size:12px}.carton-detail-actions{display:flex;align-items:center;gap:8px}.carton-detail-section+.carton-detail-section{border-top:1px solid var(--client-border)}.carton-detail-section>h3{display:flex;min-height:40px;align-items:center;margin:0;padding:0 16px;border-bottom:1px solid var(--client-border);background:var(--client-header-bg);font-size:14px}.carton-detail-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:0}.carton-detail-grid div{display:grid;min-height:42px;grid-template-columns:88px minmax(0,1fr);align-items:center;gap:8px;padding:5px 12px;border-right:1px solid var(--client-border);border-bottom:1px solid var(--client-border)}.carton-detail-grid dt{color:var(--client-muted);font-size:12px}.carton-detail-grid dd{margin:0;overflow:hidden;color:var(--client-text);font-size:13px;font-weight:600;text-overflow:ellipsis;white-space:nowrap}@media(max-width:1100px){.carton-detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.carton-detail-header{grid-template-columns:1fr auto}.carton-detail-back{grid-column:1/-1}.carton-detail-grid{grid-template-columns:1fr}}
|
.carton-detail-surface{overflow:hidden;min-height:240px;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff}.carton-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)}.carton-detail-back{display:inline-flex;align-items:center;gap:5px;padding:5px 0;border:0;background:transparent;color:var(--el-color-primary);cursor:pointer}.carton-detail-header>div:nth-child(2){display:flex;min-width:0;flex-direction:column;gap:3px}.carton-detail-header strong{overflow:hidden;color:#1f2d45;font-size:18px;text-overflow:ellipsis;white-space:nowrap}.carton-detail-header span{color:#7c899c;font-size:12px}.carton-detail-actions{display:flex;align-items:center;gap:8px}.carton-detail-section+.carton-detail-section{border-top:1px solid var(--client-border)}.carton-detail-section>h3{display:flex;min-height:40px;align-items:center;margin:0;padding:0 16px;border-bottom:1px solid var(--client-border);background:var(--client-header-bg);font-size:14px}.carton-detail-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:0}.carton-detail-grid div{display:grid;min-height:42px;grid-template-columns:88px minmax(0,1fr);align-items:center;gap:8px;padding:5px 12px;border-right:1px solid var(--client-border);border-bottom:1px solid var(--client-border)}.carton-detail-grid dt{color:var(--client-muted);font-size:12px}.carton-detail-grid dd{margin:0;overflow:hidden;color:var(--client-text);font-size:13px;font-weight:600;text-overflow:ellipsis;white-space:nowrap}@media(max-width:1100px){.carton-detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.carton-detail-header{grid-template-columns:1fr auto}.carton-detail-back{grid-column:1/-1}.carton-detail-grid{grid-template-columns:1fr}}
|
||||||
.carton-detail-error{display:flex;min-height:220px;align-items:center;justify-content:center;gap:12px;color:#b42318}
|
.carton-detail-error{display:flex;min-height:220px;align-items:center;justify-content:center;gap:12px;color:#b42318}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -5,6 +5,45 @@ import test from 'node:test'
|
|||||||
const view = readFileSync(new URL('./ReturnOrdersView.vue', import.meta.url), 'utf8')
|
const view = readFileSync(new URL('./ReturnOrdersView.vue', import.meta.url), 'utf8')
|
||||||
const api = readFileSync(new URL('../api/returnOrders.ts', import.meta.url), 'utf8')
|
const api = readFileSync(new URL('../api/returnOrders.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
|
function submitHarness(failure) {
|
||||||
|
const source = view.slice(view.indexOf('async function submit()'), view.indexOf('\nfunction statusType('))
|
||||||
|
const state = { requests: [], loads: 0, routes: [], errors: [], successes: [] }
|
||||||
|
const form = { overseasWarehouseId: 'WH-1', warehouseContactName: 'Contact', warehouseContactPhone: '123', customerReferenceNo: 'REF-NEW', remark: 'edited', needRelabel: true, items: [{ skuCode: 'SKU-NEW', productNameZh: 'Product', expectedQuantity: 25 }] }
|
||||||
|
const editingReturnNo = { value: 'RT-TEST' }, showCreate = { value: true }, creating = { value: false }
|
||||||
|
const submit = new Function('form', 'duplicateSkuIds', 'creating', 'editingReturnNo', 'showCreate', 'props', 'ElMessage', 'updateReturnOrder', 'createReturnOrder', 'createIdempotencyKey', 'resetForm', 'router', 'load', `${source}; return submit`)(
|
||||||
|
form, { value: new Set() }, creating, editingReturnNo, showCreate, { createPage: false, detailPage: false },
|
||||||
|
{ warning() {}, success(message) { state.successes.push(message) }, error(message) { state.errors.push(message) } },
|
||||||
|
async (returnNo, payload) => { state.requests.push({ returnNo, payload }); if (failure) throw failure },
|
||||||
|
async () => assert.fail('Editing must use update'), () => 'edit-test', () => {},
|
||||||
|
{ async push(route) { state.routes.push(route) } }, async () => { state.loads++ },
|
||||||
|
)
|
||||||
|
return { submit, state, editingReturnNo, showCreate, creating }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('编辑退货保存提交修改后的字段,并重新读取当前列表', async () => {
|
||||||
|
const { submit, state, editingReturnNo, showCreate, creating } = submitHarness()
|
||||||
|
await submit()
|
||||||
|
assert.equal(state.requests[0].returnNo, 'RT-TEST')
|
||||||
|
assert.equal(state.requests[0].payload.customerReferenceNo, 'REF-NEW')
|
||||||
|
assert.equal(state.requests[0].payload.items[0].expectedQuantity, 25)
|
||||||
|
assert.equal(state.loads, 1)
|
||||||
|
assert.deepEqual(state.routes, [])
|
||||||
|
assert.equal(showCreate.value, false)
|
||||||
|
assert.equal(editingReturnNo.value, '')
|
||||||
|
assert.equal(creating.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('编辑退货保存失败显示接口错误并保留编辑内容供重试', async () => {
|
||||||
|
const { submit, state, editingReturnNo, showCreate, creating } = submitHarness(new Error('只有待审核退货预报可以修改'))
|
||||||
|
await submit()
|
||||||
|
assert.deepEqual(state.errors, ['只有待审核退货预报可以修改'])
|
||||||
|
assert.deepEqual(state.successes, [])
|
||||||
|
assert.equal(state.loads, 0)
|
||||||
|
assert.equal(showCreate.value, true)
|
||||||
|
assert.equal(editingReturnNo.value, 'RT-TEST')
|
||||||
|
assert.equal(creating.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
test('退货签收照片通过客户鉴权下载接口加载并释放对象 URL', () => {
|
test('退货签收照片通过客户鉴权下载接口加载并释放对象 URL', () => {
|
||||||
assert.match(api, /\/return-orders\/\$\{encodeURIComponent\(returnNo\)\}\/photos\/files\/\$\{encodeURIComponent\(String\(fileId\)\)\}\/download/)
|
assert.match(api, /\/return-orders\/\$\{encodeURIComponent\(returnNo\)\}\/photos\/files\/\$\{encodeURIComponent\(String\(fileId\)\)\}\/download/)
|
||||||
assert.match(api, /apiBlobRequest/)
|
assert.match(api, /apiBlobRequest/)
|
||||||
@@ -38,6 +77,17 @@ test('新建退货预报使用独立路由页面,编辑仍保留加宽弹框',
|
|||||||
assert.match(view, /class="return-create-actions"[\s\S]*?<el-button type="primary" :loading="creating" @click="submit">提交预报<\/el-button>/)
|
assert.match(view, /class="return-create-actions"[\s\S]*?<el-button type="primary" :loading="creating" @click="submit">提交预报<\/el-button>/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('新建预报居左限宽,联系字段与数量输入保持紧凑', () => {
|
||||||
|
assert.match(view, /return-create-surface \{ width:calc\(100% - 24px\);[^}]*max-width:1120px;[^}]*margin:0 0 0 24px; justify-self:start;/)
|
||||||
|
assert.match(view, /<el-form label-width="130px" class="return-create-form">/)
|
||||||
|
assert.match(view, /return-create-form :deep\(\.el-input\) \{ max-width:320px;/)
|
||||||
|
assert.match(view, /return-create-form :deep\(\.el-select\) \{ max-width:520px;/)
|
||||||
|
assert.match(view, /:deep\(\.el-table \.el-input-number\) \{ width:120px;/)
|
||||||
|
assert.match(view, /<el-table class="return-forecast-table"[^>]*>/)
|
||||||
|
assert.match(view, /return-forecast-table \{[^}]*border-radius:8px;/)
|
||||||
|
assert.match(view, /return-forecast-table :deep\(th.el-table__cell\) \{ height:38px;/)
|
||||||
|
})
|
||||||
|
|
||||||
test('退货列表和详情使用客户可读仓库、状态与时间', () => {
|
test('退货列表和详情使用客户可读仓库、状态与时间', () => {
|
||||||
assert.match(view, /function operationWarehouseLabel\(warehouseId: string\)/)
|
assert.match(view, /function operationWarehouseLabel\(warehouseId: string\)/)
|
||||||
assert.match(view, /return warehouse \? warehouseLabel\(warehouse\) : '未关联'/)
|
assert.match(view, /return warehouse \? warehouseLabel\(warehouse\) : '未关联'/)
|
||||||
@@ -53,10 +103,9 @@ test('退货列表和详情使用客户可读仓库、状态与时间', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('可操作退货表格把操作列固定在最左侧', () => {
|
test('可操作退货表格把操作列固定在最左侧', () => {
|
||||||
const createTable = view.slice(view.indexOf('<el-table :data="form.items"'), view.indexOf('</el-table>', view.indexOf('<el-table :data="form.items"')))
|
|
||||||
assert.match(view, /label: '操作', slotName: 'actions', width: 220, fixed: 'left'/)
|
assert.match(view, /label: '操作', slotName: 'actions', width: 220, fixed: 'left'/)
|
||||||
assert.match(view, /<DataTable[^>]*:row-actions="rowActions"/)
|
assert.match(view, /<DataTable[^>]*:row-actions="rowActions"/)
|
||||||
assert.match(createTable, /^<el-table[\s\S]*?<el-table-column label="操作" width="80" fixed="left">/)
|
assert.match(view, /<el-table class="return-forecast-table"[\s\S]*?<el-table-column label="操作" width="80" fixed="left">/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('分页初始化不会重复请求退货列表', () => {
|
test('分页初始化不会重复请求退货列表', () => {
|
||||||
@@ -74,12 +123,138 @@ test('退货签收详情使用独立路由和紧凑连续页面', () => {
|
|||||||
assert.doesNotMatch(view, /class="return-detail-dialog"/)
|
assert.doesNotMatch(view, /class="return-detail-dialog"/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ReturnInventoryService supplies the 100 mm template; the client must preserve
|
||||||
|
// its page margin (8 mm) and content padding (4 mm), including barcode markup.
|
||||||
|
const labelStyle = '<style>@page{size:100mm 100mm;margin:8mm}.label{width:84mm;height:84mm;padding:4mm;page-break-after:always}.label:last-child{page-break-after:auto}</style>'
|
||||||
|
const labelHtml = mark => `<!doctype html><html><head>${labelStyle}</head><body><div class="label"><p>${mark}</p><svg data-barcode="${mark}"></svg></div></body></html>`
|
||||||
|
|
||||||
|
function printHarness() {
|
||||||
|
const source = view.slice(view.indexOf('async function printReturnLabel('), view.indexOf('\nfunction openDetail('))
|
||||||
|
.replace('receipt: ReturnReceipt | ReturnReceipt[]', 'receipt')
|
||||||
|
const calls = { opened: 0, printed: 0, html: '', warnings: [], errors: [], fetched: [] }
|
||||||
|
const popup = {
|
||||||
|
document: { open() {}, write(html) { calls.html = html }, close() {} },
|
||||||
|
focus() {}, print() { calls.printed += 1 }, close() {},
|
||||||
|
}
|
||||||
|
const print = new Function('window', 'ElMessage', 'getReturnInventoryLabel', `${source}; return printReturnLabel`)(
|
||||||
|
{ open() { calls.opened += 1; return popup } },
|
||||||
|
{ warning(message) { calls.warnings.push(message) }, error(message) { calls.errors.push(message) } },
|
||||||
|
async mark => { calls.fetched.push(mark); return { printableHtml: labelHtml(mark) } },
|
||||||
|
)
|
||||||
|
return { print, calls }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('包裹唛头可按实物识别码打印,不把快递单号或商品件数当作唛头', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
await print({ unitType: 'PARCEL', unitCode: 'PK-PARCEL-1', trackingNo: 'SF-WAYBILL', receivedQuantity: 20 })
|
||||||
|
assert.deepEqual(calls.fetched, ['PK-PARCEL-1'])
|
||||||
|
assert.ok(calls.html.includes('data-barcode="PK-PARCEL-1"'))
|
||||||
|
assert.equal((calls.html.match(/<section class="return-label">/g) || []).length, 1)
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('批量包裹唛头按包裹分页、去重并保留服务端条码模板', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
const parcels = ['PK-PARCEL-1', 'PK-PARCEL-2'].map(mark => ({ unitType: 'PARCEL', unitCode: mark,
|
||||||
|
receivedQuantity: 3, labels: [{ cartonMark: mark, printableHtml: labelHtml(mark) }] }))
|
||||||
|
await print([...parcels, parcels[0]])
|
||||||
|
assert.equal((calls.html.match(/<section class="return-label">/g) || []).length, 2)
|
||||||
|
assert.ok(calls.html.includes('data-barcode="PK-PARCEL-1"'))
|
||||||
|
assert.ok(calls.html.includes('data-barcode="PK-PARCEL-2"'))
|
||||||
|
assert.deepEqual(calls.fetched, [])
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('退货箱唛打印保留服务端整份模板,不另行覆盖纸张或条码', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
const printableHtml = labelHtml('RETURN-TEST-1')
|
||||||
|
await print({ cartonMark: 'RETURN-TEST-1', printableHtml })
|
||||||
|
assert.equal(calls.html, printableHtml)
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.deepEqual(calls.fetched, [])
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('退货多箱打印保留统一模板尺寸和每箱条码,并按箱分页', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
const labels = ['RETURN-TEST-1', 'RETURN-TEST-2'].map(cartonMark => ({ cartonMark, printableHtml: labelHtml(cartonMark) }))
|
||||||
|
await print({ cartonMark: labels[0].cartonMark, labels })
|
||||||
|
assert.equal(calls.html.split(labelStyle).length - 1, 1)
|
||||||
|
assert.equal((calls.html.match(/<html>/g) || []).length, 1)
|
||||||
|
assert.equal((calls.html.match(/<section class="return-label">/g) || []).length, 2)
|
||||||
|
for (const label of labels) assert.ok(calls.html.includes(`<svg data-barcode="${label.cartonMark}"></svg>`))
|
||||||
|
assert.match(calls.html, /\.return-label\{break-after:page\}/)
|
||||||
|
assert.match(calls.html, /\.return-label:last-child\{break-after:auto\}/)
|
||||||
|
assert.match(calls.html, /\.return-label \.label\{page-break-after:auto\}/)
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.deepEqual(calls.fetched, [])
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
assert.match(view, /打印全部箱唛(\{\{ printableBoxCount \}\} 箱)/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('缺少内嵌模板时读取鉴权箱唛模板,待修复箱记录禁止打印', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
await print({ cartonMark: 'RETURN-TEST-1' })
|
||||||
|
assert.deepEqual(calls.fetched, ['RETURN-TEST-1'])
|
||||||
|
assert.ok(calls.html.includes(labelStyle))
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
await print({ cartonMark: 'RETURN-TEST-2', labelRepairRequired: true })
|
||||||
|
assert.equal(calls.opened, 1)
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.deepEqual(calls.fetched, ['RETURN-TEST-1'])
|
||||||
|
assert.equal(calls.warnings.length, 1)
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('两托各两箱合并为一次四页打印,每箱条码保留且模板样式不重复', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
const receipts = [1, 2].map(pallet => ({
|
||||||
|
cartonMark: `PALLET-${pallet}`, boxCount: 2,
|
||||||
|
labels: [1, 2].map(box => ({ cartonMark: `SKU-${pallet}#2-${box}`, printableHtml: labelHtml(`SKU-${pallet}#2-${box}`) })),
|
||||||
|
printableHtml: `batch-${pallet}`,
|
||||||
|
}))
|
||||||
|
await print(receipts)
|
||||||
|
assert.equal(calls.opened, 1)
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.equal((calls.html.match(/<section class="return-label">/g) || []).length, 4)
|
||||||
|
assert.equal(calls.html.split(labelStyle).length - 1, 1)
|
||||||
|
for (const receipt of receipts) for (const label of receipt.labels) assert.ok(calls.html.includes(`data-barcode="${label.cartonMark}"`))
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('同一托盘分两次签收三箱和四箱,打印全部七个独立箱唛', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
const receipts = [3, 4].map((count, batch) => ({
|
||||||
|
palletCode: 'PLT-SHARED', boxCount: String(count),
|
||||||
|
labels: Array.from({ length: count }, (_, index) => ({ cartonMark: `BATCH-${batch}-${index}`, printableHtml: labelHtml(`BATCH-${batch}-${index}`) })),
|
||||||
|
printableHtml: 'old-batch-template',
|
||||||
|
}))
|
||||||
|
await print(receipts)
|
||||||
|
assert.equal((calls.html.match(/<section class="return-label">/g) || []).length, 7)
|
||||||
|
for (const receipt of receipts) for (const label of receipt.labels) assert.ok(calls.html.includes(`data-barcode="${label.cartonMark}"`))
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('打印以完整箱唛列表为准,不使用可能只包含最后一批的汇总模板', async () => {
|
||||||
|
const { print, calls } = printHarness()
|
||||||
|
const labels = Array.from({ length: 7 }, (_, index) => ({ cartonMark: `RC-${index}`, printableHtml: labelHtml(`RC-${index}`) }))
|
||||||
|
await print({ labels, printableHtml: 'last-four-boxes-only' })
|
||||||
|
assert.equal((calls.html.match(/<section class="return-label">/g) || []).length, 7)
|
||||||
|
assert.equal(calls.printed, 1)
|
||||||
|
assert.deepEqual(calls.errors, [])
|
||||||
|
})
|
||||||
|
|
||||||
test('待审核退货可编辑,完成入库后从独立新增页发起贴标', () => {
|
test('待审核退货可编辑,完成入库后从独立新增页发起贴标', () => {
|
||||||
assert.match(view, /row\.status === 'PENDING_REVIEW'.*key: 'edit'/)
|
assert.match(view, /row\.status === 'PENDING_REVIEW'.*key: 'edit'/)
|
||||||
assert.match(view, /await \(editingReturnNo\.value \? updateReturnOrder\(editingReturnNo\.value, payload\) : createReturnOrder\(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, /order\.status === 'COMPLETED' && order\.needRelabel === true/)
|
||||||
assert.match(view, /name: 'overseas-labeling-create'/)
|
assert.match(view, /name: 'overseas-labeling-create'/)
|
||||||
assert.match(view, /query: \{ returnNo: order\.returnNo, warehouseId: String\(order\.overseasWarehouseId\) \}/)
|
assert.match(view, /query: \{ returnNo: order\.returnNo, warehouseId: String\(order\.overseasWarehouseId\)/)
|
||||||
|
assert.match(view, /cartonMark \? \{ cartonMark \}/)
|
||||||
|
assert.match(view, /openRelabel\(selected\.order, current\.carton\.cartonMark\)/)
|
||||||
assert.match(view, /v-for="application in row\.relabelApplications \|\| \[\]"/)
|
assert.match(view, /v-for="application in row\.relabelApplications \|\| \[\]"/)
|
||||||
assert.match(view, /relabelStatusLabel\(application\.status\)/)
|
assert.match(view, /relabelStatusLabel\(application\.status\)/)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||||
import { ElMessage } from 'element-plus'
|
import { ElMessage } from 'element-plus'
|
||||||
import { ArrowLeft, Plus } from '@lucide/vue'
|
import { ArrowLeft, ChevronDown, Plus } from '@lucide/vue'
|
||||||
import { useRoute, useRouter } from 'vue-router'
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
import QueryToolbar, { type QueryField, type QueryModel } from '@/components/common/QueryToolbar.vue'
|
||||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
@@ -10,6 +10,8 @@ import { useAuthStore } from '@/modules/auth/public'
|
|||||||
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public'
|
import { getMerchantWarehouses, type MerchantWarehouse } from '@/modules/first-leg/public'
|
||||||
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
||||||
import { createReturnOrder, downloadReturnPhoto, getReturnOrder, listReturnOrders, updateReturnOrder, type ReturnOrderDetail, type ReturnOrderSummary, type ReturnReceipt } from '../api/returnOrders'
|
import { createReturnOrder, downloadReturnPhoto, getReturnOrder, listReturnOrders, updateReturnOrder, type ReturnOrderDetail, type ReturnOrderSummary, type ReturnReceipt } from '../api/returnOrders'
|
||||||
|
import { getReturnInventoryLabel } from '../api/returnInventory'
|
||||||
|
import { formatReturnVolume, receiptBoxDetails, receiptPhysicalDetails, receiptPrintableBoxCount, receiptTrackingNo } from '../utils/returnReceiptDisplay'
|
||||||
|
|
||||||
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean; returnNo?: string }>(), { createPage: false, detailPage: false, returnNo: '' })
|
const props = withDefaults(defineProps<{ createPage?: boolean; detailPage?: boolean; returnNo?: string }>(), { createPage: false, detailPage: false, returnNo: '' })
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
@@ -23,6 +25,17 @@ const creating = ref(false)
|
|||||||
const showCreate = ref(false)
|
const showCreate = ref(false)
|
||||||
const editingReturnNo = ref('')
|
const editingReturnNo = ref('')
|
||||||
const selected = ref<ReturnOrderDetail>()
|
const selected = ref<ReturnOrderDetail>()
|
||||||
|
const showCartons = ref(false)
|
||||||
|
const parcelDetailsExpanded = ref(true)
|
||||||
|
const receiptBatchesExpanded = ref(true)
|
||||||
|
const signedBoxDetails = computed(() => receiptBoxDetails(selected.value?.receipts || [], selected.value?.cartons || []).map(box => ({
|
||||||
|
...box,
|
||||||
|
measurements: selected.value?.pallets.find(unit => unit.unitType === 'BOX' && (unit.unitCode || unit.palletCode) === box.cartonMark) || (box.length != null || box.width != null || box.height != null || box.weight != null ? { ...box, volumeCbm: box.length != null && box.width != null && box.height != null ? Number(box.length) * Number(box.width) * Number(box.height) / 1_000_000 : null } : undefined),
|
||||||
|
})))
|
||||||
|
const physicalDetails = computed(() => receiptPhysicalDetails(selected.value?.pallets || [], signedBoxDetails.value))
|
||||||
|
const printableReceipts = computed(() => selected.value?.receipts.filter(item => item.unitType !== 'PARCEL' && (item.cartonMark || item.labels?.length)) || [])
|
||||||
|
const parcelReceipts = computed(() => selected.value?.receipts.filter(item => item.unitType === 'PARCEL') || [])
|
||||||
|
const printableBoxCount = computed(() => receiptPrintableBoxCount(printableReceipts.value))
|
||||||
const photoUrls = reactive<Record<string, string>>({})
|
const photoUrls = reactive<Record<string, string>>({})
|
||||||
const rows = ref<ReturnOrderSummary[]>([])
|
const rows = ref<ReturnOrderSummary[]>([])
|
||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
@@ -54,19 +67,22 @@ const tableColumns: DataTableColumn[] = [
|
|||||||
{ key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 180 },
|
{ key: 'createdAt', label: '创建时间', slotName: 'createdAt', width: 180 },
|
||||||
]
|
]
|
||||||
const itemColumns: DataTableColumn[] = [
|
const itemColumns: DataTableColumn[] = [
|
||||||
{ prop: 'skuCode', label: 'SKU', minWidth: 190 },
|
{ prop: 'skuCode', label: 'SKU', width: 300 },
|
||||||
{ prop: 'productNameZh', label: '中文品名', minWidth: 220 },
|
{ prop: 'productNameZh', label: '中文品名', width: 300 },
|
||||||
{ prop: 'expectedQuantity', label: '预报数量', width: 110 },
|
{ prop: 'expectedQuantity', label: '预报数量', width: 200 },
|
||||||
{ prop: 'receivedQuantity', label: '实收数量', width: 110 },
|
{ prop: 'receivedQuantity', label: '实收数量', width: 140 },
|
||||||
|
{ key: 'spacer', label: '', minWidth: 1 },
|
||||||
]
|
]
|
||||||
const receiptColumns: DataTableColumn[] = [
|
const receiptColumns: DataTableColumn[] = [
|
||||||
{ prop: 'receiptBatchNo', label: '批次号', minWidth: 170 },
|
{ prop: 'receiptBatchNo', label: '批次号', minWidth: 145 },
|
||||||
{ prop: 'receiptNo', label: '签收单号', minWidth: 170 },
|
{ prop: 'receiptNo', label: '签收单号', minWidth: 145 },
|
||||||
{ prop: 'palletCode', label: '托盘码', minWidth: 190 },
|
{ key: 'unitType', label: '实物类型', slotName: 'unitType', width: 90 },
|
||||||
{ key: 'trackingNo', label: '快递单号', slotName: 'trackingNo', minWidth: 160 },
|
{ key: 'unitCode', label: '实物编码', slotName: 'unitCode', minWidth: 160 },
|
||||||
{ key: 'startedBy', label: '开始方式', slotName: 'startedBy', width: 110 },
|
{ key: 'trackingNo', label: '快递单号', slotName: 'trackingNo', minWidth: 140 },
|
||||||
{ prop: 'receivedQuantity', label: '实收', width: 90 },
|
{ key: 'startedBy', label: '开始方式', slotName: 'startedBy', width: 100 },
|
||||||
{ key: 'signedAt', label: '签收时间', slotName: 'signedAt', minWidth: 180 },
|
{ 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 }
|
interface SkuDraft { id: number; skuCode: string; productNameZh: string; expectedQuantity: number }
|
||||||
let skuSequence = 0
|
let skuSequence = 0
|
||||||
@@ -172,12 +188,46 @@ function previewPhoto(fileId: string | number) {
|
|||||||
const url = photoUrls[String(fileId)]
|
const url = photoUrls[String(fileId)]
|
||||||
if (url) window.open(url, '_blank', 'noopener')
|
if (url) window.open(url, '_blank', 'noopener')
|
||||||
}
|
}
|
||||||
|
async function printReturnLabel(receipt: ReturnReceipt | ReturnReceipt[]) {
|
||||||
|
const receipts = Array.isArray(receipt) ? receipt : [receipt]
|
||||||
|
if (receipts.some(item => item.labelRepairRequired)) { ElMessage.warning('签收箱数与当前箱记录不一致,请联系仓库核实并修复后打印'); return }
|
||||||
|
if (!receipts.length) return
|
||||||
|
const popup = window.open('', '_blank')
|
||||||
|
if (!popup) { ElMessage.warning('请允许浏览器打开打印窗口'); return }
|
||||||
|
popup.opener = null
|
||||||
|
try {
|
||||||
|
const groups = await Promise.all(receipts.map(async item => {
|
||||||
|
if (item.labels?.length) return await Promise.all(item.labels.map(async label => ({ ...label, printableHtml: label.printableHtml || (await getReturnInventoryLabel(label.cartonMark)).printableHtml })))
|
||||||
|
const mark = item.cartonMark || (item.unitType === 'PARCEL' ? item.unitCode : undefined)
|
||||||
|
return mark ? [{ cartonMark: mark, printableHtml: item.printableHtml || (await getReturnInventoryLabel(mark)).printableHtml }] : []
|
||||||
|
}))
|
||||||
|
const labels = [...new Map(groups.flat().map(label => [label.cartonMark, label])).values()]
|
||||||
|
if (!labels.length) { popup.close(); ElMessage.warning('暂无可打印的唛头'); return }
|
||||||
|
const printStyles = [...new Set(labels.flatMap(label => label.printableHtml.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi) || []))].join('')
|
||||||
|
const printableHtml = (receipts.length === 1 && !receipts[0]?.labels?.length ? receipts[0]?.printableHtml : undefined) || `<!doctype html><html><head><meta charset="utf-8"><title>退货箱唛</title>${printStyles}<style>.return-label{break-after:page}.return-label:last-child{break-after:auto}.return-label .label{page-break-after:auto}</style></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>')
|
||||||
|
const content = contentStart > 0 && bodyEnd > contentStart ? html.slice(contentStart, bodyEnd) : html
|
||||||
|
return `<section class="return-label">${content}</section>`
|
||||||
|
}).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 openDetail(returnNo: string) { void router.push({ name: 'overseas-return-relabel-detail', params: { returnNo } }) }
|
||||||
function returnToList() { void router.push({ name: 'overseas-return-relabel' }) }
|
function returnToList() { void router.push({ name: 'overseas-return-relabel' }) }
|
||||||
function cancelCreate() { resetForm(); void router.push({ name: 'overseas-return-relabel' }) }
|
function cancelCreate() { resetForm(); void router.push({ name: 'overseas-return-relabel' }) }
|
||||||
function canApplyRelabel(order: { status?: unknown; needRelabel?: unknown; relabelNo?: unknown }) { return order.status === 'COMPLETED' && order.needRelabel === true && !order.relabelNo }
|
function canApplyRelabel(order: { status?: unknown; needRelabel?: unknown; relabelNo?: unknown }) { return order.status === 'COMPLETED' && order.needRelabel === true && !order.relabelNo }
|
||||||
function openRelabel(order: Pick<ReturnOrderSummary, 'returnNo' | 'overseasWarehouseId'>) {
|
function openRelabel(order: Pick<ReturnOrderSummary, 'returnNo' | 'overseasWarehouseId'>, cartonMark?: string) {
|
||||||
void router.push({ name: 'overseas-labeling-create', query: { returnNo: order.returnNo, warehouseId: String(order.overseasWarehouseId) } })
|
void router.push({ name: 'overseas-labeling-create', query: { returnNo: order.returnNo, warehouseId: String(order.overseasWarehouseId), ...(cartonMark ? { cartonMark } : {}) } })
|
||||||
}
|
}
|
||||||
async function submit() {
|
async function submit() {
|
||||||
const items = form.items.map(({ skuCode, productNameZh, expectedQuantity }) => ({ skuCode: skuCode.trim(), productNameZh: productNameZh.trim(), expectedQuantity }))
|
const items = form.items.map(({ skuCode, productNameZh, expectedQuantity }) => ({ skuCode: skuCode.trim(), productNameZh: productNameZh.trim(), expectedQuantity }))
|
||||||
@@ -187,8 +237,14 @@ async function submit() {
|
|||||||
creating.value = true
|
creating.value = true
|
||||||
try {
|
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 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 })) }
|
||||||
await (editingReturnNo.value ? updateReturnOrder(editingReturnNo.value, payload) : createReturnOrder(payload))
|
if (editingReturnNo.value) await updateReturnOrder(editingReturnNo.value, payload)
|
||||||
ElMessage.success(editingReturnNo.value ? '退货预报已更新' : '退货预报已创建'); showCreate.value = false; editingReturnNo.value = ''; resetForm(); await router.push({ name: 'overseas-return-relabel' })
|
else await createReturnOrder(payload)
|
||||||
|
const wasEditing = Boolean(editingReturnNo.value)
|
||||||
|
ElMessage.success(wasEditing ? '退货预报已更新' : '退货预报已创建'); showCreate.value = false; editingReturnNo.value = ''; resetForm()
|
||||||
|
if (props.createPage || props.detailPage) await router.push({ name: 'overseas-return-relabel' })
|
||||||
|
else await load()
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error(error instanceof Error ? error.message : '保存退货预报失败')
|
||||||
} finally { creating.value = false }
|
} finally { creating.value = false }
|
||||||
}
|
}
|
||||||
function statusType(status: string, needRelabel = false) {
|
function statusType(status: string, needRelabel = false) {
|
||||||
@@ -204,10 +260,13 @@ function statusLabel(status: string, needRelabel = false) {
|
|||||||
return ({ PENDING_REVIEW: '待审核', PENDING_RECEIPT: '待签收', PARTIALLY_RECEIVED: '部分签收', REJECTED: '已驳回', CANCELLED: '已取消' } as Record<string, string>)[status] ?? (status || '未知状态')
|
return ({ PENDING_REVIEW: '待审核', PENDING_RECEIPT: '待签收', PARTIALLY_RECEIVED: '部分签收', REJECTED: '已驳回', CANCELLED: '已取消' } as Record<string, string>)[status] ?? (status || '未知状态')
|
||||||
}
|
}
|
||||||
function relabelStatusType(status?: string) {
|
function relabelStatusType(status?: string) {
|
||||||
return ({ PENDING_REVIEW: 'warning', PENDING_PROCESSING: 'primary', PROCESSING: 'primary', CUSTOMER_CONFIRM_PENDING: 'warning', COMPLETED: 'success', REJECTED: 'danger', CANCELLED: 'info' } as Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'>)[status || ''] || 'info'
|
return ({ PENDING_REVIEW: 'warning', PENDING_PROCESSING: 'primary', PROCESSING: 'primary', CUSTOMER_CONFIRM_PENDING: 'warning', READY_FOR_OUTBOUND: 'success', COMPLETED: 'success', REJECTED: 'danger', CANCELLED: 'info' } as Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'>)[status || ''] || 'info'
|
||||||
}
|
}
|
||||||
function relabelStatusLabel(status?: string) {
|
function relabelStatusLabel(status?: string) {
|
||||||
return ({ PENDING_REVIEW: '待审核', PENDING_PROCESSING: '待处理', PROCESSING: '处理中', CUSTOMER_CONFIRM_PENDING: '待客户确认', COMPLETED: '已完成', REJECTED: '已驳回', CANCELLED: '已取消' } as Record<string, string>)[status || ''] ?? (status || '—')
|
return ({ PENDING_REVIEW: '待审核', PENDING_PROCESSING: '待处理', PROCESSING: '处理中', CUSTOMER_CONFIRM_PENDING: '待客户确认', READY_FOR_OUTBOUND: '换标完成', COMPLETED: '已完成', REJECTED: '已驳回', CANCELLED: '已取消' } as Record<string, string>)[status || ''] ?? (status || '—')
|
||||||
|
}
|
||||||
|
function relabelQuantityUnit(unit?: string) {
|
||||||
|
return unit === '箱' ? '箱' : '件'
|
||||||
}
|
}
|
||||||
function startedByLabel(startedBy: ReturnReceipt['startedBy']) { return startedBy === 'SKU' ? 'SKU 查询' : '退货单号' }
|
function startedByLabel(startedBy: ReturnReceipt['startedBy']) { return startedBy === 'SKU' ? 'SKU 查询' : '退货单号' }
|
||||||
function formatDateTime(value?: string | null) {
|
function formatDateTime(value?: string | null) {
|
||||||
@@ -237,21 +296,21 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
<el-button @click="returnToList"><ArrowLeft :size="16" />返回列表</el-button>
|
<el-button @click="returnToList"><ArrowLeft :size="16" />返回列表</el-button>
|
||||||
</header>
|
</header>
|
||||||
<div class="return-create-body">
|
<div class="return-create-body">
|
||||||
<el-form label-width="150px" class="return-create-form">
|
<el-form label-width="130px" class="return-create-form">
|
||||||
<el-form-item label="海外仓" required class="return-form-wide"><el-select v-model="form.overseasWarehouseId" filterable clearable :loading="operationWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" @change="selectOperationWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><div v-if="operationWarehousesError" class="warehouse-error">{{ operationWarehousesError }}</div></el-form-item>
|
<el-form-item label="海外仓" required><el-select v-model="form.overseasWarehouseId" filterable clearable :loading="operationWarehousesLoading" :disabled="Boolean(operationWarehousesError)" placeholder="请选择海外仓" @change="selectOperationWarehouse"><el-option v-for="warehouse in operationWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="String(warehouse.id)" /></el-select><div v-if="operationWarehousesError" class="warehouse-error">{{ operationWarehousesError }}</div></el-form-item>
|
||||||
|
<el-form-item label="客户参考号"><el-input v-model="form.customerReferenceNo" placeholder="可填写客户侧参考号" /></el-form-item>
|
||||||
<el-form-item label="海外仓联系人" required><el-input v-model="form.warehouseContactName" :readonly="Boolean(selectedOperationWarehouse?.contactName)" :placeholder="selectedOperationWarehouse?.contactName ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item>
|
<el-form-item label="海外仓联系人" required><el-input v-model="form.warehouseContactName" :readonly="Boolean(selectedOperationWarehouse?.contactName)" :placeholder="selectedOperationWarehouse?.contactName ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item>
|
||||||
<el-form-item label="海外仓联系电话" required><el-input v-model="form.warehouseContactPhone" :readonly="Boolean(selectedOperationWarehouse?.contactPhone)" :placeholder="selectedOperationWarehouse?.contactPhone ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item>
|
<el-form-item label="海外仓联系电话" required><el-input v-model="form.warehouseContactPhone" :readonly="Boolean(selectedOperationWarehouse?.contactPhone)" :placeholder="selectedOperationWarehouse?.contactPhone ? '已从海外仓资料带出' : '该海外仓未维护,请手动填写'" /></el-form-item>
|
||||||
<el-form-item label="客户参考号" class="return-form-wide"><el-input v-model="form.customerReferenceNo" placeholder="可填写客户侧参考号" /></el-form-item>
|
<el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" :rows="2" placeholder="填写退货说明(选填)" /></el-form-item>
|
||||||
<el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" :rows="3" placeholder="填写退货说明(选填)" /></el-form-item>
|
|
||||||
</el-form>
|
</el-form>
|
||||||
<div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div>
|
<div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div>
|
||||||
<div class="return-relabel-option"><span>换标</span><el-checkbox v-model="form.needRelabel">需要换标</el-checkbox></div>
|
<div class="return-relabel-option"><span>是否换标</span><el-radio-group v-model="form.needRelabel" aria-label="是否换标"><el-radio-button :value="false">不换标</el-radio-button><el-radio-button :value="true">需要换标</el-radio-button></el-radio-group></div>
|
||||||
<div class="items-hint">客户只需填写预计退回的 SKU 和数量;快递单号由仓库签收时按实际包裹扫描绑定。</div>
|
<div class="items-hint">客户只需填写预计退回的 SKU 和数量;快递单号由仓库签收时按实际包裹扫描绑定。</div>
|
||||||
<el-table :data="form.items" row-key="id" size="small" border>
|
<el-table class="return-forecast-table" :data="form.items" row-key="id" size="small">
|
||||||
<el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column>
|
<el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column>
|
||||||
<el-table-column label="SKU" min-width="240"><template #default="{ row }"><div><el-input v-model="row.skuCode" :class="{ 'duplicate-sku-input': duplicateSkuIds.has(row.id) }" placeholder="填写 SKU" @blur="row.skuCode = row.skuCode.trim()" /><div v-if="duplicateSkuIds.has(row.id)" class="duplicate-sku-error">该 SKU 已在明细中填写</div></div></template></el-table-column>
|
<el-table-column label="SKU" width="300"><template #default="{ row }"><div><el-input v-model="row.skuCode" :class="{ 'duplicate-sku-input': duplicateSkuIds.has(row.id) }" placeholder="填写 SKU" @blur="row.skuCode = row.skuCode.trim()" /><div v-if="duplicateSkuIds.has(row.id)" class="duplicate-sku-error">该 SKU 已在明细中填写</div></div></template></el-table-column>
|
||||||
<el-table-column label="中文品名" min-width="320"><template #default="{ row }"><el-input v-model="row.productNameZh" placeholder="填写中文品名(选填)" /></template></el-table-column>
|
<el-table-column label="中文品名" min-width="320"><template #default="{ row }"><el-input v-model="row.productNameZh" placeholder="填写中文品名(选填)" /></template></el-table-column>
|
||||||
<el-table-column label="预报数量" width="180"><template #default="{ row }"><el-input-number v-model="row.expectedQuantity" :min="1" controls-position="right" placeholder="数量" /></template></el-table-column>
|
<el-table-column label="预报数量" width="150"><template #default="{ row }"><el-input-number v-model="row.expectedQuantity" :min="1" controls-position="right" placeholder="数量" /></template></el-table-column>
|
||||||
</el-table>
|
</el-table>
|
||||||
</div>
|
</div>
|
||||||
<footer class="return-create-actions"><el-button @click="cancelCreate">取消</el-button><el-button type="primary" :loading="creating" @click="submit">提交预报</el-button></footer>
|
<footer class="return-create-actions"><el-button @click="cancelCreate">取消</el-button><el-button type="primary" :loading="creating" @click="submit">提交预报</el-button></footer>
|
||||||
@@ -259,14 +318,14 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template v-else-if="!props.detailPage">
|
<template v-else-if="!props.detailPage">
|
||||||
<QueryToolbar v-model="queryModel" layout="grid" ariaLabel="退货签收筛选" :fields="queryFields" @search="search" />
|
<QueryToolbar v-model="queryModel" class="return-query" layout="grid" ariaLabel="退货签收筛选" :fields="queryFields" @search="search" />
|
||||||
<div class="return-table-card">
|
<div class="return-table-card">
|
||||||
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[15, 30, 50, 100]" :row-actions="rowActions" row-key="returnNo" empty-text="暂无退货预报">
|
<DataTable v-model:page="query.page" v-model:page-size="query.size" :data="rows" :columns="tableColumns" :loading="loading" :total="total" :page-sizes="[15, 30, 50, 100]" :row-actions="rowActions" row-key="returnNo" empty-text="暂无退货预报">
|
||||||
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新建退货预报</el-button></template>
|
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />新建退货预报</el-button></template>
|
||||||
<template #warehouse="{ row }">{{ operationWarehouseLabel(row.overseasWarehouseId) }}</template>
|
<template #warehouse="{ row }">{{ operationWarehouseLabel(row.overseasWarehouseId) }}</template>
|
||||||
<template #relabel="{ row }"><el-tag v-if="row.needRelabel" type="warning" effect="light">需要换标</el-tag><span v-else>否</span></template>
|
<template #relabel="{ row }"><el-tag v-if="row.needRelabel" type="warning" effect="light">需要换标</el-tag><span v-else>否</span></template>
|
||||||
<template #status="{ row }"><el-tag :type="statusType(row.status, row.needRelabel)" :class="statusClass(row.status, row.needRelabel)" effect="light">{{ statusLabel(row.status, row.needRelabel) }}</el-tag></template>
|
<template #status="{ row }"><el-tag :type="statusType(row.status, row.needRelabel)" :class="statusClass(row.status, row.needRelabel)" effect="light">{{ statusLabel(row.status, row.needRelabel) }}</el-tag></template>
|
||||||
<template #relabelApplications="{ row }"><div v-for="application in row.relabelApplications || []" :key="application.relabelNo" class="relabel-suborder"><span>{{ application.relabelNo }}</span><el-tag :type="relabelStatusType(application.status)" effect="light">{{ relabelStatusLabel(application.status) }}</el-tag><span>{{ application.quantity }} 件</span></div><span v-if="!row.relabelApplications?.length">—</span></template>
|
<template #relabelApplications="{ row }"><div v-for="application in row.relabelApplications || []" :key="application.relabelNo" class="relabel-suborder"><span>{{ application.relabelNo }}</span><el-tag :type="relabelStatusType(application.status)" effect="light">{{ relabelStatusLabel(application.status) }}</el-tag><span>{{ application.quantity }} {{ relabelQuantityUnit(application.quantityUnit) }}</span></div><span v-if="!row.relabelApplications?.length">—</span></template>
|
||||||
<template #createdAt="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
<template #createdAt="{ row }">{{ formatDateTime(row.createdAt) }}</template>
|
||||||
</DataTable>
|
</DataTable>
|
||||||
</div>
|
</div>
|
||||||
@@ -280,7 +339,7 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
<el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" placeholder="填写退货说明(选填)" /></el-form-item>
|
<el-form-item label="备注" class="return-form-wide"><el-input v-model="form.remark" type="textarea" placeholder="填写退货说明(选填)" /></el-form-item>
|
||||||
</el-form>
|
</el-form>
|
||||||
<div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div>
|
<div class="items-title"><span>SKU 预报明细</span><el-button text type="primary" @click="addItem"><Plus :size="15" />添加 SKU</el-button></div>
|
||||||
<div class="return-relabel-option"><span>换标</span><el-checkbox v-model="form.needRelabel">需要换标</el-checkbox></div>
|
<div class="return-relabel-option"><span>是否换标</span><el-radio-group v-model="form.needRelabel" aria-label="是否换标"><el-radio-button :value="false">不换标</el-radio-button><el-radio-button :value="true">需要换标</el-radio-button></el-radio-group></div>
|
||||||
<div class="items-hint">客户只需填写预计退回的 SKU 和数量;快递单号由仓库签收时按实际包裹扫描绑定。</div>
|
<div class="items-hint">客户只需填写预计退回的 SKU 和数量;快递单号由仓库签收时按实际包裹扫描绑定。</div>
|
||||||
<el-table :data="form.items" row-key="id" size="small">
|
<el-table :data="form.items" row-key="id" size="small">
|
||||||
<el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column>
|
<el-table-column label="操作" width="80" fixed="left"><template #default="{ $index }"><el-button link type="danger" :disabled="form.items.length === 1" @click="removeItem($index)">删除</el-button></template></el-table-column>
|
||||||
@@ -312,33 +371,97 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
</div>
|
</div>
|
||||||
<div v-if="selected.remark" class="return-detail-remark"><span>备注</span><strong>{{ selected.remark }}</strong></div>
|
<div v-if="selected.remark" class="return-detail-remark"><span>备注</span><strong>{{ selected.remark }}</strong></div>
|
||||||
</section>
|
</section>
|
||||||
<section class="return-detail-section">
|
<section v-if="selected.order.relabelApplications?.length" class="return-detail-section">
|
||||||
<h3>换标子单({{ selected.order.relabelApplications?.length || 0 }})</h3>
|
<h3>换标子单({{ selected.order.relabelApplications?.length || 0 }})</h3>
|
||||||
<el-table :data="selected.order.relabelApplications || []" empty-text="暂无换标申请">
|
<el-table class="return-aligned-table" :data="selected.order.relabelApplications || []" empty-text="暂无换标申请">
|
||||||
<el-table-column prop="relabelNo" label="换标单号" min-width="220" />
|
<el-table-column prop="relabelNo" label="换标单号" width="300" />
|
||||||
<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 label="状态" width="300"><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 label="本次换标数量" width="200"><template #default="{ row }">{{ row.quantity }} {{ relabelQuantityUnit(row.quantityUnit) }}</template></el-table-column>
|
||||||
|
<el-table-column min-width="1" />
|
||||||
</el-table>
|
</el-table>
|
||||||
</section>
|
</section>
|
||||||
<section class="return-detail-section">
|
<section v-if="selected.items?.length" class="return-detail-section">
|
||||||
<h3>预报与实收</h3>
|
<h3>预报与实收</h3>
|
||||||
<DataTable :data="selected.items" :columns="itemColumns" row-key="skuCode" empty-text="暂无 SKU 明细" />
|
<DataTable class="return-aligned-table" :data="selected.items" :columns="itemColumns" row-key="skuCode" empty-text="暂无 SKU 明细" />
|
||||||
</section>
|
</section>
|
||||||
<section class="return-detail-section">
|
<section v-if="selected.packingDetails?.length" class="return-detail-section">
|
||||||
<h3>打托明细({{ selected.pallets?.length || 0 }} 托)</h3>
|
<h3>合箱明细</h3>
|
||||||
<el-collapse v-if="selected.pallets?.length" class="return-pallet-list">
|
<el-table class="return-aligned-table" :data="selected.packingDetails" size="small">
|
||||||
<el-collapse-item v-for="pallet in selected.pallets" :key="pallet.palletCode" :name="pallet.palletCode">
|
<el-table-column prop="planNo" label="合箱计划" width="240" />
|
||||||
<template #title><strong>{{ pallet.palletCode }}</strong><span class="return-pallet-summary">{{ pallet.skuTypes }} 种 SKU · {{ pallet.totalQuantity }} 件</span></template>
|
<el-table-column prop="sourceCartonMark" label="来源箱唛" width="300" />
|
||||||
|
<el-table-column prop="targetCartonMark" label="目标箱唛" width="300" />
|
||||||
|
<el-table-column prop="skuCode" label="SKU" width="200" />
|
||||||
|
<el-table-column prop="quantity" label="本单装入数量" width="140" />
|
||||||
|
<el-table-column label="合箱时间" width="200"><template #default="{ row }">{{ formatDateTime(row.createdAt) }}</template></el-table-column>
|
||||||
|
<el-table-column min-width="1" />
|
||||||
|
</el-table>
|
||||||
|
</section>
|
||||||
|
<section v-if="selected.receipts?.some(item => item.unitType === 'PARCEL')" class="return-detail-section">
|
||||||
|
<h3 class="section-heading-with-action return-parcel-heading"><span>包裹签收明细</span><span class="return-label-actions"><el-button type="primary" size="small" @click="printReturnLabel(parcelReceipts)">打印包裹唛头({{ parcelReceipts.length }} 个)</el-button><el-button text :aria-expanded="parcelDetailsExpanded" aria-controls="return-parcel-details" @click="parcelDetailsExpanded = !parcelDetailsExpanded">{{ parcelDetailsExpanded ? '收起明细' : '展开明细' }}</el-button></span></h3>
|
||||||
|
<div v-show="parcelDetailsExpanded" id="return-parcel-details">
|
||||||
|
<details v-for="receipt in parcelReceipts" :key="`${receipt.receiptNo}-items`" class="return-parcel-items" open>
|
||||||
|
<summary class="return-parcel-items__head"><div class="return-parcel-items__identity"><strong>包裹 {{ receipt.unitCode || receipt.trackingNo || receipt.receiptNo }}</strong><span class="return-parcel-items__measurements">长 {{ receipt.length ?? '—' }} cm · 宽 {{ receipt.width ?? '—' }} cm · 高 {{ receipt.height ?? '—' }} cm · 体积 {{ formatReturnVolume(receipt.length != null && receipt.width != null && receipt.height != null ? receipt.length * receipt.width * receipt.height / 1_000_000 : null) }} m³ · 重量 {{ receipt.weight ?? '—' }} kg</span></div><span class="return-parcel-items__summary">{{ receipt.receivedQuantity }} 件<ChevronDown :size="16" aria-hidden="true" /></span></summary>
|
||||||
|
<div class="return-parcel-items__list"><div v-for="item in receipt.items" :key="item.skuCode" class="return-parcel-item"><span class="return-parcel-item__sku">{{ item.skuCode }}</span><span class="return-parcel-item__name">{{ item.productNameZh || '中文品名未填写' }}</span><strong>{{ item.quantity }} 件</strong></div></div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section v-if="physicalDetails.length" class="return-detail-section">
|
||||||
|
<h3 class="section-heading-with-action"><span>实物明细({{ physicalDetails.length }} 个托盘/箱)</span><span v-if="printableReceipts.length" class="return-label-actions"><el-button type="primary" size="small" @click="printReturnLabel(printableReceipts)">打印全部箱唛({{ printableBoxCount }} 箱)</el-button></span></h3>
|
||||||
|
<el-collapse v-if="physicalDetails.length" class="return-pallet-list">
|
||||||
|
<el-collapse-item v-for="pallet in physicalDetails" :key="pallet.palletCode" :name="pallet.palletCode">
|
||||||
|
<template #title><strong>{{ pallet.unitType === 'BOX' ? '箱子' : '托盘' }} {{ pallet.unitCode || pallet.palletCode }}</strong><span class="return-pallet-summary">{{ pallet.skuTypes }} 种 SKU · {{ pallet.totalQuantity }} 件 · {{ pallet.totalBoxCount }} 箱 · 体积 {{ formatReturnVolume(pallet.volumeCbm) }} m³</span></template>
|
||||||
|
<div class="return-pallet-measurements">长 {{ pallet.length ?? '—' }} cm · 宽 {{ pallet.width ?? '—' }} cm · 高 {{ pallet.height ?? '—' }} cm · 重量 {{ pallet.weight ?? '—' }} kg</div>
|
||||||
<el-table :data="pallet.items" size="small" border>
|
<el-table :data="pallet.items" size="small" border>
|
||||||
<el-table-column prop="skuCode" label="SKU" min-width="180" />
|
<el-table-column prop="skuCode" label="SKU" min-width="150" />
|
||||||
<el-table-column prop="productNameZh" label="中文品名" min-width="220"><template #default="{ row }">{{ row.productNameZh || '—' }}</template></el-table-column>
|
<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="100" />
|
<el-table-column prop="quantity" label="数量" width="80" />
|
||||||
|
<el-table-column prop="boxCount" label="箱数" width="80" />
|
||||||
</el-table>
|
</el-table>
|
||||||
</el-collapse-item>
|
</el-collapse-item>
|
||||||
</el-collapse>
|
</el-collapse>
|
||||||
<el-empty v-else description="暂无打托记录" :image-size="64" />
|
<el-empty v-else description="暂无打托记录" :image-size="64" />
|
||||||
</section>
|
</section>
|
||||||
|
<section v-if="signedBoxDetails.length" class="return-detail-section">
|
||||||
|
<h3 class="section-heading-with-action"><span>签收箱号明细({{ signedBoxDetails.length }} 箱)</span><span class="return-label-actions"><el-button v-if="!physicalDetails.length && printableReceipts.length" type="primary" size="small" @click="printReturnLabel(printableReceipts)">打印全部箱唛({{ printableBoxCount }} 箱)</el-button><el-button type="primary" size="small" @click="showCartons = true">查看箱号明细</el-button></span></h3>
|
||||||
|
<el-dialog v-model="showCartons" title="签收箱号明细" width="1120px" align-center destroy-on-close>
|
||||||
|
<div class="return-cartons-dialog-body">
|
||||||
|
<el-collapse v-if="signedBoxDetails.length" class="return-pallet-list">
|
||||||
|
<el-collapse-item v-for="box in signedBoxDetails" :key="box.cartonMark" :name="box.cartonMark">
|
||||||
|
<template #title><strong>{{ box.cartonMark }}</strong><span class="return-pallet-summary">{{ box.countStatus === 'CONFIRMED' ? `已确认 · ${box.items.length} 种 SKU · ${box.items.reduce((sum, item) => sum + Number(item.quantity), 0)} 件` : box.countStatus === 'PENDING' ? '待清点' : '未留存箱内签收明细' }}</span></template>
|
||||||
|
<div class="return-pallet-measurements">签收单 {{ box.receiptNo }}<template v-if="box.palletCode"> · 托盘 {{ box.palletCode }}</template><template v-if="box.countedAt"> · 确认时间 {{ formatDateTime(box.countedAt) }}</template></div>
|
||||||
|
<div v-if="box.measurements" class="return-pallet-measurements">长 {{ box.measurements.length ?? '—' }} cm · 宽 {{ box.measurements.width ?? '—' }} cm · 高 {{ box.measurements.height ?? '—' }} cm · 重量 {{ box.measurements.weight ?? '—' }} kg · 体积 {{ formatReturnVolume(box.measurements.volumeCbm) }} m³</div>
|
||||||
|
<el-table v-if="box.countStatus === 'CONFIRMED'" :data="box.items" size="small" border>
|
||||||
|
<el-table-column prop="skuCode" label="SKU" min-width="220" />
|
||||||
|
<el-table-column prop="productNameZh" label="中文品名" min-width="180" />
|
||||||
|
<el-table-column prop="quantity" label="实际签收数量" width="130" />
|
||||||
|
</el-table>
|
||||||
|
<div v-else class="return-pallet-measurements">{{ box.countStatus === 'PENDING' ? '箱内数量待仓库清点确认' : '未留存原始箱内明细,不以当前库存代替签收数量' }}</div>
|
||||||
|
</el-collapse-item>
|
||||||
|
</el-collapse>
|
||||||
|
<el-empty v-else description="暂无签收箱号明细,包裹签收请查看下方 SKU 明细" :image-size="64" />
|
||||||
|
</div>
|
||||||
|
<template #footer><el-button @click="showCartons = false">关闭</el-button></template>
|
||||||
|
</el-dialog>
|
||||||
|
</section>
|
||||||
<section class="return-detail-section">
|
<section class="return-detail-section">
|
||||||
|
<h3>当前关联实物箱</h3>
|
||||||
|
<el-collapse v-if="selected.currentCartons?.length">
|
||||||
|
<el-collapse-item v-for="current in selected.currentCartons" :key="current.carton.cartonMark" :name="current.carton.cartonMark">
|
||||||
|
<template #title>{{ current.carton.cartonMark }} · 整箱 {{ current.carton.totalQuantity }} 件 · 本单 {{ current.orderQuantity }} 件 · {{ current.carton.sourceReturnNo?.includes(',') ? '跨来源单合箱' : '单一来源' }}</template>
|
||||||
|
<p>来源退货单:{{ current.carton.sourceReturnNo }} · 我方箱唛:{{ current.labelStatus === 'CONFIRMED' ? '已确认贴标' : '待贴标确认' }}</p>
|
||||||
|
<el-table :data="current.ownership" border>
|
||||||
|
<el-table-column prop="returnNo" label="来源退货单" min-width="200" />
|
||||||
|
<el-table-column prop="skuCode" label="SKU" min-width="180" />
|
||||||
|
<el-table-column prop="quantity" label="来源贡献数量" width="130" />
|
||||||
|
</el-table>
|
||||||
|
<p>换箱唛以当前实物箱为单位;跨来源单同 SKU 的部分贴标须先现场分拣确认。</p>
|
||||||
|
<el-button v-if="canCreateRelabel" :disabled="!current.canRelabel" @click="openRelabel(selected.order, current.carton.cartonMark)">选择此箱贴标</el-button>
|
||||||
|
<p v-if="!current.canRelabel">{{ current.blockReason }}</p>
|
||||||
|
</el-collapse-item>
|
||||||
|
</el-collapse>
|
||||||
|
<el-empty v-else description="暂无当前关联实物箱" :image-size="64" />
|
||||||
|
</section>
|
||||||
|
<section v-if="selected.photos?.length" class="return-detail-section">
|
||||||
<h3>退货打托照片({{ selected.photos?.length || 0 }} 张)</h3>
|
<h3>退货打托照片({{ selected.photos?.length || 0 }} 张)</h3>
|
||||||
<div v-if="selected.photos?.length" class="return-photo-grid">
|
<div v-if="selected.photos?.length" class="return-photo-grid">
|
||||||
<button v-for="photo in selected.photos" :key="photo.fileId" class="return-photo" type="button" @click="previewPhoto(photo.fileId)">
|
<button v-for="photo in selected.photos" :key="photo.fileId" class="return-photo" type="button" @click="previewPhoto(photo.fileId)">
|
||||||
@@ -349,13 +472,17 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
</div>
|
</div>
|
||||||
<el-empty v-else description="暂无退货打托照片" :image-size="64" />
|
<el-empty v-else description="暂无退货打托照片" :image-size="64" />
|
||||||
</section>
|
</section>
|
||||||
<section class="return-detail-section">
|
<section v-if="selected.receipts?.length" class="return-detail-section">
|
||||||
<h3>签收批次</h3>
|
<h3 class="section-heading-with-action"><span>签收批次</span><span class="return-label-actions"><el-button text :aria-expanded="receiptBatchesExpanded" aria-controls="return-receipt-batches" @click="receiptBatchesExpanded = !receiptBatchesExpanded">{{ receiptBatchesExpanded ? '收起批次' : '展开批次' }}</el-button></span></h3>
|
||||||
|
<div v-show="receiptBatchesExpanded" id="return-receipt-batches">
|
||||||
<DataTable :data="selected.receipts" :columns="receiptColumns" row-key="receiptNo" empty-text="暂无签收批次">
|
<DataTable :data="selected.receipts" :columns="receiptColumns" row-key="receiptNo" empty-text="暂无签收批次">
|
||||||
<template #trackingNo="{ row }">{{ row.trackingNo || '无快递单号' }}</template>
|
<template #unitType="{ row }">{{ row.unitType === 'PALLET' ? '托盘' : row.unitType === 'BOX' ? '箱子' : '包裹' }}</template>
|
||||||
|
<template #unitCode="{ row }">{{ row.unitType === 'PARCEL' && row.unitCode === receiptTrackingNo(row) ? '—' : row.unitCode || '—' }}</template>
|
||||||
|
<template #trackingNo="{ row }">{{ receiptTrackingNo(row) || '无快递单号' }}</template>
|
||||||
<template #startedBy="{ row }">{{ startedByLabel(row.startedBy) }}</template>
|
<template #startedBy="{ row }">{{ startedByLabel(row.startedBy) }}</template>
|
||||||
<template #signedAt="{ row }">{{ formatDateTime(row.signedAt) }}</template>
|
<template #signedAt="{ row }">{{ formatDateTime(row.signedAt) }}</template>
|
||||||
</DataTable>
|
</DataTable>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
</article>
|
</article>
|
||||||
@@ -363,16 +490,37 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
.return-query.query-toolbar--grid { display:grid; grid-template-columns:repeat(4,minmax(0,280px)) max-content; gap:14px 18px; align-items:end; }
|
||||||
|
.return-query :deep(.query-toolbar__filters) { display:contents; }
|
||||||
|
.return-query :deep(.query-toolbar__field) { display:flex; flex-direction:column; align-items:stretch; gap:6px; }
|
||||||
|
.return-query :deep(.query-toolbar__label) { line-height:18px; }
|
||||||
|
.return-query :deep(.query-toolbar__actions) { margin:0; padding:0; border:0; align-self:end; }
|
||||||
|
@media(max-width:1200px) { .return-query.query-toolbar--grid { grid-template-columns:repeat(2,minmax(0,320px)); } }
|
||||||
.relabel-suborder { display: flex; align-items: center; gap: 8px; min-height: 30px; white-space: nowrap; }
|
.relabel-suborder { display: flex; align-items: center; gap: 8px; min-height: 30px; white-space: nowrap; }
|
||||||
.return-orders-page { display:grid; gap:12px; } .return-create-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); column-gap:20px; } .return-form-wide { grid-column:1 / -1; } .items-title { display:flex; justify-content:space-between; align-items:center; margin:16px 0 4px; font-weight:600; } .items-hint { margin-bottom:10px; color:var(--el-text-color-secondary); font-size:12px; } h3 { margin:24px 0 10px; font-size:16px; } h4 { margin:16px 0 8px; font-size:14px; } .remark { white-space:pre-wrap; } .warehouse-error, .duplicate-sku-error { margin-top:6px; color:var(--el-color-danger); font-size:12px; } :deep(.duplicate-sku-input .el-input__wrapper) { box-shadow:0 0 0 1px var(--el-color-danger) inset; } :deep(.el-dialog .el-select) { width:100%; }
|
.return-orders-page { display:grid; gap:12px; } .return-create-form { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); column-gap:20px; } .return-form-wide { grid-column:1 / -1; } .items-title { display:flex; justify-content:space-between; align-items:center; margin:16px 0 4px; font-weight:600; } .items-hint { margin-bottom:10px; color:var(--el-text-color-secondary); font-size:12px; } h3 { margin:24px 0 10px; font-size:16px; } h4 { margin:16px 0 8px; font-size:14px; } .remark { white-space:pre-wrap; } .warehouse-error, .duplicate-sku-error { margin-top:6px; color:var(--el-color-danger); font-size:12px; } :deep(.duplicate-sku-input .el-input__wrapper) { box-shadow:0 0 0 1px var(--el-color-danger) inset; } :deep(.el-dialog .el-select) { width:100%; }
|
||||||
.return-create-surface { overflow:hidden; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; }
|
.return-create-surface { width:calc(100% - 24px); max-width:1120px; min-width:0; margin:0 0 0 24px; justify-self:start; box-sizing:border-box; overflow:hidden; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; }
|
||||||
.return-create-header { display:flex; min-height:68px; align-items:center; justify-content:space-between; gap:20px; padding:12px 20px; border-bottom:1px solid var(--client-border); }
|
.return-create-header { display:flex; min-height:68px; align-items:center; justify-content:space-between; gap:20px; padding:12px 20px; border-bottom:1px solid var(--client-border); }
|
||||||
.return-create-header h2 { margin:0; color:#1f2d45; font-size:20px; }
|
.return-create-header h2 { margin:0; color:#1f2d45; font-size:20px; }
|
||||||
.return-create-header p { margin:4px 0 0; color:#7c899c; font-size:12px; }
|
.return-create-header p { margin:4px 0 0; color:#7c899c; font-size:12px; }
|
||||||
.return-create-body { padding:18px 20px 14px; }
|
.return-create-body { padding:18px 20px 14px; }
|
||||||
.return-create-body :deep(.el-select), .return-create-body :deep(.el-input-number) { width:100%; }
|
.return-create-body :deep(.el-select), .return-create-body :deep(.el-input-number) { width:100%; }
|
||||||
|
.return-create-body .return-create-form { max-width:900px; column-gap:24px; }
|
||||||
|
.return-create-body .return-create-form :deep(.el-form-item) { margin-bottom:16px; }
|
||||||
|
.return-create-body .return-create-form :deep(.el-form-item__content) { min-width:0; }
|
||||||
|
.return-create-body .return-create-form :deep(.el-input) { max-width:320px; }
|
||||||
|
.return-create-body .return-create-form :deep(.el-select) { max-width:520px; }
|
||||||
|
.return-create-body .return-create-form :deep(.el-textarea) { max-width:100%; }
|
||||||
|
.return-create-body :deep(.el-table .el-input-number) { width:120px; }
|
||||||
|
.return-forecast-table { overflow:hidden; border:1px solid var(--client-border); border-radius:8px; --el-table-header-bg-color:#f5f7fb; --el-table-header-text-color:#526176; --el-table-border-color:#edf1f5; --el-table-row-hover-bg-color:#f8faff; }
|
||||||
|
.return-forecast-table :deep(th.el-table__cell) { height:38px; padding:4px 0; font-size:12px; font-weight:600; }
|
||||||
|
.return-forecast-table :deep(td.el-table__cell) { padding:9px 0; }
|
||||||
|
.return-forecast-table :deep(.cell) { padding:0 12px; }
|
||||||
|
.return-forecast-table :deep(.el-input__wrapper) { min-height:30px; box-sizing:border-box; border-radius:6px; }
|
||||||
|
.return-forecast-table :deep(.el-input__inner) { font-size:13px; }
|
||||||
|
.return-forecast-table :deep(.el-button) { font-size:12px; }
|
||||||
.return-create-body .items-title { margin-top:8px; }
|
.return-create-body .items-title { margin-top:8px; }
|
||||||
.return-relabel-option { display:flex; align-items:center; gap:16px; margin:8px 0; color:#526176; }
|
.return-relabel-option { display:flex; align-items:center; gap:16px; margin:12px 0; color:#526176; }
|
||||||
|
.return-relabel-option :deep(.el-radio-button__inner) { min-width:96px; padding:8px 16px; }
|
||||||
.return-create-actions { display:flex; align-items:center; justify-content:flex-end; gap:10px; padding:12px 20px; border-top:1px solid var(--client-border); background:#fbfcfe; }
|
.return-create-actions { display:flex; align-items:center; justify-content:flex-end; gap:10px; padding:12px 20px; border-top:1px solid var(--client-border); background:#fbfcfe; }
|
||||||
.return-table-card { overflow:hidden; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; box-shadow:none; }
|
.return-table-card { overflow:hidden; border:1px solid var(--client-border); border-radius:var(--client-radius); background:#fff; box-shadow:none; }
|
||||||
.return-table-card :deep(.el-table) { width:100%; }
|
.return-table-card :deep(.el-table) { width:100%; }
|
||||||
@@ -388,7 +536,7 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
.return-pagination-total { color:#526176; font-size:14px; }
|
.return-pagination-total { color:#526176; font-size:14px; }
|
||||||
.return-page-size-select { width:112px; margin-left:8px; }
|
.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-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-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-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; }
|
.return-detail-title { display:flex; min-width:0; flex-direction:column; gap:3px; }
|
||||||
@@ -396,19 +544,52 @@ onBeforeUnmount(clearPhotoUrls)
|
|||||||
.return-detail-title span { color:#7c899c; font-size:12px; }
|
.return-detail-title span { color:#7c899c; font-size:12px; }
|
||||||
.return-detail-actions { display:flex; align-items:center; gap:8px; }
|
.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 + .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-parcel-heading { display:grid; grid-template-columns:800px minmax(0,1fr); gap:0; }
|
||||||
|
.return-parcel-heading .return-label-actions { display:grid; grid-template-columns:134px max-content; gap:6px; justify-content:start; }
|
||||||
|
.return-parcel-heading .return-label-actions :deep(.el-button:first-child) { height:auto; min-height:28px; padding:4px 2px; white-space:normal; }
|
||||||
|
.return-parcel-heading .return-label-actions :deep(.el-button:first-child > span) { line-height:16px; }
|
||||||
.return-detail-grid { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); border-top:1px solid #edf1f5; }
|
.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 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 92px; color:#8490a1; font-size:12px; }
|
.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:13px; }
|
.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:10px; padding:10px 14px; background:#f8fafc; }
|
.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-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(.return-aligned-table .cell) { padding:0 14px; text-align:left; }
|
||||||
|
.return-detail-section :deep(.el-table .el-tag) { font-size:12px; }
|
||||||
|
.return-pallet-list { padding:0 14px 10px; }
|
||||||
|
.return-cartons-dialog-body { max-height:65vh; overflow-y:auto; }
|
||||||
.return-pallet-summary { margin-left:12px; color:#7c899c; font-size:12px; font-weight:400; }
|
.return-pallet-summary { margin-left:12px; color:#7c899c; font-size:12px; font-weight:400; }
|
||||||
|
.return-pallet-measurements { margin-bottom:8px; color:#7c899c; font-size:12px; }
|
||||||
.return-photo-grid { display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); gap:12px; padding:0 16px 16px; }
|
.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; }
|
.return-photo { min-width:0; overflow:hidden; padding:0; border:1px solid #dfe6ef; border-radius:6px; color:#526176; background:#fff; cursor:pointer; }
|
||||||
.return-photo img,.return-photo>span { display:flex; width:100%; height:120px; align-items:center; justify-content:center; object-fit:cover; background:#f4f7fb; }
|
.return-photo img,.return-photo>span { display:flex; width:100%; height:120px; align-items:center; justify-content:center; object-fit:cover; background:#f4f7fb; }
|
||||||
.return-photo small { display:block; overflow:hidden; padding:7px; text-overflow:ellipsis; white-space:nowrap; }
|
.return-photo small { display:block; overflow:hidden; padding:7px; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.return-parcel-items { width:calc(100% - 32px); max-width:760px; box-sizing:border-box; margin:8px 16px 12px; overflow:hidden; border:1px solid #dfe6ef; border-radius:8px; background:#fbfcfe; }
|
||||||
|
.return-parcel-items__head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:8px 12px; color:#26364f; font-size:13px; background:#f3f7fc; border-bottom:1px solid #e7edf5; }
|
||||||
|
.return-parcel-items__head span { color:#1764c0; font-size:12px; font-weight:600; }
|
||||||
|
.return-parcel-items__identity { display:flex; align-items:center; flex-wrap:wrap; gap:8px 16px; min-width:0; }
|
||||||
|
.return-parcel-items__identity strong { overflow-wrap:anywhere; }
|
||||||
|
.return-parcel-items__head .return-parcel-items__measurements { color:#7c899c; font-weight:400; }
|
||||||
|
.return-parcel-items__head { cursor:pointer; list-style:none; }
|
||||||
|
.return-parcel-items__head::-webkit-details-marker { display:none; }
|
||||||
|
.return-parcel-items__head:focus-visible { outline:2px solid var(--el-color-primary); outline-offset:-2px; }
|
||||||
|
.return-parcel-items__summary { display:flex; align-items:center; flex-shrink:0; gap:12px; white-space:nowrap; }
|
||||||
|
.return-parcel-items__summary svg { transition:transform .15s ease; }
|
||||||
|
.return-parcel-items:not([open]) .return-parcel-items__summary svg { transform:rotate(-90deg); }
|
||||||
|
.return-parcel-items__list { display:grid; grid-template-columns:minmax(0,1fr); gap:6px; padding:8px; }
|
||||||
|
/* Match the 300px table columns above, accounting for the parcel card's inset and 8px gaps. */
|
||||||
|
.return-parcel-item { display:grid; grid-template-columns:minmax(0,272px) minmax(0,292px) minmax(0,1fr); align-items:center; gap:8px; min-height:32px; box-sizing:border-box; padding:5px 8px; border:1px solid #edf1f5; border-radius:6px; background:#fff; font-size:12px; }
|
||||||
|
.return-parcel-item__sku { min-width:0; overflow-wrap:anywhere; color:#2c3c55; font-weight:600; }
|
||||||
|
.return-parcel-item__name { overflow:hidden; color:#8490a1; font-size:12px; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.return-parcel-item strong { color:#1764c0; white-space:nowrap; }
|
||||||
@media (max-width: 760px) { .return-create-form { grid-template-columns:1fr; } }
|
@media (max-width: 760px) { .return-create-form { grid-template-columns:1fr; } }
|
||||||
@media (max-width: 1100px) { .return-detail-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
|
@media (max-width: 1100px) { .return-detail-grid { grid-template-columns:repeat(2,minmax(0,1fr)); } }
|
||||||
@media (max-width: 900px) { .return-photo-grid { grid-template-columns:repeat(3,minmax(0,1fr)); } }
|
@media (max-width: 900px) { .return-photo-grid { grid-template-columns:repeat(3,minmax(0,1fr)); } }
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ import QueryToolbar, { type QueryField, type QueryModel } from '@/components/com
|
|||||||
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
import DataTable, { type DataTableColumn } from '@/components/common/DataTable.vue'
|
||||||
import type { TableAction } from '@/components/common/tableActions'
|
import type { TableAction } from '@/components/common/tableActions'
|
||||||
import { useAuthStore } from '@/modules/auth/public'
|
import { useAuthStore } from '@/modules/auth/public'
|
||||||
|
import { returnRelabelCandidate } from '../utils/returnRelabelCandidates'
|
||||||
import {
|
import {
|
||||||
createDiscard, createRelabel, createTransfer, getDiscard, getRelabel, getTransfer, resubmitRelabel,
|
createDiscard, createRelabel, createTransfer, getDiscard, getRelabel, getTransfer, resubmitRelabel,
|
||||||
getTransferCartonLabel, submitTransfer, updateTransfer,
|
getTransferCartonLabel, submitTransfer, updateTransfer,
|
||||||
confirmRelabelCompletion, confirmTransferMeasurement, downloadRelabelCompletionPhoto, downloadTransferMeasurementPhoto, uploadRelabelShippingLabel,
|
confirmRelabelCompletion, confirmTransferMeasurement, downloadRelabelCompletionPhoto, downloadTransferMeasurementPhoto, downloadDiscardPhoto, type DiscardPhoto, uploadRelabelShippingLabel,
|
||||||
uploadRelabelFile,
|
uploadRelabelFile,
|
||||||
listDiscards, listRelabelInventoryCandidates, listRelabelHistoricalOrders, listRelabels, listTransfers, cancelDiscard,
|
listDiscards, listRelabelInventoryCandidates, listRelabelHistoricalOrders, listRelabels, listTransfers, cancelDiscard,
|
||||||
type RelabelInventoryCandidate,
|
type RelabelInventoryCandidate,
|
||||||
@@ -26,16 +27,15 @@ import {
|
|||||||
} from '@/modules/first-leg/api/firstLeg'
|
} from '@/modules/first-leg/api/firstLeg'
|
||||||
import { loadAllWarehouseRecords } from '@/modules/first-leg/utils/warehousePagination'
|
import { loadAllWarehouseRecords } from '@/modules/first-leg/utils/warehousePagination'
|
||||||
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
import { createIdempotencyKey } from '@/utils/idempotencyKey'
|
||||||
import { createReturnRelabel, uploadReturnRelabelFile } from '../api/returnOrders'
|
import { relabelSkuCodes, relabelSkuCount } from '../utils/relabelSkuDisplay'
|
||||||
|
|
||||||
type ServiceType = 'labeling' | 'transfer' | 'disposal' | 'relabel'
|
type ServiceType = 'labeling' | 'transfer' | 'disposal' | 'relabel'
|
||||||
type PageMode = 'list' | 'create' | 'edit' | 'detail'
|
type PageMode = 'list' | 'create' | 'edit' | 'detail'
|
||||||
type LabelingMode = 'carton' | 'sku' | 'carton_and_sku'
|
type LabelingMode = 'carton' | 'sku' | 'carton_and_sku'
|
||||||
type RelabelTemplateType = 'carton' | 'sku' | 'mixed'
|
type RelabelTemplateType = 'carton' | 'sku' | 'mixed'
|
||||||
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 CargoRow { id: number; included?: boolean; sku: string; name: string; quantity: number; availableQuantity?: number; sourceOrderId?: string; sourceType?: 'DROPSHIP' | 'RETURN_CARTON' | 'RETURN_PARCEL'; 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 SkuRelabelRow { id: number; sourceRowId: number | null; cartonMark: string; originalSku: string; newSku: string; quantity: number; fbaCartonMark: string; shipmentNo: string; destinationWarehouseId: string; remark: string }
|
||||||
interface ImportedRelabelBinding extends SkuRelabelRow { templateType: RelabelTemplateType; selected: boolean; shipmentNo: string }
|
interface ImportedRelabelBinding extends SkuRelabelRow { templateType: RelabelTemplateType; selected: boolean; shipmentNo: string }
|
||||||
interface ReturnRelabelSkuRow { skuCode: string; productNameZh: string; availableQuantity: number; selected: boolean; quantity: number }
|
|
||||||
interface ServiceConfig { title: string; createTitle: string; numberLabel: string; emptyText: string; columns: string[] }
|
interface ServiceConfig { title: string; createTitle: string; numberLabel: string; emptyText: string; columns: string[] }
|
||||||
interface TransferCarton { cartonMark: string; customerCartonMark?: string; cartonIndex: number; totalCartons: number; status: string }
|
interface TransferCarton { cartonMark: string; customerCartonMark?: string; cartonIndex: number; totalCartons: number; status: string }
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ const canConfirmRelabel = computed(() => auth.hasPermission('merchant:overseas-w
|
|||||||
const canConfirmTransfer = computed(() => auth.hasPermission('merchant:overseas-warehouse:transfer:confirm'))
|
const canConfirmTransfer = computed(() => auth.hasPermission('merchant:overseas-warehouse:transfer:confirm'))
|
||||||
const canCancelDiscard = computed(() => auth.hasPermission('merchant:overseas-warehouse:discard:cancel'))
|
const canCancelDiscard = computed(() => auth.hasPermission('merchant:overseas-warehouse:discard:cancel'))
|
||||||
const configs: Record<ServiceType, ServiceConfig> = {
|
const configs: Record<ServiceType, ServiceConfig> = {
|
||||||
labeling: { title: '贴标申请', createTitle: '新增贴标申请', numberLabel: '贴标申请单号', emptyText: '暂无贴标申请', columns: ['操作', '贴标申请单号', '客户单号', '海外操作仓', '贴标要求', 'SKU 数', '总箱数', '状态', '审核时间', '贴标完成时间', '贴标出库时间', '创建时间'] },
|
labeling: { title: '贴标申请', createTitle: '新增贴标申请', numberLabel: '贴标申请单号', emptyText: '暂无贴标申请', columns: ['操作', '贴标申请单号', '关联业务单号', '海外操作仓', 'SKU 数(种)', '总箱数/包裹', '换标类型', '状态', '审核时间', '贴标完成时间', '贴标出库时间', '创建时间'] },
|
||||||
transfer: { title: '仓储转运单', createTitle: '新增仓储转运单', numberLabel: '转运单号', emptyText: '暂无仓储转运订单', columns: ['操作', '转运单号', '箱数', '海外仓', 'FBA 目的仓', '入仓方式', '是否换标', '换标单号', '换标状态', '状态', '审核时间', '测量时间', '出库时间', '创建时间'] },
|
transfer: { title: '仓储转运单', createTitle: '新增仓储转运单', numberLabel: '转运单号', emptyText: '暂无仓储转运订单', columns: ['操作', '转运单号', '箱数', '海外仓', 'FBA 目的仓', '入仓方式', '是否换标', '换标单号', '换标状态', '状态', '审核时间', '测量时间', '出库时间', '创建时间'] },
|
||||||
disposal: { title: '货物废弃', createTitle: '新增货物废弃申请', numberLabel: '废弃申请单号', emptyText: '暂无货物废弃申请', columns: ['操作', '废弃申请单号', '废弃出库单号', '进仓编号', '操作仓', 'SKU 汇总', '废弃数量', '预估费用', '状态', '废弃完成时间', '创建时间'] },
|
disposal: { title: '货物废弃', createTitle: '新增货物废弃申请', numberLabel: '废弃申请单号', emptyText: '暂无货物废弃申请', columns: ['操作', '废弃申请单号', '废弃出库单号', '进仓编号', '操作仓', 'SKU 汇总', '废弃数量', '预估费用', '状态', '废弃完成时间', '创建时间'] },
|
||||||
relabel: { title: '退货换标', createTitle: '新建退货换标单', numberLabel: '退货换标单号', emptyText: '暂无退货换标订单', columns: ['操作', '退货换标单号', '来源 FBA 仓', '目的 FBA 仓', 'SKU 汇总', '退件总数', '是否换标', '换标状态', '尾程状态', '审核时间', '测量时间', '出库时间', '创建时间'] },
|
relabel: { title: '退货换标', createTitle: '新建退货换标单', numberLabel: '退货换标单号', emptyText: '暂无退货换标订单', columns: ['操作', '退货换标单号', '来源 FBA 仓', '目的 FBA 仓', 'SKU 汇总', '退件总数', '是否换标', '换标状态', '尾程状态', '审核时间', '测量时间', '出库时间', '创建时间'] },
|
||||||
@@ -119,6 +119,7 @@ const editingTransferNo = ref('')
|
|||||||
interface TransferPallet { id?: string | number; sequenceNo?: number; palletNo?: string; warehouseLocationCode?: string; cartonCount?: number; lengthCm?: number; widthCm?: number; heightCm?: number; grossWeightKg?: number; volumeCbm?: number; status?: string; completedAt?: string }
|
interface TransferPallet { id?: string | number; sequenceNo?: number; palletNo?: string; warehouseLocationCode?: string; cartonCount?: number; lengthCm?: number; widthCm?: number; heightCm?: number; grossWeightKg?: number; volumeCbm?: number; status?: string; completedAt?: string }
|
||||||
interface TransferMeasurementPhoto { fileId: string | number; fileName?: string; contentType?: string; sizeBytes?: number; uploadedAt?: string }
|
interface TransferMeasurementPhoto { fileId: string | number; fileName?: string; contentType?: string; sizeBytes?: number; uploadedAt?: string }
|
||||||
interface ServiceDetail extends Record<string, unknown> {
|
interface ServiceDetail extends Record<string, unknown> {
|
||||||
|
discardNo?: string; photos?: DiscardPhoto[]
|
||||||
transferNo?: string; status?: string; operatingWarehouseId?: string; fbaWarehouseCode?: string
|
transferNo?: string; status?: string; operatingWarehouseId?: string; fbaWarehouseCode?: string
|
||||||
destinationType?: 'NONE' | 'FBA' | 'PRIVATE'; destinationWarehouseCode?: string; destinationWarehouseName?: string
|
destinationType?: 'NONE' | 'FBA' | 'PRIVATE'; destinationWarehouseCode?: string; destinationWarehouseName?: string
|
||||||
privateDestinationAddress?: string; privateDestinationPostalCode?: string; privateDestinationContactName?: string; privateDestinationContactPhone?: string
|
privateDestinationAddress?: string; privateDestinationPostalCode?: string; privateDestinationContactName?: string; privateDestinationContactPhone?: string
|
||||||
@@ -146,6 +147,21 @@ const measurementPhotoLoading = reactive<Record<string, boolean>>({})
|
|||||||
const measurementPhotoErrors = reactive<Record<string, boolean>>({})
|
const measurementPhotoErrors = reactive<Record<string, boolean>>({})
|
||||||
const measurementPhotoPreviewUrls = computed(() => (selectedDetail.value?.measurementPhotos || [])
|
const measurementPhotoPreviewUrls = computed(() => (selectedDetail.value?.measurementPhotos || [])
|
||||||
.map((photo) => measurementPhotoUrls[photo.fileId]).filter(Boolean))
|
.map((photo) => measurementPhotoUrls[photo.fileId]).filter(Boolean))
|
||||||
|
const discardPhotoUrls = reactive<Record<string, string>>({})
|
||||||
|
const discardPhotoLoading = reactive<Record<string, boolean>>({})
|
||||||
|
const discardPhotoErrors = reactive<Record<string, boolean>>({})
|
||||||
|
const discardPhotoPreviewUrls = computed(() => (selectedDetail.value?.photos || []).map(photo => discardPhotoUrls[photo.fileId]).filter(Boolean))
|
||||||
|
let discardPhotoGeneration = 0
|
||||||
|
function clearDiscardPhotos() { discardPhotoGeneration++; Object.values(discardPhotoUrls).forEach(URL.revokeObjectURL); for (const map of [discardPhotoUrls, discardPhotoLoading, discardPhotoErrors]) Object.keys(map).forEach(key => delete map[key]) }
|
||||||
|
async function loadDiscardPhoto(fileId: string) {
|
||||||
|
const current = selectedDetail.value; const generation = discardPhotoGeneration
|
||||||
|
if (!current?.discardNo || discardPhotoLoading[fileId]) return
|
||||||
|
discardPhotoLoading[fileId] = true; discardPhotoErrors[fileId] = false
|
||||||
|
try { const blob = await downloadDiscardPhoto(current.discardNo, fileId); if (generation !== discardPhotoGeneration || selectedDetail.value !== current || mode.value !== 'detail') return; if (discardPhotoUrls[fileId]) URL.revokeObjectURL(discardPhotoUrls[fileId]); discardPhotoUrls[fileId] = URL.createObjectURL(blob) }
|
||||||
|
catch { if (generation === discardPhotoGeneration) discardPhotoErrors[fileId] = true }
|
||||||
|
finally { if (generation === discardPhotoGeneration) discardPhotoLoading[fileId] = false }
|
||||||
|
}
|
||||||
|
async function loadDiscardPhotos() { clearDiscardPhotos(); await Promise.all((selectedDetail.value?.photos || []).map(photo => loadDiscardPhoto(photo.fileId))) }
|
||||||
const fbaWarehouses = ref<MerchantWarehouse[]>([])
|
const fbaWarehouses = ref<MerchantWarehouse[]>([])
|
||||||
const operationWarehouses = ref<MerchantWarehouse[]>([])
|
const operationWarehouses = ref<MerchantWarehouse[]>([])
|
||||||
const fbaWarehousesLoading = ref(false)
|
const fbaWarehousesLoading = ref(false)
|
||||||
@@ -182,48 +198,80 @@ const listQueryFields = computed<QueryField[]>(() => {
|
|||||||
})
|
})
|
||||||
const listColumns = computed<DataTableColumn[]>(() => config.value.columns.map((label, index) => index === 0
|
const listColumns = computed<DataTableColumn[]>(() => config.value.columns.map((label, index) => index === 0
|
||||||
? { key: 'actions', label, slotName: 'actions', width: props.service === 'transfer' ? 210 : 160, fixed: 'left' }
|
? { key: 'actions', label, slotName: 'actions', width: props.service === 'transfer' ? 210 : 160, fixed: 'left' }
|
||||||
: { key: String(index - 1), prop: String(index - 1), label, minWidth: index === 1 || label === '换标单号' ? 190 : 130,
|
: { key: String(index - 1), prop: String(index - 1), label, minWidth: label === '关联业务单号' ? 300 : index === 1 || label === '换标单号' ? 190 : 130,
|
||||||
slotName: props.service === 'transfer' && label === '换标状态' ? 'transferRelabelStatus' : props.service === 'transfer' && label === '状态' ? 'transferStatus' : undefined }))
|
singleLine: label !== '关联业务单号', className: label === '关联业务单号' ? 'related-business-number-cell' : undefined,
|
||||||
|
slotName: props.service === 'labeling' && label === '换标类型' ? 'labelingType' : props.service === 'labeling' && label === '状态' ? 'labelingStatus' : props.service === 'transfer' && label === '换标状态' ? 'transferRelabelStatus' : props.service === 'transfer' && label === '状态' ? 'transferStatus' : undefined }))
|
||||||
const discardCandidates = ref<import('../api/warehouseServices').DiscardCandidate[]>([])
|
const discardCandidates = ref<import('../api/warehouseServices').DiscardCandidate[]>([])
|
||||||
const selectedDiscardOrderId = ref('')
|
const selectedDiscardOrderId = ref('')
|
||||||
const discardCandidatesLoading = ref(false)
|
const discardCandidatesLoading = ref(false)
|
||||||
const relabelCandidates = ref<RelabelInventoryCandidate[]>([])
|
const relabelCandidates = ref<RelabelInventoryCandidate[]>([])
|
||||||
const selectedRelabelInboundOrderId = ref('')
|
const selectedRelabelInboundOrderId = ref('')
|
||||||
|
const orderInfoCollapsed = ref(false)
|
||||||
|
const availableBoxesCollapsed = ref(false)
|
||||||
|
const availableSkusCollapsed = ref(false)
|
||||||
const relabelCandidatesLoading = ref(false)
|
const relabelCandidatesLoading = ref(false)
|
||||||
const transferInventoryCandidates = ref<RelabelInventoryCandidate[]>([])
|
const transferInventoryCandidates = ref<RelabelInventoryCandidate[]>([])
|
||||||
const selectedTransferInventory = ref('')
|
const selectedTransferInventory = ref('')
|
||||||
// Snowflake IDs exceed JavaScript's safe integer range. Keep them as strings
|
// 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.
|
// all the way to JSON so the backend receives the exact source order ID.
|
||||||
const selectedTransferSourceOrderIds = ref<string[]>([])
|
const selectedTransferSourceOrderIds = ref<string[]>([])
|
||||||
const returnRelabelSkuRows = ref<ReturnRelabelSkuRow[]>([])
|
|
||||||
const isReturnRelabelSource = computed(() => props.service === 'labeling' && selectedRelabelInboundOrderId.value.startsWith('RETURN_ORDER:'))
|
const isReturnRelabelSource = computed(() => props.service === 'labeling' && selectedRelabelInboundOrderId.value.startsWith('RETURN_ORDER:'))
|
||||||
const selectedReturnOrderNo = computed(() => isReturnRelabelSource.value ? selectedRelabelInboundOrderId.value.slice('RETURN_ORDER:'.length) : '')
|
const selectedReturnOrderNo = computed(() => isReturnRelabelSource.value ? selectedRelabelInboundOrderId.value.slice('RETURN_ORDER:'.length) : '')
|
||||||
const requiresBothTotalFiles = computed(() => (props.service === 'labeling' || (props.service === 'transfer' && form.relabel)) && !isReturnRelabelSource.value && labelingMode.value === 'carton_and_sku')
|
const currentRelabelCandidates = computed(() => relabelCandidates.value.map(item => returnRelabelCandidate(item, labelingMode.value)))
|
||||||
|
const returnCartonQuery = ref(String(route.query.cartonMark || ''))
|
||||||
|
const selectedReturnCandidates = computed(() => currentRelabelCandidates.value.filter(item => Boolean(item.returnCartonId)
|
||||||
|
&& returnSourceNos(item).includes(selectedReturnOrderNo.value)
|
||||||
|
&& (!returnCartonQuery.value.trim() || (item.cartonMark || '').toUpperCase().includes(returnCartonQuery.value.trim().toUpperCase()))))
|
||||||
|
const availableReturnCandidates = computed(() => selectedReturnCandidates.value.filter(item => inventoryQuantity(item.availablePackages) > 0).map(item => ({ ...item, skuItems: (item.skuItems || []).filter(sku => inventoryQuantity(sku.quantity) > 0) })))
|
||||||
|
const returnBoxCandidates = computed(() => availableReturnCandidates.value.filter(item => item.sourceType === 'RETURN_CARTON'))
|
||||||
|
const returnLooseCandidates = computed(() => availableReturnCandidates.value.filter(item => item.sourceType === 'RETURN_PARCEL'))
|
||||||
|
const requiresBothTotalFiles = computed(() => (props.service === 'labeling' || (props.service === 'transfer' && form.relabel)) && labelingMode.value === 'carton_and_sku')
|
||||||
function inventoryQuantity(value: number | string | null | undefined) {
|
function inventoryQuantity(value: number | string | null | undefined) {
|
||||||
const quantity = Number(value)
|
const quantity = Number(value)
|
||||||
return Number.isFinite(quantity) && quantity > 0 ? quantity : 0
|
return Number.isFinite(quantity) && quantity > 0 ? quantity : 0
|
||||||
}
|
}
|
||||||
|
const relabelInventorySearch = ref('')
|
||||||
|
function returnSourceNos(candidate: RelabelInventoryCandidate): string[] {
|
||||||
|
return [...new Set((candidate.inboundOrderNo || '').split(',').map(value => value.trim()).filter(Boolean))]
|
||||||
|
}
|
||||||
|
function returnRelabelProgress(candidate: RelabelInventoryCandidate) {
|
||||||
|
const labels: Record<string, string> = { UNLABELLED: '未换标', BOUND: '处理中', PROCESSING: '处理中', PARTIALLY_COMPLETED: '部分完成', COMPLETED: '全部完成' }
|
||||||
|
return [labels[candidate.relabelStatus || ''] || '—', '实际完成 ' + (candidate.relabelledQuantity ?? '—') + ' 件', '处理中占用 ' + (candidate.relabelReservedQuantity ?? '—') + ' 件'].join('|')
|
||||||
|
}
|
||||||
|
function returnInventoryState(candidate: RelabelInventoryCandidate) {
|
||||||
|
const labels: Record<string, string> = { AVAILABLE: '可选库存', RELABEL_PENDING: '换标占用', PACKING_RESERVED: '合箱计划预留', OUTBOUND_PENDING: '出库占用', DISCARD_PENDING: '废弃申请占用', OUTBOUNDED: '已出库', MERGED: '已合箱' }
|
||||||
|
return [...(returnSourceNos(candidate).length > 1 ? ['跨来源单合箱,数量为整箱内容'] : []), ...(candidate.mergedIntoCartonMarks?.length ? ['历史部分转入 ' + candidate.mergedIntoCartonMarks.join('、') + '(不代表当前库存位置)'] : []), labels[candidate.inventoryStatus || ''] || (inventoryQuantity(candidate.availablePackages) > 0 ? '可选库存' : '当前不可选'), candidate.occupiedRelabelNo].filter(Boolean).join(' · ')
|
||||||
|
}
|
||||||
const relabelInboundOptions = computed(() => {
|
const relabelInboundOptions = computed(() => {
|
||||||
const grouped = new Map<string, { value: string; inboundOrderNo: string; inboundCode: string; availablePackages: number; relabelledPackages: number; quantityUnit: '箱' | '件' }>()
|
const grouped = new Map<string, { value: string; inboundOrderNo: string; inboundCode: string; availablePackages: number; quantityUnit: '箱' | '件'; stockQuantity: number | null; units: number; hasOutbound: boolean; reasons: string[] }>()
|
||||||
for (const candidate of relabelCandidates.value) {
|
for (const candidate of currentRelabelCandidates.value) {
|
||||||
const returnOrderNo = candidate.inboundOrderNo || String(candidate.returnCartonId || '')
|
const sources = candidate.returnCartonId ? returnSourceNos(candidate) : [String(candidate.inboundOrderId)]
|
||||||
const value = candidate.sourceType === 'RETURN_CARTON' ? `RETURN_ORDER:${returnOrderNo}` : String(candidate.inboundOrderId)
|
for (const sourceNo of sources) {
|
||||||
|
const value = candidate.returnCartonId ? 'RETURN_ORDER:' + sourceNo : sourceNo
|
||||||
const current = grouped.get(value)
|
const current = grouped.get(value)
|
||||||
if (current) {
|
if (current) {
|
||||||
|
current.hasOutbound ||= candidate.hasOutbound === true || candidate.inventoryStatus === 'OUTBOUNDED'
|
||||||
current.availablePackages += inventoryQuantity(candidate.availablePackages)
|
current.availablePackages += inventoryQuantity(candidate.availablePackages)
|
||||||
current.relabelledPackages += inventoryQuantity(candidate.relabelledPackages)
|
current.units += candidate.returnCartonId && Number(candidate.stockQuantity) === 0 ? 0 : 1
|
||||||
|
current.stockQuantity = current.stockQuantity == null || candidate.stockQuantity == null ? null : current.stockQuantity + inventoryQuantity(candidate.stockQuantity)
|
||||||
|
if (candidate.returnCartonId) current.reasons.push(returnInventoryState(candidate))
|
||||||
}
|
}
|
||||||
else grouped.set(value, {
|
else grouped.set(value, {
|
||||||
value,
|
value, inboundOrderNo: candidate.returnCartonId ? '退货单 ' + sourceNo : (candidate.inboundOrderNo || '—'),
|
||||||
inboundOrderNo: candidate.sourceType === 'RETURN_CARTON' ? `退货单 ${candidate.inboundOrderNo || '—'}` : (candidate.inboundOrderNo || '—'),
|
inboundCode: candidate.returnCartonId ? '已签收退货库存(含合箱)' : (candidate.inboundCode || '—'),
|
||||||
inboundCode: candidate.sourceType === 'RETURN_CARTON' ? '已签收退货库存' : (candidate.inboundCode || '—'),
|
|
||||||
availablePackages: inventoryQuantity(candidate.availablePackages),
|
availablePackages: inventoryQuantity(candidate.availablePackages),
|
||||||
relabelledPackages: inventoryQuantity(candidate.relabelledPackages),
|
quantityUnit: candidate.returnCartonId ? '件' : '箱',
|
||||||
quantityUnit: candidate.sourceType === 'RETURN_CARTON' ? '件' : '箱',
|
stockQuantity: candidate.stockQuantity == null ? null : inventoryQuantity(candidate.stockQuantity), units: candidate.returnCartonId && Number(candidate.stockQuantity) === 0 ? 0 : 1, hasOutbound: candidate.hasOutbound === true || candidate.inventoryStatus === 'OUTBOUNDED', reasons: candidate.returnCartonId ? [returnInventoryState(candidate)] : [],
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return [...grouped.values()]
|
}
|
||||||
|
return [...grouped.values()].map(option => ({ ...option, reasons: [...new Set(option.reasons)] }))
|
||||||
})
|
})
|
||||||
|
const visibleRelabelInboundOptions = computed(() => relabelInboundOptions.value.filter(option => option.availablePackages > 0))
|
||||||
|
function relabelOptionLabel(option: typeof relabelInboundOptions.value[number]) {
|
||||||
|
if (option.quantityUnit === '箱') return option.inboundOrderNo + '|' + option.inboundCode + '|可选 ' + option.availablePackages + ' 箱'
|
||||||
|
return option.inboundOrderNo + '|在仓 ' + option.units + ' 包裹/箱 · ' + (option.stockQuantity ?? '待查询') + ' 件' + (option.reasons.some(reason => reason.includes('跨来源单')) ? '(关联整箱数量,含其他来源)' : '') + (option.hasOutbound && Number(option.stockQuantity) > 0 ? '|部分出库' : '')
|
||||||
|
}
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const saving = ref(false)
|
const saving = ref(false)
|
||||||
const cartonTemplateInput = ref<HTMLInputElement | null>(null)
|
const cartonTemplateInput = ref<HTMLInputElement | null>(null)
|
||||||
@@ -249,7 +297,7 @@ watch(() => [props.service, props.createPage, props.detailPage, detailNumber.val
|
|||||||
else if (props.detailPage && detailNumber.value) void loadDetailPage()
|
else if (props.detailPage && detailNumber.value) void loadDetailPage()
|
||||||
else void loadPage()
|
else void loadPage()
|
||||||
})
|
})
|
||||||
watch(mode, (value) => { if (value !== 'detail') { clearCompletionPhotos(); clearMeasurementPhotos() } })
|
watch(mode, (value) => { if (value !== 'detail') { clearCompletionPhotos(); clearMeasurementPhotos(); clearDiscardPhotos() } })
|
||||||
watch(() => form.relabel, (value) => {
|
watch(() => form.relabel, (value) => {
|
||||||
if (props.service === 'transfer' && value) {
|
if (props.service === 'transfer' && value) {
|
||||||
labelingMode.value = 'carton_and_sku'
|
labelingMode.value = 'carton_and_sku'
|
||||||
@@ -263,7 +311,9 @@ watch(() => cargoRows.value.map((row) => row.sku), (skus) => {
|
|||||||
if (sourceSku) row.sku = sourceSku
|
if (sourceSku) row.sku = sourceSku
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
watch(labelingMode, (value) => { if (value !== 'carton' && !skuRelabelRows.value.length) addSkuRelabelRow() })
|
watch(labelingMode, (value) => {
|
||||||
|
if (!isReturnRelabelSource.value && value !== 'carton' && !skuRelabelRows.value.length) addSkuRelabelRow()
|
||||||
|
})
|
||||||
watch(() => form.destination, (value) => {
|
watch(() => form.destination, (value) => {
|
||||||
if (props.service !== 'labeling') return
|
if (props.service !== 'labeling') return
|
||||||
for (const row of cargoRows.value) row.destinationWarehouseId = value
|
for (const row of cargoRows.value) row.destinationWarehouseId = value
|
||||||
@@ -290,9 +340,12 @@ onMounted(() => {
|
|||||||
else void loadPage()
|
else void loadPage()
|
||||||
void nextTick(refreshWarehouseMarkLabels)
|
void nextTick(refreshWarehouseMarkLabels)
|
||||||
})
|
})
|
||||||
onBeforeUnmount(() => { clearCompletionPhotos(); clearMeasurementPhotos() })
|
onBeforeUnmount(() => { clearCompletionPhotos(); clearMeasurementPhotos(); clearDiscardPhotos() })
|
||||||
function resetFilters() { Object.assign(filters, { number: '', inboundNo: '', warehouse: '', destination: '', status: '', start: '', end: '', reviewStart: '', reviewEnd: '', completedStart: '', completedEnd: '', measuredStart: '', measuredEnd: '', outboundStart: '', outboundEnd: '' }) }
|
function resetFilters() { Object.assign(filters, { number: '', inboundNo: '', warehouse: '', destination: '', status: '', start: '', end: '', reviewStart: '', reviewEnd: '', completedStart: '', completedEnd: '', measuredStart: '', measuredEnd: '', outboundStart: '', outboundEnd: '' }) }
|
||||||
function resetForm() {
|
function resetForm() {
|
||||||
|
orderInfoCollapsed.value = false
|
||||||
|
availableBoxesCollapsed.value = false
|
||||||
|
availableSkusCollapsed.value = false
|
||||||
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 })
|
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 = []
|
cargoRows.value = []
|
||||||
transferRelabelRows.value = []
|
transferRelabelRows.value = []
|
||||||
@@ -488,10 +541,11 @@ function clearTransferRelabelRows() {
|
|||||||
transferRelabelRows.value = []
|
transferRelabelRows.value = []
|
||||||
}
|
}
|
||||||
function addSkuRelabelRow() {
|
function addSkuRelabelRow() {
|
||||||
|
if (isReturnRelabelSource.value) { ElMessage.warning('请从上方实际包裹/箱库存选择 SKU'); return }
|
||||||
const source = cargoRows.value[Math.min(skuRelabelRows.value.length, Math.max(0, cargoRows.value.length - 1))]
|
const source = cargoRows.value[Math.min(skuRelabelRows.value.length, Math.max(0, cargoRows.value.length - 1))]
|
||||||
skuRelabelRows.value.push({ id: ++skuRelabelSequence, sourceRowId: source?.id || null,
|
skuRelabelRows.value.push({ id: ++skuRelabelSequence, sourceRowId: source?.id || null,
|
||||||
cartonMark: '', originalSku: source?.sku || '', newSku: '', quantity: 1,
|
cartonMark: '', originalSku: source?.sku || '', newSku: '', quantity: 1,
|
||||||
fbaCartonMark: '', destinationWarehouseId: form.destination, remark: '' })
|
fbaCartonMark: '', shipmentNo: '', destinationWarehouseId: form.destination, remark: '' })
|
||||||
}
|
}
|
||||||
function removeSkuRelabelRow(id: number) { skuRelabelRows.value = skuRelabelRows.value.filter((row) => row.id !== id) }
|
function removeSkuRelabelRow(id: number) { skuRelabelRows.value = skuRelabelRows.value.filter((row) => row.id !== id) }
|
||||||
function applyExistingSkuBinding(row: SkuRelabelRow) {
|
function applyExistingSkuBinding(row: SkuRelabelRow) {
|
||||||
@@ -508,6 +562,7 @@ function applyExistingCartonBinding(row: SkuRelabelRow) {
|
|||||||
&& item.cartonMark.trim().toUpperCase() === cartonMark && item.fbaCartonMark.trim())
|
&& item.cartonMark.trim().toUpperCase() === cartonMark && item.fbaCartonMark.trim())
|
||||||
if (!mapping) return
|
if (!mapping) return
|
||||||
if (!row.fbaCartonMark.trim()) row.fbaCartonMark = mapping.fbaCartonMark
|
if (!row.fbaCartonMark.trim()) row.fbaCartonMark = mapping.fbaCartonMark
|
||||||
|
if (!row.shipmentNo.trim()) row.shipmentNo = mapping.shipmentNo
|
||||||
if (!row.destinationWarehouseId) row.destinationWarehouseId = mapping.destinationWarehouseId
|
if (!row.destinationWarehouseId) row.destinationWarehouseId = mapping.destinationWarehouseId
|
||||||
}
|
}
|
||||||
function selectShippingLabel(event: Event) { shippingLabelFile.value = (event.target as HTMLInputElement).files?.[0] || null }
|
function selectShippingLabel(event: Event) { shippingLabelFile.value = (event.target as HTMLInputElement).files?.[0] || null }
|
||||||
@@ -546,17 +601,34 @@ function buildSkuRelabelItems(): RelabelCreate['items'] {
|
|||||||
throw new Error('填写的箱唛数量超过当前入仓单可用库存箱数')
|
throw new Error('填写的箱唛数量超过当前入仓单可用库存箱数')
|
||||||
}
|
}
|
||||||
return [...groups.entries()].map(([_, rows], groupIndex) => {
|
return [...groups.entries()].map(([_, rows], groupIndex) => {
|
||||||
const source = cargoRows.value.find((item) => item.id === rows[0].sourceRowId) || anchors[groupIndex]
|
const source = isReturnRelabelSource.value
|
||||||
|
? cargoRows.value.find(item => item.id === rows[0].sourceRowId && item.cartonMark === rows[0].cartonMark.trim())
|
||||||
|
: cargoRows.value.find((item) => item.id === rows[0].sourceRowId) || anchors[groupIndex]
|
||||||
|
if (isReturnRelabelSource.value && !source) throw new Error('请选择该退货单实际可用的来源箱号')
|
||||||
|
if (isReturnRelabelSource.value) {
|
||||||
|
const candidate = selectedReturnCandidates.value.find(item => String(item.returnCartonId) === source?.returnCartonId)
|
||||||
|
if (rows.some(row => row.sourceRowId !== source?.id)) throw new Error('同一换标箱内的 SKU 必须选择相同的实际来源包裹/箱')
|
||||||
|
const requested = new Map<string, number>()
|
||||||
|
for (const row of rows) {
|
||||||
|
const quantity = (requested.get(row.originalSku) || 0) + row.quantity
|
||||||
|
requested.set(row.originalSku, quantity)
|
||||||
|
if (quantity > Number(candidate?.skuItems?.find(item => item.skuCode === row.originalSku)?.quantity || 0)) throw new Error(`SKU ${row.originalSku} 超过来源箱可用数量`)
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!source?.returnCartonId && (!source?.sourceInventoryBalanceId || !source.sourceInventoryPositionId || !source.sourceInboundOrderId)) {
|
if (!source?.returnCartonId && (!source?.sourceInventoryBalanceId || !source.sourceInventoryPositionId || !source.sourceInboundOrderId)) {
|
||||||
throw new Error('来源库存已变化,请重新选择有库存的历史入仓单')
|
throw new Error('来源库存已变化,请重新选择有库存的历史入仓单')
|
||||||
}
|
}
|
||||||
const cartonMark = rows[0].cartonMark.trim()
|
const cartonMark = rows[0].cartonMark.trim()
|
||||||
const changeCarton = labelingMode.value === 'carton_and_sku'
|
const changeCarton = labelingMode.value === 'carton_and_sku'
|
||||||
const fbaCartonMark = rows[0].fbaCartonMark.trim()
|
const fbaCartonMark = rows[0].fbaCartonMark.trim()
|
||||||
|
const shipmentNo = rows[0].shipmentNo.trim()
|
||||||
if (changeCarton && (!fbaCartonMark || !form.destination
|
if (changeCarton && (!fbaCartonMark || !form.destination
|
||||||
|| rows.some((row) => row.fbaCartonMark.trim() !== fbaCartonMark))) {
|
|| rows.some((row) => row.fbaCartonMark.trim() !== fbaCartonMark))) {
|
||||||
throw new Error('同一我方箱唛的组合换标必须使用相同的新 FBA 箱唛,并选择整票 FBA 目的仓')
|
throw new Error('同一我方箱唛的组合换标必须使用相同的新 FBA 箱唛,并选择整票 FBA 目的仓')
|
||||||
}
|
}
|
||||||
|
if (changeCarton && (!shipmentNo || rows.some(row => row.shipmentNo.trim() !== shipmentNo))) {
|
||||||
|
throw new Error('同一我方箱唛的组合换标必须填写相同的 FBA 货件编号')
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
sourceInventoryBalanceId: source.sourceInventoryBalanceId,
|
sourceInventoryBalanceId: source.sourceInventoryBalanceId,
|
||||||
sourceInventoryPositionId: source.sourceInventoryPositionId,
|
sourceInventoryPositionId: source.sourceInventoryPositionId,
|
||||||
@@ -566,7 +638,7 @@ function buildSkuRelabelItems(): RelabelCreate['items'] {
|
|||||||
productNameZh: source.name,
|
productNameZh: source.name,
|
||||||
totalPackageCount: 1,
|
totalPackageCount: 1,
|
||||||
notifiedPackageCount: 1,
|
notifiedPackageCount: 1,
|
||||||
shipmentNo: source.shipmentNo || cartonMark,
|
shipmentNo: changeCarton ? shipmentNo : source.shipmentNo || cartonMark,
|
||||||
trackingCode: form.trackingNo || undefined,
|
trackingCode: form.trackingNo || undefined,
|
||||||
newSkuCode: rows[0].newSku,
|
newSkuCode: rows[0].newSku,
|
||||||
labelRequirement: form.requirement || undefined,
|
labelRequirement: form.requirement || undefined,
|
||||||
@@ -774,7 +846,7 @@ function importSelectedBindingsToDetails() {
|
|||||||
}
|
}
|
||||||
labelingMode.value = 'carton'
|
labelingMode.value = 'carton'
|
||||||
} else {
|
} else {
|
||||||
const importedRows = selected.map(({ templateType: _, selected: __, shipmentNo, ...item }) => item)
|
const importedRows = selected.map(({ templateType: _, selected: __, ...item }) => item)
|
||||||
for (const item of importedRows) {
|
for (const item of importedRows) {
|
||||||
skuRelabelRows.value = skuRelabelRows.value.filter((row) => !(row.cartonMark.trim().toUpperCase() === item.cartonMark.trim().toUpperCase()
|
skuRelabelRows.value = skuRelabelRows.value.filter((row) => !(row.cartonMark.trim().toUpperCase() === item.cartonMark.trim().toUpperCase()
|
||||||
&& row.originalSku.trim().toUpperCase() === item.originalSku.trim().toUpperCase()))
|
&& row.originalSku.trim().toUpperCase() === item.originalSku.trim().toUpperCase()))
|
||||||
@@ -846,6 +918,19 @@ function statusLabel(value: string) {
|
|||||||
return labels[value] || value || '—'
|
return labels[value] || value || '—'
|
||||||
}
|
}
|
||||||
type StatusTagType = 'primary' | 'success' | 'warning' | 'danger' | 'info'
|
type StatusTagType = 'primary' | 'success' | 'warning' | 'danger' | 'info'
|
||||||
|
function labelingTypeLabels(value: unknown): string[] {
|
||||||
|
return typeof value === 'string' && value !== '—' ? [...new Set(value.split('、'))] : []
|
||||||
|
}
|
||||||
|
function labelingTypeTagType(label: string): StatusTagType {
|
||||||
|
if (label === '只换 SKU') return 'primary'
|
||||||
|
if (label === '只换箱唛') return 'warning'
|
||||||
|
return 'success'
|
||||||
|
}
|
||||||
|
function labelingStatusTagType(status: string): StatusTagType {
|
||||||
|
if (status === 'CANCELLED') return 'info'
|
||||||
|
if (!['READY_FOR_OUTBOUND', 'COMPLETED', 'REJECTED', 'WAIT_APPROVAL', 'PENDING_REVIEW', 'PENDING_PROCESSING', 'CUSTOMER_CONFIRM_PENDING', 'PROCESSING'].includes(status)) return 'info'
|
||||||
|
return relabelStatusTagType(status)
|
||||||
|
}
|
||||||
function relabelStatusTagType(status: string): StatusTagType {
|
function relabelStatusTagType(status: string): StatusTagType {
|
||||||
if (['READY_FOR_OUTBOUND', 'COMPLETED'].includes(status)) return 'success'
|
if (['READY_FOR_OUTBOUND', 'COMPLETED'].includes(status)) return 'success'
|
||||||
if (['REJECTED', 'CANCELLED'].includes(status)) return 'danger'
|
if (['REJECTED', 'CANCELLED'].includes(status)) return 'danger'
|
||||||
@@ -919,7 +1004,7 @@ async function load() {
|
|||||||
total.value = Number.isFinite(Number(result.total)) ? Number(result.total) : result.records.length
|
total.value = Number.isFinite(Number(result.total)) ? Number(result.total) : result.records.length
|
||||||
submittedRows.value = result.records.map((item) => {
|
submittedRows.value = result.records.map((item) => {
|
||||||
const destinationWarehouses = warehouseDisplay(item.overseasWarehouseId)
|
const destinationWarehouses = warehouseDisplay(item.overseasWarehouseId)
|
||||||
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 || '' }
|
return { ...row([item.relabelNo, (item.relatedBusinessOrderNos || []).join('、') || '—', destinationWarehouses, new Set(item.skuCodes.split(',').map(code => code.trim()).filter(Boolean)).size, item.totalPackageCount, (item.operationTypes || []).map(type => ({ CARTON_LABEL: '只换箱唛', SKU_LABEL: '只换 SKU', RETURN_BULK_SKU_LABEL: '只换 SKU', CARTON_AND_SKU: 'SKU 和箱唛都换' }[type] || type)).join('、') || '—', 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') {
|
} 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), completedFrom: dateTime(filters.completedStart), completedTo: dateTime(filters.completedEnd, 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) })
|
||||||
@@ -949,41 +1034,11 @@ function listRowActions(candidate: object): TableAction[] {
|
|||||||
if (canConfirmRelabel.value && props.service === 'labeling' && item.__status === 'CUSTOMER_CONFIRM_PENDING' && !item.__confirmedAt) actions.push({ key: 'confirm-relabel', label: '确认换标', run: () => confirmRelabelFromList(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
|
return actions
|
||||||
}
|
}
|
||||||
async function submitReturnRelabel() {
|
|
||||||
const items = returnRelabelSkuRows.value.filter(item => item.selected)
|
|
||||||
.map(item => ({ skuCode: item.skuCode, quantity: Number(item.quantity) }))
|
|
||||||
if (!selectedReturnOrderNo.value || !items.length) { ElMessage.warning('请至少选择一个需要贴标的 SKU'); return }
|
|
||||||
if (items.some(item => item.quantity < 1 || item.quantity > (returnRelabelSkuRows.value.find(row => row.skuCode === item.skuCode)?.availableQuantity || 0))) {
|
|
||||||
ElMessage.warning('本次贴标数量必须大于 0,且不能超过该 SKU 的库存总数'); return
|
|
||||||
}
|
|
||||||
const destination = fbaWarehouses.value.find(warehouse => warehouse.warehouseCode === form.destination)
|
|
||||||
if (!destination) { ElMessage.warning('请选择 FBA 目的仓'); return }
|
|
||||||
const selectedFile = cartonTotalFile.value || skuTotalFile.value
|
|
||||||
const fileScope = cartonTotalFile.value ? 'CARTON_TOTAL' as const : 'SKU_TOTAL' as const
|
|
||||||
if (!selectedFile) { ElMessage.warning('请上传箱唛总文件或 SKU 总文件(二选一)'); return }
|
|
||||||
try { await ElMessageBox.confirm(`确认提交退货单 ${selectedReturnOrderNo.value} 的贴标申请吗?`, '提交确认', { confirmButtonText: '提交', cancelButtonText: '取消' }) } catch { return }
|
|
||||||
saving.value = true
|
|
||||||
try {
|
|
||||||
const created = await createReturnRelabel(selectedReturnOrderNo.value, {
|
|
||||||
items,
|
|
||||||
fileScope,
|
|
||||||
destinationFbaWarehouseId: String(destination.id),
|
|
||||||
destinationFbaWarehouseCode: destination.warehouseCode,
|
|
||||||
cartonRemark: form.remark.trim() || undefined,
|
|
||||||
idempotencyKey: createIdempotencyKey(),
|
|
||||||
})
|
|
||||||
await uploadReturnRelabelFile(created.relabelNo, fileScope, selectedFile)
|
|
||||||
ElMessage.success(`贴标申请 ${created.relabelNo} 已提交,等待审核`)
|
|
||||||
await router.push({ name: 'overseas-labeling' })
|
|
||||||
} catch (error) { ElMessage.error(error instanceof Error ? error.message : '退货贴标申请提交失败,请重试') }
|
|
||||||
finally { saving.value = false }
|
|
||||||
}
|
|
||||||
watch([page, pageSize], ([nextPage, nextSize], [previousPage, previousSize]) => {
|
watch([page, pageSize], ([nextPage, nextSize], [previousPage, previousSize]) => {
|
||||||
if (nextSize !== previousSize && nextPage !== 1) { page.value = 1; return }
|
if (nextSize !== previousSize && nextPage !== 1) { page.value = 1; return }
|
||||||
void load()
|
void load()
|
||||||
})
|
})
|
||||||
async function submit(action: 'draft' | 'submit' = 'submit') {
|
async function submit(action: 'draft' | 'submit' = 'submit') {
|
||||||
if (isReturnRelabelSource.value) { await submitReturnRelabel(); return }
|
|
||||||
const primaryWarehouse = props.service === 'relabel' ? form.sourceWarehouse : form.warehouse
|
const primaryWarehouse = props.service === 'relabel' ? form.sourceWarehouse : form.warehouse
|
||||||
const relabelRows = labelingMode.value === 'carton' ? cartonDetailRows.value : skuRelabelRows.value
|
const relabelRows = labelingMode.value === 'carton' ? cartonDetailRows.value : skuRelabelRows.value
|
||||||
const invalidCargo = props.service === 'disposal'
|
const invalidCargo = props.service === 'disposal'
|
||||||
@@ -991,7 +1046,7 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
|||||||
|| cargoRows.value.some((item) => item.quantity < 0 || item.quantity > Number(item.availableQuantity || 0))
|
|| cargoRows.value.some((item) => item.quantity < 0 || item.quantity > Number(item.availableQuantity || 0))
|
||||||
: (props.service === 'labeling' || props.service === 'relabel') && (relabelRows.length === 0 || (props.service === 'labeling' && labelingMode.value !== 'carton'
|
: (props.service === 'labeling' || props.service === 'relabel') && (relabelRows.length === 0 || (props.service === 'labeling' && labelingMode.value !== 'carton'
|
||||||
? skuRelabelRows.value.some((item) => !item.cartonMark || !item.originalSku || !item.newSku || item.quantity < 1
|
? skuRelabelRows.value.some((item) => !item.cartonMark || !item.originalSku || !item.newSku || item.quantity < 1
|
||||||
|| (labelingMode.value === 'carton_and_sku' && !item.fbaCartonMark))
|
|| (labelingMode.value === 'carton_and_sku' && (!item.fbaCartonMark || !item.shipmentNo.trim())))
|
||||||
: cargoRows.value.some((item) => (props.service !== 'labeling' && !item.sku) || !item.name
|
: cargoRows.value.some((item) => (props.service !== 'labeling' && !item.sku) || !item.name
|
||||||
|| (props.service !== 'labeling' && item.quantity < 1))))
|
|| (props.service !== 'labeling' && item.quantity < 1))))
|
||||||
if ((props.service === 'relabel' && !form.inboundNo) || !primaryWarehouse || invalidCargo) {
|
if ((props.service === 'relabel' && !form.inboundNo) || !primaryWarehouse || invalidCargo) {
|
||||||
@@ -1003,8 +1058,8 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
|||||||
if (props.service === 'labeling' && requiresBothTotalFiles.value && (!cartonTotalFile.value || !skuTotalFile.value)) {
|
if (props.service === 'labeling' && requiresBothTotalFiles.value && (!cartonTotalFile.value || !skuTotalFile.value)) {
|
||||||
ElMessage.warning('SKU 和箱唛都换时,必须同时上传箱唛总文件和 SKU 总文件'); return
|
ElMessage.warning('SKU 和箱唛都换时,必须同时上传箱唛总文件和 SKU 总文件'); return
|
||||||
}
|
}
|
||||||
if (props.service === 'labeling' && !requiresBothTotalFiles.value && !cartonTotalFile.value && !skuTotalFile.value) {
|
if (props.service === 'labeling' && !requiresBothTotalFiles.value && (labelingMode.value === 'sku' ? !skuTotalFile.value : !cartonTotalFile.value)) {
|
||||||
ElMessage.warning('请上传箱唛总文件或 SKU 总文件(二选一)'); return
|
ElMessage.warning(labelingMode.value === 'sku' ? '请上传 SKU 标签总文件' : '请上传箱唛总文件'); return
|
||||||
}
|
}
|
||||||
if (props.service === 'labeling' && labelingMode.value !== 'sku' && !form.deliveryMethod) {
|
if (props.service === 'labeling' && labelingMode.value !== 'sku' && !form.deliveryMethod) {
|
||||||
ElMessage.warning('请选择换标完成后的派送方式'); return
|
ElMessage.warning('请选择换标完成后的派送方式'); return
|
||||||
@@ -1019,7 +1074,7 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
|||||||
if (props.service === 'labeling' && labelingMode.value === 'carton' && cartonDetailRows.value.some((item) => !item.shipmentNo || !item.cartonMark || !item.fbaCartonMark)) {
|
if (props.service === 'labeling' && labelingMode.value === 'carton' && cartonDetailRows.value.some((item) => !item.shipmentNo || !item.cartonMark || !item.fbaCartonMark)) {
|
||||||
ElMessage.warning('请上传关联面单,确保每箱的我方箱唛和 FBA 箱唛完整'); return
|
ElMessage.warning('请上传关联面单,确保每箱的我方箱唛和 FBA 箱唛完整'); return
|
||||||
}
|
}
|
||||||
if (props.service === 'labeling' && labelingMode.value === 'carton' && cartonDetailRows.value.some((item) => !item.sourceInventoryPositionId)) {
|
if (props.service === 'labeling' && labelingMode.value === 'carton' && cartonDetailRows.value.some((item) => !item.returnCartonId && !item.sourceInventoryPositionId)) {
|
||||||
ElMessage.warning('请选择有库存的历史入仓单'); return
|
ElMessage.warning('请选择有库存的历史入仓单'); return
|
||||||
}
|
}
|
||||||
if (props.service === 'disposal' && !form.reason) {
|
if (props.service === 'disposal' && !form.reason) {
|
||||||
@@ -1061,6 +1116,8 @@ async function submit(action: 'draft' | 'submit' = 'submit') {
|
|||||||
const items = labelingMode.value === 'carton'
|
const items = labelingMode.value === 'carton'
|
||||||
? cartonDetailRows.value.map((item) => ({ sourceInventoryBalanceId: item.sourceInventoryBalanceId, sourceInventoryPositionId: item.sourceInventoryPositionId, sourceInboundOrderId: item.sourceInboundOrderId, returnCartonId: item.returnCartonId, skuCode: item.sku, productNameZh: item.name, totalPackageCount: 1, notifiedPackageCount: 1, shipmentNo: item.shipmentNo, trackingCode: form.trackingNo || undefined, newSkuCode: undefined, labelRequirement: form.requirement || undefined, cartonMark: item.cartonMark, fbaCartonMark: item.fbaCartonMark, destinationFbaWarehouseCode: form.destination, operationType: 'CARTON_LABEL' as const, skuItems: [], remark: item.remark || undefined }))
|
? cartonDetailRows.value.map((item) => ({ sourceInventoryBalanceId: item.sourceInventoryBalanceId, sourceInventoryPositionId: item.sourceInventoryPositionId, sourceInboundOrderId: item.sourceInboundOrderId, returnCartonId: item.returnCartonId, skuCode: item.sku, productNameZh: item.name, totalPackageCount: 1, notifiedPackageCount: 1, shipmentNo: item.shipmentNo, trackingCode: form.trackingNo || undefined, newSkuCode: undefined, labelRequirement: form.requirement || undefined, cartonMark: item.cartonMark, fbaCartonMark: item.fbaCartonMark, destinationFbaWarehouseCode: form.destination, operationType: 'CARTON_LABEL' as const, skuItems: [], remark: item.remark || undefined }))
|
||||||
: buildSkuRelabelItems()
|
: buildSkuRelabelItems()
|
||||||
|
const selectedOperationType = labelingMode.value === 'carton' ? 'CARTON_LABEL' : labelingMode.value === 'sku' ? 'SKU_LABEL' : 'CARTON_AND_SKU'
|
||||||
|
if (items.some(item => item.operationType !== selectedOperationType)) throw new Error('一张申请只能选择一种换标类型,请核对绑定明细')
|
||||||
const created = await createRelabel({ customerOrderNo: sourceInboundOrders || '贴标申请', operationWarehouseId: form.warehouse, labelDeadline: form.labelDeadline, contactName: form.contact, contactPhone: form.phone, remark: form.remark || undefined, idempotencyKey, items,
|
const created = await createRelabel({ customerOrderNo: sourceInboundOrders || '贴标申请', operationWarehouseId: form.warehouse, labelDeadline: form.labelDeadline, contactName: form.contact, contactPhone: form.phone, remark: form.remark || undefined, idempotencyKey, items,
|
||||||
deliveryMethod: labelingMode.value === 'sku' ? undefined : form.deliveryMethod as 'TRUCK' | 'EXPRESS' | 'TRUCK_PICKUP' | 'EXPRESS_PICKUP',
|
deliveryMethod: labelingMode.value === 'sku' ? undefined : form.deliveryMethod as 'TRUCK' | 'EXPRESS' | 'TRUCK_PICKUP' | 'EXPRESS_PICKUP',
|
||||||
printShippingLabel: labelingMode.value !== 'sku' && (form.deliveryMethod === 'EXPRESS' || form.deliveryMethod === 'EXPRESS_PICKUP') && form.relabel })
|
printShippingLabel: labelingMode.value !== 'sku' && (form.deliveryMethod === 'EXPRESS' || form.deliveryMethod === 'EXPRESS_PICKUP') && form.relabel })
|
||||||
@@ -1148,6 +1205,7 @@ async function openDetail(value: Record<string, string>) {
|
|||||||
mode.value = 'detail'
|
mode.value = 'detail'
|
||||||
if (props.service === 'labeling') void loadCompletionPhotos()
|
if (props.service === 'labeling') void loadCompletionPhotos()
|
||||||
if (props.service === 'transfer') void loadMeasurementPhotos()
|
if (props.service === 'transfer') void loadMeasurementPhotos()
|
||||||
|
if (props.service === 'disposal') void loadDiscardPhotos()
|
||||||
} catch (error) { selectedDetail.value = null; selectedRelabelDetail.value = null; detailError.value = error instanceof Error ? error.message : '详情加载失败'; mode.value = 'detail'; ElMessage.error(detailError.value) }
|
} catch (error) { selectedDetail.value = null; selectedRelabelDetail.value = null; detailError.value = error instanceof Error ? error.message : '详情加载失败'; mode.value = 'detail'; ElMessage.error(detailError.value) }
|
||||||
}
|
}
|
||||||
async function loadDetailPage() {
|
async function loadDetailPage() {
|
||||||
@@ -1397,36 +1455,17 @@ async function selectOperationWarehouse() {
|
|||||||
}
|
}
|
||||||
function selectRelabelInventory(inboundOrderId: string) {
|
function selectRelabelInventory(inboundOrderId: string) {
|
||||||
const rows: CargoRow[] = []
|
const rows: CargoRow[] = []
|
||||||
const selectedCandidates = relabelCandidates.value.filter((item) => {
|
const selectedCandidates = currentRelabelCandidates.value.filter((item) => {
|
||||||
const returnOrderNo = item.inboundOrderNo || String(item.returnCartonId || '')
|
return item.returnCartonId ? returnSourceNos(item).includes(inboundOrderId.slice('RETURN_ORDER:'.length)) : String(item.inboundOrderId) === inboundOrderId
|
||||||
return (item.sourceType === 'RETURN_CARTON' ? `RETURN_ORDER:${returnOrderNo}` : String(item.inboundOrderId)) === inboundOrderId
|
|
||||||
})
|
})
|
||||||
returnRelabelSkuRows.value = []
|
|
||||||
if (inboundOrderId.startsWith('RETURN_ORDER:')) {
|
if (inboundOrderId.startsWith('RETURN_ORDER:')) {
|
||||||
const grouped = new Map<string, ReturnRelabelSkuRow>()
|
for (const candidate of selectedCandidates) rows.push({
|
||||||
for (const candidate of selectedCandidates) {
|
id: ++cargoSequence, sku: candidate.skuItems?.[0]?.skuCode || candidate.skuCode || '',
|
||||||
const skuItems = candidate.skuItems?.length
|
name: candidate.productNameZh || '', included: false, quantity: 1, availableQuantity: 1,
|
||||||
? candidate.skuItems
|
returnCartonId: String(candidate.returnCartonId), sourceInboundOrderNo: candidate.inboundOrderNo,
|
||||||
: candidate.skuCode ? [{ skuCode: candidate.skuCode, quantity: inventoryQuantity(candidate.availablePackages) }] : []
|
fnsku: '', shipmentNo: candidate.inboundOrderNo || '', newSkuCode: '', shippingMark: '', customerCartonMarks: '',
|
||||||
for (const item of skuItems) {
|
cartonMark: candidate.cartonMark || '', fbaCartonMark: '', destinationWarehouseId: '', remark: '',
|
||||||
const skuCode = item.skuCode.trim()
|
|
||||||
if (!skuCode) continue
|
|
||||||
const key = skuCode.toUpperCase()
|
|
||||||
const current = grouped.get(key)
|
|
||||||
const quantity = inventoryQuantity(item.quantity)
|
|
||||||
if (current) current.availableQuantity += quantity
|
|
||||||
else grouped.set(key, {
|
|
||||||
skuCode,
|
|
||||||
productNameZh: candidate.skuCode?.trim().toUpperCase() === key ? (candidate.productNameZh || '') : '',
|
|
||||||
availableQuantity: quantity,
|
|
||||||
selected: false,
|
|
||||||
// 可贴库存和本次申请数量是两个概念;重复换标时默认不应自动带入上次/首个箱子的数量。
|
|
||||||
quantity: 0,
|
|
||||||
})
|
})
|
||||||
}
|
|
||||||
}
|
|
||||||
returnRelabelSkuRows.value = [...grouped.values()]
|
|
||||||
labelingMode.value = 'sku'
|
|
||||||
} else for (const candidate of selectedCandidates) {
|
} else for (const candidate of selectedCandidates) {
|
||||||
for (const position of candidate.positions) rows.push(...Array.from({ length: Math.min(inventoryQuantity(position.availablePackages), 500) }, () => ({
|
for (const position of candidate.positions) rows.push(...Array.from({ length: Math.min(inventoryQuantity(position.availablePackages), 500) }, () => ({
|
||||||
id: ++cargoSequence, sku: candidate.skuCode || '', name: candidate.productNameZh || '库存货物',
|
id: ++cargoSequence, sku: candidate.skuCode || '', name: candidate.productNameZh || '库存货物',
|
||||||
@@ -1440,7 +1479,7 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
cargoRows.value = rows.slice(0, 500)
|
cargoRows.value = rows.slice(0, 500)
|
||||||
if (cargoRows.value.length) cargoRows.value[0].included = true
|
if (cargoRows.value.length && !inboundOrderId.startsWith('RETURN_ORDER:')) cargoRows.value[0].included = true
|
||||||
skuRelabelRows.value = []
|
skuRelabelRows.value = []
|
||||||
importedRelabelBindings.value = []
|
importedRelabelBindings.value = []
|
||||||
shippingLabelFile.value = null
|
shippingLabelFile.value = null
|
||||||
@@ -1448,17 +1487,35 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
skuTotalFile.value = null
|
skuTotalFile.value = null
|
||||||
if (!isReturnRelabelSource.value && labelingMode.value !== 'carton') addSkuRelabelRow()
|
if (!isReturnRelabelSource.value && labelingMode.value !== 'carton') addSkuRelabelRow()
|
||||||
}
|
}
|
||||||
|
function addReturnSkuBinding(source: RelabelInventoryCandidate, skuCode: string) {
|
||||||
|
const sku = source.skuItems?.find(item => item.skuCode === skuCode)
|
||||||
|
if (!sku) return
|
||||||
|
const row = skuRelabelRows.value.find(item => item.cartonMark === source.cartonMark && item.originalSku === skuCode)
|
||||||
|
if (row) return
|
||||||
|
const sourceRow = cargoRows.value.find(item => item.returnCartonId === String(source.returnCartonId))
|
||||||
|
skuRelabelRows.value.push({ id: ++skuRelabelSequence, sourceRowId: sourceRow?.id || null, cartonMark: source.cartonMark || '', originalSku: skuCode, newSku: '', quantity: Math.max(1, Number(sku.quantity)), fbaCartonMark: '', shipmentNo: '', destinationWarehouseId: '', remark: '' })
|
||||||
|
}
|
||||||
|
function addReturnBoxBinding(source: RelabelInventoryCandidate) {
|
||||||
|
if (labelingMode.value !== 'carton') {
|
||||||
|
for (const sku of source.skuItems || []) addReturnSkuBinding(source, sku.skuCode)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (cartonDetailRows.value.some(item => item.cartonMark === source.cartonMark)) return
|
||||||
|
cargoRows.value.push({ id: ++cargoSequence, included: true, sku: source.skuItems?.map(item => item.skuCode).join(',') || '', name: source.productNameZh || '', shipmentNo: '', cartonMark: source.cartonMark || '', fbaCartonMark: '', remark: '', sourceInventoryBalanceId: undefined, sourceInventoryPositionId: undefined, sourceInboundOrderId: undefined, returnCartonId: String(source.returnCartonId), quantity: 1, fnsku: '', newSkuCode: '', shippingMark: '', customerCartonMarks: '', destinationWarehouseId: '' })
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="warehouse-service-page" :class="{ 'warehouse-service-page--detail': mode === 'detail', 'warehouse-service-page--return-relabel': isReturnRelabelSource }">
|
<section class="warehouse-service-page" :class="{ 'warehouse-service-page--detail': mode === 'detail', 'warehouse-service-page--return-relabel': isReturnRelabelSource }">
|
||||||
<template v-if="mode === 'list'">
|
<template v-if="mode === 'list'">
|
||||||
<QueryToolbar v-model="listQueryModel" layout="grid" :ariaLabel="`${config.title}筛选`" :fields="listQueryFields" :search-on-reset="false" @search="query" @reset="resetListQuery" />
|
<QueryToolbar v-model="listQueryModel" :class="{ 'labeling-query': props.service === 'labeling', 'transfer-query': props.service === 'transfer' || props.service === 'disposal', 'disposal-query': props.service === 'disposal' }" layout="grid" :ariaLabel="`${config.title}筛选`" :fields="listQueryFields" :search-on-reset="false" @search="query" @reset="resetListQuery" />
|
||||||
<div class="warehouse-card warehouse-table-card">
|
<div class="warehouse-card warehouse-table-card">
|
||||||
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="submittedRows" :columns="listColumns" :loading="loading" :total="total" :page-sizes="[15, 30, 50, 100]" :row-actions="listRowActions" :empty-text="config.emptyText">
|
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="submittedRows" :columns="listColumns" :loading="loading" :total="total" :page-sizes="[15, 30, 50, 100]" :row-actions="listRowActions" :empty-text="config.emptyText">
|
||||||
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />{{ props.service === 'relabel' ? '新建退货换标单' : props.service === 'transfer' ? '新增订单' : `新增${config.title}` }}</el-button></template>
|
<template #toolbar-actions><el-button v-if="canCreate" type="primary" @click="openCreate"><Plus :size="16" />{{ props.service === 'relabel' ? '新建退货换标单' : props.service === 'transfer' ? '新增订单' : `新增${config.title}` }}</el-button></template>
|
||||||
<template v-if="props.service === 'transfer' && submittedRows.some((item) => item.__status === 'WAIT_CUSTOMER_CONFIRMATION')" #before-table><div class="warehouse-list-notice">部分入库完成订单已有 PDA 实测数据,请在对应行确认测量数据。</div></template>
|
<template v-if="props.service === 'transfer' && submittedRows.some((item) => item.__status === 'WAIT_CUSTOMER_CONFIRMATION')" #before-table><div class="warehouse-list-notice">部分入库完成订单已有 PDA 实测数据,请在对应行确认测量数据。</div></template>
|
||||||
<template #transferRelabelStatus="{ row }"><el-tag :type="transferRelabelStatusTagType(row.__relabelStatus)" effect="light">{{ row.__relabelStatusLabel }}</el-tag></template>
|
<template #transferRelabelStatus="{ row }"><el-tag :type="transferRelabelStatusTagType(row.__relabelStatus)" effect="light">{{ row.__relabelStatusLabel }}</el-tag></template>
|
||||||
|
<template #labelingType="{ row }"><span v-if="row['5'] === '—'">—</span><span v-else class="labeling-type-tags"><el-tag v-for="label in labelingTypeLabels(row['5'])" :key="label" :type="labelingTypeTagType(label)" size="small" effect="light">{{ label }}</el-tag></span></template>
|
||||||
|
<template #labelingStatus="{ row }"><el-tag :type="labelingStatusTagType(row.__status)" size="small" effect="light">{{ statusLabel(row.__status) }}</el-tag></template>
|
||||||
<template #transferStatus="{ row }"><el-tag :type="transferStatusTagType(row.__status)" effect="light">{{ row.__statusLabel }}</el-tag></template>
|
<template #transferStatus="{ row }"><el-tag :type="transferStatusTagType(row.__status)" effect="light">{{ row.__statusLabel }}</el-tag></template>
|
||||||
</DataTable>
|
</DataTable>
|
||||||
</div>
|
</div>
|
||||||
@@ -1467,17 +1524,26 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
<template v-else-if="mode === 'create' || mode === 'edit'">
|
<template v-else-if="mode === 'create' || mode === 'edit'">
|
||||||
<div class="warehouse-page-heading"><h2>{{ mode === 'edit' ? `编辑转运草稿 ${editingTransferNo}` : config.createTitle }}</h2><el-button @click="returnToList"><ArrowLeft :size="16" />返回列表</el-button></div>
|
<div class="warehouse-page-heading"><h2>{{ mode === 'edit' ? `编辑转运草稿 ${editingTransferNo}` : config.createTitle }}</h2><el-button @click="returnToList"><ArrowLeft :size="16" />返回列表</el-button></div>
|
||||||
<form :class="{ 'warehouse-transfer-form': props.service === 'transfer', 'warehouse-transfer-form--relabel': props.service === 'transfer' && form.relabel }" @submit.prevent="submit('submit')">
|
<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-card warehouse-form-section warehouse-transfer-main-card">
|
||||||
<div class="warehouse-form-grid">
|
<div v-if="props.service === 'labeling'" class="warehouse-order-info-heading">
|
||||||
|
<h3>订单信息</h3>
|
||||||
|
<el-button text type="primary" native-type="button" :aria-expanded="!orderInfoCollapsed" @click="orderInfoCollapsed = !orderInfoCollapsed">{{ orderInfoCollapsed ? '展开信息' : '收起信息' }}</el-button>
|
||||||
|
</div>
|
||||||
|
<h3 v-else>{{ props.service === 'transfer' ? '转运信息' : props.service === 'relabel' ? '退货信息' : '基础信息' }}</h3>
|
||||||
|
<div v-if="props.service === 'labeling' && orderInfoCollapsed" class="warehouse-order-info-summary">
|
||||||
|
<span>{{ operationWarehouses.find(item => String(item.id) === form.warehouse)?.warehouseName || '未选择操作仓' }}</span>
|
||||||
|
<span>{{ relabelInboundOptions.find(item => item.value === selectedRelabelInboundOrderId)?.inboundOrderNo || '未选择来源单据' }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-show="props.service !== 'labeling' || !orderInfoCollapsed" class="warehouse-form-grid">
|
||||||
<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="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 === '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>进仓编号</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-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'" 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-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-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 === 'labeling'" class="warehouse-span-2"><span><i>*</i>选择入仓单或退货单</span><el-select v-model="selectedRelabelInboundOrderId" filterable clearable :filter-method="(value: string) => relabelInventorySearch = value" :loading="relabelCandidatesLoading" :disabled="!form.warehouse" no-data-text="暂无匹配的可选库存" placeholder="搜索单号或选择可用库存" @change="selectRelabelInventory"><el-option v-for="option in visibleRelabelInboundOptions.filter(item => !relabelInventorySearch.trim() || item.inboundOrderNo.toUpperCase().includes(relabelInventorySearch.trim().toUpperCase()) || item.inboundCode.toUpperCase().includes(relabelInventorySearch.trim().toUpperCase()))" :key="option.value" :label="relabelOptionLabel(option)" :value="option.value" :disabled="option.availablePackages <= 0" /></el-select><small class="warehouse-hint">在仓数量包含被占用货物;本次可选数量才可加入申请。合箱后的库存按当前包裹/箱展示,来源退货单保留。</small></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>
|
<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>
|
||||||
<label v-if="props.service === 'labeling' && (isReturnRelabelSource || labelingMode !== 'sku')"><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 === 'labeling' && labelingMode !== 'sku'"><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>
|
||||||
<div v-if="props.service === 'transfer'" class="warehouse-choice-field warehouse-span-2"><span><i>*</i>入仓方式</span><el-radio-group v-model="form.deliveryMethod" @change="selectTransferInboundMethod"><el-radio-button value="WAREHOUSE_PICKUP">仓库上门提货</el-radio-button><el-radio-button value="CUSTOMER_DELIVERY">客户送货到仓</el-radio-button></el-radio-group></div>
|
<div v-if="props.service === 'transfer'" class="warehouse-choice-field warehouse-span-2"><span><i>*</i>入仓方式</span><el-radio-group v-model="form.deliveryMethod" @change="selectTransferInboundMethod"><el-radio-button value="WAREHOUSE_PICKUP">仓库上门提货</el-radio-button><el-radio-button value="CUSTOMER_DELIVERY">客户送货到仓</el-radio-button></el-radio-group></div>
|
||||||
<label v-if="props.service === 'transfer' && form.deliveryMethod === 'WAREHOUSE_PICKUP'" class="pickup-address-field"><span><i>*</i>提货地址</span><el-input v-model="form.address" placeholder="请输入仓库上门提货的详细地址" /></label>
|
<label v-if="props.service === 'transfer' && form.deliveryMethod === 'WAREHOUSE_PICKUP'" class="pickup-address-field"><span><i>*</i>提货地址</span><el-input v-model="form.address" placeholder="请输入仓库上门提货的详细地址" /></label>
|
||||||
<label v-if="props.service === 'transfer' && form.deliveryMethod === 'WAREHOUSE_PICKUP'"><span><i>*</i>提货联系人</span><el-input v-model="form.pickupContact" placeholder="请输入提货联系人" maxlength="128" /></label>
|
<label v-if="props.service === 'transfer' && form.deliveryMethod === 'WAREHOUSE_PICKUP'"><span><i>*</i>提货联系人</span><el-input v-model="form.pickupContact" placeholder="请输入提货联系人" maxlength="128" /></label>
|
||||||
@@ -1520,16 +1586,16 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
<div class="warehouse-section-heading warehouse-labeling-heading">
|
<div class="warehouse-section-heading warehouse-labeling-heading">
|
||||||
<div><h3>货物明细</h3></div>
|
<div><h3>货物明细</h3></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="warehouse-file-groups" :class="{ 'warehouse-file-groups--single': isReturnRelabelSource }">
|
<div class="warehouse-file-groups warehouse-file-groups--compact">
|
||||||
<section v-if="canManageRelabelFiles" class="warehouse-file-group warehouse-file-group--primary">
|
<section v-if="canManageRelabelFiles" class="warehouse-file-group warehouse-file-group--primary">
|
||||||
<div class="warehouse-file-group__heading"><div><strong><span>1</span>贴标总文件</strong></div><em>{{ requiresBothTotalFiles ? '必传 · 两份文件' : '必传 · 二选一' }}</em></div>
|
<div class="warehouse-file-group__heading"><div><strong><span>1</span>贴标总文件</strong></div><em>{{ requiresBothTotalFiles ? '必传 · 两份文件' : isReturnRelabelSource ? labelingMode === 'sku' ? '必传 · SKU 标签文件' : '必传 · 箱唛文件' : '必传 · 二选一' }}</em></div>
|
||||||
<div class="warehouse-file-options">
|
<div class="warehouse-file-options">
|
||||||
<div class="warehouse-file-option" :class="{ 'is-selected': Boolean(cartonTotalFile) }"><div class="warehouse-file-option__name"><strong>箱唛总文件</strong></div><el-button native-type="button" :type="cartonTotalFile ? 'primary' : 'default'" plain @click="chooseCreateTotalFile('CARTON_TOTAL')"><Upload :size="15" />{{ cartonTotalFile ? '重新上传' : '选择文件' }}</el-button><div class="warehouse-file-option__status" :class="{ 'is-empty': !cartonTotalFile }"><span>{{ cartonTotalFile?.name || '尚未选择文件' }}</span><button v-if="cartonTotalFile" type="button" class="warehouse-file-clear" title="清除箱唛总文件" aria-label="清除箱唛总文件" :disabled="saving" @click="clearCreateTotalFile('CARTON_TOTAL')"><X :size="14" /></button></div></div>
|
<div class="warehouse-file-option" :class="{ 'is-selected': Boolean(cartonTotalFile) }"><div class="warehouse-file-option__name"><strong>箱唛总文件</strong></div><el-button native-type="button" :type="cartonTotalFile ? 'primary' : 'default'" plain @click="chooseCreateTotalFile('CARTON_TOTAL')"><Upload :size="15" />{{ cartonTotalFile ? '重新上传' : '选择文件' }}</el-button><div class="warehouse-file-option__status" :class="{ 'is-empty': !cartonTotalFile }"><span>{{ cartonTotalFile?.name || '尚未选择文件' }}</span><button v-if="cartonTotalFile" type="button" class="warehouse-file-clear" title="清除箱唛总文件" aria-label="清除箱唛总文件" :disabled="saving" @click="clearCreateTotalFile('CARTON_TOTAL')"><X :size="14" /></button></div></div>
|
||||||
<div class="warehouse-file-choice-or" :class="{ 'is-both': requiresBothTotalFiles }">{{ requiresBothTotalFiles ? '和' : '或' }}</div>
|
<div class="warehouse-file-choice-or" :class="{ 'is-both': requiresBothTotalFiles }">{{ requiresBothTotalFiles ? '和' : '或' }}</div>
|
||||||
<div class="warehouse-file-option" :class="{ 'is-selected': Boolean(skuTotalFile) }"><div class="warehouse-file-option__name"><strong>SKU 总文件</strong></div><el-button native-type="button" :type="skuTotalFile ? 'primary' : 'default'" plain @click="chooseCreateTotalFile('SKU_TOTAL')"><Upload :size="15" />{{ skuTotalFile ? '重新上传' : '选择文件' }}</el-button><div class="warehouse-file-option__status" :class="{ 'is-empty': !skuTotalFile }"><span>{{ skuTotalFile?.name || '尚未选择文件' }}</span><button v-if="skuTotalFile" type="button" class="warehouse-file-clear" title="清除 SKU 总文件" aria-label="清除 SKU 总文件" :disabled="saving" @click="clearCreateTotalFile('SKU_TOTAL')"><X :size="14" /></button></div></div>
|
<div class="warehouse-file-option" :class="{ 'is-selected': Boolean(skuTotalFile) }"><div class="warehouse-file-option__name"><strong>SKU 总文件</strong></div><el-button native-type="button" :type="skuTotalFile ? 'primary' : 'default'" plain @click="chooseCreateTotalFile('SKU_TOTAL')"><Upload :size="15" />{{ skuTotalFile ? '重新上传' : '选择文件' }}</el-button><div class="warehouse-file-option__status" :class="{ 'is-empty': !skuTotalFile }"><span>{{ skuTotalFile?.name || '尚未选择文件' }}</span><button v-if="skuTotalFile" type="button" class="warehouse-file-clear" title="清除 SKU 总文件" aria-label="清除 SKU 总文件" :disabled="saving" @click="clearCreateTotalFile('SKU_TOTAL')"><X :size="14" /></button></div></div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section v-if="!isReturnRelabelSource" class="warehouse-file-group">
|
<section class="warehouse-file-group">
|
||||||
<div class="warehouse-file-group__heading"><div><strong><span>2</span>明细关联模板</strong></div><em>按需使用</em></div>
|
<div class="warehouse-file-group__heading"><div><strong><span>2</span>明细关联模板</strong></div><em>按需使用</em></div>
|
||||||
<div class="warehouse-template-list">
|
<div class="warehouse-template-list">
|
||||||
<div><span><strong>SKU 关联</strong></span><el-button size="small" :disabled="!cargoRows.length" @click="downloadRelabelTemplate('sku')"><Download :size="15" />下载模板</el-button><el-button type="primary" plain size="small" :disabled="!cargoRows.length" @click="skuTemplateInput?.click()"><Upload :size="15" />上传文件</el-button></div>
|
<div><span><strong>SKU 关联</strong></span><el-button size="small" :disabled="!cargoRows.length" @click="downloadRelabelTemplate('sku')"><Download :size="15" />下载模板</el-button><el-button type="primary" plain size="small" :disabled="!cargoRows.length" @click="skuTemplateInput?.click()"><Upload :size="15" />上传文件</el-button></div>
|
||||||
@@ -1539,13 +1605,20 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<input ref="skuTemplateInput" class="warehouse-hidden-input" type="file" accept=".csv,text/csv" @change="importRelabelTemplate($event, 'sku')"><input ref="cartonTemplateInput" class="warehouse-hidden-input" type="file" accept=".csv,text/csv" @change="importRelabelTemplate($event, 'carton')"><input ref="mixedTemplateInput" class="warehouse-hidden-input" type="file" accept=".csv,text/csv" @change="importRelabelTemplate($event, 'mixed')"><input ref="cartonTotalCreateInput" class="warehouse-hidden-input" type="file" accept="application/pdf,.pdf" @change="selectCartonTotalFile"><input ref="skuTotalCreateInput" class="warehouse-hidden-input" type="file" accept="application/pdf,.pdf" @change="selectSkuTotalFile">
|
<input ref="skuTemplateInput" class="warehouse-hidden-input" type="file" accept=".csv,text/csv" @change="importRelabelTemplate($event, 'sku')"><input ref="cartonTemplateInput" class="warehouse-hidden-input" type="file" accept=".csv,text/csv" @change="importRelabelTemplate($event, 'carton')"><input ref="mixedTemplateInput" class="warehouse-hidden-input" type="file" accept=".csv,text/csv" @change="importRelabelTemplate($event, 'mixed')"><input ref="cartonTotalCreateInput" class="warehouse-hidden-input" type="file" accept="application/pdf,.pdf" @change="selectCartonTotalFile"><input ref="skuTotalCreateInput" class="warehouse-hidden-input" type="file" accept="application/pdf,.pdf" @change="selectSkuTotalFile">
|
||||||
|
<p v-if="isReturnRelabelSource" class="warehouse-list-notice">仓库识别码用于定位实物,不代表商品已换标。SKU 换标完成后扣减旧 SKU、增加新 SKU,包裹/箱总件数不变;已换标件数不可重复申请,剩余未换标件数可继续选择。客户确认前新 SKU 保持占用。</p>
|
||||||
<div v-if="isReturnRelabelSource" class="warehouse-table-scroll">
|
<div v-if="isReturnRelabelSource" class="warehouse-table-scroll">
|
||||||
<table class="warehouse-edit-table warehouse-return-relabel-table">
|
<el-input v-model="returnCartonQuery" clearable placeholder="按当前箱唛筛选贴标箱子" />
|
||||||
<thead><tr><th>选择</th><th>SKU</th><th>中文品名</th><th>库存总数</th><th>本次贴标数量</th></tr></thead>
|
<p class="warehouse-hint">来源退货单用于查找;贴标选择当前实物箱。跨来源单箱内数量为整箱内容,同 SKU 部分贴标请先现场分拣确认。</p>
|
||||||
<tbody><tr v-for="row in returnRelabelSkuRows" :key="row.skuCode"><td><el-checkbox :model-value="row.selected" @change="row.selected = Boolean($event)" /></td><td><strong>{{ row.skuCode }}</strong></td><td>{{ row.productNameZh || '—' }}</td><td><strong>{{ row.availableQuantity }}</strong></td><td><el-input-number v-model="row.quantity" :disabled="!row.selected" :min="1" :max="row.availableQuantity" :precision="0" controls-position="right" placeholder="请输入贴标数量" /></td></tr><tr v-if="returnRelabelSkuRows.length === 0"><td colspan="5"><div class="warehouse-empty">该退货单暂无可申请贴标的 SKU 库存</div></td></tr></tbody>
|
<template v-if="returnLooseCandidates.length">
|
||||||
</table>
|
<div class="warehouse-section-heading"><h3>可用包裹</h3><el-button text type="primary" native-type="button" :aria-expanded="!availableSkusCollapsed" aria-controls="return-available-skus" @click="availableSkusCollapsed = !availableSkusCollapsed">{{ availableSkusCollapsed ? '展开明细' : '收起明细' }}</el-button></div>
|
||||||
|
<table v-show="!availableSkusCollapsed" id="return-available-skus" class="warehouse-edit-table"><thead><tr><th>包裹识别码</th><th>来源退货单</th><th>SKU</th><th>SKU 换标结果</th><th>剩余可换(件)</th><th>操作</th></tr></thead><tbody><template v-for="source in returnLooseCandidates" :key="source.returnCartonId"><tr v-for="sku in source.skuItems" :key="sku.skuCode"><td>{{ source.cartonMark }}</td><td>{{ source.inboundOrderNo }}</td><td>{{ sku.skuCode }}</td><td><div v-for="conversion in (source.skuConversions || []).filter(item => item.status !== 'REVERSED')" :key="`${conversion.relabelNo}-${conversion.oldSkuCode}-${conversion.newSkuCode}`">{{ conversion.oldSkuCode }} → {{ conversion.newSkuCode }}:已换 {{ conversion.quantity }} 件{{ conversion.status === 'APPLIED' ? '(待确认)' : '' }}</div><span v-if="!source.skuConversions?.some(item => item.status !== 'REVERSED')">尚未换标</span></td><td>{{ sku.quantity }}</td><td><el-button size="small" :disabled="inventoryQuantity(source.availablePackages) <= 0" @click="labelingMode === 'sku' ? addReturnSkuBinding(source, sku.skuCode) : addReturnBoxBinding(source)">添加贴标</el-button></td></tr></template><tr v-if="!returnLooseCandidates.length"><td colspan="6">暂无可用包裹库存</td></tr></tbody></table>
|
||||||
|
</template>
|
||||||
|
<template v-if="returnBoxCandidates.length">
|
||||||
|
<div class="warehouse-section-heading"><h3>可用箱子({{ returnBoxCandidates.length }} 箱)</h3><el-button text type="primary" native-type="button" :aria-expanded="!availableBoxesCollapsed" aria-controls="return-available-boxes" @click="availableBoxesCollapsed = !availableBoxesCollapsed">{{ availableBoxesCollapsed ? '展开明细' : '收起明细' }}</el-button></div>
|
||||||
|
<table v-show="!availableBoxesCollapsed" id="return-available-boxes" class="warehouse-edit-table"><thead><tr><th>仓库箱识别码</th><th>来源退货单</th><th>箱内 SKU</th><th>SKU 换标结果</th><th>剩余可换(件)</th><th>操作</th></tr></thead><tbody><tr v-for="source in returnBoxCandidates" :key="source.returnCartonId"><td><strong>{{ source.cartonMark }}</strong></td><td>{{ source.inboundOrderNo }}</td><td><div v-for="sku in source.skuItems" :key="sku.skuCode">{{ sku.skuCode }}</div></td><td><div v-for="conversion in (source.skuConversions || []).filter(item => item.status !== 'REVERSED')" :key="`${conversion.relabelNo}-${conversion.oldSkuCode}-${conversion.newSkuCode}`">{{ conversion.oldSkuCode }} → {{ conversion.newSkuCode }}:已换 {{ conversion.quantity }} 件{{ conversion.status === 'APPLIED' ? '(待确认)' : '' }}</div><span v-if="!source.skuConversions?.some(item => item.status !== 'REVERSED')">尚未换标</span></td><td><div v-for="sku in source.skuItems" :key="sku.skuCode">{{ sku.quantity }}</div></td><td><el-button size="small" :disabled="inventoryQuantity(source.availablePackages) <= 0" @click="addReturnBoxBinding(source)">添加贴标</el-button></td></tr><tr v-if="!returnBoxCandidates.length"><td colspan="6">暂无可用箱子库存</td></tr></tbody></table>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!isReturnRelabelSource" class="warehouse-labeling-mode">
|
<div class="warehouse-labeling-mode">
|
||||||
<span>换标类型</span>
|
<span>换标类型</span>
|
||||||
<el-radio-group v-model="labelingMode" aria-label="换标类型">
|
<el-radio-group v-model="labelingMode" aria-label="换标类型">
|
||||||
<el-radio-button value="carton">只换箱唛</el-radio-button>
|
<el-radio-button value="carton">只换箱唛</el-radio-button>
|
||||||
@@ -1553,17 +1626,17 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
<el-radio-button value="carton_and_sku">SKU 和箱唛都换</el-radio-button>
|
<el-radio-button value="carton_and_sku">SKU 和箱唛都换</el-radio-button>
|
||||||
</el-radio-group>
|
</el-radio-group>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!isReturnRelabelSource && importedRelabelBindings.length" class="warehouse-import-preview">
|
<div v-if="importedRelabelBindings.length" class="warehouse-import-preview">
|
||||||
<div class="warehouse-section-heading"><div><strong>待导入绑定关系</strong><p>可只勾选本次需要换标的部分,也可以全选后一次导入。</p></div><div><el-checkbox :model-value="importedRelabelBindings.every((item) => item.selected)" @change="selectAllImportedBindings(Boolean($event))">全选</el-checkbox><el-button type="primary" size="small" @click="importSelectedBindingsToDetails">导入到明细</el-button></div></div>
|
<div class="warehouse-section-heading"><div><strong>待导入绑定关系</strong><p>可只勾选本次需要换标的部分,也可以全选后一次导入。</p></div><div><el-checkbox :model-value="importedRelabelBindings.every((item) => item.selected)" @change="selectAllImportedBindings(Boolean($event))">全选</el-checkbox><el-button type="primary" size="small" @click="importSelectedBindingsToDetails">导入到明细</el-button></div></div>
|
||||||
<div class="warehouse-table-scroll"><table class="warehouse-binding-preview-table"><thead><tr><th>选择</th><th>关系类型</th><th>仓库唛头</th><th>旧 SKU</th><th>新 SKU</th><th>数量</th><th>新 FBA 箱唛</th></tr></thead><tbody><tr v-for="item in importedRelabelBindings" :key="item.id"><td><el-checkbox v-model="item.selected" /></td><td>{{ item.templateType === 'mixed' ? 'SKU 混箱换标' : item.templateType === 'carton' ? '箱号关联' : 'SKU 关联' }}</td><td>{{ item.cartonMark }}</td><td>{{ item.originalSku || '—' }}</td><td>{{ item.newSku || '—' }}</td><td>{{ item.quantity }}</td><td>{{ item.fbaCartonMark || '—' }}</td></tr></tbody></table></div>
|
<div class="warehouse-table-scroll"><table class="warehouse-binding-preview-table"><thead><tr><th>选择</th><th>关系类型</th><th>仓库唛头</th><th>旧 SKU</th><th>新 SKU</th><th>数量</th><th>新 FBA 箱唛</th></tr></thead><tbody><tr v-for="item in importedRelabelBindings" :key="item.id"><td><el-checkbox v-model="item.selected" /></td><td>{{ item.templateType === 'mixed' ? 'SKU 混箱换标' : item.templateType === 'carton' ? '箱号关联' : 'SKU 关联' }}</td><td>{{ item.cartonMark }}</td><td>{{ item.originalSku || '—' }}</td><td>{{ item.newSku || '—' }}</td><td>{{ item.quantity }}</td><td>{{ item.fbaCartonMark || '—' }}</td></tr></tbody></table></div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!isReturnRelabelSource" class="warehouse-section-heading warehouse-tab-actions">
|
<div class="warehouse-section-heading warehouse-tab-actions">
|
||||||
<div><strong>绑定明细</strong></div>
|
<div><strong>绑定明细</strong></div>
|
||||||
<div v-if="labelingMode === 'carton'"><el-button type="primary" size="small" @click="addRelabelCargoRow"><Plus :size="15" />手动添加行</el-button><el-button size="small" @click="clearRelabelRows">清空</el-button></div>
|
<div v-if="labelingMode === 'carton'"><el-button type="primary" size="small" @click="addRelabelCargoRow"><Plus :size="15" />手动添加行</el-button><el-button size="small" @click="clearRelabelRows">清空</el-button></div>
|
||||||
<div v-else><el-button type="primary" size="small" @click="addSkuRelabelRow"><Plus :size="15" />添加 SKU 明细</el-button><el-button size="small" @click="skuRelabelRows = []">清空</el-button></div>
|
<div v-else><el-button type="primary" size="small" @click="addSkuRelabelRow"><Plus :size="15" />添加 SKU 明细</el-button><el-button size="small" @click="skuRelabelRows = []">清空</el-button></div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="!isReturnRelabelSource && labelingMode === 'carton'" class="warehouse-table-scroll"><table class="warehouse-edit-table warehouse-label-table"><thead><tr><th>商品 SKU</th><th>中文品名 *</th><th>FBA 货件编号 *</th><th>箱数</th><th>仓库唛头 *</th><th>新 FBA 箱唛 *</th><th>备注</th><th>操作</th></tr></thead><tbody><tr v-for="row in cartonDetailRows" :key="row.id"><td><el-input v-model="row.sku" placeholder="选填" /></td><td><el-input v-model="row.name" placeholder="请输入中文品名" /></td><td><el-input v-model="row.shipmentNo" placeholder="请输入FBA货件编号" /></td><td><strong>1 箱</strong></td><td><el-input v-model="row.cartonMark" placeholder="请输入仓库唛头" /></td><td><el-input v-model="row.fbaCartonMark" placeholder="请输入新的 FBA 箱唛" /></td><td><el-input v-model="row.remark" type="textarea" :rows="2" maxlength="1000" show-word-limit placeholder="请输入明细备注" /></td><td><button type="button" class="warehouse-delete" title="移出本次明细" @click="removeCargoRow(row.id)"><Trash2 :size="16" />移出</button></td></tr><tr v-if="cartonDetailRows.length === 0"><td colspan="8"><div class="warehouse-empty">暂无本次换标明细,请上传关系后导入或手动添加</div></td></tr></tbody></table></div>
|
<div v-if="labelingMode === 'carton'" class="warehouse-table-scroll"><table class="warehouse-edit-table warehouse-label-table"><thead><tr><th>商品 SKU</th><th>中文品名 *</th><th>FBA 货件编号 *</th><th>箱数</th><th>仓库唛头 *</th><th>新 FBA 箱唛 *</th><th>备注</th><th>操作</th></tr></thead><tbody><tr v-for="row in cartonDetailRows" :key="row.id"><td><el-input v-model="row.sku" placeholder="选填" /></td><td><el-input v-model="row.name" placeholder="请输入中文品名" /></td><td><el-input v-model="row.shipmentNo" placeholder="请输入FBA货件编号" /></td><td><strong>1 箱</strong></td><td><el-input v-model="row.cartonMark" :readonly="isReturnRelabelSource" placeholder="请输入仓库唛头" /></td><td><el-input v-model="row.fbaCartonMark" placeholder="请输入新的 FBA 箱唛" /></td><td><el-input v-model="row.remark" type="textarea" :rows="2" maxlength="1000" show-word-limit placeholder="请输入明细备注" /></td><td><button type="button" class="warehouse-delete" title="移出本次明细" @click="removeCargoRow(row.id)"><Trash2 :size="16" />移出</button></td></tr><tr v-if="cartonDetailRows.length === 0"><td colspan="8"><div class="warehouse-empty">暂无本次换标明细,请上传关系后导入或手动添加</div></td></tr></tbody></table></div>
|
||||||
<div v-else class="warehouse-table-scroll"><table class="warehouse-edit-table warehouse-sku-label-table"><thead><tr><th>仓库唛头 *</th><th>旧 SKU *</th><th>新 SKU *</th><th>换标数量(件)*</th><th v-if="labelingMode === 'carton_and_sku'">新 FBA 箱唛 *</th><th>备注</th><th>操作</th></tr></thead><tbody><tr v-for="row in skuRelabelRows" :key="row.id"><td><el-input v-model="row.cartonMark" placeholder="请输入仓库唛头" @change="applyExistingCartonBinding(row)" /></td><td><el-input v-model="row.originalSku" placeholder="请输入旧 SKU" @change="applyExistingSkuBinding(row)" /></td><td><el-input v-model="row.newSku" placeholder="请输入新 SKU" /></td><td><el-input-number v-model="row.quantity" :min="1" :precision="0" controls-position="right" placeholder="请输入件数" /></td><td v-if="labelingMode === 'carton_and_sku'"><el-input v-model="row.fbaCartonMark" placeholder="请输入新的 FBA 箱唛" /></td><td><el-input v-model="row.remark" placeholder="请输入备注" /></td><td><button type="button" class="warehouse-delete" title="删除" @click="removeSkuRelabelRow(row.id)"><Trash2 :size="16" />删除</button></td></tr><tr v-if="skuRelabelRows.length === 0"><td :colspan="labelingMode === 'carton_and_sku' ? 7 : 6"><div class="warehouse-empty">暂无绑定明细,请点击“添加 SKU 明细”</div></td></tr></tbody></table></div>
|
<div v-else class="warehouse-table-scroll"><table class="warehouse-edit-table warehouse-sku-label-table"><thead><tr><th>仓库唛头 *</th><th>旧 SKU *</th><th>新 SKU *</th><th>换标数量(件)*</th><th v-if="labelingMode === 'carton_and_sku'">新 FBA 箱唛 *</th><th v-if="labelingMode === 'carton_and_sku'">FBA 货件编号 *</th><th>备注</th><th>操作</th></tr></thead><tbody><tr v-for="row in skuRelabelRows" :key="row.id"><td><el-input v-model="row.cartonMark" :readonly="isReturnRelabelSource" placeholder="请输入仓库唛头" @change="applyExistingCartonBinding(row)" /></td><td><el-input v-model="row.originalSku" :readonly="isReturnRelabelSource" placeholder="请输入旧 SKU" @change="applyExistingSkuBinding(row)" /></td><td><el-input v-model="row.newSku" placeholder="请输入新 SKU" /></td><td><el-input-number v-model="row.quantity" :min="1" :precision="0" controls-position="right" placeholder="请输入件数" /></td><td v-if="labelingMode === 'carton_and_sku'"><el-input v-model="row.fbaCartonMark" placeholder="请输入新的 FBA 箱唛" /></td><td v-if="labelingMode === 'carton_and_sku'"><el-input v-model="row.shipmentNo" placeholder="请输入 FBA 货件编号" /></td><td><el-input v-model="row.remark" placeholder="请输入备注" /></td><td><button type="button" class="warehouse-delete" title="删除" @click="removeSkuRelabelRow(row.id)"><Trash2 :size="16" />删除</button></td></tr><tr v-if="skuRelabelRows.length === 0"><td :colspan="labelingMode === 'carton_and_sku' ? 8 : 6"><div class="warehouse-empty">暂无绑定明细,请点击“添加 SKU 明细”</div></td></tr></tbody></table></div>
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<div class="warehouse-section-heading" :class="{ 'warehouse-step-heading': props.service === 'transfer' }"><div><h3><span v-if="props.service === 'transfer'" class="warehouse-step-number">1</span>货物明细</h3></div><div v-if="props.service !== 'disposal'" class="warehouse-heading-actions"><el-button v-if="props.service === 'transfer'" size="small" :disabled="!cargoRows.some((row) => row.sku.trim() && row.quantity > 0)" @click="printTransferDraftCartonMarks"><Printer :size="15" />打印唛头</el-button><el-button type="primary" size="small" @click="addCargoRow"><Plus :size="15" />添加行</el-button><el-button size="small" @click="cargoRows = []">清空</el-button></div></div>
|
<div class="warehouse-section-heading" :class="{ 'warehouse-step-heading': props.service === 'transfer' }"><div><h3><span v-if="props.service === 'transfer'" class="warehouse-step-number">1</span>货物明细</h3></div><div v-if="props.service !== 'disposal'" class="warehouse-heading-actions"><el-button v-if="props.service === 'transfer'" size="small" :disabled="!cargoRows.some((row) => row.sku.trim() && row.quantity > 0)" @click="printTransferDraftCartonMarks"><Printer :size="15" />打印唛头</el-button><el-button type="primary" size="small" @click="addCargoRow"><Plus :size="15" />添加行</el-button><el-button size="small" @click="cargoRows = []">清空</el-button></div></div>
|
||||||
@@ -1574,7 +1647,7 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
<div class="warehouse-section-heading warehouse-labeling-heading warehouse-step-heading"><div><h3><span class="warehouse-step-number">2</span>换标申请</h3></div></div>
|
<div class="warehouse-section-heading warehouse-labeling-heading warehouse-step-heading"><div><h3><span class="warehouse-step-number">2</span>换标申请</h3></div></div>
|
||||||
<div class="warehouse-form-grid warehouse-transfer-relabel-fields"><label><span><i>*</i>换标截止时间</span><el-date-picker v-model="form.labelDeadline" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="请选择截止时间" /></label><label><span><i>*</i>换标联系人</span><el-input v-model="form.relabelContact" placeholder="选择海外仓后自动带出,也可手动填写" maxlength="128" /></label><label><span><i>*</i>换标联系人电话</span><el-input v-model="form.relabelPhone" placeholder="选择海外仓后自动带出,也可手动填写" maxlength="64" /></label><label v-if="labelingMode !== 'sku'"><span><i>*</i>换标后派送方式</span><el-select v-model="form.relabelDeliveryMethod" placeholder="请选择派送方式"><el-option label="卡车派送" value="TRUCK" /><el-option label="快递派送" value="EXPRESS" /><el-option label="卡车自提" value="TRUCK_PICKUP" /><el-option label="快递自提" value="EXPRESS_PICKUP" /></el-select></label><label class="warehouse-span-2"><span><i>*</i>整票换标货物目的 FBA 仓</span><el-select v-model="transferRelabelDefaultDestination" :loading="fbaWarehousesLoading" :disabled="Boolean(fbaWarehousesError)" filterable placeholder="请选择整票货物的目的仓"><el-option v-for="warehouse in fbaWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="warehouse.warehouseCode" /></el-select><small class="warehouse-hint">本票所有换标货物统一前往该目的仓,暂不支持一票多个目的仓。</small></label><label class="warehouse-span-2"><span>贴标要求</span><el-input v-model="form.requirement" type="textarea" :rows="2" maxlength="1000" show-word-limit placeholder="请输入贴标要求(选填)" /></label></div>
|
<div class="warehouse-form-grid warehouse-transfer-relabel-fields"><label><span><i>*</i>换标截止时间</span><el-date-picker v-model="form.labelDeadline" type="datetime" value-format="YYYY-MM-DDTHH:mm:ss" placeholder="请选择截止时间" /></label><label><span><i>*</i>换标联系人</span><el-input v-model="form.relabelContact" placeholder="选择海外仓后自动带出,也可手动填写" maxlength="128" /></label><label><span><i>*</i>换标联系人电话</span><el-input v-model="form.relabelPhone" placeholder="选择海外仓后自动带出,也可手动填写" maxlength="64" /></label><label v-if="labelingMode !== 'sku'"><span><i>*</i>换标后派送方式</span><el-select v-model="form.relabelDeliveryMethod" placeholder="请选择派送方式"><el-option label="卡车派送" value="TRUCK" /><el-option label="快递派送" value="EXPRESS" /><el-option label="卡车自提" value="TRUCK_PICKUP" /><el-option label="快递自提" value="EXPRESS_PICKUP" /></el-select></label><label class="warehouse-span-2"><span><i>*</i>整票换标货物目的 FBA 仓</span><el-select v-model="transferRelabelDefaultDestination" :loading="fbaWarehousesLoading" :disabled="Boolean(fbaWarehousesError)" filterable placeholder="请选择整票货物的目的仓"><el-option v-for="warehouse in fbaWarehouses" :key="warehouse.id" :label="warehouseLabel(warehouse)" :value="warehouse.warehouseCode" /></el-select><small class="warehouse-hint">本票所有换标货物统一前往该目的仓,暂不支持一票多个目的仓。</small></label><label class="warehouse-span-2"><span>贴标要求</span><el-input v-model="form.requirement" type="textarea" :rows="2" maxlength="1000" show-word-limit placeholder="请输入贴标要求(选填)" /></label></div>
|
||||||
<div class="warehouse-labeling-mode"><span>换标类型</span><el-radio-group v-model="labelingMode" aria-label="换标类型"><el-radio-button value="carton">只换箱唛</el-radio-button><el-radio-button value="sku">只换 SKU 标签</el-radio-button><el-radio-button value="carton_and_sku">SKU 和箱唛都换</el-radio-button></el-radio-group></div>
|
<div class="warehouse-labeling-mode"><span>换标类型</span><el-radio-group v-model="labelingMode" aria-label="换标类型"><el-radio-button value="carton">只换箱唛</el-radio-button><el-radio-button value="sku">只换 SKU 标签</el-radio-button><el-radio-button value="carton_and_sku">SKU 和箱唛都换</el-radio-button></el-radio-group></div>
|
||||||
<div class="warehouse-transfer-file-groups">
|
<div class="warehouse-transfer-file-groups warehouse-file-groups--compact">
|
||||||
<section v-if="canManageRelabelFiles" class="warehouse-file-group warehouse-transfer-total-files">
|
<section v-if="canManageRelabelFiles" class="warehouse-file-group warehouse-transfer-total-files">
|
||||||
<div class="warehouse-file-group__heading"><div><strong>贴标总文件</strong></div><em>{{ requiresBothTotalFiles ? '必传 · 两份文件' : '必传 · 二选一' }}</em></div>
|
<div class="warehouse-file-group__heading"><div><strong>贴标总文件</strong></div><em>{{ requiresBothTotalFiles ? '必传 · 两份文件' : '必传 · 二选一' }}</em></div>
|
||||||
<div class="warehouse-file-options">
|
<div class="warehouse-file-options">
|
||||||
@@ -1607,7 +1680,10 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
</header>
|
</header>
|
||||||
<div v-if="detailError" class="warehouse-detail-error" role="alert"><strong>{{ detailError }}</strong><el-button @click="loadDetailPage">重新加载</el-button></div>
|
<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 || '平台未填写驳回备注'" />
|
<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 || '平台未填写驳回备注'" />
|
||||||
<div v-else class="warehouse-card warehouse-form-section"><h3>订单概览</h3><div v-if="props.service === 'labeling'" class="warehouse-detail-grid"><div><span>操作仓</span><strong>{{ warehouseDisplay(selectedRelabelDetail?.application.overseasWarehouseId) }}</strong></div><div><span>客户参考号</span><strong>{{ selectedRelabelDetail?.application.customerOrderNo || '—' }}</strong></div><div><span>SKU 数</span><strong>{{ selectedRelabelDetail?.application.itemCount ?? '—' }}</strong></div><div><span>总箱数</span><strong>{{ selectedRelabelDetail?.application.totalPackageCount ?? '—' }}</strong></div><div><span>贴标截止时间</span><strong>{{ formatDateTime(selectedRelabelDetail?.application.labelDeadline) }}</strong></div><div><span>仓库联系人</span><strong>{{ selectedRelabelDetail?.application.contactName || '—' }}</strong></div><div><span>联系电话</span><strong>{{ selectedRelabelDetail?.application.contactPhone || '—' }}</strong></div><div><span>创建时间</span><strong>{{ formatDateTime(selectedRelabelDetail?.application.createdAt) }}</strong></div></div><div v-else-if="props.service === 'transfer'" class="warehouse-detail-grid warehouse-transfer-overview-grid"><div><span>状态</span><el-tag :type="transferStatusTagType(selectedDetail?.status || '')" effect="light">{{ statusLabel(selectedDetail?.status || '') }}</el-tag></div><div><span>目的去向</span><strong>{{ destinationTypeLabel(selectedDetail?.destinationType, selectedDetail?.fbaWarehouseCode) }}</strong></div><div v-if="selectedDetail?.destinationType !== 'PRIVATE'"><span>FBA 目的仓</span><strong>{{ selectedDetail?.destinationWarehouseName || warehouseDisplay(selectedDetail?.destinationWarehouseCode || selectedDetail?.fbaWarehouseCode) }}</strong></div><div v-if="selectedDetail?.destinationType !== 'PRIVATE'"><span>FBA 货件号</span><strong>{{ selectedDetail?.fbaShipmentNo || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'" class="warehouse-overview-wide"><span>私人仓地址</span><strong>{{ selectedDetail?.privateDestinationAddress || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'"><span>邮编</span><strong>{{ selectedDetail?.privateDestinationPostalCode || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'"><span>私人仓联系人</span><strong>{{ selectedDetail?.privateDestinationContactName || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'"><span>联系电话</span><strong>{{ selectedDetail?.privateDestinationContactPhone || '—' }}</strong></div><div><span>海外仓</span><strong>{{ warehouseDisplay(selectedDetail?.operatingWarehouseId) }}</strong></div><div><span>箱数</span><strong>{{ selectedDetail?.packageCount ?? '—' }}</strong></div><div><span>入仓方式</span><strong>{{ deliveryMethodLabel(selectedDetail?.deliveryMethod || '') }}</strong></div><div><span>期望发货时间</span><strong>{{ formatDateTime(selectedDetail?.estimatedShipAt) }}</strong></div><div><span>实际发货时间</span><strong>{{ formatDateTime(selectedDetail?.actualShipAt) }}</strong></div><div><span>是否换标</span><strong>{{ selectedDetail?.needRelabel ? '是' : '否' }}</strong></div><div><span>换标状态</span><el-tag :type="transferRelabelStatusTagType(transferRelabelStatus(selectedDetail || {}).code)" effect="light">{{ transferRelabelStatus(selectedDetail || {}).label }}</el-tag></div><div><span>换标单号</span><strong>{{ selectedDetail?.relabelNo || '—' }}</strong></div><div><span>创建时间</span><strong>{{ formatDateTime(selectedDetail?.createdAt) }}</strong></div><div><span>转运单号</span><strong>{{ selectedDetail?.transferNo || '—' }}</strong></div></div><div v-else class="warehouse-detail-grid"><div v-for="(column, index) in config.columns.slice(1)" :key="column"><span>{{ column }}</span><strong>{{ selectedDetail?.[String(index)] || '—' }}</strong></div></div></div>
|
<div v-else class="warehouse-card warehouse-form-section"><h3>订单概览</h3><div v-if="props.service === 'labeling'" class="warehouse-detail-grid"><div><span>操作仓</span><strong>{{ warehouseDisplay(selectedRelabelDetail?.application.overseasWarehouseId) }}</strong></div><div><span>客户参考号</span><strong>{{ selectedRelabelDetail?.application.customerOrderNo || '—' }}</strong></div><div><span>SKU 数(种)</span><strong>{{ selectedRelabelDetail ? relabelSkuCount(selectedRelabelDetail.items) : '—' }}</strong></div><div><span>总箱数</span><strong>{{ selectedRelabelDetail?.application.totalPackageCount ?? '—' }}</strong></div><div><span>贴标截止时间</span><strong>{{ formatDateTime(selectedRelabelDetail?.application.labelDeadline) }}</strong></div><div><span>仓库联系人</span><strong>{{ selectedRelabelDetail?.application.contactName || '—' }}</strong></div><div><span>联系电话</span><strong>{{ selectedRelabelDetail?.application.contactPhone || '—' }}</strong></div><div><span>创建时间</span><strong>{{ formatDateTime(selectedRelabelDetail?.application.createdAt) }}</strong></div></div><div v-else-if="props.service === 'transfer'" class="warehouse-detail-grid warehouse-transfer-overview-grid"><div><span>状态</span><el-tag :type="transferStatusTagType(selectedDetail?.status || '')" effect="light">{{ statusLabel(selectedDetail?.status || '') }}</el-tag></div><div><span>目的去向</span><strong>{{ destinationTypeLabel(selectedDetail?.destinationType, selectedDetail?.fbaWarehouseCode) }}</strong></div><div v-if="selectedDetail?.destinationType !== 'PRIVATE'"><span>FBA 目的仓</span><strong>{{ selectedDetail?.destinationWarehouseName || warehouseDisplay(selectedDetail?.destinationWarehouseCode || selectedDetail?.fbaWarehouseCode) }}</strong></div><div v-if="selectedDetail?.destinationType !== 'PRIVATE'"><span>FBA 货件号</span><strong>{{ selectedDetail?.fbaShipmentNo || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'" class="warehouse-overview-wide"><span>私人仓地址</span><strong>{{ selectedDetail?.privateDestinationAddress || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'"><span>邮编</span><strong>{{ selectedDetail?.privateDestinationPostalCode || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'"><span>私人仓联系人</span><strong>{{ selectedDetail?.privateDestinationContactName || '—' }}</strong></div><div v-if="selectedDetail?.destinationType === 'PRIVATE'"><span>联系电话</span><strong>{{ selectedDetail?.privateDestinationContactPhone || '—' }}</strong></div><div><span>海外仓</span><strong>{{ warehouseDisplay(selectedDetail?.operatingWarehouseId) }}</strong></div><div><span>箱数</span><strong>{{ selectedDetail?.packageCount ?? '—' }}</strong></div><div><span>入仓方式</span><strong>{{ deliveryMethodLabel(selectedDetail?.deliveryMethod || '') }}</strong></div><div><span>期望发货时间</span><strong>{{ formatDateTime(selectedDetail?.estimatedShipAt) }}</strong></div><div><span>实际发货时间</span><strong>{{ formatDateTime(selectedDetail?.actualShipAt) }}</strong></div><div><span>是否换标</span><strong>{{ selectedDetail?.needRelabel ? '是' : '否' }}</strong></div><div><span>换标状态</span><el-tag :type="transferRelabelStatusTagType(transferRelabelStatus(selectedDetail || {}).code)" effect="light">{{ transferRelabelStatus(selectedDetail || {}).label }}</el-tag></div><div><span>换标单号</span><strong>{{ selectedDetail?.relabelNo || '—' }}</strong></div><div><span>创建时间</span><strong>{{ formatDateTime(selectedDetail?.createdAt) }}</strong></div><div><span>转运单号</span><strong>{{ selectedDetail?.transferNo || '—' }}</strong></div></div><div v-else class="warehouse-detail-grid"><div v-for="(column, index) in config.columns.slice(1)" :key="column"><span>{{ column }}</span><strong>{{ selectedDetail?.[String(index)] || '—' }}</strong></div></div></div>
|
||||||
|
<div v-if="props.service === 'disposal'" class="warehouse-card warehouse-form-section">
|
||||||
|
<h3>废弃现场照片</h3><div v-if="selectedDetail?.photos?.length" class="warehouse-photo-grid"><div v-for="photo in selectedDetail.photos" :key="photo.fileId" class="warehouse-photo-item"><el-image v-if="discardPhotoUrls[photo.fileId]" :src="discardPhotoUrls[photo.fileId]" :preview-src-list="discardPhotoPreviewUrls" :initial-index="discardPhotoPreviewUrls.indexOf(discardPhotoUrls[photo.fileId])" fit="cover" preview-teleported /><div v-else-if="discardPhotoLoading[photo.fileId]" class="warehouse-photo-placeholder">照片加载中…</div><button v-else class="warehouse-photo-placeholder warehouse-photo-retry" type="button" @click="loadDiscardPhoto(photo.fileId)">{{ discardPhotoErrors[photo.fileId] ? '加载失败,点击重试' : '加载照片' }}</button><small>{{ formatDateTime(photo.submittedAt) }}</small></div></div><div v-else class="warehouse-empty">暂无已提交的废弃现场照片</div>
|
||||||
|
</div>
|
||||||
<div v-if="props.service === 'transfer'" class="warehouse-card warehouse-form-section warehouse-transfer-measurement-card">
|
<div v-if="props.service === 'transfer'" class="warehouse-card warehouse-form-section warehouse-transfer-measurement-card">
|
||||||
<div class="warehouse-section-heading"><h3>PDA 打托实测数据</h3><span class="warehouse-hint">PDA 作业完成即显示入库完成,客户可确认仓库实测数据</span></div>
|
<div class="warehouse-section-heading"><h3>PDA 打托实测数据</h3><span class="warehouse-hint">PDA 作业完成即显示入库完成,客户可确认仓库实测数据</span></div>
|
||||||
<div v-if="selectedDetail?.pallets?.length" class="warehouse-table-scroll"><table><thead><tr><th>托盘号</th><th>库位</th><th>箱数</th><th>长 × 宽 × 高(cm)</th><th>毛重(kg)</th><th>体积(m³)</th><th>状态</th><th>完成时间</th></tr></thead><tbody><tr v-for="pallet in selectedDetail.pallets" :key="String(pallet.id || pallet.sequenceNo)"><td>{{ pallet.palletNo || `第${pallet.sequenceNo || '—'}托` }}</td><td>{{ pallet.warehouseLocationCode || '—' }}</td><td>{{ pallet.cartonCount ?? '—' }}</td><td>{{ [pallet.lengthCm, pallet.widthCm, pallet.heightCm].every((value) => value != null) ? `${pallet.lengthCm} × ${pallet.widthCm} × ${pallet.heightCm}` : '—' }}</td><td>{{ pallet.grossWeightKg ?? '—' }}</td><td>{{ pallet.volumeCbm ?? '—' }}</td><td>{{ statusLabel(pallet.status || '') }}</td><td>{{ formatDateTime(pallet.completedAt) }}</td></tr></tbody></table></div>
|
<div v-if="selectedDetail?.pallets?.length" class="warehouse-table-scroll"><table><thead><tr><th>托盘号</th><th>库位</th><th>箱数</th><th>长 × 宽 × 高(cm)</th><th>毛重(kg)</th><th>体积(m³)</th><th>状态</th><th>完成时间</th></tr></thead><tbody><tr v-for="pallet in selectedDetail.pallets" :key="String(pallet.id || pallet.sequenceNo)"><td>{{ pallet.palletNo || `第${pallet.sequenceNo || '—'}托` }}</td><td>{{ pallet.warehouseLocationCode || '—' }}</td><td>{{ pallet.cartonCount ?? '—' }}</td><td>{{ [pallet.lengthCm, pallet.widthCm, pallet.heightCm].every((value) => value != null) ? `${pallet.lengthCm} × ${pallet.widthCm} × ${pallet.heightCm}` : '—' }}</td><td>{{ pallet.grossWeightKg ?? '—' }}</td><td>{{ pallet.volumeCbm ?? '—' }}</td><td>{{ statusLabel(pallet.status || '') }}</td><td>{{ formatDateTime(pallet.completedAt) }}</td></tr></tbody></table></div>
|
||||||
@@ -1636,14 +1712,14 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
<div class="warehouse-section-heading"><h3>贴标明细资料</h3><input ref="relabelFileInput" class="warehouse-hidden-input" type="file" accept="application/pdf,.pdf" @change="uploadSelectedRelabelFile"></div>
|
<div class="warehouse-section-heading"><h3>贴标明细资料</h3><input ref="relabelFileInput" class="warehouse-hidden-input" type="file" accept="application/pdf,.pdf" @change="uploadSelectedRelabelFile"></div>
|
||||||
<div class="warehouse-hint">需要补充或替换资料时,可在对应明细行上传 SKU 或箱唛文件。</div>
|
<div class="warehouse-hint">需要补充或替换资料时,可在对应明细行上传 SKU 或箱唛文件。</div>
|
||||||
<div class="warehouse-table-scroll"><table class="warehouse-relabel-detail-table"><thead><tr><th>换标模式</th><th>仓库唛头</th><th>SKU</th><th>明细文件</th><th>操作</th></tr></thead><tbody>
|
<div class="warehouse-table-scroll"><table class="warehouse-relabel-detail-table"><thead><tr><th>换标模式</th><th>仓库唛头</th><th>SKU</th><th>明细文件</th><th>操作</th></tr></thead><tbody>
|
||||||
<tr v-for="item in selectedRelabelDetail?.items || []" :key="item.id"><td>{{ item.operationType === 'CARTON_AND_SKU' ? '箱唛 + SKU 换标' : item.operationType === 'SKU_LABEL' ? 'SKU 换标' : '箱唛换标' }}</td><td>{{ item.cartonMark || '—' }}</td><td>{{ item.skuCode || '—' }}</td><td>{{ item.relabelFileName || '未上传' }}</td><td><el-button size="small" @click="chooseRelabelFile('ITEM', String(item.id))"><Upload :size="14" />上传明细文件</el-button></td></tr>
|
<tr v-for="item in selectedRelabelDetail?.items || []" :key="item.id"><td>{{ item.operationType === 'CARTON_AND_SKU' ? '箱唛 + SKU 换标' : item.operationType === 'SKU_LABEL' ? 'SKU 换标' : '箱唛换标' }}</td><td>{{ item.cartonMark || '—' }}</td><td>{{ relabelSkuCodes(item).join('、') || '—' }}</td><td>{{ item.relabelFileName || '未上传' }}</td><td><el-button size="small" @click="chooseRelabelFile('ITEM', String(item.id))"><Upload :size="14" />上传明细文件</el-button></td></tr>
|
||||||
<tr v-if="!selectedRelabelDetail?.items?.length"><td colspan="5"><div class="warehouse-empty">暂无贴标明细</div></td></tr>
|
<tr v-if="!selectedRelabelDetail?.items?.length"><td colspan="5"><div class="warehouse-empty">暂无贴标明细</div></td></tr>
|
||||||
</tbody></table></div>
|
</tbody></table></div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="props.service === 'labeling'" class="warehouse-card warehouse-form-section">
|
<div v-if="props.service === 'labeling'" class="warehouse-card warehouse-form-section">
|
||||||
<h3>换标任务明细</h3>
|
<h3>换标任务明细</h3>
|
||||||
<div class="warehouse-table-scroll"><table class="warehouse-relabel-detail-table"><thead><tr><th>换标模式</th><th>我方箱唛</th><th>新 FBA 箱唛</th><th>FBA 目的仓</th><th>任务箱数</th><th>商品 SKU</th><th>SKU 换标明细</th><th>FBA 货件编号</th><th>贴标要求</th><th>备注</th></tr></thead><tbody>
|
<div class="warehouse-table-scroll"><table class="warehouse-relabel-detail-table"><thead><tr><th>换标模式</th><th>我方箱唛</th><th>新 FBA 箱唛</th><th>FBA 目的仓</th><th>任务箱数</th><th>商品 SKU</th><th>SKU 换标明细</th><th>FBA 货件编号</th><th>贴标要求</th><th>备注</th></tr></thead><tbody>
|
||||||
<tr v-for="item in selectedRelabelDetail?.items || []" :key="item.id"><td>{{ item.operationType === 'CARTON_AND_SKU' ? '箱唛 + SKU 换标' : item.operationType === 'SKU_LABEL' ? 'SKU 换标' : '箱唛换标' }}</td><td><strong>{{ item.cartonMark || '—' }}</strong></td><td><strong>{{ item.fbaCartonMark || '—' }}</strong></td><td>{{ warehouseDisplay(item.destinationFbaWarehouseCode) }}</td><td>{{ item.totalPackageCount }} 箱</td><td>{{ item.skuCode || '—' }}</td><td><template v-if="item.skuItems?.length"><div v-for="skuItem in item.skuItems" :key="`${skuItem.skuCode}-${skuItem.newSkuCode}-${skuItem.quantity}`">{{ skuItem.skuCode }} → {{ skuItem.newSkuCode }} × {{ skuItem.quantity }} 件</div></template><span v-else>{{ item.newSkuCode || '—' }}</span></td><td>{{ item.shipmentNo || '—' }}</td><td>{{ item.labelRequirement || '—' }}</td><td>{{ item.remark || '—' }}</td></tr>
|
<tr v-for="item in selectedRelabelDetail?.items || []" :key="item.id"><td>{{ item.operationType === 'CARTON_AND_SKU' ? '箱唛 + SKU 换标' : item.operationType === 'SKU_LABEL' ? 'SKU 换标' : '箱唛换标' }}</td><td><strong>{{ item.cartonMark || '—' }}</strong></td><td><strong>{{ item.fbaCartonMark || '—' }}</strong></td><td>{{ warehouseDisplay(item.destinationFbaWarehouseCode) }}</td><td>{{ item.totalPackageCount }} 箱</td><td>{{ relabelSkuCodes(item).join('、') || '—' }}</td><td><template v-if="item.skuItems?.length"><div v-for="skuItem in item.skuItems" :key="`${skuItem.skuCode}-${skuItem.newSkuCode}-${skuItem.quantity}`">{{ skuItem.skuCode }} → {{ skuItem.newSkuCode }} × {{ skuItem.quantity }} 件</div></template><span v-else>{{ item.newSkuCode || '—' }}</span></td><td>{{ item.shipmentNo || '—' }}</td><td>{{ item.labelRequirement || '—' }}</td><td>{{ item.remark || '—' }}</td></tr>
|
||||||
<tr v-if="!selectedRelabelDetail?.items?.length"><td colspan="10"><div class="warehouse-empty">暂无换标任务明细</div></td></tr>
|
<tr v-if="!selectedRelabelDetail?.items?.length"><td colspan="10"><div class="warehouse-empty">暂无换标任务明细</div></td></tr>
|
||||||
</tbody></table></div>
|
</tbody></table></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1652,6 +1728,92 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
.warehouse-table-card :deep(.related-business-number-cell .cell) { white-space:normal; overflow:visible; text-overflow:clip; overflow-wrap:anywhere; padding-top:6px; padding-bottom:6px; }
|
||||||
|
.labeling-type-tags { display:inline-flex; flex-wrap:wrap; gap:4px; }
|
||||||
|
.labeling-query.query-toolbar--grid { display:grid; grid-template-columns:repeat(4,minmax(0,320px)); gap:14px 18px; align-items:end; }
|
||||||
|
.labeling-query :deep(.query-toolbar__filters) { display:contents; }
|
||||||
|
.labeling-query :deep(.query-toolbar__field) { display:flex; flex-direction:column; align-items:stretch; gap:6px; }
|
||||||
|
.labeling-query :deep(.query-toolbar__field:nth-child(-n+3)) { grid-row:1; }
|
||||||
|
.labeling-query :deep(.query-toolbar__field:nth-child(n+4)) { grid-row:2; }
|
||||||
|
.labeling-query :deep(.query-toolbar__label) { line-height:18px; }
|
||||||
|
.labeling-query :deep(.query-toolbar__actions) { grid-column:4; grid-row:1; margin:0; padding:0; border:0; align-self:end; }
|
||||||
|
.transfer-query.query-toolbar--grid { display:grid; grid-template-columns:repeat(5,minmax(0,280px)); gap:14px 18px; align-items:end; }
|
||||||
|
.transfer-query :deep(.query-toolbar__filters) { display:contents; }
|
||||||
|
.transfer-query :deep(.query-toolbar__field) { display:flex; flex-direction:column; align-items:stretch; gap:6px; }
|
||||||
|
.transfer-query :deep(.query-toolbar__field:nth-child(-n+5)) { grid-row:1; }
|
||||||
|
.transfer-query :deep(.query-toolbar__field:nth-child(n+6)) { grid-row:2; }
|
||||||
|
.transfer-query :deep(.query-toolbar__label) { line-height:18px; }
|
||||||
|
.transfer-query :deep(.query-toolbar__actions) { grid-column:5; grid-row:2; margin:0; padding:0; border:0; align-self:end; }
|
||||||
|
.disposal-query :deep(.query-toolbar__field:nth-child(5)) { grid-column:1; grid-row:2; }
|
||||||
|
.disposal-query :deep(.query-toolbar__actions) { grid-column:2; }
|
||||||
|
@media(max-width:1200px) {
|
||||||
|
.labeling-query.query-toolbar--grid { grid-template-columns:repeat(2,minmax(0,320px)); }
|
||||||
|
.labeling-query :deep(.query-toolbar__field:nth-child(n)) { grid-row:auto; }
|
||||||
|
.labeling-query :deep(.query-toolbar__actions) { grid-column:auto; grid-row:auto; }
|
||||||
|
.transfer-query.query-toolbar--grid { grid-template-columns:repeat(2,minmax(0,320px)); }
|
||||||
|
.transfer-query :deep(.query-toolbar__field:nth-child(n)) { grid-row:auto; }
|
||||||
|
.disposal-query :deep(.query-toolbar__field:nth-child(5)) { grid-column:auto; }
|
||||||
|
.transfer-query :deep(.query-toolbar__actions) { grid-column:auto; grid-row:auto; }
|
||||||
|
}
|
||||||
|
.warehouse-order-info-heading { display: flex; align-items: center; justify-content: space-between; max-width: 1296px; margin-bottom: 16px; border-bottom: 1px solid #edf0f4; padding-bottom: 10px; }
|
||||||
|
.warehouse-form-section .warehouse-order-info-heading h3 { margin: 0; padding: 0; border: 0; }
|
||||||
|
.warehouse-order-info-summary { display: flex; flex-wrap: wrap; gap: 10px 24px; color: #64748b; font-size: 12px; }
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-labeling-mode {
|
||||||
|
width: fit-content;
|
||||||
|
max-width: 1296px;
|
||||||
|
box-sizing: border-box;
|
||||||
|
border: 1px solid #e2e8f0;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #f8fafc;
|
||||||
|
padding: 8px 12px;
|
||||||
|
gap: 14px;
|
||||||
|
margin: 20px 0 22px;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-labeling-mode > span {
|
||||||
|
color: #475569;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-table-scroll th {
|
||||||
|
background: #f0f5fc;
|
||||||
|
color: #385579;
|
||||||
|
border-bottom: 1px solid #dce6f2;
|
||||||
|
height: 38px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-labeling-mode :deep(.el-radio-button) {
|
||||||
|
--el-color-primary: #2563eb;
|
||||||
|
--el-radio-button-checked-bg-color: #2563eb;
|
||||||
|
--el-radio-button-checked-border-color: #2563eb;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-labeling-mode :deep(.el-radio-button:not(.is-disabled) .el-radio-button__inner) {
|
||||||
|
border-color: #cbdaf0;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-labeling-mode :deep(.el-radio-group) { gap: 6px; }
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-labeling-mode :deep(.el-radio-button .el-radio-button__inner) {
|
||||||
|
padding: 8px 12px;
|
||||||
|
border: 1px solid #dce3ec;
|
||||||
|
border-radius: 5px;
|
||||||
|
box-shadow: none;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-labeling-mode :deep(.el-radio-button.is-disabled .el-radio-button__inner) {
|
||||||
|
color: #a3adbb;
|
||||||
|
background: #f1f4f8;
|
||||||
|
border-color: #e5eaf0;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-table-scroll td { padding: 10px 12px; }
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-table-scroll h3 {
|
||||||
|
font-size: 14px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
padding-bottom: 10px;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-sku-label-table :deep(.el-input__wrapper) {
|
||||||
|
min-height: 30px;
|
||||||
|
box-shadow: 0 0 0 1px #dce3ec inset;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-sku-label-table :deep(.el-input-number) { width: 120px; }
|
||||||
|
.warehouse-service-page--return-relabel .warehouse-transfer-cargo-card .warehouse-tab-actions { margin-bottom: 10px; }
|
||||||
.warehouse-service-page{display:grid;gap:12px;color:#25324a}.warehouse-breadcrumb{display:flex;align-items:center;gap:9px;margin:0 0 14px;color:#9aa3b2;font-size:12px}.warehouse-breadcrumb b{font-weight:400}.warehouse-breadcrumb strong{color:#606b7c}.warehouse-breadcrumb button{padding:0;border:0;background:transparent;color:#4376b8;cursor:pointer}.warehouse-page-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.warehouse-page-heading h2{margin:0;color:#17233a;font-size:22px;letter-spacing:0}.warehouse-card{margin-bottom:0;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff;box-shadow:none}.warehouse-filter-card{padding:20px 22px 16px}.warehouse-filter-grid{display:grid;grid-template-columns:repeat(4,minmax(180px,1fr));gap:16px 20px}.warehouse-filter-grid label,.warehouse-form-grid label{display:flex;min-width:0;flex-direction:column;gap:7px}.warehouse-filter-grid label>span,.warehouse-form-grid label>span{color:#596579;font-size:12px}.warehouse-filter-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:18px}.warehouse-table-card{overflow:hidden}.warehouse-list-notice{padding:8px 12px;border-bottom:1px solid var(--client-border);background:#fff8e8;color:#8a6116;font-size:12px}.warehouse-table-scroll{overflow-x:auto}table{width:100%;min-width:940px;border-collapse:collapse;font-size:12px}th{height:44px;padding:0 14px;border-bottom:1px solid #e8edf3;background:#f7f9fc;color:#4d5a6e;font-weight:650;text-align:left;white-space:nowrap}td{height:48px;padding:8px 14px;border-bottom:1px solid #eef1f5;color:#526176;white-space:nowrap}.warehouse-empty{display:grid;height:72px;color:#a0a9b7;place-items:center}.warehouse-link,.warehouse-delete{display:inline-flex;align-items:center;gap:5px;padding:4px;border:0;background:transparent;color:#2176d2;cursor:pointer}.warehouse-delete{color:#d64545}.warehouse-pagination{display:flex;align-items:center;justify-content:flex-end;gap:8px;padding:14px 18px;color:#778398;font-size:12px}.warehouse-pagination span{margin-right:8px}.warehouse-page-number{width:28px;height:28px;border:1px solid #2176d2;border-radius:3px;background:#2176d2;color:#fff}.warehouse-form-section{padding:22px}.warehouse-form-section h3{margin:0 0 18px;padding-bottom:12px;border-bottom:1px solid #edf0f4;color:#26364f;font-size:15px;letter-spacing:0}.warehouse-form-grid{display:grid;grid-template-columns:repeat(2,minmax(240px,1fr));gap:18px 28px}.warehouse-form-grid i{margin-right:3px;color:#e24b4b;font-style:normal}.warehouse-span-2{grid-column:1/-1}.warehouse-section-heading{display:flex;align-items:center;justify-content:space-between}.warehouse-section-heading h3{flex:1}.warehouse-edit-table td{padding:9px 10px}.warehouse-edit-table :deep(.el-input-number){width:130px}.warehouse-hint{margin:12px 0 0;color:#8792a2;font-size:12px}.warehouse-submit-bar{display:flex;justify-content:center;gap:10px;padding:12px 0 30px}.warehouse-detail-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:24px}.warehouse-detail-grid div{display:flex;flex-direction:column;gap:7px}.warehouse-detail-grid span{color:#8a95a5;font-size:12px}.warehouse-detail-grid strong{color:#334157;font-size:13px}:deep(.el-button){border-radius:4px}:deep(.el-button span){display:inline-flex;align-items:center;gap:6px}:deep(.el-select),:deep(.el-date-editor.el-input){width:100%}@media(max-width:1100px){.warehouse-filter-grid{grid-template-columns:repeat(2,1fr)}.warehouse-detail-grid{grid-template-columns:repeat(2,1fr)}}
|
.warehouse-service-page{display:grid;gap:12px;color:#25324a}.warehouse-breadcrumb{display:flex;align-items:center;gap:9px;margin:0 0 14px;color:#9aa3b2;font-size:12px}.warehouse-breadcrumb b{font-weight:400}.warehouse-breadcrumb strong{color:#606b7c}.warehouse-breadcrumb button{padding:0;border:0;background:transparent;color:#4376b8;cursor:pointer}.warehouse-page-heading{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.warehouse-page-heading h2{margin:0;color:#17233a;font-size:22px;letter-spacing:0}.warehouse-card{margin-bottom:0;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff;box-shadow:none}.warehouse-filter-card{padding:20px 22px 16px}.warehouse-filter-grid{display:grid;grid-template-columns:repeat(4,minmax(180px,1fr));gap:16px 20px}.warehouse-filter-grid label,.warehouse-form-grid label{display:flex;min-width:0;flex-direction:column;gap:7px}.warehouse-filter-grid label>span,.warehouse-form-grid label>span{color:#596579;font-size:12px}.warehouse-filter-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:18px}.warehouse-table-card{overflow:hidden}.warehouse-list-notice{padding:8px 12px;border-bottom:1px solid var(--client-border);background:#fff8e8;color:#8a6116;font-size:12px}.warehouse-table-scroll{overflow-x:auto}table{width:100%;min-width:940px;border-collapse:collapse;font-size:12px}th{height:44px;padding:0 14px;border-bottom:1px solid #e8edf3;background:#f7f9fc;color:#4d5a6e;font-weight:650;text-align:left;white-space:nowrap}td{height:48px;padding:8px 14px;border-bottom:1px solid #eef1f5;color:#526176;white-space:nowrap}.warehouse-empty{display:grid;height:72px;color:#a0a9b7;place-items:center}.warehouse-link,.warehouse-delete{display:inline-flex;align-items:center;gap:5px;padding:4px;border:0;background:transparent;color:#2176d2;cursor:pointer}.warehouse-delete{color:#d64545}.warehouse-pagination{display:flex;align-items:center;justify-content:flex-end;gap:8px;padding:14px 18px;color:#778398;font-size:12px}.warehouse-pagination span{margin-right:8px}.warehouse-page-number{width:28px;height:28px;border:1px solid #2176d2;border-radius:3px;background:#2176d2;color:#fff}.warehouse-form-section{padding:22px}.warehouse-form-section h3{margin:0 0 18px;padding-bottom:12px;border-bottom:1px solid #edf0f4;color:#26364f;font-size:15px;letter-spacing:0}.warehouse-form-grid{display:grid;grid-template-columns:repeat(2,minmax(240px,1fr));gap:18px 28px}.warehouse-form-grid i{margin-right:3px;color:#e24b4b;font-style:normal}.warehouse-span-2{grid-column:1/-1}.warehouse-section-heading{display:flex;align-items:center;justify-content:space-between}.warehouse-section-heading h3{flex:1}.warehouse-edit-table td{padding:9px 10px}.warehouse-edit-table :deep(.el-input-number){width:130px}.warehouse-hint{margin:12px 0 0;color:#8792a2;font-size:12px}.warehouse-submit-bar{display:flex;justify-content:center;gap:10px;padding:12px 0 30px}.warehouse-detail-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:24px}.warehouse-detail-grid div{display:flex;flex-direction:column;gap:7px}.warehouse-detail-grid span{color:#8a95a5;font-size:12px}.warehouse-detail-grid strong{color:#334157;font-size:13px}:deep(.el-button){border-radius:4px}:deep(.el-button span){display:inline-flex;align-items:center;gap:6px}:deep(.el-select),:deep(.el-date-editor.el-input){width:100%}@media(max-width:1100px){.warehouse-filter-grid{grid-template-columns:repeat(2,1fr)}.warehouse-detail-grid{grid-template-columns:repeat(2,1fr)}}
|
||||||
.warehouse-service-page--detail{display:block;overflow:hidden;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff}.warehouse-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)}.warehouse-detail-back{display:inline-flex;align-items:center;gap:5px;padding:5px 0;border:0;background:transparent;color:var(--el-color-primary);cursor:pointer}.warehouse-detail-title{display:flex;min-width:0;flex-direction:column;gap:3px}.warehouse-detail-title strong{overflow:hidden;color:#1f2d45;font-size:18px;text-overflow:ellipsis;white-space:nowrap}.warehouse-detail-title span{color:#7c899c;font-size:12px}.warehouse-detail-actions{display:flex;align-items:center;gap:8px}.warehouse-service-page--detail>.warehouse-card{border:0;border-top:1px solid var(--client-border);border-radius:0}.warehouse-service-page--detail>.warehouse-detail-header+.warehouse-card{border-top:0}.warehouse-service-page--detail>.warehouse-form-section{padding:0}.warehouse-service-page--detail .warehouse-form-section h3{min-height:40px;margin:0;padding:11px 16px 9px;border-bottom:1px solid #edf1f5;font-size:14px}.warehouse-service-page--detail .warehouse-detail-grid{grid-template-columns:repeat(4,minmax(0,1fr));gap:0;margin:0}.warehouse-service-page--detail .warehouse-detail-grid>div{min-height:48px;flex-direction:row;align-items:center;gap:10px;padding:8px 14px;border-right:1px solid #edf1f5;border-bottom:1px solid #edf1f5}.warehouse-service-page--detail .warehouse-detail-grid span{flex:0 0 90px}.warehouse-service-page--detail .warehouse-detail-grid strong{min-width:0;overflow-wrap:anywhere}.warehouse-service-page--detail .warehouse-fulfillment-grid{margin-bottom:0}.warehouse-service-page--detail .warehouse-evidence{margin:12px 14px}.warehouse-service-page--detail .warehouse-completion-remark,.warehouse-service-page--detail .warehouse-hint{margin:10px 14px}.warehouse-service-page--detail .warehouse-table-scroll table{margin:0}.warehouse-service-page--detail .warehouse-empty{height:64px}@media(max-width:1100px){.warehouse-service-page--detail .warehouse-detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.warehouse-detail-header{grid-template-columns:1fr auto}.warehouse-detail-back{grid-column:1/-1}.warehouse-detail-actions{justify-content:flex-end}}
|
.warehouse-service-page--detail{display:block;overflow:hidden;border:1px solid var(--client-border);border-radius:var(--client-radius);background:#fff}.warehouse-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)}.warehouse-detail-back{display:inline-flex;align-items:center;gap:5px;padding:5px 0;border:0;background:transparent;color:var(--el-color-primary);cursor:pointer}.warehouse-detail-title{display:flex;min-width:0;flex-direction:column;gap:3px}.warehouse-detail-title strong{overflow:hidden;color:#1f2d45;font-size:18px;text-overflow:ellipsis;white-space:nowrap}.warehouse-detail-title span{color:#7c899c;font-size:12px}.warehouse-detail-actions{display:flex;align-items:center;gap:8px}.warehouse-service-page--detail>.warehouse-card{border:0;border-top:1px solid var(--client-border);border-radius:0}.warehouse-service-page--detail>.warehouse-detail-header+.warehouse-card{border-top:0}.warehouse-service-page--detail>.warehouse-form-section{padding:0}.warehouse-service-page--detail .warehouse-form-section h3{min-height:40px;margin:0;padding:11px 16px 9px;border-bottom:1px solid #edf1f5;font-size:14px}.warehouse-service-page--detail .warehouse-detail-grid{grid-template-columns:repeat(4,minmax(0,1fr));gap:0;margin:0}.warehouse-service-page--detail .warehouse-detail-grid>div{min-height:48px;flex-direction:row;align-items:center;gap:10px;padding:8px 14px;border-right:1px solid #edf1f5;border-bottom:1px solid #edf1f5}.warehouse-service-page--detail .warehouse-detail-grid span{flex:0 0 90px}.warehouse-service-page--detail .warehouse-detail-grid strong{min-width:0;overflow-wrap:anywhere}.warehouse-service-page--detail .warehouse-fulfillment-grid{margin-bottom:0}.warehouse-service-page--detail .warehouse-evidence{margin:12px 14px}.warehouse-service-page--detail .warehouse-completion-remark,.warehouse-service-page--detail .warehouse-hint{margin:10px 14px}.warehouse-service-page--detail .warehouse-table-scroll table{margin:0}.warehouse-service-page--detail .warehouse-empty{height:64px}@media(max-width:1100px){.warehouse-service-page--detail .warehouse-detail-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:720px){.warehouse-detail-header{grid-template-columns:1fr auto}.warehouse-detail-back{grid-column:1/-1}.warehouse-detail-actions{justify-content:flex-end}}
|
||||||
.warehouse-detail-error{display:flex;min-height:220px;align-items:center;justify-content:center;gap:12px;color:#b42318}
|
.warehouse-detail-error{display:flex;min-height:220px;align-items:center;justify-content:center;gap:12px;color:#b42318}
|
||||||
@@ -1667,7 +1829,42 @@ function selectRelabelInventory(inboundOrderId: string) {
|
|||||||
.warehouse-unmaintained{margin-left:8px;color:#e6a23c;font-size:12px;font-style:normal}
|
.warehouse-unmaintained{margin-left:8px;color:#e6a23c;font-size:12px;font-style:normal}
|
||||||
.warehouse-labeling-tabs{margin-top:-8px}.warehouse-labeling-heading{align-items:flex-start}.warehouse-labeling-heading h3{margin-bottom:16px}.warehouse-template-actions{display:flex;gap:8px;padding-bottom:12px}.warehouse-tab-actions{align-items:center;margin:2px 0 14px}.warehouse-tab-actions p{margin:0;color:#7d8797;font-size:12px}.warehouse-tab-actions>div{display:flex;gap:8px}.warehouse-sku-notice{margin:0 0 14px;padding:10px 12px;border:1px solid #f2d39b;border-radius:4px;background:#fff8e8;color:#8a6116;font-size:12px}.warehouse-sku-label-table{min-width:980px}.warehouse-sku-label-table :deep(.el-input-number){width:160px}:deep(.warehouse-labeling-tabs>.el-tabs__header){margin-bottom:18px}:deep(.warehouse-labeling-tabs .el-tabs__item){height:42px;padding:0 26px;font-weight:600}.warehouse-labeling-mode{display:flex;align-items:center;gap:14px;margin:0 0 16px;padding:14px 16px;border:1px solid #dce5f5;border-radius:5px;background:#f7f9ff}.warehouse-labeling-mode>span{color:#34445c;font-size:13px;font-weight:650;white-space:nowrap}.warehouse-labeling-mode p{margin:0;color:#71809a;font-size:12px}.warehouse-labeling-mode :deep(.el-radio-group){display:flex;flex-shrink:0}.warehouse-labeling-mode :deep(.el-radio-button__inner){padding:8px 14px}
|
.warehouse-labeling-tabs{margin-top:-8px}.warehouse-labeling-heading{align-items:flex-start}.warehouse-labeling-heading h3{margin-bottom:16px}.warehouse-template-actions{display:flex;gap:8px;padding-bottom:12px}.warehouse-tab-actions{align-items:center;margin:2px 0 14px}.warehouse-tab-actions p{margin:0;color:#7d8797;font-size:12px}.warehouse-tab-actions>div{display:flex;gap:8px}.warehouse-sku-notice{margin:0 0 14px;padding:10px 12px;border:1px solid #f2d39b;border-radius:4px;background:#fff8e8;color:#8a6116;font-size:12px}.warehouse-sku-label-table{min-width:980px}.warehouse-sku-label-table :deep(.el-input-number){width:160px}:deep(.warehouse-labeling-tabs>.el-tabs__header){margin-bottom:18px}:deep(.warehouse-labeling-tabs .el-tabs__item){height:42px;padding:0 26px;font-weight:600}.warehouse-labeling-mode{display:flex;align-items:center;gap:14px;margin:0 0 16px;padding:14px 16px;border:1px solid #dce5f5;border-radius:5px;background:#f7f9ff}.warehouse-labeling-mode>span{color:#34445c;font-size:13px;font-weight:650;white-space:nowrap}.warehouse-labeling-mode p{margin:0;color:#71809a;font-size:12px}.warehouse-labeling-mode :deep(.el-radio-group){display:flex;flex-shrink:0}.warehouse-labeling-mode :deep(.el-radio-button__inner){padding:8px 14px}
|
||||||
.warehouse-relabel-detail-table{min-width:1420px}.warehouse-relabel-detail-table td strong{color:#253f67}
|
.warehouse-relabel-detail-table{min-width:1420px}.warehouse-relabel-detail-table td strong{color:#253f67}
|
||||||
.warehouse-service-page--return-relabel .warehouse-table-scroll:has(> .warehouse-return-relabel-table)~.warehouse-table-scroll{display:none}
|
.warehouse-file-groups--compact {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 1296px;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
.warehouse-file-groups--compact .warehouse-file-group__heading {
|
||||||
|
padding: 10px 12px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.warehouse-file-groups--compact .warehouse-file-options {
|
||||||
|
padding: 10px;
|
||||||
|
grid-template-columns: minmax(0, 1fr) 20px minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
.warehouse-file-groups--compact .warehouse-file-option {
|
||||||
|
padding: 8px;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.warehouse-file-groups--compact .warehouse-file-option__name strong { font-size: 12px; }
|
||||||
|
.warehouse-file-groups--compact .warehouse-file-option :deep(.el-button) {
|
||||||
|
padding: 6px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.warehouse-file-groups--compact .warehouse-template-list { padding: 4px 12px; }
|
||||||
|
.warehouse-file-groups--compact .warehouse-template-list > div {
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||||
|
padding: 7px 0;
|
||||||
|
}
|
||||||
|
@media (max-width: 1180px) {
|
||||||
|
.warehouse-file-groups--compact { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
}
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.warehouse-file-groups--compact .warehouse-file-options { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.warehouse-file-groups--compact .warehouse-template-list > div { grid-template-columns: minmax(0, 1fr) auto; }
|
||||||
|
}
|
||||||
.warehouse-native-file{min-height:32px;padding:5px 8px;border:1px solid #dcdfe6;border-radius:4px;background:#fff;color:#606266}.warehouse-fulfillment-grid{margin-bottom:18px}.warehouse-evidence{display:flex;align-items:flex-start;gap:16px;padding:14px;border:1px solid #e7ebf1;border-radius:4px;background:#f8fafc}.warehouse-evidence>span{padding-top:6px;color:#71809a;font-size:12px;white-space:nowrap}.warehouse-evidence>strong{padding-top:6px;color:#8a95a5;font-size:12px;font-weight:400}.warehouse-photo-grid{display:grid;grid-template-columns:repeat(4,140px);gap:12px}.warehouse-photo-item{width:140px;height:105px;overflow:hidden;border:1px solid #dce3ed;border-radius:5px;background:#fff}.warehouse-photo-item :deep(.el-image){display:block;width:100%;height:100%;cursor:zoom-in}.warehouse-photo-placeholder{display:flex;width:100%;height:100%;align-items:center;justify-content:center;padding:10px;border:0;background:#f4f7fb;color:#8792a2;font-size:12px;text-align:center}.warehouse-photo-retry{cursor:pointer}.warehouse-completion-remark{margin:10px 0 0;color:#596579;font-size:12px}
|
.warehouse-native-file{min-height:32px;padding:5px 8px;border:1px solid #dcdfe6;border-radius:4px;background:#fff;color:#606266}.warehouse-fulfillment-grid{margin-bottom:18px}.warehouse-evidence{display:flex;align-items:flex-start;gap:16px;padding:14px;border:1px solid #e7ebf1;border-radius:4px;background:#f8fafc}.warehouse-evidence>span{padding-top:6px;color:#71809a;font-size:12px;white-space:nowrap}.warehouse-evidence>strong{padding-top:6px;color:#8a95a5;font-size:12px;font-weight:400}.warehouse-photo-grid{display:grid;grid-template-columns:repeat(4,140px);gap:12px}.warehouse-photo-item{width:140px;height:105px;overflow:hidden;border:1px solid #dce3ed;border-radius:5px;background:#fff}.warehouse-photo-item :deep(.el-image){display:block;width:100%;height:100%;cursor:zoom-in}.warehouse-photo-placeholder{display:flex;width:100%;height:100%;align-items:center;justify-content:center;padding:10px;border:0;background:#f4f7fb;color:#8792a2;font-size:12px;text-align:center}.warehouse-photo-retry{cursor:pointer}.warehouse-completion-remark{margin:10px 0 0;color:#596579;font-size:12px}
|
||||||
.warehouse-measurement-evidence{margin-top:16px}
|
.warehouse-measurement-evidence{margin-top:16px}
|
||||||
.warehouse-measurement-photo-grid{flex:1;grid-template-columns:repeat(auto-fill,minmax(240px,1fr))}
|
.warehouse-measurement-photo-grid{flex:1;grid-template-columns:repeat(auto-fill,minmax(240px,1fr))}
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
const source = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
|
||||||
|
function loader(downloadDiscardPhoto) {
|
||||||
|
const section = source.slice(source.indexOf('let discardPhotoGeneration = 0'), source.indexOf('const fbaWarehouses = ref'))
|
||||||
|
.replace('loadDiscardPhoto(fileId: string)', 'loadDiscardPhoto(fileId)')
|
||||||
|
const maps = { discardPhotoUrls: {}, discardPhotoLoading: {}, discardPhotoErrors: {} }
|
||||||
|
const selectedDetail = { value: { discardNo: 'CD/1', photos: [{ fileId: '101' }] } }
|
||||||
|
const mode = { value: 'detail' }; const revoked = []
|
||||||
|
const URL = { createObjectURL: () => 'blob:photo', revokeObjectURL: url => revoked.push(url) }
|
||||||
|
const functions = new Function('selectedDetail', 'mode', 'downloadDiscardPhoto', 'URL', ...Object.keys(maps), section + ';return { loadDiscardPhotos, loadDiscardPhoto, clearDiscardPhotos }')(selectedDetail, mode, downloadDiscardPhoto, URL, ...Object.values(maps))
|
||||||
|
return { ...functions, ...maps, selectedDetail, mode, revoked }
|
||||||
|
}
|
||||||
|
test('client detail loads submitted discard photos and frees preview URLs on close', async () => {
|
||||||
|
const calls = []; const state = loader(async (...args) => { calls.push(args); return {} })
|
||||||
|
await state.loadDiscardPhotos()
|
||||||
|
assert.deepEqual(calls, [['CD/1', '101']]); assert.equal(state.discardPhotoUrls['101'], 'blob:photo')
|
||||||
|
state.clearDiscardPhotos(); assert.deepEqual(state.revoked, ['blob:photo']); assert.deepEqual(state.discardPhotoUrls, {})
|
||||||
|
})
|
||||||
|
test('photo failures offer retry and delayed responses cannot populate a closed detail', async () => {
|
||||||
|
let reject = true
|
||||||
|
const state = loader(async () => { if (reject) throw new Error('offline'); return {} })
|
||||||
|
await state.loadDiscardPhotos(); assert.equal(state.discardPhotoErrors['101'], true)
|
||||||
|
reject = false; await state.loadDiscardPhoto('101'); assert.equal(state.discardPhotoErrors['101'], false)
|
||||||
|
let resolve; const slow = loader(() => new Promise(done => { resolve = done }))
|
||||||
|
const pending = slow.loadDiscardPhotos(); slow.mode.value = 'list'; slow.clearDiscardPhotos(); resolve({}); await pending
|
||||||
|
assert.deepEqual(slow.discardPhotoUrls, {}); assert.deepEqual(slow.discardPhotoLoading, {})
|
||||||
|
})
|
||||||
@@ -40,9 +40,9 @@ test('贴标申请移除操作项下方的解释文字,保留必要状态', ()
|
|||||||
|
|
||||||
test('贴标申请可从当前客户仍有库存的入仓单或退货单选择来源', () => {
|
test('贴标申请可从当前客户仍有库存的入仓单或退货单选择来源', () => {
|
||||||
assert.match(view, /海外操作仓(中转仓)/)
|
assert.match(view, /海外操作仓(中转仓)/)
|
||||||
assert.match(view, /选择有库存的入仓单或退货单/)
|
assert.match(view, /选择入仓单或退货单/)
|
||||||
assert.match(view, /quantityUnit: candidate\.sourceType === 'RETURN_CARTON' \? '件' : '箱'/)
|
assert.match(view, /quantityUnit: candidate\.returnCartonId \? '件' : '箱'/)
|
||||||
assert.match(view, /当前中转仓暂无可用库存/)
|
assert.match(view, /暂无匹配的可选库存/)
|
||||||
assert.match(view, /relabelInboundOptions/)
|
assert.match(view, /relabelInboundOptions/)
|
||||||
assert.match(view, /listRelabelInventoryCandidates\(form\.warehouse\)/)
|
assert.match(view, /listRelabelInventoryCandidates\(form\.warehouse\)/)
|
||||||
assert.match(api, /relabel-applications\/inventory-candidates/)
|
assert.match(api, /relabel-applications\/inventory-candidates/)
|
||||||
@@ -96,7 +96,7 @@ test('上传关系支持部分或全量选择后导入本次换标明细', () =>
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('箱唛换标一行固定代表一箱', () => {
|
test('箱唛换标一行固定代表一箱', () => {
|
||||||
const cartonTable = view.match(/<div v-if="!isReturnRelabelSource && labelingMode === 'carton'" class="warehouse-table-scroll">.+?(?=<div v-else class="warehouse-table-scroll">)/s)?.[0]
|
const cartonTable = view.match(/<div v-if="labelingMode === 'carton'" class="warehouse-table-scroll">.+?(?=<div v-else class="warehouse-table-scroll">)/s)?.[0]
|
||||||
assert.ok(cartonTable)
|
assert.ok(cartonTable)
|
||||||
assert.match(cartonTable, /<th>箱数<\/th>/)
|
assert.match(cartonTable, /<th>箱数<\/th>/)
|
||||||
assert.match(cartonTable, /<td><strong>1 箱<\/strong><\/td>/)
|
assert.match(cartonTable, /<td><strong>1 箱<\/strong><\/td>/)
|
||||||
@@ -137,17 +137,16 @@ test('箱唛相关换标必须选择四选一派送方式', () => {
|
|||||||
|
|
||||||
test('一次申请单选库存来源且退货库存按退货单汇总', () => {
|
test('一次申请单选库存来源且退货库存按退货单汇总', () => {
|
||||||
assert.doesNotMatch(view, /multiple filterable collapse-tags/)
|
assert.doesNotMatch(view, /multiple filterable collapse-tags/)
|
||||||
assert.match(view, /RETURN_ORDER:\$\{returnOrderNo\}/)
|
assert.match(view, /returnSourceNos\(item\)\.includes\(selectedReturnOrderNo\.value\)/)
|
||||||
assert.match(view, /current\.availablePackages \+= inventoryQuantity\(candidate\.availablePackages\)/)
|
assert.match(view, /current\.availablePackages \+= inventoryQuantity\(candidate\.availablePackages\)/)
|
||||||
assert.match(view, /availablePackages: inventoryQuantity\(candidate\.availablePackages\)/)
|
assert.match(view, /availablePackages: inventoryQuantity\(candidate\.availablePackages\)/)
|
||||||
assert.match(view, /const quantity = Number\(value\)/)
|
assert.match(view, /const quantity = Number\(value\)/)
|
||||||
assert.match(view, /interface ReturnRelabelSkuRow/)
|
assert.match(view, /可用包裹<\/h3>/)
|
||||||
assert.match(view, /current\.availableQuantity \+= quantity/)
|
assert.match(view, /仓库箱识别码/)
|
||||||
assert.match(view, /库存总数/)
|
assert.match(view, /箱内 SKU/)
|
||||||
assert.match(view, /本次贴标数量/)
|
assert.match(view, /returnLooseCandidates/)
|
||||||
assert.match(view, /returnRelabelSkuRows\.value = \[\.\.\.grouped\.values\(\)\]/)
|
assert.match(view, /returnBoxCandidates/)
|
||||||
assert.match(view, /createReturnRelabel\(selectedReturnOrderNo\.value/)
|
assert.doesNotMatch(view, /submitReturnRelabel/)
|
||||||
assert.match(view, /uploadReturnRelabelFile\(created\.relabelNo, fileScope, selectedFile\)/)
|
|
||||||
assert.doesNotMatch(view, /candidate\.sourceType === 'RETURN_CARTON'\) rows\.push\(\.\.\.Array\.from/)
|
assert.doesNotMatch(view, /candidate\.sourceType === 'RETURN_CARTON'\) rows\.push\(\.\.\.Array\.from/)
|
||||||
assert.match(view, /sourceInventoryBalanceId: String\(candidate\.inventoryBalanceId\)/)
|
assert.match(view, /sourceInventoryBalanceId: String\(candidate\.inventoryBalanceId\)/)
|
||||||
assert.match(view, /sourceInventoryPositionId: String\(position\.positionId\)/)
|
assert.match(view, /sourceInventoryPositionId: String\(position\.positionId\)/)
|
||||||
@@ -155,11 +154,11 @@ test('一次申请单选库存来源且退货库存按退货单汇总', () => {
|
|||||||
assert.match(api, /sourceInventoryBalanceId\?: string; sourceInventoryPositionId\?: string; sourceInboundOrderId\?: string; returnCartonId\?: string/)
|
assert.match(api, /sourceInventoryBalanceId\?: string; sourceInventoryPositionId\?: string; sourceInboundOrderId\?: string; returnCartonId\?: string/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('退货贴标总文件二选一且提交使用退货专用链路', () => {
|
test('退货贴标复用普通申请,混贴要求两份总文件', () => {
|
||||||
assert.match(view, /cartonTotalFile\.value && !requiresBothTotalFiles\.value\) clearCreateTotalFile\('SKU_TOTAL'\)/)
|
assert.match(view, /cartonTotalFile\.value && !requiresBothTotalFiles\.value\) clearCreateTotalFile\('SKU_TOTAL'\)/)
|
||||||
assert.match(view, /skuTotalFile\.value && !requiresBothTotalFiles\.value\) clearCreateTotalFile\('CARTON_TOTAL'\)/)
|
assert.match(view, /skuTotalFile\.value && !requiresBothTotalFiles\.value\) clearCreateTotalFile\('CARTON_TOTAL'\)/)
|
||||||
assert.match(view, /fileScope = cartonTotalFile\.value \? 'CARTON_TOTAL' as const : 'SKU_TOTAL' as const/)
|
assert.match(view, /const created = await createRelabel/)
|
||||||
assert.match(view, /destinationFbaWarehouseId: String\(destination\.id\)/)
|
assert.doesNotMatch(view, /&& !isReturnRelabelSource.value && labelingMode.value === 'carton_and_sku'/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('SKU 和箱唛都换时两份总文件必须同时上传', () => {
|
test('SKU 和箱唛都换时两份总文件必须同时上传', () => {
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import test from 'node:test'
|
||||||
|
import ts from 'typescript'
|
||||||
|
const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
|
||||||
|
const source = view.slice(view.indexOf('function returnSourceNos'), view.indexOf('const relabelInboundOptions'))
|
||||||
|
const compiled = ts.transpileModule(source + '\nexports.sourceNos = returnSourceNos; exports.progress = returnRelabelProgress', { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||||
|
const exports = {}
|
||||||
|
new Function('exports', compiled)(exports)
|
||||||
|
test('合箱来源按单号集合精确匹配并去重,不能用子串匹配', () => {
|
||||||
|
const sources = exports.sourceNos({ inboundOrderNo: ' RETURN-1,RETURN-10, RETURN-1 ' })
|
||||||
|
assert.deepEqual(sources, ['RETURN-1', 'RETURN-10'])
|
||||||
|
assert.equal(sources.includes('RETURN'), false)
|
||||||
|
assert.deepEqual(exports.sourceNos({}), [])
|
||||||
|
})
|
||||||
|
test('实际完成和处理中占用分别展示,缺失投影保持未知', () => {
|
||||||
|
assert.equal(exports.progress({ relabelStatus: 'PARTIALLY_COMPLETED', relabelledQuantity: 3, relabelReservedQuantity: 2 }), '部分完成|实际完成 3 件|处理中占用 2 件')
|
||||||
|
assert.equal(exports.progress({}), '—|实际完成 — 件|处理中占用 — 件')
|
||||||
|
assert.equal(exports.progress({ relabelStatus: 'PROCESSING', relabelledQuantity: 0, relabelReservedQuantity: 4 }), '处理中|实际完成 0 件|处理中占用 4 件')
|
||||||
|
})
|
||||||
|
test('退货 SKU 申请按实物箱选择,来源标识只读,部分数量转换库存', () => {
|
||||||
|
assert.match(view, /item.id === rows\[0\].sourceRowId/)
|
||||||
|
assert.match(view, /row.sourceRowId !== source\?\.id/)
|
||||||
|
assert.match(view, /:readonly="isReturnRelabelSource"/)
|
||||||
|
assert.match(view, /SKU 换标完成后扣减旧 SKU、增加新 SKU/)
|
||||||
|
assert.match(view, /labelingMode.value === 'sku' \? !skuTotalFile.value : !cartonTotalFile.value/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('整包裹支持SKU和混贴提交,实物数为1且各SKU数量仍按件', () => {
|
||||||
|
const builder = view.slice(view.indexOf('function buildSkuRelabelItems'), view.indexOf('function addRelabelCargoRow'))
|
||||||
|
const compiledBuilder = ts.transpileModule(builder, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const cargo = { id: 1, returnCartonId: 'PARCEL-ID', cartonMark: 'RP-1', sku: 'SKU-A', availableQuantity: 1 }
|
||||||
|
const rows = [{ sourceRowId: 1, cartonMark: 'RP-1', originalSku: 'SKU-A', newSku: 'NEW-A', quantity: 3, fbaCartonMark: 'FBA-NEW', shipmentNo: 'FBA-SHIP-NEW' }, { sourceRowId: 1, cartonMark: 'RP-1', originalSku: 'SKU-B', newSku: 'NEW-B', quantity: 2, fbaCartonMark: 'FBA-NEW', shipmentNo: 'FBA-SHIP-NEW' }]
|
||||||
|
const candidate = { returnCartonId: 'PARCEL-ID', sourceType: 'RETURN_PARCEL', skuItems: [{ skuCode: 'SKU-A', quantity: 3 }, { skuCode: 'SKU-B', quantity: 2 }] }
|
||||||
|
for (const mode of ['sku', 'carton_and_sku']) {
|
||||||
|
const build = new Function('skuRelabelRows', 'cargoRows', 'isReturnRelabelSource', 'selectedReturnCandidates', 'labelingMode', 'form', compiledBuilder + '; return buildSkuRelabelItems')({ value: rows }, { value: [cargo] }, { value: true }, { value: [candidate] }, { value: mode }, { destination: 'FBA-WH' })
|
||||||
|
const [item] = build()
|
||||||
|
assert.equal(item.returnCartonId, 'PARCEL-ID')
|
||||||
|
assert.equal(item.operationType, mode === 'sku' ? 'SKU_LABEL' : 'CARTON_AND_SKU')
|
||||||
|
assert.equal(item.totalPackageCount, 1)
|
||||||
|
assert.equal(item.notifiedPackageCount, 1)
|
||||||
|
assert.deepEqual(item.skuItems.map(sku => sku.quantity), [3, 2])
|
||||||
|
if (mode === 'carton_and_sku') {
|
||||||
|
assert.equal(item.fbaCartonMark, 'FBA-NEW')
|
||||||
|
assert.equal(item.destinationFbaWarehouseCode, 'FBA-WH')
|
||||||
|
assert.equal(item.shipmentNo, 'FBA-SHIP-NEW')
|
||||||
|
rows[1].shipmentNo = 'OTHER-SHIPMENT'
|
||||||
|
assert.throws(build, /相同的 FBA 货件编号/)
|
||||||
|
rows[1].shipmentNo = 'FBA-SHIP-NEW'
|
||||||
|
} else {
|
||||||
|
assert.equal(item.fbaCartonMark, undefined)
|
||||||
|
assert.equal(item.destinationFbaWarehouseCode, undefined)
|
||||||
|
const buildWithoutDestination = new Function('skuRelabelRows', 'cargoRows', 'isReturnRelabelSource', 'selectedReturnCandidates', 'labelingMode', 'form', compiledBuilder + '; return buildSkuRelabelItems')({ value: rows }, { value: [cargo] }, { value: true }, { value: [candidate] }, { value: mode }, { destination: '' })
|
||||||
|
assert.equal(buildWithoutDestination()[0].operationType, 'SKU_LABEL')
|
||||||
|
}
|
||||||
|
rows[0].quantity = 4
|
||||||
|
assert.throws(build, /超过来源箱可用数量/)
|
||||||
|
rows[0].quantity = 3
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('包裹箱唛添加保持一个实物并去重,三种类型不再禁用', () => {
|
||||||
|
const binding = view.slice(view.indexOf('function addReturnBoxBinding'), view.indexOf('</script>'))
|
||||||
|
const compiledBinding = ts.transpileModule(binding, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||||
|
const cargoRows = { value: [] }
|
||||||
|
const bind = new Function('labelingMode', 'cartonDetailRows', 'cargoRows', 'selectedReturnOrderNo', 'addReturnSkuBinding', 'let cargoSequence = 0; ' + compiledBinding + '; return addReturnBoxBinding')({ value: 'carton' }, { value: cargoRows.value }, cargoRows, { value: 'RETURN-1' }, () => assert.fail('箱唛模式不添加SKU行'))
|
||||||
|
const parcel = { returnCartonId: 'PARCEL-ID', sourceType: 'RETURN_PARCEL', cartonMark: 'RP-1', productNameZh: '测试商品中文名', skuItems: [{ skuCode: 'SKU-A', quantity: 80 }] }
|
||||||
|
bind(parcel)
|
||||||
|
bind(parcel)
|
||||||
|
assert.equal(cargoRows.value.length, 1)
|
||||||
|
assert.equal(cargoRows.value[0].returnCartonId, 'PARCEL-ID')
|
||||||
|
assert.equal(cargoRows.value[0].quantity, 1)
|
||||||
|
assert.equal(cargoRows.value[0].shipmentNo, '')
|
||||||
|
assert.equal(cargoRows.value[0].name, '测试商品中文名')
|
||||||
|
assert.doesNotMatch(view, /returnSkuOnly|散件库存只能贴 SKU/)
|
||||||
|
assert.match(view, /labelingMode === 'sku' \? addReturnSkuBinding\(source, sku.skuCode\) : addReturnBoxBinding\(source\)/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('部分换标明细显示实物来源、旧新SKU、实际件数和待确认状态', () => {
|
||||||
|
for (const id of ['return-available-skus', 'return-available-boxes']) {
|
||||||
|
const start = view.indexOf('id="' + id + '"')
|
||||||
|
const table = view.slice(start, view.indexOf('</table>', start))
|
||||||
|
assert.match(table, /SKU 换标结果/)
|
||||||
|
assert.match(table, /剩余可换(件)/)
|
||||||
|
assert.match(table, /conversion.oldSkuCode/)
|
||||||
|
assert.match(table, /conversion.newSkuCode/)
|
||||||
|
assert.match(table, /conversion.quantity/)
|
||||||
|
assert.match(table, /item.status !== 'REVERSED'/)
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import ts from 'typescript'
|
||||||
|
const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url), 'utf8')
|
||||||
|
const source = view.slice(view.indexOf('function returnSourceNos'), view.indexOf('const loading = ref(false)'))
|
||||||
|
function setup(candidates) {
|
||||||
|
const output = ts.transpileModule(source + '\nexports.options = relabelInboundOptions; exports.visible = visibleRelabelInboundOptions; exports.label = relabelOptionLabel', { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS } }).outputText
|
||||||
|
const exports = {}, show = { value: false }, search = { value: '' }, selected = { value: '' }
|
||||||
|
new Function('exports', 'computed', 'currentRelabelCandidates', 'showOccupiedRelabelInventory', 'relabelInventorySearch', 'selectedRelabelInboundOrderId', 'inventoryQuantity', output)(exports, fn => ({ get value() { return fn() } }), { value: candidates }, show, search, selected, value => Math.max(0, Number(value) || 0))
|
||||||
|
return { ...exports, show, search, selected }
|
||||||
|
}
|
||||||
|
test('occupied return keeps stock facts but remains hidden when searched', () => {
|
||||||
|
const context=setup([{ returnCartonId:'C', inboundOrderNo:'RT-1', availablePackages:0, stockQuantity:10, inventoryStatus:'RELABEL_PENDING', occupiedRelabelNo:'RL-1' }])
|
||||||
|
assert.equal(context.visible.value.length,0)
|
||||||
|
context.search.value='RT-1'; assert.equal(context.visible.value.length,0)
|
||||||
|
const label=context.label(context.options.value[0]); assert.match(label,/在仓 1 包裹\/箱 · 10 件/); assert.equal(label,'退货单 RT-1|在仓 1 包裹/箱 · 10 件'); assert.match(context.options.value[0].reasons.join(';'),/换标占用 · RL-1/)
|
||||||
|
context.search.value=''; assert.equal(context.visible.value.length,0)
|
||||||
|
})
|
||||||
|
test('merged empty source adds history reason without inflating physical stock count', () => {
|
||||||
|
const context=setup([{ returnCartonId:'OLD', inboundOrderNo:'RT-1', availablePackages:0, stockQuantity:0, inventoryStatus:'MERGED', mergedIntoCartonMarks:['NEW'] },{ returnCartonId:'NEW', inboundOrderNo:'RT-1', availablePackages:10, stockQuantity:10, inventoryStatus:'AVAILABLE' }])
|
||||||
|
assert.equal(context.options.value[0].units,1); assert.equal(context.options.value[0].stockQuantity,10); assert.equal(context.options.value[0].availablePackages,10)
|
||||||
|
assert.match(context.options.value[0].reasons.join(';'),/历史部分转入 NEW(不代表当前库存位置)/)
|
||||||
|
})
|
||||||
|
test('missing stock projection stays unknown and outbound history does not count in-warehouse units', () => {
|
||||||
|
const context=setup([{returnCartonId:'C',inboundOrderNo:'RT-1',availablePackages:0},{returnCartonId:'D',inboundOrderNo:'RT-2',availablePackages:0,stockQuantity:0,inventoryStatus:'OUTBOUNDED'}])
|
||||||
|
assert.match(context.label(context.options.value[0]),/待查询/)
|
||||||
|
assert.equal(context.options.value[1].units,0);assert.match(context.options.value[1].reasons.join(';'),/已出库/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('fully outbound orders stay hidden even in history search; mixed remaining stock marks partial outbound', () => {
|
||||||
|
const context=setup([{returnCartonId:'D',inboundOrderNo:'RT-D',availablePackages:0,stockQuantity:0,inventoryStatus:'OUTBOUNDED'}, {returnCartonId:'A',inboundOrderNo:'RT-P',availablePackages:0,stockQuantity:0,inventoryStatus:'OUTBOUNDED'}, {returnCartonId:'B',inboundOrderNo:'RT-P',availablePackages:2,stockQuantity:2,inventoryStatus:'AVAILABLE'}])
|
||||||
|
context.show.value=true
|
||||||
|
assert.deepEqual(context.visible.value.map(item=>item.inboundOrderNo),['退货单 RT-P'])
|
||||||
|
context.search.value='RT-D';assert.equal(context.visible.value.some(item=>item.inboundOrderNo==='退货单 RT-D'),false)
|
||||||
|
assert.equal(context.label(context.options.value[1]),'退货单 RT-P|在仓 1 包裹/箱 · 2 件|部分出库')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('partially shipped contents within one physical box show partial outbound', () => {
|
||||||
|
const context=setup([{returnCartonId:'B',inboundOrderNo:'RT-P',availablePackages:3,stockQuantity:3,inventoryStatus:'AVAILABLE',hasOutbound:true}])
|
||||||
|
assert.match(context.label(context.options.value[0]),/3 件|部分出库$/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('available box and parcel lists remove zero-quantity sources and zero SKU rows', () => {
|
||||||
|
const block=view.slice(view.indexOf('const availableReturnCandidates'),view.indexOf('const requiresBothTotalFiles'))
|
||||||
|
const output=ts.transpileModule(block+'\nexports.boxes=returnBoxCandidates; exports.parcels=returnLooseCandidates',{compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText
|
||||||
|
const exports={}
|
||||||
|
const sources=[{sourceType:'RETURN_CARTON',cartonMark:'EMPTY',availablePackages:0,skuItems:[{skuCode:'A',quantity:0}]},{sourceType:'RETURN_CARTON',cartonMark:'BOX',availablePackages:3,skuItems:[{skuCode:'A',quantity:0},{skuCode:'B',quantity:3}]},{sourceType:'RETURN_PARCEL',cartonMark:'P0',availablePackages:0},{sourceType:'RETURN_PARCEL',cartonMark:'P1',availablePackages:2,skuItems:[{skuCode:'C',quantity:2}]}]
|
||||||
|
new Function('exports','computed','selectedReturnCandidates','inventoryQuantity',output)(exports,fn=>({get value(){return fn()}}),{value:sources},value=>Math.max(0,Number(value)||0))
|
||||||
|
assert.deepEqual(exports.boxes.value.map(item=>item.cartonMark),['BOX'])
|
||||||
|
assert.deepEqual(exports.boxes.value[0].skuItems,[{skuCode:'B',quantity:3}])
|
||||||
|
assert.deepEqual(exports.parcels.value.map(item=>item.cartonMark),['P1'])
|
||||||
|
assert.doesNotMatch(view,/显示占用及历史单据|showOccupiedRelabelInventory/)
|
||||||
|
})
|
||||||
@@ -6,7 +6,9 @@ const view = readFileSync(new URL('./WarehouseServiceView.vue', import.meta.url)
|
|||||||
const api = readFileSync(new URL('../api/warehouseServices.ts', import.meta.url), 'utf8')
|
const api = readFileSync(new URL('../api/warehouseServices.ts', import.meta.url), 'utf8')
|
||||||
|
|
||||||
test('贴标总文件与关联模板保持左右分组,退货来源使用专用明细', () => {
|
test('贴标总文件与关联模板保持左右分组,退货来源使用专用明细', () => {
|
||||||
assert.match(view, /class="warehouse-file-groups" :class="\{ 'warehouse-file-groups--single': isReturnRelabelSource \}"/)
|
assert.match(view, /class="warehouse-file-groups(?:\s[^"]*)?"/)
|
||||||
|
assert.match(view, /\.warehouse-file-groups--compact\s*\{[^}]*grid-template-columns:\s*minmax\(0, 1fr\) minmax\(0, 1fr\)/)
|
||||||
|
assert.match(view, /v-if="isReturnRelabelSource" class="warehouse-table-scroll"/)
|
||||||
assert.match(view, /warehouse-service-page--return-relabel/)
|
assert.match(view, /warehouse-service-page--return-relabel/)
|
||||||
assert.match(view, /const sourceValue = `RETURN_ORDER:\$\{requestedReturnNo\}`/)
|
assert.match(view, /const sourceValue = `RETURN_ORDER:\$\{requestedReturnNo\}`/)
|
||||||
})
|
})
|
||||||
@@ -136,7 +138,7 @@ test('仓储转运需要换标时上传总文件并挂到关联换标单', () =>
|
|||||||
})
|
})
|
||||||
|
|
||||||
test('仓储转运换标总文件与明细模板在桌面端左右排列', () => {
|
test('仓储转运换标总文件与明细模板在桌面端左右排列', () => {
|
||||||
assert.match(view, /class="warehouse-transfer-file-groups"/)
|
assert.match(view, /class="warehouse-transfer-file-groups(?:\s[^"]*)?"/)
|
||||||
assert.match(view, /\.warehouse-transfer-file-groups\{display:grid;grid-template-columns:minmax\(0,1\.15fr\) minmax\(360px,\.85fr\)/)
|
assert.match(view, /\.warehouse-transfer-file-groups\{display:grid;grid-template-columns:minmax\(0,1\.15fr\) minmax\(360px,\.85fr\)/)
|
||||||
assert.match(view, /\.warehouse-transfer-total-files,\.warehouse-transfer-template-group\{height:100%;margin:0\}/)
|
assert.match(view, /\.warehouse-transfer-total-files,\.warehouse-transfer-template-group\{height:100%;margin:0\}/)
|
||||||
assert.match(view, /@media\(max-width:1180px\)\{\.warehouse-transfer-file-groups\{grid-template-columns:minmax\(0,1fr\)\}\}/)
|
assert.match(view, /@media\(max-width:1180px\)\{\.warehouse-transfer-file-groups\{grid-template-columns:minmax\(0,1fr\)\}\}/)
|
||||||
@@ -303,7 +305,7 @@ test('仓储转运详情自动加载 PDA 测量照片并释放 Blob URL', () =>
|
|||||||
assert.match(view, /加载失败,点击重试/)
|
assert.match(view, /加载失败,点击重试/)
|
||||||
assert.match(view, /URL\.createObjectURL\(blob\)/)
|
assert.match(view, /URL\.createObjectURL\(blob\)/)
|
||||||
assert.match(view, /URL\.revokeObjectURL\(url\)/)
|
assert.match(view, /URL\.revokeObjectURL\(url\)/)
|
||||||
assert.match(view, /onBeforeUnmount\(\(\) => \{ clearCompletionPhotos\(\); clearMeasurementPhotos\(\) \}\)/)
|
assert.match(view, /onBeforeUnmount\(\(\) => \{ clearCompletionPhotos\(\); clearMeasurementPhotos\(\); clearDiscardPhotos\(\) \}\)/)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('PDA 完成后主单显示入库完成并保留客户确认测量入口', () => {
|
test('PDA 完成后主单显示入库完成并保留客户确认测量入口', () => {
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ test('keeps standalone business pages at the client sidebar root', () => {
|
|||||||
{ title: '首页', children: undefined },
|
{ title: '首页', children: undefined },
|
||||||
{
|
{
|
||||||
title: '订单中心',
|
title: '订单中心',
|
||||||
children: ['头程订单', '海外采购', '美国本土卡', '美本土散板'],
|
children: ['头程订单', '入库订单', '派送订单', '海外采购', '美国本土卡', '美本土散板'],
|
||||||
},
|
},
|
||||||
{ title: '报关资料', children: undefined },
|
{ title: '报关资料', children: undefined },
|
||||||
{ title: '船期价格', children: undefined },
|
{ title: '船期价格', children: undefined },
|
||||||
@@ -88,6 +88,8 @@ test('flattens visible leaves with unique paths', () => {
|
|||||||
assert.deepEqual(paths, [
|
assert.deepEqual(paths, [
|
||||||
'/',
|
'/',
|
||||||
'/orders/first-leg',
|
'/orders/first-leg',
|
||||||
|
'/orders/inbound',
|
||||||
|
'/orders/delivery',
|
||||||
'/cross-border/procurement',
|
'/cross-border/procurement',
|
||||||
'/cross-border/domestic-trucking',
|
'/cross-border/domestic-trucking',
|
||||||
'/cross-border/pallet-shipping',
|
'/cross-border/pallet-shipping',
|
||||||
@@ -119,6 +121,24 @@ test('filters inaccessible leaves and empty navigation groups', () => {
|
|||||||
assert.equal(getFirstAccessiblePath([]), '/forbidden')
|
assert.equal(getFirstAccessiblePath([]), '/forbidden')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('exposes active inbound and delivery queries only with their existing read permissions', () => {
|
||||||
|
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', () => {
|
test('excludes entries marked for manual hiding without affecting other visible items', () => {
|
||||||
const visible = filterNavigationByPermissions([
|
const visible = filterNavigationByPermissions([
|
||||||
{ key: 'shown', title: '显示入口', icon: LayoutGrid, path: '/shown', permission: 'shown:view' },
|
{ 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'/)
|
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 = [
|
const routerSource = [
|
||||||
'first-leg',
|
'first-leg',
|
||||||
'cross-border',
|
'cross-border',
|
||||||
@@ -364,8 +384,6 @@ test('keeps internal operational pages routable without exposing them in custome
|
|||||||
|
|
||||||
const hiddenActivePaths = new Set([
|
const hiddenActivePaths = new Set([
|
||||||
'first-leg/quick-order',
|
'first-leg/quick-order',
|
||||||
'orders/inbound',
|
|
||||||
'orders/delivery',
|
|
||||||
'overseas-warehouse/return-inventory',
|
'overseas-warehouse/return-inventory',
|
||||||
'overseas-warehouse/return-cartons',
|
'overseas-warehouse/return-cartons',
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -52,6 +52,8 @@ export const clientNavigation: ClientNavigationNode[] = [
|
|||||||
icon: ClipboardList,
|
icon: ClipboardList,
|
||||||
children: [
|
children: [
|
||||||
requireLeaf('first-leg-orders', '头程订单'),
|
requireLeaf('first-leg-orders', '头程订单'),
|
||||||
|
requireLeaf('orders-inbound', '入库订单'),
|
||||||
|
requireLeaf('orders-delivery', '派送订单'),
|
||||||
requireLeaf('cross-border-procurement'),
|
requireLeaf('cross-border-procurement'),
|
||||||
requireLeaf('cross-border-domestic-trucking'),
|
requireLeaf('cross-border-domestic-trucking'),
|
||||||
requireLeaf('cross-border-pallet-shipping'),
|
requireLeaf('cross-border-pallet-shipping'),
|
||||||
|
|||||||
Reference in New Issue
Block a user