'use strict'; const {test}=require('node:test'),assert=require('node:assert/strict'),M=require('./conversion-model.js'),Base=require('./model.js'),L=require('./lifecycle.js'); const clock=()=> '2026-10-16T12:00:00.000Z'; function memory(){const m=new Map();return {getItem:k=>m.get(k)||null,setItem:(k,v)=>m.set(k,v),removeItem:k=>m.delete(k)};} function fixture(){const storage=memory(),s=M.createStore(storage,{clock}),o=L.initialize(Base.samples())[1];s.observe(o,'B1','event');let c=s.interest(o,'B1',M.cents('100000'),'organic'),seq=0;const fresh=()=>({offerVersion:o.version,eligible:true,inventoryFresh:true,offerActive:true});return {storage,s,o,get c(){return c;},fresh,run(action,role,input={},ctx){c=s.run(action,c.id,{confirm:true,...input},{role,id:role==='buyer'?'B1':role==='seller'?o.issuer:'STAFF-'+role},{expectedVersion:c.version,requestId:'REQ-'+(++seq)},ctx||fresh()).record;return c;}};} function agreed(f){f.run('review','reviewer',{gates:[true,true,true,true,true],reference:'R'});f.run('propose','buyer',{quantity:'1000',price:'100',feePayer:'seller',agentPayer:'buyer',reference:'P'});f.run('confirm','seller',{proposalVersion:1});} function instructed(f){agreed(f);f.run('agreement','reviewer',{reference:'AG'});f.run('instruct','rails',{network:'N',destination:'D',paymentRef:'PAY'});} function delivered(f){instructed(f);f.run('deliver','rails',{receivedAmount:'100000',receivedUnits:'1000',network:'N',destination:'D',deliveryRef:'DEL'});} function reconciled(f){delivered(f);f.run('reconcile','auditor',{reference:'REC',paymentChecked:true,assetChecked:true});} function throws(code,fn){assert.throws(fn,e=>e.code===code);} test('empty metrics preserve unknown costs and actuals, not zero revenue',()=>{const d=M.createStore(memory()).metrics();assert.equal(d.recordedCostCents,null);assert.equal(d.actualVolumeCents,null);assert.equal(d.actualRevenueCents,null);assert(d.rows.every(r=>r.count===0&&r.previousRate===null));}); test('first recorded channel is retained and eligible views deduplicate',()=>{const f=fixture();f.s.observe(f.o,'B1','organic');assert.equal(f.c.channel,'event');assert.equal(f.s.metrics().viewCount,1);assert.equal(f.s.metrics().rows[1].count,1);}); test('duplicate interest reuses case without extra history',()=>{const f=fixture(),n=f.s.history(f.c.id).length;assert.equal(f.s.interest(f.o,'B1',10000000,'advisor').id,f.c.id);assert.equal(f.s.history(f.c.id).length,n);}); test('a reconfirmed offer version forms a distinct cohort',()=>{const f=fixture(),o={...f.o,version:2};f.s.observe(o,'B1','advisor');f.s.interest(o,'B1',10000000,'advisor');assert.equal(f.s.metrics().rows[1].count,2);}); test('interest without observed view does not fabricate a view or conversion rate',()=>{const f=fixture();f.s.clear();f.s.interest(f.o,'B1',10000000,'event');const d=f.s.metrics();assert.equal(d.rows[0].count,0);assert.equal(d.rows[1].count,1);assert.equal(d.rows[1].previousRate,null);}); test('five handoff gates and reviewer role required',()=>{const f=fixture();throws('forbidden',()=>f.run('review','buyer',{gates:[true,true,true,true,true],reference:'R'}));throws('required',()=>f.run('review','reviewer',{gates:[true,true,true,true,false],reference:'R'}));assert.equal(f.c.stage,'interested');}); for(const [field,value]of [['offerVersion',2],['eligible',false],['inventoryFresh',false],['offerActive',false]])test('fresh handoff blocks '+field,()=>{const f=fixture();throws('offerChanged',()=>f.run('review','reviewer',{gates:[true,true,true,true,true],reference:'R'},{...f.fresh(),[field]:value}));}); test('same buyer role with wrong identity cannot withdraw',()=>{const f=fixture();throws('forbidden',()=>f.s.run('withdraw',f.c.id,{confirm:true,dropReason:'other',reason:'R'},{id:'B2',role:'buyer'},{expectedVersion:1,requestId:'BAD'}));}); test('stage cannot be skipped or accepted by same proposer',()=>{const f=fixture();throws('transition',()=>f.run('confirm','seller',{proposalVersion:1}));f.run('review','reviewer',{gates:[true,true,true,true,true],reference:'R'});f.run('propose','buyer',{quantity:'1000',price:'100',feePayer:'seller',agentPayer:'none',reference:'P'});throws('forbidden',()=>f.run('confirm','buyer',{proposalVersion:1}));}); test('counterproposal requires confirmation of latest version',()=>{const f=fixture();agreed(f);f.run('propose','seller',{quantity:'1000',price:'99',feePayer:'seller',agentPayer:'none',reference:'P2'});assert.equal(f.c.stage,'negotiating');assert.equal(f.c.proposal.confirmedBy,null);throws('stale',()=>f.run('confirm','buyer',{proposalVersion:1}));f.run('confirm','buyer',{proposalVersion:2});assert.equal(f.c.stage,'agreed');}); test('external instructions require a separately reviewed agreement',()=>{const f=fixture();agreed(f);throws('required',()=>f.run('instruct','rails',{network:'N',destination:'D',paymentRef:'PAY'}));}); test('agreement does not allow silent repricing or nonbinding cancellation',()=>{const f=fixture();agreed(f);f.run('agreement','reviewer',{reference:'AG'});throws('transition',()=>f.run('propose','buyer',{quantity:'1000',price:'99',feePayer:'buyer',agentPayer:'none',reference:'P'}));throws('transition',()=>f.run('withdraw','buyer',{dropReason:'timing',reason:'R'}));}); test('reconciliation requires independent reviewer and both leg reviews',()=>{const f=fixture();delivered(f);throws('forbidden',()=>f.run('reconcile','rails',{reference:'R',paymentChecked:true,assetChecked:true}));throws('required',()=>f.run('reconcile','auditor',{reference:'R',paymentChecked:true,assetChecked:false}));throws('forbidden',()=>f.s.run('reconcile',f.c.id,{confirm:true,reference:'R',paymentChecked:true,assetChecked:true},{id:f.c.delivery.by,role:'auditor'},{expectedVersion:f.c.version,requestId:'INDEPENDENCE'}));}); for(const [field,value]of [['receivedAmount','99999'],['receivedUnits','999'],['network','WRONG'],['destination','WRONG']])test('mismatched '+field+' remains exception with zero recognised volume',()=>{const f=fixture();instructed(f);f.run('deliver','rails',{receivedAmount:'100000',receivedUnits:'1000',network:'N',destination:'D',deliveryRef:'DEL',[field]:value});assert.equal(f.c.stage,'exception');assert.equal(f.s.metrics().principalCents,0);assert.equal(f.s.metrics().glemoCents,0);throws('transition',()=>f.run('reconcile','auditor',{reference:'R',paymentChecked:true,assetChecked:true}));}); test('corrected delivery retains failed receipt in append-only local history',()=>{const f=fixture();instructed(f);f.run('deliver','rails',{receivedAmount:'99999',receivedUnits:'1000',network:'N',destination:'D',deliveryRef:'BAD'});throws('required',()=>f.run('correct','rails',{receivedAmount:'100000',receivedUnits:'1000',network:'N',destination:'D',deliveryRef:'FIX'}));f.run('correct','rails',{receivedAmount:'100000',receivedUnits:'1000',network:'N',destination:'D',deliveryRef:'FIX',reason:'Corrected evidence'});f.run('reconcile','auditor',{reference:'R',paymentChecked:true,assetChecked:true});assert(f.s.history(f.c.id).some(e=>e.data.deliveryRef==='BAD'&&e.stage==='exception'));assert.equal(f.s.metrics().principalCents,10000000);}); test('only reconciled cases contribute volume and fee, never interest/agreement/delivery',()=>{const f=fixture();delivered(f);assert.equal(f.s.metrics().principalCents,0);f.run('reconcile','auditor',{reference:'R',paymentChecked:true,assetChecked:true});assert.equal(f.s.metrics().principalCents,10000000);assert.equal(f.s.metrics().glemoCents,120000);assert.equal(f.s.metrics().actualRevenueCents,null);}); test('allocation conserves cents with explicit payers and optional additional agent',()=>{const f=fixture();reconciled(f);const a=M.allocation(f.c);assert.equal(a.buyerPaysCents,10100000);assert.equal(a.sellerReceivesCents,9860000);assert.equal(a.gatewayCents,20000);assert.equal(a.agentCents,100000);assert.equal(a.buyerPaysCents,a.sellerReceivesCents+a.glemoCents+a.gatewayCents+a.agentCents);for(const feePayer of ['buyer','seller'])for(const agentPayer of ['none','buyer','seller']){const c=structuredClone(f.c);Object.assign(c.proposal,{feePayer,agentPayer});const a=M.allocation(c);assert.equal(a.buyerPaysCents,a.sellerReceivesCents+a.glemoCents+a.gatewayCents+a.agentCents);}}); test('exact decimal units allow no fractional cents or float drift',()=>{assert.equal(M.principal('0.25','100'),2500);assert.equal(M.principal('100000000000','0.01'),100000000000);throws('invalid',()=>M.principal('0.001','0.01'));}); for(const v of ['','-1','0','NaN','Infinity','1e3','1,000','0x10','2.001','9007199254740992'])test('invalid money rejected: '+JSON.stringify(v),()=>throws('invalid',()=>M.cents(v))); test('wrong currency, amount outside offer and malformed input are rejected',()=>{const f=fixture();throws('invalid',()=>f.s.interest({...f.o,currency:'EUR'},'B2',10000000));throws('invalid',()=>f.s.interest(f.o,'B2',1));throws('invalid',()=>f.s.interest(f.o,'B2',M.cents('2000000')));}); test('idempotent replay returns original result and conflicting reuse fails',()=>{const f=fixture(),input={confirm:true,gates:[true,true,true,true,true],reference:'R'},who={role:'reviewer',id:'STAFF-reviewer'},options={expectedVersion:1,requestId:'IDEMP'};const first=f.s.run('review',f.c.id,input,who,options,f.fresh());const replay=f.s.run('review',f.c.id,input,who,options,f.fresh());assert.deepEqual(first.record,replay.record);assert(replay.replayed);throws('stale',()=>f.s.run('review',f.c.id,{...input,reference:'R2'},who,options,f.fresh()));assert.equal(f.s.metrics().rows[2].count,1);}); test('two stores refresh shared local state and stale form version cannot overwrite',()=>{const f=fixture(),other=M.createStore(f.storage,{clock});f.run('review','reviewer',{gates:[true,true,true,true,true],reference:'R'});assert.equal(other.snapshot().cases[0].version,2);throws('stale',()=>other.run('review',f.c.id,{confirm:true,gates:[true,true,true,true,true],reference:'R'},{id:'R2',role:'reviewer'},{expectedVersion:1,requestId:'OTHER'},f.fresh()));}); test('withdrawal retains funnel history but recognises no deal',()=>{const f=fixture();f.run('withdraw','buyer',{dropReason:'timing',reason:'Not now'});const d=f.s.metrics();assert.equal(d.rows[1].count,1);assert.equal(d.currentCounts.withdrawn,1);assert.equal(d.principalCents,0);}); test('UTC filters align campaign, channel and date across stages and costs',()=>{const f=fixture();reconciled(f);f.run('cost','reviewer',{costUSD:'1500',costRef:'C1'});const d=f.s.metrics({campaign:f.o.id,channel:'event',from:'2026-10-16',to:'2026-10-16'});assert.equal(d.costPerInterestCents,150000);assert.equal(d.costPerDealCents,150000);assert.equal(d.rows[7].previousRate,1);const empty=f.s.metrics({channel:'organic'});assert.equal(empty.rows[1].count,0);assert.equal(empty.recordedCostCents,null);assert.equal(f.s.metrics({from:'2026-10-17'}).rows[1].count,0);throws('filterInvalid',()=>f.s.metrics({from:'2026-10-17',to:'2026-10-16'}));throws('filterInvalid',()=>f.s.metrics({from:'2026-02-30'}));}); test('cost evidence is unique and cannot count an invoice twice',()=>{const f=fixture();f.run('cost','reviewer',{costUSD:'1500',costRef:'C1'});throws('duplicate',()=>f.run('cost','reviewer',{costUSD:'1500',costRef:'C1'}));assert.equal(f.s.metrics().recordedCostCents,150000);assert.equal(f.s.metrics().costPerDealCents,null);}); test('native conversation link requires reviewed exact mapping and has attribution-only semantics',()=>{const f=fixture();f.run('review','reviewer',{gates:[true,true,true,true,true],reference:'R'});const d={platformOfferId:'RWA-01',platformBuyerId:'P1',linkedDiscussion:'OPP-DIS-1',mappingRef:'MAP'};throws('linkMismatch',()=>f.run('link','reviewer',d));f.run('link','reviewer',d,{...f.fresh(),nativeMatches:true});assert.equal(f.c.link.attributionOnly,true);assert.equal(f.c.stage,'reviewed');assert.equal(f.s.metrics().principalCents,0);}); test('corrupt session state blocks writes without overwriting source',()=>{const storage=memory();storage.setItem(M.KEY,'{"schema":"broken"}');const s=M.createStore(storage);assert.equal(s.health().valid,false);throws('unavailable',()=>s.observe(Base.samples()[0],'B1'));assert.equal(storage.getItem(M.KEY),'{"schema":"broken"}');s.clear();assert.equal(s.health().valid,true);}); test('storage quota failure retains visible in-memory record and reports nonpersistent state',()=>{const storage={getItem:()=>null,setItem(){throw Error('quota');},removeItem(){}};const s=M.createStore(storage,{clock}),o=Base.samples()[0];s.observe(o,'B1');s.interest(o,'B1',M.cents('25000'));assert.equal(s.snapshot().cases.length,1);assert.equal(s.health().persistent,false);}); test('export snapshots cannot mutate internal history or counted principal',()=>{const f=fixture();reconciled(f);const s=f.s.snapshot();s.cases[0].reconciliation.allocation.principalCents=1;s.events.length=0;assert.equal(f.s.metrics().principalCents,10000000);assert(f.s.history(f.c.id).length>0);assert(M.validate(f.s.snapshot()));}); test('missing nested proposal or allocation is rejected during restore without raw overwrite',()=>{for(const field of ['proposal','allocation','wrongFee']){const f=fixture();reconciled(f);const broken=f.s.snapshot();if(field==='proposal')broken.cases[0].proposal=null;else if(field==='allocation')broken.cases[0].reconciliation.allocation=null;else broken.cases[0].reconciliation.allocation.glemoCents=1;assert.equal(M.validate(broken),false);const raw=JSON.stringify(broken);f.storage.setItem(M.KEY,raw);const s=M.createStore(f.storage);assert.equal(s.health().valid,false);assert.equal(s.metrics().principalCents,0);assert.equal(f.storage.getItem(M.KEY),raw);}}); test('same-version reinterest retains cohort/history but requires fresh review',()=>{const f=fixture();agreed(f);f.run('withdraw','buyer',{dropReason:'timing',reason:'Later'});const c=f.s.interest(f.o,'B1',M.cents('120000'),'organic');assert.equal(c.id,f.c.id);assert.equal(c.stage,'interested');assert.equal(c.channel,'event');assert.equal(c.proposal,null);assert.equal(c.agreement,null);assert.equal(f.s.metrics().rows[1].count,1);assert(f.s.history(c.id).some(e=>e.action==='withdraw'));assert(M.validate(f.s.snapshot()));}); test('denied storage reads use clearly nonpersistent memory mode',()=>{const storage={getItem(){throw Error('denied');},setItem(){throw Error('denied');},removeItem(){}};const s=M.createStore(storage,{clock}),o=Base.samples()[0];assert.equal(s.health().valid,true);assert.equal(s.health().persistent,false);s.observe(o,'B1');assert.equal(s.interest(o,'B1',2500000).stage,'interested');});