2026-10-18 19:21:12 +08:00
import { randomUUID , createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
const BASE = '/api/platform/v1/last-leg'
const id = value => value == null ? '' : String ( value )
const same = ( a , b ) => JSON . stringify ( a ) === JSON . stringify ( b )
const must = ( value , reason ) => { if ( ! value ) throw Error ( reason ) }
const success = r => r ? . http === 200 && String ( r ? . body ? . code ) === '200'
const rejected = r => [ 400 , 409 , 422 ]. includes ( r ? . http )
|| r ? . http === 200 && [ 'A0400' , 'A0409' , 'A0422' ]. includes ( String ( r ? . body ? . code ))
const key = () => `dispatch-repair- ${ randomUUID () } `
const scope = ( path , customerId ) => ` ${ path } ? ${ new URLSearchParams ({ customerId } )}`
const cases = [ 'cancellation' , 'departedGate' , 'wholeRelabel' , 'mixedSources' , 'receiptRefresh' , 'nativeCartonReturn' , 'permissions' ]
/** The allowlist is derived from successful producer API receipts, never from fixture ownership flags. */
async function loadProducerResources ( context ) {
must ( context . producerEvidence ? . path && /^[a-f0-9]{64}$/ . test ( context . producerEvidence ? . sha256 || '' ), 'Hashed current-run producer evidence required' )
const bytes = await readFile ( context . producerEvidence . path )
must ( createHash ( 'sha256' ). update ( bytes ). digest ( 'hex' ) === context . producerEvidence . sha256 , 'Producer evidence hash mismatch' )
const report = JSON . parse ( bytes . toString ( 'utf8' ))
must ( report . environment === 'TEST' && report . marker === context . marker && report . sourceCommit === context . release . lastlegCommit
&& Array . isArray ( report . requests ), 'Producer report run/environment/release mismatch' )
const own = Object . fromEntries ([ 'transfer' , 'inbound' , 'candidate' , 'dispatch' , 'outbound' , 'delivery' , 'relabel' , 'trip' , 'booking' , 'return' , 'carton' , 'pallet' ]. map ( k => [ k , new Map ()]))
const actors = new Map ()
function add ( kind , key , customerId , warehouseId , event , extra = {}) {
must ( key && warehouseId , `Producer ${ kind } response lacks identity/warehouse` )
const previous = own [ kind ]. get ( id ( key ))
if ( previous ) must ( id ( previous . customerId ) === id ( customerId ) && id ( previous . warehouseId ) === id ( warehouseId ), 'Producer resource scope drifted' )
own [ kind ]. set ( id ( key ), { ... previous , ... extra , key : id ( key ), customerId : id ( customerId ), warehouseId : id ( warehouseId ),
requestId : event . requestId , traceId : event . traceId })
}
for ( const e of report . requests ) {
if ( e . status !== 'RESPONDED' || e . http !== 200 || String ( e . code ) !== '200' || ! e . requestId || ! e . traceId || ! e . result ) continue
const u = new URL ( e . path , 'https://producer.invalid' ), path = u . pathname , data = e . result
if ( e . method === 'GET' && path === '/api/merchant/v1/iam/tenant/profile' && data . id ) actors . set ( e . actor , id ( data . id ))
if ( e . method === 'POST' && path === ` ${ BASE } /warehouse-transfers` && String ( e . body ? . remark ). includes ( context . marker )) {
must ( data . operatingWarehouseId === e . body . operatingWarehouseId && u . searchParams . get ( 'customerId' ), 'Transfer birth scope mismatch' )
add ( 'transfer' , data . transferNo , u . searchParams . get ( 'customerId' ), data . operatingWarehouseId , e )
}
if ( e . method === 'POST' && path === ` ${ BASE } /fleet/trips` && String ( e . body ? . remark ). includes ( context . marker ))
add ( 'trip' , data . trip ? . tripNo , '' , data . trip ? . warehouseId , e )
let match = path . match ( /\/fleet\/trips\/([^/]+)\/bookings(?:\/([^/]+)(?:\/incoming|\/confirm|\/receipt-confirmation|\/dispatch)?)?$/ )
if ( e . method === 'POST' && match && own . trip . has ( decodeURIComponent ( match [ 1 ])) && data . booking ) {
const trip = own . trip . get ( decodeURIComponent ( match [ 1 ])), b = data . booking
if ( ! match [ 2 ] || own . booking . has ( b . bookingNo )) {
add ( 'booking' , b . bookingNo , b . customerId , trip . warehouseId , e , { tripNo : b . tripNo , booking : data . booking })
if ( b . incomingNo ) add ( 'transfer' , b . incomingNo , b . customerId , trip . warehouseId , e , { externalBookingNo : b . bookingNo })
}
}
match = path . match ( /\/warehouse-transfers\/([^/]+)(?:\/palletize|\/confirm-measurement|\/review)?$/ )
const transfer = match && own . transfer . get ( decodeURIComponent ( match [ 1 ]))
if ( transfer && data . transferNo === transfer . key && id ( data . operatingWarehouseId ) === transfer . warehouseId && data . inboundCode ) {
const pallets = data . pallets || [], received = pallets . reduce (( n , row ) => n + Number ( row . cartonCount || 0 ), 0 )
add ( 'inbound' , data . inboundCode , transfer . customerId , transfer . warehouseId , e , { receivedPackages : received ,
kind : transfer . externalBookingNo ? 'EXTERNAL' : 'ORDINARY' , externalBookingNo : transfer . externalBookingNo })
for ( const row of pallets ) if ( row . warehousePalletId ) add ( 'pallet' , row . warehousePalletId , transfer . customerId , transfer . warehouseId , e , { palletCode : row . palletNo })
if ( data . relabelNo ) add ( 'relabel' , data . relabelNo , transfer . customerId , transfer . warehouseId , e )
}
if ( e . method === 'POST' && path === '/api/merchant/v1/last-leg/relabel-applications' && actors . has ( e . actor )) {
const a = data . application
2026-10-18 19:29:35 +08:00
const customerId = actors . get ( e . actor )
must ( a && ( a . customerId === undefined || id ( a . customerId ) === customerId )
&& id ( a . overseasWarehouseId ) === id ( e . body ? . operationWarehouseId ), 'Relabel producer scope mismatch' )
// Merchant summaries omit customerId; the authenticated profile receipt supplies its scope.
add ( 'relabel' , a . relabelNo , customerId , a . overseasWarehouseId , e )
2026-10-18 19:21:12 +08:00
}
if ( e . method === 'POST' && path === '/api/merchant/v1/last-leg/return-orders' && actors . has ( e . actor )
&& String ( e . body ? . remark ). includes ( context . marker )) add ( 'return' , data . order ? . returnNo , actors . get ( e . actor ), data . order ? . overseasWarehouseId , e )
match = path . match ( /\/overseas-warehouse-resources\/([^/]+)\/pallets(?:\/([^/]+))?$/ )
if ( match && e . method === 'POST' && ! match [ 2 ] && String ( e . body ? . palletCode ). includes ( context . marker ))
add ( 'pallet' , typeof data === 'object' ? data . id : data , '' , decodeURIComponent ( match [ 1 ]), e , { palletCode : e . body . palletCode })
if ( match && e . method === 'GET' && match [ 2 ] && own . pallet . has ( decodeURIComponent ( match [ 2 ]))) {
const old = own . pallet . get ( decodeURIComponent ( match [ 2 ]))
must ( id ( data . warehouseId ) === old . warehouseId && data . palletCode === old . palletCode , 'New pallet readback drifted' )
add ( 'pallet' , old . key , old . customerId , old . warehouseId , e , { locationId : id ( data . locationId ), palletCode : data . palletCode })
}
match = path . match ( /\/overseas-warehouse-resources\/([^/]+)\/locations$/ )
if ( e . method === 'GET' && match ) for ( const pallet of own . pallet . values ()) {
if ( pallet . warehouseId !== decodeURIComponent ( match [ 1 ]) || ! pallet . locationId ) continue
const location = ( Array . isArray ( data ) ? data : data . records || []). find ( row => id ( row . id ) === pallet . locationId )
if ( location ? . locationCode ) pallet . locationCode = location . locationCode
}
match = path . match ( /\/return-inventory\/cartons\/([^/]+)$/ )
const returned = match && own . return . get ( data . sourceReturnNo )
if ( e . method === 'GET' && returned && data . cartonMark === decodeURIComponent ( match [ 1 ])) {
must ( id ( data . customerId ) === returned . customerId && id ( data . overseasWarehouseId ) === returned . warehouseId , 'New return carton scope mismatch' )
add ( 'carton' , data . cartonMark , returned . customerId , returned . warehouseId , e , { sourceReturnNo : data . sourceReturnNo ,
...( data . status !== 'OUTBOUNDED' ? { originalSkuItems : data . items } : {}) })
}
if ( e . method === 'GET' && path === ` ${ BASE } /dispatches/candidates` && Array . isArray ( data )) {
for ( const row of data ) {
const parent = row . sourceStage === 'RELABEL' ? own . relabel . get ( row . orderRefs ) : own . inbound . get ( row . inboundCode )
if ( ! parent || id ( row . customerId ) !== parent . customerId || id ( row . overseasWarehouseId ) !== parent . warehouseId ) continue
add ( 'candidate' , row . sourceStage === 'RELABEL' ? `RL: ${ row . warehousePalletId } ` : row . planPalletId , parent . customerId , parent . warehouseId , e , { candidate : row })
}
}
if ( e . method === 'POST' && path === ` ${ BASE } /dispatches/pre-arrange` ) {
const sources = ( e . body ? . planPalletIds || []). map ( value => own . candidate . get ( e . body . relabelNo ? `RL: ${ value } ` : id ( value )))
must ( sources . length && sources . every ( Boolean ) && sources . every ( row => row . customerId === sources [ 0 ]. customerId && row . warehouseId === sources [ 0 ]. warehouseId ), 'Dispatch creation lacks owned source receipts' )
must ( id ( data . overseasWarehouseId ) === sources [ 0 ]. warehouseId && same (( data . items || []). map ( row => id ( row . warehousePalletId )). sort (), sources . map ( row => id ( row . candidate . warehousePalletId )). sort ()), 'Dispatch birth response differs from producer selection' )
add ( 'dispatch' , data . dispatchNo , sources [ 0 ]. customerId , sources [ 0 ]. warehouseId , e , { dispatch : data , arrangeBody : e . body })
}
match = path . match ( /\/dispatches\/([^/]+)\/transfer-delivery$/ )
const dispatched = match && own . dispatch . get ( decodeURIComponent ( match [ 1 ]))
if ( e . method === 'POST' && dispatched && data . outboundNo && ! data . replayed ) {
add ( 'outbound' , data . outboundNo , dispatched . customerId , dispatched . warehouseId , e , { dispatchNo : dispatched . key })
for ( const row of data . deliveries || []) add ( 'delivery' , row . deliveryNo , dispatched . customerId , dispatched . warehouseId , e , { outboundNo : data . outboundNo , dispatchNo : dispatched . key })
}
match = path . match ( /\/delivery-orders\/([^/]+)\/return-inbound-options$/ )
if ( e . method === 'GET' && match && own . delivery . has ( decodeURIComponent ( match [ 1 ])) && Array . isArray ( data )) {
for ( const relation of data ) for ( const source of relation . returnSources || []) {
const carton = own . carton . get ( source . cartonMark )
if ( carton && source . returnCartonId && source . inventoryPositionId == null
&& id ( relation . customerId ) === carton . customerId && relation . deliveryNo === decodeURIComponent ( match [ 1 ])
&& relation . outboundNo === own . delivery . get ( decodeURIComponent ( match [ 1 ])). outboundNo )
add ( 'carton' , carton . key , carton . customerId , carton . warehouseId , e , { returnCartonId : id ( source . returnCartonId ), lastMileOrderId : id ( relation . lastMileOrderId ), deliveryNo : relation . deliveryNo })
}
}
}
return own
}
function requireOwned ( own , kind , key , fixture ) {
const row = own [ kind ]. get ( id ( key ))
must ( row && row . warehouseId === id ( fixture . warehouseId ) && ( ! row . customerId || row . customerId === id ( fixture . customerId )), `Unowned ${ kind } ${ id ( key ) } ; producer receipt identity/customer/warehouse mismatch` )
return row
}
function validateAllResources ( own , fixtures ) {
for ( const [ name , f ] of Object . entries ( fixtures || {})) {
must ( f . customerId && f . warehouseId , 'Fixture customer and warehouse required' )
if ( name === 'cancellation' ) {
const d = requireOwned ( own , 'dispatch' , f . dispatchNo , f )
must ( same ( d . arrangeBody . planPalletIds . map ( id ). sort (), f . rearrangeBody ? . planPalletIds ? . map ( id ). sort ()), 'Re-arrangement must reuse only the exact producer sources' )
}
if ([ 'departedGate' , 'permissions' , 'nativeCartonReturn' ]. includes ( name )) {
requireOwned ( own , 'outbound' , f . outboundNo , f )
if ( f . deliveryNo ) {
const d = requireOwned ( own , 'delivery' , f . deliveryNo , f )
must ( d . outboundNo === f . outboundNo , 'Delivery/outbound producer relation mismatch' )
}
}
if ( name === 'wholeRelabel' ) requireOwned ( own , 'relabel' , f . relabelNo , f )
if ( name === 'receiptRefresh' ) {
const b = requireOwned ( own , 'booking' , f . bookingNo , f )
must ( b . tripNo === f . tripNo , 'Booking/trip producer relation mismatch' )
for ( const row of f . measurements || []) requireOwned ( own , 'pallet' , row . warehousePalletId , f )
}
if ( name === 'mixedSources' ) {
must ( f . samples ? . length === 2 && new Set ( f . samples . map ( x => x . dispatchNo )). size === 2
&& new Set ( f . samples . map ( x => id ( x . palletId ))). size === 2 && new Set ( f . samples . map ( x => x . bookingNo )). size === 2 , 'Mixed-source samples must be independent dispatches, pallets and bookings' )
for ( const sample of f . samples ) {
requireOwned ( own , 'dispatch' , sample . dispatchNo , f ); requireOwned ( own , 'pallet' , sample . palletId , f )
const normal = requireOwned ( own , 'inbound' , sample . ordinaryInboundCode , f ), external = requireOwned ( own , 'inbound' , sample . externalInboundCode , f )
const booking = requireOwned ( own , 'booking' , sample . bookingNo , f )
must ( normal . kind === 'ORDINARY' && external . kind === 'EXTERNAL' && external . externalBookingNo === booking . key
&& normal . receivedPackages > 0 && external . receivedPackages > 0 , 'Independent ordinary/external receipt quantities required' )
}
}
if ( name === 'nativeCartonReturn' ) {
const carton = requireOwned ( own , 'carton' , f . cartonMark , f ), pallet = requireOwned ( own , 'pallet' , f . target ? . targetPalletId , f )
const delivery = own . delivery . get ( f . deliveryNo ), dispatch = own . dispatch . get ( delivery . dispatchNo )
must ( carton . returnCartonId === id ( f . returnCartonId ) && carton . lastMileOrderId === id ( f . lastMileOrderId )
&& carton . deliveryNo === f . deliveryNo && carton . originalSkuItems ? . length && dispatch . dispatch . packageCount === 1 ,
'Native carton/master must come from the owned single-carton shipment' )
must ( pallet . palletCode === f . target . targetPalletNo && pallet . locationId === id ( f . target . targetLocationId ) && pallet . locationCode === f . target . targetLocationCode , 'Return target must match the newly created physical pallet/location' )
}
}
}
/** Internal, explicit TEST-only runner. Import and plan mode never send requests. */
export async function verifyDispatchRepair ( context , fixtures , { execute = false } = {}) {
if ( ! execute ) return { status : 'PLAN_ONLY' , cases , excluded : [ 'item DELETE negative branch' , 'UI/PDA hardware' , 'external document authenticity' ] }
must ( context . environment === 'TEST' && context . release ? . lastlegHealthy && context . release ? . adminHealthy
&& context . release ? . schemaReady && /^[a-f0-9]{40}$/ . test ( context . release ? . lastlegCommit || '' ), 'Matching healthy TEST releases and schema readback required' )
must ( context . marker && typeof context . checkpoint === 'function' , 'Current run marker and durable checkpoint required' )
const own = await loadProducerResources ( context )
validateAllResources ( own , fixtures )
const proof = { marker : context . marker , release : context . release , status : 'CHECKING' , requests : [], cases : {},
externalEvidence : 'Synthetic test records only; not real appointment/POD proof' , sourceEventsVerified : false }
context . createdResources ??= {}
must ( ! context . createdResources . dispatchRepairAcceptance , 'No automatic restart of an existing acceptance run' )
context . createdResources . dispatchRepairAcceptance = proof
async function call ( method , path , body , { failure = false , file = null , cancel = false , actor = 'PLATFORM' } = {}) {
must ( method !== 'DELETE' || cancel && /^\/api\/platform\/v1\/last-leg\/dispatches\/[^/?]+$/ . test ( path ), 'Item deletion and arbitrary DELETE are excluded' )
const entry = { method , path , actor , body : body === undefined ? undefined : structuredClone ( body ), status : 'SENDING' }
if ( file ) entry . file = { name : file . name , type : file . type , size : file . content . byteLength , sha256 : createHash ( 'sha256' ). update ( file . content ). digest ( 'hex' ) }
proof . requests . push ( entry ); await context . checkpoint ()
let response
try {
if ( actor === 'READ_ONLY' ) must ( typeof context . requestReadonly === 'function' , 'Own read-only session required' )
response = file ? await context . requestMultipart ( method , path , file )
: await ( actor === 'READ_ONLY' ? context . requestReadonly : context . request ). call ( context , method , path , body )
must ( Number . isInteger ( response ? . http ) && response . http >= 200 && response . http < 500
&& response . requestId && response . traceId && response . body && typeof response . body === 'object'
&& ( success ( response ) || /^[A-Z]\d{4}$/ . test ( String ( response . body . code ))), 'Unknown transport or uncorrelated response; preserve command, do not replay' )
} catch ( error ) { entry . status = 'UNKNOWN_RESULT' ; await context . checkpoint (); throw error }
Object . assign ( entry , { status : 'RESPONDED' , http : response . http , code : response . body . code ,
requestId : response . requestId , traceId : response . traceId }); await context . checkpoint ()
must ( failure === 'FORBIDDEN' ? response . http === 403 || response . http === 200 && String ( response . body . code ) === 'A0403'
: failure ? rejected ( response ) : success ( response ), `Unexpected result: ${ method } ${ path } ` )
return response . body . data
}
const number = value => { const n = Number ( value ); must ( value != null && Number . isSafeInteger ( n ), 'Exact safe integer quantity required' ); return n }
const cents = value => { const v = String ( value ); must ( /^\d+(?:\.\d{1,2})?$/ . test ( v ), 'Exact nonnegative money value required' ); const [ a , b = '' ] = v . split ( '.' ); return BigInt ( a ) * 100 n + BigInt ( b . padEnd ( 2 , '0' )) }
async function pages ( path ) {
const rows = [], url = new URL ( path , 'https://test.invalid' )
for ( let page = 1 ; page <= 100 ; page ++ ) {
url . searchParams . set ( 'page' , String ( page )); url . searchParams . set ( 'size' , '200' )
const data = await call ( 'GET' , url . pathname + url . search )
must ( Array . isArray ( data ? . records ) && number ( data . total ) >= 0 , 'Complete paged API evidence required' )
rows . push (... data . records )
if ( rows . length === number ( data . total )) return rows
must ( rows . length < number ( data . total ) && data . records . length > 0 , 'Paged evidence has inconsistent total or missing page' )
}
throw Error ( 'Paged evidence exceeded bounded limit; not verified' )
}
async function nativeSnapshot ( f , skuCodes ) {
const stock = [], movements = []
for ( const skuCode of skuCodes ) {
const query = new URLSearchParams ({ customerId : f . customerId , overseasWarehouseId : f . warehouseId , skuCode })
const exact = row => id ( row . customerId ) === id ( f . customerId ) && id ( row . overseasWarehouseId ) === id ( f . warehouseId ) && row . skuCode === skuCode
const balances = ( await pages ( ` ${ BASE } /return-inventory? ${ query } ` )). filter ( exact )
must ( balances . length <= 1 , 'Duplicate exact native SKU balance' )
const row = balances [ 0 ]
stock . push ({ skuCode , present : Boolean ( row ), total : row ? number ( row . totalQuantity ) : 0 ,
availableView : row ? number ( row . availableQuantity ) : 0 , cartons : row ? number ( row . cartonQuantity ) : 0 ,
updatedAt : row ? . updatedAt ?? null })
movements . push (...( await pages ( ` ${ BASE } /return-inventory/movements? ${ query } ` )). filter ( exact ). map ( row => ({
customerId : id ( row . customerId ), warehouseId : id ( row . overseasWarehouseId ), skuCode : row . skuCode ,
type : row . movementType , referenceNo : row . referenceNo , totalDelta : number ( row . totalDelta ), availableDelta : number ( row . availableDelta ), occurredAt : row . occurredAt })))
}
return { stock : stock . sort (( a , b ) => a . skuCode . localeCompare ( b . skuCode )), movements : movements . sort (( a , b ) => JSON . stringify ( a ). localeCompare ( JSON . stringify ( b ))) }
}
const shipment = value => ({ status : value ? . status , version : value ? . version , outboundNo : value ? . outboundNo ,
packageCount : value ? . packageCount , signedAt : value ? . signedAt , signedPackages : value ? . signedPackages })
const dispatch = value => ({ status : value ? . status , packageCount : value ? . packageCount , items : value ? . items })
async function run ( name , action ) {
const fixture = fixtures ? .[ name ]
if ( ! fixture ) { proof . cases [ name ] = { status : 'NOT_RUN' , reason : 'Current-run producer fixture missing' }; return }
proof . cases [ name ] = { status : 'CHECKING' , producerEvidenceSha256 : context . producerEvidence . sha256 }
try { proof . cases [ name ]. evidence = await action ( fixture ); proof . cases [ name ]. status = 'PASS' }
catch ( error ) { Object . assign ( proof . cases [ name ], { status : 'FAILED' , reason : error . message }); throw error }
finally { await context . checkpoint () }
}
try {
await run ( 'cancellation' , async f => {
must ( f . allowDispatchCancellation === true && f . dispatchNo && f . transferBody && f . rearrangeBody , 'Owned cancellation fixture and explicit business cancel scope required' )
const path = ` ${ BASE } /dispatches/ ${ encodeURIComponent ( f . dispatchNo ) } `
const original = await call ( 'GET' , path )
must ( original . status === 'PENDING_DEPARTURE' && original . createdAt && original . actions ? . canTransfer , 'New unpicked execution required' )
const transferBody = { ... f . transferBody , idempotencyKey : key () }
const transfer = await call ( 'POST' , ` ${ path } /transfer-delivery` , transferBody )
must ( transfer . outboundNo && transfer . deliveries ? . length , 'New outbound and delivery required' )
const dpath = scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( transfer . deliveries [ 0 ]. deliveryNo ) } ` , f . customerId )
const before = await call ( 'GET' , dpath )
must ( before . order ? . status === 'WAIT_DELIVERY' && before . order . outboundNo === transfer . outboundNo , 'Delivery must belong to new unexecuted outbound' )
for ( const status of [ 'DELIVERING' , 'REJECTED' , 'CANCELLED' ]) {
await call ( 'PUT' , scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( before . order . deliveryNo ) } /status` , f . customerId ),
{ status , expectedVersion : before . order . version , remark : context . marker }, { failure : true })
}
must ( same ( shipment (( await call ( 'GET' , dpath )). order ), shipment ( before . order )), 'Rejected status commands changed delivery' )
const opath = ` ${ BASE } /outbound-orders/ ${ encodeURIComponent ( transfer . outboundNo ) } `
await call ( 'POST' , ` ${ opath } /cancel` , { reason : context . marker })
must (( await call ( 'GET' , opath )). outbound ? . status === 'CANCELLED' , 'Outbound cancellation did not persist' )
must (( await call ( 'GET' , dpath )). order ? . status === 'CANCELLED' , 'Linked delivery cancellation did not persist' )
await call ( 'DELETE' , path , undefined , { cancel : true })
must (( await call ( 'GET' , path )). status === 'CANCELLED' , 'Original dispatch was not retained as cancelled' )
const candidateQuery = new URLSearchParams ( f . candidateQuery )
const candidates = await call ( 'GET' , ` ${ BASE } /dispatches/candidates? ${ candidateQuery } ` )
const expected = f . rearrangeBody . planPalletIds . map ( id )
must ( expected . length && expected . every ( value => candidates . some ( row => id ( row . planPalletId ) === value )), 'Cancelled source pallets were not released' )
const replacement = await call ( 'POST' , ` ${ BASE } /dispatches/pre-arrange` , f . rearrangeBody )
must ( replacement . dispatchNo && replacement . dispatchNo !== f . dispatchNo && replacement . status === 'PENDING_DEPARTURE'
&& same ( replacement . items . map ( row => id ( row . planPalletId )). sort (), [... expected ]. sort ()), 'Released source was not re-arranged exactly once' )
const replay = await call ( 'POST' , ` ${ path } /transfer-delivery` , transferBody )
must ( replay . outboundNo === transfer . outboundNo && replay . replayed , 'Old transfer replay generated another outbound' )
return { originalDispatchNo : f . dispatchNo , cancelledOutboundNo : transfer . outboundNo , replacementDispatchNo : replacement . dispatchNo }
})
await run ( 'departedGate' , async f => {
const opath = ` ${ BASE } /outbound-orders/ ${ encodeURIComponent ( f . outboundNo ) } `
const dpath = scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( f . deliveryNo ) } ` , f . customerId )
const outbound = await call ( 'GET' , opath ), before = await call ( 'GET' , dpath )
must ( outbound . outbound ? . status === 'OUTBOUNDED' && before . order ? . outboundNo === f . outboundNo , 'Actual current-run shipment required' )
await call ( 'POST' , ` ${ opath } /cancel` , { reason : context . marker }, { failure : true })
await call ( 'PUT' , scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( f . deliveryNo ) } /status` , f . customerId ),
{ status : 'CANCELLED' , expectedVersion : before . order . version , remark : context . marker }, { failure : true })
must ( same ( shipment (( await call ( 'GET' , dpath )). order ), shipment ( before . order )), 'Departure cancellation gate changed delivery' )
return { outboundNo : f . outboundNo , deliveryNo : f . deliveryNo }
})
await run ( 'wholeRelabel' , async f => {
const apath = scope ( ` ${ BASE } /relabel-applications/ ${ encodeURIComponent ( f . relabelNo ) } ` , f . customerId )
const cpath = ` ${ BASE } /dispatches/candidates? ${ new URLSearchParams ({ sourceStage : 'RELABEL' , orderNo : f . relabelNo } )}`
const before = await call ( 'GET' , apath ), candidates = await call ( 'GET' , cpath )
const ids = candidates . filter ( row => row . orderRefs === f . relabelNo ). map ( row => id ( row . warehousePalletId )). sort ()
must ( ids . length === 2 && new Set ( ids ). size === 2 , 'Exactly two real pallets from the owned relabel application required' )
await call ( 'POST' , ` ${ BASE } /dispatches/pre-arrange` , { relabelNo : f . relabelNo , planPalletIds : ids . slice ( 0 , 1 ) }, { failure : true })
must ( same (( await call ( 'GET' , apath )). application , before . application ), 'Partial relabel rejection changed the application' )
must ( same (( await call ( 'GET' , cpath )). filter ( row => row . orderRefs === f . relabelNo ). map ( row => id ( row . warehousePalletId )). sort (), ids ), 'Partial relabel rejection retained a lock or lost cargo' )
const full = await call ( 'POST' , ` ${ BASE } /dispatches/pre-arrange` , { relabelNo : f . relabelNo , planPalletIds : ids })
must ( full . status === 'PENDING_DEPARTURE' && full . items ? . length === 2 && same ( full . items . map ( row => id ( row . warehousePalletId )). sort (), ids ), 'Full relabel selection did not preserve both pallets' )
return { relabelNo : f . relabelNo , dispatchNo : full . dispatchNo , pallets : ids }
})
await run ( 'mixedSources' , async f => {
must ( same ( f . samples . map ( row => row . displayKind ). sort (), [ 'EXTERNAL' , 'ORDINARY' ]), 'Both physical display permutations required' )
const evidence = []
for ( const sample of f . samples ) {
const normal = own . inbound . get ( sample . ordinaryInboundCode ), external = own . inbound . get ( sample . externalInboundCode )
const booking = own . booking . get ( sample . bookingNo ). booking
const current = await call ( 'GET' , ` ${ BASE } /dispatches/ ${ encodeURIComponent ( sample . dispatchNo ) } ` )
const displayed = current . items ? . find ( row => id ( row . warehousePalletId ) === id ( sample . palletId ))
const expectedDisplay = sample . displayKind === 'ORDINARY' ? normal . key : external . key
must ( displayed ? . inboundCode === expectedDisplay && displayed . palletNo && id ( current . overseasWarehouseId ) === id ( f . warehouseId ), 'Displayed source does not match its independently produced ordinary/external origin' )
const balances = ( await pages ( ` ${ BASE } /inventory/balances? ${ new URLSearchParams ({ customerId : f . customerId , overseasWarehouseId : f . warehouseId } )}` ))
. filter ( row => id ( row . customerId ) === id ( f . customerId ) && id ( row . overseasWarehouseId ) === id ( f . warehouseId ))
const quantities = new Map (), positions = []
for ( const balance of balances ) {
const rows = await call ( 'GET' , ` ${ BASE } /inventory/balances/ ${ encodeURIComponent ( id ( balance . id )) } /positions? ${ new URLSearchParams ({ customerId : f . customerId , palletNo : displayed . palletNo } )}` )
must ( Array . isArray ( rows ), 'Actual inventory positions required' )
for ( const row of rows . filter ( row => id ( row . palletId ) === id ( sample . palletId ))) {
must ( id ( row . customerId ) === id ( f . customerId ) && id ( row . overseasWarehouseId ) === id ( f . warehouseId ), 'Physical pallet source scope mismatch' )
const quantity = number ( row . availablePackages ) + number ( row . pickedPackages )
if ( quantity > 0 ) quantities . set ( row . inboundCode , ( quantities . get ( row . inboundCode ) || 0 ) + quantity )
positions . push ({ positionId : id ( row . id ), inboundCode : row . inboundCode , quantity })
}
}
must ( quantities . size === 2 && quantities . get ( normal . key ) === normal . receivedPackages && quantities . get ( external . key ) === external . receivedPackages ,
'Physical pallet composition differs from independent receiving facts' )
const freight = await call ( 'GET' , ` ${ BASE } /dispatches/ ${ encodeURIComponent ( sample . dispatchNo ) } /external-freight` )
const quote = freight . quotes ? .[ 0 ], cargo = booking . cargo , receipt = booking . receipt ? . source
const quantity = cargo ? . priceBasis === 'PALLET' ? number ( cargo . palletSpaces ) : 1
must ( freight . requiresDeliveryFee === true && freight . quotes ? . length === 1 && quote . bookingNo === sample . bookingNo
&& quote . inboundCode === external . key && quote . currency === cargo . currency && quote . destinationKey === receipt ? . destinationKey
&& number ( quote . quantity ) === quantity && cents ( quote . unitPrice ) === cents ( cargo . unitPrice )
&& cents ( quote . amount ) === cents ( booking . agreedAmount ) && cents ( quote . amount ) === cents ( cargo . unitPrice ) * BigInt ( quantity )
&& freight . snapshotHash , 'Actual external quote quantity/price/amount/currency differs from producer commercial facts' )
evidence . push ({ dispatchNo : sample . dispatchNo , palletId : sample . palletId , displayKind : sample . displayKind ,
expectedSources : [{ inboundCode : normal . key , packages : normal . receivedPackages }, { inboundCode : external . key , packages : external . receivedPackages }],
positions , quote , snapshotHash : freight . snapshotHash })
}
return evidence
})
await run ( 'receiptRefresh' , async f => {
must ( f . tripNo && f . bookingNo && f . oldReceiptHash && Number ( f . unitPrice ) >= 0 , 'Owned booking and previous actual receipt required' )
const bookingsPath = ` ${ BASE } /fleet/trips/ ${ encodeURIComponent ( f . tripNo ) } /bookings`
const listing = await call ( 'GET' , bookingsPath )
const booking = listing . records ? . find ( row => row . bookingNo === f . bookingNo )
must ( booking && id ( booking . customerId ) === id ( f . customerId ) && booking . status === 'RECEIVED' && ! booking . dispatchNo
&& booking . receipt ? . source ? . receiptHash === f . oldReceiptHash , 'Previously accepted, currently unbound own-customer booking required' )
const path = ` ${ bookingsPath } / ${ encodeURIComponent ( f . bookingNo ) } `
const before = await call ( 'GET' , ` ${ path } /incoming` )
must ( before . incoming ? . receiptHash && before . incoming . receiptHash !== f . oldReceiptHash && before . incoming . pallets ? . length
&& before . incoming . pallets . some ( row => row . weightKg == null || row . volumeCbm == null ), 'Fresh split/merge geometry requiring measurement must be proven' )
must ( f . measurements ? . length === before . incoming . pallets . length , 'Independent new physical pallet measurements required' )
const body = { tripRecordVersion : before . tripRecordVersion , recordVersion : before . recordVersion , receiptHash : before . incoming . receiptHash ,
pallets : before . incoming . pallets . map ( row => ({ warehousePalletId : id ( row . warehousePalletId ), palletSpaces : 1 })), unitPrice : f . unitPrice , idempotencyKey : key () }
await call ( 'POST' , ` ${ path } /receipt-confirmation` , body , { failure : true })
body . idempotencyKey = key ()
body . pallets = body . pallets . map ( row => ({ ... row , ... f . measurements . find ( value => id ( value . warehousePalletId ) === row . warehousePalletId ) }))
must ( body . pallets . every ( row => Number ( row . weightKg ) > 0 && Number ( row . volumeCbm ) > 0 ), 'Positive new measurements required' )
const confirmed = await call ( 'POST' , ` ${ path } /receipt-confirmation` , body )
const replay = await call ( 'POST' , ` ${ path } /receipt-confirmation` , body )
must ( confirmed . booking ? . receipt ? . source ? . receiptHash === body . receiptHash && replay . replayed === true
&& same ( replay . booking . receipt , confirmed . booking . receipt ), 'Re-confirmed receipt or exact replay drifted' )
return { tripNo : f . tripNo , bookingNo : f . bookingNo , receipt : confirmed . booking . receipt }
})
await run ( 'nativeCartonReturn' , async f => {
must ( f . cartonMark && f . returnCartonId && f . lastMileOrderId && f . target , 'Owned native carton, actual master and actual target resources required' )
const cartonPath = ` ${ BASE } /return-inventory/cartons/ ${ encodeURIComponent ( f . cartonMark ) } `
const before = await call ( 'GET' , cartonPath )
must ( before . status === 'OUTBOUNDED' && id ( before . customerId ) === id ( f . customerId ) && id ( before . overseasWarehouseId ) === id ( f . warehouseId ), 'Native carton must be actually shipped for this customer and warehouse' )
const relations = await call ( 'GET' , scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( f . deliveryNo ) } /return-inbound-options` , f . customerId ))
const relation = relations . find ( row => id ( row . lastMileOrderId ) === id ( f . lastMileOrderId ) && row . deliveryNo === f . deliveryNo && row . outboundNo === f . outboundNo )
const source = relation ? . returnSources ? . find ( row => id ( row . returnCartonId ) === id ( f . returnCartonId ) && row . inventoryPositionId == null && row . cartonMark === f . cartonMark && Number ( row . maxReturnPackages ) === 1 )
must ( source , 'Actual native carton source is missing; do not invent an inventory position or inbound' )
const body = { lastMileOrderId : id ( f . lastMileOrderId ), reason : ` ${ context . marker } synthetic refusal` , returnDirection : 'OVERSEAS_WAREHOUSE' ,
items : [{ outboundPalletItemId : id ( source . outboundPalletItemId ), returnCartonId : id ( source . returnCartonId ), packageCount : 1 }], idempotencyKey : key () }
const markPath = scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( f . deliveryNo ) } /mark-return` , f . customerId )
const marked = await call ( 'POST' , markPath , body ), replayMark = await call ( 'POST' , markPath , body )
must ( marked . exceptionNo && replayMark . exceptionNo === marked . exceptionNo && replayMark . replayed , 'Native mark-return replay drifted' )
const path = ` ${ BASE } /exception-orders/ ${ encodeURIComponent ( marked . exceptionNo ) } `
const started = await call ( 'POST' , scope ( ` ${ path } /start-processing` , f . customerId ), { expectedVersion : marked . version , idempotencyKey : key (), handlingAction : 'SYNTHETIC TEST CARTON RETURN' })
const file = { name : ` ${ context . marker } -native-return.txt` , type : 'text/plain' , content : new TextEncoder (). encode ( 'SYNTHETIC TEST EVIDENCE; not a real external POD' ) }
const uploaded = await call ( 'POST' , scope ( ` ${ path } /evidence` , f . customerId ), undefined , { file })
const completeBody = { expectedVersion : started . version , idempotencyKey : key (), handlingResult : 'SYNTHETIC TEST ACTUAL RETURN' , evidenceFileIds : [ uploaded . fileId ],
receipts : [{ outboundPalletItemId : id ( source . outboundPalletItemId ), inventoryPositionId : null , returnCartonId : id ( source . returnCartonId ), receivedPackages : 1 , ... f . target }] }
const born = own . carton . get ( f . cartonMark ), expected = new Map ( born . originalSkuItems . map ( row => [ row . skuCode , number ( row . quantity )]))
must ( expected . size === born . originalSkuItems . length && [... expected . values ()]. every ( n => n > 0 ), 'Unique original native SKU quantities required' )
const skus = [... expected . keys ()]. sort (), S = await nativeSnapshot ( f , skus )
const dispatchNo = own . delivery . get ( f . deliveryNo ). dispatchNo
const outboundEvidence = S . movements . filter ( row => row . type === 'OUTBOUND' && row . referenceNo === dispatchNo )
must ( outboundEvidence . length === skus . length && skus . every ( sku => outboundEvidence . filter ( row => row . skuCode === sku ). length === 1
&& outboundEvidence . find ( row => row . skuCode === sku ). totalDelta === - expected . get ( sku )), 'Original single-carton per-SKU outbound movement does not match producer carton' )
const completed = await call ( 'POST' , scope ( ` ${ path } /complete` , f . customerId ), completeBody )
const R = await nativeSnapshot ( f , skus ), history = await call ( 'GET' , scope ( path , f . customerId )), after = await call ( 'GET' , cartonPath )
must ( completed . status === 'COMPLETED' && number ( completed . restoredPackages ) === 1 && history . returnReceipts ? . length === 1
&& number ( history . returnReceipts [ 0 ]. receivedPackages ) === 1 && history . returnReceipts [ 0 ]. receiptNo && history . returnReceipts [ 0 ]. receivedAt , 'Native receipt identity/box count is incomplete' )
const receiptNo = history . returnReceipts [ 0 ]. receiptNo
const incoming = R . movements . filter ( row => row . type === 'EXCEPTION_RETURN_IN' && row . referenceNo === receiptNo )
must ( ! S . movements . some ( row => row . referenceNo === receiptNo ) && incoming . length === skus . length
&& same ( incoming . map ( row => row . skuCode ). sort (), skus ) && skus . every ( sku => {
const previous = S . stock . find ( row => row . skuCode === sku ), restored = R . stock . find ( row => row . skuCode === sku )
const movement = incoming . find ( row => row . skuCode === sku )
return restored . present && restored . updatedAt && restored . total - previous . total === expected . get ( sku )
&& previous . total === 0 && previous . availableView === 0 && previous . cartons === 0
&& restored . availableView === expected . get ( sku ) && restored . cartons === 1
&& movement . totalDelta === expected . get ( sku ) && movement . availableDelta === expected . get ( sku ) && movement . occurredAt
}), 'Every original SKU must restore its exact total, visible availability, carton count and one immutable receipt movement' )
must ( after . status === 'AVAILABLE' && id ( after . customerId ) === id ( f . customerId ) && id ( after . overseasWarehouseId ) === id ( f . warehouseId )
&& after . cartonMark === f . cartonMark && after . palletCode === f . target . targetPalletNo && after . locationCode === f . target . targetLocationCode && after . putawayAt ,
'Native carton did not return to the exact validated physical pallet/location' )
const deliveryAfter = await call ( 'GET' , scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( f . deliveryNo ) } ` , f . customerId ))
must ( deliveryAfter . order ? . status === 'RETURNED' , 'Actual single-carton recovery did not close its delivery' )
const replay = await call ( 'POST' , scope ( ` ${ path } /complete` , f . customerId ), completeBody )
const Rprime = await nativeSnapshot ( f , skus ), historyAgain = await call ( 'GET' , scope ( path , f . customerId )), cartonAgain = await call ( 'GET' , cartonPath )
const deliveryAgain = await call ( 'GET' , scope ( ` ${ BASE } /delivery-orders/ ${ encodeURIComponent ( f . deliveryNo ) } ` , f . customerId ))
must ( replay . replayed === true && same ( Rprime , R ) && same ( historyAgain . returnReceipts , history . returnReceipts )
&& same ({ pallet : cartonAgain . palletCode , location : cartonAgain . locationCode , at : cartonAgain . putawayAt , status : cartonAgain . status },
{ pallet : after . palletCode , location : after . locationCode , at : after . putawayAt , status : after . status })
&& same ( shipment ( deliveryAgain . order ), shipment ( deliveryAfter . order )), 'Native replay changed SKU stock, receipt rows/times, target or delivery' )
return { exceptionNo : marked . exceptionNo , cartonMark : f . cartonMark , dispatchNo , receiptNo , S , R , Rprime ,
expectedSkuQuantities : Object . fromEntries ( expected ), target : f . target ,
availableQuantityMeaning : 'HTTP availableQuantity is a capped visible value; total and immutable availableDelta verified, no naked-ledger availability claim' }
})
await run ( 'permissions' , async f => {
must ( typeof context . requestReadonly === 'function' && f . outboundNo , 'Dedicated read-only session and owned fresh outbound required' )
const path = ` ${ BASE } /outbound-orders/ ${ encodeURIComponent ( f . outboundNo ) } `
const before = await call ( 'GET' , path , undefined , { actor : 'READ_ONLY' })
must ( before . outbound ? . status === 'WAIT_OUTBOUND' , 'Current unexecuted outbound required for permission isolation' )
await call ( 'POST' , ` ${ path } /cancel` , { reason : context . marker }, { failure : 'FORBIDDEN' , actor : 'READ_ONLY' })
const after = await call ( 'GET' , path )
must ( same ( shipment ( after . outbound ), shipment ( before . outbound )), 'Forbidden read-only command changed outbound' )
return { outboundNo : f . outboundNo , readAllowed : true , cancellationForbidden : true }
})
proof . status = cases . every ( name => proof . cases [ name ] ? . status === 'PASS' ) ? 'HTTP_CASES_PASSED_REVIEW_REQUIRED' : 'PARTIAL_NOT_ALL_VERIFIED'
return proof
} catch ( error ) { proof . status = 'FAILED' ; proof . error = error . message ; throw error }
finally { await context . checkpoint () }
}