'use strict'; const test=require('node:test'),assert=require('node:assert/strict'); const {summary}=require('../../src/modules/order-rules/query.cjs'); const {windowForCutoff}=require('../../src/modules/order-rules/window.cjs'); const alice={username:'alice',role:'operator'},admin={username:'admin',role:'admin'}; function fixture(){ const data={},schedule={times:['11:00','17:00'],weekends:false}; const store={all:k=>data[k]||[],get:(k,id)=>(data[k]||[]).find(r=>r.id===id),snapshot:()=>({}),clock:()=>new Date('2026-10-26T01:00:00Z'),schedule:()=>schedule,calendar:()=>[],settings:()=>({}),intakeWindow:()=>null}; const add=(id,categoryId='a',connectionId='alice-source',extra={})=>{ const event={source:'todo',connectionId,taskId:id,instanceId:id,processName:'process',nodeName:'node',receivedAt:'2026-10-26T00:30:00Z',fields:{private:'RAW-SECRET'}}; const rule={id:categoryId,categoryId,name:'Category '+categoryId,version:1,scopes:[{processName:'process',nodeName:'node'}],huizhouEnabled:true,to:['SECRET@example.com'],cc:['CC@example.com'],intro:'BODY-SECRET'}; const order={id,categoryId,status:'pending',sample:event,event,ruleSnapshot:rule,notifications:{huizhou:{status:'pending',orderNos:['H-'+id],issues:[]}},...extra}; (data.orders||=[]).push(order);return order; }; return {data,store,add,context:{orderRules:store,workspace:{recordSources:()=>[{id:'alice-source',owner:'alice'},{id:'bob-source',owner:'bob'}]}}}; } test('home counts physical orders once across normal and Hui current collection and omits historical/removed orders',()=>{ const f=fixture();f.add('one');f.add('two');f.add('removed','removed','alice-source',{removedAt:'2026-10-26T00:40:00Z'}); const old=f.add('old','old');old.event.receivedAt='2026-10-20T00:00:00Z'; f.data.batches=[{id:'prepared-old',categoryId:'old',status:'prepared',orderIds:['old']},{id:'unknown-old',status:'unknown',orderIds:['old']}]; const result=summary(f.context,alice); assert.equal(result.home?.pendingOrders,2);assert.equal(result.home.collectingBatches,2);assert.equal(result.home.carriedOrders,0); assert.deepEqual(result.counts,{orders:3,blocked:0,unknown:1,activeBatches:4}); assert.deepEqual(result.home.batches.map(b=>[b.categoryName,b.notificationMode,b.orderCount,b.carryCount,b.cutoff]),[ ['Category a','normal',2,0,'2026-10-26T03:00:00.000Z'],['Category a','huizhou',2,0,'2026-10-26T03:00:00.000Z']]); for(const row of result.home.batches){assert.deepEqual(Object.keys(row).sort(),['id','categoryId','categoryName','notificationMode','orderCount','carryCount','cutoff','error'].sort());assert.equal(typeof row.error,'string');} assert.doesNotMatch(JSON.stringify(result.home),/SECRET|orderIds|ruleSnapshot|subject|text|html/); }); test('home respects entire-batch ownership for operators and viewers, and rechecks ownership each request',()=>{ const f=fixture();f.add('own','own');f.add('mixed-own','mixed');f.add('mixed-private','mixed','bob-source');f.add('private','private','bob-source'); for(const role of ['operator','viewer']){const home=summary(f.context,{...alice,role}).home;assert.equal(home?.pendingOrders,1);assert.equal(home.collectingBatches,2);assert(home.batches.every(b=>b.categoryId==='own'));} assert.equal(summary(f.context,admin).home.pendingOrders,4);assert.equal(summary(f.context,admin).home.collectingBatches,6); f.context.workspace.recordSources=()=>[{id:'alice-source',owner:'bob'},{id:'bob-source',owner:'bob'}]; assert.deepEqual(summary(f.context,alice).home,{pendingOrders:0,collectingBatches:0,carriedOrders:0,batches:[],lastScanAt:null}); }); test('home previews at most four groups without truncating aggregate counts',()=>{ const f=fixture();for(const id of ['a','b','c'])f.add(id,id); const home=summary(f.context,admin).home; assert.equal(home?.batches.length,4);assert.equal(home.collectingBatches,6);assert.equal(home.pendingOrders,3); }); test('home deduplicates carried physical orders across notification modes without mutating durable records',()=>{ const f=fixture(),order=f.add('carried'); order.archive={archivedAt:'2026-10-23T02:00:00Z',files:[{name:'x.pdf',path:'C:\\x.pdf',sha256:'a'.repeat(64),size:1,kind:'pdf'}]}; order.event.receivedAt='2026-10-23T01:00:00Z'; f.data['execution-tasks']=[{id:'task',orderId:order.id,connectionId:'alice-source',row:order.sample,sampleId:'capture',status:'pending',step:'complete'}]; f.data['capture-samples']=[{id:'capture',taskId:'task',provenance:'server-provider',sample:order.sample,snapshot:{html:'
capture
'}}]; f.store.intakeWindow=()=>windowForCutoff('2026-10-23T03:00:00.000Z',f.store.schedule()); const basisHash=require('../../src/modules/order-rules/task-identity.cjs').digest([order.sourceHash,order.sample,order.ruleSnapshot,order.archiveGeneration,order.archive]); order.carryForward={normal:{basisHash,targetCutoff:'2026-10-26T03:00:00.000Z'},huizhou:{basisHash,targetCutoff:'2026-10-26T03:00:00.000Z'}}; const before=structuredClone(f.data),home=summary(f.context,alice).home; assert.equal(home?.carriedOrders,1);assert.equal(home.pendingOrders,1);assert.deepEqual(home.batches.map(b=>b.carryCount),[1,1]);assert.deepEqual(f.data,before); }); test('home last scan selects latest valid successful authorized completion and supports empty state',()=>{ const f=fixture();assert.deepEqual(summary(f.context,alice).home,{pendingOrders:0,collectingBatches:0,carriedOrders:0,batches:[],lastScanAt:null}); f.data['execution-scans']=[ {id:'older',connectionId:'alice-source',status:'complete',finishedAt:'2026-10-26T00:00:00Z'}, {id:'latest',connectionId:'alice-source',status:'complete',finishedAt:'2026-10-26T00:30:00Z'}, {id:'failed',connectionId:'alice-source',status:'failed',finishedAt:'2026-10-26T00:50:00Z'}, {id:'invalid',connectionId:'alice-source',status:'complete',finishedAt:'bad-date'}, {id:'private',connectionId:'bob-source',status:'complete',finishedAt:'2026-10-26T00:55:00Z'}]; assert.equal(summary(f.context,alice).home.lastScanAt,'2026-10-26T00:30:00Z');assert.equal(summary(f.context,admin).home.lastScanAt,'2026-10-26T00:55:00Z'); });