Files
baiyue-firstleg/scripts/admin-test-env-modules/phase4-carrier-nodes-contract.test.mjs
T

249 lines
14 KiB
JavaScript
Raw Normal View History

2026-08-21 10:38:28 +08:00
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath } from 'node:url'
2026-08-24 19:44:28 +08:00
import { EXCEPTION_CODES, NODE_SEQUENCES, QUERY_STATUSES, STANDARD_NODES,
manualNodePayload, markerOwnedCarrierQuery, run } from './phase4-carrier-nodes.mjs'
import { normalizeModuleOrder } from '../admin-test-env-acceptance.mjs'
2026-08-21 10:38:28 +08:00
const here = path.dirname(fileURLToPath(import.meta.url))
const source = fs.readFileSync(path.join(here, 'phase4-carrier-nodes.mjs'), 'utf8')
2026-08-24 19:44:28 +08:00
const BASE = '/api/platform/v1/carrier-schedule-queries'
const QUERY_ID = '9007199254740993001'
const CUSTOMER_ID = '9007199254740993002'
const OCEAN_ID = '9007199254740993003'
const CONTAINER_ID = '9007199254740993004'
const MARKER = 'T-PHASE4'
2026-08-21 10:38:28 +08:00
2026-08-24 19:44:28 +08:00
function ok(data, requestId = 'req-ok') {
return { http: 200, body: { code: '200', data, requestId }, requestId, traceId: 'trace-ok' }
2026-08-21 10:38:28 +08:00
}
2026-08-26 15:58:54 +08:00
function conflict(requestId, message = 'conflict') {
return { http: 200, body: { code: 'A0409', message, requestId }, requestId, traceId: 'trace-conflict' }
2026-08-24 19:44:28 +08:00
}
function clone(value) { return structuredClone(value) }
2026-08-21 10:38:28 +08:00
test('focused carrier node execution injects the complete outbound-confirm producer chain', () => {
const modules = normalizeModuleOrder(['phase4-carrier-nodes'])
const required = ['merchant-qualification-fixture', 'orders', 'inbound-measurement',
'phase3-container-loading', 'phase3-loading', 'phase3-pda-convergence', 'phase3-evidence-gate',
'phase3-loading-finalize', 'phase3-customs', 'ocean-bookings', 'phase3-port-schedules',
'truck-appointments', 'service-center-flow', 'phase3-outbound-dispatch',
'phase3-carrier-schedule-queries', 'phase4-carrier-pickup-ready',
'phase4-overseas-pda', 'phase4-carrier-nodes']
for (const module of required) assert.ok(modules.includes(module), module)
for (let index = 1; index < required.length; index += 1) {
assert.ok(modules.indexOf(required[index - 1]) < modules.indexOf(required[index]), required[index])
}
})
test('real lifecycle opens the shipping gate before PDA and records pickup and empty return afterwards', () => {
const modules = normalizeModuleOrder(['phase4-overseas-pda', 'phase4-carrier-nodes'])
const pickup = modules.indexOf('phase4-carrier-pickup-ready')
const pda = modules.indexOf('phase4-overseas-pda')
const completion = modules.indexOf('phase4-carrier-nodes')
assert.ok(pickup >= 0 && pickup < pda)
assert.ok(pda < completion)
assert.match(source, /phase4CarrierPickupReady/)
assert.match(source, /STANDARD_NODES\.slice\(STANDARD_NODES\.indexOf\('PICKED_UP'\)\)/)
})
2026-08-24 19:44:28 +08:00
test('canonical states, ten ordered nodes, exception codes and complete payload are frozen', () => {
2026-08-21 16:04:16 +08:00
assert.deepEqual(QUERY_STATUSES, ['READY', 'MANUAL_REQUIRED', 'STOPPED'])
2026-08-21 10:38:28 +08:00
assert.deepEqual(STANDARD_NODES, [
2026-08-21 16:04:16 +08:00
'DEPARTED_WAREHOUSE', 'AT_ORIGIN_PORT', 'LOADED_ON_VESSEL', 'DEPARTED_ORIGIN_PORT',
'IN_TRANSIT', 'ARRIVED_DESTINATION_PORT', 'DISCHARGED_FROM_VESSEL', 'PICKUP_READY',
'PICKED_UP', 'EMPTY_RETURNED',
2026-08-21 10:38:28 +08:00
])
2026-08-24 19:44:28 +08:00
assert.deepEqual(Object.values(NODE_SEQUENCES), [10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
2026-08-21 16:04:16 +08:00
assert.deepEqual(EXCEPTION_CODES, ['CUSTOMS_HOLD', 'TERMINAL_HOLD', 'DOCUMENT_HOLD', 'UNKNOWN_HOLD'])
2026-08-24 19:44:28 +08:00
assert.deepEqual(Object.keys(manualNodePayload({ expectedVersion: 7, standardNode: 'PICKED_UP',
observedAt: '2026-08-24T12:00:00', actualAt: '2026-08-24T11:59:00', marker: MARKER })),
['expectedVersion', 'standardNode', 'observedAt', 'estimatedAt', 'actualAt',
'locationCode', 'locationName', 'reason'])
2026-08-21 10:38:28 +08:00
})
2026-08-24 23:43:08 +08:00
test('actual node timestamps advance from the frozen outbound-confirm fact instead of the runner timezone', () => {
assert.match(source, /Date\.parse\(`\$\{frozenLatestActual\}Z`\)/)
assert.match(source, /frozenLatestActualMs\) \? Date\.now\(\) : frozenLatestActualMs/)
})
2026-08-24 19:44:28 +08:00
test('module exposes no scheduler, attempt, internal or arbitrary stop endpoint', () => {
assert.match(source, /\/manual-nodes/)
assert.match(source, /'Idempotency-Key'/)
assert.doesNotMatch(source, /\/manual-results|\/attempts|\/scheduler|\/internal|\/pda|\/stop/)
assert.doesNotMatch(source, /\bfetch\s*\(/)
for (const method of ['PUT', 'PATCH', 'DELETE']) {
assert.doesNotMatch(source, new RegExp(`context\\.request\\(['"]${method}['"]`))
}
})
test('ownership requires current marker, long query id and outbound-confirm source', () => {
const valid = { queryId: QUERY_ID, marker: MARKER, ownedByModule: true,
triggerSource: 'OUTBOUND_CONFIRM' }
assert.equal(markerOwnedCarrierQuery({ marker: MARKER,
createdResources: { phase3CarrierScheduleQuery: valid } }).queryId, QUERY_ID)
assert.equal(markerOwnedCarrierQuery({ marker: 'OLD',
createdResources: { phase3CarrierScheduleQuery: valid } }), null)
assert.equal(markerOwnedCarrierQuery({ marker: MARKER, createdResources: {
phase3CarrierScheduleQuery: { ...valid, queryId: '1' },
2026-08-21 17:58:52 +08:00
} }), null)
2026-08-24 19:44:28 +08:00
assert.equal(markerOwnedCarrierQuery({ marker: MARKER, createdResources: {
phase3CarrierScheduleQuery: { ...valid, triggerSource: 'MANUAL' },
2026-08-21 17:58:52 +08:00
} }), null)
})
2026-08-24 19:44:28 +08:00
test('missing phase3 outbound query is an explicit deployment blocker and performs no write', async () => {
const calls = []; const steps = []
const context = {
marker: MARKER, token: 'token', createdResources: {}, calls,
request: async (method, requestPath) => {
calls.push({ method, path: requestPath })
if (requestPath === `${BASE}/carriers`) return ok([])
if (requestPath === `${BASE}?page=1&size=20`) return ok({ records: [], page: 1, size: 20, total: 0, pages: 0 })
throw new Error(`unexpected path ${requestPath}`)
},
apiSuccess: (_module, _name, response) => response.body.data,
assert: (_module, name, _response, condition, evidence) => assert.ok(condition, `${name}: ${evidence}`),
addStep: (_module, name, _response, passed, evidence, options) => steps.push({ name, passed, evidence, options }),
}
2026-08-21 17:58:52 +08:00
await run(context)
2026-08-24 19:44:28 +08:00
assert.deepEqual(calls.map((item) => item.method), ['GET', 'GET'])
assert.equal(steps.length, 1)
assert.equal(steps[0].passed, false)
assert.equal(steps[0].options.deploymentBlocker, true)
assert.match(steps[0].name, /禁止借历史任务写节点/)
})
function markerOwnedContext() {
let nextId = 9007199254740994000n
2026-08-26 15:58:54 +08:00
const calls = []; const steps = []; const assertions = []; const idempotency = new Map()
2026-08-24 19:44:28 +08:00
const task = {
id: QUERY_ID, queryNo: `CSQ${QUERY_ID}`, customerId: CUSTOMER_ID, oceanBookingId: OCEAN_ID,
containerBookingId: CONTAINER_ID, carrierCode: 'ZIM', trackingType: 'CONTAINER_NO',
trackingNo: 'ZCSU7881970', status: 'READY', triggerSource: 'OUTBOUND_CONFIRM',
2026-08-24 19:44:28 +08:00
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,
}
const nodes = [{
id: String(nextId++), providerCode: 'FIRSTLEG', providerEventId: 'OUTBOUND_CONFIRM',
providerNodeCode: 'OUTBOUND_CONFIRM', standardNode: 'DEPARTED_WAREHOUSE', nodeSequence: 10,
observedAt: '2026-08-24T08:00:00', estimatedAt: null, actualAt: '2026-08-24T08:00:00',
locationCode: null, locationName: null, sourceReference: 'OUTBOUND_CONFIRM',
rawPayloadHash: 'a'.repeat(64), createdAt: '2026-08-24T08:00:01',
}]
const exceptions = [{
id: String(nextId++), providerCode: 'MATSON_PUBLIC_TRACKING', providerEventId: 'hold-1',
providerStatus: 'CONTAINER ON HOLD - Customs Clearance', exceptionCode: 'CUSTOMS_HOLD', active: true,
observedAt: '2026-08-24T08:01:00', locationCode: 'USLAX', locationName: 'Long Beach',
sourceReference: 'MATSON:MASKED', rawPayloadHash: 'b'.repeat(64), createdAt: '2026-08-24T08:01:01',
}]
const histories = [{
id: String(nextId++), action: 'AUTO_CREATE', fromVersion: null, toVersion: 0,
2026-08-24 23:35:26 +08:00
reason: '国内确认出仓自动创建', operatorId: '1000001', operatorName: 'fixture',
2026-08-24 19:44:28 +08:00
createdAt: '2026-08-24T08:00:01',
}]
const detail = () => ({ query: { query: clone(task), expired: true },
nodes: clone(nodes), exceptions: clone(exceptions), histories: clone(histories) })
const context = {
marker: MARKER, token: 'token', calls, steps,
createdResources: { phase3CarrierScheduleQuery: {
queryId: QUERY_ID, marker: MARKER, ownedByModule: true, triggerSource: 'OUTBOUND_CONFIRM',
customerId: CUSTOMER_ID, oceanBookingId: OCEAN_ID, containerBookingId: CONTAINER_ID,
trackingNo: task.trackingNo, version: 0,
} },
request: async (method, requestPath, body, _token, headers = {}) => {
calls.push(method === 'POST' ? { method, path: requestPath, body: clone(body), headers: clone(headers) }
: { method, path: requestPath })
if (method === 'GET' && requestPath === `${BASE}/carriers`) return ok([{
carrierCode: 'ZIM', carrierName: 'ZIM', officialUrl: 'https://api.zim.com/',
accessMode: 'OFFICIAL_API', automated: true, coverageGap: false,
}])
if (method === 'GET' && requestPath === `${BASE}?page=1&size=20`) return ok({ records: [{
query: { ...task, id: '9007199254740993999', trackingNo: 'MATU4646247' }, expired: false,
2026-08-24 19:44:28 +08:00
}], 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))
if (method !== 'POST' || requestPath !== `${BASE}/${QUERY_ID}/manual-nodes`) {
throw new Error(`unexpected ${method} ${requestPath}`)
}
const key = headers['Idempotency-Key']; const signature = JSON.stringify(body)
if (idempotency.has(key)) {
const previous = idempotency.get(key)
return previous.signature === signature ? ok(clone(previous.detail), `req-replay-${key}`)
: conflict(`req-hash-${key}`)
}
if (Number(body.expectedVersion) !== Number(task.version)) return conflict(`req-version-${key}`)
2026-08-26 15:58:54 +08:00
if (body.actualAt != null
&& NODE_SEQUENCES[body.standardNode] <= NODE_SEQUENCES[task.latestActualNode]) {
return conflict(`req-monotonic-${key}`,
`人工实际节点必须严格晚于当前最新实际节点:${task.latestActualNode}`)
}
2026-08-24 19:44:28 +08:00
const providerEventId = `manual-${String(nextId)}`
nodes.push({
id: String(nextId++), providerCode: 'MANUAL', providerEventId, providerNodeCode: body.standardNode,
standardNode: body.standardNode, nodeSequence: NODE_SEQUENCES[body.standardNode],
observedAt: body.observedAt, estimatedAt: body.estimatedAt, actualAt: body.actualAt,
locationCode: body.locationCode, locationName: body.locationName, sourceReference: `MANUAL:${CUSTOMER_ID}`,
rawPayloadHash: 'c'.repeat(64), createdAt: body.observedAt,
})
task.version += 1
if (body.actualAt != null) {
task.latestActualNode = body.standardNode; task.latestActualAt = body.actualAt
if (body.standardNode === 'EMPTY_RETURNED') {
task.status = 'STOPPED'; task.stopReason = '已还柜'; task.stoppedAt = body.observedAt
} else task.status = 'READY'
}
histories.push({ id: String(nextId++), action: 'MANUAL_NODE', fromVersion: task.version - 1,
2026-08-24 23:35:26 +08:00
toVersion: task.version, reason: body.reason, operatorId: '1000001', operatorName: 'fixture',
2026-08-24 19:44:28 +08:00
createdAt: body.observedAt })
const saved = detail(); idempotency.set(key, { signature, detail: clone(saved) })
return ok(saved, `req-${key}`)
},
apiSuccess: (_module, _name, response) => {
assert.equal(response.http, 200); assert.equal(response.body.code, '200'); return response.body.data
},
2026-08-26 15:58:54 +08:00
assert: (_module, name, response, condition, evidence, options) => {
assertions.push({ name, passed: Boolean(condition), evidence, options, requestId: response?.requestId || null })
assert.ok(condition, `${name}: ${evidence}`)
},
2026-08-24 19:44:28 +08:00
addStep: (_module, name, response, passed, evidence, options) => {
steps.push({ name, passed, evidence, options, requestId: response?.requestId || null })
assert.ok(passed, `${name}: ${evidence}`)
},
}
2026-08-26 15:58:54 +08:00
return { context, task, nodes, exceptions, histories, steps, assertions }
2026-08-24 19:44:28 +08:00
}
test('marker-owned chain covers idempotency conflicts, all actual nodes, exception DTO and empty-return stop', async () => {
const fixture = markerOwnedContext()
await run(fixture.context)
const posts = fixture.context.calls.filter((item) => item.method === 'POST')
2026-08-26 15:58:54 +08:00
assert.equal(posts.length, 17)
2026-08-24 19:44:28 +08:00
assert.ok(posts.every((item) => item.path === `${BASE}/${QUERY_ID}/manual-nodes`))
assert.ok(posts.every((item) => item.headers['Idempotency-Key']))
assert.ok(posts.every((item) => Object.keys(item.body).length === 8))
2026-08-26 15:58:54 +08:00
assert.equal(fixture.steps.filter((item) => /A0409/.test(item.name)).length, 6)
assert.ok(fixture.assertions.some((item) => /重复当前实际节点A0409后task、node、history零漂移/.test(item.name)))
assert.ok(fixture.assertions.some((item) => /更早实际节点A0409后task、node、history零漂移/.test(item.name)))
assert.ok(fixture.steps.some((item) => /同级actual失败请求同键重试.*operation claim零残留/.test(item.name)))
assert.ok(fixture.steps.some((item) => /更早actual失败请求同键重试.*operation claim零残留/.test(item.name)))
2026-08-24 19:44:28 +08:00
assert.equal(fixture.task.status, 'STOPPED')
assert.equal(fixture.task.latestActualNode, 'EMPTY_RETURNED')
assert.equal(fixture.task.stopReason, '已还柜')
const actualNodes = new Set(fixture.nodes.filter((item) => item.actualAt != null).map((item) => item.standardNode))
assert.deepEqual([...actualNodes].sort(), [...STANDARD_NODES].sort())
assert.equal(fixture.exceptions[0].exceptionCode, 'CUSTOMS_HOLD')
assert.ok(fixture.nodes.every((item) => /^\d{16,}$/.test(item.id)))
assert.equal(fixture.context.calls.some((item) => /attempts|scheduler|internal|\/stop/.test(item.path)), false)
const firstPageQuery = fixture.context.calls.find((item) => item.path === `${BASE}?page=1&size=20`)
assert.ok(firstPageQuery)
2026-08-21 17:58:52 +08:00
})