import test from 'node:test'; import assert from 'node:assert/strict'; import {readFile} from 'node:fs/promises'; import {createRequire} from 'node:module'; import vm from 'node:vm'; import {modules} from '../src/core/modules.ts'; import {allows} from '../src/core/network.ts'; import * as dateDisplay from '../src/core/date-display.ts'; import {purchaseRecordStatus} from '../src/core/record-presentation.ts'; const require=createRequire(import.meta.url),React=require('react'),ts=require('typescript'); async function screen({mode='arrival',failure=false,lookup=undefined}={}){ const source=await readFile(new URL('../src/screens/ArrivalOperation.tsx',import.meta.url),'utf8'); const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,jsx:ts.JsxEmit.ReactJSX,esModuleInterop:true}}).outputText; const values=[],refs=[],calls=[];let cursor=0,refCursor=0,done=0,restore; const record={id:101,arrivalNo:'DH-101',arrivalQuantity:3,acceptanceStatus:0,label:'DH-101 · 3 个'}; const react={...React,useState:initial=>{const i=cursor++;if(!(i in values))values[i]=initial;return[values[i],v=>values[i]=typeof v==='function'?v(values[i]):v];},useRef:initial=>{const i=refCursor++;return refs[i]??= {current:initial};},useEffect:()=>{}}; const native={Modal:'Modal',ScrollView:'ScrollView',View:'View',KeyboardAvoidingView:'KeyboardAvoidingView',Platform:{OS:'android'}}; const ui={useTheme:()=>({bg:'#fff'}),s:{},Button:'Button',Card:'Card',Choice:'Choice',DateField:'DateField',Field:'Field',Heading:'Heading',Note:'Note'}; const imports={'./ArrivalHistory':{ArrivalHistory:'ArrivalHistory'},'./ArrivalPhotos':{ArrivalPhotos:'ArrivalPhotos'},react,'react/jsx-runtime':require('react/jsx-runtime'),'react-native':native,'react-native-safe-area-context':{SafeAreaView:'SafeAreaView'},'expo-crypto':{randomUUID:()=> 'stable-test-key'},'../ui':ui,'../core/date-display':dateDisplay,'../core/modules':{display:v=>v??'—',localDate:()=> '2026-10-19',validDate:v=>v==='2026-10-19'},'../dialogs':{Dialog:{alert(){}}},'../hooks/useOperationDraft':{useOperationDraft:options=>{restore=options.onRestore;return {ready:true,restored:false,error:'',saveNow:async()=>{},clear:async()=>{}}}}}; imports['./ItemIdentity']={ItemIdentity:'ItemIdentity'};imports['../core/record-presentation']={purchaseRecordStatus}; const module={exports:{}};vm.runInNewContext(compiled,{module,exports:module.exports,require:name=>imports[name]||require(name),AbortController}); const api={async request(path,options){calls.push({path,...options});if(path.endsWith('/submission')&&lookup!==undefined)return {data:lookup};if(failure)throw Error('timeout');return {data:{}};}}; const render=()=>{cursor=0;refCursor=0;const root=module.exports.ArrivalOperation({api,row:{id:10,materialName:'电机',remainingQuantity:2,unit:'个'},mode,close(){},done(){done++;}});return typeof root.type==='function'?root.type(root.props):root;}; let tree=render();if(mode==='accept'){values[3]=[record];values[4]=record;values[5]=false;tree=render();} function find(type,prop,value,node=tree){if(!node||typeof node!=='object')return null;if(node.type===type&&node.props[prop]===value)return node;for(const child of React.Children.toArray(node.props?.children)){const match=find(type,prop,value,child);if(match)return match;}return null;} return {calls,get tree(){return tree;},restore(value){restore(value);tree=render();},get done(){return done;},render(){tree=render();},button:title=>find('Button','title',title),field:label=>find('Field','label',label),photos:()=>find('ArrivalPhotos','requestId',10)}; } const settle=()=>new Promise(resolve=>setImmediate(resolve)); test('five field operations are distinct entries; read-only accounts do not gain write entries',()=>{ for(const key of ['arrival','pending','use','move','count'])assert.ok(modules.some(m=>m.key===key)); const permissions=['warehouse:stock:list']; assert.ok(modules.find(m=>m.key==='stock').permissions.every(p=>allows(permissions,p))); for(const key of ['arrival','use','move','count'])assert.equal(modules.find(m=>m.key===key).permissions.every(p=>allows(permissions,p)),false); }); test('registering arrival previews first, then submits one stable request through the existing API',async()=>{ const photo='11111111-1111-4111-8111-111111111111'; const s=await screen();assert.equal(s.calls.length,0);s.photos().props.onChange([{id:photo}]);s.render();s.button('本次全部到齐').props.onPress();s.render();assert.equal(s.field('本次到货数量').props.value,'2');s.button('核对预览').props.onPress();s.render();assert.equal(s.calls.length,0);s.button('确认提交').props.onPress();await settle(); assert.equal(s.calls.length,1);assert.equal(s.calls[0].path,'/warehouse/purchase/arrival');assert.equal(s.calls[0].body.requestKey,'stable-test-key');assert.equal(s.calls[0].body.arrivalQuantity,2);assert.equal(s.done,1); }); test('arrival quantity above the remaining amount cannot reach confirmation',async()=>{ const s=await screen();s.field('本次到货数量').props.onChange('3');s.render();s.button('核对预览').props.onPress();s.render();assert.equal(s.button('确认提交'),null);assert.equal(s.calls.length,0); }); test('arrival without a completed photo cannot preview or submit; a failed upload is not evidence',async()=>{ const s=await screen();s.button('核对预览').props.onPress();s.render();assert.equal(s.button('确认提交'),null);assert.equal(s.calls.length,0); s.photos().props.onChange([{clientKey:'failed',error:'upload failed'}]);s.render();s.button('核对预览').props.onPress();s.render();assert.equal(s.button('确认提交'),null);assert.equal(s.calls.length,0); }); test('arrival retry preserves the original idempotency key and body after a lost response',async()=>{ const s=await screen({failure:true});s.photos().props.onChange([{id:'11111111-1111-4111-8111-111111111111'}]);s.render();s.button('本次全部到齐').props.onPress();s.render();s.button('核对预览').props.onPress();s.render();s.button('确认提交').props.onPress();await settle();s.render();assert.equal(s.button('返回修改').props.disabled,true);s.button('核对后重试原请求').props.onPress();await settle();assert.equal(s.calls.length,2);assert.deepEqual(s.calls[0].body,s.calls[1].body); }); test('old acceptance navigation opens arrival history without submitting acceptance',async()=>{ const s=await screen({mode:'accept'});assert.equal(s.tree.type,'ArrivalHistory');assert.equal(s.tree.props.canSupplement,true);assert.equal(s.calls.length,0);assert.equal(s.button('确认提交'),null); }); test('a rejected old photo-free draft can be checked, repaired and retried using its original key',async()=>{ const s=await screen({failure:true,lookup:null}); s.restore({quantity:'2',date:'2026-10-19',attempted:true,photos:[],requestKey:'old-stable-key',preview:{body:{purchaseRequestId:10,arrivalQuantity:2,photoIds:[]}}}); s.button('核对提交结果').props.onPress();await settle();s.render(); assert.equal(s.calls[0].path,'/warehouse/purchase/arrival/10/submission');assert.equal(s.calls[0].query.requestKey,'old-stable-key');assert.equal(s.photos().props.readonly,false);assert.ok(s.button('核对预览')); s.photos().props.onChange([{id:'11111111-1111-4111-8111-111111111111'}]);s.render();s.button('核对预览').props.onPress();s.render();s.button('确认提交').props.onPress();await settle(); assert.equal(s.calls.at(-1).body.requestKey,'old-stable-key');assert.equal(s.calls.at(-1).body.photoIds.length,1); }); test('recovering an already-saved photo-free arrival offers direct supplements instead of a duplicate registration',async()=>{ const s=await screen({lookup:{id:708,arrivalNo:'DH-708',arrivalQuantity:2,photos:[]}}); s.restore({quantity:'2',date:'2026-10-19',attempted:true,requestKey:'original',preview:{body:{purchaseRequestId:10,photoIds:[]}}}); s.button('核对提交结果').props.onPress();await settle();s.render(); assert.equal(s.photos().props.arrivalId,708);assert.equal(s.photos().props.supplemental,true);assert.equal(s.button('确认提交'),null);assert.equal(s.calls.filter(call=>call.method==='POST').length,0); });