Treasury & Bank Transfer Management System — سامانه مدیریت خزانه‌داری و حواله‌های بانکی

1 import assert from 'node:assert/strict';
2 import {spawn,execFileSync} from 'node:child_process';
3 import {existsSync,mkdirSync,writeFileSync} from 'node:fs';
4 import {join} from 'node:path';
5 const [exe,fixtureDir]=process.argv.slice(2);
6 assert.equal(process.platform,'win32');
7 assert(exe&&existsSync(exe)&&fixtureDir,'EXACT_INSTALLED_EXE_AND_ISOLATED_DIR_REQUIRED');
8 mkdirSync(fixtureDir,{recursive:true});
9 const root='http://127.0.0.1:3210',debug='http://127.0.0.1:9345';
10 const sleep=ms=>new Promise(ok=>setTimeout(ok,ms));
11 const report={status:'NOT_RUN',cdpConnected:false,bankDisabled:false,
12 pages:[],actualLocalClick:false,stage:'BOOT',reconnections:0};
13 let app,conn;
14 async function targets(){
15 const response=await fetch(debug+'/json/list',{signal:AbortSignal.timeout(2000)});
16 assert(response.ok,'CDP_TARGET_LIST_UNAVAILABLE');
17 return response.json();
18 }
19 async function connect(target){
20 const ws=new WebSocket(target);
21 await new Promise((ok,fail)=>{
22 const timer=setTimeout(()=>fail(Error('CDP_CONNECT_TIMEOUT')),10000);
23 ws.addEventListener('open',()=>{clearTimeout(timer);ok()},{once:true});
24 ws.addEventListener('error',()=>{clearTimeout(timer);fail(Error('CDP_CONNECT_ERROR'));},{once:true});
25 });
26 let id=0;const pending=new Map();
27 ws.addEventListener('message',message=>{
28 let v;try{v=JSON.parse(message.data)}catch{return}
29 const p=pending.get(v.id);if(!p)return;
30 pending.delete(v.id);clearTimeout(p.timer);
31 v.error?p.fail(Error('CDP_REMOTE_ERROR')):p.ok(v.result);
32 });
33 const send=(method,params={})=>new Promise((ok,fail)=>{
34 const n=++id,timer=setTimeout(()=>{pending.delete(n);fail(Error('CDP_COMMAND_TIMEOUT'))},12000);
35 pending.set(n,{ok,fail,timer});
36 ws.send(JSON.stringify({id:n,method,params}));
37 });
38 const evaluate=async expression=>{
39 const reply=await send('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});
40 if(reply.exceptionDetails)throw Error('CDP_SCRIPT_ERROR');
41 return reply.result?.value;
42 };
43 await send('Runtime.enable');await send('Page.enable');
44 return {ws,send,evaluate,uri:target};
45 }
46 async function until(fn,timeoutMs=65000){
47 const stop=Date.now()+timeoutMs;let latest;
48 while(Date.now()<stop){
49 // On Windows, the launcher PID may exit after handing off to a renderer.
50 // Require actual localhost readiness and CDP instead of equating launcher
51 // lifecycle with failure. The test deadline remains bounded.
52 if(app?.exitCode!==null&&app?.exitCode!==undefined)report.launcherExited=true;
53 try{const outcome=await fn();if(outcome)return outcome}catch(e){latest=e}
54 await sleep(350);
55 }
56 throw latest||Error('CDP_NATIVE_ROUTE_TIMEOUT');
57 }
58 async function attach(expectedPath){
59 const listing=await targets();
60 const matched=listing.find(p=>p.type==='page'&&p.url?.startsWith(root)&&p.webSocketDebuggerUrl);
61 if(!matched)return null;
62 if(!conn||conn.uri!==matched.webSocketDebuggerUrl){
63 const fresh=await connect(matched.webSocketDebuggerUrl);
64 try{conn?.ws.close()}catch{}
65 conn=fresh;report.reconnections++;
66 }
67 const result=await conn.evaluate("({route:location.pathname,text:document.body?.innerText||'',anchors:[...document.querySelectorAll('a')].map(a=>a.getAttribute('href'))})");
68 return result?.route===expectedPath?result:null;
69 }
70 async function go(path,heading){
71 report.stage='ROUTE_'+path.replace(/[^a-z]/gi,'_');
72 const initial=await attach(path).catch(()=>null);
73 if(!initial){
74 if(conn)await conn.send('Page.navigate',{url:root+path}).catch(()=>null);
75 else {
76 await until(async()=>{const targetsNow=await targets();return targetsNow.some(p=>p.type==='page'&&p.url?.startsWith(root))});
77 const existing=await attach('/login').catch(()=>null);
78 if(!existing){const listing=await targets();const t=listing.find(p=>p.type==='page'&&p.webSocketDebuggerUrl);if(t)conn=await connect(t.webSocketDebuggerUrl)}
79 await conn?.send('Page.navigate',{url:root+path}).catch(()=>null);
80 }
81 }
82 return until(async()=>{
83 const p=await attach(path);
84 return p&&p.text.includes(heading)?p:null;
85 },65000);
86 }
87 try{
88 const separateUserData=join(fixtureDir,'isolated-electron-localappdata');
89 const roamingUserData=join(fixtureDir,'isolated-electron-roaming-appdata');
90 mkdirSync(separateUserData,{recursive:true});
91 mkdirSync(roamingUserData,{recursive:true});
92 // Electron userData on Windows defaults to APPDATA (Roaming), not LOCALAPPDATA.
93 // Both must be isolated after force-killing the preceding synthetic launcher.
94 const env={...process.env,LOCALAPPDATA:separateUserData,APPDATA:roamingUserData,TREASURYFLOW_DESKTOP_LOCAL:'1',BANK_ADAPTER_MODE:'disabled',
95 TREASURYFLOW_ENABLE_MAYAN_EXTERNAL_READ:'0',TREASURYFLOW_MAYAN_ENABLE_EXTERNAL_READ:'0',
96 TREASURYFLOW_ENABLE_SQL_LAB:'0',
97 TREASURYFLOW_DATA_FILE:join(fixtureDir,'synthetic-v7-ui.sqlite')};
98 const prior=await fetch(root+'/api/ready',{signal:AbortSignal.timeout(900)}).then(()=>true,()=>false);
99 assert(!prior,'STALE_LOCAL_SERVICE_BEFORE_TEST');
100 app=spawn(exe,['--remote-debugging-port=9345','--remote-allow-origins=*'],{env,stdio:'ignore'});
101 report.stage='LOCAL_READY';
102 const ready=await until(async()=>{
103 const r=await fetch(root+'/api/ready',{signal:AbortSignal.timeout(1400)});
104 if(!r.ok)return null;
105 const v=await r.json();
106 return v.status==='ready'&&v.bankAdapter==='disabled'?v:null;
107 },65000);
108 assert.equal(ready.bankAdapter,'disabled');
109 report.bankDisabled=true;
110 const login=await go('/login','ورود به محیط محلی امن');
111 report.cdpConnected=true;
112 assert(login.anchors.includes('/dashboard'),'NATIVE_LOCAL_LOGIN_ENTRY_MISSING');
113 const clicked=await conn.evaluate("(()=>{const anchor=document.querySelector('a[href=\"/dashboard\"]');if(!anchor)return false;anchor.click();return true})()");
114 assert(clicked,'NATIVE_ENTRY_NOT_CLICKABLE');
115 await until(async()=>attach('/dashboard').then(x=>x?.text.includes('داشبورد خزانه‌داری')?x:null),65000);
116 report.actualLocalClick=true;
117 for(const [route,title] of [
118 ['/dashboard','داشبورد خزانه‌داری'],['/payments','حواله‌ها'],
119 ['/accounts','حساب‌های بانکی'],['/queue','صف ارسال بانکی'],
120 ['/audit','رویدادهای حسابرسی']]){
121 const view=await go(route,title);
122 assert(view.text.includes(title),'NATIVE_ROUTE_HEADING_MISSING');
123 report.pages.push({route,pass:true});
124 }
125 const queue=await go('/queue','صف ارسال بانکی');
126 assert(queue.text.includes('غیرفعال'),'LIVE_BANK_MUST_REMAIN_DISABLED');
127 const screen=await conn.send('Page.captureScreenshot',{format:'png'});
128 assert(typeof screen.data==='string'&&screen.data.length>1000,'NATIVE_REAL_RENDERER_SCREENSHOT_MISSING');
129 report.screenshot=true;
130 report.status='PASS';
131 console.log('GATE_PASS_V7_NONFINAL_REAL_ELECTRON_CDP_LOGIN_CLICK_FIVE_ROUTES_SIX_PAGES_BANK_DISABLED');
132 }catch(e){
133 report.status='FAIL';
134 report.error=String(e?.message||'UNKNOWN').replace(/[^A-Z0-9_]/gi,'_').slice(0,90);
135 report.launcherExitCode=Number.isInteger(app?.exitCode)?app.exitCode:null;
136 report.cdpAttempts=report.reconnections;
137 console.log('V7_NATIVE_CDP_FAILURE_CLASS_'+report.error);
138 process.exitCode=1;
139 }finally{
140 try{conn?.ws.close()}catch{}
141 if(app?.pid)try{execFileSync('taskkill.exe',['/PID',String(app.pid),'/T','/F'],{stdio:'ignore',timeout:14000})}catch{}
142 writeFileSync(join(fixtureDir,'v7-native-cdp-qa.json'),JSON.stringify(report,null,2));
143 }