This commit is contained in:
2026-10-20 16:45:04 +08:00
parent 0ff1eefff6
commit 0dd9c8db07
44 changed files with 889 additions and 93 deletions
@@ -1,5 +1,8 @@
import assert from 'node:assert/strict'
import { verifyFleetCrossCustomer } from './fleet-cross-customer-acceptance.mjs'
import { run as createQualifiedMerchant } from './merchant-qualification-fixture.mjs'
import { nativeRelabelCreateBody } from '../overseas-relabel-real-acceptance.mjs'
import { finishFleetTrip } from './fleet-trip-fulfillment.mjs'
const ROOT = '/api/platform/v1/last-leg', MODULE = 'dispatch-workflow-extensions'
const OPTIONS = { scenario: MODULE, deploymentBlocker: true }
@@ -8,7 +11,7 @@ const id = value => String(value ?? '')
export const extensionMatrix = Object.freeze([
{ scenario: 'dual-destination', scope: 'Two fresh customers, two distinct real FBA destinations, one main/trip; distinct fee inputs and isolated execution documents', readiness: 'READY' },
{ scenario: 'reviews', scope: 'Both rejection/resubmission rounds, zero-pick return and cargo/resource changes, stale/version/idempotency conflicts', readiness: 'READY' },
{ scenario: 'relabel', scope: 'Confirmed relabel cancellation/rearrangement and multiple applications sharing one physical pallet', readiness: 'REQUIRES_FORMAL_RELABEL_FIXTURE' },
{ scenario: 'relabel', scope: 'Fresh three-box customer receipt, confirmed zero-scan cancellation, two applications sharing one pallet and native rearrangement', readiness: 'READY_FORMAL_THREE_BOX_RECEIPT' },
{ scenario: 'competition', scope: 'Two-request Admin/PDA replay race, occupied resources and unarranged departure gates; first-execution race remains untested', readiness: 'READY_BOUNDED_REPLAY' },
{ scenario: 'bol', scope: 'Fresh same-destination cargo, empty/same/different formal appointment allocations and actual PDF conservation', readiness: 'READY_FORMAL_APPOINTMENTS' },
])
@@ -87,7 +90,7 @@ export async function verifyDualDestination(context, fixture, options) {
dispatchNo: fixture.dispatchNo, status: 'CHECKING', syntheticTestMaterials: true, physicalMeasurementVerified: false,
hardwareVerified: false, midTransactionRollback: 'NOT_TESTED_NO_CONTROLLED_INJECTION', expectedFees: {}, isolation: [] }
const original = context.request
let arrangement, deferredFailure, raceDone = false, unarrangedDone = false
let arrangement, deferredFailure, raceDone = false, firstRaceDone = false, unarrangedDone = false
const mainPath = `${ROOT}/dispatches/${encodeURIComponent(fixture.dispatchNo)}`
const pdaPath = `/api/pda/v1/last-leg/dispatches/${encodeURIComponent(fixture.dispatchNo)}`
context.request = async function (method, path, body, ...rest) {
@@ -96,11 +99,18 @@ export async function verifyDualDestination(context, fixture, options) {
proof.expectedFees = applyIndependentFees(body, arrangement?.groups, fixture.members, context.marker)
proof.arrangeRequest = clone(body); await context.checkpoint()
}
const response = await original.call(this, method, path, body, ...rest)
let response
if (options.firstCompetition && !firstRaceDone && method === 'POST' && path === `${pdaPath}/loading-complete`
&& fixture.tripProof.loadingCommand?.body?.idempotencyKey === body?.idempotencyKey) {
firstRaceDone = true
const outcome = await executeFirstLoadingRace(context, fixture, options, original.bind(this), body)
response = outcome.pdaResponse
if (outcome.error) deferredFailure = outcome.error
} else response = await original.call(this, method, path, body, ...rest)
if (method === 'GET' && path === `${ROOT}/dispatches/${encodeURIComponent(fixture.dispatchNo)}/delivery-arrangement`
&& response.http === 200 && String(response.body?.code) === '200') arrangement = clone(response.body.data)
// 写请求已收到确定回执后,只做独立扩展;后续核验失败延至下一读请求抛出,不能把已知成功伪报成未知写。
if (response.http === 200 && String(response.body?.code) === '200') {
if (!deferredFailure && response.http === 200 && String(response.body?.code) === '200') {
try {
if (options.competition && method === 'POST' && path === `${pdaPath}/loading-complete` && !raceDone
&& response.body.data?.replayed !== true && response.body.data?.stage === 'AFTER_LOADING') {
@@ -206,6 +216,49 @@ export async function verifyLoadingReplayRace(context, fixture, options, send, b
race.status = 'VERIFIED'; await context.checkpoint()
}
/** 首次命令使用两个不同键和同一真实版本;胜者必须唯一,真实PDA回执原样交还调用者。 */
export async function executeFirstLoadingRace(context, fixture, options, send, body) {
const proof = context.createdResources.dispatchWorkflowCompetition
assert(proof && proof.status === 'CHECKING')
const adminBody = { ...clone(body), idempotencyKey: `${context.marker}-EXT-FIRST-ADMIN-LOAD` }
const race = proof.firstLoadingRace = { status: 'INTENT', pdaBody: clone(body), adminBody,
before: await competitionSnapshot(context, fixture, options, send) }
assert.equal(race.before.main.stage, 'LOADING'); assert.equal(Number(race.before.main.counts.pickedPackageCount), 2)
assert.equal(id(race.before.main.recordVersion), id(body.recordVersion)); await context.checkpoint()
const results = await Promise.allSettled([
send('POST', `/api/pda/v1/last-leg/dispatches/${encodeURIComponent(fixture.dispatchNo)}/loading-complete`, clone(body), fixture.pdaToken),
send('POST', `${ROOT}/dispatches/${encodeURIComponent(fixture.dispatchNo)}/loading-complete`, adminBody),
])
race.responses = results.map(result => result.status === 'fulfilled' ? receipt(result.value) : { outcome: 'UNKNOWN_RESULT' })
race.status = results.every(result => result.status === 'fulfilled') ? 'RESPONDED' : 'UNKNOWN_RESULT'; await context.checkpoint()
for (const result of results) if (result.status === 'rejected') throw result.reason
const responses = results.map(result => result.value)
try {
const winnerIndexes = responses.map((response, index) => String(response.body?.code) === '200' ? index : -1).filter(index => index >= 0)
assert.equal(winnerIndexes.length, 1)
const winnerIndex = winnerIndexes[0], winner = responses[winnerIndex], loser = responses[1 - winnerIndex]
assert.equal(String(loser.body?.code), 'A0409')
assert.equal(winner.body.data.stage, 'AFTER_LOADING')
assert.equal(winner.body.data.result?.confirmedLoad?.manifestHash, body.manifestHash)
assert.equal(BigInt(winner.body.data.recordVersion), BigInt(body.recordVersion) + 1n)
race.after = await competitionSnapshot(context, fixture, options, send)
assert.equal(race.after.main.stage, 'AFTER_LOADING')
assert.equal(id(race.after.main.recordVersion), id(winner.body.data.recordVersion))
assert.deepEqual(race.after.stock, race.before.stock)
assert.equal(Number(race.after.main.counts.packageCount), 2)
assert.equal(Number(race.after.main.counts.pickedPackageCount), 2)
race.winner = winnerIndex === 0 ? 'PDA' : 'ADMIN'; race.winnerResult = clone(winner.body.data)
race.status = 'VERIFIED'; proof.firstExecutionRace = 'VERIFIED'
context.assert(MODULE, 'First valid Admin/PDA loading race commits exactly one version and preserves complete inventories', winner, true, '', OPTIONS)
await context.checkpoint()
if (winnerIndex !== 0) return { pdaResponse: responses[0], error: Error('Admin won the first loading race; original PDA rejection retained, no fulfillment replay') }
return { pdaResponse: responses[0] }
} catch (error) {
race.verificationError = error.message; await context.checkpoint()
return { pdaResponse: responses[0], error }
}
}
async function verifyUnarrangedDeparture(context, fixture, options, send, arrangement) {
const proof = context.createdResources.dispatchWorkflowCompetition
const state = proof.unarrangedDeparture = { status: 'INTENT', before: await competitionSnapshot(context, fixture, options, send),
@@ -239,9 +292,13 @@ export async function verifyCompetitionExtension(context, fixture, options) {
proof.resourceConflict.status = 'VERIFIED'
const verified = await verifyDualDestination(context, fixture, { ...options, competition: true })
assert.equal(proof.loadingReplayRace?.status, 'VERIFIED'); assert.equal(proof.unarrangedDeparture?.status, 'VERIFIED')
proof.status = 'VERIFIED_BOUNDED_SCOPE'; await context.checkpoint(); return verified
if (options.firstCompetition) assert.equal(proof.firstLoadingRace?.status, 'VERIFIED')
proof.status = options.firstCompetition ? 'VERIFIED_FIRST_EXECUTION_AND_REPLAY' : 'VERIFIED_BOUNDED_SCOPE'
await context.checkpoint(); return verified
}
export const verifyFirstCompetitionExtension = (context, fixture, options) => verifyCompetitionExtension(context, fixture, { ...options, firstCompetition: true })
/** 仅使用本轮PDA实收的一箱来源,正式创建预约并向原生建单返回实际份额。 */
export async function prepareBolAppointments(context, members, scenario, warehouseId) {
assert(['bol-empty', 'bol-same', 'bol-different'].includes(scenario))
@@ -427,6 +484,261 @@ export async function verifyReviewExtension(context, fixture, options) {
return verifyDualDestination(context, fixture, options)
}
export function assertConfirmedRelabelCancellation(before, after, outbound, stockBefore, stockAfter) {
assert.equal(before.application.status, 'READY_FOR_OUTBOUND')
assert(before.application.customerConfirmedAt && before.application.outboundOrderNo)
assert.equal(after.application.relabelNo, before.application.relabelNo)
assert.equal(after.application.customerConfirmedAt, before.application.customerConfirmedAt)
assert.equal(after.application.status, 'READY_FOR_OUTBOUND')
assert.equal(after.application.deliveryMethod, before.application.deliveryMethod)
assert.equal(after.application.outboundOrderNo ?? null, null)
assert.equal(after.application.fulfillmentStatus, 'WAIT_OUTBOUND_CREATION')
assert.deepEqual(after.items, before.items)
assert.equal(outbound.outbound.status, 'CANCELLED')
assert.equal(outbound.outbound.outboundNo, before.application.outboundOrderNo)
assert.deepEqual(stockAfter, stockBefore, 'Zero-scan cancellation preserves all completed relabel stock and immutable ledger rows')
}
/** 独立第三客户三箱正式实收;不改变正常链两个客户的一箱库存基线。 */
export async function exerciseRelabelExtensions(context, fixture, { readInventory }) {
const proof = context.createdResources.dispatchWorkflowRelabel = { marker: context.marker, status: 'PREPARING',
syntheticTestMaterials: true, hardwareVerified: false, physicalMeasurementVerified: false,
scenarios: [], sharedDispatches: [], nonTruckRearrangement: 'NOT_TESTED_NO_FORMAL_PUBLIC_ENTRY' }
const key = label => `${context.marker}-RL-${label}`
const api = async (method, path, body, token) => {
const response = await context.request(method, path, body, token)
const data = context.apiSuccess(MODULE, 'Formal relabel extension HTTP', response, '', OPTIONS)
assert.equal(response.http, 200); assert.equal(String(response.body?.code), '200'); return data
}
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aH1kAAAAASUVORK5CYII=', 'base64')
const upload = async (path, name) => {
const response = await context.requestMultipart('POST', path, { name, type: 'image/png', content: png }, fixture.pdaToken)
const data = context.apiSuccess(MODULE, 'Upload explicitly synthetic TEST relabel evidence', response, '', OPTIONS)
assert.equal(String(response.body?.code), '200'); assert(data?.fileId); return id(data.fileId)
}
const master = await api('GET', `/api/platform/v1/warehouse-admin/${encodeURIComponent(fixture.members[0].destination.warehouseId)}?tenantId=0`)
const address = master.addresses?.find(row => row.addressLine1)
assert(address && master.warehouse?.status === 'ACTIVE')
const child = Object.create(context)
child.marker = `${context.marker}-RELABEL`; child.options = { ...context.options, customerName: `TEST换标扩展-${context.marker.slice(-12)}` }
child.context = {}; child.createdResources = {}
child.request = async (...args) => context.request(...args)
await createQualifiedMerchant(child, { publishEnvironment: false })
const credentials = child.context.merchantQualificationFixture
assert(credentials?.tenantId && credentials.marker === child.marker)
proof.customerId = id(credentials.tenantId); proof.qualification = clone(child.createdResources.merchantQualificationFixture)
let session
try { session = await api('POST', '/api/auth/login', { loginId: credentials.username, password: credentials.password }, '') }
finally { delete child.context.merchantQualificationFixture }
assert(session?.accessToken && session.refreshToken)
const merchantToken = session.accessToken, customerId = proof.customerId
const stock = () => readInventory({ marker: context.marker, customerId, warehouseId: fixture.warehouseId })
try {
const profile = await api('GET', '/api/merchant/v1/iam/tenant/profile', undefined, merchantToken)
assert.equal(id(profile.id), customerId)
const skuCode = `RL-${context.marker.slice(-12)}`
const merchantRoot = '/api/merchant/v1/last-leg/warehouse-transfers'
const create = { sourceLastlegOrderIds: [], operatingWarehouseId: fixture.warehouseId,
fbaWarehouseCode: master.warehouse.warehouseCode, destinationType: 'FBA', destinationWarehouseId: id(master.warehouse.id),
destinationWarehouseCode: master.warehouse.warehouseCode, destinationWarehouseName: master.warehouse.warehouseName,
deliveryAddress: [address.countryCode, address.stateProvince, address.city, address.addressLine1, address.postalCode].filter(Boolean).join(' '),
packageCount: 3, volumeCbm: 3, deliveryMethod: 'CUSTOMER_DELIVERY', estimatedArrivalAt: new Date(Date.now() + 3600000).toISOString().slice(0, 19),
needRelabel: false, remark: `${context.marker} TEST三箱换标独立来货`, idempotencyKey: key('RECEIPT-CREATE'),
items: [{ skuCode, productNameZh: 'TEST三箱换标货物', packageCount: 3, quantity: 3 }] }
proof.receiptCreate = clone(create); await context.checkpoint()
let incoming = await api('POST', merchantRoot, create, merchantToken)
proof.incomingNo = incoming.transferNo; assert(proof.incomingNo)
const merchantPath = `${merchantRoot}/${encodeURIComponent(proof.incomingNo)}`
incoming = await api('POST', `${merchantPath}/submit`, undefined, merchantToken)
incoming = await api('POST', `${ROOT}/warehouse-transfers/${encodeURIComponent(proof.incomingNo)}/review?customerId=${customerId}`,
{ decision: 'APPROVE', remark: `${context.marker} TEST三箱独立实收` })
assert.equal(incoming.status, 'WAIT_PDA_RECEIVING')
const pda = `/api/pda/v1/last-leg/warehouse-transfers/${encodeURIComponent(proof.incomingNo)}`
const task = await api('GET', pda, undefined, fixture.pdaToken)
assert.equal(Number(task.packageCount), 3); assert.equal(task.items.length, 1); assert.equal(task.cartons.length, 3)
assert.equal(task.items[0].skuCode, skuCode); assert.equal(Number(task.items[0].quantity), 3)
assert.equal(new Set(task.cartons.map(row => row.cartonMark)).size, 3)
const draft = await api('POST', `${pda}/pallets/drafts`, { idempotencyKey: key('DRAFT') }, fixture.pdaToken)
assert.equal(draft.pallets.length, 1)
const palletPath = `${pda}/pallets/${encodeURIComponent(draft.pallets[0].id)}`
const generated = await api('POST', `${palletPath}/generate`, { idempotencyKey: key('GENERATE') }, fixture.pdaToken)
const pallet = generated.pallets[0]; assert(pallet.warehousePalletId && pallet.palletNo)
await api('POST', `${palletPath}/bind`, { palletCode: pallet.palletNo, idempotencyKey: key('BIND') }, fixture.pdaToken)
const counted = await api('POST', `${pda}/cartons/count`, { forecastPackageCount: 3, idempotencyKey: key('COUNT'),
boxes: task.cartons.map(carton => ({ cartonMark: carton.cartonMark, transferItemId: id(task.items[0].id), transferPalletId: id(draft.pallets[0].id),
length: 100, width: 100, height: 100, weight: 100, items: [{ skuCode, quantity: 1 }] })) }, fixture.pdaToken)
assert.equal(counted.cartons.length, 3); assert(counted.cartons.every(row => row.status === 'COUNTED' && Number(row.quantity) === 1))
assert.equal(Number(counted.pallets[0].cartonCount), 3); assert.equal(Number(counted.pallets[0].grossWeightKg), 300)
const photoId = await upload(`${pda}/measurement-photos/files`, `${context.marker}-TEST-three-boxes.png`)
incoming = await api('POST', `${pda}/palletize`, { idempotencyKey: key('PALLETIZE'), photoFileIds: [photoId] }, fixture.pdaToken)
assert.equal(incoming.status, 'WAIT_CUSTOMER_CONFIRMATION')
incoming = await api('POST', `${merchantPath}/confirm-measurement`, { idempotencyKey: key('CONFIRM-RECEIPT'), remark: context.marker }, merchantToken)
assert.equal(incoming.status, 'READY_FOR_DISPATCH')
proof.receipt = await stock()
assert.equal(proof.receipt.balances.length, 1); assert.equal(proof.receipt.positions.length, 1); assert.equal(proof.receipt.ledger.length, 1)
assert.equal(Number(proof.receipt.balances[0].availablePackages), 3)
assert.equal(id(proof.receipt.positions[0].palletId), id(pallet.warehousePalletId))
const candidates = await api('GET', `/api/merchant/v1/last-leg/relabel-applications/inventory-candidates?operationWarehouseId=${fixture.warehouseId}`, undefined, merchantToken)
const sources = candidates.filter(row => id(row.inventoryBalanceId) === id(proof.receipt.balances[0].id) && row.inboundCode === proof.incomingNo)
assert.equal(sources.length, 1); const source = sources[0]
const positions = source.positions.filter(row => id(row.positionId) === id(proof.receipt.positions[0].id))
assert.equal(positions.length, 1); assert.equal(Number(positions[0].availablePackages), 3)
const resolve = code => api('POST', '/api/pda/v1/last-leg/pallet-operations/pallets/resolve', { code }, fixture.pdaToken)
let sharedTarget
for (const [index, method] of ['TRUCK', 'TRUCK', 'PICKUP'].entries()) {
const name = `${method}-${index + 1}`, scenario = { name, operationType: 'CARTON_LABEL', deliveryMethod: method }
proof.scenarios.push(scenario)
const item = { sourceInventoryBalanceId: id(source.inventoryBalanceId), sourceInventoryPositionId: id(positions[0].positionId),
sourceInboundOrderId: id(source.inboundOrderId), skuCode, productNameZh: 'TEST三箱换标货物', totalPackageCount: 1, notifiedPackageCount: 1,
shipmentNo: `TEST-RL-${context.marker.slice(-12)}-${index + 1}`, cartonMark: task.cartons[index].cartonMark,
fbaCartonMark: `TEST-NEW-${context.marker.slice(-12)}-${index + 1}`, destinationFbaWarehouseCode: master.warehouse.warehouseCode,
operationType: 'CARTON_LABEL', skuItems: [], labelRequirement: `${context.marker} TEST换标成果` }
scenario.createBody = { customerOrderNo: `TEST-${context.marker.slice(-12)}-${name}`, operationWarehouseId: fixture.warehouseId,
labelDeadline: new Date(Date.now() + 7 * 86400000).toISOString().slice(0, 19), contactName: 'TEST换标验收', contactPhone: '19900000000',
remark: context.marker, idempotencyKey: key(`${name}-CREATE`), deliveryMethod: method, printShippingLabel: false, items: [item] }
await context.checkpoint()
const created = await api('POST', `${ROOT}/relabel-applications?customerId=${customerId}`, scenario.createBody)
scenario.relabelNo = created.application.relabelNo; assert(scenario.relabelNo)
assert.equal(created.application.status, 'PENDING_REVIEW')
assert(created.application.lastlegOrderId)
const approved = await api('PUT', `${ROOT}/orders/${encodeURIComponent(created.application.lastlegOrderId)}/relabel-review?customerId=${customerId}`,
{ status: 'PENDING_PROCESSING', remark: `${context.marker} TEST正式审核后允许PDA作业` })
assert.equal(approved.application.status, 'PENDING_PROCESSING'); scenario.approved = clone(approved)
const taskRoot = `/api/pda/v1/last-leg/relabel-tasks/${encodeURIComponent(scenario.relabelNo)}`
let detail = await api('POST', `${taskRoot}/claim`, { idempotencyKey: key(`${name}-CLAIM`) }, fixture.pdaToken)
assert.equal(detail.items.length, 1)
detail = await api('POST', `${taskRoot}/units`, { itemId: id(detail.items[0].itemId), oldLabel: item.cartonMark, newLabel: item.fbaCartonMark,
skuVerifications: [], expectedVersion: detail.version, idempotencyKey: key(`${name}-SCAN`) }, fixture.pdaToken)
let target
if (index === 1) target = sharedTarget
else target = await api('POST', '/api/pda/v1/last-leg/pallet-operations/relabel-pallet-label', { relabelNo: scenario.relabelNo,
idempotencyKey: key(`${name}-LABEL`) }, fixture.pdaToken)
assert(target?.palletId && target.palletCode); if (index === 0) sharedTarget = target
const from = await resolve(pallet.palletNo), to = await resolve(target.palletCode)
await api('POST', '/api/pda/v1/last-leg/pallet-operations/relabel-disassemble', { relabelNo: scenario.relabelNo,
idempotencyKey: key(`${name}-MOVE`), source: { palletCode: from.palletCode, expectedVersion: from.palletVersion },
target: { palletCode: to.palletCode, expectedVersion: to.palletVersion }, cartonMarks: [item.cartonMark], reason: `${context.marker} TEST实际箱移绑` }, fixture.pdaToken)
scenario.targets = [clone(target)]
const fileId = await upload(`${taskRoot}/photos/files`, `${context.marker}-${name}-TEST.png`)
detail = await api('POST', `${taskRoot}/complete`, { photoFileIds: [fileId], expectedVersion: detail.version,
idempotencyKey: key(`${name}-COMPLETE`), remark: context.marker }, fixture.pdaToken)
assert.equal(detail.applicationStatus, 'CUSTOMER_CONFIRM_PENDING')
const confirmed = await api('POST', `/api/merchant/v1/last-leg/relabel-applications/${encodeURIComponent(scenario.relabelNo)}/confirm-completion`,
{ idempotencyKey: key(`${name}-CONFIRM`), remark: context.marker }, merchantToken)
assert.equal(confirmed.application.status, 'READY_FOR_OUTBOUND'); assert(confirmed.application.customerConfirmedAt)
scenario.confirmed = clone(confirmed); scenario.items = clone(confirmed.items); scenario.relabelVerified = true
scenario.destinationFbaWarehouseCode = master.warehouse.warehouseCode
await context.checkpoint()
}
proof.sharedPhysical = await resolve(sharedTarget.palletCode)
assert.equal(Number(proof.sharedPhysical.totalPackages), 2)
const pickup = proof.scenarios[2], relabelPath = `${ROOT}/relabel-applications/${encodeURIComponent(pickup.relabelNo)}`
const before = await api('GET', relabelPath), stockBefore = await stock()
assert.equal(before.application.fulfillmentStatus, 'OUTBOUND_CREATED'); assert(before.application.outboundOrderNo)
const outboundPath = `${ROOT}/outbound-orders/${encodeURIComponent(before.application.outboundOrderNo)}`
const outboundBefore = await api('GET', outboundPath)
assert(['WAIT_PICK', 'WAIT_OUTBOUND'].includes(outboundBefore.outbound.status))
proof.cancel = { status: 'INTENT', before, stockBefore, outboundBefore, body: { reason: `${context.marker} TEST已确认换标零扫码撤销本次出库安排` } }
await context.checkpoint()
await api('POST', `${outboundPath}/cancel`, proof.cancel.body)
const after = await api('GET', relabelPath), outboundAfter = await api('GET', outboundPath), stockAfter = await stock()
Object.assign(proof.cancel, { after, outboundAfter, stockAfter })
assertConfirmedRelabelCancellation(before, after, outboundAfter, stockBefore, stockAfter)
proof.cancel.status = 'VERIFIED'; await context.checkpoint()
context.assert(MODULE, 'Confirmed relabel zero-scan outbound cancellation preserves completed items, customer confirmation and all raw stock', null, true, '', OPTIONS)
await verifyRelabelSharedDispatches(context, fixture, { readInventory }, proof)
return proof
} finally {
await api('POST', '/api/auth/logout', { refreshToken: session.refreshToken }, merchantToken)
proof.ownedMerchantSessionClosed = true; await context.checkpoint()
}
}
export async function verifyRelabelSharedDispatches(context, fixture, { readInventory }, proof) {
const customerId = proof.customerId, truck = proof.scenarios.slice(0, 2)
const stock = () => readInventory({ marker: context.marker, customerId, warehouseId: fixture.warehouseId })
const api = async (method, path, body) => {
const response = await context.request(method, path, body)
const data = context.apiSuccess(MODULE, 'Exact owned relabel shared physical selection', response, '', OPTIONS)
assert.equal(String(response.body?.code), '200'); return data
}
assert.equal(proof.cancel.status, 'VERIFIED'); assert.equal(truck.length, 2)
assert(truck.every(row => row.relabelVerified && row.deliveryMethod === 'TRUCK'))
proof.status = 'CHECKING_SHARED_NATIVE'
for (const round of [1, 2]) {
const byKey = new Map()
for (const scenario of truck) {
const page = await api('GET', `${ROOT}/dispatches/candidates?${new URLSearchParams({ warehouseId: fixture.warehouseId,
sourceStage: 'RELABEL', orderNo: scenario.relabelNo })}`)
assert.equal(page.complete, true)
for (const row of page.candidates) {
assert(truck.some(item => item.relabelNo === row.selection?.relabelNo))
const prior = byKey.get(row.sourceKey)
if (prior) assert.deepEqual(prior, row)
byKey.set(row.sourceKey, row)
}
}
const rows = [...byKey.values()]
assert.equal(rows.length, 2); assert.equal(new Set(rows.map(row => id(row.selection.warehousePalletId))).size, 1)
const createBody = nativeRelabelCreateBody(`${context.marker}-ROUND-${round}`, truck, rows, customerId, fixture.warehouseId)
const run = { round, status: 'INTENT', createBody, stockBefore: await stock() }; proof.sharedDispatches.push(run); await context.checkpoint()
run.result = await api('POST', `${ROOT}/dispatches`, createBody)
assert(run.result.dispatchNo)
const path = `${ROOT}/dispatches/${encodeURIComponent(run.result.dispatchNo)}`
run.detail = await api('GET', path); run.items = await api('GET', `${path}/items`)
assert.equal(Number(run.detail.counts.packageCount), 2); assert.equal(Number(run.detail.counts.palletCount), 1)
assert.equal(Number(run.detail.counts.pickedPackageCount), 0); assert.equal(run.items.items.length, 2)
assert.equal(new Set(run.items.items.map(row => id(row.warehousePalletId))).size, 1)
assert(run.items.items.every(row => id(row.customerId) === customerId && Number(row.scheduledPackages) === 1))
run.cancelBody = { recordVersion: run.detail.recordVersion, idempotencyKey: `${context.marker}-RL-SHARED-${round}-CANCEL`, reason: `${context.marker} TEST零扫码验证后撤销安排保留换标成果` }
await context.checkpoint(); run.cancelled = await api('POST', `${path}/cancel`, run.cancelBody)
assert.equal(run.cancelled.status, 'CANCELLED'); run.stockAfter = await stock(); assert.deepEqual(run.stockAfter, run.stockBefore)
for (const scenario of truck) {
const current = await api('GET', `${ROOT}/relabel-applications/${encodeURIComponent(scenario.relabelNo)}`)
assert.equal(current.application.status, 'READY_FOR_OUTBOUND'); assert.equal(current.application.customerConfirmedAt, scenario.confirmed.application.customerConfirmedAt)
assert.deepEqual(current.items, scenario.confirmed.items)
}
run.status = 'VERIFIED'; await context.checkpoint()
}
assert.notEqual(proof.sharedDispatches[0].result.dispatchNo, proof.sharedDispatches[1].result.dispatchNo)
context.assert(MODULE, 'Two confirmed applications share one actual pallet without double counting and can be natively rearranged after zero-pick cancellation', null, true, '', OPTIONS)
proof.status = 'VERIFIED_WITH_NON_TRUCK_REARRANGEMENT_GAP'; await context.checkpoint(); return proof
}
export async function reconcileRelabelShared(context, fixture, options, prior) {
const proof = context.createdResources.dispatchWorkflowRelabel = clone(prior.createdResources.dispatchWorkflowRelabel)
assert.equal(proof.sharedDispatches.length, 0); assert.equal(proof.cancel.status, 'VERIFIED')
assert(proof.scenarios.every(row => row.relabelVerified === true))
const read = async path => {
const response = await context.request('GET', path)
assert.equal(String(response.body?.code), '200'); return response.body.data
}
const main = await read(`${ROOT}/dispatches/${encodeURIComponent(fixture.dispatchNo)}`)
const trip = await read(`${ROOT}/fleet/trips/${encodeURIComponent(fixture.tripNo)}`)
assert.equal(main.stage, 'DELIVERED'); assert.equal(trip.trip.status, 'COMPLETED')
assert(trip.trip.vehicleRelease && trip.trip.driverRelease)
const currentStock = await options.readInventory({ marker: context.marker, customerId: proof.customerId, warehouseId: fixture.warehouseId })
assert.deepEqual(currentStock, proof.cancel.stockAfter)
for (const scenario of proof.scenarios) {
const current = await read(`${ROOT}/relabel-applications/${encodeURIComponent(scenario.relabelNo)}`)
assert.equal(current.application.status, 'READY_FOR_OUTBOUND'); assert.equal(current.application.customerConfirmedAt, scenario.confirmed.application.customerConfirmedAt)
assert.deepEqual(current.items, scenario.confirmed.items)
}
await verifyRelabelSharedDispatches(context, fixture, options, proof)
context.createdResources.fleetCrossCustomer = clone(prior.createdResources.fleetCrossCustomer)
return context.createdResources.fleetCrossCustomer
}
export async function verifyRelabelExtension(context, fixture, options) {
const verified = await verifyDualDestination(context, fixture, options)
try { await exerciseRelabelExtensions(context, fixture, options) }
catch (error) {
if (!context.createdResources.fleetWriteBoundary && !fixture.tripProof.closure) await finishFleetTrip(context, MODULE, fixture.tripProof)
throw error
}
return verified
}
/** Read-only terminal reconciliation after the known sequential-read completion race; never replay fulfillment. */
export async function reconcileReviewTerminal(context, fixture, { readInventory }, prior) {
assert.equal(prior.success, false)