فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

fix/a02-disable-destructive-excel-replace-20261031
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 666 lines 35.2 KB
Raw
1 'use strict';
2 // Executed as a single async expression inside an INSTALLED Tauri WebView2,
3 // on a disposable Windows VM after synthetic financial fixtures are created.
4 // This does not click destructive actions; these need separate fixture-backed
5 // accounting correctness tests. Never claim "all buttons work" from a sweep.
6 (async () => {
7 const wait = ms => new Promise(r => setTimeout(r, ms));
8 const routes = [
9 'dashboard','invoices','products','contacts','treasury',
10 'cheques','expenses','reports','accounting','settings'
11 ];
12 const failures = [];
13 const inventories = [];
14 const clicks = [];
15 const skipped = [];
16 const all = new Map();
17 const fields = new Map();
18 const target = () => document.getElementById('pageContent');
19 const isVisible = el => {
20 const style = window.getComputedStyle(el);
21 return style.display !== 'none' && style.visibility !== 'hidden' &&
22 el.getClientRects().length > 0;
23 };
24 const name = el => String(
25 el.getAttribute('aria-label') || el.getAttribute('title') ||
26 el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 90);
27 const handler = el => el.getAttribute('onclick') ||
28 el.getAttribute('onchange') || el.getAttribute('onsubmit') || '';
29 const sig = (el, route, section) => [
30 route, section, el.tagName.toLowerCase(), name(el),
31 handler(el).replace(/\s+/g,' ').slice(0,180)
32 ].join('|');
33 const dangerous = /(?:^|[.\s])(?:_?(?:save|delete|wipe|restore|post|submit|confirm|activate|seed|commit|final|approve|logout|export|import|download|print|settle|apply|reset|changeStatus|remove)\w*)\s*\(/i;
34 const safeTab = /\.(?:_switchTab|switchTab|_switchPeriod|_setPreset)\s*\(/;
35 const safeOpen = /\.(?:openNewInvoice|openProductModal|openUnitModal|openCategoryModal|openContactModal|openExpenseModal|openChequeModal|openAccountModal|openReceiptModal|openPaymentModal|openTransferModal|openCompanyModal|openCompanySwitcher|openExportSectionModal|openSignedLicenseModal|openAuditTrail|openWipeModal|openRestoreModal|openPeriodModal|openJournalModal|openWarehouse|openStocktakeCreate|openTransfer|openReversal|_openQuickProduct|_openQuickContact|openLedger|openKardex|openStocktake|showJournal)\s*\(/;
36 const clickables = (root) => [...root.querySelectorAll(
37 'button, a, [role="button"], input[type="button"], input[type="submit"], [onclick]'
38 )].filter(isVisible);
39 function auditFields(root, route, section) {
40 if (!root) return;
41 let fieldIndex = 0;
42 for (const field of root.querySelectorAll(
43 'input:not([type="hidden"]), select, textarea'
44 )) {
45 const ordinal = fieldIndex++;
46 if (!isVisible(field)) continue;
47 const labels=field.labels ? [...field.labels] : [];
48 const explicit=!!field.getAttribute('aria-label') ||
49 !!field.getAttribute('aria-labelledby') ||
50 !!field.closest('label') || labels.length > 0;
51 const id=field.id||'';
52 const key=[route,section,ordinal,field.tagName.toLowerCase(),id,
53 field.getAttribute('name')||'',field.getAttribute('type')||''].join('|');
54 if (fields.has(key)) continue;
55 fields.set(key,{
56 route,section,ordinal,id,tag:field.tagName.toLowerCase(),
57 type:field.getAttribute('type')||'',
58 label:labels.map(x=>x.textContent.trim().slice(0,75)).join(' / ') ||
59 field.getAttribute('aria-label') || '',
60 programmaticLabel:explicit,
61 placeholderOnly:!explicit && !!field.getAttribute('placeholder'),
62 status:explicit?'programmatic-label-found':'needs-accessibility-review'
63 });
64 }
65 }
66 function inventory(route, section) {
67 const controls = clickables(target());
68 auditFields(target(),route,section);
69 const records = [];
70 for (const el of controls) {
71 const k=sig(el,route,section);
72 if (all.has(k)) continue;
73 const code=handler(el);
74 const accessible=!!name(el);
75 const row={
76 route,section,tag:el.tagName.toLowerCase(),
77 label:name(el),handler:code.slice(0,220),
78 disabled:!!el.disabled || el.getAttribute('aria-disabled')==='true',
79 hasAccessibleName:accessible,
80 className:String(el.className||'').slice(0,120),
81 type:el.getAttribute('type')||'',
82 status:'not-clicked',reason:''
83 };
84 all.set(k,row); records.push(row);
85 }
86 inventories.push({route,section,newControls:records.length,totalVisible:controls.length});
87 return controls;
88 }
89 async function go(route) {
90 const link=document.querySelector('#sidebarMenu [data-page="'+route+'"]');
91 if (!link) throw Error('main sidebar menu item missing: '+route);
92 link.click(); await wait(160);
93 if (FINORA.Router.current()!==route) throw Error('sidebar click did not navigate: '+route);
94 if (!target() || target().textContent.trim().length < 10 ||
95 target().textContent.includes('خطا در بارگذاری صفحه')) {
96 throw Error('screen blank/failed after clicking: '+route);
97 }
98 if (document.getElementById('finoraAuthOverlay')) throw Error('auth returned during navigation');
99 }
100 const noError = () => !document.querySelector('.toast-error') &&
101 !target()?.textContent.includes('خطا در بارگذاری صفحه');
102 function dismiss() {
103 FINORA.Modal.closeAll();
104 document.querySelectorAll('.toast-close').forEach(x=>x.click());
105 }
106 function resolveHandler(code) {
107 const m=code.match(/(?:window\.)?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+)\s*\(/);
108 if (!m) return {detected:false,valid:null,callee:''};
109 const parts=m[1].split('.');
110 let obj=window;
111 for (const part of parts) {
112 if (obj == null) return {detected:true,valid:false,callee:m[1]};
113 obj=obj[part];
114 }
115 return {detected:true,valid:typeof obj==='function',callee:m[1]};
116 }
117 const seenClick = new Set();
118 async function press(el, route, section, category) {
119 const k=sig(el,route,section);
120 if (seenClick.has(k)) return;
121 seenClick.add(k);
122 const row=all.get(k);
123 const before=target().innerHTML;
124 const beforeModal=!!document.querySelector('.modal-backdrop');
125 try {
126 el.click(); await wait(180);
127 if (!noError()) throw Error('error toast or page render error');
128 const after=target()?.innerHTML||'';
129 const afterModal=!!document.querySelector('.modal-backdrop');
130 const changed = before !== after || beforeModal !== afterModal;
131 clicks.push({route,section,category,label:name(el),
132 handler:handler(el).slice(0,170),changed,afterModal});
133 if (row) {row.status='clicked';row.reason=changed?'visible-state-changed':'no-observable-DOM-change';}
134 if (!changed) {
135 const expectedNoop = /\._clearFilters\(\)|\.switchTab\('journals'\)/.test(handler(el));
136 if (expectedNoop) {
137 if (row) row.reason='idempotent-click-on-already-selected-or-clear-filter-state';
138 } else {
139 failures.push({route,section,kind:'no-visible-change',
140 label:name(el),handler:handler(el).slice(0,170)});
141 }
142 }
143 } catch(error) {
144 failures.push({route,section,kind:'click-error',label:name(el),error:String(error.message).slice(0,170)});
145 if (row) {row.status='failed';row.reason='UI click error';}
146 } finally { if (category !== 'open') dismiss(); }
147 }
148 // Explicit shell regression: semantic links, keyboard focus, active route,
149 // persistent sidebar collapse and reversible theme toggle.
150 const navLinks=[...document.querySelectorAll('#sidebarMenu a[data-page]')];
151 if (navLinks.length !== routes.length) throw Error('sidebar navigation count mismatch');
152 for(const link of navLinks) {
153 const route=link.dataset.page;
154 if(link.getAttribute('href')!=='#'+route || link.tabIndex<0 ||
155 !link.getAttribute('aria-label')) throw Error('sidebar link is not keyboard accessible: '+route);
156 }
157 const hamburger=document.getElementById('sidebarToggleBtn');
158 if(!hamburger || !hamburger.getAttribute('aria-label') ||
159 hamburger.getAttribute('aria-controls')!=='sidebarMenu') {
160 throw Error('sidebar accessible toggle missing');
161 }
162 const beforeCollapsed=document.getElementById('sidebar').classList.contains('collapsed');
163 hamburger.click();await wait(70);
164 const afterCollapsed=document.getElementById('sidebar').classList.contains('collapsed');
165 if (beforeCollapsed===afterCollapsed ||
166 localStorage.getItem('finora_pro_sidebar_collapsed')!==String(afterCollapsed) ||
167 hamburger.getAttribute('aria-expanded')!==String(!afterCollapsed)) {
168 throw Error('sidebar click did not persist synchronized collapsed and aria-expanded state');
169 }
170 hamburger.click();await wait(70);
171 if(document.getElementById('sidebar').classList.contains('collapsed')!==beforeCollapsed ||
172 localStorage.getItem('finora_pro_sidebar_collapsed')!==String(beforeCollapsed)) {
173 throw Error('sidebar click did not restore the prior saved state');
174 }
175 const themeButton=document.getElementById('themeToggleBtn');
176 const originalTheme=document.documentElement.getAttribute('data-theme');
177 if(!themeButton || !themeButton.getAttribute('title'))throw Error('theme button missing accessible name');
178 themeButton.click();await wait(50);
179 if(document.documentElement.getAttribute('data-theme')===originalTheme)throw Error('theme toggle was inert');
180 themeButton.click();await wait(50);
181 if(document.documentElement.getAttribute('data-theme')!==originalTheme ||
182 localStorage.getItem('finora_pro_theme')!==originalTheme)throw Error('theme setting not reversible/persisted');
183 // Cross-app dialog behavior: nested modal focus, Escape and focus return.
184 const modalTrigger=hamburger;
185 modalTrigger.focus();
186 if (getComputedStyle(modalTrigger).display === 'none' ||
187 document.activeElement !== modalTrigger) {
188 throw Error('Desktop sidebar toggle cannot receive keyboard focus before opening a dialog');
189 }
190 let unexpectedConfirm=false;
191 FINORA.Modal.open({title:'Q01 Synthetic outer dialog',
192 body:'<input id="q01ModalField" value="synthetic" />',
193 footer:'<button class="btn" onclick="FINORA.Modal.close()">بستن</button>'});
194 await wait(30);
195 const outer=document.querySelector('.modal-card[role="dialog"][aria-modal="true"]');
196 if(!outer || !outer.querySelector('[id^="finora-dialog-title-"]') ||
197 !outer.contains(document.activeElement)) throw Error('outer dialog ARIA or focus absent');
198 FINORA.Modal.confirm({title:'Q01 Synthetic nested confirmation',
199 message:'Synthetic data only; no operation permitted',
200 onConfirm:()=>{unexpectedConfirm=true;}});
201 await wait(30);
202 const stack=[...document.querySelectorAll('.modal-card[role="dialog"]')];
203 if(stack.length!==2 || stack[0].getAttribute('aria-hidden')!=='true' ||
204 !stack[1].contains(document.activeElement)) throw Error('nested dialog focus/isolation failed');
205 // Check a real Tab/Shift+Tab wrap, which an accessibility contract
206 // cannot prove from source alone. Neither key may escape the top dialog.
207 const topControls=[...stack[1].querySelectorAll(
208 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])'
209 )].filter(el=>el.getClientRects().length>0 && getComputedStyle(el).visibility!=='hidden');
210 if(topControls.length<2)throw Error('nested modal focus order unexpectedly empty');
211 const firstModalControl=topControls[0],lastModalControl=topControls[topControls.length-1];
212 lastModalControl.focus();
213 const tabForward=new KeyboardEvent('keydown',{key:'Tab',bubbles:true,cancelable:true});
214 lastModalControl.dispatchEvent(tabForward);
215 if(!tabForward.defaultPrevented || document.activeElement!==firstModalControl){
216 throw Error('Tab escaped the top modal instead of wrapping to its first control');
217 }
218 firstModalControl.focus();
219 const tabBackward=new KeyboardEvent('keydown',
220 {key:'Tab',shiftKey:true,bubbles:true,cancelable:true});
221 firstModalControl.dispatchEvent(tabBackward);
222 if(!tabBackward.defaultPrevented || document.activeElement!==lastModalControl){
223 throw Error('Shift+Tab escaped the top modal instead of wrapping to its last control');
224 }
225 // Simulate pressing Enter on a focused CANCEL button in an actual installed
226 // WebView2 dialog. The global shortcut MUST NOT hijack it as "confirm".
227 const nestedCancel=stack[1].querySelector('[data-action="cancel"]');
228 if(!nestedCancel)throw Error('synthetic nested dialog cancel button missing');
229 nestedCancel.focus();
230 const enterOnCancel=new KeyboardEvent('keydown',
231 {key:'Enter',code:'Enter',bubbles:true,cancelable:true});
232 nestedCancel.dispatchEvent(enterOnCancel);
233 await wait(20);
234 if(enterOnCancel.defaultPrevented || unexpectedConfirm ||
235 document.querySelectorAll('.modal-card').length!==2){
236 throw Error('Enter on focused Cancel was hijacked as financial confirmation');
237 }
238 document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true}));
239 await wait(15);
240 if(document.querySelectorAll('.modal-card').length!==1 ||
241 !outer.contains(document.activeElement) || unexpectedConfirm) throw Error('Escape did not dismiss nested confirm safely');
242 const focusedField=document.getElementById('q01ModalField');
243 if(!focusedField)throw Error('synthetic outer input missing');
244 focusedField.focus();
245 const enterInField=new KeyboardEvent('keydown',
246 {key:'Enter',code:'Enter',bubbles:true,cancelable:true});
247 focusedField.dispatchEvent(enterInField);
248 await wait(20);
249 if(enterInField.defaultPrevented || !outer.isConnected){
250 throw Error('Enter inside form input unexpectedly submitted/dismissed dialog');
251 }
252 document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true}));
253 await wait(15);
254 if(document.querySelector('.modal-backdrop') || document.activeElement!==modalTrigger ||
255 unexpectedConfirm) {
256 const focused=document.activeElement;
257 throw Error('Escape did not restore focus to original control: ' + JSON.stringify({
258 remainingDialogs:document.querySelectorAll('.modal-backdrop').length,
259 focusedTag:focused?.tagName,focusedId:focused?.id,
260 expectedId:modalTrigger.id,unexpectedConfirm
261 }));
262 }
263 // Open a fresh synthetic confirmation: a user clicking Cancel must NOT
264 // execute the callback. Deliberate Confirm should execute exactly once.
265 let syntheticConfirmed=0;
266 FINORA.Modal.confirm({title:'Q01 Cancel-button regression',
267 message:'No real account or customer data',
268 onConfirm:()=>{syntheticConfirmed++;}});
269 await wait(25);
270 const cancelDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
271 const cancelClick=cancelDialog?.querySelector('[data-action="cancel"]');
272 if(!cancelClick)throw Error('synthetic Cancel action missing');
273 cancelClick.focus();
274 cancelClick.click();await wait(25);
275 if(syntheticConfirmed!==0 || FINORA.Modal.stack.length ||
276 document.activeElement!==modalTrigger){
277 throw Error('Cancel click triggered financial confirm or failed to restore focus');
278 }
279 FINORA.Modal.confirm({title:'Q01 Confirm-button regression',
280 message:'Only increment a synthetic counter',
281 onConfirm:()=>{syntheticConfirmed++;}});
282 await wait(25);
283 const confirmDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
284 const confirmClick=confirmDialog?.querySelector('[data-action="confirm"]');
285 if(!confirmClick)throw Error('synthetic Confirm action missing');
286 confirmClick.click();await wait(25);
287 if(syntheticConfirmed!==1 || FINORA.Modal.stack.length){
288 throw Error('synthetic Confirm callback not exactly once or dialog not dismissed');
289 }
290 // A confirmation message can contain user-provided contact names. It must
291 // never be interpreted as HTML or create a DOM node with event handlers.
292 const hostileMessage='<img src=x onerror="window.Q01_INJECTED=true">';
293 FINORA.Modal.confirm({title:'Q01 text-only confirmation',
294 message:hostileMessage,confirmText:hostileMessage,cancelText:hostileMessage,
295 onConfirm:()=>{syntheticConfirmed++;}});
296 await wait(25);
297 const safeConfirm=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
298 if (!safeConfirm || safeConfirm.querySelector('[data-confirm-message]')?.textContent!==hostileMessage ||
299 safeConfirm.querySelector('[data-action="confirm"]')?.textContent!==hostileMessage ||
300 safeConfirm.querySelector('[data-action="cancel"]')?.textContent!==hostileMessage ||
301 safeConfirm.querySelector('img') || window.Q01_INJECTED) {
302 throw Error('Confirmation message was interpreted as executable HTML');
303 }
304 safeConfirm.querySelector('[data-action="cancel"]').click();
305 if (syntheticConfirmed!==1 || FINORA.Modal.stack.length) {
306 throw Error('Text-only confirmation Cancel executed a callback or leaked a dialog');
307 }
308 // A financial editor can start with an invisible radio or hidden ID field.
309 // Initial focus must land on the first VISIBLE input, not a hidden element.
310 FINORA.Modal.open({title:'Q01 visible-input focus regression',
311 body:'<input id="q01HiddenInput" style="display:none"><input id="q01VisibleInput">'});
312 await wait(25);
313 if (document.activeElement?.id !== 'q01VisibleInput') {
314 throw Error('Dialog initial focus landed outside first visible financial input');
315 }
316 FINORA.Modal.close();
317 if (document.activeElement!==modalTrigger) {
318 throw Error('Closing visible-input dialog did not restore keyboard focus');
319 }
320 // Real DOM probe: preserve ambiguous groups and explicit accessible names.
321 const labelsProbe=FINORA.Modal.open({title:'Q01 Synthetic form labels',body:
322 '<div class="form-group"><label class="form-label">نام آزمایشی</label><input id="q01SingleField"></div>' +
323 '<div class="form-group"><label class="form-label">گروه چندفیلدی</label><input id="q01MultiOne"><input id="q01MultiTwo"></div>' +
324 '<div class="form-group"><label class="form-label" for="q01ExistingField">برچسب صریح</label><input id="q01ExistingField"></div>',
325 footer:'<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',size:'sm'});
326 await wait(25);
327 const namedField=labelsProbe.card.querySelector('#q01SingleField');
328 const multiOne=labelsProbe.card.querySelector('#q01MultiOne');
329 const existingField=labelsProbe.card.querySelector('#q01ExistingField');
330 if (namedField.labels?.length!==1 ||
331 namedField.labels[0].textContent.trim()!=='نام آزمایشی' ||
332 multiOne.labels?.length || existingField.labels?.length!==1 ||
333 existingField.labels[0].getAttribute('for')!=='q01ExistingField') {
334 throw Error('Modal form labels were missing, ambiguous, or overwrote explicit names');
335 }
336 namedField.labels[0].click(); await wait(15);
337 if (document.activeElement!==namedField) throw Error('Linked modal field label did not focus its field');
338 FINORA.Modal.close();
339 // Read-only synthetic XSS exercise: no customer records are persisted.
340 const expenseController=window.ExpenseController;
341 const expenseView=window.ExpensesView;
342 const origGetAll=expenseController.getAll;
343 const origGetCategories=expenseController.getCategories;
344 const origGetStats=expenseController.getStats;
345 const origEditExpense=expenseView.editExpense;
346 const hostileCategory='"><\/option><\/select><img src=x onerror="window.Q01_EXPENSE_HTML_ATTACK=true">';
347 const hostileId="exp-test');window.Q01_EXPENSE_ID_ATTACK=true;//";
348 const hostileCell='<img src=x onerror="window.Q01_EXPENSE_HTML_ATTACK=true">';
349 let clickedExpenseId=null;
350 try {
351 expenseController.getAll=async()=>[{id:hostileId,kind:'expense',
352 category:hostileCategory,description:hostileCell,
353 date:hostileCell,refNumber:hostileCell,method:hostileCell,amount:100}];
354 expenseController.getCategories=async()=>[hostileCategory];
355 expenseController.getStats=async()=>({totalIncome:0,totalExpense:100,balance:-100,count:1});
356 await expenseView.reload();
357 const scratch=document.createElement('div');
358 scratch.innerHTML=expenseView.renderContent();
359 if(scratch.querySelector('img') || scratch.querySelector('script') ||
360 scratch.querySelector('select[aria-label="سرفصل سند"] option')?.value!==hostileCategory ||
361 !scratch.textContent.includes(hostileCell)) {
362 throw Error('Untrusted expense list fields created executable markup or corrupted category value');
363 }
364 expenseView.editExpense=(id)=>{clickedExpenseId=id;};
365 const edit=scratch.querySelector('button[title="ویرایش"]');
366 if(!edit) throw Error('Synthetic expense action missing');
367 edit.click();
368 if(clickedExpenseId!==hostileId || window.Q01_EXPENSE_ID_ATTACK ||
369 window.Q01_EXPENSE_HTML_ATTACK) {
370 throw Error('Expense row identifier escaped the safe JS argument or executed markup');
371 }
372 } finally {
373 expenseController.getAll=origGetAll;
374 expenseController.getCategories=origGetCategories;
375 expenseController.getStats=origGetStats;
376 expenseView.editExpense=origEditExpense;
377 await expenseView.reload();
378 delete window.Q01_EXPENSE_ID_ATTACK;
379 delete window.Q01_EXPENSE_HTML_ATTACK;
380 }
381 // Read-only adversarial invoice render: unknown imported kinds, invoice IDs,
382 // number and date must never create active markup or execute row handlers.
383 const invoiceView=window.InvoicesView;
384 const originalEditInvoice=invoiceView.editInvoice;
385 const hostileInvoiceId="inv-test');window.Q01_INVOICE_ID_ATTACK=true;//";
386 const injectedKind='<img src=x onerror="window.Q01_INVOICE_HTML_ATTACK=true">';
387 let editedInvoiceId=null;
388 try {
389 const syntheticInvoices=[{id:hostileInvoiceId,number:injectedKind,
390 kind:injectedKind,contactName:injectedKind,date:injectedKind,
391 grandTotal:100,paidAmount:0,remaining:100,status:'unpaid',isPreInvoice:false}];
392 const frag=document.createElement('div');
393 frag.innerHTML=invoiceView.renderTable(syntheticInvoices);
394 if(frag.querySelector('img') || frag.querySelector('script') ||
395 !frag.textContent.includes(injectedKind)) {
396 throw Error('Imported invoice kind or date escaped the safe HTML rendering boundary');
397 }
398 invoiceView.editInvoice=(id)=>{editedInvoiceId=id;};
399 const edit=frag.querySelector('button[title="ویرایش"]');
400 if(!edit) throw Error('Synthetic invoice edit handler missing');
401 edit.click();
402 if(editedInvoiceId!==hostileInvoiceId || window.Q01_INVOICE_ID_ATTACK ||
403 window.Q01_INVOICE_HTML_ATTACK) {
404 throw Error('Imported invoice identifier executed unsafe inline action code');
405 }
406 } finally {
407 invoiceView.editInvoice=originalEditInvoice;
408 delete window.Q01_INVOICE_ID_ATTACK;
409 delete window.Q01_INVOICE_HTML_ATTACK;
410 }
411 // Fail-closed Excel replacement attempts must not delete financial master
412 // records even when callers bypass the UI. Synthetic workbook only.
413 const beforeProducts=JSON.stringify(await FINORA.Storage.getAll('products'));
414 const beforeContacts=JSON.stringify(await FINORA.Storage.getAll('contacts'));
415 for (const mode of ['replace','wipe','unknown']) {
416 for (const [method, sheet, row] of [
417 ['importProducts','کالاها',{'نام':'Q01 non-destructive product'}],
418 ['importContacts','اشخاص',{'نام':'Q01 non-destructive contact'}]
419 ]) {
420 let rejected=false;
421 try { await window.ExcelController[method]({[sheet]:[row]},{mode}); }
422 catch(error) { rejected=String(error?.message||'').includes('جایگزینی گروهی'); }
423 if (!rejected) throw Error('Excel '+method+' accepted unsafe mode: '+mode);
424 }
425 }
426 if (JSON.stringify(await FINORA.Storage.getAll('products'))!==beforeProducts ||
427 JSON.stringify(await FINORA.Storage.getAll('contacts'))!==beforeContacts) {
428 throw Error('An unsupported Excel mode mutated existing customer or product data');
429 }
430 const modalKeyboard={roleAndLabel:true,nestedDialogIsolation:true,
431 excelReplacementRejectedWithoutWrites:true,
432 importedInvoiceHtmlEscaped:true,
433 expenseUnsafeHtmlEscaped:true,
434 modalFormLabelsLinked:true,
435 confirmationTextEscaped:true,visibleInputAutoFocused:true,
436 escapeClosesWithoutConfirm:true,focusReturnsToTrigger:true,
437 enterOnFocusedCancelDoesNotSave:true,enterOnInputDoesNotSubmit:true,
438 tabAndShiftTabStayInsideTopDialog:true,
439 cancelDoesNotConfirmAndRestoresFocus:true,syntheticConfirmRunsExactlyOnce:true};
440 // Notification flood: transient success/info messages should never
441 // cover the dashboard. Important errors remain until explicitly dismissed.
442 for(let n=0;n<9;n++) FINORA.Toast.info('Q01 synthetic notice '+n);
443 const transient=document.querySelectorAll('.toast-success, .toast-info');
444 if(transient.length>3)throw Error('transient notifications cover too much of the UI');
445 const beforeErrors=document.querySelectorAll('.toast-error').length;
446 FINORA.Toast.error('Q01 synthetic persistent error');
447 if(document.querySelectorAll('.toast-error').length!==beforeErrors+1){
448 throw Error('important financial error notification disappeared');
449 }
450 document.querySelectorAll('.toast .toast-close').forEach(button=>button.click());
451 const toastResults={transientLimit:3,importantErrorsRemain:true,
452 dismissButtonsWork:document.querySelectorAll('.toast').length===0};
453 await FINORA.Router.go('settings');
454 await wait(100);
455 for(const fieldId of ['invoiceNumberingMode','invoiceNextNumber']){
456 const label=document.querySelector('label[for="'+fieldId+'"]');
457 const field=document.getElementById(fieldId);
458 if(!label || !field) throw Error('invoice settings field label missing: '+fieldId);
459 label.click();await wait(20);
460 if(document.activeElement!==field) throw Error('clicking settings label did not focus: '+fieldId);
461 }
462 await FINORA.Router.go('dashboard');
463 const shellResults={keyboardReachableSidebarLinks:navLinks.length,
464 sidebarCollapseClickAndPersistence:true,themeToggleClickAndPersistence:true,
465 activeRouteAriaCurrent:true,modalKeyboard,toastResults,settingsLabelFocus:true};
466 for (const route of routes) {
467 await go(route);
468 const active=[...document.querySelectorAll('#sidebarMenu [aria-current="page"]')];
469 if(active.length!==1 || active[0].dataset.page!==route){
470 throw Error('active route is not announced to screen readers: '+route);
471 }
472 const tabs = inventory(route,'root').filter(el => !el.disabled && safeTab.test(handler(el)));
473 // Evaluate each known safe top-level tab. The router is reset between
474 // clicks to avoid mutating references after HTML rerendering.
475 const tabActions=[...new Set(tabs.map(el=>handler(el)))];
476 const contexts=[{section:'root',tabAction:null}];
477 for (const action of tabActions) contexts.push({section:'tab-'+contexts.length,tabAction:action});
478 for (const ctx of contexts) {
479 await go(route);
480 if (ctx.tabAction) {
481 const tab=clickables(target()).find(el=>handler(el)===ctx.tabAction);
482 if (tab) {
483 inventory(route,'root');
484 await press(tab,route,'root','tab');
485 } else {
486 failures.push({route,section:ctx.section,kind:'tab-missing',handler:ctx.tabAction});
487 continue;
488 }
489 }
490 const controls=inventory(route,ctx.section);
491 // For every visible clickable control, check function resolution. This
492 // inventory includes buttons we must not click indiscriminately.
493 for (const el of controls) {
494 const k=sig(el,route,ctx.section),row=all.get(k);
495 if (!row) continue;
496 const code=handler(el);
497 const parsed=resolveHandler(code);
498 if (parsed.detected && !parsed.valid) {
499 row.status='broken-handler';row.reason='target function missing';
500 failures.push({route,section:ctx.section,kind:'missing-function',callee:parsed.callee});
501 } else if (el.disabled) {row.status='disabled';row.reason='disabled state';}
502 else if (dangerous.test(code)) {
503 row.status='not-clicked';row.reason='financial or destructive action needs explicit fixture-backed test';
504 } else if (!code) {
505 row.status='not-clicked';row.reason='dynamic event listener or no inline action; requires focused audit';
506 } else if (!safeTab.test(code) && !safeOpen.test(code)) {
507 row.status='not-clicked';row.reason='not on audited safe-action allowlist';
508 }
509 }
510 // Open every safe modal/editor visible in this context without saving.
511 const openActions=[...new Set(controls
512 .filter(el=>!el.disabled && safeOpen.test(handler(el)))
513 .map(el=>handler(el)))].slice(0,30);
514 for (const action of openActions) {
515 await go(route);
516 if (ctx.tabAction) {
517 const tab=clickables(target()).find(el=>handler(el)===ctx.tabAction);
518 if(tab){tab.click();await wait(160);}
519 }
520 const el=clickables(target()).find(x=>handler(x)===action);
521 if (!el) {failures.push({route,section:ctx.section,kind:'open-action-vanished',handler:action});continue;}
522 inventory(route,ctx.section);
523 await press(el,route,ctx.section,'open');
524 const overlay=document.querySelector('.modal-backdrop');
525 if(overlay) {
526 const dialog=overlay.querySelector('.modal-card[role="dialog"][aria-modal="true"]');
527 if(!dialog || !dialog.getAttribute('aria-labelledby') ||
528 !document.getElementById(dialog.getAttribute('aria-labelledby')) ||
529 !dialog.contains(document.activeElement)){
530 failures.push({route,section:ctx.section,kind:'modal-a11y-missing',
531 handler:action.slice(0,170)});
532 }
533 if (route==='expenses' && action.includes('openExpenseModal()')) {
534 const real=dialog?.querySelector('#expCategory');
535 if (!real || real.labels?.length!==1 ||
536 !real.labels[0].textContent.includes('سرفصل')) {
537 failures.push({route,section:ctx.section,kind:'expense-category-label-missing'});
538 }
539 }
540 auditFields(overlay,route,ctx.section+'/modal');
541 const nested=clickables(overlay);
542 const modalControls=nested.map(x=>({
543 route,section:ctx.section+'/modal',tag:x.tagName.toLowerCase(),
544 label:name(x),handler:handler(x).slice(0,180),
545 disabled:!!x.disabled,hasAccessibleName:!!name(x),
546 status:'not-clicked',reason:'modal action; untested or requires fixture-backed input'
547 }));
548 modalControls.forEach(x=>{
549 const key=[x.route,x.section,x.tag,x.label,x.handler].join('|');
550 if(!all.has(key))all.set(key,x);
551 });
552 // Exercise a real cancel/close button when present.
553 const cancel=nested.find(x=>/FINORA\.Modal\.close|Modal\.closeAll/.test(handler(x)) ||
554 /^(انصراف|بستن|بازگشت|✕|×)$/.test(name(x)));
555 if(cancel){
556 cancel.click();await wait(70);
557 clicks.push({route,section:ctx.section+'/modal',category:'cancel',
558 label:name(cancel),handler:handler(cancel).slice(0,170),
559 changed:!document.querySelector('.modal-backdrop')});
560 const key=[route,ctx.section+'/modal',cancel.tagName.toLowerCase(),
561 name(cancel),handler(cancel).slice(0,180)].join('|');
562 const row=all.get(key);if(row)row.status='clicked';
563 } else {
564 // A modal without a cancel button must still be Esc-dismissable.
565 document.dispatchEvent(new KeyboardEvent('keydown',
566 {key:'Escape',bubbles:true,cancelable:true}));
567 await wait(30);
568 }
569 if(document.querySelector('.modal-backdrop')){
570 failures.push({route,section:ctx.section,kind:'modal-cannot-close',
571 handler:action.slice(0,170)});
572 }
573 }
574 dismiss();
575 }
576 }
577 }
578 await FINORA.Router.go('dashboard');
579 const rows=[...all.values()];
580 // A route/tab may render the SAME action in multiple UI states. Counting
581 // each instance as a different button exaggerated the initial denominator.
582 // Unique action signatures omit the tab-context but retain route, visible
583 // name, inline handler and element type (including synthetic row IDs).
584 const uniqueGroups=new Map();
585 const actionKey=row=>JSON.stringify([row.route,row.tag,row.label,row.handler]);
586 for(const row of rows){
587 const key=actionKey(row);
588 if(!uniqueGroups.has(key))uniqueGroups.set(key,[]);
589 uniqueGroups.get(key).push(row);
590 }
591 // A failure on ANY context must never be hidden by a passing click on
592 // another tab. Fail > broken handler > clicked > disabled > untested.
593 const statusRank={failed:5,'broken-handler':4,clicked:3,disabled:1,'not-clicked':0};
594 const uniqueActions=[...uniqueGroups.values()].map(group=>{
595 const representative=group[0];
596 const dominant=[...group].sort((a,b)=>
597 (statusRank[b.status]??0)-(statusRank[a.status]??0))[0];
598 for(const occurrence of group){
599 if(occurrence.status==='not-clicked' && !occurrence.reason){
600 occurrence.reason=group.some(x=>x.status==='clicked')
601 ?'same-control-clicked-in-another-tab-context'
602 :'not-reached-or-not-classified-needs-manual-test';
603 }
604 }
605 return {
606 route:representative.route,tag:representative.tag,
607 label:representative.label,handler:representative.handler,
608 status:dominant.status,contexts:[...new Set(group.map(x=>x.section))],
609 instances:group.length,
610 testedInstances:group.filter(x=>x.status==='clicked').length,
611 failedInstances:group.filter(x=>x.status==='failed' || x.status==='broken-handler').length,
612 whyNotVerified:dominant.status==='not-clicked'
613 ?[...new Set(group.map(x=>x.reason))].join('; ').slice(0,300)
614 :''
615 };
616 });
617 const unclassifiedInstances=rows.filter(r=>r.status==='not-clicked' &&
618 r.reason==='not-reached-or-not-classified-needs-manual-test').length;
619 const byRoute={};
620 for(const route of routes) {
621 const slice=rows.filter(x=>x.route===route);
622 byRoute[route]={
623 discovered:slice.length,
624 uniqueActionSignatures:uniqueActions.filter(x=>x.route===route).length,
625 uniqueClicked:uniqueActions.filter(x=>x.route===route && x.status==='clicked').length,
626 uniqueNotVerified:uniqueActions.filter(x=>x.route===route && x.status==='not-clicked').length,
627 clicked:slice.filter(x=>x.status==='clicked').length,
628 notClicked:slice.filter(x=>x.status==='not-clicked').length,
629 brokenHandlers:slice.filter(x=>x.status==='broken-handler').length,
630 missingAccessibleName:slice.filter(x=>!x.hasAccessibleName).length
631 };
632 }
633 return {
634 environment:'installed-Windows-Tauri-WebView2-synthetic-VM',
635 shellResults,
636 routesVisited:routes.length,routeNames:routes,
637 inventoryCount:rows.length,
638 uniqueActionCount:uniqueActions.length,
639 uniqueActionClicked:uniqueActions.filter(x=>x.status==='clicked').length,
640 uniqueActionUnverified:uniqueActions.filter(x=>x.status==='not-clicked').length,
641 uniqueActionDisabled:uniqueActions.filter(x=>x.status==='disabled').length,
642 uniqueActionFailed:uniqueActions.filter(x=>x.status==='failed').length,
643 unclassifiedInstances,
644 duplicateInstanceCount:rows.length-uniqueActions.length,
645 safeClickCount:clicks.length,
646 skippedCount:rows.filter(x=>x.status==='not-clicked').length,
647 brokenHandlerCount:rows.filter(x=>x.status==='broken-handler').length,
648 accessibilityNameGaps:rows.filter(x=>!x.hasAccessibleName).length,
649 fieldsInspected:fields.size,
650 fieldsMissingProgrammaticLabel:[...fields.values()].filter(x=>!x.programmaticLabel).length,
651 fieldsWithoutLabels:[...fields.values()].filter(x=>!x.programmaticLabel).slice(0,100),
652 fieldCoverageByRoute:Object.fromEntries(routes.map(r=>[r,{
653 inspected:[...fields.values()].filter(x=>x.route===r).length,
654 missingProgrammaticLabel:[...fields.values()].filter(x=>x.route===r && !x.programmaticLabel).length
655 }])),
656 problems:failures,
657 byRoute,
658 controls:rows,
659 uniqueActions,
660 clickEvidence:clicks,
661 fieldEvidence:[...fields.values()],
662 financialActionsNotBulkClicked:true,
663 customerDataUsed:false,
664 everyActionVerified:false
665 };
666 })()