Files
baiyue-firstleg/scripts/fleet-same-route-cost-test-env.test.mjs
T

174 lines
16 KiB
JavaScript
Raw Normal View History

import test from 'node:test'
import assert from 'node:assert/strict'
2026-10-20 10:35:52 +08:00
import {fixtureContract} from './admin-test-env-modules/fleet-cross-customer-acceptance.mjs'
import {assertSameRouteCost,assertSameRouteBasis,sameRouteShares,sameRouteMeasurements,sameRouteArrangement,sameRouteIo,runSameRouteCost,verifySameRouteCost} from './fleet-same-route-cost-test-env.mjs'
function sample(ownSpaces=[1,1],externalSpaces=1){
const shares=[{businessNo:'DS-OWN',dispatchNo:'DS-OWN',sourceType:'OWN',customerIds:['101','102'],palletSpaces:ownSpaces.reduce((sum,n)=>sum+n,0),warehousePalletIds:['9007199254740993','2']},
{businessNo:'BK-C',dispatchNo:'DS-OWN',sourceType:'EXTERNAL',customerId:'101',palletSpaces:externalSpaces,warehousePalletIds:['3']}]
const departure={action:'DEPART',recordVersion:'9007199254740997',snapshot:{trip:{stops:[{name:'Origin'},{destinationKey:'FBA:A'},{destinationKey:'FBA:B'}]},
confirmedLoad:{manifestHash:'real-hash',pallets:[...ownSpaces,externalSpaces].map((palletSpaces,index)=>({warehousePalletId:['9007199254740993','2','3'][index],palletSpaces,deliveryIndex:1})),
cargo:['101','102','101'].map((customerId,index)=>({warehousePalletId:['9007199254740993','2','3'][index],dispatchNo:'DS-OWN',customerId,packages:'1',destinationKey:'FBA:A'}))},
externalBookings:[{bookingNo:'BK-C',dispatchNo:'DS-OWN',customerId:'101',status:'BOUND',receipt:{source:{receivedPackages:'1',pallets:[{warehousePalletId:'3',packages:'1'}]},pallets:[{warehousePalletId:'3',palletSpaces:externalSpaces}]}}]}}
// Independent two-business 2:1 oracle: 100 cents => OWN 67, EXTERNAL 33.
const summary={departureVersion:'9007199254740997',manifestHash:'real-hash',allocationMethod:'SAME_ROUTE_PALLET_SPACES',totals:[{currency:'USD',directCost:'1.00',ownCost:'0.67',externalCost:'0.33',
allocations:shares.map(s=>({businessNo:s.businessNo,dispatchNo:s.dispatchNo,sourceType:s.sourceType,palletSpaces:s.palletSpaces,amount:s.sourceType==='OWN'?'0.67':'0.33'}))}]}
return {shares,departure,summary}
}
test('offline entry does not call remote services and missing runtime scope is rejected',async()=>{
2026-10-20 10:35:52 +08:00
assert.equal((await runSameRouteCost({execute:false},{env:{}})).deploy,false)
assert.equal((await verifySameRouteCost()).businessSqlWrites,false)
await assert.rejects(verifySameRouteCost({},null,{execute:true}),/FIXTURE/)
})
2026-10-20 10:35:52 +08:00
test('ordinary native arrangement declares exactly two actual own customer groups without a third external fee',()=>{
const fixture={marker:'RUN',dispatchNo:'DS-OWN',members:['101','102'].map(customerId=>({marker:'RUN',dispatchNo:'DS-OWN',customerId,destination:{key:'FBA:A'}}))}
const source=sameRouteArrangement({marker:'RUN'},fixture)
assert.equal(source.mode,'NATIVE');assert.equal(source.dispatchNo,'DS-OWN');assert.equal(source.groups.length,2)
assert.deepEqual(source.groups.map(g=>[g.customerId,g.destinationKey,g.fees.length,g.fees[0].amount]),[['101','FBA:A',1,'30.00'],['102','FBA:A',1,'30.00']])
assert.ok(!source.groups.some(g=>g.bookingNo));assert.ok(Number.isFinite(Date.parse(source.plannedDeliveryAt)))
fixture.members[1].destination.key='FBA:B';assert.throws(()=>sameRouteArrangement({marker:'RUN'},fixture),/GROUPS/)
})
2026-10-20 10:35:52 +08:00
test('three physical pallets share one native main and two business allocations with independent 67:33 oracle',()=>{
const s=sample();assert.equal(assertSameRouteBasis(s.departure,s.shares).pallets.length,3)
assert.deepEqual(assertSameRouteCost(s.summary,s.departure,s.shares).map(x=>[x.businessNo,x.cents]),[['BK-C','33'],['DS-OWN','67']])
assert.equal(new Set(s.shares.map(x=>x.dispatchNo)).size,1)
})
test('actual non-unit capacities aggregate own pallets; 4:2 remains 67:33',()=>{
const s=sample([1,3],2);assert.deepEqual(assertSameRouteCost(s.summary,s.departure,s.shares).map(x=>x.cents),['33','67'])
})
test('wire BigDecimal money numbers retain exact integer-cent verification',()=>{
const s=sample(),t=s.summary.totals[0];t.directCost=1;t.ownCost=0.67;t.externalCost=0.33
for(const row of t.allocations)row.amount=Number(row.amount)
assert.deepEqual(assertSameRouteCost(s.summary,s.departure,s.shares).map(x=>x.cents),['33','67'])
})
test('other actual weights use actual ratio rather than planned 2:1 or physical pallet count',()=>{
const s=sample([1,2],2),t=s.summary.totals[0];t.ownCost='0.60';t.externalCost='0.40'
t.allocations.find(x=>x.sourceType==='OWN').amount='0.60';t.allocations.find(x=>x.sourceType==='EXTERNAL').amount='0.40'
assert.deepEqual(assertSameRouteCost(s.summary,s.departure,s.shares).map(x=>x.cents),['40','60'])
})
test('equal business capacities use business-number tie break for a residual cent',()=>{
const s=sample([1,1],2),t=s.summary.totals[0];t.directCost='0.01';t.ownCost='0.00';t.externalCost='0.01'
t.allocations.find(x=>x.sourceType==='OWN').amount='0.00';t.allocations.find(x=>x.sourceType==='EXTERNAL').amount='0.01'
assert.deepEqual(assertSameRouteCost(s.summary,s.departure,s.shares,'0.01').map(x=>x.cents),['1','0'])
})
for(const fault of ['wrong action','missing pallet','overlapping source','different destination','wrong customer','wrong dispatch','wrong receipt','unbound booking','uncovered external','stale version','stale hash','invented method','mixed currency','lost penny','wrong source type','wrong aggregate','wrong residual winner','invented separate main','plan capacity','external plan capacity','unsafe quantity','missing own customer','foreign cargo'])test(`rejects invalid allocation evidence: ${fault}`,()=>{
const s=sample(),l=s.departure.snapshot.confirmedLoad,t=s.summary.totals[0],b=s.departure.snapshot.externalBookings[0]
if(fault==='wrong action')s.departure.action='PLAN'
if(fault==='missing pallet')l.pallets.pop()
if(fault==='overlapping source')s.shares[0].warehousePalletIds[1]='3'
if(fault==='different destination')l.pallets[2].deliveryIndex=2
if(fault==='wrong customer')l.cargo[0].customerId='FOREIGN'
if(fault==='wrong dispatch')l.cargo[0].dispatchNo='DS-FOREIGN'
if(fault==='wrong receipt')b.receipt.source.pallets[0].packages=2
if(fault==='unbound booking')b.status='CONFIRMED'
if(fault==='uncovered external')s.departure.snapshot.externalBookings.push({...b,bookingNo:'BK-OTHER'})
if(fault==='stale version')s.summary.departureVersion='9007199254740998'
if(fault==='stale hash')s.summary.manifestHash='new-hash'
if(fault==='invented method')s.summary.allocationMethod='GUESS'
if(fault==='mixed currency')t.currency='CNY'
if(fault==='lost penny')t.allocations[0].amount='0.66'
if(fault==='wrong source type')t.allocations[1].sourceType='OWN'
if(fault==='wrong aggregate'){t.ownCost='0.66';t.externalCost='0.34'}
if(fault==='wrong residual winner'){t.allocations[0].amount='0.66';t.allocations[1].amount='0.34';t.ownCost='0.66';t.externalCost='0.34'}
if(fault==='invented separate main')s.shares[1].dispatchNo='DS-OTHER'
if(fault==='plan capacity')s.shares[0].palletSpaces=1
if(fault==='external plan capacity')b.receipt.pallets[0].palletSpaces=2
if(fault==='unsafe quantity')l.cargo[0].packages=9007199254740992
if(fault==='missing own customer')s.shares[0].customerIds=['101']
if(fault==='foreign cargo')l.cargo.push({...l.cargo[0],warehousePalletId:'OTHER'})
assert.throws(()=>assertSameRouteCost(s.summary,s.departure,s.shares))
})
function nativeSource(){
const s=sample(),fixture={dispatchNo:'DS-OWN',members:[{palletId:'9007199254740993',customerId:'101',incomingNo:'IN-A'},{palletId:'2',customerId:'102',incomingNo:'IN-B'}]},receipt={warehousePalletId:'3',bookingNo:'BK-C',incomingNo:'IN-C',createRequest:{customerId:'101'}},
bundle={detail:{dispatchNo:'DS-OWN',recordVersion:'0'},items:{dispatchNo:'DS-OWN',recordVersion:'0',items:s.departure.snapshot.confirmedLoad.cargo.map((c,i)=>({...c,inboundCode:['IN-A','IN-B','IN-C'][i],scheduledPackages:'1'}))}}
return {...s,fixture,receipt,bundle}
}
test('shares derive from native Detail/Items, real source identities and immutable measured load',()=>{
const s=nativeSource();assert.deepEqual(sameRouteShares(s.departure,s.fixture,s.receipt,s.bundle),s.shares)
})
for(const fault of ['version','source','customer','missing pallet'])test(`native source identity refuses ${fault}`,()=>{
const s=nativeSource()
if(fault==='version')s.bundle.items.recordVersion='1'
if(fault==='source')s.bundle.items.items[2].inboundCode='HISTORY'
if(fault==='customer')s.bundle.items.items[1].customerId='101'
if(fault==='missing pallet')s.bundle.items.items.pop()
assert.throws(()=>sameRouteShares(s.departure,s.fixture,s.receipt,s.bundle))
})
function measurements(){
const context={marker:'RUN'},trip={stops:[{name:'Origin'},{destinationKey:'FBA:A'}]},preview={dispatchNo:'DS-OWN',status:'ACTIVE',pallets:[{warehousePalletId:'9007199254740993',palletNo:'P1',scheduledPackages:'1',pickedPackages:'0',palletSpaces:null,deliveryIndex:1}]},
row={warehousePalletId:'9007199254740993',palletSpaces:3,weightKg:'120.25',volumeCbm:'1.75',deliveryIndex:1}
row.evidence=['palletSpaces','weightKg','volumeCbm'].map(field=>({field,value:row[field],actual:true,sourceType:'WAREHOUSE_TRANSFER_PDA',sourceBusinessNo:'IN-A',observedAt:'2026-10-19T00:00:00Z'}))
const fixture={dispatchNo:'DS-OWN',members:[{palletId:'9007199254740993',incomingNo:'IN-A'}],loadingMeasurements:{environment:'TEST',marker:'RUN',dispatchNo:'DS-OWN',pallets:[row]}}
return {context,fixture,trip,preview}
}
test('pre-pick capacity reads physical evidence without falsifying picked counts or unit capacities',()=>{
const s=measurements(),r=sameRouteMeasurements(s.context,s.fixture,s.trip,s.preview)
assert.equal(r.pallets[0].palletSpaces,3);assert.equal(s.preview.pallets[0].pickedPackages,'0')
})
for(const fault of ['absent','marker','environment','dispatch','actual','field','duplicate','foreign','unit','conflict','stop','historical source'])test(`missing or foreign actual physical evidence blocks: ${fault}`,()=>{
const s=measurements(),m=s.fixture.loadingMeasurements,row=m.pallets[0]
if(fault==='absent')delete s.fixture.loadingMeasurements
if(fault==='marker')m.marker='HISTORY'
if(fault==='environment')m.environment='DEV'
if(fault==='dispatch')m.dispatchNo='DS-OTHER'
if(fault==='actual')row.evidence[0].actual=false
if(fault==='field')delete row.palletSpaces
if(fault==='duplicate')m.pallets.push(structuredClone(row))
if(fault==='foreign')m.pallets.push({...structuredClone(row),warehousePalletId:'OTHER'})
if(fault==='unit')row.palletSpaces='3'
if(fault==='conflict'){s.preview.pallets[0].palletSpaces=2;s.preview.pallets[0].evidence=[{...row.evidence[0],value:2}]}
if(fault==='stop')row.deliveryIndex=0
if(fault==='historical source')row.evidence[0].sourceBusinessNo='HISTORY'
assert.throws(()=>sameRouteMeasurements(s.context,s.fixture,s.trip,s.preview))
})
test('external actual capacity and dimensions come from operator-confirmed receipt',()=>{
const s=measurements();s.trip.externalReceipt={status:'VERIFIED',finalBooking:{cargo:{destinationKey:'FBA:A'},receipt:{operatorId:'9007199254740998',confirmedAt:'2026-10-19T01:00:00Z',
source:{incomingNo:'IN-EXT',pallets:[{warehousePalletId:'3',weightKg:'110',volumeCbm:'1.1'}]},pallets:[{warehousePalletId:'3',palletSpaces:2}]}}}
const r=sameRouteMeasurements(s.context,s.fixture,s.trip,s.preview,{external:true})
assert.equal(r.pallets[1].palletSpaces,2);assert.equal(r.pallets[1].weightKg,'110');assert.equal(r.pallets[1].evidence[0].sourceType,'FLEET_RECEIPT_CONFIRMATION')
delete s.trip.externalReceipt.finalBooking.receipt.operatorId
assert.throws(()=>sameRouteMeasurements(s.context,s.fixture,s.trip,s.preview,{external:true}),/EXTERNAL_MEASUREMENT/)
})
test('executable native chain fails and checkpoints before any write when actual measurements are absent',async()=>{
const physical=measurements().preview
physical.pallets.push({...physical.pallets[0],warehousePalletId:'2',palletNo:'P2'})
const trip={dispatchNo:'DS-OWN',tripNo:'FT-OWN'},members=['101','102'].map((customerId,index)=>({marker:'RUN',customerId,dispatchNo:'DS-OWN',receiptVerified:true,incomingNo:['IN-A','IN-B'][index],palletId:['9007199254740993','2'][index],palletNo:['P1','P2'][index]})),
fixture={marker:'RUN',stage:fixtureContract.stage,dispatchNo:'DS-OWN',tripNo:'FT-OWN',warehouseId:'1',pdaToken:'EPHEMERAL',tripProof:trip,members},
calls=[],context={marker:'RUN',createdResources:{fleetTrips:[trip]},assert(){},checkpoint:async()=>calls.push('checkpoint'),request:async(method,path)=>{
calls.push(method)
const data=path.endsWith('/loading')?physical:path.endsWith('/capacity-plan')?{recordVersion:'0',manifestHash:'original',cargo:members.map(()=>({dispatchNo:'DS-OWN',destinationKey:'FBA:A'}))}
:{dispatches:[{dispatchNo:'DS-OWN'}],trip:{stops:[{name:'origin'},{destinationKey:'FBA:A'}]}}
return {http:200,body:{code:'200',data},requestId:'R',traceId:'T'}
}}
await assert.rejects(verifySameRouteCost(context,fixture,{execute:true,readInventory:async()=>{throw Error('should not read before measurements')}}),/ACTUAL_LOADING_MEASUREMENT_REQUIRED/)
assert.equal(context.createdResources.fleetSameRouteCost.status,'FAILED')
assert.ok(calls.includes('checkpoint'));assert.ok(!calls.includes('POST'));assert.ok(!calls.includes('PUT'))
assert.ok(!JSON.stringify(context.createdResources.fleetSameRouteCost).includes('EPHEMERAL'))
})
function transport(response){
const events=[],proof={requests:[]},context={createdResources:{},token:'NEVER_PERSIST_ME',assert(){},checkpoint:async()=>events.push(structuredClone(proof)),
request:async(...args)=>{events.push(args);if(response instanceof Error)throw response;return response}}
return {events,proof,context,io:sameRouteIo(context,proof)}
}
test('write intent is persisted before transport and zero / large-string facts remain lossless',async()=>{
const s=transport({http:200,body:{code:'200',data:{recordVersion:'0',id:'9007199254740997'}},requestId:'R',traceId:'T'}),body={recordVersion:'9007199254740996',idempotencyKey:'ORIGINAL'}
assert.equal((await s.io.request('POST','/native',body)).recordVersion,'0')
assert.deepEqual(s.events[0].requests[0],{method:'POST',path:'/native',body,status:'SENDING'})
assert.equal(s.proof.requests[0].result.id,'9007199254740997');assert.ok(!JSON.stringify(s.proof).includes('NEVER_PERSIST_ME'))
})
for(const response of [new Error('network'),{http:503,body:{code:'ERROR'}},{http:200,body:{code:'200',data:null}},{http:200,body:{}}])test(`unknown write stops all later writes and retains original command: ${response instanceof Error?'transport':JSON.stringify(response)}`,async()=>{
const s=transport(response),body={recordVersion:'0',idempotencyKey:'ORIGINAL'}
await assert.rejects(s.io.request('POST','/native',body));assert.equal(s.proof.requests[0].status,'UNKNOWN_RESULT');assert.equal(s.context.createdResources.dispatchWriteBoundary.stopped,true)
assert.deepEqual(s.proof.requests[0].body,body)
await assert.rejects(s.io.request('POST','/native',{...body,idempotencyKey:'REPLACEMENT'}),/STOPPED/);assert.equal(s.proof.requests.length,1)
})
test('failed intent checkpoint prevents transport; failed result archive stops new writes',async()=>{
const s=transport({http:200,body:{code:'200',data:{ok:true}},requestId:'R',traceId:'T'})
s.context.checkpoint=async()=>{throw Error('disk')}
await assert.rejects(s.io.request('POST','/native',{idempotencyKey:'ORIGINAL'}),/disk/);assert.equal(s.events.length,0);assert.equal(s.proof.requests[0].status,'NOT_SENT')
const t=transport({http:200,body:{code:'200',data:{ok:true}},requestId:'R',traceId:'T'});let writes=0
t.context.checkpoint=async()=>{if(++writes===2)throw Error('archive')}
await assert.rejects(t.io.request('POST','/native',{idempotencyKey:'ORIGINAL'}),/archive/)
await assert.rejects(t.io.request('POST','/native',{}),/STOPPED/)
})