Merge branch 'test' of http://git.buggoglobal.com/java-project/baiyue-firstleg into dev
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
# 后端脚本管理指引
|
||||
|
||||
## 适用范围与读取顺序
|
||||
|
||||
- 本文件适用于后端根 `scripts/` 及其子目录;服务自己的 `<service>/scripts/` 继续受对应服务 `AGENTS.md` 约束。
|
||||
- 先用本文件判断脚本类别,再到 `README.md` 查询仓库级入口的用途、参数边界和副作用;Admin HTTP 模块继续读 `admin-test-env-modules/README.md`。
|
||||
- 不扫描 `target/`、`reports/`、`.logs/`、`node_modules/`、`.codex-*`、`output/` 或 `outputs/` 寻找业务脚本和验收事实。
|
||||
|
||||
## 脚本分类与入口
|
||||
|
||||
| 类别 | 正式入口 | 管理边界 |
|
||||
|---|---|---|
|
||||
| Admin 全量 HTTP 验证 | `admin-test-env-acceptance.mjs` | 默认模块覆盖平台全链路;定向验证使用 `--modules`,模块注册和依赖以总入口及 `admin-test-env-modules/README.md` 为准 |
|
||||
| Client 全量 HTTP 验证 | `client-test-env-acceptance.mjs` | 客户工作台完整链路;`client-phase2-test-env-acceptance.mjs` 只是二期专项,不替代全量入口 |
|
||||
| 待审核订单造数 | `create-pending-review-orders.mjs` | 使用已配置客户创建并提交订单,停在待审核;不审核、不推进后续履约 |
|
||||
| 批量待分柜造数 | `it-test-wait-split-bulk.mjs` | 固定“IT测试”和“义乌仓”,随机客户可选真实线路并尽力推进到 `WAIT_SPLIT`;失败记录后继续,不自动删除成功数据;只复用 `TP-001`/`YW-TP-002`,不新增托盘或库位,普通位不足落 `A0` |
|
||||
| Admin HTTP 内部模块 | `admin-test-env-modules/*.mjs` | 由 Admin 总入口动态加载,除文档明确的独立编排器外不得当作独立全量入口;`*contract.test.mjs` 只做离线合同 |
|
||||
| 定向 HTTP/诊断 | 以 `README.md` 的“仓库级入口清单”为准 | 必须明确是只读诊断还是会补证据、创建资源或推进状态,不能用诊断成功冒充全量通过 |
|
||||
| 本地质量与静态合同 | `backend-full-regression.ps1`、`frontend-full-regression.ps1`、`mapper-scan-contract.mjs`、`script-documentation-contract.test.mjs` 等 | 默认不访问测试环境;数据库非 dry-run、Nacos 发布等有写入能力的入口必须按 README 单独识别 |
|
||||
| 部署与基础设施 | `../deploy/scripts/`、`../deploy/rocketmq/` | 靠近部署组件管理,不移动到根脚本目录;部署、初始化数据库或发布配置必须获得当前轮明确授权 |
|
||||
| 服务局部合同 | `../firstleg/scripts/`、`../lastleg-service/scripts/`、`../warehouse/scripts/` | 只服务所属模块,入口与命令登记在服务 `AGENTS.md` 或局部 README;不得散落到 `src/test/scripts/` |
|
||||
|
||||
## 新增与修改规则
|
||||
|
||||
- 跨服务编排、全仓质量检查、测试环境验收和通用诊断放在根 `scripts/`;只理解单一服务源码或数据的脚本放在 `<service>/scripts/`。
|
||||
- 可直接运行的脚本必须在 `README.md` 登记:用途、目标环境、是否写数据、凭据来源、报告位置、失败/重跑语义和清理边界。内部模块必须登记到 `admin-test-env-modules/README.md`,并按需同步总入口模块注册及依赖展开。
|
||||
- 文件命名使用稳定业务语义:离线 Node 合同以 `.test.mjs` 结尾;环境写入入口显式包含 `test-env` 或在 README 中标记目标环境;fixture/verify 必须区分准备写入和只读核验。
|
||||
- 不在源码、AGENTS、README 或报告中写入密码、Token、私钥、真实客户数据和固定环境密钥;环境地址与账号从入口已支持的参数或本机环境配置读取。
|
||||
- 开发与测试验收配置分别只维护在 `$env:USERPROFILE\.codex\chongchong-global-dev-acceptance.env`、`$env:USERPROFILE\.codex\chongchong-global-test-acceptance.env`。脚本不得自动猜测环境或读取另一份文件;运行者必须通过位于脚本路径之前的 `node --env-file="<明确文件>"` 选择环境。
|
||||
- 不直接写业务数据库伪造 HTTP 验收成功,不吞掉 `deploymentBlocker`、业务错误码、`requestId` 或 `traceId`。造数脚本的部分成功数据默认保留,清理、重置或删除必须另行授权。
|
||||
- 不默认并发运行共享环境造数。只有用户明确要求并确认序号、报告目录和服务容量边界时,才允许拆分 worker;每个 worker 必须使用不重叠序号和独立报告目录。
|
||||
- 修改公共参数、上下文或模块签名时,定向检查总入口、生产模块、fixture、合同测试、README 和调用命令,禁止保留旧参数兼容分支。
|
||||
|
||||
## 最低验证
|
||||
|
||||
- 修改单个 Node 脚本先运行 `node --check <script>`;PowerShell 使用解析检查或该脚本声明的 `-DryRun`,Shell/Groovy 使用现有离线合同,不为验证触发部署。
|
||||
- 修改 Admin 模块时运行直接对应的 `*contract.test.mjs`;修改造数链时同时运行 `admin-test-env-modules/it-test-wait-split-bulk-contract.test.mjs` 等受影响合同。
|
||||
- 新增、移动或删除脚本后运行 `node --test scripts/script-documentation-contract.test.mjs`,确认目录已登记且所有直接入口都有说明。
|
||||
- 修改任一 `AGENTS.md` 后从后端根运行 `./scripts/agents-index-contract.ps1`;真实 HTTP、数据库、Nacos、Jenkins 和部署验证仍须当前轮明确授权。
|
||||
+40
-3
@@ -1,7 +1,44 @@
|
||||
# 全量 HTTP 验收脚本索引
|
||||
# 后端脚本管理与全量 HTTP 验收索引
|
||||
|
||||
全量验收只认测试环境 HTTP 脚本。它们通过 Gateway 调用已部署服务,按业务模块执行真实登录、权限、状态、幂等、跨服务和数据链路检查;脚本通过后,剩余工作是 Admin/Client 的真实接口调用与浏览器样式验收,以及 PDA 页面/设备验收。
|
||||
|
||||
进入本目录维护或运行脚本前先读 `scripts/AGENTS.md`;本文件是脚本入口、用途和副作用的唯一总索引,具体模块说明继续下沉到相邻 README。
|
||||
|
||||
## 验收环境变量文件
|
||||
|
||||
开发与测试环境的账号、密码和 Gateway 只维护在用户目录的两份外部文件中,不写入仓库:
|
||||
|
||||
| 环境 | 文件 |
|
||||
|---|---|
|
||||
| 开发环境 | `$env:USERPROFILE\.codex\chongchong-global-dev-acceptance.env` |
|
||||
| 测试环境 | `$env:USERPROFILE\.codex\chongchong-global-test-acceptance.env` |
|
||||
|
||||
两份文件统一提供以下变量:
|
||||
|
||||
```text
|
||||
ADMIN_TEST_GATEWAY
|
||||
ADMIN_OVERSEAS_GATEWAY
|
||||
ADMIN_TEST_USERNAME
|
||||
ADMIN_TEST_PASSWORD
|
||||
MERCHANT_TEST_USERNAME
|
||||
MERCHANT_TEST_PASSWORD
|
||||
```
|
||||
|
||||
脚本只读取当前 Node 进程的环境变量,不会自行查找或加载上述文件。运行时必须把 `--env-file` 放在脚本路径之前,明确选择环境:
|
||||
|
||||
```powershell
|
||||
# 开发环境
|
||||
node --env-file="$env:USERPROFILE\.codex\chongchong-global-dev-acceptance.env" scripts/admin-test-env-acceptance.mjs
|
||||
|
||||
# 测试环境
|
||||
node --env-file="$env:USERPROFILE\.codex\chongchong-global-test-acceptance.env" scripts/admin-test-env-acceptance.mjs
|
||||
|
||||
# 测试环境批量待分柜造数
|
||||
node --env-file="$env:USERPROFILE\.codex\chongchong-global-test-acceptance.env" scripts/it-test-wait-split-bulk.mjs
|
||||
```
|
||||
|
||||
Client 全量、Client 二期、待审核订单和批量待分柜均复用这套变量,不再维护各自的 Gateway、管理员或客户账号变量。外部文件必须保留在仓库之外,不得复制到项目目录、报告或提交记录。
|
||||
|
||||
## 脚本目录归属
|
||||
|
||||
脚本按作用域放置,不要求全部集中到根 `scripts/`:
|
||||
@@ -64,7 +101,7 @@
|
||||
|---|---|---|---|
|
||||
| 平台后台全模块 HTTP 验收 | `scripts/admin-test-env-acceptance.mjs` | 会创建、更新或最终停用测试数据 | `--modules` 默认列表中的平台客户、仓储、订单、入库、分柜、装柜、船期、拖车、报关、财务、通知、统计等模块 |
|
||||
| 客户工作台完整 HTTP 链路验收 | `scripts/client-test-env-acceptance.mjs` | 会创建测试企业、订单、入库、权限和站内消息数据 | 注册/审核、客户隔离、订单、入库计费、文件、财务、客户侧权限,以及我的消息未读/已读/全部已读链路 |
|
||||
| 固定客户批量创建待审核订单 | `scripts/create-pending-review-orders.mjs` | 只使用固定客户账号创建指定数量订单 | 登录 `17512095155`,选择真实可计价仓库/渠道,创建并提交订单,停在待审核,不创建客户、不审核订单 |
|
||||
| 固定客户批量创建待审核订单 | `scripts/create-pending-review-orders.mjs` | 只使用 `MERCHANT_TEST_USERNAME/PASSWORD` 配置的客户账号创建指定数量订单 | 使用 `ADMIN_TEST_GATEWAY`,选择真实可计价仓库/渠道,创建并提交订单,停在待审核,不创建客户、不审核订单 |
|
||||
| Client 二期专项 HTTP 验收 | `scripts/client-phase2-test-env-acceptance.mjs` | 会写入测试环境业务数据 | 二期客户入库、测量、费用和权限专项场景;不是替代 Client 全量入口 |
|
||||
| 人工分柜至 LOADED 分段验收 | `scripts/admin-test-env-acceptance.mjs` 的 `manual-*-fixture/verify` 可选模块;步骤和参数见 `scripts/admin-test-env-modules/README.md` | fixture 通过正式 HTTP 准备本轮数据,verify 只读核验;不进入默认全量 | `WAIT_SPLIT → 人工分柜 → 推送预装 → 订舱关联/计划确认 → PDA 领取与原子 batch → 五类证据/完成 → LOADED` |
|
||||
|
||||
@@ -74,7 +111,7 @@
|
||||
|
||||
## 固定客户待审核订单
|
||||
|
||||
需要为人工审核准备固定数量的订单时,使用 `create-pending-review-orders.mjs`。可直接在文件顶部 `CONFIG` 中填写 `GATEWAY`、`USERNAME`、`PASSWORD` 和 `COUNT`;固定账号为 `17512095155`。脚本不会创建客户,也不会调用平台审核、入库或后续履约接口。数量支持 `1-100`,每张订单创建后立即提交并回查客户端状态为 `SUBMITTED`,报告统一记录为 `PENDING_REVIEW`。
|
||||
需要为人工审核准备固定数量的订单时,使用 `create-pending-review-orders.mjs`。Gateway 统一读取 `ADMIN_TEST_GATEWAY`,客户账号统一读取 `MERCHANT_TEST_USERNAME/PASSWORD`;数量可通过 `--count` 或 `PENDING_REVIEW_ORDER_COUNT` 设置,默认 50。脚本不会创建客户,也不会调用平台审核、入库或后续履约接口。数量支持 `1-100`,每张订单创建后立即提交并回查客户端状态为 `SUBMITTED`,报告统一记录为 `PENDING_REVIEW`。
|
||||
|
||||
```powershell
|
||||
node scripts/create-pending-review-orders.mjs
|
||||
|
||||
@@ -13,6 +13,33 @@ const OPTIONAL_MODULES = ['manual-order-splitting-fixture', 'manual-order-splitt
|
||||
'manual-loading-complete-fixture', 'manual-loading-complete-verify',
|
||||
'coload-groups']
|
||||
const AVAILABLE_MODULES = new Set([...CONFIGURED_MODULES, ...OPTIONAL_MODULES])
|
||||
const A0_LOCATION_PAGE_SIZE = 200
|
||||
const A0_MAX_LOCATION_MUTATIONS = 8
|
||||
|
||||
export function planA0LocationIsolation(locations, requiredSlots = 1,
|
||||
maxMutations = A0_MAX_LOCATION_MUTATIONS) {
|
||||
const slots = Math.max(1, Number.isInteger(Number(requiredSlots)) ? Number(requiredSlots) : 1)
|
||||
const limit = Math.max(0, Number.isInteger(Number(maxMutations)) ? Number(maxMutations) : 0)
|
||||
const unique = new Map()
|
||||
for (const location of Array.isArray(locations) ? locations : []) {
|
||||
const locationId = location?.id == null ? '' : String(location.id)
|
||||
if (!locationId || location?.sharedOverflow === true || unique.has(locationId)) continue
|
||||
unique.set(locationId, location)
|
||||
}
|
||||
const normal = [...unique.values()].sort((left, right) =>
|
||||
String(left?.locationCode || '').localeCompare(String(right?.locationCode || ''))
|
||||
|| String(left.id).localeCompare(String(right.id)))
|
||||
const remainingNormal = Math.max(0, slots - 1)
|
||||
const mutationsRequired = Math.max(0, normal.length - remainingNormal)
|
||||
return {
|
||||
enabled: mutationsRequired <= limit,
|
||||
requiredSlots: slots,
|
||||
normalCount: normal.length,
|
||||
expectedRemainingNormal: Math.min(normal.length, remainingNormal),
|
||||
mutationsRequired,
|
||||
targets: mutationsRequired <= limit ? normal.slice(0, mutationsRequired) : [],
|
||||
}
|
||||
}
|
||||
|
||||
const MODULE_DEPENDENCIES = new Map([
|
||||
['suppliers', ['merchant-qualification-fixture']],
|
||||
@@ -1236,15 +1263,17 @@ export class AcceptanceRun {
|
||||
this.assert('phase3-loading-fixture', 'A0 隔离使用本轮订单收货仓', null,
|
||||
Boolean(warehouseId), `warehouseId=${warehouseId || 'missing'}`,
|
||||
{ scenario: 'phase3-loading-a0-fixture', deploymentBlocker: true })
|
||||
const disabledLocations = requireSharedOverflow
|
||||
? await this.disableAvailableLocationsForA0(warehouseId) : []
|
||||
this.context.phase3LoadingRequireSharedOverflow = requireSharedOverflow
|
||||
const requiredPalletCount = Math.max(1, Number(this.context?.waitSplitVariant?.palletCount || 1))
|
||||
const isolation = requireSharedOverflow
|
||||
? await this.disableAvailableLocationsForA0(warehouseId, requiredPalletCount)
|
||||
: { forced: false, disabled: [] }
|
||||
this.context.phase3LoadingRequireSharedOverflow = isolation.forced === true
|
||||
try {
|
||||
const measurement = await import(new URL('./admin-test-env-modules/inbound-measurement.mjs', import.meta.url))
|
||||
await this.executeModule('inbound-measurement-phase3-loading-fixture', () => measurement.run(this))
|
||||
} finally {
|
||||
if (requireSharedOverflow) {
|
||||
await this.restoreAvailableLocationsAfterA0(warehouseId, disabledLocations)
|
||||
await this.restoreAvailableLocationsAfterA0(warehouseId, isolation)
|
||||
}
|
||||
}
|
||||
const fixture = this.createdResources.inboundMeasurement || this.createdResources.orders
|
||||
@@ -1430,24 +1459,60 @@ export class AcceptanceRun {
|
||||
{ scenario: 'phase3-phase4-producer-fixture', deploymentBlocker: true })
|
||||
}
|
||||
|
||||
async disableAvailableLocationsForA0(warehouseId) {
|
||||
async listAvailableLocationsForA0(warehouseId, module, options) {
|
||||
const locations = []
|
||||
const seen = new Set()
|
||||
let expectedTotal = null
|
||||
for (let pageNumber = 1; pageNumber <= 100; pageNumber += 1) {
|
||||
const response = await this.request('GET',
|
||||
`/api/platform/v1/locations?tenantId=0&page=${pageNumber}&size=${A0_LOCATION_PAGE_SIZE}&warehouseId=${encodeURIComponent(warehouseId)}&status=AVAILABLE`)
|
||||
const page = this.apiSuccess(module, `查询 A0 隔离前可用库位第 ${pageNumber} 页`, response,
|
||||
`page=${pageNumber}`, options)
|
||||
if (!page) return null
|
||||
const pageTotal = Number(page.total)
|
||||
const records = Array.isArray(page.records) ? page.records : []
|
||||
if (!Number.isInteger(pageTotal) || pageTotal < 0
|
||||
|| (expectedTotal !== null && pageTotal !== expectedTotal)) {
|
||||
this.assert(module, 'A0 隔离库位分页总数稳定', response, false,
|
||||
`page=${pageNumber}, firstTotal=${expectedTotal ?? 'missing'}, currentTotal=${page.total ?? 'missing'}`, options)
|
||||
return null
|
||||
}
|
||||
expectedTotal ??= pageTotal
|
||||
for (const location of records) {
|
||||
const locationId = location?.id == null ? '' : String(location.id)
|
||||
if (locationId && !seen.has(locationId)) {
|
||||
seen.add(locationId)
|
||||
locations.push(location)
|
||||
}
|
||||
}
|
||||
if (locations.length >= expectedTotal) break
|
||||
if (records.length === 0) break
|
||||
}
|
||||
const complete = locations.length === expectedTotal
|
||||
this.assert(module, 'A0 隔离库位分页完整且无重复', null, complete,
|
||||
`total=${expectedTotal ?? 'missing'}, uniqueRecords=${locations.length}`, options)
|
||||
return complete ? locations : null
|
||||
}
|
||||
|
||||
async disableAvailableLocationsForA0(warehouseId, requiredSlots = 1) {
|
||||
const module = 'phase3-loading-fixture'
|
||||
const options = { scenario: 'phase3-loading-a0-fixture', deploymentBlocker: true }
|
||||
if (!warehouseId) {
|
||||
this.assert(module, 'A0 隔离收货仓 ID 完整', null, false, 'warehouseId=missing', options)
|
||||
return []
|
||||
return { forced: false, disabled: [] }
|
||||
}
|
||||
const locations = await this.listAvailableLocationsForA0(warehouseId, module, options)
|
||||
if (!locations) return { forced: false, disabled: [] }
|
||||
const isolation = planA0LocationIsolation(locations, requiredSlots)
|
||||
if (!isolation.enabled) {
|
||||
this.addStep(module, 'A0 大仓保护:不批量停用普通库位', null, true,
|
||||
`normal=${isolation.normalCount}, requiredSlots=${isolation.requiredSlots}, mutationsRequired=${isolation.mutationsRequired}, safetyLimit=${A0_MAX_LOCATION_MUTATIONS}`,
|
||||
{ scenario: options.scenario })
|
||||
return { forced: false, disabled: [], isolation }
|
||||
}
|
||||
const pageResponse = await this.request('GET',
|
||||
`/api/platform/v1/locations?tenantId=0&page=1&size=200&warehouseId=${encodeURIComponent(warehouseId)}&status=AVAILABLE`)
|
||||
const page = this.apiSuccess(module, '查询 A0 隔离前全部可用普通库位', pageResponse, '', options)
|
||||
const records = Array.isArray(page?.records) ? page.records : []
|
||||
const locations = records.filter((item) => item.sharedOverflow !== true)
|
||||
this.assert(module, 'A0 隔离库位分页完整', pageResponse,
|
||||
Number(page?.total) === records.length && records.length < 200,
|
||||
`total=${page?.total ?? 'missing'}, records=${records.length}, normal=${locations.length}`, options)
|
||||
const disabled = []
|
||||
const skippedOccupied = []
|
||||
for (const location of locations) {
|
||||
for (const location of isolation.targets) {
|
||||
const response = await this.request('PATCH',
|
||||
`/api/platform/v1/locations/${encodeURIComponent(location.id)}/status?tenantId=0&warehouseId=${encodeURIComponent(warehouseId)}`,
|
||||
{ status: 'DISABLED', version: Number(location.version) })
|
||||
@@ -1462,16 +1527,19 @@ export class AcceptanceRun {
|
||||
}
|
||||
const availableResponse = await this.request('GET',
|
||||
`/api/platform/v1/locations/available?tenantId=0&warehouseId=${encodeURIComponent(warehouseId)}&limit=200`)
|
||||
const available = this.apiSuccess(module, '停用后回查收货仓无可用普通库位', availableResponse, '', options)
|
||||
this.assert(module, '测量前 A0 溢出条件成立', availableResponse,
|
||||
Array.isArray(available) && available.length === 0,
|
||||
`disabled=${disabled.length}, skippedOccupied=${skippedOccupied.map((item) => `${item.code}:${item.id}`).join('|') || 'none'}, available=${Array.isArray(available) ? available.length : 'missing'}`, options)
|
||||
return disabled
|
||||
const available = this.apiSuccess(module, '停用后回查收货仓剩余普通库位', availableResponse, '', options)
|
||||
const remainingNormal = Array.isArray(available)
|
||||
? available.filter((item) => item?.sharedOverflow !== true) : null
|
||||
const forced = Array.isArray(remainingNormal) && remainingNormal.length < isolation.requiredSlots
|
||||
this.assert(module, '测量前 A0 溢出条件成立', availableResponse, forced,
|
||||
`requiredSlots=${isolation.requiredSlots}, disabled=${disabled.length}, skippedOccupied=${skippedOccupied.map((item) => `${item.code}:${item.id}`).join('|') || 'none'}, remainingNormal=${Array.isArray(remainingNormal) ? remainingNormal.length : 'missing'}`, options)
|
||||
return { forced, disabled, isolation }
|
||||
}
|
||||
|
||||
async restoreAvailableLocationsAfterA0(warehouseId, disabledLocations) {
|
||||
async restoreAvailableLocationsAfterA0(warehouseId, result) {
|
||||
const module = 'phase3-loading-fixture'
|
||||
const options = { scenario: 'phase3-loading-a0-fixture', deploymentBlocker: true }
|
||||
const disabledLocations = Array.isArray(result?.disabled) ? result.disabled : []
|
||||
for (const location of disabledLocations) {
|
||||
const response = await this.request('PATCH',
|
||||
`/api/platform/v1/locations/${encodeURIComponent(location.id)}/status?tenantId=0&warehouseId=${encodeURIComponent(warehouseId)}`,
|
||||
@@ -1481,7 +1549,10 @@ export class AcceptanceRun {
|
||||
`locationId=${location.id}, restoreVersion=${location.version}`, options)
|
||||
}
|
||||
this.createdResources.phase3LoadingA0Isolation = {
|
||||
warehouseId, restored: disabledLocations.map((item) => item.id), marker: this.marker,
|
||||
warehouseId, forced: result?.forced === true,
|
||||
normalCount: result?.isolation?.normalCount ?? null,
|
||||
mutationsRequired: result?.isolation?.mutationsRequired ?? 0,
|
||||
restored: disabledLocations.map((item) => item.id), marker: this.marker,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ export async function run(context) {
|
||||
|---|---|---|
|
||||
| 商户资质与下单身份 | `merchant-qualification-fixture.mjs` | `merchant-qualification-fixture-contract.test.mjs` |
|
||||
| 公共主数据与往来单位 | `master-data.mjs` | `master-data-partner-contract.test.mjs` |
|
||||
| 订单创建、可计价主数据与审核异步收敛 | `orders.mjs` | `orders-pricing-fixture-contract.test.mjs`、`orders-approval-convergence-contract.test.mjs` |
|
||||
| 订单创建、可计价主数据、幂等零漂移与审核异步收敛 | `orders.mjs` | `orders-pricing-fixture-contract.test.mjs`、`orders-lifecycle-idempotency-contract.test.mjs`、`orders-approval-convergence-contract.test.mjs` |
|
||||
| 入库测量、首次打印冻结箱码与墨家扫码 | `inbound-measurement.mjs` | `inbound-measurement-box-code-contract.test.mjs` |
|
||||
| 入仓自动头程费用、派生详情、人工发布与 MANUAL 其他费用版本 | `inbound-fees.mjs`(前置:`merchant-qualification-fixture,orders,inbound-measurement`) | `inbound-fees-contract.test.mjs` |
|
||||
| 三期模拟柜关联、柜次概览、渠道隔离、装柜模型桥接、PDA、动态增量、四类货柜资料、报关与证据/出仓门禁 | `phase3-container-loading.mjs`、`ocean-booking-fixture.mjs`、`phase3-container-overview.mjs`、`phase3-loading.mjs`、`phase3-loading-model-bridge.mjs`、`phase3-pda-convergence.mjs`、`phase3-evidence-gate.mjs`、`phase3-loading-finalize.mjs`、`phase3-container-documents.mjs`、`phase3-customs.mjs`、`phase3-outbound-dispatch.mjs` | `container-simulation-association-contract.test.mjs`、`container-specification-fixture-contract.test.mjs`、`ocean-booking-channel-contract.test.mjs`、`phase3-container-regression-contract.test.mjs`、`phase3-loading-model-bridge-contract.test.mjs`、`phase3-loading-dynamic-final-contract.test.mjs`、`phase3-container-documents-contract.test.mjs`、`phase3-phase4-departure-pickup-chain-contract.test.mjs`、`phase3-producer-chain-contract.test.mjs`、`manual-state-loading-pda-contract.test.mjs` |
|
||||
|
||||
@@ -37,6 +37,7 @@ test('验收只使用本轮 marker fixture,解析真实 XLSX 并覆盖门禁
|
||||
assert.match(source, /无 Finance export 权限拒绝创建/)
|
||||
assert.match(source, /Provider 失败信息可见/)
|
||||
assert.match(source, /9223372036854775806/)
|
||||
assert.match(source, /find\(\(item\) => item\?\.direction === 'RECEIVABLE'\)/)
|
||||
assert.doesNotMatch(source, /exportType:\s*['"]CUSTOMER_LIST/)
|
||||
assert.doesNotMatch(source, /FINANCE_FEE_SOURCE_LIST:[^\n]*参与结算/)
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@ export const REQUIRED_PERMISSIONS = Object.freeze([
|
||||
])
|
||||
|
||||
export const EXPORT_SPECS = Object.freeze({
|
||||
FINANCE_CUSTOMER_ACCOUNT_LIST: ['客户编码', '客户', '联系人', '联系电话', '待收(CNY)', '待开账(CNY)', '本期已收(CNY)', '总成本(CNY)', '已付成本(CNY)', '待付(CNY)', '客户状态', '最近变动'],
|
||||
FINANCE_CUSTOMER_ACCOUNT_LIST: ['客户编码', '客户', '联系人', '联系电话', '待收客户款(CNY)', '待开账(CNY)', '本期已收(CNY)', '总成本(CNY)', '已线下支付供应商款(CNY)', '待付供应商款(CNY)', '客户状态', '最近变动'],
|
||||
FINANCE_CUSTOMER_ACCOUNT_LEDGER: ['流水号', '发生时间', '业务类型', '关联单据', '应收变动(CNY)', '应付变动(CNY)', '变动后未收(CNY)', '操作人', '备注'],
|
||||
FINANCE_FEE_SOURCE_LIST: ['客户', '收付方向', '来源类型', '来源单据ID', '来源版本', '入仓号', '柜次号', '业务发生日', '费用项目', '计费量', '单价(CNY)', '金额(CNY)', '审核状态', '来源状态', '已生成对账单'],
|
||||
FINANCE_RECONCILIATION_STATEMENT_LIST: ['对账单号', '客户', '结算起始日', '结算结束日', '账期(天)', '货币', '总应收金额(CNY)', '已收金额(CNY)', '未收金额(CNY)', '是否结清', '审核状态', '备注', '创建人', '创建时间', '更新人', '更新时间'],
|
||||
@@ -233,7 +233,10 @@ export async function run(context) {
|
||||
const ar = await official(context, `/api/platform/finance/v1/settlements/${encodeURIComponent(arId)}`, '读取应收结算导出事实')
|
||||
const ap = await official(context, `/api/platform/finance/v1/settlements/${encodeURIComponent(apId)}`, '读取应付结算导出事实')
|
||||
const fee = await official(context, `/api/platform/finance/v1/fee-pool?customerId=${encodeURIComponent(customerId)}&direction=ALL`, '读取费用来源导出事实')
|
||||
const feeRow = values(fee.data)[0]
|
||||
// PAYABLE rows are removed from the payable pool once an AP settlement owns
|
||||
// them. Use a receivable row so the export filter still has an authoritative
|
||||
// post-settlement match instead of asserting against an intentionally consumed row.
|
||||
const feeRow = values(fee.data).find((item) => item?.direction === 'RECEIVABLE') || values(fee.data)[0]
|
||||
const statementNo = statement.data?.statementNo
|
||||
const arSummary = ar.data?.summary || ar.data
|
||||
const apSummary = ap.data?.summary || ap.data
|
||||
|
||||
@@ -16,6 +16,7 @@ test('Finance AP consumes only published fin_fee_source rows and never substitut
|
||||
})
|
||||
const financePermissions = [
|
||||
'platform:finance:customer-account:list', 'platform:finance:customer-arap:list',
|
||||
'platform:finance:fee-source:edit',
|
||||
'platform:finance:fee-source:review', 'platform:finance:customer-statement:list',
|
||||
'platform:finance:reconciliation:create', 'platform:finance:reconciliation:review',
|
||||
'platform:finance:reconciliation:issue', 'platform:finance:reconciliation:adjust',
|
||||
@@ -61,6 +62,7 @@ function fakeContext(withFixture = true, permissions = financePermissions, denyF
|
||||
const calls = []
|
||||
const steps = []
|
||||
const coverageGaps = []
|
||||
const submittedSourceIds = new Set()
|
||||
const reviewedSourceIds = new Set()
|
||||
|
||||
function responseForStatement(statement) { return structuredClone(statement) }
|
||||
@@ -124,14 +126,24 @@ function fakeContext(withFixture = true, permissions = financePermissions, denyF
|
||||
const feeSourceDetailMatch = requestPath.match(/\/fee-sources\/(\d+)$/)
|
||||
if (method === 'GET' && feeSourceDetailMatch) {
|
||||
const localId = feeSourceDetailMatch[1]
|
||||
return ok({ feeSourceId: localId, reviewStatus: reviewedSourceIds.has(localId) ? 'APPROVED' : 'PENDING',
|
||||
sourceStatus: 'AVAILABLE', statementGenerated: false, operationVersion: reviewedSourceIds.has(localId) ? 1 : 0 })
|
||||
return ok({ feeSourceId: localId, reviewStatus: reviewedSourceIds.has(localId) ? 'APPROVED'
|
||||
: submittedSourceIds.has(localId) ? 'PENDING' : 'DRAFT',
|
||||
sourceStatus: 'AVAILABLE', statementGenerated: false,
|
||||
operationVersion: reviewedSourceIds.has(localId) ? 2 : submittedSourceIds.has(localId) ? 1 : 0 })
|
||||
}
|
||||
const feeSourceSubmitMatch = requestPath.match(/\/fee-sources\/(\d+)\/submit$/)
|
||||
if (method === 'POST' && feeSourceSubmitMatch) {
|
||||
submittedSourceIds.add(feeSourceSubmitMatch[1])
|
||||
const submitted = { feeSourceId: feeSourceSubmitMatch[1], reviewStatus: 'PENDING',
|
||||
sourceStatus: 'AVAILABLE', statementGenerated: false, operationVersion: 1 }
|
||||
if (idem) idempotency.set(idem, submitted)
|
||||
return ok(submitted)
|
||||
}
|
||||
const feeSourceReviewMatch = requestPath.match(/\/fee-sources\/(\d+)\/review$/)
|
||||
if (method === 'POST' && feeSourceReviewMatch) {
|
||||
reviewedSourceIds.add(feeSourceReviewMatch[1])
|
||||
const reviewed = { feeSourceId: feeSourceReviewMatch[1], reviewStatus: 'APPROVED',
|
||||
sourceStatus: 'AVAILABLE', statementGenerated: false, operationVersion: 1 }
|
||||
sourceStatus: 'AVAILABLE', statementGenerated: false, operationVersion: 2 }
|
||||
if (idem) idempotency.set(idem, reviewed)
|
||||
return ok(reviewed)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ const LEGACY_STATEMENT_VIEW_PERMISSION = 'platform:finance:bill:view'
|
||||
const REQUIRED_PERMISSIONS = [
|
||||
'platform:finance:customer-account:list',
|
||||
'platform:finance:customer-arap:list',
|
||||
'platform:finance:fee-source:edit',
|
||||
'platform:finance:fee-source:review',
|
||||
STATEMENT_LIST_PERMISSION,
|
||||
'platform:finance:reconciliation:create',
|
||||
@@ -172,6 +173,16 @@ async function approveFixtureSources(context, fixture) {
|
||||
let detail = context.apiSuccess(MODULE, '回读本轮 Finance 费用来源审核状态', detailResponse,
|
||||
`feeSourceId=${source.feeSourceId}`, OPTIONS)
|
||||
if (!detail) return false
|
||||
if (detail.reviewStatus === 'DRAFT' || detail.reviewStatus === 'REJECTED') {
|
||||
const submitResponse = await write(context, 'POST', `${BASE}/fee-sources/${encodeURIComponent(source.feeSourceId)}/submit`, {
|
||||
reason: context.marker, expectedVersion: Number(detail.operationVersion),
|
||||
}, `fee-source-submit-${source.feeSourceId}`)
|
||||
detail = context.apiSuccess(MODULE, '提交本轮 Finance 费用来源审核', submitResponse,
|
||||
`feeSourceId=${source.feeSourceId}`, OPTIONS)
|
||||
context.assert(MODULE, '费用来源提交后进入待审核', submitResponse,
|
||||
detail?.reviewStatus === 'PENDING' && detail?.sourceStatus === 'AVAILABLE',
|
||||
`feeSourceId=${source.feeSourceId}, reviewStatus=${detail?.reviewStatus ?? 'missing'}, sourceStatus=${detail?.sourceStatus ?? 'missing'}`, OPTIONS)
|
||||
}
|
||||
if (detail.reviewStatus === 'PENDING') {
|
||||
const reviewResponse = await write(context, 'POST', `${BASE}/fee-sources/${encodeURIComponent(source.feeSourceId)}/review`, {
|
||||
action: 'APPROVE', reason: context.marker, expectedVersion: Number(detail.operationVersion),
|
||||
|
||||
@@ -122,6 +122,8 @@ export function truckAppointmentFieldGaps(record) {
|
||||
status: isNonBlank,
|
||||
carrierId: isPositiveId,
|
||||
carrierName: isNonBlank,
|
||||
payableAmount: isNonNegativeNumber,
|
||||
currency: (value) => value === 'RMB' || value === 'USD',
|
||||
attachmentCount: isNonNegativeNumber,
|
||||
})
|
||||
}
|
||||
|
||||
+6
-10
@@ -6,7 +6,6 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
import {
|
||||
containerFieldGaps,
|
||||
customsCaseFieldGaps,
|
||||
loadingListFieldGaps,
|
||||
oceanBookingFieldGaps,
|
||||
outboundAggregateFieldGaps,
|
||||
@@ -33,14 +32,13 @@ test('原型锁定货柜、预装、装柜、订舱与拖车关键列表字段',
|
||||
}
|
||||
})
|
||||
|
||||
test('八类 Admin 列表均以左固定操作列开头', () => {
|
||||
test('现行 Admin 履约列表均以左固定操作列开头', () => {
|
||||
const sources = [
|
||||
['container-loading/pages/ContainersView.vue', 1],
|
||||
['loading-lists/components/LoadingListsView.vue', 2],
|
||||
['ocean-bookings/pages/OceanBookingsView.vue', 1],
|
||||
['port-schedules/pages/PortSchedulesView.vue', 1],
|
||||
['trucking/pages/TruckAppointmentsView.vue', 1],
|
||||
['customs/pages/CustomsCasesView.vue', 1],
|
||||
['outbound-dispatch/pages/OutboundDispatchesView.vue', 1],
|
||||
]
|
||||
for (const [relative, count] of sources) {
|
||||
@@ -56,8 +54,7 @@ test('Admin 当前列表逐字段列与验收矩阵一致', () => {
|
||||
'loading-lists/components/LoadingListsView.vue': ['preloadNo', 'customers', 'skuCount', 'loadingListNo', 'totalPackageCount', 'totalGrossWeightKg', 'totalNetWeightKg', 'totalVolumeCbm', 'totalQuantity', 'createdByName'],
|
||||
'ocean-bookings/pages/OceanBookingsView.vue': ['bookingNo', 'customerName', 'billOfLadingNo', 'carrierName', 'bookingAgent', 'vesselName', 'pol', 'pod', 'etd', 'eta', 'updatedAt'],
|
||||
'port-schedules/pages/PortSchedulesView.vue': ['schedule.scheduleNo', 'schedule.sourceName', 'schedule.vesselName', 'schedule.departurePortName', 'schedule.destinationPortName', 'schedule.etdAt', 'schedule.etaAt', 'schedule.observedAt', 'expired'],
|
||||
'trucking/pages/TruckAppointmentsView.vue': ['appointmentNo', 'containerNo', 'company', 'driver', 'vehicleNo', 'store', 'payableAmount', 'receivableAmount', 'plannedLoadingAt', 'attachmentCount'],
|
||||
'customs/pages/CustomsCasesView.vue': ['customsNo', 'orderLink', 'inboundLink', 'checklistCode', 'checklistVersionNo', 'status', 'updatedAt'],
|
||||
'trucking/pages/TruckAppointmentsView.vue': ['appointmentNo', 'containerNo', 'company', 'driver', 'vehicleNo', 'store', 'payableAmount', 'currency', 'plannedLoadingAt', 'attachmentCount'],
|
||||
'outbound-dispatch/pages/OutboundDispatchesView.vue': ['inboundCode', 'customerName', 'containerNo', 'oceanBookingStatus', 'truckAppointmentStatus', 'pickTaskStatus', 'dispatchStatus', 'gate'],
|
||||
}
|
||||
for (const [relative, fields] of Object.entries(expectations)) {
|
||||
@@ -73,7 +70,8 @@ test('正式 DTO/OpenAPI 暴露矩阵使用的稳定字段', () => {
|
||||
['firstleg/src/main/java/com/baiyue/firstleg/oceanbooking/dto/OceanBookingDtos.java', ['record Detail', 'record RealContainer', 'bookingAgentName', 'estimatedSailingAt', 'estimatedArrivalAt']],
|
||||
['firstleg/src/main/java/com/baiyue/firstleg/portschedule/dto/PortScheduleDtos.java', ['record ScheduleView', 'sourceName', 'etdAt', 'etaAt', 'expiresAt']],
|
||||
['firstleg/src/main/java/com/baiyue/firstleg/entity/TruckAppointmentEntity.java', ['appointmentNo', 'carrierName', 'plannedLoadingAt', 'containerNo']],
|
||||
['firstleg/src/main/java/com/baiyue/firstleg/customs/entity/CustomsCaseEntity.java', ['customsNo', 'checklistCode', 'checklistVersionNo', 'updatedAt']],
|
||||
['firstleg/src/main/java/com/baiyue/firstleg/customs/container/dto/ContainerCustomsDtos.java', ['record ContainerView', 'aggregateId', 'loadingPlanId', 'containerBookingId', 'planNo', 'cabinetNo', 'merchantStatus', 'coveredTaxRefundCount', 'documents']],
|
||||
['firstleg/src/main/resources/openapi/customs-v1.yaml', ['ContainerView:', 'WAITING_CUSTOMER_DOCUMENTS', 'READY_TO_START', 'DECLARING', 'COMPLETED']],
|
||||
['firstleg/src/main/java/com/baiyue/firstleg/outbound/dispatch/dto/OutboundDispatchDtos.java', ['record Aggregate', 'customerName', 'pickTaskStatus', 'dispatchStatus', 'GateResult']],
|
||||
]
|
||||
for (const [relative, fields] of sources) {
|
||||
@@ -89,14 +87,13 @@ test('字段校验器接受正式完整投影并精确暴露缺字段', () => {
|
||||
[loadingListFieldGaps, { planId: ids.plan, containerBookingId: ids.container, loadingListNo: 'LL-1', containerNo: 'MSCU1234567', cabinetNo: 'CAB-1', warehouseName: '宁波仓', status: 'COMPLETED', totalPackageCount: 1, totalGrossWeightKg: 10, totalNetWeightKg: 9, totalVolumeCbm: 1, totalQuantity: 2, createdAt: at }, undefined, 'containerNo'],
|
||||
[oceanBookingFieldGaps, { id: ids.id, bookingNo: 'BK-1', status: 'RELEASED', vesselName: 'VESSEL', voyageNo: 'V1', estimatedSailingAt: at, estimatedArrivalAt: at, customerId: ids.id, customerName: '测试客户', shippingCompanyId: null, shippingCompanyName: null, bookingAgentId: ids.id, bookingAgentName: '代理' }, undefined, 'voyageNo'],
|
||||
[portScheduleFieldGaps, { portSchedule: { schedule: { id: ids.id, scheduleNo: 'PS-1', sourceName: '船公司', vesselName: 'VESSEL', voyageNo: 'V1', departurePortCode: 'CNNGB', destinationPortCode: 'USLAX', etdAt: at, etaAt: at, observedAt: at, updatedAt: at, expiresAt: at }, expired: false } }, undefined, 'sourceName'],
|
||||
[truckAppointmentFieldGaps, { id: ids.id, appointmentNo: 'TA-1', oceanBookingId: ids.id, containerBookingId: ids.container, loadingPlanId: ids.plan, warehouseId: ids.id, warehouseName: '宁波仓', carrierId: ids.id, carrierName: '拖车商', plannedLoadingAt: at, status: 'DRAFT', attachmentCount: 0 }, undefined, 'appointmentNo'],
|
||||
[customsCaseFieldGaps, { customsCase: { id: ids.id, customsNo: 'CUS-1', orderId: ids.order, inboundId: ids.inbound, containerBookingId: ids.container, checklistVersionId: ids.id, checklistCode: 'CHECK', checklistVersionNo: 'V1', status: 'DOCUMENTS_PENDING', updatedAt: at } }, undefined, 'checklistCode'],
|
||||
[truckAppointmentFieldGaps, { id: ids.id, appointmentNo: 'TA-1', oceanBookingId: ids.id, containerBookingId: ids.container, loadingPlanId: ids.plan, warehouseId: ids.id, warehouseName: '宁波仓', carrierId: ids.id, carrierName: '拖车商', payableAmount: 0, currency: 'RMB', plannedLoadingAt: at, status: 'DRAFT', attachmentCount: 0 }, undefined, 'appointmentNo'],
|
||||
[outboundAggregateFieldGaps, { containerBookingId: ids.container, containerNo: 'MSCU1234567', loadingPlanId: ids.plan, loadingPlanStatus: 'COMPLETED', oceanBookingId: ids.id, oceanBookingStatus: 'RELEASED', dispatchStatus: 'READY_FOR_DISPATCH', version: 1, inbounds: [{ orderId: ids.order, inboundId: ids.inbound, inboundCode: 'IN-1', tenantId: ids.id, inboundStatus: 'LOADED', pickTaskId: ids.task, pickTaskStatus: 'COMPLETED' }], gate: { inbounds: [{ inboundId: ids.inbound, inboundCode: 'IN-1', gate: { items: [] } }] } }, undefined, 'containerNo'],
|
||||
]
|
||||
for (const [validator, sample, options, missing] of samples) {
|
||||
assert.deepEqual(validator(sample, options), [])
|
||||
const invalid = structuredClone(sample)
|
||||
const target = invalid.portSchedule?.schedule ?? invalid.customsCase ?? invalid
|
||||
const target = invalid.portSchedule?.schedule ?? invalid
|
||||
target[missing] = ''
|
||||
assert.ok(validator(invalid, options).includes(missing))
|
||||
}
|
||||
@@ -108,7 +105,6 @@ test('字段断言接入正式生产模块和默认全量入口', () => {
|
||||
'ocean-bookings.mjs': ['oceanBookingFieldGaps'],
|
||||
'phase3-port-schedules.mjs': ['portScheduleFieldGaps'],
|
||||
'truck-appointments.mjs': ['truckAppointmentFieldGaps'],
|
||||
'phase3-customs.mjs': ['customsCaseFieldGaps'],
|
||||
'phase3-outbound-dispatch.mjs': ['outboundAggregateFieldGaps'],
|
||||
}
|
||||
for (const [file, tokens] of Object.entries(consumers)) {
|
||||
|
||||
@@ -3,6 +3,11 @@ import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('inbound-measurement.mjs', import.meta.url), 'utf8')
|
||||
const read = (relativeUrl) => readFileSync(new URL(relativeUrl, import.meta.url), 'utf8')
|
||||
const labelTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/InboundCartonLabelServiceTest.java')
|
||||
const measurementTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/InboundMeasurementServiceTest.java')
|
||||
const cartonTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/CartonMeasurementServiceTest.java')
|
||||
const reviewTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/MeasurementReviewServiceTest.java')
|
||||
|
||||
test('measurement acceptance scans the stable box code frozen by first print', () => {
|
||||
assert.match(source, /const boxCode = `\$\{inboundCode\}#\$\{originalPackageCount\}-1`/)
|
||||
@@ -32,3 +37,37 @@ test('measurement fixture derives pallet resources from confirmed image count',
|
||||
test('volume ceiling removes binary floating point noise before scaling', () => {
|
||||
assert.match(source, /Number\.EPSILON \* Math\.max\(1, Math\.abs\(value\)\) \* 4/)
|
||||
})
|
||||
|
||||
test('demo package freezes repeated label printing and Mojia dimension replacement', () => {
|
||||
assert.match(labelTests, /repeatedAndPartialPrintsReadFrozenMappingWithoutReallocation/)
|
||||
assert.match(labelTests, /changedCargoKeepsTheFirstFrozenBoxCodes/)
|
||||
assert.match(cartonTests, /repeatedScanReplacesDeviceValuesButPreservesManualCountAndOldImageIsDeleted/)
|
||||
assert.match(source, /增量 fixture 形成动态真实独立货物测量明细/)
|
||||
})
|
||||
|
||||
test('demo package covers OCR failure, manual confirmation, aggregation and stale versions', () => {
|
||||
assert.match(source, /OCR无有效重量时转人工确认/)
|
||||
assert.match(source, /称重旧版本确认被拒绝且不覆盖已确认结果/)
|
||||
assert.match(source, /图片张数决定托数且净重汇总已落地/)
|
||||
assert.match(measurementTests, /ocrFailureCreatesManualWeightThatCanBeAdjustedAndConfirmed/)
|
||||
assert.match(measurementTests, /confirmingFifthPalletSeparatelyAggregatesGrossAndCargoNetWeight/)
|
||||
assert.match(measurementTests, /confirmingWithStaleVersionDoesNotTreatRequestAsIdempotent/)
|
||||
})
|
||||
|
||||
test('demo package keeps pallet pages bounded and historical snapshots read-only', () => {
|
||||
assert.match(source, /weight-pallet-options[^\n]+page=1&size=20&keyword=/)
|
||||
assert.match(source, /records\.length <= 20/)
|
||||
assert.match(measurementTests, /detailUsesStoredPalletSnapshotAfterCandidateBecomesUnavailable/)
|
||||
})
|
||||
|
||||
test('approval freezes measurement and requires quantity weight and volume conservation', () => {
|
||||
assert.match(source, /审核进入WAIT_SPLIT后箱码尺寸与图片快照不可再覆盖/)
|
||||
assert.match(measurementTests, /approvedMeasurementCannotBeResubmittedOrMutateFrozenTotals/)
|
||||
assert.match(reviewTests, /shouldApproveMultipleCargoLinesOnlyWhenAllFrozenTotalsMatch/)
|
||||
assert.match(reviewTests, /shouldRejectApprovalWhenVolumeSnapshotDoesNotConserve/)
|
||||
assert.match(source, /actualPackageCount[^\n]+originalPackageCount/)
|
||||
assert.match(source, /actualGrossWeightKg[^\n]+weightEvidence\.grossWeightKg/)
|
||||
assert.match(source, /actualNetWeightKg[^\n]+weightEvidence\.netWeightKg/)
|
||||
assert.match(source, /actualVolumeCbm[^\n]+totalVolume/)
|
||||
assert.match(source, /volumeWeightKg[^\n]+volumeWeight/)
|
||||
})
|
||||
|
||||
@@ -84,7 +84,7 @@ async function waitForCompletedMeasurement(context, measurementPath, attempts =
|
||||
return { response, measurement, attempts }
|
||||
}
|
||||
|
||||
async function provisionWarehouseResources(context, { inboundId, warehouseId, palletCount }) {
|
||||
async function provisionWarehouseResources(context, { inboundId, tenantId, warehouseId, palletCount }) {
|
||||
if (!warehouseId || !Number.isInteger(palletCount) || palletCount < 1) return null
|
||||
|
||||
const resources = []
|
||||
@@ -92,6 +92,20 @@ async function provisionWarehouseResources(context, { inboundId, warehouseId, pa
|
||||
if (!candidates) return null
|
||||
const palletIds = randomlyReusePalletIds(candidates, palletCount,
|
||||
context.context?.waitSplitVariant?.randomValue)
|
||||
const candidateKeyword = candidates.find((item) => item.id === palletIds[0])?.code || ''
|
||||
const candidateResponse = await context.request('GET',
|
||||
`/api/platform/v1/first-leg/inbounds/${inboundId}/weight-pallet-options?${query(tenantId)}&page=1&size=20&keyword=${encodeURIComponent(candidateKeyword)}`)
|
||||
const candidatePage = context.apiSuccess(MODULE, '按关键词分页查询当前入库仓称重托盘候选', candidateResponse,
|
||||
`warehouseId=${warehouseId}, keyword=${candidateKeyword}`, OPTIONS)
|
||||
const pageControlled = Array.isArray(candidatePage?.records) && candidatePage.records.length <= 20
|
||||
&& Number(candidatePage?.page) === 1 && Number(candidatePage?.size) === 20
|
||||
&& Number(candidatePage?.total) >= candidatePage.records.length
|
||||
&& candidatePage.records.some((item) => asId(item?.palletId) === palletIds[0])
|
||||
context.assert(MODULE, '托盘候选保持服务端关键词分页且不返回无界数组', candidateResponse,
|
||||
pageControlled,
|
||||
`records=${candidatePage?.records?.length ?? 'missing'}, page=${candidatePage?.page ?? 'missing'}, size=${candidatePage?.size ?? 'missing'}, total=${candidatePage?.total ?? 'missing'}`,
|
||||
OPTIONS)
|
||||
if (!pageControlled) return null
|
||||
for (let index = 1; index <= palletCount; index += 1) {
|
||||
const palletId = palletIds[index - 1]
|
||||
context.assert(MODULE, `随机复用原有称重托盘 ${index}/${palletCount}`, null,
|
||||
@@ -134,6 +148,10 @@ async function createConfirmedWeightEvidence(context, {
|
||||
const created = context.apiSuccess(MODULE, `登记称重图片与托盘快照 ${index + 1}/${palletIds.length}`,
|
||||
createResponse, `fileId=${fileId}, palletId=${palletId}`, OPTIONS)
|
||||
if (!created?.id) return null
|
||||
context.assert(MODULE, `OCR无有效重量时转人工确认 ${index + 1}/${palletIds.length}`, createResponse,
|
||||
created.recognitionStatus === 'NEEDS_MANUAL' && created.ocrWeightValue == null,
|
||||
`recognitionStatus=${created.recognitionStatus || 'missing'}, ocrWeightValue=${created.ocrWeightValue ?? 'null'}`,
|
||||
OPTIONS)
|
||||
|
||||
const grossWeight = Number(grossWeightPerPalletKg) + index * 5
|
||||
const confirmResponse = await context.request('POST',
|
||||
@@ -148,6 +166,16 @@ async function createConfirmedWeightEvidence(context, {
|
||||
if (confirmed?.recognitionStatus !== 'CONFIRMED' || !Number.isFinite(netWeightKg) || netWeightKg <= 0) {
|
||||
return null
|
||||
}
|
||||
const staleConfirmResponse = await context.request('POST',
|
||||
`/api/platform/v1/first-leg/inbounds/${inboundId}/weight-results/${created.id}/confirm?${query(tenantId)}`, {
|
||||
version: Number(created.version), adjustedWeightValue: grossWeight + 1,
|
||||
adjustedWeightUnit: 'KG', adjustmentReason: `${context.marker} 旧版本冲突验证`,
|
||||
})
|
||||
context.assert(MODULE, `称重旧版本确认被拒绝且不覆盖已确认结果 ${index + 1}/${palletIds.length}`,
|
||||
staleConfirmResponse,
|
||||
staleConfirmResponse.http === 200 && String(staleConfirmResponse.body?.code) === 'A0409',
|
||||
`HTTP=${staleConfirmResponse.http}, code=${staleConfirmResponse.body?.code ?? 'missing'}, requestId=${staleConfirmResponse.requestId || 'missing'}`,
|
||||
OPTIONS)
|
||||
confirmedResults.push({ id: asId(created.id), palletId, netWeightKg, grossWeightKg })
|
||||
}
|
||||
|
||||
@@ -161,7 +189,9 @@ async function createConfirmedWeightEvidence(context, {
|
||||
const netWeightKg = confirmedResults.reduce((sum, result) => sum + result.netWeightKg, 0)
|
||||
const persisted = confirmedRows.length === palletIds.length
|
||||
&& confirmedResults.every((expected) => confirmedRows.some((row) =>
|
||||
asId(row?.id) === expected.id && asId(row?.palletId) === expected.palletId))
|
||||
asId(row?.id) === expected.id && asId(row?.palletId) === expected.palletId
|
||||
&& String(row?.palletCode || '').trim() && String(row?.palletType || '').trim()
|
||||
&& Number.isFinite(Number(row?.palletTareWeightKg))))
|
||||
&& closeTo(workspace?.actualGrossWeightKg, grossWeightKg, 0.001)
|
||||
&& closeTo(workspace?.actualNetWeightKg, netWeightKg, 0.001)
|
||||
context.assert(MODULE, '图片张数决定托数且净重汇总已落地', workspaceResponse, persisted,
|
||||
@@ -533,7 +563,7 @@ export async function run(context) {
|
||||
|
||||
const palletCount = Math.max(1, Number(context.context?.waitSplitVariant?.palletCount || 1))
|
||||
const warehouseResourcesReady = await provisionWarehouseResources(context, {
|
||||
inboundId, warehouseId: asId(summary?.warehouseId), palletCount,
|
||||
inboundId, tenantId, warehouseId: asId(summary?.warehouseId), palletCount,
|
||||
})
|
||||
context.assert(MODULE, '测量提交前按称重图片数准备真实库位', draftResponse,
|
||||
Boolean(warehouseResourcesReady),
|
||||
@@ -606,6 +636,15 @@ export async function run(context) {
|
||||
&& closeTo(finalMeasurement?.volumeWeightKg, volumeWeight),
|
||||
`processStatus=${finalMeasurement?.processStatus ?? 'missing'}, measurementStatus=${finalMeasurement?.measurementStatus ?? 'missing'}, packages=${finalMeasurement?.actualPackageCount ?? 'missing'}, pallets=${weightEvidence.count}, grossWeight=${finalMeasurement?.actualGrossWeightKg ?? 'missing'}, netWeight=${finalMeasurement?.actualNetWeightKg ?? 'missing'}`, OPTIONS)
|
||||
|
||||
const approvedScanResponse = await multipartRequest(context, scanPath, {
|
||||
boxCode, ...replacement, machineNo: 'MJ-ADMIN-E2E-AFTER-APPROVAL',
|
||||
measuredAt: new Date().toISOString().slice(0, 19),
|
||||
})
|
||||
context.assert(MODULE, '审核进入WAIT_SPLIT后箱码尺寸与图片快照不可再覆盖', approvedScanResponse,
|
||||
approvedScanResponse.http === 200 && String(approvedScanResponse.body?.code) === 'A0409',
|
||||
`HTTP=${approvedScanResponse.http}, code=${approvedScanResponse.body?.code ?? 'missing'}, requestId=${approvedScanResponse.requestId || 'missing'}`,
|
||||
OPTIONS)
|
||||
|
||||
context.createdResources.inboundMeasurement = {
|
||||
marker: context.marker, tenantId, inboundId, measurementId: asId(draft.measurementId),
|
||||
boxCode, finalStatus: finalMeasurement?.measurementStatus || null,
|
||||
|
||||
@@ -8,7 +8,7 @@ const measurement = readFileSync(new URL('./inbound-measurement.mjs', import.met
|
||||
const runner = readFileSync(new URL('../it-test-wait-split-bulk.mjs', import.meta.url), 'utf8')
|
||||
const warehouseLocationResources = readFileSync(new URL('../../warehouse/src/main/java/com/baiyue/warehouse/service/LocationResourceService.java', import.meta.url), 'utf8')
|
||||
|
||||
test('单票随机箱数严格分配到各 SKU 并限制为1到1000', () => {
|
||||
test('Admin 通用单票支持到1000箱且八千票专项入口限制为300箱', () => {
|
||||
assert.match(acceptance, /--wait-split-package-count <n>/)
|
||||
assert.match(acceptance, /wait-split-package-count必须是1-1000的整数或0/)
|
||||
assert.match(acceptance, /packageCounts\.push\(remaining\)/)
|
||||
@@ -16,6 +16,7 @@ test('单票随机箱数严格分配到各 SKU 并限制为1到1000', () => {
|
||||
assert.match(orders, /packageCounts\[index\] \|\| packageCountPerSku/)
|
||||
assert.match(measurement, /detailPackageCounts\.reduce\(\(sum, count\) => sum \+ count, 0\)/)
|
||||
assert.match(measurement, /detailPackageCounts\.slice\(0, detailIndex\)/)
|
||||
assert.match(runner, /boxMax > 300/)
|
||||
})
|
||||
|
||||
test('随机线路只固定义乌仓并从客户真实可计价候选选择', () => {
|
||||
|
||||
@@ -42,7 +42,11 @@ test('backend never appends a generic STATUS_UPDATE and push replay is read-only
|
||||
assert.doesNotMatch(serviceSources, /(?:history|appendHistory)\([^;]{0,500}"STATUS_UPDATE"/s)
|
||||
assert.match(smartLoading, /if \(key\.equals\(plan\.getPushIdempotencyKey\(\)\)\)[\s\S]{0,300}return view\(plan, booking\)/)
|
||||
assert.match(smartLoading, /history\(planId, null, "PUSH_PRELOAD"/)
|
||||
assert.match(smartLoadingTest, /exactPushReplayIsReadOnly[\s\S]{0,1000}never\(\)\.insert/)
|
||||
const replayStart = smartLoadingTest.indexOf('void exactPushReplayIsReadOnly()')
|
||||
const replayEnd = smartLoadingTest.indexOf('@Test', replayStart + 10)
|
||||
const replayBlock = smartLoadingTest.slice(replayStart, replayEnd)
|
||||
assert.notEqual(replayStart, -1)
|
||||
assert.match(replayBlock, /never\(\)\)\.insert/)
|
||||
assert.match(smartLoadingTest, /getActionType\(\)\)\.isEqualTo\("PUSH_PRELOAD"\)/)
|
||||
})
|
||||
|
||||
@@ -50,7 +54,7 @@ test('operationId is projected end-to-end for identity-based frontend deduplicat
|
||||
assert.match(loadingDtos, /record History\([\s\S]{0,180}String operationId/)
|
||||
assert.match(loadingRepository, /new History\([\s\S]{0,180}getOperationId\(\)/)
|
||||
assert.match(openapi, /OperationHistory:[\s\S]{0,500}operationId:/)
|
||||
assert.match(adminApi, /interface LoadingHistory[\s\S]{0,260}operationId:\s*string/)
|
||||
assert.match(adminApi, /interface LoadingHistory[\s\S]*?operationId:\s*string/)
|
||||
assert.match(adminApi, /normalizeHistory[\s\S]{0,260}operationId:/)
|
||||
})
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ function truckPayload(context, oceanBooking, carrier, index) {
|
||||
storeAddress: '深圳市南山区人工验收地址', storeCity: '深圳市', storeZipcode: '518000',
|
||||
packageCount: 10, grossWeightKg: 100, volumeCbm: 2.5, palletCount: 1, poNo: `PO-${value}`,
|
||||
plannedLoadingAt: '2026-09-16T08:00:00', transitMinutes: 120, payableAmount: 100,
|
||||
receivableAmount: 150, currency: 'RMB', remark: `${context.marker} 人工列表状态 ${index}`, expectedVersion: 0 }
|
||||
currency: 'RMB', remark: `${context.marker} 人工列表状态 ${index}`, expectedVersion: 0 }
|
||||
}
|
||||
|
||||
async function createTruck(context, oceanBooking, index) {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
import { orderPersistenceFacts, requestedOrderDestinationType } from './orders.mjs'
|
||||
|
||||
const source = readFileSync(new URL('orders.mjs', import.meta.url), 'utf8')
|
||||
|
||||
test('order demo payload covers multi-box multi-SKU images and both destination families', () => {
|
||||
for (const boxType of ['SMALL', 'MEDIUM', 'LARGE', 'EXTRA_LARGE']) {
|
||||
assert.match(source, new RegExp(`boxType: '${boxType}'`))
|
||||
}
|
||||
assert.match(source, /cargoes: selectedBoxes\.map/)
|
||||
assert.match(source, /productImageFileId/)
|
||||
assert.equal(requestedOrderDestinationType({ context: { orderDestinationType: 'FBA' } }), 'FBA')
|
||||
assert.equal(requestedOrderDestinationType({ context: { orderDestinationType: 'OVERSEAS' } }), 'OVERSEAS')
|
||||
})
|
||||
|
||||
test('create and submit lifecycle covers replay payload conflict and zero drift', () => {
|
||||
assert.match(source, /Client 创建订单幂等重放/)
|
||||
assert.match(source, /Client 创建订单同键异载荷返回A0409/)
|
||||
assert.match(source, /创建同键异载荷失败后订单全事实零漂移/)
|
||||
assert.match(source, /Client 提交订单同键同载荷精确重放/)
|
||||
assert.match(source, /已提交订单使用新键重复提交返回A0409/)
|
||||
assert.match(source, /重复提交失败后订单状态货物与历史零漂移/)
|
||||
assert.match(source, /orderPersistenceFacts\(draftAfterConflict\) === orderPersistenceFacts\(draft\)/)
|
||||
assert.match(source, /orderPersistenceFacts\(submittedAfterFailure\) === orderPersistenceFacts\(submitted\)/)
|
||||
})
|
||||
|
||||
test('persistence fact comparison includes order cargo parties notes and history', () => {
|
||||
const detail = {
|
||||
order: { id: '1', status: 'DRAFT' }, cargoes: [{ skuNo: 'SKU-1' }],
|
||||
parties: [{ role: 'SENDER' }], internalNotes: [{ content: 'note' }],
|
||||
statusHistory: [{ toStatus: 'DRAFT' }],
|
||||
}
|
||||
const baseline = orderPersistenceFacts(detail)
|
||||
assert.equal(orderPersistenceFacts(structuredClone(detail)), baseline)
|
||||
assert.notEqual(orderPersistenceFacts({ ...detail, order: { ...detail.order, status: 'SUBMITTED' } }), baseline)
|
||||
assert.notEqual(orderPersistenceFacts({ ...detail, cargoes: [{ skuNo: 'SKU-2' }] }), baseline)
|
||||
assert.notEqual(orderPersistenceFacts({ ...detail, statusHistory: [...detail.statusHistory, { toStatus: 'SUBMITTED' }] }), baseline)
|
||||
})
|
||||
|
||||
test('approval convergence is a hard WAIT_MEASURE prerequisite without coverage downgrade', () => {
|
||||
assert.match(source, /审核后入库单与履约任务异步收敛/)
|
||||
assert.match(source, /MEASURABLE_STATUSES/)
|
||||
assert.match(source, /throw new Error\('订单审核后的入库单与履约任务未在30秒内收敛/)
|
||||
assert.doesNotMatch(source, /审核后入库单与履约任务异步收敛[\s\S]{0,300}addCoverageGap/)
|
||||
})
|
||||
@@ -25,6 +25,15 @@ function rotate(values, offset) {
|
||||
return [...values.slice(shift), ...values.slice(0, shift)]
|
||||
}
|
||||
function key(context, operation) { return `${context.marker}-${operation}`.slice(0, 128) }
|
||||
export function orderPersistenceFacts(detail) {
|
||||
return JSON.stringify({
|
||||
order: detail?.order ?? null,
|
||||
cargoes: Array.isArray(detail?.cargoes) ? detail.cargoes : [],
|
||||
parties: Array.isArray(detail?.parties) ? detail.parties : [],
|
||||
internalNotes: Array.isArray(detail?.internalNotes) ? detail.internalNotes : [],
|
||||
statusHistory: Array.isArray(detail?.statusHistory) ? detail.statusHistory : [],
|
||||
})
|
||||
}
|
||||
export function requestedOrderDestinationType(context) {
|
||||
const value = String(context?.context?.orderDestinationType || 'FBA').trim().toUpperCase()
|
||||
return ['FBA', 'OVERSEAS', 'PRIVATE'].includes(value) ? value : 'FBA'
|
||||
@@ -547,13 +556,41 @@ export async function run(context) {
|
||||
assertCargoContract(context, draftResponse, draft?.cargoes, payload)
|
||||
context.createdResources.orders.orderNo = orderNo
|
||||
|
||||
const createConflictPayload = {
|
||||
...payload,
|
||||
customerRemark: `${payload.customerRemark} 同键异载荷`,
|
||||
}
|
||||
const createConflictResponse = await request(context, 'POST', createPath, createConflictPayload, merchantToken,
|
||||
{ 'Idempotency-Key': key(context, 'client-create') })
|
||||
context.assert(MODULE, 'Client 创建订单同键异载荷返回A0409', createConflictResponse,
|
||||
createConflictResponse.http === 200 && String(createConflictResponse.body?.code) === 'A0409',
|
||||
`http=${createConflictResponse.http}, code=${createConflictResponse.body?.code ?? 'missing'}`, CONTRACT_OPTIONS)
|
||||
const draftAfterConflictResponse = await request(context, 'GET', clientDetailPath, undefined, merchantToken)
|
||||
const draftAfterConflict = context.apiSuccess(MODULE, 'Client 回查创建冲突后的订单草稿', draftAfterConflictResponse)
|
||||
context.assert(MODULE, '创建同键异载荷失败后订单全事实零漂移', draftAfterConflictResponse,
|
||||
orderPersistenceFacts(draftAfterConflict) === orderPersistenceFacts(draft),
|
||||
`orderId=${orderId}, status=${draftAfterConflict?.order?.status ?? 'missing'}`, CONTRACT_OPTIONS)
|
||||
|
||||
const submitResponse = await request(context, 'POST', `${clientDetailPath}/submit`, undefined,
|
||||
merchantToken, { 'Idempotency-Key': key(context, 'client-submit') })
|
||||
context.apiSuccess(MODULE, 'Client 提交隔离订单', submitResponse, `orderId=${orderId}`)
|
||||
const submitReplayResponse = await request(context, 'POST', `${clientDetailPath}/submit`, undefined,
|
||||
merchantToken, { 'Idempotency-Key': key(context, 'client-submit') })
|
||||
context.apiSuccess(MODULE, 'Client 提交订单同键同载荷精确重放', submitReplayResponse, `orderId=${orderId}`)
|
||||
const submittedResponse = await request(context, 'GET', clientDetailPath, undefined, merchantToken)
|
||||
const submitted = context.apiSuccess(MODULE, 'Client 回查已提交订单', submittedResponse)
|
||||
context.assert(MODULE, 'Client 订单已进入待审核状态', submittedResponse,
|
||||
submitted?.order?.status === 'SUBMITTED', `status=${submitted?.order?.status ?? 'missing'}`)
|
||||
const duplicateSubmitResponse = await request(context, 'POST', `${clientDetailPath}/submit`, undefined,
|
||||
merchantToken, { 'Idempotency-Key': key(context, 'client-submit-new-key') })
|
||||
context.assert(MODULE, '已提交订单使用新键重复提交返回A0409', duplicateSubmitResponse,
|
||||
duplicateSubmitResponse.http === 200 && String(duplicateSubmitResponse.body?.code) === 'A0409',
|
||||
`http=${duplicateSubmitResponse.http}, code=${duplicateSubmitResponse.body?.code ?? 'missing'}`, CONTRACT_OPTIONS)
|
||||
const submittedAfterFailureResponse = await request(context, 'GET', clientDetailPath, undefined, merchantToken)
|
||||
const submittedAfterFailure = context.apiSuccess(MODULE, 'Client 回查重复提交失败后的订单', submittedAfterFailureResponse)
|
||||
context.assert(MODULE, '重复提交失败后订单状态货物与历史零漂移', submittedAfterFailureResponse,
|
||||
orderPersistenceFacts(submittedAfterFailure) === orderPersistenceFacts(submitted),
|
||||
`orderId=${orderId}, status=${submittedAfterFailure?.order?.status ?? 'missing'}`, CONTRACT_OPTIONS)
|
||||
|
||||
const unifiedListResponse = await context.request('GET',
|
||||
`/api/platform/v1/orders?page=1&size=100&tenantId=${encodeURIComponent(tenantId)}&orderNo=${encodeURIComponent(orderNo)}`)
|
||||
|
||||
+20
-17
@@ -8,6 +8,7 @@ const loadingPickService = read('../../firstleg/src/main/java/com/baiyue/firstle
|
||||
const completionCommand = read('../../firstleg/src/main/java/com/baiyue/firstleg/entity/LoadingCompletionCommandEntity.java')
|
||||
const completionWorker = read('../../firstleg/src/main/java/com/baiyue/firstleg/service/LoadingCompletionWorker.java')
|
||||
const loadingPickTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/LoadingPickServiceTest.java')
|
||||
const completionWorkerTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/LoadingCompletionWorkerTest.java')
|
||||
const settlementTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/PdaPickSettlementServiceTest.java')
|
||||
const unifiedSql = read('../../deploy/sql/头程数据库统一增量-MySQL8.sql')
|
||||
const finalizeHttp = read('phase3-loading-finalize.mjs')
|
||||
@@ -15,8 +16,6 @@ const pdaPage = read('../../../apps/pda-uniapp/pages/picking/picking.vue')
|
||||
const pdaCompletionState = read('../../../apps/pda-uniapp/utils/loading-completion-state.js')
|
||||
const pdaCompletionTests = read('../../../apps/pda-uniapp/tests/loading-completion-state.test.mjs')
|
||||
|
||||
const RECOVERY_TASK_ID = '2092817774453780481'
|
||||
|
||||
function retryDecision({ operationStatus, sameRequest, finalTaskStatus }) {
|
||||
if (!sameRequest) return 'CONFLICT'
|
||||
if (operationStatus === 'PROCESSING') return 'PROCESSING'
|
||||
@@ -74,7 +73,8 @@ test('durable worker processes inbound settlements incrementally with retry back
|
||||
assert.match(completionWorker, /15L <<|nextRetryAt|retryAt/)
|
||||
assert.match(completionWorker, /"FAILED"\s*:\s*"RETRYABLE"/)
|
||||
assert.match(loadingPickService, /checkpointAtLeast[\s\S]{0,1800}SETTLED/)
|
||||
assert.match(loadingPickTests, /(?:transient|瞬时)[\s\S]{0,1500}(?:backoff|retry|退避)/i)
|
||||
assert.match(completionWorkerTests, /transientFailureIsReleasedForBackoffRetry/)
|
||||
assert.match(completionWorkerTests, /"RETRYABLE"/)
|
||||
assert.match(loadingPickTests, /FAILED[\s\S]{0,1500}(?:same operationId|同operationId|resume|恢复)/i)
|
||||
})
|
||||
|
||||
@@ -89,27 +89,30 @@ test('a different operationId is rejected while the completion command is proces
|
||||
})
|
||||
|
||||
test('fifteen completed Warehouse settlements can be reconciled after Firstleg rollback', () => {
|
||||
assert.match(settlementTests, /15|fifteen/i)
|
||||
assert.match(settlementTests, /(?:partial success|部分成功|local rollback|本地回滚)/i)
|
||||
assert.match(settlementTests, /(?:settlementTarget|COMPLETED|replaySettlement)/)
|
||||
assert.match(loadingPickTests, /(?:resume|recover|reconcile|恢复|核平)[\s\S]{0,2000}COMPLETE_LOADING/i)
|
||||
assert.match(loadingPickTests, /workerProcessesFifteenInboundOwnersInStableOrderAndFinalizesOnce/)
|
||||
assert.match(loadingPickTests, /IntStream\.range\(0, 15\)/)
|
||||
assert.match(settlementTests, /reusesWarehouseSettlementTargetWhenRetryingAfterLocalRollback/)
|
||||
assert.match(settlementTests, /warehouse\.settlementTarget\("internal-token", 31L, "PDA-SETTLE-1-31"\)/)
|
||||
assert.match(settlementTests, /targetBusinessId\(\) == 999L/)
|
||||
assert.match(loadingPickTests, /workerRestartResumesFromOwnerCheckpointsWithoutRepeatingSettlements/)
|
||||
})
|
||||
|
||||
test('recovery fixture preserves the observed fifteen-settlement partial success', () => {
|
||||
assert.equal(RECOVERY_TASK_ID, '2092817774453780481')
|
||||
assert.match(finalizeHttp, new RegExp(RECOVERY_TASK_ID))
|
||||
assert.match(finalizeHttp, /15[\s\S]{0,600}(?:Warehouse|settlement)/i)
|
||||
assert.match(finalizeHttp, /(?:LOADING|v1)[\s\S]{0,600}(?:恢复|recovery|resume)/i)
|
||||
test('recovery contract is fixture-independent and uses durable checkpoints', () => {
|
||||
assert.doesNotMatch(finalizeHttp, /2092817774453780481/)
|
||||
assert.match(loadingPickService, /checkpointAtLeast\(checkpoint, "SETTLED"\)/)
|
||||
assert.match(loadingPickService, /checkpointAtLeast\(checkpoint, "INBOUND_COMPLETED"\)/)
|
||||
assert.match(loadingPickTests, /workerRestartResumesFromOwnerCheckpointsWithoutRepeatingSettlements/)
|
||||
})
|
||||
|
||||
test('final acceptance reconciles task allocation reservation occupancy and one completion audit', () => {
|
||||
for (const fact of ['task', 'allocation', 'reservation', 'occupancy']) {
|
||||
test('final acceptance reconciles terminal task and one completion audit after owner checkpoints', () => {
|
||||
for (const fact of ['task', 'plan', 'inbound', 'operation']) {
|
||||
assert.match(finalizeHttp, new RegExp(fact, 'i'), `missing final ${fact} reconciliation`)
|
||||
}
|
||||
assert.match(finalizeHttp, /COMPLETE_LOADING/)
|
||||
assert.match(finalizeHttp, /(?:length === 1|恰有一次|只写一条)/)
|
||||
assert.match(finalizeHttp, /(?:PROCESSING|处理中)/)
|
||||
assert.match(finalizeHttp, /(?:elapsed|latency|耗时|毫秒|ms)/i)
|
||||
assert.match(finalizeHttp, /concurrentCompleteOperations\.length === 1/)
|
||||
assert.match(finalizeHttp, /异步完成命令收敛到终态/)
|
||||
assert.match(loadingPickService, /completionTransaction\.executeWithoutResult/)
|
||||
assert.match(loadingPickService, /private void finalizeCompletion/)
|
||||
})
|
||||
|
||||
test('PDA treats accepted completion as processing, returns to list, and never claims completion early', () => {
|
||||
|
||||
+9
-2
@@ -11,6 +11,7 @@ const locationTests = read('../../warehouse/src/test/java/com/baiyue/warehouse/s
|
||||
const settlementService = read('../../warehouse/src/main/java/com/baiyue/warehouse/service/PalletLocationAllocationService.java')
|
||||
const settlementTests = read('../../warehouse/src/test/java/com/baiyue/warehouse/service/PalletLocationAllocationServiceTest.java')
|
||||
const finalizeHttp = read('phase3-loading-finalize.mjs')
|
||||
const loadingPickService = read('../../firstleg/src/main/java/com/baiyue/firstleg/service/LoadingPickService.java')
|
||||
|
||||
function releaseDecision({ sharedOverflow, locationStatus, activeOccupanciesAfterRelease }) {
|
||||
if (sharedOverflow) return 'SHARED_STATUS_UNCHANGED'
|
||||
@@ -63,10 +64,16 @@ test('same settlement key replays without a second release or transfer', () => {
|
||||
assert.match(settlementTests, /verify\(locations,\s*never\(\)\)\.transferToChildByReservation/)
|
||||
})
|
||||
|
||||
test('HTTP failure contract proves task plan allocation location history outbox operation zero drift', () => {
|
||||
for (const fact of ['task', 'plan', 'inbound', 'allocation', 'location', 'history', 'outbox', 'operation']) {
|
||||
test('acceptance failure is zero-write before worker and final local convergence is transactional', () => {
|
||||
for (const fact of ['task', 'plan', 'inbound', 'operation']) {
|
||||
assert.match(finalizeHttp, new RegExp(fact, 'i'), `missing ${fact} failure baseline`)
|
||||
}
|
||||
assert.match(finalizeHttp, /A0409/)
|
||||
assert.match(finalizeHttp, /零写入|零漂移/)
|
||||
assert.match(loadingPickService, /completionTransaction\.executeWithoutResult/)
|
||||
const finalizer = loadingPickService.slice(loadingPickService.indexOf('private void finalizeCompletion'),
|
||||
loadingPickService.indexOf('private void requireColoadConservation'))
|
||||
for (const fact of ['COMPLETE_LOADING', 'finishFromPda', 'publishCompletedEvent', 'completeAccepted']) {
|
||||
assert.match(finalizer, new RegExp(fact), `missing transactional ${fact}`)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { planA0LocationIsolation } from '../admin-test-env-acceptance.mjs'
|
||||
|
||||
function locations(count) {
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
id: String(index + 1), locationCode: `L-${String(index + 1).padStart(4, '0')}`,
|
||||
sharedOverflow: false, version: 0,
|
||||
}))
|
||||
}
|
||||
|
||||
test('large warehouse is never selected for default mass disable', () => {
|
||||
const plan = planA0LocationIsolation(locations(614), 1)
|
||||
assert.equal(plan.enabled, false)
|
||||
assert.equal(plan.mutationsRequired, 614)
|
||||
assert.deepEqual(plan.targets, [])
|
||||
})
|
||||
|
||||
test('minimum mutations leave fewer normal locations than required pallets', () => {
|
||||
const plan = planA0LocationIsolation(locations(3), 3)
|
||||
assert.equal(plan.enabled, true)
|
||||
assert.equal(plan.mutationsRequired, 1)
|
||||
assert.equal(plan.targets.length, 1)
|
||||
assert.equal(plan.expectedRemainingNormal, 2)
|
||||
assert.ok(plan.expectedRemainingNormal < plan.requiredSlots)
|
||||
})
|
||||
|
||||
test('natural shortage proves A0 fallback without any location mutation', () => {
|
||||
const plan = planA0LocationIsolation(locations(1), 2)
|
||||
assert.equal(plan.enabled, true)
|
||||
assert.equal(plan.mutationsRequired, 0)
|
||||
assert.deepEqual(plan.targets, [])
|
||||
assert.ok(plan.normalCount < plan.requiredSlots)
|
||||
})
|
||||
|
||||
test('shared A0 and duplicate rows never inflate the normal location plan', () => {
|
||||
const normal = locations(2)
|
||||
const plan = planA0LocationIsolation([
|
||||
...normal, normal[0], { id: 'A0', locationCode: 'A0', sharedOverflow: true, version: 0 },
|
||||
], 2)
|
||||
assert.equal(plan.normalCount, 2)
|
||||
assert.equal(plan.mutationsRequired, 1)
|
||||
assert.deepEqual(plan.targets.map((item) => item.id), ['1'])
|
||||
})
|
||||
@@ -50,6 +50,18 @@ function blocker(context, name, evidence) {
|
||||
}
|
||||
|
||||
function validLongId(value) { return typeof value === 'string' && /^\d{16,}$/.test(value) }
|
||||
export function validContainerNo(value) {
|
||||
if (typeof value !== 'string' || !/^[A-Z]{3}[UJZ][0-9]{7}$/.test(value)) return false
|
||||
const letterValues = [10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24,
|
||||
25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38]
|
||||
let sum = 0
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
const number = code >= 48 && code <= 57 ? code - 48 : letterValues[code - 65]
|
||||
sum += number * (2 ** index)
|
||||
}
|
||||
return Number(value[10]) === (sum % 11) % 10
|
||||
}
|
||||
|
||||
export async function run(context) {
|
||||
context.addCoverageGap(MODULE, OPTIONS.scenario, 'COSCO官方API自动查询',
|
||||
@@ -84,6 +96,7 @@ export async function run(context) {
|
||||
const task = item?.query
|
||||
return id(task?.customerId) === fixture.customerId && id(task?.oceanBookingId) === fixture.oceanBookingId
|
||||
&& id(task?.containerBookingId) === fixture.containerBookingId && task?.trackingNo === fixture.trackingNo
|
||||
&& task?.trackingType === 'CONTAINER_NO' && validContainerNo(task?.trackingNo)
|
||||
&& task?.triggerSource === 'OUTBOUND_CONFIRM'
|
||||
})
|
||||
context.assert(MODULE, '本轮出仓范围唯一命中CarrierScheduleQuery', pageResponse,
|
||||
@@ -104,6 +117,8 @@ export async function run(context) {
|
||||
&& item.actualAt != null && item.estimatedAt == null)
|
||||
context.assert(MODULE, '出仓自动任务携带实际DEPARTED_WAREHOUSE事实与长ID', detailResponse,
|
||||
id(detail?.query?.query?.id) === queryId && validLongId(detail?.query?.query?.id)
|
||||
&& detail?.query?.query?.trackingType === 'CONTAINER_NO'
|
||||
&& validContainerNo(detail?.query?.query?.trackingNo)
|
||||
&& departed.length >= 1 && departed.every((item) => validLongId(item.id)
|
||||
&& item.providerCode === 'FIRSTLEG' && item.providerEventId && item.providerNodeCode
|
||||
&& typeof item.rawPayloadHash === 'string' && /^[0-9a-f]{64}$/.test(item.rawPayloadHash)),
|
||||
|
||||
@@ -4,21 +4,21 @@ import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { currentOutboundFixture, ownsCarrierQuery } from './phase3-carrier-schedule-queries.mjs'
|
||||
import { currentOutboundFixture, ownsCarrierQuery, validContainerNo } from './phase3-carrier-schedule-queries.mjs'
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||
const source = fs.readFileSync(path.join(here, 'phase3-carrier-schedule-queries.mjs'), 'utf8')
|
||||
|
||||
function context(marker = 'RUN') {
|
||||
return { marker, createdResources: {
|
||||
phase3Loading: { marker, tenantId: '10001', oceanBookingId: '20001', containerBookingId: '30001', containerNo: 'TSTU1234567' },
|
||||
phase3Loading: { marker, tenantId: '10001', oceanBookingId: '20001', containerBookingId: '30001', containerNo: 'ZCSU7881970' },
|
||||
phase3OutboundDispatch: { marker, tenantId: '10001', containerBookingId: '30001', confirmedStatus: 'WAITING_FOR_LOADING' },
|
||||
} }
|
||||
}
|
||||
|
||||
test('outbound fixture requires exact current marker and matching loading/outbound container', () => {
|
||||
assert.deepEqual(currentOutboundFixture(context()), {
|
||||
marker: 'RUN', customerId: '10001', oceanBookingId: '20001', containerBookingId: '30001', trackingNo: 'TSTU1234567',
|
||||
marker: 'RUN', customerId: '10001', oceanBookingId: '20001', containerBookingId: '30001', trackingNo: 'ZCSU7881970',
|
||||
})
|
||||
const old = context(); old.createdResources.phase3OutboundDispatch.marker = 'OLD'
|
||||
assert.equal(currentOutboundFixture(old), null)
|
||||
@@ -26,6 +26,13 @@ test('outbound fixture requires exact current marker and matching loading/outbou
|
||||
assert.equal(currentOutboundFixture(mismatch), null)
|
||||
})
|
||||
|
||||
test('carrier fixture only accepts normalized ISO 6346 physical container numbers', () => {
|
||||
assert.equal(validContainerNo('ZCSU7881970'), true)
|
||||
assert.equal(validContainerNo('zcsu7881970'), false)
|
||||
assert.equal(validContainerNo('ZCSU7881971'), false)
|
||||
assert.equal(validContainerNo('CAB-260901-0001'), false)
|
||||
})
|
||||
|
||||
test('carrier query ownership requires explicit outbound-confirm marker registration', () => {
|
||||
assert.equal(ownsCarrierQuery({ queryId: '1', marker: 'RUN', ownedByModule: true,
|
||||
triggerSource: 'OUTBOUND_CONFIRM' }, 'RUN'), true)
|
||||
@@ -41,6 +48,8 @@ test('phase3 script only discovers the current outbound task and blocks missing
|
||||
assert.match(source, /缺少本轮phase3出仓fixture,禁止借历史Query验收/)
|
||||
assert.match(source, /deploymentBlocker:\s*true/)
|
||||
assert.match(source, /triggerSource === 'OUTBOUND_CONFIRM'/)
|
||||
assert.match(source, /trackingType === 'CONTAINER_NO'/)
|
||||
assert.match(source, /validContainerNo\(task\?\.trackingNo\)/)
|
||||
assert.match(source, /DEPARTED_WAREHOUSE/)
|
||||
assert.match(source, /providerEventId/)
|
||||
assert.match(source, /\^\\d\{16,/)
|
||||
|
||||
@@ -22,6 +22,21 @@ function failure(response) {
|
||||
}
|
||||
function records(page) { return Array.isArray(page?.records) ? page.records : [] }
|
||||
|
||||
async function waitForCompletedTask(context, taskId, warehouseId, attempts = 45) {
|
||||
let response = null
|
||||
let task = null
|
||||
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
||||
response = await context.request('GET',
|
||||
`${PDA}/tasks/${taskId}?warehouseId=${encodeURIComponent(warehouseId)}`)
|
||||
task = response?.http === 200 && codeOf(response) === '200' ? response.body?.data : null
|
||||
if (task?.taskStatus === 'COMPLETED' && task?.workflowStatus === 'COMPLETED') {
|
||||
return { response, task, attempts: attempt }
|
||||
}
|
||||
if (attempt < attempts) await new Promise((resolve) => setTimeout(resolve, 1_000))
|
||||
}
|
||||
return { response, task, attempts }
|
||||
}
|
||||
|
||||
async function request(context, method, path, body, headers = {}) {
|
||||
try {
|
||||
const response = await fetch(`${context.options.gateway}${path}`, {
|
||||
@@ -43,15 +58,21 @@ async function request(context, method, path, body, headers = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadLoadingEvidence(context, tenantId, inboundId, evidenceType) {
|
||||
const path = `/api/platform/v1/files/loading-evidence/${tenantId}/${inboundId}?evidenceType=${encodeURIComponent(evidenceType)}`
|
||||
async function uploadLoadingEvidence(context, taskId, warehouseId, evidenceType, sealNo) {
|
||||
const path = `${PDA}/tasks/${taskId}/evidence`
|
||||
const form = new FormData()
|
||||
const png = Uint8Array.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,6,0,0,0,31,21,196,137,0,0,0,13,73,68,65,84,8,215,99,248,207,192,240,31,0,5,0,1,255,137,153,61,29,0,0,0,0,73,69,78,68,174,66,96,130])
|
||||
form.append('warehouseId', String(warehouseId))
|
||||
form.append('expectedVersion', '0')
|
||||
form.append('evidenceType', evidenceType)
|
||||
if (evidenceType === 'SEAL') form.append('sealNo', sealNo)
|
||||
form.append('remark', context.marker)
|
||||
form.append('file', new Blob([png], { type: 'image/png' }), `${context.marker}-${evidenceType.toLowerCase()}.png`)
|
||||
try {
|
||||
const response = await fetch(`${context.options.gateway}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', Authorization: `Bearer ${context.token}` },
|
||||
headers: { Accept: 'application/json', Authorization: `Bearer ${context.token}`,
|
||||
'Idempotency-Key': `${context.marker}-cab-evidence-${evidenceType}`.slice(0, 128) },
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
})
|
||||
@@ -66,14 +87,6 @@ async function uploadLoadingEvidence(context, tenantId, inboundId, evidenceType)
|
||||
}
|
||||
}
|
||||
|
||||
async function bindLoadingEvidence(context, inboundId, tenantId, evidenceType, fileId, sealNo) {
|
||||
return request(context, 'POST',
|
||||
`/api/platform/v1/inbounds/${inboundId}/loading/evidence?tenantId=${encodeURIComponent(tenantId)}`,
|
||||
{ expectedVersion: 0, evidenceType, fileId, fileName: 'client-must-not-override.png',
|
||||
sealNo: evidenceType === 'SEAL' ? sealNo : null, remark: context.marker },
|
||||
{ 'Idempotency-Key': `${context.marker}-cab-evidence-${evidenceType}`.slice(0, 128) })
|
||||
}
|
||||
|
||||
export function selectContainerLoadingFixture(context) {
|
||||
const candidates = [
|
||||
context.createdResources?.orchestrationFixtures?.phase3Container,
|
||||
@@ -721,30 +734,22 @@ export async function run(context) {
|
||||
const evidenceTypes = ['PHOTO_STEP_1', 'PHOTO_STEP_2', 'PHOTO_STEP_3', 'PHOTO_STEP_4', 'SEAL']
|
||||
const sealNo = `SEAL-${suffix}`.slice(0, 64)
|
||||
for (const evidenceType of evidenceTypes) {
|
||||
const uploadResponse = await uploadLoadingEvidence(context, tenantId, inboundId, evidenceType)
|
||||
const uploaded = context.apiSuccess(MODULE, `上传柜次 ${evidenceType} 真实证据文件`, uploadResponse,
|
||||
const uploadResponse = await uploadLoadingEvidence(context, taskId, warehouseId, evidenceType, sealNo)
|
||||
const bound = context.apiSuccess(MODULE, `上传并绑定柜次 ${evidenceType} 真实证据文件`, uploadResponse,
|
||||
responseEvidence(uploadResponse), OPTIONS)
|
||||
const fileId = id(uploaded?.fileId)
|
||||
context.assert(MODULE, `${evidenceType} 文件类型、归属和二进制元数据完整`, uploadResponse,
|
||||
Boolean(fileId) && uploaded?.businessType === `LOADING_${evidenceType}`
|
||||
&& uploaded?.contentType === 'image/png' && Number(uploaded?.sizeBytes) > 0,
|
||||
`fileId=${fileId || 'missing'}, businessType=${uploaded?.businessType || 'missing'}, size=${uploaded?.sizeBytes ?? 'missing'}`, OPTIONS)
|
||||
if (!fileId) return
|
||||
|
||||
const bindResponse = await bindLoadingEvidence(context, inboundId, tenantId, evidenceType, fileId, sealNo)
|
||||
const bound = context.apiSuccess(MODULE, `绑定柜次 ${evidenceType} 装柜证据`, bindResponse,
|
||||
responseEvidence(bindResponse), OPTIONS)
|
||||
const boundItem = bound?.evidences?.evidences?.find?.((item) =>
|
||||
item.evidenceType === evidenceType && id(item.fileId) === fileId && item.status !== 'VOID')
|
||||
context.assert(MODULE, `${evidenceType} 有效证据归属稳定且锁码门禁完整`, bindResponse,
|
||||
bound?.mainStatus === 'LOADING' && Boolean(boundItem?.id)
|
||||
const boundItem = bound?.evidences?.find?.((item) => item.evidenceType === evidenceType && item.status !== 'VOID')
|
||||
const evidenceId = id(boundItem?.evidenceId)
|
||||
const fileId = id(boundItem?.fileId)
|
||||
context.assert(MODULE, `${evidenceType} 有效证据归属稳定且锁码门禁完整`, uploadResponse,
|
||||
id(bound?.taskId) === taskId && id(bound?.containerBookingId) === containerId
|
||||
&& Boolean(evidenceId) && Boolean(fileId)
|
||||
&& boundItem?.remark === context.marker
|
||||
&& (evidenceType !== 'SEAL' || boundItem?.sealNo === sealNo),
|
||||
`mainStatus=${bound?.mainStatus || 'missing'}, evidenceId=${id(boundItem?.id) || 'missing'}, sealNo=${boundItem?.sealNo || 'n/a'}`, OPTIONS)
|
||||
if (!boundItem?.id) return
|
||||
`taskId=${id(bound?.taskId) || 'missing'}, containerBookingId=${id(bound?.containerBookingId) || 'missing'}, evidenceId=${evidenceId || 'missing'}, sealNo=${boundItem?.sealNo || 'n/a'}`, OPTIONS)
|
||||
if (!evidenceId) return
|
||||
|
||||
const downloadResponse = await context.requestBinary('GET',
|
||||
`/api/platform/v1/files/loading-evidence/${tenantId}/${inboundId}/${fileId}`)
|
||||
`${PDA}/tasks/${taskId}/evidence/${encodeURIComponent(evidenceId)}/content?warehouseId=${encodeURIComponent(warehouseId)}`)
|
||||
context.assert(MODULE, `下载柜次 ${evidenceType} 证据为非空受控二进制`, downloadResponse,
|
||||
downloadResponse.http === 200 && downloadResponse.bytes.length > 0
|
||||
&& downloadResponse.contentType.toLowerCase().includes('image/png'),
|
||||
@@ -752,7 +757,7 @@ export async function run(context) {
|
||||
}
|
||||
|
||||
const evidenceListResponse = await context.request('GET',
|
||||
`/api/platform/v1/inbounds/${inboundId}/loading/evidence?tenantId=${encodeURIComponent(tenantId)}`)
|
||||
`${PDA}/tasks/${taskId}/evidence?warehouseId=${encodeURIComponent(warehouseId)}`)
|
||||
const evidenceList = context.apiSuccess(MODULE, 'PDA 完成前回查五类有效装柜证据与锁码', evidenceListResponse,
|
||||
'', OPTIONS)
|
||||
const activeEvidence = Array.isArray(evidenceList?.evidences)
|
||||
@@ -771,13 +776,19 @@ export async function run(context) {
|
||||
remark: context.marker,
|
||||
}
|
||||
const completeResponse = await request(context, 'POST', completePath, completePayload)
|
||||
const completed = context.apiSuccess(MODULE, 'PDA 人工确认装柜完成', completeResponse, '', OPTIONS)
|
||||
const acceptedCompletion = context.apiSuccess(MODULE, 'PDA 提交人工确认装柜完成', completeResponse, '', OPTIONS)
|
||||
context.assert(MODULE, '装柜完成命令已接受并进入处理或终态', completeResponse,
|
||||
['COMPLETING', 'COMPLETED'].includes(acceptedCompletion?.taskStatus),
|
||||
`taskStatus=${acceptedCompletion?.taskStatus || 'missing'}, workflow=${acceptedCompletion?.workflowStatus || 'missing'}`, OPTIONS)
|
||||
const completion = await waitForCompletedTask(context, taskId, warehouseId)
|
||||
const completed = context.apiSuccess(MODULE, '等待 PDA 装柜完成异步收敛', completion.response,
|
||||
`attempts=${completion.attempts}`, OPTIONS)
|
||||
const directPdaCompletion = completed?.taskStatus === 'COMPLETED'
|
||||
&& completed?.workflowStatus === 'COMPLETED'
|
||||
context.assert(MODULE, '人工确认后 PDA 任务进入 COMPLETED', completeResponse,
|
||||
context.assert(MODULE, '人工确认后 PDA 任务进入 COMPLETED', completion.response,
|
||||
directPdaCompletion
|
||||
&& completed?.items?.every?.((item) => Number(item.pickedPackageCount) === Number(item.plannedPackageCount)),
|
||||
`taskStatus=${completed?.taskStatus || 'missing'}, workflow=${completed?.workflowStatus || 'missing'}`, OPTIONS)
|
||||
`taskStatus=${completed?.taskStatus || 'missing'}, workflow=${completed?.workflowStatus || 'missing'}, attempts=${completion.attempts}`, OPTIONS)
|
||||
|
||||
const operationsResponse = await request(context, 'GET', `${PDA}/tasks/${taskId}/operations`)
|
||||
const operations = context.apiSuccess(MODULE, '回查完成后的 PDA 操作审计', operationsResponse, '', OPTIONS)
|
||||
|
||||
@@ -71,9 +71,13 @@ test('truck attachment API and Admin upload-reference-delete flow are frozen', (
|
||||
assert.match(truckAttachmentDialog, /uploadTruckAppointmentAttachment/)
|
||||
assert.match(truckAttachmentDialog, /上传并关联/)
|
||||
assert.match(truckAttachmentDialog, /confirmButtonText: '确认', cancelButtonText: '取消'/)
|
||||
assert.match(truckAcceptance, /attachmentType=BILL_OF_LADING/)
|
||||
assert.match(truckAcceptance, /派车前保留有效 BILL_OF_LADING 提单附件/)
|
||||
assert.match(truckAcceptance, /缺提单号与文件明确拒绝/)
|
||||
for (const type of ['DISPATCH_ORDER', 'DRIVER_DOCUMENT', 'VEHICLE_DOCUMENT', 'OTHER'])
|
||||
assert.match(truckAttachmentDialog, new RegExp(type))
|
||||
assert.doesNotMatch(truckAttachmentDialog, /BILL_OF_LADING/)
|
||||
for (const label of ['上传并关联DISPATCH_ORDER拖车附件', '删除首次上传的拖车附件引用',
|
||||
'重新引用平台归属拖车附件', '附件列表包含重新引用的DISPATCH_ORDER', '删除重新引用的拖车附件'])
|
||||
assert.match(truckAcceptance, new RegExp(label))
|
||||
assert.doesNotMatch(truckAcceptance, /attachmentType=BILL_OF_LADING|派车前保留有效 BILL_OF_LADING 提单附件/)
|
||||
assert.match(matrix, /拖车附件闭环[\s\S]*`LANDED`/)
|
||||
})
|
||||
|
||||
@@ -97,7 +101,11 @@ test('PDA task opens only after no-number push, release, four-field link and pla
|
||||
assert.match(containerLoadingAcceptance, /订舱放舱为 RELEASED 且不预生成真实货柜/)
|
||||
assert.match(containerLoadingAcceptance, /订舱 RELEASED 但预装未 CONFIRMED 不生成 PDA 任务/)
|
||||
assert.match(containerLoadingAcceptance, /loading-plans\/\$\{planId\}\/confirm/)
|
||||
assert.match(containerLoadingAcceptance, /PDA}\/tasks\/\$\{taskId\}\/evidence/)
|
||||
assert.match(containerLoadingAcceptance, /evidence\/\$\{encodeURIComponent\(evidenceId\)\}\/content/)
|
||||
assert.match(containerLoadingAcceptance, /计划级原子确认整份预装并触发唯一 PDA 任务/)
|
||||
assert.match(containerLoadingAcceptance, /waitForCompletedTask/)
|
||||
assert.match(containerLoadingAcceptance, /taskStatus === 'COMPLETED' && task\?\.workflowStatus === 'COMPLETED'/)
|
||||
assert.match(containerLoadingAcceptance, /confirmationStatus === 'CONFIRMED'/)
|
||||
assert.match(containerLoadingAcceptance, /readiness\?\.readyForPda === true/)
|
||||
assert.match(containerLoadingAcceptance, /taskId === confirmedTaskId/)
|
||||
@@ -109,10 +117,9 @@ test('PDA task opens only after no-number push, release, four-field link and pla
|
||||
})
|
||||
|
||||
test('customer public display uses tenantName without a legalName fallback', () => {
|
||||
for (const source of [truckList, containerList]) {
|
||||
assert.match(source, /label: customer\.tenantName/)
|
||||
}
|
||||
assert.match(truckForm, /return customer\.tenantName/)
|
||||
assert.match(containerList, /label: customer\.tenantName/)
|
||||
for (const source of [truckList, truckForm])
|
||||
assert.doesNotMatch(source, /customer\.(?:tenantName|legalName)/)
|
||||
for (const source of [truckList, containerList, truckForm])
|
||||
assert.doesNotMatch(source, /customer\.legalName\?\.trim\(\) \|\| customer\.tenantName/)
|
||||
assert.match(matrix, /客户公开名称一致性[\s\S]*已统一 `tenantName`[\s\S]*`LANDED`/)
|
||||
|
||||
@@ -107,19 +107,19 @@ test('downstream finalizer uses the frozen truck-coupled complete contract', ()
|
||||
assert.doesNotMatch(finalize, /\/loading\/complete\?tenantId=/)
|
||||
})
|
||||
|
||||
test('PDA complete OpenAPI freezes optional truck coupling and atomic rollback', () => {
|
||||
test('PDA complete OpenAPI freezes reliable async acceptance and checkpoint recovery', () => {
|
||||
assert.match(pdaOpenApi, /\/api\/platform\/v1\/first-leg\/pda-loading\/tasks\/\{taskId\}\/complete:/)
|
||||
assert.match(pdaOpenApi, /拖车状态不是前置门禁/)
|
||||
assert.match(pdaOpenApi, /没有有效拖车则直接继续/)
|
||||
assert.match(pdaOpenApi, /恰有一条有效拖车时由服务端加锁推进为COMPLETED并写历史/)
|
||||
assert.match(pdaOpenApi, /多条有效拖车或并发修改返回A0409且全部Firstleg本地状态回滚/)
|
||||
assert.match(pdaOpenApi, /同operationId重放返回冻结结果,不重复推进拖车或写历史/)
|
||||
assert.match(pdaOpenApi, /持久化可靠完成命令并将任务置为COMPLETING后立即返回PROCESSING事实/)
|
||||
assert.match(pdaOpenApi, /后台worker按稳定入库单顺序以checkpoint恢复/)
|
||||
assert.match(pdaOpenApi, /请求事务内不调用任何远程服务/)
|
||||
assert.match(pdaOpenApi, /同operationId重放立即返回相同PROCESSING或最终结果/)
|
||||
assert.match(pdaOpenApi, /不同operationId在处理期间返回A0409/)
|
||||
})
|
||||
|
||||
test('PDA final completion refreshes post-settlement versions for full and partial split', () => {
|
||||
ordered(loadingPickService, [
|
||||
'settlementService.settle(taskId, operatorId, operatorName)',
|
||||
'loadingDeliveryService.completeAfterPdaSettlement',
|
||||
'settlementService.settleOwner(',
|
||||
'loadingDeliveryService.completeAfterPdaSettlement(',
|
||||
])
|
||||
assert.doesNotMatch(loadingPickService,
|
||||
/new LoadingRequests\.CompleteLoadingRequest\(entry\.getValue\(\)\.version\(\), remark\)/)
|
||||
@@ -133,7 +133,8 @@ test('PDA final completion refreshes post-settlement versions for full and parti
|
||||
'pdaFinalizeLocksAndUsesLoadedSliceVersionAfterPartialSettlement',
|
||||
'pdaFinalizeKeepsOptimisticConflictForRealConcurrentChange',
|
||||
]) assert.match(loadingDeliveryServiceTest, new RegExp(regression))
|
||||
assert.match(loadingDeliveryServiceTest, /verify\(repository, never\(\)\)\.completeLoadedChild\(10, 20, 7, 6\)/)
|
||||
assert.match(loadingDeliveryServiceTest, /verify\(repository\)\.findInboundForUpdate\(10L, 21L\)/)
|
||||
assert.match(loadingDeliveryServiceTest, /verify\(repository\)\.completeLoadedChild\(10L, 20L, 9L, 9\)/)
|
||||
assert.match(loadingDeliveryServiceTest, /verify\(histories, never\(\)\)\.insert/)
|
||||
})
|
||||
|
||||
@@ -159,7 +160,8 @@ test('HTTP finalizer races distinct completion keys and persists exactly one ter
|
||||
'读取结算前 PDA 操作历史基线',
|
||||
'const completeAttempts = [1, 2].map',
|
||||
'const concurrentCompleteResponses = await Promise.all',
|
||||
'并发完成后回查 PDA 操作审计',
|
||||
'异步完成命令收敛到终态',
|
||||
'const operationsAfterConcurrent = completion.operations',
|
||||
'两个不同幂等键并发 complete 仅一成功且只写一条完成审计',
|
||||
'订舱与五类证据等保留门禁齐备后完成装柜',
|
||||
'LOADED 完成请求 Idempotency-Key 重放保持终态',
|
||||
@@ -176,3 +178,17 @@ test('HTTP finalizer races distinct completion keys and persists exactly one ter
|
||||
assert.match(finalize, /concurrentCompleteOperations\.length === 1/)
|
||||
assert.match(finalize, /concurrentCompleteOperations\[0\]\?\.operationId === completeBody\.operationId/)
|
||||
})
|
||||
|
||||
test('worker final Firstleg convergence is one short transaction after remote owner settlement', () => {
|
||||
ordered(loadingPickService, [
|
||||
'settlementService.settleOwner(',
|
||||
'loadingDeliveryService.completeAfterPdaSettlement(',
|
||||
'completionTransaction.executeWithoutResult',
|
||||
'completeTruckAfterCommit(',
|
||||
])
|
||||
const finalizer = loadingPickService.slice(loadingPickService.indexOf('private void finalizeCompletion'),
|
||||
loadingPickService.indexOf('private void requireColoadConservation'))
|
||||
for (const token of ['COMPLETE_LOADING', 'finishFromPda', 'syncInboundProjections',
|
||||
'publishCompletedEvent', 'completeAccepted', 'completionCommands.complete']) assert.match(finalizer, new RegExp(token))
|
||||
assert.doesNotMatch(finalizer, /settlementService|completeTruckAfterCommit/)
|
||||
})
|
||||
|
||||
@@ -37,7 +37,7 @@ test('AWAITING_REVIEW derives zero client actions and never needs a repeated bat
|
||||
|
||||
test('pending backend contract derives workflow from task items instead of assignment alone', () => {
|
||||
assert.match(openApi,
|
||||
/PendingTask:[\s\S]*workflowStatus: \{type: string, enum: \[UNASSIGNED, IN_PROGRESS, AWAITING_REVIEW\][^\r\n]*}/)
|
||||
/PendingTask:[\s\S]*workflowStatus: \{type: string, enum: \[UNASSIGNED, IN_PROGRESS, AWAITING_REVIEW, PROCESSING, COMPLETION_FAILED\][^\r\n]*}/)
|
||||
assert.match(mapper,
|
||||
/WHEN SUM\(CASE WHEN pick_item\.item_status IN \('PENDING', 'PICKING'\)[\s\S]*= 0[\s\S]*THEN 'AWAITING_REVIEW'/)
|
||||
assert.doesNotMatch(mapper,
|
||||
|
||||
@@ -6,6 +6,8 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const read = (name) => readFileSync(resolve(here, name), 'utf8')
|
||||
const readFirstlegTest = (name) => readFileSync(resolve(here,
|
||||
'../../firstleg/src/test/java/com/baiyue/firstleg/portschedule/service', name), 'utf8')
|
||||
|
||||
test('current-marker departure batch proves four documents photos customs and container-level confirm', () => {
|
||||
const customs = read('phase3-customs.mjs')
|
||||
@@ -48,3 +50,25 @@ test('outbound-created query supports automated or manual carrier then reaches P
|
||||
assert.match(pda, /deploymentBlocker: true/)
|
||||
assert.doesNotMatch(pda, /addCoverageGap\([^\n]*PICKUP_READY/)
|
||||
})
|
||||
|
||||
test('demo package locks provider failure retry and refuses stray facts on failed calls', () => {
|
||||
const scheduler = readFirstlegTest('CarrierScheduleQuerySchedulerTest.java')
|
||||
const service = readFirstlegTest('CarrierScheduleQueryServiceTest.java')
|
||||
assert.match(scheduler, /retryableProviderResultCannotAdvanceEvenWhenItCarriesStrayFacts/)
|
||||
assert.match(scheduler, /verify\(service, never\(\)\)\.applyProviderObservation/)
|
||||
assert.match(scheduler, /completeScheduledAttempt\(1L, "RETRYABLE_FAILURE", "HTTP_503", "unavailable"\)/)
|
||||
assert.match(service, /retryableFailureUsesFifteenThenThirtyMinutesAndStopsAfterThreeCallsInTheSlot/)
|
||||
assert.match(service, /containsExactly\(1, 2, 3\)/)
|
||||
assert.match(service, /retryThatWouldReachTheNextSlotWaitsForTheSlotInstead/)
|
||||
})
|
||||
|
||||
test('demo package exposes the stable Admin task, node, exception and history DTO contract', () => {
|
||||
const nodes = read('phase4-carrier-nodes.mjs')
|
||||
assert.match(nodes, /trackingType === 'CONTAINER_NO'/)
|
||||
assert.match(nodes, /validContainerNo\(task\?\.trackingNo\)/)
|
||||
assert.match(nodes, /Array\.isArray\(detail\?\.nodes\)/)
|
||||
assert.match(nodes, /nodes\.every\(validNode\)/)
|
||||
assert.match(nodes, /exceptions\.every\(validException\)/)
|
||||
assert.match(nodes, /histories\.every\(validHistory\)/)
|
||||
assert.match(nodes, /!Object\.hasOwn\(detail \|\| \{\}, 'attempts'\)/)
|
||||
})
|
||||
|
||||
@@ -10,10 +10,11 @@ import { collectPhase4InboundProducerFixture } from './phase3-loading-finalize.m
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const read = (name) => readFileSync(resolve(here, name), 'utf8')
|
||||
|
||||
test('order fixture defaults to FBA and accepts only the explicit OVERSEAS variant', () => {
|
||||
test('order fixture defaults to FBA and preserves explicit OVERSEAS or PRIVATE routes', () => {
|
||||
assert.equal(requestedOrderDestinationType({ context: {} }), 'FBA')
|
||||
assert.equal(requestedOrderDestinationType({ context: { orderDestinationType: 'overseas' } }), 'OVERSEAS')
|
||||
assert.equal(requestedOrderDestinationType({ context: { orderDestinationType: 'PRIVATE' } }), 'FBA')
|
||||
assert.equal(requestedOrderDestinationType({ context: { orderDestinationType: 'PRIVATE' } }), 'PRIVATE')
|
||||
assert.equal(requestedOrderDestinationType({ context: { orderDestinationType: 'invalid' } }), 'FBA')
|
||||
const orders = read('orders.mjs')
|
||||
assert.match(orders, /warehouseType=\$\{encodeURIComponent\(destinationType\)\}/)
|
||||
assert.match(orders, /destinationType: master\.destinationType/)
|
||||
@@ -88,7 +89,8 @@ test('measurement and loading pass destination identity into the LOADED producer
|
||||
assert.match(entry, /skuLines: Array\.isArray\(fixtureOrder\.skuLines\) \? fixtureOrder\.skuLines : \[\]/)
|
||||
const pda = read('phase4-overseas-pda.mjs')
|
||||
assert.match(pda, /find\(\(item\) => item\?\.fulfillmentType === 'ONE_CLICK_DROPSHIP'\)/)
|
||||
assert.match(pda, /skuFixtures\(context, producer\)/)
|
||||
assert.match(pda, /resolveCartonFixtures\(context, token, current\.data\.inbounds, producerCartonMarks\)/)
|
||||
assert.match(pda, /FBA与OVERSEAS箱码resolve均为纯查询且零状态写入/)
|
||||
})
|
||||
|
||||
test('only PDA-operated variants traverse real outbound and carrier nodes before overseas receiving', () => {
|
||||
|
||||
@@ -377,7 +377,10 @@ test('container loading enforces channel isolation and stable PDA identity acros
|
||||
assert.match(value, /bookingAgentId: id\(bookingAgent\.id\), bookingAgentName: bookingAgent\.name/)
|
||||
assert.match(value, /const frozenTransport = Object\.fromEntries\(transportFields\.map/)
|
||||
assert.match(value, /if \(!frozenTransportMatches\) return/)
|
||||
assert.match(value, /expectedVersion: Number\(bookingCreatedDraft\?\.oceanBooking\?\.version\), reason: context\.marker/)
|
||||
assert.match(value, /const releaseVersion = Number\(bookingDocument\?\.bookingVersion\)/)
|
||||
assert.match(value, /expectedVersion: releaseVersion, reason: context\.marker/)
|
||||
assertOrder(value, ['上传有效订舱确认文件', '订舱确认文件已关联且版本递增',
|
||||
'订舱放舱为 RELEASED 且不预生成真实货柜'])
|
||||
assert.doesNotMatch(value, /const sailingAt = new Date\(Date\.now\(\)/)
|
||||
const batch = value.slice(value.indexOf('const staleBatchResponse'), value.indexOf('const completePath'))
|
||||
assert.doesNotMatch(batch, /containerNo:/)
|
||||
@@ -412,16 +415,18 @@ test('PDA completion acceptance verifies immutable BATCH and COMPLETE_LOADING au
|
||||
const convergence = source('./phase3-pda-convergence.mjs')
|
||||
assertOrder(container, [
|
||||
'最后一箱拣货后 PDA 任务等待人工确认装柜完成',
|
||||
'上传柜次 ${evidenceType} 真实证据文件',
|
||||
'绑定柜次 ${evidenceType} 装柜证据',
|
||||
'上传并绑定柜次 ${evidenceType} 真实证据文件',
|
||||
'${evidenceType} 有效证据归属稳定且锁码门禁完整',
|
||||
'PDA 完成前回查五类有效装柜证据与锁码',
|
||||
'PDA 人工确认装柜完成',
|
||||
'PDA 提交人工确认装柜完成',
|
||||
'等待 PDA 装柜完成异步收敛',
|
||||
])
|
||||
assert.match(container, /const evidenceTypes = \['PHOTO_STEP_1', 'PHOTO_STEP_2', 'PHOTO_STEP_3', 'PHOTO_STEP_4', 'SEAL'\]/)
|
||||
assert.match(container, /businessType === `LOADING_\$\{evidenceType\}`/)
|
||||
assert.match(container, /form\.append\('evidenceType', evidenceType\)/)
|
||||
assert.match(container, /new Blob\(\[png\], \{ type: 'image\/png' \}\)/)
|
||||
assert.match(container, /item\.evidenceType === 'SEAL' && item\.sealNo === sealNo/)
|
||||
assert.match(container, /if \(!evidenceTypes\.every[\s\S]*\) return/)
|
||||
assert.match(container, /requestBinary\('GET',[\s\S]*files\/loading-evidence/)
|
||||
assert.match(container, /requestBinary\('GET',[\s\S]*\/evidence\/\$\{encodeURIComponent\(evidenceId\)\}\/content/)
|
||||
assert.match(container, /回查完成后的 PDA 操作审计/)
|
||||
assert.match(container, /item\.actionType === 'BATCH'/)
|
||||
assert.match(container, /item\.actionType === 'COMPLETE_LOADING'/)
|
||||
@@ -502,7 +507,7 @@ test('phase3 loading resolves legal SKIP and PARTIAL exceptions before downstrea
|
||||
assert.match(loading, /Number\(exceptionOverview\?\.pda\?\.unresolvedItemCount\) === 0/)
|
||||
assert.doesNotMatch(loading, /addCoverageGap\([^)]*(SKIP|PARTIAL|未解决异常)/)
|
||||
assert.match(entry, /this\.context\.phase3LoadingIncrementalDetailCount = 4/)
|
||||
assert.match(measurement, /增量 fixture 形成四条真实独立货物测量明细/)
|
||||
assert.match(measurement, /增量 fixture 形成动态真实独立货物测量明细/)
|
||||
assert.match(measurement, /detailBoxCode = `\$\{inboundCode\}#\$\{originalPackageCount\}-\$\{cartonIndex\}`/)
|
||||
assert.match(measurement, /items: draftItems/)
|
||||
assert.match(measurement, /expectedPackages === originalPackageCount/)
|
||||
@@ -511,20 +516,22 @@ test('phase3 loading resolves legal SKIP and PARTIAL exceptions before downstrea
|
||||
assert.doesNotMatch(loading, /if \(Number\(dynamicCandidate\?\.availablePackageCount\) < 2\) return/)
|
||||
})
|
||||
|
||||
test('phase3 loading fixture forces A0 through reversible public location status APIs', () => {
|
||||
test('phase3 loading fixture paginates A0 candidates and refuses mass location mutations', () => {
|
||||
const entry = source('../admin-test-env-acceptance.mjs')
|
||||
const measurement = source('./inbound-measurement.mjs')
|
||||
const orders = source('./orders.mjs')
|
||||
assertOrder(entry, [
|
||||
'disableAvailableLocationsForA0(warehouseId)',
|
||||
'this.context.phase3LoadingRequireSharedOverflow = true',
|
||||
'disableAvailableLocationsForA0(warehouseId, requiredPalletCount)',
|
||||
'this.context.phase3LoadingRequireSharedOverflow = isolation.forced === true',
|
||||
"executeModule('inbound-measurement-phase3-loading-fixture'",
|
||||
'restoreAvailableLocationsAfterA0(warehouseId, disabledLocations)',
|
||||
'restoreAvailableLocationsAfterA0(warehouseId, isolation)',
|
||||
])
|
||||
assert.match(entry, /page=\$\{pageNumber\}&size=\$\{A0_LOCATION_PAGE_SIZE\}/)
|
||||
assert.match(entry, /A0_MAX_LOCATION_MUTATIONS = 8/)
|
||||
assert.match(entry, /A0 大仓保护:不批量停用普通库位/)
|
||||
assert.match(entry, /remainingNormal\.length < isolation\.requiredSlots/)
|
||||
assert.match(entry, /\/locations\/\$\{encodeURIComponent\(location\.id\)\}\/status/)
|
||||
assert.match(entry, /\{ status: 'DISABLED', version: Number\(location\.version\) \}/)
|
||||
assert.match(entry, /\{ status: 'AVAILABLE', version: location\.version \}/)
|
||||
assert.match(measurement, /phase3LoadingRequireSharedOverflow !== true/)
|
||||
assert.match(orders, /receivingWarehouseId: id\(master\.receiving\.id\)/)
|
||||
})
|
||||
|
||||
@@ -558,9 +565,11 @@ test('downstream container consumers prefer the phase3Loading fixture', () => {
|
||||
assert.match(ocean, /finalStatus: 'RELEASED', containerBookingId: null, loadingPlanId: null/)
|
||||
assert.match(source('./phase3-loading.mjs'), /oceanBookingId: bookingId, loadingPlanId, containerBookingId/)
|
||||
assert.match(serviceCenter, /if \(!allocationMatches\) return/)
|
||||
assert.match(serviceCenter, /const customerName = String\(oceanDetail\?\.oceanBooking\?\.customerName \|\| ''\)\.trim\(\)/)
|
||||
assert.match(serviceCenter, /category=TRUCKING&status=ACTIVE/)
|
||||
assert.match(serviceCenter, /customerId, customerName: null, carrierId: id\(carrier\.id\), carrierName: carrier\.name/)
|
||||
assert.match(serviceCenter, /oceanBookingId: ocean\.id/)
|
||||
assert.match(serviceCenter, /containerBookingId: linkContainer \? id\(containerFlow\.containerBookingId\) : null/)
|
||||
assert.match(serviceCenter, /carrierId: id\(carrier\.id\), carrierName: carrier\.name/)
|
||||
assert.doesNotMatch(serviceCenter, /customerId:|customerName:/)
|
||||
assert.doesNotMatch(serviceCenter, /链路承运商-/)
|
||||
assert.doesNotMatch(serviceCenter, /customerName: `服务中心链路客户-/)
|
||||
const schedules = source('./phase3-port-schedules.mjs')
|
||||
@@ -594,7 +603,8 @@ test('container overview always follows phase3 loading in default and custom mod
|
||||
|
||||
const entry = source('../admin-test-env-acceptance.mjs')
|
||||
assert.match(entry, /const DEFAULT_MODULES = normalizeModuleOrder\(CONFIGURED_MODULES\)/)
|
||||
assert.match(entry, /modules: normalizeModuleOrder\(/)
|
||||
assert.match(entry, /const modules = normalizeModuleOrder\(/)
|
||||
assert.match(entry, /return \{[\s\S]{0,500}modules,/)
|
||||
})
|
||||
|
||||
test('overview does not fall back to a container fixture when loading evidence was requested', () => {
|
||||
|
||||
@@ -125,7 +125,7 @@ function markerOwnedContext() {
|
||||
const task = {
|
||||
id: QUERY_ID, queryNo: `CSQ${QUERY_ID}`, customerId: CUSTOMER_ID, oceanBookingId: OCEAN_ID,
|
||||
containerBookingId: CONTAINER_ID, carrierCode: 'ZIM', trackingType: 'CONTAINER_NO',
|
||||
trackingNo: 'TSTU1234567', status: 'READY', triggerSource: 'OUTBOUND_CONFIRM',
|
||||
trackingNo: 'ZCSU7881970', status: 'READY', triggerSource: 'OUTBOUND_CONFIRM',
|
||||
latestActualNode: 'DEPARTED_WAREHOUSE', latestActualAt: '2026-08-24T08:00:00', version: 0,
|
||||
lastSuccessAt: null, sourceUpdatedAt: '2026-08-24T08:00:00', expiresAt: null,
|
||||
stoppedAt: null, stopReason: null,
|
||||
@@ -165,7 +165,7 @@ function markerOwnedContext() {
|
||||
accessMode: 'OFFICIAL_API', automated: true, coverageGap: false,
|
||||
}])
|
||||
if (method === 'GET' && requestPath === `${BASE}?page=1&size=20`) return ok({ records: [{
|
||||
query: { ...task, id: '9007199254740993999', trackingNo: 'HISTORICAL000' }, expired: false,
|
||||
query: { ...task, id: '9007199254740993999', trackingNo: 'MATU4646247' }, expired: false,
|
||||
}], page: 1, size: 20, total: 2, pages: 1 })
|
||||
if (method === 'GET' && requestPath === `${BASE}/${QUERY_ID}`) return ok(detail())
|
||||
if (method === 'GET' && requestPath === `${BASE}/${QUERY_ID}/history`) return ok(clone(histories))
|
||||
|
||||
@@ -10,14 +10,25 @@ export const STANDARD_NODES = Object.freeze([
|
||||
])
|
||||
export const EXCEPTION_CODES = Object.freeze(['CUSTOMS_HOLD', 'TERMINAL_HOLD', 'DOCUMENT_HOLD', 'UNKNOWN_HOLD'])
|
||||
export const NODE_SEQUENCES = Object.freeze(Object.fromEntries(STANDARD_NODES.map((node, index) => [node, (index + 1) * 10])))
|
||||
const ISO_CONTAINER_PATTERN = /^[A-Z]{3}[UJZ][0-9]{7}$/
|
||||
|
||||
function id(value) { return value == null ? '' : String(value) }
|
||||
function number(value) { return Number.isFinite(Number(value)) }
|
||||
function nullableText(value) { return value == null || typeof value === 'string' }
|
||||
function nullableId(value) { return value == null || validLongId(value) }
|
||||
function nullableIso(value) { return value == null || (typeof value === 'string' && !Number.isNaN(Date.parse(value))) }
|
||||
function validLongId(value) { return typeof value === 'string' && /^\d{16,}$/.test(value) }
|
||||
function validNumericId(value) { return typeof value === 'string' && /^\d+$/.test(value) && value !== '0' }
|
||||
function validContainerNo(value) {
|
||||
if (typeof value !== 'string' || !ISO_CONTAINER_PATTERN.test(value)) return false
|
||||
const letterValues = [10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24,
|
||||
25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38]
|
||||
let sum = 0
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const code = value.charCodeAt(index)
|
||||
sum += (code >= 48 && code <= 57 ? code - 48 : letterValues[code - 65]) * (2 ** index)
|
||||
}
|
||||
return Number(value[10]) === (sum % 11) % 10
|
||||
}
|
||||
function codeOf(response) { return response?.body?.code == null ? 'missing' : String(response.body.code) }
|
||||
function rejected(response) { return response?.http === 200 && ['A0409', '409'].includes(codeOf(response)) }
|
||||
function monotonicRejected(response) {
|
||||
@@ -45,7 +56,8 @@ export function manualNodePayload({ expectedVersion, standardNode, observedAt, e
|
||||
function validTask(task) {
|
||||
return validLongId(task?.id) && Boolean(task?.queryNo) && validNumericId(task?.customerId)
|
||||
&& validLongId(task?.oceanBookingId) && QUERY_STATUSES.includes(task?.status)
|
||||
&& nullableId(task?.containerBookingId) && nullableText(task?.latestActualNode)
|
||||
&& validLongId(task?.containerBookingId) && task?.trackingType === 'CONTAINER_NO'
|
||||
&& validContainerNo(task?.trackingNo) && nullableText(task?.latestActualNode)
|
||||
&& (task?.latestActualNode == null || STANDARD_NODES.includes(task.latestActualNode))
|
||||
&& number(task?.version)
|
||||
&& ['latestActualAt', 'lastSuccessAt', 'sourceUpdatedAt', 'expiresAt', 'stoppedAt']
|
||||
|
||||
@@ -7,7 +7,7 @@ const source = readFileSync(new URL('./phase4-overseas-master-data.mjs', import.
|
||||
const controllerSource = [
|
||||
'../../lastleg-service/src/main/java/com/baiyue/lastleg/masterdata/quote/controller/PlatformOverseasQuoteController.java',
|
||||
'../../lastleg-service/src/main/java/com/baiyue/lastleg/masterdata/exchange/controller/PlatformMonthlyExchangeRateController.java',
|
||||
'../../lastleg-service/src/main/java/com/baiyue/lastleg/masterdata/vehicle/controller/PlatformVehicleController.java',
|
||||
'../../lastleg-service/src/main/java/com/baiyue/lastleg/masterdata/vehicle/adapter/in/web/PlatformVehicleController.java',
|
||||
].map((path) => readFileSync(new URL(path, import.meta.url), 'utf8')).join('\n')
|
||||
const DOMESTIC_BASE = '/api/platform/v1/warehouse-admin'
|
||||
const OVERSEAS_BASE = '/api/platform/v1/last-leg/master-data'
|
||||
|
||||
@@ -291,10 +291,14 @@ async function convertReceivingContainers(context, producers) {
|
||||
{ 'Idempotency-Key': key }, context.overseasToken)
|
||||
const plans = success(convertedResponse) && Array.isArray(convertedResponse.body?.data)
|
||||
? convertedResponse.body.data : []
|
||||
const convertedInboundCodes = new Set(plans
|
||||
.flatMap((item) => Array.isArray(item?.lines) ? item.lines : [])
|
||||
.map((line) => id(line?.inboundCode)).filter(nonBlank))
|
||||
context.addStep(MODULE, `整柜转换为逐入仓码独立计划 ${containerNo}`, convertedResponse,
|
||||
plans.length === Number(summary.inboundCodeCount)
|
||||
&& plans.every((item) => nonBlank(item?.planNo) && Array.isArray(item?.lines) && item.lines.length > 0),
|
||||
`plans=${plans.length}, expected=${summary.inboundCodeCount}; ${trace(convertedResponse)}`, OPTIONS)
|
||||
&& plans.every((item) => Array.isArray(item?.lines) && item.lines.length > 0)
|
||||
&& convertedInboundCodes.size === Number(summary.inboundCodeCount),
|
||||
`plans=${plans.length}, inboundCodes=${convertedInboundCodes.size}, expected=${summary.inboundCodeCount}; ${trace(convertedResponse)}`, OPTIONS)
|
||||
if (plans.length !== Number(summary.inboundCodeCount)) return false
|
||||
const replayResponse = await context.requestOverseas('POST',
|
||||
'/api/platform/v1/last-leg/inbound-plans/convert-container', body,
|
||||
|
||||
@@ -98,7 +98,7 @@ export async function run(context) {
|
||||
driverIdCard: null, vehicleNo: `粤D-${suffix.slice(-6)}`, storeName: `链路门店-${suffix}`, storeContact: '链路联系人',
|
||||
storePhone: '13800000009', storeAddress: '深圳市南山区链路地址', storeCity: '深圳市', storeZipcode: '518000',
|
||||
packageCount: 1, grossWeightKg: 1, volumeCbm: 0.1, palletCount: 0, poNo: `FLOW-PO-${suffix}`,
|
||||
plannedLoadingAt: '2026-09-03T08:00:00', transitMinutes: 60, payableAmount: 1, receivableAmount: 2,
|
||||
plannedLoadingAt: '2026-09-03T08:00:00', transitMinutes: 60, payableAmount: 1,
|
||||
currency: 'RMB', remark: context.marker, expectedVersion: 0,
|
||||
}
|
||||
if (linkContainer) {
|
||||
|
||||
@@ -39,9 +39,3 @@ export function validEventReplay(before, after) {
|
||||
&& Number(before?.detailCount) === Number(after?.detailCount)
|
||||
&& Number(before?.historyCount) === Number(after?.historyCount)
|
||||
}
|
||||
|
||||
export function adminPreservesOrderNumber(apiValue, displayedValue, copiedValue) {
|
||||
return TAILLEG_ORDER_NUMBER.pattern.test(String(apiValue ?? ''))
|
||||
&& displayedValue === apiValue
|
||||
&& copiedValue === apiValue
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
adminPreservesOrderNumber,
|
||||
IMMUTABLE_TAILLEG_EVENT_FIXTURE,
|
||||
TAILLEG_ORDER_NUMBER,
|
||||
validContainerOrderGroup,
|
||||
@@ -13,18 +12,14 @@ import {
|
||||
|
||||
const read = (relativeUrl) => readFileSync(new URL(relativeUrl, import.meta.url), 'utf8')
|
||||
const eventV2 = read('../../common-event-contract/src/main/java/com/baiyue/common/event/FirstLegLoadingPlanCompletedV2.java')
|
||||
const producer = read('../../firstleg/src/main/java/com/baiyue/firstleg/service/LoadingCompletedOutboxService.java')
|
||||
const producerRows = read('../../firstleg/src/main/java/com/baiyue/firstleg/mapper/LoadingCompletedEventMapper.java')
|
||||
const eventV2Tests = read('../../common-event-contract/src/test/java/com/baiyue/common/event/FirstLegLoadingPlanCompletedV2Test.java')
|
||||
const consumer = read('../../lastleg-service/src/main/java/com/baiyue/lastleg/service/LoadingCompletedConsumer.java')
|
||||
const orderEntity = read('../../lastleg-service/src/main/java/com/baiyue/lastleg/entity/LastlegOrder.java')
|
||||
const orderSummary = read('../../lastleg-service/src/main/java/com/baiyue/lastleg/dto/LastlegOrderSummary.java')
|
||||
const orderService = read('../../lastleg-service/src/main/java/com/baiyue/lastleg/service/LastlegOrderService.java')
|
||||
const generator = read('../../lastleg-service/src/main/java/com/baiyue/lastleg/service/LastlegOrderNoGenerator.java')
|
||||
const generatorTests = read('../../lastleg-service/src/test/java/com/baiyue/lastleg/service/LastlegOrderNoGeneratorTest.java')
|
||||
const consumerTests = read('../../lastleg-service/src/test/java/com/baiyue/lastleg/service/LoadingCompletedConsumerTest.java')
|
||||
const adminApi = read('../../../apps/admin-web/src/modules/overseas-warehouse/api/lastMileOrders.ts')
|
||||
const adminPresentation = read('../../../apps/admin-web/src/modules/overseas-warehouse/lastMilePresentation.ts')
|
||||
const adminList = read('../../../apps/admin-web/src/modules/overseas-warehouse/pages/LastMileOrdersView.vue')
|
||||
const adminDetail = read('../../../apps/admin-web/src/modules/overseas-warehouse/pages/LastMileOrderDetailView.vue')
|
||||
|
||||
test('new 15-order event requires one non-empty trusted owner snapshot', () => {
|
||||
const orders = Array.from({ length: 15 }, (_, index) => ({
|
||||
@@ -44,26 +39,27 @@ test('the processed historical event is immutable and cannot be reused for accep
|
||||
})
|
||||
})
|
||||
|
||||
test('V2 producer freezes customerId and customerName and rejects a blank name', () => {
|
||||
test('V2 event contract freezes customerId and customerName and rejects a blank or mixed owner', () => {
|
||||
assert.match(eventV2, /List<Item> items,\s*String customerId,\s*String customerName,\s*String orderType/)
|
||||
assert.match(producerRows, /b\.customer_name/)
|
||||
assert.match(producer, /first\.getCustomerName\(\)/)
|
||||
assert.match(producer, /(?:customerName|getCustomerName)[\s\S]{0,300}(?:isBlank|hasText)/)
|
||||
assert.match(eventV2, /customerId\s*=\s*customerId\.trim\(\)/)
|
||||
assert.match(eventV2, /customerName\s*=\s*customerName\.trim\(\)/)
|
||||
assert.match(eventV2, /orders must share one immutable customerId\/customerName snapshot/)
|
||||
assert.match(eventV2Tests, /rejectsMissingImmutableCustomerName/)
|
||||
assert.match(eventV2Tests, /freezesTrimmedOwnerSnapshotAndRejectsMixedOwners/)
|
||||
})
|
||||
|
||||
test('Lastleg rejects a missing owner snapshot, persists it, and never calls IAM to repair it', () => {
|
||||
assert.match(consumer, /source\.customerName\(\)/)
|
||||
assert.match(consumer, /customerName[\s\S]{0,240}(?:isBlank|hasText)/)
|
||||
assert.match(consumer, /OwnerSnapshot owner\s*=\s*requireOwnerSnapshot\(payload\.orders\(\),\s*envelope\.tenantId\(\)\)/)
|
||||
assert.match(consumer, /requiredOwnerValue\(orders\.get\(0\)\.customerName\(\),\s*"customerName"\)/)
|
||||
assert.match(consumer, /value\s*==\s*null\s*\|\|\s*value\.isBlank\(\)/)
|
||||
assert.match(consumer, /order\.setCustomerName\(customerName\)/)
|
||||
assert.match(orderEntity, /private String customerName;/)
|
||||
assert.doesNotMatch(consumer, /(?:Iam|IAM|\/iam|CustomerClient|customer.*client)/)
|
||||
})
|
||||
|
||||
test('Lastleg query DTO and Admin list/detail use the frozen owner name', () => {
|
||||
test('Lastleg query DTO uses the persisted frozen owner name', () => {
|
||||
assert.match(orderSummary, /String customerName/)
|
||||
assert.match(orderService, /o\.getCustomerName\(\)/)
|
||||
assert.match(adminApi, /customerName\?: string \| null/)
|
||||
assert.match(adminPresentation, /owner:\s*text\(dto\.customerName\)/)
|
||||
assert.match(adminDetail, /label:\s*'货主',\s*value:\s*text\(order\?\.customerName\)/)
|
||||
})
|
||||
|
||||
test('new tailleg number is Shanghai daily LMO-yyMMdd-#### with concurrency and cross-day tests', () => {
|
||||
@@ -76,7 +72,8 @@ test('new tailleg number is Shanghai daily LMO-yyMMdd-#### with concurrency and
|
||||
assert.match(generator, /%04d|padStart\(4|String\.format/)
|
||||
assert.match(generatorTests, /(?:concurrent|并发)/i)
|
||||
assert.match(generatorTests, /(?:cross.?day|next.?day|跨天)/i)
|
||||
assert.match(generatorTests, /\^LMO-\\d\{6\}-\\d\{4\}\$/)
|
||||
assert.match(generatorTests, /LMO-260827-0001/)
|
||||
assert.match(generatorTests, /LMO-260828-0001/)
|
||||
})
|
||||
|
||||
test('one container with 15 inbound rows shares one new LMO number', () => {
|
||||
@@ -86,8 +83,9 @@ test('one container with 15 inbound rows shares one new LMO number', () => {
|
||||
assert.equal(validContainerOrderGroup(rows), true)
|
||||
assert.equal(validContainerOrderGroup(rows.map((row, index) => index === 14
|
||||
? { ...row, orderNo: 'LMO-260827-0043' } : row)), false)
|
||||
assert.match(consumer, /String orderNo\s*=\s*orderNoGenerator\.[^(]+\(payload\.containerNo\(\)\);[\s\S]*for \(int index/)
|
||||
assert.match(consumer, /createOrder\(envelope, payload, source, orderNo, rawSource\)/)
|
||||
assert.match(consumer, /String orderNo\s*=\s*orderNoGenerator\.next\(\);[\s\S]*for \(int index/)
|
||||
assert.match(consumer, /createOrder\(envelope, payload, source, orderNo, rawSource, containerNo/)
|
||||
assert.match(consumerTests, /oneContainerWith15InboundRowsSharesOneNewLmoNumber/)
|
||||
})
|
||||
|
||||
test('same event replay adds nothing and preserves the allocated number', () => {
|
||||
@@ -95,16 +93,6 @@ test('same event replay adds nothing and preserves the allocated number', () =>
|
||||
assert.equal(validEventReplay(before, { ...before }), true)
|
||||
assert.equal(validEventReplay(before, { ...before, orderCount: 30 }), false)
|
||||
assert.match(consumer, /if\s*\(existing\s*!=\s*null\)[\s\S]{0,400}return countOrders/)
|
||||
assert.match(consumerTests, /(?:replay|duplicate|重复)[\s\S]{0,900}(?:orderNo|OrderNo)/i)
|
||||
})
|
||||
|
||||
test('Admin displays and copies the exact queried number without reformatting', () => {
|
||||
const value = 'LMO-260827-0042'
|
||||
assert.equal(adminPreservesOrderNumber(value, value, value), true)
|
||||
assert.equal(adminPreservesOrderNumber(value, value.replaceAll('-', ''), value), false)
|
||||
assert.match(adminPresentation, /orderNo:\s*text\(dto\.orderNo\)/)
|
||||
assert.match(adminList, /prop:\s*'orderNo'/)
|
||||
assert.match(adminDetail, /reference-value="referenceValue"/)
|
||||
const adminOrderSources = `${adminList}\n${adminDetail}`
|
||||
assert.match(adminOrderSources, /(?:clipboard\.writeText|copyText|copyToClipboard)[\s\S]{0,240}(?:orderNo|referenceValue)|(?:orderNo|referenceValue)[\s\S]{0,240}(?:clipboard\.writeText|copyText|copyToClipboard)/)
|
||||
assert.match(consumerTests, /replayPreservesExistingLmoNumberAndAddsNothing/)
|
||||
assert.match(consumerTests, /verify\(sequences,never\(\)\)\.nextValue/)
|
||||
})
|
||||
|
||||
@@ -2,7 +2,44 @@ import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
import { inspectOceanBookingIdentity, truckAppointmentPayload } from './truck-appointments.mjs'
|
||||
import { activeCustomerIdentity, inspectOceanBookingIdentity, platformWarehouseIdentity, truckAppointmentPayload } from './truck-appointments.mjs'
|
||||
|
||||
test('booking prerequisite resolves an ACTIVE platform customer without fixture state', () => {
|
||||
assert.deepEqual(activeCustomerIdentity({ id: '21', tenantName: '现有客户' }),
|
||||
{ customerId: '21', customerName: '现有客户' })
|
||||
assert.deepEqual(activeCustomerIdentity({ tenantId: 22, customerName: '备用客户' }),
|
||||
{ customerId: '22', customerName: '备用客户' })
|
||||
assert.equal(activeCustomerIdentity({ id: '23' }), null)
|
||||
const source = readFileSync(new URL('truck-appointments.mjs', import.meta.url), 'utf8')
|
||||
assert.match(source, /\/api\/platform\/v1\/iam\/tenants\?page=1&size=100&status=ACTIVE/)
|
||||
assert.match(source, /fixtureCustomerId[\s\S]*\|\| candidates\[0\]/)
|
||||
})
|
||||
|
||||
test('channel catalog accepts the formal array response shape', () => {
|
||||
const source = readFileSync(new URL('truck-appointments.mjs', import.meta.url), 'utf8')
|
||||
assert.match(source, /const channelRows = records\(data\(channelsResponse\)\); const channel = channelRows\[0\]/)
|
||||
assert.doesNotMatch(source, /\(data\(channelsResponse\) \|\| \[\]\)\[0\]/)
|
||||
})
|
||||
|
||||
test('ACTIVE domestic platform warehouses are scanned through bounded pagination', () => {
|
||||
const source = readFileSync(new URL('truck-appointments.mjs', import.meta.url), 'utf8')
|
||||
assert.match(source, /for \(let page = 1; page <= 100; page\+\+\)/)
|
||||
assert.match(source, /warehouse-admin\?tenantId=0&warehouseType=DOMESTIC&status=ACTIVE&page=\$\{page\}&size=100/)
|
||||
assert.match(source, /const total = Number\(warehousePage\?\.total \?\? warehouseRows\.length\)/)
|
||||
assert.match(source, /page \* 100 >= total/)
|
||||
assert.match(source, /完整分页平台仓并解析有效海运渠道/)
|
||||
assert.doesNotMatch(source, /193000000000200001|193000000000200002/)
|
||||
})
|
||||
|
||||
test('platform warehouse scope is fixed to zero without requiring response tenantId', () => {
|
||||
assert.deepEqual(platformWarehouseIdentity({ warehouseId: '41', warehouseName: '宁波仓' }),
|
||||
{ warehouseId: '41', platformTenantId: '0' })
|
||||
assert.deepEqual(platformWarehouseIdentity({ id: 42, warehouseName: '义乌仓' }),
|
||||
{ warehouseId: '42', platformTenantId: '0' })
|
||||
const source = readFileSync(new URL('truck-appointments.mjs', import.meta.url), 'utf8')
|
||||
assert.match(source, /platformWarehouseIdentity\(item\)[\s\S]*platformTenantId: '0'/)
|
||||
assert.doesNotMatch(source, /platformWarehouseIdentity\(item\)[^{]*\{[^}]*tenantId/)
|
||||
})
|
||||
|
||||
test('booking identity is marker scoped and contains no customer snapshot', () => {
|
||||
const result = inspectOceanBookingIdentity('RUN-2', { id: '91', marker: 'RUN-2', warehouseId: '41' })
|
||||
@@ -21,6 +58,7 @@ test('payload requires booking container and carrier but never emits customer fi
|
||||
{ oceanBookingId: '91', containerBookingId: '81', carrierId: '501', carrierName: '正式拖车商' })
|
||||
assert.equal(Object.hasOwn(payload, 'customerId'), false)
|
||||
assert.equal(Object.hasOwn(payload, 'customerName'), false)
|
||||
assert.equal(Object.hasOwn(payload, 'receivableAmount'), false)
|
||||
})
|
||||
|
||||
test('backend DTO entity mapper service and OpenAPI have no truck customer protocol', () => {
|
||||
@@ -49,11 +87,26 @@ test('backend freezes released booking real container bill file and carrier rule
|
||||
}
|
||||
})
|
||||
|
||||
test('HTTP regression covers no-customer response and submit idempotency matrix', () => {
|
||||
test('HTTP regression is self-contained and covers no-customer and idempotency matrix', () => {
|
||||
const source = readFileSync(new URL('truck-appointments.mjs', import.meta.url), 'utf8')
|
||||
for (const label of ['响应不含客户字段且冻结订舱柜号关系', '同键同载荷重放', '提交幂等重放零漂移',
|
||||
'同键异载荷拒绝', '提单号与订舱不一致拒绝创建']) assert.match(source, new RegExp(label))
|
||||
assert.doesNotMatch(source, /customerId\s*:|customerName\s*:|独立拖车/)
|
||||
for (const label of ['自包含创建 DRAFT 订舱', '上传当前有效 BILL_OF_LADING 文件', '放舱自包含订舱',
|
||||
'绑定本轮真实 ISO 柜号', '拖车请求不含客户字段', '同柜第二条非终态预约拒绝且零漂移',
|
||||
'同键同载荷重放', '同键重放版本零漂移', '同键异载荷拒绝', '错误订舱拒绝创建',
|
||||
'错误柜号归属拒绝创建', '错误提单拒绝创建', '错误承运商拒绝创建', '非法拖车币种拒绝创建',
|
||||
'RMB应付费用响应无客户及应收字段', '编辑为USD应付费用', 'USD应付费用保存且无应收字段',
|
||||
'上传并关联DISPATCH_ORDER拖车附件', '拖车附件类型仅使用运营附件而非订舱提单',
|
||||
'删除首次上传的拖车附件引用', '重新引用平台归属拖车附件', '附件列表包含重新引用的DISPATCH_ORDER',
|
||||
'删除重新引用的拖车附件',
|
||||
'派车命令返回状态身份与版本正确', '派车后回查拖车完整详情',
|
||||
'详情字段完整且订舱柜号身份无客户字段漂移']) assert.match(source, new RegExp(label))
|
||||
assert.match(source, /const detailResponse = await request\(context, 'GET', path\); const detail = data\(detailResponse\)/)
|
||||
assert.match(source, /const detailGaps = truckAppointmentFieldGaps\(detail\)/)
|
||||
assert.doesNotMatch(source, /truckAppointmentFieldGaps\(dispatched\)/)
|
||||
assert.doesNotMatch(source, /phase3ContainerLoading|phase3Loading/)
|
||||
assert.doesNotMatch(source, /receivableAmount\s*:/)
|
||||
const entry = readFileSync(new URL('../admin-test-env-acceptance.mjs', import.meta.url), 'utf8')
|
||||
assert.match(entry, /\['truck-appointments', \['merchant-qualification-fixture'\]\]/)
|
||||
assert.doesNotMatch(entry, /\['truck-appointments', \[[^\]]*phase3-loading/)
|
||||
})
|
||||
|
||||
test('schema owns platform attachments and one active appointment per real container', () => {
|
||||
|
||||
@@ -1,113 +1,249 @@
|
||||
import { ensureMatsonCarrierPartner } from './carrier-partner-fixture.mjs'
|
||||
import { oceanBookingDraft } from './ocean-booking-fixture.mjs'
|
||||
import { truckAppointmentFieldGaps } from './fulfillment-list-field-contract.mjs'
|
||||
|
||||
const MODULE = 'truck-appointments'
|
||||
const OPTIONS = { scenario: 'truck-appointment-lifecycle', deploymentBlocker: true }
|
||||
const BASE = '/api/platform/v1/truck-appointments'
|
||||
const TRUCKS = '/api/platform/v1/truck-appointments'
|
||||
const BOOKINGS = '/api/platform/v1/ocean-bookings'
|
||||
const CONTAINERS = '/api/platform/v1/containers'
|
||||
|
||||
function id(value) { return value == null ? '' : String(value) }
|
||||
function codeOf(response) { return response?.body?.code == null ? 'missing' : String(response.body.code) }
|
||||
function failure(response) { return response?.http === 200 && codeOf(response) !== '200' }
|
||||
function data(response) { return codeOf(response) === '200' ? response.body.data : null }
|
||||
function failure(response) { return response?.http === 0 || response?.http >= 400 || (response?.http === 200 && codeOf(response) !== '200') }
|
||||
function records(value) { return Array.isArray(value) ? value : value?.records || [] }
|
||||
|
||||
export function platformWarehouseIdentity(item) {
|
||||
return { warehouseId: id(item?.warehouseId || item?.id || item?.warehouse?.id), platformTenantId: '0' }
|
||||
}
|
||||
|
||||
export function activeCustomerIdentity(item) {
|
||||
const customerId = id(item?.id || item?.tenantId)
|
||||
const customerName = String(item?.tenantName || item?.customerName || item?.name || '').trim()
|
||||
return customerId && customerName ? { customerId, customerName } : null
|
||||
}
|
||||
|
||||
async function request(context, method, path, body, headers = {}) {
|
||||
try {
|
||||
const response = await fetch(`${context.options.gateway}${path}`, {
|
||||
method,
|
||||
headers: { Accept: 'application/json', Authorization: `Bearer ${context.token}`,
|
||||
method, headers: { Accept: 'application/json', Authorization: `Bearer ${context.token}`,
|
||||
...(body === undefined ? {} : { 'Content-Type': 'application/json; charset=utf-8' }), ...headers },
|
||||
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(60_000),
|
||||
})
|
||||
const raw = await response.text(); let payload = null
|
||||
try { payload = raw ? JSON.parse(raw) : null } catch { /* bounded raw evidence */ }
|
||||
return { method, path, http: response.status, body: payload, raw: payload === null ? raw.slice(0, 500) : null,
|
||||
requestId: payload?.requestId || response.headers.get('x-request-id'), traceId: payload?.traceId || response.headers.get('x-trace-id') }
|
||||
const raw = await response.text(); let parsed = null
|
||||
try { parsed = raw ? JSON.parse(raw) : null } catch { /* bounded raw evidence */ }
|
||||
return { method, path, http: response.status, body: parsed, raw: parsed == null ? raw.slice(0, 500) : null,
|
||||
requestId: parsed?.requestId || response.headers.get('x-request-id'), traceId: parsed?.traceId || response.headers.get('x-trace-id') }
|
||||
} catch (error) { return { method, path, http: 0, body: null, raw: String(error), requestId: null, traceId: null } }
|
||||
}
|
||||
|
||||
export function inspectOceanBookingIdentity(marker, resource, detail = null) {
|
||||
if (!resource?.id) return { identity: null, reason: '本轮 oceanBooking.id 缺失' }
|
||||
if (resource.marker !== marker) return { identity: null, reason: `oceanBooking marker 不属于本轮:expected=${marker}, actual=${resource.marker || 'missing'}` }
|
||||
const booking = detail?.oceanBooking || null
|
||||
if (booking && id(booking.id) !== id(resource.id)) return { identity: null, reason: '订舱详情资源归属不一致' }
|
||||
const identity = { oceanBookingId: id(resource.id), warehouseId: id(resource.warehouseId || booking?.warehouseId) }
|
||||
const missingFields = Object.entries(identity).filter(([, value]) => !value).map(([key]) => key)
|
||||
return missingFields.length ? { identity: null, reason: `本轮订舱身份字段缺失:${missingFields.join(',')}`, missingFields }
|
||||
: { identity, reason: null, missingFields: [] }
|
||||
if (!resource?.id || resource.marker !== marker) return { identity: null, reason: '订舱不属于本轮' }
|
||||
const booking = detail?.oceanBooking || resource
|
||||
if (id(booking.id) !== id(resource.id)) return { identity: null, reason: '订舱详情资源归属不一致' }
|
||||
return { identity: { oceanBookingId: id(resource.id), warehouseId: id(booking.warehouseId) }, reason: null, missingFields: [] }
|
||||
}
|
||||
|
||||
export function truckAppointmentPayload(context, suffix, identity, version = 0, overrides = {}) {
|
||||
const supplier = context.createdResources?.truckSupplier || {}
|
||||
return {
|
||||
outboundOrderId: null, oceanBookingId: identity.oceanBookingId,
|
||||
containerBookingId: identity.containerBookingId, loadingPlanId: identity.loadingPlanId || null,
|
||||
warehouseId: identity.warehouseId || null, carrierId: id(supplier.supplierId) || null,
|
||||
carrierName: supplier.supplierName || null, billOfLadingNo: identity.billOfLadingNo || null,
|
||||
fleetContact: '车队联系人', fleetPhone: '13800000004', driverName: '司机验收', driverPhone: '13800000005',
|
||||
vehicleNo: `粤B-${suffix.slice(-6)}`, storeName: `装柜点-${suffix}`, storeContact: '仓库联系人',
|
||||
storePhone: '13800000006', storeAddress: '深圳市南山区验收地址', storeCity: '深圳', storeZipcode: '518000',
|
||||
const supplier = identity.truckSupplier || context.createdResources?.truckSupplier || {}
|
||||
return { outboundOrderId: null, oceanBookingId: identity.oceanBookingId,
|
||||
containerBookingId: identity.containerBookingId, loadingPlanId: null, warehouseId: identity.warehouseId,
|
||||
carrierId: id(supplier.supplierId), carrierName: supplier.supplierName,
|
||||
billOfLadingNo: identity.billOfLadingNo, fleetContact: '车队联系人', fleetPhone: '13800000004',
|
||||
driverName: '司机验收', driverPhone: '13800000005', vehicleNo: `粤B-${suffix.slice(-6)}`,
|
||||
storeName: `装柜点-${suffix}`, storeContact: '仓库联系人', storePhone: '13800000006',
|
||||
storeAddress: '深圳市南山区验收地址', storeCity: '深圳', storeZipcode: '518000',
|
||||
packageCount: 0, grossWeightKg: 0, volumeCbm: 0, palletCount: 0, poNo: `PO-${suffix}`,
|
||||
plannedLoadingAt: '2026-12-31T10:00:00', transitMinutes: 0, payableAmount: 0, receivableAmount: 0,
|
||||
currency: 'RMB', remark: `拖车平台业务-${suffix}`, expectedVersion: version, ...overrides,
|
||||
}
|
||||
plannedLoadingAt: '2026-12-31T10:00:00', transitMinutes: 0, payableAmount: 0,
|
||||
currency: 'RMB', remark: `拖车平台业务-${suffix}`, expectedVersion: version, ...overrides }
|
||||
}
|
||||
|
||||
function currentIdentity(context) {
|
||||
const fixture = [context.createdResources?.phase3ContainerLoading, context.createdResources?.phase3Loading]
|
||||
.find((item) => item?.marker === context.marker && id(item.oceanBookingId) && id(item.containerBookingId))
|
||||
if (!fixture) return null
|
||||
return { oceanBookingId: id(fixture.oceanBookingId), containerBookingId: id(fixture.containerBookingId),
|
||||
loadingPlanId: id(fixture.loadingPlanId) || null, warehouseId: id(fixture.warehouseId) || null,
|
||||
billOfLadingNo: fixture.billOfLadingNo || null }
|
||||
async function activeSupplier(context, category, suffix) {
|
||||
const list = await request(context, 'GET', `/api/platform/v1/suppliers?tenantId=0&category=${category}&status=ACTIVE&page=1&size=100`)
|
||||
const existing = records(data(list)).find((item) => item?.category === category && item?.status === 'ACTIVE')
|
||||
if (existing) return { supplierId: id(existing.id), supplierName: existing.name }
|
||||
const created = await request(context, 'POST', '/api/platform/v1/suppliers?tenantId=0', {
|
||||
name: `${category}-验收-${suffix}`, category, carrierCodes: category === 'BOOKING' ? ['MATSON'] : [],
|
||||
region: '深圳', contactName: '验收联系人', phone: '13800000000', status: 'ACTIVE', remark: context.marker,
|
||||
})
|
||||
const value = data(created); const supplierId = id(value?.id || value)
|
||||
context.apiSuccess(MODULE, `创建 ACTIVE ${category} 供应商`, created, '', OPTIONS)
|
||||
return supplierId ? { supplierId, supplierName: value?.name || `${category}-验收-${suffix}` } : null
|
||||
}
|
||||
|
||||
async function bookingMaster(context, suffix) {
|
||||
const fixtureCustomerId = id(context.createdResources?.merchantQualificationFixture?.tenantId
|
||||
|| context.context?.customerId || context.customerId)
|
||||
const customersResponse = await request(context, 'GET', '/api/platform/v1/iam/tenants?page=1&size=100&status=ACTIVE')
|
||||
const candidates = records(data(customersResponse))
|
||||
const customer = activeCustomerIdentity(candidates.find((item) =>
|
||||
fixtureCustomerId && id(item?.id || item?.tenantId) === fixtureCustomerId) || candidates[0])
|
||||
if (!customer) {
|
||||
context.addStep(MODULE, '通过正式平台客户查询解析 ACTIVE 订舱客户', customersResponse, false,
|
||||
`preferredCustomerId=${fixtureCustomerId || 'missing'}`, OPTIONS)
|
||||
return null
|
||||
}
|
||||
let lastWarehousesResponse = null
|
||||
for (let page = 1; page <= 100; page++) {
|
||||
const warehousesResponse = await request(context, 'GET',
|
||||
`/api/platform/v1/warehouse-admin?tenantId=0&warehouseType=DOMESTIC&status=ACTIVE&page=${page}&size=100`)
|
||||
lastWarehousesResponse = warehousesResponse
|
||||
const warehousePage = data(warehousesResponse); const warehouseRows = records(warehousePage)
|
||||
for (const item of warehouseRows) {
|
||||
const { warehouseId } = platformWarehouseIdentity(item)
|
||||
if (!warehouseId) continue
|
||||
const channelsResponse = await request(context, 'GET', `${BOOKINGS}/channels?originWarehouseId=${warehouseId}`)
|
||||
const channelRows = records(data(channelsResponse)); const channel = channelRows[0]
|
||||
if (channel?.channelCode) {
|
||||
context.addStep(MODULE, '完整分页平台仓并解析有效海运渠道', channelsResponse, true,
|
||||
`warehousePage=${page}, warehouseRecords=${warehouseRows.length}, channelRecords=${channelRows.length}, warehouseId=${warehouseId}`, OPTIONS)
|
||||
return { ...customer, warehouseId, channelCode: channel.channelCode, channelName: channel.channelName }
|
||||
}
|
||||
}
|
||||
const total = Number(warehousePage?.total ?? warehouseRows.length)
|
||||
if (warehouseRows.length === 0 || page * 100 >= total) break
|
||||
}
|
||||
context.addStep(MODULE, '解析具备有效海运渠道的平台仓库', lastWarehousesResponse, false,
|
||||
`platformTenantId=0, customerId=${customer.customerId}`, OPTIONS)
|
||||
return null
|
||||
}
|
||||
|
||||
function isoContainerNo(marker) {
|
||||
const values = {}; let value = 10
|
||||
for (let code = 65; code <= 90; code++) { while (value % 11 === 0) value++; values[String.fromCharCode(code)] = value++ }
|
||||
const serial = String([...marker].reduce((sum, char) => (sum * 31 + char.charCodeAt(0)) >>> 0, 0) % 1_000_000).padStart(6, '0')
|
||||
const base = `TSTU${serial}`; let sum = 0
|
||||
;[...base].forEach((char, index) => { sum += (values[char] ?? Number(char)) * (2 ** index) })
|
||||
return `${base}${(sum % 11) % 10}`
|
||||
}
|
||||
|
||||
async function fixture(context) {
|
||||
const suffix = context.marker.replace(/[^A-Za-z0-9]/g, '').slice(-10) || 'TRUCK'
|
||||
const master = await bookingMaster(context, suffix); if (!master?.customerId) return null
|
||||
const bookingAgent = await activeSupplier(context, 'BOOKING', suffix)
|
||||
const truckSupplier = await activeSupplier(context, 'TRUCKING', suffix)
|
||||
const carrier = await ensureMatsonCarrierPartner(context, MODULE, OPTIONS)
|
||||
if (!bookingAgent || !truckSupplier || !carrier?.id) return null
|
||||
const draft = oceanBookingDraft(context, suffix, master, {
|
||||
bookingAgentId: bookingAgent.supplierId, bookingAgentName: bookingAgent.supplierName,
|
||||
shippingCompanyId: id(carrier.id), shippingCompanyName: carrier.name, carrierCode: 'MATSON',
|
||||
containerRequirements: [{ containerType: '40HC', containerKind: 'FCL', quantity: 2, capacityCbm: 76, maxWeightKg: 28000 }],
|
||||
})
|
||||
const createdResponse = await request(context, 'POST', BOOKINGS, { expectedVersion: 0, data: draft },
|
||||
{ 'Idempotency-Key': `${context.marker}-truck-booking-create`.slice(0, 128) })
|
||||
const created = context.apiSuccess(MODULE, '自包含创建 DRAFT 订舱', createdResponse, '', OPTIONS)
|
||||
const bookingId = id(created?.oceanBooking?.id); if (!bookingId) return null
|
||||
const form = new FormData(); form.append('expectedVersion', String(created.oceanBooking.version))
|
||||
form.append('documentType', 'BILL_OF_LADING')
|
||||
form.append('file', new Blob([`${context.marker}-BILL_OF_LADING`], { type: 'application/pdf' }), `bill-${suffix}.pdf`)
|
||||
const uploadResponse = await context.requestMultipart('POST', `${BOOKINGS}/${bookingId}/documents/upload`, form,
|
||||
context.token, { 'Idempotency-Key': `${context.marker}-truck-booking-file`.slice(0, 128) })
|
||||
const uploaded = context.apiSuccess(MODULE, '上传当前有效 BILL_OF_LADING 文件', uploadResponse, '', OPTIONS)
|
||||
const releaseResponse = await request(context, 'POST', `${BOOKINGS}/${bookingId}/release`,
|
||||
{ expectedVersion: Number(uploaded?.bookingVersion), reason: context.marker },
|
||||
{ 'Idempotency-Key': `${context.marker}-truck-booking-release`.slice(0, 128) })
|
||||
const released = context.apiSuccess(MODULE, '放舱自包含订舱', releaseResponse, '', OPTIONS)
|
||||
const requirement = released?.containerRequirements?.[0]; if (released?.oceanBooking?.status !== 'RELEASED' || !requirement?.id) return null
|
||||
const simulationResponse = await request(context, 'POST', CONTAINERS, { channelCode: master.channelCode,
|
||||
warehouseId: master.warehouseId, containerType: '40HC', capacityCbm: 76, maxWeightKg: 28000 })
|
||||
const simulation = context.apiSuccess(MODULE, '创建自包含模拟柜', simulationResponse, '', OPTIONS)
|
||||
const containerNo = isoContainerNo(context.marker); if (!simulation?.id) return null
|
||||
const linkResponse = await request(context, 'POST', `${CONTAINERS}/${simulation.id}/ocean-booking-link`, {
|
||||
oceanBookingId: bookingId, requirementId: id(requirement.id), containerNo, expectedVersion: Number(simulation.version),
|
||||
})
|
||||
const linked = context.apiSuccess(MODULE, '绑定本轮真实 ISO 柜号', linkResponse, '', OPTIONS)
|
||||
if (linked?.containerNo !== containerNo) return null
|
||||
return { suffix, oceanBookingId: bookingId, containerBookingId: id(linked.id), warehouseId: master.warehouseId,
|
||||
billOfLadingNo: released.oceanBooking.billOfLadingNo, truckSupplier, bookingVersion: released.oceanBooking.version }
|
||||
}
|
||||
|
||||
export async function run(context) {
|
||||
const identity = currentIdentity(context)
|
||||
const supplier = context.createdResources?.truckSupplier
|
||||
context.assert(MODULE, '本轮拖车前置仅依赖已放舱订舱、真实柜和拖车供应商', null,
|
||||
Boolean(identity?.oceanBookingId && identity?.containerBookingId && supplier?.supplierId),
|
||||
`oceanBookingId=${identity?.oceanBookingId || 'missing'}, containerBookingId=${identity?.containerBookingId || 'missing'}, carrierId=${id(supplier?.supplierId) || 'missing'}`, OPTIONS)
|
||||
if (!identity?.oceanBookingId || !identity?.containerBookingId || !supplier?.supplierId) return
|
||||
|
||||
const suffix = context.marker.replace(/[^A-Za-z0-9]/g, '').slice(-10)
|
||||
const base = truckAppointmentPayload(context, suffix, identity)
|
||||
const identity = await fixture(context)
|
||||
context.assert(MODULE, '拖车模块自包含前置链完整', null, Boolean(identity?.oceanBookingId && identity?.containerBookingId),
|
||||
`oceanBookingId=${identity?.oceanBookingId || 'missing'}, containerBookingId=${identity?.containerBookingId || 'missing'}`, OPTIONS)
|
||||
if (!identity) return
|
||||
context.createdResources.truckSupplier = identity.truckSupplier
|
||||
const base = truckAppointmentPayload(context, identity.suffix, identity)
|
||||
context.assert(MODULE, '拖车请求不含客户字段', null,
|
||||
!Object.hasOwn(base, 'customerId') && !Object.hasOwn(base, 'customerName'), Object.keys(base).join(','), OPTIONS)
|
||||
for (const [label, payload] of [
|
||||
['缺少 oceanBookingId 拒绝创建', { ...base, oceanBookingId: null }],
|
||||
['缺少 containerBookingId 拒绝创建', { ...base, containerBookingId: null }],
|
||||
['缺少拖车供应商拒绝创建', { ...base, carrierId: null }],
|
||||
['提单号与订舱不一致拒绝创建', { ...base, billOfLadingNo: `WRONG-${suffix}` }],
|
||||
['错误订舱拒绝创建', { ...base, oceanBookingId: (BigInt(identity.oceanBookingId) + 1n).toString() }],
|
||||
['错误柜号归属拒绝创建', { ...base, containerBookingId: (BigInt(identity.containerBookingId) + 1n).toString() }],
|
||||
['错误提单拒绝创建', { ...base, billOfLadingNo: `WRONG-${identity.suffix}` }],
|
||||
['错误承运商拒绝创建', { ...base, carrierId: (BigInt(identity.truckSupplier.supplierId) + 1n).toString() }],
|
||||
['非法拖车币种拒绝创建', { ...base, currency: 'CNY' }],
|
||||
]) {
|
||||
const response = await request(context, 'POST', BASE, payload)
|
||||
context.addStep(MODULE, label, response, failure(response), `HTTP=${response.http}, code=${codeOf(response)}`, OPTIONS)
|
||||
const response = await request(context, 'POST', TRUCKS, payload)
|
||||
context.addStep(MODULE, label, response, failure(response), `code=${codeOf(response)}`, OPTIONS)
|
||||
}
|
||||
|
||||
const createdResponse = await request(context, 'POST', BASE, base)
|
||||
const appointment = context.apiSuccess(MODULE, '创建订舱真实柜拖车预约', createdResponse, '', OPTIONS)
|
||||
const appointmentId = id(appointment?.id)
|
||||
context.assert(MODULE, '响应不含客户字段且冻结订舱柜号关系', createdResponse,
|
||||
Boolean(appointmentId) && appointment?.status === 'DRAFT' && !Object.hasOwn(appointment, 'customerId')
|
||||
&& !Object.hasOwn(appointment, 'customerName') && id(appointment?.oceanBookingId) === identity.oceanBookingId
|
||||
&& id(appointment?.containerBookingId) === identity.containerBookingId,
|
||||
`appointmentId=${appointmentId || 'missing'}`, OPTIONS)
|
||||
if (!appointmentId) return
|
||||
context.createdResources.truckAppointment = { id: appointmentId, marker: context.marker, finalStatus: 'DISPATCHED' }
|
||||
const path = `${BASE}/${appointmentId}`
|
||||
let version = Number(appointment.version)
|
||||
const submitKey = `${context.marker}-submit`
|
||||
const submitBody = { expectedVersion: version, reason: '并发幂等提交' }
|
||||
const createdResponse = await request(context, 'POST', TRUCKS, base)
|
||||
const appointment = context.apiSuccess(MODULE, '创建合法拖车预约', createdResponse, '', OPTIONS)
|
||||
const appointmentId = id(appointment?.id); if (!appointmentId) return
|
||||
context.assert(MODULE, 'RMB应付费用响应无客户及应收字段', createdResponse,
|
||||
appointment?.currency === 'RMB' && Number(appointment?.payableAmount) === 0
|
||||
&& !Object.hasOwn(appointment, 'receivableAmount')
|
||||
&& !Object.hasOwn(appointment, 'customerId') && !Object.hasOwn(appointment, 'customerName'), '', OPTIONS)
|
||||
const path = `${TRUCKS}/${appointmentId}`
|
||||
const attachmentForm = new FormData(); attachmentForm.append('attachmentType', 'DISPATCH_ORDER')
|
||||
attachmentForm.append('file', new Blob([`${context.marker}-DISPATCH_ORDER`], { type: 'application/pdf' }),
|
||||
`dispatch-order-${identity.suffix}.pdf`)
|
||||
const uploadAttachmentResponse = await context.requestMultipart('POST', `${path}/attachments/upload`,
|
||||
attachmentForm, context.token)
|
||||
const uploadedAttachment = context.apiSuccess(MODULE, '上传并关联DISPATCH_ORDER拖车附件', uploadAttachmentResponse, '', OPTIONS)
|
||||
const uploadedAttachmentId = id(uploadedAttachment?.id); const uploadedFileId = id(uploadedAttachment?.fileId)
|
||||
context.assert(MODULE, '拖车附件类型仅使用运营附件而非订舱提单', uploadAttachmentResponse,
|
||||
Boolean(uploadedAttachmentId && uploadedFileId) && uploadedAttachment?.attachmentType === 'DISPATCH_ORDER',
|
||||
`attachmentId=${uploadedAttachmentId || 'missing'}, fileId=${uploadedFileId || 'missing'}`, OPTIONS)
|
||||
const deleteUploadedResponse = await request(context, 'DELETE', `${path}/attachments/${uploadedAttachmentId}`)
|
||||
context.apiSuccess(MODULE, '删除首次上传的拖车附件引用', deleteUploadedResponse, '', OPTIONS)
|
||||
const referenceResponse = await request(context, 'POST', `${path}/attachments`,
|
||||
{ fileId: uploadedFileId, attachmentType: 'DISPATCH_ORDER' })
|
||||
const referencedAttachment = context.apiSuccess(MODULE, '重新引用平台归属拖车附件', referenceResponse, '', OPTIONS)
|
||||
const referencedAttachmentId = id(referencedAttachment?.id)
|
||||
const attachmentListResponse = await request(context, 'GET', `${path}/attachments`)
|
||||
const attachmentList = context.apiSuccess(MODULE, '查询拖车运营附件列表', attachmentListResponse, '', OPTIONS)
|
||||
context.assert(MODULE, '附件列表包含重新引用的DISPATCH_ORDER', attachmentListResponse,
|
||||
Array.isArray(attachmentList) && attachmentList.some((item) => id(item?.id) === referencedAttachmentId
|
||||
&& item?.attachmentType === 'DISPATCH_ORDER'), `attachmentId=${referencedAttachmentId || 'missing'}`, OPTIONS)
|
||||
const deleteReferencedResponse = await request(context, 'DELETE', `${path}/attachments/${referencedAttachmentId}`)
|
||||
context.apiSuccess(MODULE, '删除重新引用的拖车附件', deleteReferencedResponse, '', OPTIONS)
|
||||
const usdResponse = await request(context, 'PUT', path,
|
||||
{ ...base, currency: 'USD', payableAmount: 12.34, expectedVersion: Number(appointment.version) })
|
||||
const usdAppointment = context.apiSuccess(MODULE, '编辑为USD应付费用', usdResponse, '', OPTIONS)
|
||||
context.assert(MODULE, 'USD应付费用保存且无应收字段', usdResponse,
|
||||
usdAppointment?.currency === 'USD' && Number(usdAppointment?.payableAmount) === 12.34
|
||||
&& !Object.hasOwn(usdAppointment || {}, 'receivableAmount'), '', OPTIONS)
|
||||
const duplicate = await request(context, 'POST', TRUCKS, base)
|
||||
context.addStep(MODULE, '同柜第二条非终态预约拒绝且零漂移', duplicate, failure(duplicate), `code=${codeOf(duplicate)}`, OPTIONS)
|
||||
const submitKey = `${context.marker}-truck-submit`.slice(0, 128)
|
||||
const submitBody = { expectedVersion: Number(usdAppointment?.version), reason: '幂等提交' }
|
||||
const first = await request(context, 'POST', `${path}/submit`, submitBody, { 'Idempotency-Key': submitKey })
|
||||
const firstData = context.apiSuccess(MODULE, '提交拖车预约', first, '', OPTIONS)
|
||||
const replay = await request(context, 'POST', `${path}/submit`, submitBody, { 'Idempotency-Key': submitKey })
|
||||
const replayData = context.apiSuccess(MODULE, '同键同载荷重放', replay, '', OPTIONS)
|
||||
context.assert(MODULE, '提交幂等重放零漂移', replay,
|
||||
id(firstData?.id) === id(replayData?.id) && Number(firstData?.version) === Number(replayData?.version),
|
||||
`firstVersion=${firstData?.version}, replayVersion=${replayData?.version}`, OPTIONS)
|
||||
version = Number(firstData?.version)
|
||||
const conflict = await request(context, 'POST', `${path}/submit`, { expectedVersion: version, reason: '异载荷' },
|
||||
{ 'Idempotency-Key': submitKey })
|
||||
context.assert(MODULE, '同键重放版本零漂移', replay, Number(firstData?.version) === Number(replayData?.version), '', OPTIONS)
|
||||
const conflict = await request(context, 'POST', `${path}/submit`, { ...submitBody, reason: '异载荷' }, { 'Idempotency-Key': submitKey })
|
||||
context.addStep(MODULE, '同键异载荷拒绝', conflict, failure(conflict), `code=${codeOf(conflict)}`, OPTIONS)
|
||||
const dispatch = await request(context, 'POST', `${path}/dispatch`, { expectedVersion: version, reason: '派车' },
|
||||
{ 'Idempotency-Key': `${context.marker}-dispatch` })
|
||||
const dispatch = await request(context, 'POST', `${path}/dispatch`,
|
||||
{ expectedVersion: Number(firstData?.version), reason: '派车' },
|
||||
{ 'Idempotency-Key': `${context.marker}-truck-dispatch`.slice(0, 128) })
|
||||
const dispatched = context.apiSuccess(MODULE, '有效提单后派车', dispatch, '', OPTIONS)
|
||||
context.assert(MODULE, '派车状态与稳定字段完整', dispatch,
|
||||
dispatched?.status === 'DISPATCHED' && truckAppointmentFieldGaps(dispatched).length === 0,
|
||||
`status=${dispatched?.status || 'missing'}`, OPTIONS)
|
||||
context.assert(MODULE, '派车命令返回状态身份与版本正确', dispatch,
|
||||
dispatched?.status === 'DISPATCHED' && id(dispatched?.id) === appointmentId
|
||||
&& Number(dispatched?.version) > Number(firstData?.version),
|
||||
`id=${id(dispatched?.id) || 'missing'}, status=${dispatched?.status || 'missing'}, version=${dispatched?.version ?? 'missing'}`, OPTIONS)
|
||||
const detailResponse = await request(context, 'GET', path); const detail = data(detailResponse)
|
||||
context.apiSuccess(MODULE, '派车后回查拖车完整详情', detailResponse, '', OPTIONS)
|
||||
const detailGaps = truckAppointmentFieldGaps(detail)
|
||||
context.assert(MODULE, '详情字段完整且订舱柜号身份无客户字段漂移', detailResponse,
|
||||
detail?.status === 'DISPATCHED' && detailGaps.length === 0
|
||||
&& !Object.hasOwn(detail || {}, 'customerId') && !Object.hasOwn(detail || {}, 'customerName')
|
||||
&& !Object.hasOwn(detail || {}, 'receivableAmount')
|
||||
&& detail?.currency === 'USD' && Number(detail?.payableAmount) === 12.34
|
||||
&& id(detail?.oceanBookingId) === identity.oceanBookingId
|
||||
&& id(detail?.containerBookingId) === identity.containerBookingId,
|
||||
`missing=${detailGaps.join(',') || 'none'}, currency=${detail?.currency || 'missing'}, payableAmount=${detail?.payableAmount ?? 'missing'}, oceanBookingId=${id(detail?.oceanBookingId) || 'missing'}, containerBookingId=${id(detail?.containerBookingId) || 'missing'}`, OPTIONS)
|
||||
context.createdResources.truckAppointment = { id: appointmentId, marker: context.marker, finalStatus: 'DISPATCHED',
|
||||
oceanBookingId: identity.oceanBookingId, containerBookingId: identity.containerBookingId }
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ const read = (relativeUrl) => readFileSync(new URL(relativeUrl, import.meta.url)
|
||||
const controller = read('../../firstleg/src/main/java/com/baiyue/firstleg/controller/PlatformInboundMeasurementController.java')
|
||||
const service = read('../../firstleg/src/main/java/com/baiyue/firstleg/service/InboundMeasurementService.java')
|
||||
const warehouseClient = read('../../firstleg/src/main/java/com/baiyue/firstleg/client/WarehousePalletLocationClient.java')
|
||||
const serviceTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/InboundMeasurementServiceTest.java')
|
||||
const openapi = read('../../firstleg/src/main/resources/openapi/firstleg-v1.yaml')
|
||||
const adminApi = read('../../../apps/admin-web/src/modules/inbounds/weight/api/weightOcr.ts')
|
||||
const adminPanel = read('../../../apps/admin-web/src/modules/inbounds/weight/components/WeightOcrPanel.vue')
|
||||
@@ -112,3 +113,16 @@ test('historical pallet snapshot remains read-only visible when it is no longer
|
||||
assert.match(cards, /row\.palletTareWeightKg/)
|
||||
assert.match(adminBehavior, /(?:historical|history|历史|失去候选|no longer eligible).{0,220}(?:palletCode|托盘编码|TP-)/is)
|
||||
})
|
||||
|
||||
test('backend detail reads the stored historical pallet snapshot without revalidating current eligibility', () => {
|
||||
assert.match(serviceTests, /detailUsesStoredPalletSnapshotAfterCandidateBecomesUnavailable/)
|
||||
assert.match(serviceTests, /verify\(warehousePallets, never\(\)\)\.palletSnapshot/)
|
||||
assert.match(serviceTests, /verify\(warehousePallets, never\(\)\)\.palletSnapshots/)
|
||||
})
|
||||
|
||||
test('backend evidence fails closed for Warehouse non-2xx and network errors', () => {
|
||||
assert.match(serviceTests, /weightPalletOptionsFailsClosedOnWarehouseNon2xxResponse/)
|
||||
assert.match(serviceTests, /weightPalletOptionsFailsClosedOnWarehouseNetworkError/)
|
||||
assert.match(serviceTests, /FeignException/)
|
||||
assert.match(serviceTests, /RetryableException/)
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ const read = (relativeUrl) => readFileSync(new URL(relativeUrl, import.meta.url)
|
||||
const controller = read('../../firstleg/src/main/java/com/baiyue/firstleg/controller/PlatformInboundMeasurementController.java')
|
||||
const pageResult = read('../../common-core/src/main/java/com/baiyue/common/core/api/PageResult.java')
|
||||
const longJackson = read('../../common-web/src/main/java/com/baiyue/common/web/LongIdJacksonConfiguration.java')
|
||||
const serviceTests = read('../../firstleg/src/test/java/com/baiyue/firstleg/service/InboundMeasurementServiceTest.java')
|
||||
const openapi = read('../../firstleg/src/main/resources/openapi/firstleg-v1.yaml')
|
||||
const adminApi = read('../../../apps/admin-web/src/modules/inbounds/weight/api/weightOcr.ts')
|
||||
const adminApiTests = read('../../../apps/admin-web/src/modules/inbounds/weight/api/weightOcr.test.ts')
|
||||
@@ -84,3 +85,9 @@ test('Admin behavior separately covers a non-2xx HTTP or network error', () => {
|
||||
test('Admin aborts and ignores an expired candidate response', () => {
|
||||
assert.match(adminBehavior, /in-flight pallet request[\s\S]{0,900}signal\?\.aborted[\s\S]{0,300}过期托盘/)
|
||||
})
|
||||
|
||||
test('backend preserves failure evidence for Warehouse non-2xx and network errors', () => {
|
||||
assert.match(serviceTests, /weightPalletOptionsFailsClosedOnWarehouseNon2xxResponse/)
|
||||
assert.match(serviceTests, /weightPalletOptionsFailsClosedOnWarehouseNetworkError/)
|
||||
assert.match(serviceTests, /仓库服务暂不可用/)
|
||||
})
|
||||
|
||||
@@ -92,6 +92,7 @@ $clientAgents = Read-RequiredText $clientAgentsPath
|
||||
$pdaAgents = Read-RequiredText $pdaAgentsPath
|
||||
$overseasPdaAgents = Read-RequiredText $overseasPdaAgentsPath
|
||||
$backendAgents = Read-RequiredText $backendAgentsPath
|
||||
$scriptsAgents = Read-RequiredText (Join-Path $backendRoot 'scripts/AGENTS.md')
|
||||
$engineeringConstraints = Read-RequiredText (Join-Path $workspaceRoot 'docs/AI工程执行与协作约束.md')
|
||||
$mapperScanContract = Read-RequiredText (Join-Path $backendRoot 'scripts/mapper-scan-contract.mjs')
|
||||
|
||||
@@ -100,19 +101,33 @@ Assert-Contains $rootAgents '源码结构、接口与 DTO、字段、状态机
|
||||
Assert-Contains $rootAgents '数据库记录、上传文件、缓存、会话、消息、搜索索引和其他运行状态均视为可丢弃' '根开发运行状态范围'
|
||||
Assert-Contains $rootAgents '后端 MyBatis Mapper 新增、移动或扫描遗漏' '根 Mapper 快速入口'
|
||||
Assert-Contains $rootAgents 'node scripts/mapper-scan-contract.mjs' '根 Mapper 静态门禁'
|
||||
Assert-Contains $rootAgents '脚本管理、全量验证与测试造数' '根脚本管理快速入口'
|
||||
Assert-Contains $rootAgents 'baiyue-firstleg/scripts/AGENTS.md' '根脚本最近指引'
|
||||
Assert-Contains $engineeringConstraints '禁止为旧代码、旧调用或开发环境存量保留旧接口/旧字段别名' '工程无兼容执行规则'
|
||||
Assert-Contains $engineeringConstraints '不授权自动重置数据库、删除数据/文件、执行 SQL、部署或修改环境' '无兼容安全边界'
|
||||
Assert-Contains $clientAgents '不得继续扩展 `LEGACY_MANUAL`、旧系统入仓码、C02 不可用回退旧 API' 'Client 头程无兼容边界'
|
||||
Assert-Contains $backendAgents '所有生产 MyBatis Mapper 接口必须显式标记 `@Mapper`' '后端 Mapper 注册规则'
|
||||
Assert-Contains $backendAgents 'Mapper 新增、移动、Bean 缺失与扫描遗漏' '后端 Mapper 快速路由'
|
||||
Assert-Contains $backendAgents '脚本管理、全量验证、测试造数与诊断' '后端脚本管理快速路由'
|
||||
Assert-Contains $backendAgents 'scripts/it-test-wait-split-bulk.mjs' '后端批量待分柜造数入口'
|
||||
Assert-Contains $backendAgents 'scripts/create-pending-review-orders.mjs' '后端待审核订单造数入口'
|
||||
Assert-Contains $scriptsAgents 'admin-test-env-acceptance.mjs' '脚本指引 Admin 全量入口'
|
||||
Assert-Contains $scriptsAgents 'client-test-env-acceptance.mjs' '脚本指引 Client 全量入口'
|
||||
Assert-Contains $scriptsAgents 'script-documentation-contract.test.mjs' '脚本说明防漏门禁'
|
||||
Assert-Contains $scriptsAgents '不得散落到 `src/test/scripts/`' '服务局部脚本目录边界'
|
||||
Assert-Path 'baiyue-firstleg/scripts/AGENTS.md'
|
||||
Assert-Path 'baiyue-firstleg/scripts/README.md'
|
||||
Assert-Path 'baiyue-firstleg/scripts/script-documentation-contract.test.mjs'
|
||||
Assert-Contains $mapperScanContract 'annotationClass = Mapper.class' 'Mapper 根包注解过滤合同'
|
||||
Assert-Contains $mapperScanContract '禁止分散维护 MapperScan' 'Mapper 单一扫描入口合同'
|
||||
$firstlegAgents = Read-RequiredText (Join-Path $backendRoot 'firstleg/AGENTS.md')
|
||||
$warehouseAgents = Read-RequiredText (Join-Path $backendRoot 'warehouse/AGENTS.md')
|
||||
$coloadOpenApi = Read-RequiredText (Join-Path $backendRoot 'firstleg/src/main/resources/openapi/coload-groups-v1.yaml')
|
||||
Assert-Contains $rootAgents 'modules/unified-orders/api/coLoadGroups.ts' '根同柜不可拆组入口'
|
||||
Assert-Contains $adminAgents '成员数是入仓片段数,不等于订单票数' 'Admin 同柜成员语义'
|
||||
Assert-Contains $backendAgents 'loading/coload/controller/PlatformColoadGroupController.java' '后端同柜不可拆组入口'
|
||||
Assert-Contains $firstlegAgents '服务端冻结每票全部 `WAIT_SPLIT` 可用入仓片段与满箱数' 'Firstleg 同柜建组边界'
|
||||
Assert-Contains $warehouseAgents 'scripts/warehouse-public-master-data-contract.test.mjs' 'Warehouse 局部脚本入口'
|
||||
Assert-Contains $coloadOpenApi '允许跨客户及不同目的仓港成组,仅要求国内仓和渠道一致' '同柜资格 OpenAPI'
|
||||
Assert-Contains $coloadOpenApi '服务端解析每个订单全部 WAIT_SPLIT' '同柜订单展开 OpenAPI'
|
||||
Assert-Contains $rootAgents '用户可见页面、提示和错误不得展示或以内部数据库 ID 作为业务编号回退' '根业务编号展示边界'
|
||||
@@ -125,6 +140,22 @@ $orderAgents = Read-RequiredText (Join-Path $backendRoot 'order/AGENTS.md')
|
||||
Assert-Contains $orderAgents '`channelCode` 直接来自 Order/Firstleg 权威快照' 'Order 稳定渠道编码'
|
||||
Assert-Contains $orderAgents 'InboundCodeAssociationService.java' 'Order 入仓码业务关系入口'
|
||||
Assert-Contains $firstlegAgents '/loading-plans/{planId}/lifecycle' 'Firstleg 装柜生命周期入口'
|
||||
$fileAgents = Read-RequiredText (Join-Path $backendRoot 'file/AGENTS.md')
|
||||
$truckOpenApi = Read-RequiredText (Join-Path $backendRoot 'firstleg/src/main/resources/openapi/truck-appointments-v1.yaml')
|
||||
$pdaLoadingApi = Read-RequiredText (Join-Path $workspaceRoot 'apps/pda-uniapp/api/pda-loading.js')
|
||||
Assert-Contains $rootAgents '拖车预约由已放舱订舱拥有,不按客户归属' '根订舱拥有拖车语义'
|
||||
Assert-Contains $rootAgents '证据以 `taskId + warehouseId` 进入任务专用 API' '根柜级证据入口'
|
||||
Assert-Contains $adminAgents '订舱拥有的拖车预约' 'Admin 拖车快速入口'
|
||||
Assert-Contains $adminAgents '不选择或提交客户' 'Admin 拖车无客户语义'
|
||||
Assert-Contains $backendAgents '订舱拥有的拖车' '后端拖车快速入口'
|
||||
Assert-Contains $firstlegAgents '请求、实体、查询和附件不得恢复 `customerId/customerName`' 'Firstleg 拖车无客户边界'
|
||||
Assert-Contains $firstlegAgents '同一真实柜通过查询锁与唯一约束最多保留一条非取消预约' 'Firstleg 拖车唯一有效预约'
|
||||
Assert-Contains $fileAgents '`businessType=TRUCK_APPOINTMENT_ATTACHMENT`' 'File 拖车平台附件入口'
|
||||
Assert-Contains $truckOpenApi 'required: [oceanBookingId, containerBookingId, carrierId, plannedLoadingAt, expectedVersion]' '拖车请求无客户字段'
|
||||
Assert-NotContains $truckOpenApi 'customerId:' '拖车 OpenAPI 客户字段'
|
||||
Assert-Contains $pdaAgents '当前 `taskId + warehouseId` 走任务专用 API' '国内 PDA 柜级证据入口'
|
||||
Assert-Contains $pdaLoadingApi '/first-leg/pda-loading/tasks/${encodeURIComponent(taskId)}/evidence?warehouseId=' '国内 PDA 证据查询 API'
|
||||
Assert-NotContains $pdaLoadingApi '/inbounds/${encodeURIComponent(inboundId)}/loading/evidence' '国内 PDA 旧入仓证据 API'
|
||||
$mapperModuleAgents = @(
|
||||
@{ Module = 'audit-service'; Application = 'BaiyueAuditApplication.java' },
|
||||
@{ Module = 'auth'; Application = 'BaiyueAuthApplication.java' },
|
||||
@@ -437,6 +468,10 @@ $criticalPaths = @(
|
||||
'apps/admin-web/src/modules/unified-orders/pages/UnifiedOrdersView.vue',
|
||||
'apps/admin-web/src/modules/ocean-bookings/api/platformOceanBookings.ts',
|
||||
'apps/admin-web/src/modules/ocean-bookings/pages/OceanBookingsView.vue',
|
||||
'apps/admin-web/src/modules/ocean-bookings/components/OceanBookingDocumentsPanel.vue',
|
||||
'apps/admin-web/src/modules/ocean-bookings/components/OceanBookingPrintDialog.vue',
|
||||
'apps/admin-web/src/modules/trucking/components/TruckAppointmentForm.vue',
|
||||
'apps/admin-web/src/modules/trucking/api/platformTrucking.ts',
|
||||
'apps/admin-web/src/core/routing/navigationRecovery.ts',
|
||||
'apps/admin-web/src/core/routing/navigationRecovery.test.ts',
|
||||
'apps/admin-web/src/modules/overseas-warehouse/api/outbounds.ts',
|
||||
@@ -530,6 +565,10 @@ $criticalPaths = @(
|
||||
'baiyue-firstleg/firstleg/src/main/resources/openapi/loading-lists-v1.yaml',
|
||||
'baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/loading/coload/controller/PlatformColoadGroupController.java',
|
||||
'baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/loading/coload/service/ColoadGroupService.java',
|
||||
'baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/oceanbooking/service/OceanBookingDocumentService.java',
|
||||
'baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/oceanbooking/service/OceanBookingPrintService.java',
|
||||
'baiyue-firstleg/firstleg/src/main/java/com/baiyue/firstleg/service/TruckAppointmentService.java',
|
||||
'baiyue-firstleg/firstleg/src/main/resources/openapi/truck-appointments-v1.yaml',
|
||||
'baiyue-firstleg/file/src/main/resources/openapi/customs-file-and-export-v1.yaml',
|
||||
'baiyue-firstleg/order/src/main/java/com/baiyue/order/service/InboundCodeAssociationService.java',
|
||||
'baiyue-firstleg/order/src/main/java/com/baiyue/order/service/UnifiedOrderQueryService.java',
|
||||
@@ -710,5 +749,5 @@ if ($failures.Count -gt 0) {
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "AGENTS 索引合同通过:$checked 项检查,覆盖快速表唯一性、部署单元、前端模块、Client active 路由、业务编号与内部 ID 隔离、装柜清单生命周期、四/五期范围边界、仓库主档唯一权威、订舱候选与柜量语义、整柜出仓与船节点单调性、Gateway 覆盖、PDA 页面/运行配置/独立更新/语言预留/能力开关、人工分段验收链、Maven 模块、Lastleg 海外安全投影、同步 Trace、关键入口和排除目录。" -ForegroundColor Green
|
||||
Write-Host "AGENTS 索引合同通过:$checked 项检查,覆盖快速表唯一性、部署单元、前端模块、Client active 路由、业务编号与内部 ID 隔离、装柜清单生命周期、订舱拥有拖车与柜级证据、四/五期范围边界、仓库主档唯一权威、订舱候选与柜量语义、整柜出仓与船节点单调性、Gateway 覆盖、PDA 页面/运行配置/独立更新/语言预留/能力开关、人工分段验收链、Maven 模块、Lastleg 海外安全投影、同步 Trace、关键入口和排除目录。" -ForegroundColor Green
|
||||
exit 0
|
||||
|
||||
@@ -16,22 +16,21 @@ import { resolve } from 'node:path'
|
||||
import { createInterface } from 'node:readline/promises'
|
||||
|
||||
const args = parseArgs(process.argv.slice(2))
|
||||
const gateway = trimSlash(args.gateway ?? process.env.CLIENT_PHASE2_TEST_GATEWAY
|
||||
?? 'http://8.163.30.128:9000')
|
||||
const clientUsername = args['client-username'] ?? process.env.CLIENT_PHASE2_USERNAME
|
||||
const gateway = trimSlash(args.gateway ?? process.env.ADMIN_TEST_GATEWAY)
|
||||
const clientUsername = args['client-username'] ?? process.env.MERCHANT_TEST_USERNAME
|
||||
?? await promptText('二期客户端账号(必须由正式注册/建档产生)', '')
|
||||
const clientPassword = args['client-password'] ?? process.env.CLIENT_PHASE2_PASSWORD
|
||||
const clientPassword = args['client-password'] ?? process.env.MERCHANT_TEST_PASSWORD
|
||||
?? await promptSecret('二期客户端密码')
|
||||
const platformUsername = args['platform-username'] ?? process.env.PLATFORM_USERNAME
|
||||
?? await promptText('平台夹具查询账号', 'platform_admin')
|
||||
const platformPassword = args['platform-password'] ?? process.env.PLATFORM_PASSWORD
|
||||
const platformUsername = args['platform-username'] ?? process.env.ADMIN_TEST_USERNAME
|
||||
?? await promptText('平台夹具查询账号', '')
|
||||
const platformPassword = args['platform-password'] ?? process.env.ADMIN_TEST_PASSWORD
|
||||
?? await promptSecret('平台夹具查询密码')
|
||||
const forcedOrderId = args['order-id'] ?? process.env.CLIENT_PHASE2_ORDER_ID ?? null
|
||||
const reportDir = resolve(args['report-dir'] ?? process.env.CLIENT_PHASE2_REPORT_DIR ?? 'reports')
|
||||
const timeoutMs = Number(args['timeout-ms'] ?? process.env.CLIENT_PHASE2_TIMEOUT_MS ?? 30_000)
|
||||
|
||||
if (!clientUsername || !clientPassword || !platformPassword) {
|
||||
console.error('An onboarded Client account and platform credentials are required')
|
||||
if (!gateway || !clientUsername || !clientPassword || !platformUsername || !platformPassword) {
|
||||
console.error('ADMIN_TEST_GATEWAY, an onboarded Client account, and platform credentials are required')
|
||||
process.exit(2)
|
||||
}
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs < 1_000) {
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
*
|
||||
* Run directly and enter the platform/client test credentials when prompted.
|
||||
* Optional environment variables for CI:
|
||||
* CLIENT_TEST_GATEWAY, PLATFORM_USERNAME, EXISTING_CLIENT_USERNAME,
|
||||
* PLATFORM_PASSWORD, EXISTING_CLIENT_PASSWORD, CLIENT_TEST_REPORT_DIR
|
||||
* ADMIN_TEST_GATEWAY, ADMIN_TEST_USERNAME, ADMIN_TEST_PASSWORD,
|
||||
* MERCHANT_TEST_USERNAME, MERCHANT_TEST_PASSWORD, CLIENT_TEST_REPORT_DIR
|
||||
*
|
||||
* Example:
|
||||
* node scripts/client-test-env-acceptance.mjs
|
||||
@@ -18,20 +18,20 @@ import { resolve } from 'node:path'
|
||||
import { createInterface } from 'node:readline/promises'
|
||||
|
||||
const args = parseArgs(process.argv.slice(2))
|
||||
const gateway = trimSlash(args.gateway ?? process.env.CLIENT_TEST_GATEWAY ?? 'http://8.163.30.128:9000')
|
||||
const platformUsername = args['platform-username'] ?? process.env.PLATFORM_USERNAME
|
||||
?? await promptText('平台审核账号', 'platform_admin')
|
||||
const platformPassword = args['platform-password'] ?? process.env.PLATFORM_PASSWORD
|
||||
const gateway = trimSlash(args.gateway ?? process.env.ADMIN_TEST_GATEWAY)
|
||||
const platformUsername = args['platform-username'] ?? process.env.ADMIN_TEST_USERNAME
|
||||
?? await promptText('平台审核账号', '')
|
||||
const platformPassword = args['platform-password'] ?? process.env.ADMIN_TEST_PASSWORD
|
||||
?? await promptSecret('平台审核密码')
|
||||
const existingClientUsername = args['existing-client-username'] ?? process.env.EXISTING_CLIENT_USERNAME
|
||||
const existingClientUsername = args['existing-client-username'] ?? process.env.MERCHANT_TEST_USERNAME
|
||||
?? await promptText('跨客户隔离测试账号(必须由正式注册/建档产生)', '')
|
||||
const existingClientPassword = args['existing-client-password'] ?? process.env.EXISTING_CLIENT_PASSWORD
|
||||
const existingClientPassword = args['existing-client-password'] ?? process.env.MERCHANT_TEST_PASSWORD
|
||||
?? await promptSecret('跨客户隔离测试密码')
|
||||
const reportDir = resolve(args['report-dir'] ?? process.env.CLIENT_TEST_REPORT_DIR ?? 'reports')
|
||||
const timeoutMs = Number(args['timeout-ms'] ?? process.env.CLIENT_TEST_TIMEOUT_MS ?? 30_000)
|
||||
|
||||
if (!platformPassword || !existingClientUsername || !existingClientPassword) {
|
||||
console.error('Platform password and an independently onboarded client account are required')
|
||||
if (!gateway || !platformUsername || !platformPassword || !existingClientUsername || !existingClientPassword) {
|
||||
console.error('ADMIN_TEST_GATEWAY, platform credentials, and an independently onboarded client account are required')
|
||||
process.exit(2)
|
||||
}
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs < 1_000) {
|
||||
@@ -1290,7 +1290,7 @@ async function orderLifecycleModule() {
|
||||
async function isolationModule() {
|
||||
if (!existingClientUsername || !existingClientPassword) {
|
||||
recordSkipped('isolation', 'cross-client order access is rejected',
|
||||
'Set EXISTING_CLIENT_USERNAME and EXISTING_CLIENT_PASSWORD to enable this check')
|
||||
'Set MERCHANT_TEST_USERNAME and MERCHANT_TEST_PASSWORD to enable this check')
|
||||
return
|
||||
}
|
||||
const login = await apiStep('isolation', 'existing client login', {
|
||||
|
||||
@@ -6,11 +6,14 @@ import { PRODUCT_CATALOG, buildOrderPayload, diversifyRoutes, parseArguments, ra
|
||||
|
||||
const source = readFileSync(new URL('./create-pending-review-orders.mjs', import.meta.url), 'utf8')
|
||||
|
||||
test('uses the fixed merchant account and stops at pending review', () => {
|
||||
assert.ok(source.includes("USERNAME: '17512095155'"), 'fixed username is missing')
|
||||
assert.ok(/PASSWORD:\s*'[^']*'/.test(source), 'CONFIG.PASSWORD is missing')
|
||||
assert.ok(/COUNT:\s*\d+/.test(source), 'CONFIG.COUNT is missing')
|
||||
assert.match(source, /COUNT:\s*50/)
|
||||
test('uses the configured merchant account and stops at pending review', () => {
|
||||
assert.match(source, /process\.env\.ADMIN_TEST_GATEWAY/)
|
||||
assert.match(source, /process\.env\.MERCHANT_TEST_USERNAME/)
|
||||
assert.match(source, /process\.env\.MERCHANT_TEST_PASSWORD/)
|
||||
assert.match(source, /const DEFAULT_COUNT = 50/)
|
||||
assert.doesNotMatch(source, /const CONFIG\s*=/)
|
||||
assert.doesNotMatch(source, /8\.163\.30\.128/)
|
||||
assert.doesNotMatch(source, /PASSWORD:\s*'[^']+'/)
|
||||
assert.match(source, /randomInt\(1, 31\)/)
|
||||
assert.match(source, /loadPricedRoutes/)
|
||||
assert.match(source, /destinationWarehouseCode/)
|
||||
@@ -28,6 +31,7 @@ test('uses the fixed merchant account and stops at pending review', () => {
|
||||
})
|
||||
|
||||
test('supports a bounded fixed order count', () => {
|
||||
assert.equal(validateCount(undefined), 50)
|
||||
assert.equal(validateCount('1'), 1)
|
||||
assert.equal(validateCount('10'), 10)
|
||||
assert.throws(() => validateCount('0'), /between 1 and 100/)
|
||||
|
||||
@@ -29,13 +29,7 @@ export const PRODUCT_CATALOG = [
|
||||
{ cargoName: '宠物橡胶玩具', cargoNameEn: 'Pet rubber toy', hsCode: '4016999090', material: '天然橡胶 / Natural rubber', usage: '宠物玩耍 / Pet play', brand: 'PETTEST', modelPrefix: 'PET', lengthCm: 46, widthCm: 36, heightCm: 34, unitsPerPackage: 48, cartonGrossWeightKg: 15.6, unitDeclaredValue: 3.4, productLengthCm: 12, productWidthCm: 7, productHeightCm: 7 },
|
||||
]
|
||||
|
||||
// Local test-environment settings. Keep PASSWORD empty in committed code.
|
||||
const CONFIG = {
|
||||
GATEWAY: 'http://8.163.30.128:9000',
|
||||
USERNAME: '17512095155',
|
||||
PASSWORD: 'M4mmp4YWcH5DiYPT',
|
||||
COUNT: 50,
|
||||
}
|
||||
const DEFAULT_COUNT = 50
|
||||
|
||||
export function parseArguments(values) {
|
||||
const options = {}
|
||||
@@ -58,7 +52,7 @@ export function parseArguments(values) {
|
||||
}
|
||||
|
||||
export function validateCount(value) {
|
||||
const count = Number(value ?? CONFIG.COUNT)
|
||||
const count = Number(value ?? DEFAULT_COUNT)
|
||||
if (!Number.isInteger(count) || count < 1 || count > MAX_COUNT) {
|
||||
throw new Error(`--count must be an integer between 1 and ${MAX_COUNT}`)
|
||||
}
|
||||
@@ -342,12 +336,13 @@ function printHelp() {
|
||||
node scripts/create-pending-review-orders.mjs --gateway <url> --count <1-${MAX_COUNT}> [--same-channel]
|
||||
|
||||
Environment:
|
||||
CLIENT_TEST_GATEWAY Test environment Gateway URL
|
||||
ADMIN_TEST_GATEWAY Test environment Gateway URL
|
||||
MERCHANT_TEST_PASSWORD Password for the configured fixed account
|
||||
MERCHANT_TEST_USERNAME Optional username override
|
||||
MERCHANT_TEST_USERNAME Username for the configured fixed account
|
||||
PENDING_REVIEW_ORDER_COUNT Optional order count, defaults to ${DEFAULT_COUNT}
|
||||
PENDING_ORDER_REPORT Optional JSON report path
|
||||
|
||||
The GATEWAY, USERNAME, PASSWORD, and COUNT fields can also be filled in CONFIG at the top of this file.`)
|
||||
Command-line arguments override environment variables. Credentials must not be written into this file.`)
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)) {
|
||||
@@ -356,13 +351,13 @@ export async function main(argv = process.argv.slice(2)) {
|
||||
printHelp()
|
||||
return 0
|
||||
}
|
||||
const gateway = trimSlash(args.gateway ?? process.env.CLIENT_TEST_GATEWAY ?? CONFIG.GATEWAY)
|
||||
if (!gateway) throw new Error('Gateway is required via CONFIG.GATEWAY, --gateway, or CLIENT_TEST_GATEWAY')
|
||||
const count = validateCount(args.count)
|
||||
const username = args.username ?? process.env.MERCHANT_TEST_USERNAME ?? CONFIG.USERNAME
|
||||
const password = args.password ?? process.env.MERCHANT_TEST_PASSWORD ?? CONFIG.PASSWORD
|
||||
if (!username) throw new Error('Fixed merchant username is required in CONFIG.USERNAME')
|
||||
if (!password) throw new Error('Merchant password is required in CONFIG.PASSWORD or MERCHANT_TEST_PASSWORD')
|
||||
const gateway = trimSlash(args.gateway ?? process.env.ADMIN_TEST_GATEWAY)
|
||||
if (!gateway) throw new Error('Gateway is required via --gateway or ADMIN_TEST_GATEWAY')
|
||||
const count = validateCount(args.count ?? process.env.PENDING_REVIEW_ORDER_COUNT)
|
||||
const username = args.username ?? process.env.MERCHANT_TEST_USERNAME
|
||||
const password = args.password ?? process.env.MERCHANT_TEST_PASSWORD
|
||||
if (!username) throw new Error('Merchant username is required via --username or MERCHANT_TEST_USERNAME')
|
||||
if (!password) throw new Error('Merchant password is required via --password or MERCHANT_TEST_PASSWORD')
|
||||
const timeoutMs = Number(args['timeout-ms'] ?? process.env.CLIENT_TEST_TIMEOUT_MS ?? 30_000)
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs < 1_000) throw new Error('--timeout-ms must be at least 1000')
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const read = (name) => readFileSync(new URL(name, import.meta.url), 'utf8')
|
||||
const client = read('./client-test-env-acceptance.mjs')
|
||||
const clientPhase2 = read('./client-phase2-test-env-acceptance.mjs')
|
||||
const pendingOrders = read('./create-pending-review-orders.mjs')
|
||||
const readme = read('./README.md')
|
||||
const agents = read('./AGENTS.md')
|
||||
|
||||
const activeHttpScripts = [client, clientPhase2, pendingOrders]
|
||||
const removedEnvironmentVariables = [
|
||||
'CLIENT_TEST_GATEWAY', 'CLIENT_PHASE2_TEST_GATEWAY',
|
||||
'PLATFORM_USERNAME', 'PLATFORM_PASSWORD',
|
||||
'EXISTING_CLIENT_USERNAME', 'EXISTING_CLIENT_PASSWORD',
|
||||
'CLIENT_PHASE2_USERNAME', 'CLIENT_PHASE2_PASSWORD',
|
||||
]
|
||||
|
||||
test('active Client and data-generation scripts share the canonical environment variables', () => {
|
||||
for (const source of activeHttpScripts) {
|
||||
assert.match(source, /process\.env\.ADMIN_TEST_GATEWAY/)
|
||||
assert.match(source, /process\.env\.MERCHANT_TEST_USERNAME/)
|
||||
assert.match(source, /process\.env\.MERCHANT_TEST_PASSWORD/)
|
||||
}
|
||||
assert.match(client, /process\.env\.ADMIN_TEST_USERNAME/)
|
||||
assert.match(client, /process\.env\.ADMIN_TEST_PASSWORD/)
|
||||
assert.match(clientPhase2, /process\.env\.ADMIN_TEST_USERNAME/)
|
||||
assert.match(clientPhase2, /process\.env\.ADMIN_TEST_PASSWORD/)
|
||||
})
|
||||
|
||||
test('active scripts no longer carry the retired variables, fixed Gateway, or source password config', () => {
|
||||
for (const source of activeHttpScripts) {
|
||||
for (const variable of removedEnvironmentVariables) assert.doesNotMatch(source, new RegExp(`process\\.env\\.${variable}`))
|
||||
assert.doesNotMatch(source, /8\.163\.30\.128/)
|
||||
}
|
||||
assert.doesNotMatch(pendingOrders, /const CONFIG\s*=/)
|
||||
assert.doesNotMatch(pendingOrders, /PASSWORD:\s*'[^']+'/)
|
||||
})
|
||||
|
||||
test('documentation names both external environment files and requires explicit selection', () => {
|
||||
for (const source of [readme, agents]) {
|
||||
assert.match(source, /chongchong-global-dev-acceptance\.env/)
|
||||
assert.match(source, /chongchong-global-test-acceptance\.env/)
|
||||
assert.match(source, /--env-file/)
|
||||
}
|
||||
assert.match(readme, /不会自行查找或加载上述文件/)
|
||||
assert.match(readme, /ADMIN_OVERSEAS_GATEWAY/)
|
||||
})
|
||||
Reference in New Issue
Block a user