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

fix/q01-safe-ui-action-audit-coverage-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 875 lines 47.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)\s*\(/;
35 const safeNavigate = /FINORA\.Router\.go\s*\(/;
36 const safeFilter = /\.(?:_togglePreInvoice|_setStockFilter|_clearFilters|_applyCustom|_switchPeriod|_setPreset|refresh|setTheme)\s*\(/;
37 // These handlers only open an editor/preview/diagnostic dialog. The audit
38 // closes it without saving; a separate fixture-backed test owns commits.
39 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|editInvoice|editProduct|editContact|editCheque|editAccount|openAdjustModal|printInvoice|checkHolooMigrationReadiness|runFinancialDiagnostics)\s*\(/;
40 // A delete/close-period/seed action is safe to probe only up to its
41 // confirmation prompt. The audit must cancel and prove zero database writes.
42 const safeConfirmAction = /\.(?:deleteInvoice|deleteProduct|deleteContact|deleteCheque|deleteTransaction|deleteExpense|deleteAccount|closePeriod|seedChart)\s*\(/;
43 const clickables = (root) => [...root.querySelectorAll(
44 'button, a, [role="button"], input[type="button"], input[type="submit"], [onclick]'
45 )].filter(isVisible);
46 function auditFields(root, route, section) {
47 if (!root) return;
48 let fieldIndex = 0;
49 for (const field of root.querySelectorAll(
50 'input:not([type="hidden"]), select, textarea'
51 )) {
52 const ordinal = fieldIndex++;
53 if (!isVisible(field)) continue;
54 const labels=field.labels ? [...field.labels] : [];
55 const explicit=!!field.getAttribute('aria-label') ||
56 !!field.getAttribute('aria-labelledby') ||
57 !!field.closest('label') || labels.length > 0;
58 const id=field.id||'';
59 const key=[route,section,ordinal,field.tagName.toLowerCase(),id,
60 field.getAttribute('name')||'',field.getAttribute('type')||''].join('|');
61 if (fields.has(key)) continue;
62 fields.set(key,{
63 route,section,ordinal,id,tag:field.tagName.toLowerCase(),
64 type:field.getAttribute('type')||'',
65 label:labels.map(x=>x.textContent.trim().slice(0,75)).join(' / ') ||
66 field.getAttribute('aria-label') || '',
67 programmaticLabel:explicit,
68 placeholderOnly:!explicit && !!field.getAttribute('placeholder'),
69 status:explicit?'programmatic-label-found':'needs-accessibility-review'
70 });
71 }
72 }
73 function inventory(route, section) {
74 const controls = clickables(target());
75 auditFields(target(),route,section);
76 const records = [];
77 for (const el of controls) {
78 const k=sig(el,route,section);
79 if (all.has(k)) continue;
80 const code=handler(el);
81 const accessible=!!name(el);
82 const row={
83 route,section,tag:el.tagName.toLowerCase(),
84 label:name(el),handler:code.slice(0,220),
85 disabled:!!el.disabled || el.getAttribute('aria-disabled')==='true',
86 hasAccessibleName:accessible,
87 className:String(el.className||'').slice(0,120),
88 type:el.getAttribute('type')||'',
89 status:'not-clicked',reason:''
90 };
91 all.set(k,row); records.push(row);
92 }
93 inventories.push({route,section,newControls:records.length,totalVisible:controls.length});
94 return controls;
95 }
96 async function go(route) {
97 const link=document.querySelector('#sidebarMenu [data-page="'+route+'"]');
98 if (!link) throw Error('main sidebar menu item missing: '+route);
99 link.click(); await wait(160);
100 if (FINORA.Router.current()!==route) throw Error('sidebar click did not navigate: '+route);
101 if (!target() || target().textContent.trim().length < 10 ||
102 target().textContent.includes('خطا در بارگذاری صفحه')) {
103 throw Error('screen blank/failed after clicking: '+route);
104 }
105 if (document.getElementById('finoraAuthOverlay')) throw Error('auth returned during navigation');
106 }
107 const noError = () => !document.querySelector('.toast-error') &&
108 !target()?.textContent.includes('خطا در بارگذاری صفحه');
109 function dismiss() {
110 FINORA.Modal.closeAll();
111 document.querySelectorAll('.toast-close').forEach(x=>x.click());
112 }
113 function resolveHandler(code) {
114 const m=code.match(/(?:window\.)?([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+)\s*\(/);
115 if (!m) return {detected:false,valid:null,callee:''};
116 const parts=m[1].split('.');
117 let obj=window;
118 for (const part of parts) {
119 if (obj == null) return {detected:true,valid:false,callee:m[1]};
120 obj=obj[part];
121 }
122 return {detected:true,valid:typeof obj==='function',callee:m[1]};
123 }
124 const seenClick = new Set();
125 async function press(el, route, section, category) {
126 const k=sig(el,route,section);
127 if (seenClick.has(k)) return;
128 seenClick.add(k);
129 const row=all.get(k);
130 const before=target().innerHTML;
131 const beforeModal=!!document.querySelector('.modal-backdrop');
132 const beforeRoute=FINORA.Router.current();
133 const beforeTheme=document.documentElement.getAttribute('data-theme');
134 const beforeToasts=[...document.querySelectorAll('.toast')].map(x=>x.textContent.trim()).join('|');
135 try {
136 el.click(); await wait(180);
137 if (!noError()) throw Error('error toast or page render error');
138 const after=target()?.innerHTML||'';
139 const afterModal=!!document.querySelector('.modal-backdrop');
140 const afterRoute=FINORA.Router.current();
141 const afterTheme=document.documentElement.getAttribute('data-theme');
142 const afterToasts=[...document.querySelectorAll('.toast')].map(x=>x.textContent.trim()).join('|');
143 const changed = before !== after || beforeModal !== afterModal ||
144 beforeRoute !== afterRoute || beforeTheme !== afterTheme || beforeToasts !== afterToasts;
145 clicks.push({route,section,category,label:name(el),
146 handler:handler(el).slice(0,170),changed,afterModal});
147 if (row) {row.status='clicked';row.reason=changed?'visible-state-changed':'no-observable-DOM-change';}
148 if (!changed) {
149 const expectedNoop = /\._clearFilters\(\)|\._applyCustom\(\)|\.refresh\(\)|\.switchTab\('journals'\)/.test(handler(el));
150 if (expectedNoop) {
151 if (row) row.reason='idempotent-click-on-already-selected-or-clear-filter-state';
152 } else {
153 failures.push({route,section,kind:'no-visible-change',
154 label:name(el),handler:handler(el).slice(0,170)});
155 }
156 }
157 } catch(error) {
158 failures.push({route,section,kind:'click-error',label:name(el),error:String(error.message).slice(0,170)});
159 if (row) {row.status='failed';row.reason='UI click error';}
160 } finally { if (category !== 'open' && category !== 'confirm-request') dismiss(); }
161 }
162 // Explicit shell regression: semantic links, keyboard focus, active route,
163 // persistent sidebar collapse and reversible theme toggle.
164 const navLinks=[...document.querySelectorAll('#sidebarMenu a[data-page]')];
165 if (navLinks.length !== routes.length) throw Error('sidebar navigation count mismatch');
166 for(const link of navLinks) {
167 const route=link.dataset.page;
168 if(link.getAttribute('href')!=='#'+route || link.tabIndex<0 ||
169 !link.getAttribute('aria-label')) throw Error('sidebar link is not keyboard accessible: '+route);
170 }
171 const hamburger=document.getElementById('sidebarToggleBtn');
172 if(!hamburger || !hamburger.getAttribute('aria-label') ||
173 hamburger.getAttribute('aria-controls')!=='sidebarMenu') {
174 throw Error('sidebar accessible toggle missing');
175 }
176 const beforeCollapsed=document.getElementById('sidebar').classList.contains('collapsed');
177 hamburger.click();await wait(70);
178 const afterCollapsed=document.getElementById('sidebar').classList.contains('collapsed');
179 if (beforeCollapsed===afterCollapsed ||
180 localStorage.getItem('finora_pro_sidebar_collapsed')!==String(afterCollapsed) ||
181 hamburger.getAttribute('aria-expanded')!==String(!afterCollapsed)) {
182 throw Error('sidebar click did not persist synchronized collapsed and aria-expanded state');
183 }
184 hamburger.click();await wait(70);
185 if(document.getElementById('sidebar').classList.contains('collapsed')!==beforeCollapsed ||
186 localStorage.getItem('finora_pro_sidebar_collapsed')!==String(beforeCollapsed)) {
187 throw Error('sidebar click did not restore the prior saved state');
188 }
189 const themeButton=document.getElementById('themeToggleBtn');
190 const originalTheme=document.documentElement.getAttribute('data-theme');
191 if(!themeButton || !themeButton.getAttribute('title'))throw Error('theme button missing accessible name');
192 themeButton.click();await wait(50);
193 if(document.documentElement.getAttribute('data-theme')===originalTheme)throw Error('theme toggle was inert');
194 themeButton.click();await wait(50);
195 if(document.documentElement.getAttribute('data-theme')!==originalTheme ||
196 localStorage.getItem('finora_pro_theme')!==originalTheme)throw Error('theme setting not reversible/persisted');
197 // Cross-app dialog behavior: nested modal focus, Escape and focus return.
198 const modalTrigger=hamburger;
199 modalTrigger.focus();
200 if (getComputedStyle(modalTrigger).display === 'none' ||
201 document.activeElement !== modalTrigger) {
202 throw Error('Desktop sidebar toggle cannot receive keyboard focus before opening a dialog');
203 }
204 let unexpectedConfirm=false;
205 FINORA.Modal.open({title:'Q01 Synthetic outer dialog',
206 body:'<input id="q01ModalField" value="synthetic" />',
207 footer:'<button class="btn" onclick="FINORA.Modal.close()">بستن</button>'});
208 await wait(30);
209 const outer=document.querySelector('.modal-card[role="dialog"][aria-modal="true"]');
210 if(!outer || !outer.querySelector('[id^="finora-dialog-title-"]') ||
211 !outer.contains(document.activeElement)) throw Error('outer dialog ARIA or focus absent');
212 FINORA.Modal.confirm({title:'Q01 Synthetic nested confirmation',
213 message:'Synthetic data only; no operation permitted',
214 onConfirm:()=>{unexpectedConfirm=true;}});
215 await wait(30);
216 const stack=[...document.querySelectorAll('.modal-card[role="dialog"]')];
217 if(stack.length!==2 || stack[0].getAttribute('aria-hidden')!=='true' ||
218 !stack[1].contains(document.activeElement)) throw Error('nested dialog focus/isolation failed');
219 // Check a real Tab/Shift+Tab wrap, which an accessibility contract
220 // cannot prove from source alone. Neither key may escape the top dialog.
221 const topControls=[...stack[1].querySelectorAll(
222 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled])'
223 )].filter(el=>el.getClientRects().length>0 && getComputedStyle(el).visibility!=='hidden');
224 if(topControls.length<2)throw Error('nested modal focus order unexpectedly empty');
225 const firstModalControl=topControls[0],lastModalControl=topControls[topControls.length-1];
226 lastModalControl.focus();
227 const tabForward=new KeyboardEvent('keydown',{key:'Tab',bubbles:true,cancelable:true});
228 lastModalControl.dispatchEvent(tabForward);
229 if(!tabForward.defaultPrevented || document.activeElement!==firstModalControl){
230 throw Error('Tab escaped the top modal instead of wrapping to its first control');
231 }
232 firstModalControl.focus();
233 const tabBackward=new KeyboardEvent('keydown',
234 {key:'Tab',shiftKey:true,bubbles:true,cancelable:true});
235 firstModalControl.dispatchEvent(tabBackward);
236 if(!tabBackward.defaultPrevented || document.activeElement!==lastModalControl){
237 throw Error('Shift+Tab escaped the top modal instead of wrapping to its last control');
238 }
239 // Simulate pressing Enter on a focused CANCEL button in an actual installed
240 // WebView2 dialog. The global shortcut MUST NOT hijack it as "confirm".
241 const nestedCancel=stack[1].querySelector('[data-action="cancel"]');
242 if(!nestedCancel)throw Error('synthetic nested dialog cancel button missing');
243 nestedCancel.focus();
244 const enterOnCancel=new KeyboardEvent('keydown',
245 {key:'Enter',code:'Enter',bubbles:true,cancelable:true});
246 nestedCancel.dispatchEvent(enterOnCancel);
247 await wait(20);
248 if(enterOnCancel.defaultPrevented || unexpectedConfirm ||
249 document.querySelectorAll('.modal-card').length!==2){
250 throw Error('Enter on focused Cancel was hijacked as financial confirmation');
251 }
252 document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true}));
253 await wait(15);
254 if(document.querySelectorAll('.modal-card').length!==1 ||
255 !outer.contains(document.activeElement) || unexpectedConfirm) throw Error('Escape did not dismiss nested confirm safely');
256 const focusedField=document.getElementById('q01ModalField');
257 if(!focusedField)throw Error('synthetic outer input missing');
258 focusedField.focus();
259 const enterInField=new KeyboardEvent('keydown',
260 {key:'Enter',code:'Enter',bubbles:true,cancelable:true});
261 focusedField.dispatchEvent(enterInField);
262 await wait(20);
263 if(enterInField.defaultPrevented || !outer.isConnected){
264 throw Error('Enter inside form input unexpectedly submitted/dismissed dialog');
265 }
266 document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true,cancelable:true}));
267 await wait(15);
268 if(document.querySelector('.modal-backdrop') || document.activeElement!==modalTrigger ||
269 unexpectedConfirm) {
270 const focused=document.activeElement;
271 throw Error('Escape did not restore focus to original control: ' + JSON.stringify({
272 remainingDialogs:document.querySelectorAll('.modal-backdrop').length,
273 focusedTag:focused?.tagName,focusedId:focused?.id,
274 expectedId:modalTrigger.id,unexpectedConfirm
275 }));
276 }
277 // Open a fresh synthetic confirmation: a user clicking Cancel must NOT
278 // execute the callback. Deliberate Confirm should execute exactly once.
279 let syntheticConfirmed=0;
280 FINORA.Modal.confirm({title:'Q01 Cancel-button regression',
281 message:'No real account or customer data',
282 onConfirm:()=>{syntheticConfirmed++;}});
283 await wait(25);
284 const cancelDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
285 const cancelClick=cancelDialog?.querySelector('[data-action="cancel"]');
286 if(!cancelClick)throw Error('synthetic Cancel action missing');
287 cancelClick.focus();
288 cancelClick.click();await wait(25);
289 if(syntheticConfirmed!==0 || FINORA.Modal.stack.length ||
290 document.activeElement!==modalTrigger){
291 throw Error('Cancel click triggered financial confirm or failed to restore focus');
292 }
293 FINORA.Modal.confirm({title:'Q01 Confirm-button regression',
294 message:'Only increment a synthetic counter',
295 onConfirm:()=>{syntheticConfirmed++;}});
296 await wait(25);
297 const confirmDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
298 const confirmClick=confirmDialog?.querySelector('[data-action="confirm"]');
299 if(!confirmClick)throw Error('synthetic Confirm action missing');
300 confirmClick.click();
301 confirmClick.click(); // old DOM reference must not execute twice
302 await wait(25);
303 if(syntheticConfirmed!==1 || FINORA.Modal.stack.length){
304 throw Error('synthetic Confirm callback not exactly once or dialog not dismissed');
305 }
306 FINORA.Modal.confirm({title:'Q01 stale cancelled confirmation',
307 message:'Must never commit after cancellation',onConfirm:()=>{syntheticConfirmed++;}});
308 await wait(25);
309 const staleCancelDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
310 const staleConfirm=staleCancelDialog?.querySelector('[data-action="confirm"]');
311 staleCancelDialog?.querySelector('[data-action="cancel"]')?.click();
312 staleConfirm?.click();
313 if(syntheticConfirmed!==1 || FINORA.Modal.stack.length){
314 throw Error('A cancelled confirmation was executed by a stale button');
315 }
316 FINORA.Modal.confirm({title:'Q01 hidden parent confirmation',
317 message:'Must remain inert while nested',onConfirm:()=>{syntheticConfirmed++;}});
318 await wait(25);
319 const hiddenParent=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
320 FINORA.Modal.confirm({title:'Q01 active child confirmation',
321 message:'Cancel first',onConfirm:()=>{syntheticConfirmed++;}});
322 await wait(25);
323 hiddenParent?.querySelector('[data-action="confirm"]')?.click();
324 if(syntheticConfirmed!==1 || FINORA.Modal.stack.length!==2){
325 throw Error('Hidden parent confirmation changed ledger decision while child was active');
326 }
327 FINORA.Modal.stack[1].card.querySelector('[data-action="cancel"]').click();
328 hiddenParent.querySelector('[data-action="cancel"]').click();
329 if(FINORA.Modal.stack.length!==0 || syntheticConfirmed!==1){
330 throw Error('Nested financial confirmations were not safely cancelled');
331 }
332 // A confirmation message can contain user-provided contact names. It must
333 // never be interpreted as HTML or create a DOM node with event handlers.
334 const hostileMessage='<img src=x onerror="window.Q01_INJECTED=true">';
335 FINORA.Modal.confirm({title:'Q01 text-only confirmation',
336 message:hostileMessage,confirmText:hostileMessage,cancelText:hostileMessage,
337 onConfirm:()=>{syntheticConfirmed++;}});
338 await wait(25);
339 const safeConfirmDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
340 if (!safeConfirmDialog || safeConfirmDialog.querySelector('[data-confirm-message]')?.textContent!==hostileMessage ||
341 safeConfirmDialog.querySelector('[data-action="confirm"]')?.textContent!==hostileMessage ||
342 safeConfirmDialog.querySelector('[data-action="cancel"]')?.textContent!==hostileMessage ||
343 safeConfirmDialog.querySelector('img') || window.Q01_INJECTED) {
344 throw Error('Confirmation message was interpreted as executable HTML');
345 }
346 safeConfirmDialog.querySelector('[data-action="cancel"]').click();
347 if (syntheticConfirmed!==1 || FINORA.Modal.stack.length) {
348 throw Error('Text-only confirmation Cancel executed a callback or leaked a dialog');
349 }
350 // A financial editor can start with an invisible radio or hidden ID field.
351 // Initial focus must land on the first VISIBLE input, not a hidden element.
352 FINORA.Modal.open({title:'Q01 visible-input focus regression',
353 body:'<input id="q01HiddenInput" style="display:none"><input id="q01VisibleInput">'});
354 await wait(25);
355 if (document.activeElement?.id !== 'q01VisibleInput') {
356 throw Error('Dialog initial focus landed outside first visible financial input');
357 }
358 FINORA.Modal.close();
359 if (document.activeElement!==modalTrigger) {
360 throw Error('Closing visible-input dialog did not restore keyboard focus');
361 }
362 // Real DOM probe: preserve ambiguous groups and explicit accessible names.
363 const labelsProbe=FINORA.Modal.open({title:'Q01 Synthetic form labels',body:
364 '<div class="form-group"><label class="form-label">نام آزمایشی</label><input id="q01SingleField"></div>' +
365 '<div class="form-group"><label class="form-label">گروه چندفیلدی</label><input id="q01MultiOne"><input id="q01MultiTwo"></div>' +
366 '<div class="form-group"><label class="form-label" for="q01ExistingField">برچسب صریح</label><input id="q01ExistingField"></div>',
367 footer:'<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',size:'sm'});
368 await wait(25);
369 const namedField=labelsProbe.card.querySelector('#q01SingleField');
370 const multiOne=labelsProbe.card.querySelector('#q01MultiOne');
371 const existingField=labelsProbe.card.querySelector('#q01ExistingField');
372 if (namedField.labels?.length!==1 ||
373 namedField.labels[0].textContent.trim()!=='نام آزمایشی' ||
374 multiOne.labels?.length || existingField.labels?.length!==1 ||
375 existingField.labels[0].getAttribute('for')!=='q01ExistingField') {
376 throw Error('Modal form labels were missing, ambiguous, or overwrote explicit names');
377 }
378 namedField.labels[0].click(); await wait(15);
379 if (document.activeElement!==namedField) throw Error('Linked modal field label did not focus its field');
380 FINORA.Modal.close();
381 // Read-only synthetic XSS exercise: no customer records are persisted.
382 const expenseController=window.ExpenseController;
383 const expenseView=window.ExpensesView;
384 const origGetAll=expenseController.getAll;
385 const origGetCategories=expenseController.getCategories;
386 const origGetStats=expenseController.getStats;
387 const origEditExpense=expenseView.editExpense;
388 const hostileCategory='"><\/option><\/select><img src=x onerror="window.Q01_EXPENSE_HTML_ATTACK=true">';
389 const hostileId="exp-test');window.Q01_EXPENSE_ID_ATTACK=true;//";
390 const hostileCell='<img src=x onerror="window.Q01_EXPENSE_HTML_ATTACK=true">';
391 let clickedExpenseId=null;
392 try {
393 expenseController.getAll=async()=>[{id:hostileId,kind:'expense',
394 category:hostileCategory,description:hostileCell,
395 date:hostileCell,refNumber:hostileCell,method:hostileCell,amount:100}];
396 expenseController.getCategories=async()=>[hostileCategory];
397 expenseController.getStats=async()=>({totalIncome:0,totalExpense:100,balance:-100,count:1});
398 await expenseView.reload();
399 const scratch=document.createElement('div');
400 scratch.innerHTML=expenseView.renderContent();
401 const categoryFilter=scratch.querySelector('select[aria-label="سرفصل سند"]');
402 const matchingOptions=[...(categoryFilter?.options || [])]
403 .filter(option=>option.value===hostileCategory);
404 const actualLabels=matchingOptions.map(option=>option.textContent);
405 if(scratch.querySelector('img') || scratch.querySelector('script') ||
406 matchingOptions.length!==1 || actualLabels[0]!==hostileCategory ||
407 !scratch.textContent.includes(hostileCell)) {
408 throw Error('Untrusted expense list fields created executable markup or corrupted category value: ' +
409 JSON.stringify({filterFound:!!categoryFilter,
410 optionsCount:categoryFilter?.options?.length ?? -1,
411 maliciousCategoryPresent:matchingOptions.length===1,
412 labelMatches:actualLabels[0]===hostileCategory,
413 unexpectedImages:scratch.querySelectorAll('img').length,
414 unexpectedScripts:scratch.querySelectorAll('script').length}));
415 }
416 expenseView.editExpense=(id)=>{clickedExpenseId=id;};
417 const edit=scratch.querySelector('button[title="ویرایش"]');
418 if(!edit) throw Error('Synthetic expense action missing');
419 edit.click();
420 if(clickedExpenseId!==hostileId || window.Q01_EXPENSE_ID_ATTACK ||
421 window.Q01_EXPENSE_HTML_ATTACK) {
422 throw Error('Expense row identifier escaped the safe JS argument or executed markup');
423 }
424 } finally {
425 expenseController.getAll=origGetAll;
426 expenseController.getCategories=origGetCategories;
427 expenseController.getStats=origGetStats;
428 expenseView.editExpense=origEditExpense;
429 await expenseView.reload();
430 delete window.Q01_EXPENSE_ID_ATTACK;
431 delete window.Q01_EXPENSE_HTML_ATTACK;
432 }
433 // Read-only adversarial invoice render: unknown imported kinds, invoice IDs,
434 // number and date must never create active markup or execute row handlers.
435 const invoiceView=window.InvoicesView;
436 const originalEditInvoice=invoiceView.editInvoice;
437 const hostileInvoiceId="inv-test');window.Q01_INVOICE_ID_ATTACK=true;//";
438 const injectedKind='<img src=x onerror="window.Q01_INVOICE_HTML_ATTACK=true">';
439 let editedInvoiceId=null;
440 try {
441 const syntheticInvoices=[{id:hostileInvoiceId,number:injectedKind,
442 kind:injectedKind,contactName:injectedKind,date:injectedKind,
443 grandTotal:100,paidAmount:0,remaining:100,status:'unpaid',isPreInvoice:false}];
444 const frag=document.createElement('div');
445 frag.innerHTML=invoiceView.renderTable(syntheticInvoices);
446 if(frag.querySelector('img') || frag.querySelector('script') ||
447 !frag.textContent.includes(injectedKind)) {
448 throw Error('Imported invoice kind or date escaped the safe HTML rendering boundary');
449 }
450 invoiceView.editInvoice=(id)=>{editedInvoiceId=id;};
451 const edit=frag.querySelector('button[title="ویرایش"]');
452 if(!edit) throw Error('Synthetic invoice edit handler missing');
453 edit.click();
454 if(editedInvoiceId!==hostileInvoiceId || window.Q01_INVOICE_ID_ATTACK ||
455 window.Q01_INVOICE_HTML_ATTACK) {
456 throw Error('Imported invoice identifier executed unsafe inline action code');
457 }
458 } finally {
459 invoiceView.editInvoice=originalEditInvoice;
460 delete window.Q01_INVOICE_ID_ATTACK;
461 delete window.Q01_INVOICE_HTML_ATTACK;
462 }
463 // Fail-closed Excel replacement attempts must not delete financial master
464 // records even when callers bypass the UI. Synthetic workbook only.
465 const beforeProducts=JSON.stringify(await FINORA.Storage.getAll('products'));
466 const beforeContacts=JSON.stringify(await FINORA.Storage.getAll('contacts'));
467 for (const mode of ['replace','wipe','unknown']) {
468 for (const [method, sheet, row] of [
469 ['importProducts','کالاها',{'نام':'Q01 non-destructive product'}],
470 ['importContacts','اشخاص',{'نام':'Q01 non-destructive contact'}]
471 ]) {
472 let rejected=false;
473 try { await window.ExcelController[method]({[sheet]:[row]},{mode}); }
474 catch(error) { rejected=String(error?.message||'').includes('جایگزینی گروهی'); }
475 if (!rejected) throw Error('Excel '+method+' accepted unsafe mode: '+mode);
476 }
477 }
478 if (JSON.stringify(await FINORA.Storage.getAll('products'))!==beforeProducts ||
479 JSON.stringify(await FINORA.Storage.getAll('contacts'))!==beforeContacts) {
480 throw Error('An unsupported Excel mode mutated existing customer or product data');
481 }
482 // A read-only malicious ledger fixture must render all references as text.
483 const hostileLedgerText='<img src=x onerror="window.Q01_LEDGER_INJECTION=true">';
484 const syntheticLedger={finalBalance:0,totalDebit:0,totalCredit:0,
485 rows:[{date:hostileLedgerText,refNumber:hostileLedgerText,
486 type:'invoice_sale',typeLabel:hostileLedgerText,
487 isCheque:false,debit:0,credit:0,balance:0,note:hostileLedgerText}]};
488 const syntheticContact={name:hostileLedgerText,nationalId:hostileLedgerText,
489 entityType:'natural',role:'customer',tags:[]};
490 const ledgerScratch=document.createElement('div');
491 ledgerScratch.innerHTML=window.ContactLedgerModal._buildBody(syntheticContact,syntheticLedger);
492 if(ledgerScratch.querySelector('img') || window.Q01_LEDGER_INJECTION ||
493 !ledgerScratch.textContent.includes(hostileLedgerText)) {
494 throw Error('Financial contact ledger interpreted imported text as executable markup');
495 }
496 delete window.Q01_LEDGER_INJECTION;
497 // Simulate two rapid clicks on a private workbook preview. No real Excel
498 // rows are persisted; a canceled preview must never be importable later.
499 const excel = window.ExcelController;
500 const settingsView = window.SettingsView;
501 const originalExcelPreview = excel.previewFile;
502 const originalExcelImport = excel.importProducts;
503 let importCount = 0;
504 try {
505 excel.previewFile=async()=>({sheets:[{name:'کالاها',count:1}],
506 raw:{'کالاها':[{'نام':'Synthetic VM-only name'}]}});
507 excel.importProducts=async()=>{importCount++;await wait(85);return {added:1,skipped:0};};
508 await settingsView._handleImportFile({name:'synthetic-vm-preview.xlsx'},'products');
509 const importDialog=FINORA.Modal.stack[FINORA.Modal.stack.length-1]?.card;
510 const submit=importDialog?.querySelector('[data-excel-import-submit]');
511 if(!submit) throw Error('Synthetic Excel preview import button missing');
512 submit.click();submit.click();await wait(160);
513 if(importCount!==1 || submit.disabled!==true || FINORA.Modal.stack.length ||
514 Object.hasOwn(window,'__importRawData') || Object.hasOwn(window,'__importKind')) {
515 throw Error('Rapid Excel import clicks wrote twice or exposed a global workbook');
516 }
517 await settingsView._handleImportFile({name:'synthetic-vm-cancel.xlsx'},'products');
518 FINORA.Modal.close();
519 await settingsView._confirmImport('products');
520 document.querySelectorAll('.toast .toast-close').forEach(x=>x.click());
521 if(importCount!==1 || FINORA.Modal.stack.length) {
522 throw Error('Canceled private Excel preview remained importable');
523 }
524 } finally {
525 excel.previewFile=originalExcelPreview;
526 excel.importProducts=originalExcelImport;
527 FINORA.Modal.closeAll();
528 document.querySelectorAll('.toast .toast-close').forEach(x=>x.click());
529 }
530 const modalKeyboard={roleAndLabel:true,nestedDialogIsolation:true,
531 privateExcelPreviewAndSingleFlight:true,
532 financialLedgerContentEscaped:true,
533 excelReplacementRejectedWithoutWrites:true,
534 importedInvoiceHtmlEscaped:true,
535 expenseUnsafeHtmlEscaped:true,
536 modalFormLabelsLinked:true,
537 confirmationTextEscaped:true,visibleInputAutoFocused:true,
538 escapeClosesWithoutConfirm:true,focusReturnsToTrigger:true,
539 enterOnFocusedCancelDoesNotSave:true,enterOnInputDoesNotSubmit:true,
540 tabAndShiftTabStayInsideTopDialog:true,
541 cancelDoesNotConfirmAndRestoresFocus:true,syntheticConfirmRunsExactlyOnce:true,
542 staleFinancialConfirmIgnored:true};
543 // Notification flood: transient success/info messages should never
544 // cover the dashboard. Important errors remain until explicitly dismissed.
545 for(let n=0;n<9;n++) FINORA.Toast.info('Q01 synthetic notice '+n);
546 const transient=document.querySelectorAll('.toast-success, .toast-info');
547 if(transient.length>3)throw Error('transient notifications cover too much of the UI');
548 const beforeErrors=document.querySelectorAll('.toast-error').length;
549 FINORA.Toast.error('Q01 synthetic persistent error');
550 if(document.querySelectorAll('.toast-error').length!==beforeErrors+1){
551 throw Error('important financial error notification disappeared');
552 }
553 document.querySelectorAll('.toast .toast-close').forEach(button=>button.click());
554 const toastResults={transientLimit:3,importantErrorsRemain:true,
555 dismissButtonsWork:document.querySelectorAll('.toast').length===0};
556 await FINORA.Router.go('settings');
557 await wait(100);
558 for(const fieldId of ['invoiceNumberingMode','invoiceNextNumber']){
559 const label=document.querySelector('label[for="'+fieldId+'"]');
560 const field=document.getElementById(fieldId);
561 if(!label || !field) throw Error('invoice settings field label missing: '+fieldId);
562 label.click();await wait(20);
563 if(document.activeElement!==field) throw Error('clicking settings label did not focus: '+fieldId);
564 }
565 await FINORA.Router.go('dashboard');
566 const shellResults={keyboardReachableSidebarLinks:navLinks.length,
567 sidebarCollapseClickAndPersistence:true,themeToggleClickAndPersistence:true,
568 activeRouteAriaCurrent:true,modalKeyboard,toastResults,settingsLabelFocus:true};
569 for (const route of routes) {
570 await go(route);
571 const active=[...document.querySelectorAll('#sidebarMenu [aria-current="page"]')];
572 if(active.length!==1 || active[0].dataset.page!==route){
573 throw Error('active route is not announced to screen readers: '+route);
574 }
575 const tabs = inventory(route,'root').filter(el => !el.disabled && safeTab.test(handler(el)));
576 // Evaluate each known safe top-level tab. The router is reset between
577 // clicks to avoid mutating references after HTML rerendering.
578 const tabActions=[...new Set(tabs.map(el=>handler(el)))];
579 const contexts=[{section:'root',tabAction:tabActions[0]||null}];
580 for (const action of tabActions.slice(1)) contexts.push({section:'tab-'+contexts.length,tabAction:action});
581 // Delay filters until all row-scoped edit and confirmation actions have
582 // been inspected. A filter can hide the very rows needed by later probes.
583 const deferredSafeActions=[];
584 for (const ctx of contexts) {
585 await go(route);
586 if (ctx.tabAction) {
587 const tab=clickables(target()).find(el=>handler(el)===ctx.tabAction);
588 if (tab) {
589 inventory(route,'root');
590 await press(tab,route,'root','tab');
591 } else {
592 failures.push({route,section:ctx.section,kind:'tab-missing',handler:ctx.tabAction});
593 continue;
594 }
595 }
596 const controls=inventory(route,ctx.section);
597 // For every visible clickable control, check function resolution. This
598 // inventory includes buttons we must not click indiscriminately.
599 for (const el of controls) {
600 const k=sig(el,route,ctx.section),row=all.get(k);
601 if (!row) continue;
602 const code=handler(el);
603 const parsed=resolveHandler(code);
604 if (parsed.detected && !parsed.valid) {
605 row.status='broken-handler';row.reason='target function missing';
606 failures.push({route,section:ctx.section,kind:'missing-function',callee:parsed.callee});
607 } else if (el.disabled) {row.status='disabled';row.reason='disabled state';}
608 else if (!safeConfirmAction.test(code) && !safeNavigate.test(code) && !safeFilter.test(code) && !safeOpen.test(code) && dangerous.test(code)) {
609 row.status='not-clicked';row.reason='financial or destructive action needs explicit fixture-backed test';
610 } else if (!code) {
611 row.status='not-clicked';row.reason='dynamic event listener or no inline action; requires focused audit';
612 } else if (!safeTab.test(code) && !safeNavigate.test(code) && !safeFilter.test(code) && !safeOpen.test(code) && !safeConfirmAction.test(code)) {
613 row.status='not-clicked';row.reason='not on audited safe-action allowlist';
614 }
615 }
616 // Queue safe navigation and filter actions for after all contexts.
617 const safeActions=[...new Map(controls
618 .filter(el=>!el.disabled && (safeNavigate.test(handler(el)) || safeFilter.test(handler(el))))
619 .map(el=>[sig(el,route,ctx.section),{
620 handler:handler(el),label:name(el),tag:el.tagName.toLowerCase()
621 }])).values()];
622 if(safeActions.length) deferredSafeActions.push({
623 section:ctx.section,tabAction:ctx.tabAction,actions:safeActions
624 });
625 // Open destructive confirmation prompts, but NEVER approve them here.
626 // Compare every persistent store before/after Cancel to prove no write.
627 const confirmStores=['users','companies','contacts','products','units','categories',
628 'treasury','invoices','invoice_items','stock_movements','transactions','cheques',
629 'expenses','settings','logs','account_chart','fiscal_periods','journal_entries',
630 'journal_lines','warehouses','inventory_balances','stocktakes','stocktake_lines',
631 'settlements','account_mappings','audit_events','document_corrections'];
632 const confirmSnapshot=async()=>JSON.stringify(await Promise.all(confirmStores.map(async store=>
633 [store,await FINORA.Storage.getAll(store)])));
634 const confirmActions=[...new Set(controls
635 .filter(el=>!el.disabled && safeConfirmAction.test(handler(el)))
636 .map(el=>handler(el)))].slice(0,30);
637 for(const action of confirmActions){
638 await go(route);
639 if(ctx.tabAction){
640 const tab=clickables(target()).find(el=>handler(el)===ctx.tabAction);
641 if(tab){tab.click();await wait(160);}
642 }
643 const el=clickables(target()).find(x=>handler(x)===action);
644 if(!el){failures.push({route,section:ctx.section,kind:'confirm-action-vanished',handler:action});continue;}
645 const before=await confirmSnapshot();
646 inventory(route,ctx.section);
647 await press(el,route,ctx.section,'confirm-request');
648 const overlay=document.querySelector('.modal-backdrop');
649 if(!overlay){
650 failures.push({route,section:ctx.section,kind:'confirmation-prompt-missing',handler:action});
651 continue;
652 }
653 const cancel=clickables(overlay).find(x=>
654 /FINORA\.Modal\.close|Modal\.closeAll/.test(handler(x)) ||
655 /^(انصراف|بستن|بازگشت|✕|×)$/.test(name(x)));
656 if(!cancel){
657 failures.push({route,section:ctx.section,kind:'confirmation-cancel-missing',handler:action});
658 dismiss();continue;
659 }
660 cancel.click();await wait(80);
661 clicks.push({route,section:ctx.section+'/confirm',category:'confirm-cancel',
662 label:name(el),handler:action.slice(0,170),
663 changed:!document.querySelector('.modal-backdrop')});
664 if(document.querySelector('.modal-backdrop')){
665 failures.push({route,section:ctx.section,kind:'confirmation-cancel-did-not-close',handler:action});
666 dismiss();
667 }
668 const after=await confirmSnapshot();
669 if(before!==after){
670 failures.push({route,section:ctx.section,kind:'cancel-mutated-persistent-data',handler:action});
671 }
672 }
673 // Open every safe modal/editor visible in this context without saving.
674 const openActions=[...new Set(controls
675 .filter(el=>!el.disabled && safeOpen.test(handler(el)))
676 .map(el=>handler(el)))].slice(0,30);
677 for (const action of openActions) {
678 await go(route);
679 if (ctx.tabAction) {
680 const tab=clickables(target()).find(el=>handler(el)===ctx.tabAction);
681 if(tab){tab.click();await wait(160);}
682 }
683 const el=clickables(target()).find(x=>handler(x)===action);
684 if (!el) {failures.push({route,section:ctx.section,kind:'open-action-vanished',handler:action});continue;}
685 inventory(route,ctx.section);
686 await press(el,route,ctx.section,'open');
687 const overlay=document.querySelector('.modal-backdrop');
688 if(overlay) {
689 const dialog=overlay.querySelector('.modal-card[role="dialog"][aria-modal="true"]');
690 if(!dialog || !dialog.getAttribute('aria-labelledby') ||
691 !document.getElementById(dialog.getAttribute('aria-labelledby')) ||
692 !dialog.contains(document.activeElement)){
693 failures.push({route,section:ctx.section,kind:'modal-a11y-missing',
694 handler:action.slice(0,170)});
695 }
696 if (route==='expenses' && action.includes('openExpenseModal()')) {
697 const real=dialog?.querySelector('#expCategory');
698 if (!real || real.labels?.length!==1 ||
699 !real.labels[0].textContent.includes('سرفصل')) {
700 failures.push({route,section:ctx.section,kind:'expense-category-label-missing'});
701 }
702 }
703 auditFields(overlay,route,ctx.section+'/modal');
704 const nested=clickables(overlay);
705 const modalControls=nested.map(x=>({
706 route,section:ctx.section+'/modal',tag:x.tagName.toLowerCase(),
707 label:name(x),handler:handler(x).slice(0,180),
708 disabled:!!x.disabled,hasAccessibleName:!!name(x),
709 status:'not-clicked',reason:'modal action; untested or requires fixture-backed input'
710 }));
711 modalControls.forEach(x=>{
712 const key=[x.route,x.section,x.tag,x.label,x.handler].join('|');
713 if(!all.has(key))all.set(key,x);
714 });
715 // Exercise a real cancel/close button when present.
716 const cancel=nested.find(x=>/FINORA\.Modal\.close|Modal\.closeAll/.test(handler(x)) ||
717 /^(انصراف|بستن|بازگشت|✕|×)$/.test(name(x)));
718 if(cancel){
719 cancel.click();await wait(70);
720 clicks.push({route,section:ctx.section+'/modal',category:'cancel',
721 label:name(cancel),handler:handler(cancel).slice(0,170),
722 changed:!document.querySelector('.modal-backdrop')});
723 const key=[route,ctx.section+'/modal',cancel.tagName.toLowerCase(),
724 name(cancel),handler(cancel).slice(0,180)].join('|');
725 const row=all.get(key);if(row)row.status='clicked';
726 } else {
727 // A modal without a cancel button must still be Esc-dismissable.
728 document.dispatchEvent(new KeyboardEvent('keydown',
729 {key:'Escape',bubbles:true,cancelable:true}));
730 await wait(30);
731 }
732 if(document.querySelector('.modal-backdrop')){
733 failures.push({route,section:ctx.section,kind:'modal-cannot-close',
734 handler:action.slice(0,170)});
735 }
736 }
737 dismiss();
738 }
739 }
740 // Only now click reversible navigation and filter controls. Keeping this
741 // after every row-scoped action prevents filters hiding edit/delete targets.
742 for(const group of deferredSafeActions){
743 const pending=[...group.actions];
744 const seen=new Set(pending.map(action=>JSON.stringify([
745 action.tag,action.label,action.handler
746 ])));
747 for(let index=0;index<pending.length;index++){
748 const action=pending[index];
749 window.__Q01_AUDIT_STAGE='safe-action:'+route+':'+action.handler;
750 await go(route);
751 if(group.tabAction){
752 const tab=clickables(target()).find(el=>handler(el)===group.tabAction);
753 if(!tab){
754 failures.push({route,section:group.section,kind:'safe-tab-vanished',handler:group.tabAction});
755 continue;
756 }
757 inventory(route,'root');
758 tab.click();await wait(320);
759 }
760 const el=clickables(target()).find(x=>
761 handler(x)===action.handler && name(x)===action.label &&
762 x.tagName.toLowerCase()===action.tag);
763 if(!el){
764 failures.push({route,section:group.section,kind:'safe-action-vanished',
765 handler:action.handler,label:action.label});
766 continue;
767 }
768 inventory(route,group.section);
769 await press(el,route,group.section,
770 safeNavigate.test(action.handler)?'navigation':'filter');
771 // Preset/toggle controls can reveal a second safe control (for example
772 // the custom-report Apply button). Discover and verify that state too.
773 if(safeFilter.test(action.handler)){
774 await wait(80);
775 inventory(route,group.section);
776 for(const candidate of clickables(target()).filter(x=>
777 !x.disabled && safeFilter.test(handler(x)))){
778 const next={handler:handler(candidate),label:name(candidate),
779 tag:candidate.tagName.toLowerCase()};
780 const key=JSON.stringify([next.tag,next.label,next.handler]);
781 if(!seen.has(key)){seen.add(key);pending.push(next);}
782 }
783 }
784 }
785 }
786 }
787 await FINORA.Router.go('dashboard');
788 const rows=[...all.values()];
789 // A route/tab may render the SAME action in multiple UI states. Counting
790 // each instance as a different button exaggerated the initial denominator.
791 // Unique action signatures omit the tab-context but retain route, visible
792 // name, inline handler and element type (including synthetic row IDs).
793 const uniqueGroups=new Map();
794 const actionKey=row=>JSON.stringify([row.route,row.tag,row.label,row.handler]);
795 for(const row of rows){
796 const key=actionKey(row);
797 if(!uniqueGroups.has(key))uniqueGroups.set(key,[]);
798 uniqueGroups.get(key).push(row);
799 }
800 // A failure on ANY context must never be hidden by a passing click on
801 // another tab. Fail > broken handler > clicked > disabled > untested.
802 const statusRank={failed:5,'broken-handler':4,clicked:3,disabled:1,'not-clicked':0};
803 const uniqueActions=[...uniqueGroups.values()].map(group=>{
804 const representative=group[0];
805 const dominant=[...group].sort((a,b)=>
806 (statusRank[b.status]??0)-(statusRank[a.status]??0))[0];
807 for(const occurrence of group){
808 if(occurrence.status==='not-clicked' && !occurrence.reason){
809 occurrence.reason=group.some(x=>x.status==='clicked')
810 ?'same-control-clicked-in-another-tab-context'
811 :'not-reached-or-not-classified-needs-manual-test';
812 }
813 }
814 return {
815 route:representative.route,tag:representative.tag,
816 label:representative.label,handler:representative.handler,
817 status:dominant.status,contexts:[...new Set(group.map(x=>x.section))],
818 instances:group.length,
819 testedInstances:group.filter(x=>x.status==='clicked').length,
820 failedInstances:group.filter(x=>x.status==='failed' || x.status==='broken-handler').length,
821 whyNotVerified:dominant.status==='not-clicked'
822 ?[...new Set(group.map(x=>x.reason))].join('; ').slice(0,300)
823 :''
824 };
825 });
826 const unclassifiedInstances=rows.filter(r=>r.status==='not-clicked' &&
827 r.reason==='not-reached-or-not-classified-needs-manual-test').length;
828 const byRoute={};
829 for(const route of routes) {
830 const slice=rows.filter(x=>x.route===route);
831 byRoute[route]={
832 discovered:slice.length,
833 uniqueActionSignatures:uniqueActions.filter(x=>x.route===route).length,
834 uniqueClicked:uniqueActions.filter(x=>x.route===route && x.status==='clicked').length,
835 uniqueNotVerified:uniqueActions.filter(x=>x.route===route && x.status==='not-clicked').length,
836 clicked:slice.filter(x=>x.status==='clicked').length,
837 notClicked:slice.filter(x=>x.status==='not-clicked').length,
838 brokenHandlers:slice.filter(x=>x.status==='broken-handler').length,
839 missingAccessibleName:slice.filter(x=>!x.hasAccessibleName).length
840 };
841 }
842 return {
843 environment:'installed-Windows-Tauri-WebView2-synthetic-VM',
844 shellResults,
845 routesVisited:routes.length,routeNames:routes,
846 inventoryCount:rows.length,
847 uniqueActionCount:uniqueActions.length,
848 uniqueActionClicked:uniqueActions.filter(x=>x.status==='clicked').length,
849 uniqueActionUnverified:uniqueActions.filter(x=>x.status==='not-clicked').length,
850 uniqueActionDisabled:uniqueActions.filter(x=>x.status==='disabled').length,
851 uniqueActionFailed:uniqueActions.filter(x=>x.status==='failed').length,
852 unclassifiedInstances,
853 duplicateInstanceCount:rows.length-uniqueActions.length,
854 safeClickCount:clicks.length,
855 skippedCount:rows.filter(x=>x.status==='not-clicked').length,
856 brokenHandlerCount:rows.filter(x=>x.status==='broken-handler').length,
857 accessibilityNameGaps:rows.filter(x=>!x.hasAccessibleName).length,
858 fieldsInspected:fields.size,
859 fieldsMissingProgrammaticLabel:[...fields.values()].filter(x=>!x.programmaticLabel).length,
860 fieldsWithoutLabels:[...fields.values()].filter(x=>!x.programmaticLabel).slice(0,100),
861 fieldCoverageByRoute:Object.fromEntries(routes.map(r=>[r,{
862 inspected:[...fields.values()].filter(x=>x.route===r).length,
863 missingProgrammaticLabel:[...fields.values()].filter(x=>x.route===r && !x.programmaticLabel).length
864 }])),
865 problems:failures,
866 byRoute,
867 controls:rows,
868 uniqueActions,
869 clickEvidence:clicks,
870 fieldEvidence:[...fields.values()],
871 financialActionsNotBulkClicked:true,
872 customerDataUsed:false,
873 everyActionVerified:false
874 };
875 })()