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

fix/a02-private-excel-import-session-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
mjs 342 lines 20.2 KB
Raw
1 import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import fs from 'node:fs';
4 import os from 'node:os';
5 import { createRequire } from 'node:module';
6 import { execFileSync } from 'node:child_process';
7 import path from 'node:path';
8 import { fileURLToPath } from 'node:url';
9
10 const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
11 const folder = path.join(root, 'src', 'views');
12 const viewFiles = fs.readdirSync(folder).filter(n => n.endsWith('.js'));
13 const views = new Map(viewFiles.map(filename => [
14 path.basename(filename, '.js'),
15 fs.readFileSync(path.join(folder, filename), 'utf8')
16 ]));
17
18 test('Q01: every named inline view handler has an actual declared view method', () => {
19 const missing = [];
20 const refs = [];
21 for (const [sourceName, source] of views) {
22 // Find only declarations in the HTML/template markup, not arbitrary test
23 // or controller calls that do not become user-facing controls.
24 const actions = [...source.matchAll(/on(?:click|change|input|submit|mousedown|blur|focus|keyup|keydown)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)];
25 for (const action of actions) {
26 const handler = (action[1] || action[2] || '').replace(/\\(["'])/g, '$1');
27 for (const call of handler.matchAll(/(?:window\.)?([A-Za-z_$][\w$]*(?:View|Modal))\.([A-Za-z_$][\w$]*)\s*\(/g)) {
28 const viewName = call[1], method = call[2];
29 refs.push({sourceName, viewName, method});
30 const src = views.get(viewName);
31 if (!src) {
32 missing.push({sourceName, viewName, method, reason:'source-not-found'});
33 continue;
34 }
35 const declaration = new RegExp('^\\s*(?:async\\s+)?' + method + '\\s*\\(', 'm');
36 if (!declaration.test(src)) missing.push({sourceName, viewName, method, reason:'method-not-declared'});
37 }
38 }
39 }
40 assert.ok(viewFiles.length >= 10, 'unexpectedly few view files in UI inventory');
41 assert.ok(refs.length >= 80, 'inline view events not sufficiently inventoried');
42 assert.deepEqual(missing, [], 'declared on* handlers must resolve to real view methods');
43 });
44
45 test('Q01: the actual sidebar has one entry for each registered route', () => {
46 const shell = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
47 const main = fs.readFileSync(path.join(root, 'src', 'main.js'), 'utf8');
48 const sidebar = [...shell.matchAll(/data-page="([a-z]+)"/g)].map(x=>x[1]);
49 const registered = [...main.matchAll(/\{ name: '([a-z]+)',\s*title:/g)].map(x=>x[1]);
50 assert.equal(new Set(sidebar).size, sidebar.length, 'sidebar has duplicated navigation controls');
51 assert.equal(new Set(registered).size, registered.length, 'router has duplicate route definitions');
52 assert.equal(sidebar.length, 10, 'navigation coverage baseline changed; update native click audit');
53 assert.deepEqual(sidebar.sort(), registered.sort(), 'sidebar has missing, orphan or dead routes');
54 });
55
56 test('Q01: the native UI coverage runner must report unclicked controls explicitly', () => {
57 const source = fs.readFileSync(path.join(root, 'tests', 'windows-vm-ui-interaction-audit-browser.js'), 'utf8');
58 for (const required of [
59 'routesVisited','safeClickCount','not-clicked',
60 'financialActionsNotBulkClicked:true','everyActionVerified:false',
61 'accessibilityNameGaps','missing-function'
62 ]) {
63 assert.ok(source.includes(required), 'coverage reporter missing mandatory field: '+required);
64 }
65 assert.ok(!source.includes('localStorage.clear()') && !source.includes('wipeAll('),
66 'interaction audit must never clear the database in the installed VM');
67 });
68
69 test('Q01: menu controls remain keyboard-reachable with synchronized screen-reader state', () => {
70 const shell = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
71 const main = fs.readFileSync(path.join(root, 'src','main.js'), 'utf8');
72 const router = fs.readFileSync(path.join(root, 'src','core','Router.js'), 'utf8');
73 const styles = fs.readFileSync(path.join(root, 'src','styles','main.css'), 'utf8');
74 const navLinks = [...shell.matchAll(/<a href="#([a-z]+)" data-page="([a-z]+)"/g)];
75 assert.equal(navLinks.length, 10);
76 for(const match of navLinks) assert.equal(match[1], match[2]);
77 assert.match(shell, /id="sidebarToggleBtn"[^>]*aria-label="[^"]+"[^>]*aria-expanded="true"[^>]*aria-controls="sidebarMenu"/);
78 assert.match(main, /localStorage\.setItem\(SIDEBAR_COLLAPSED_KEY,/);
79 assert.match(main, /aria-expanded/);
80 assert.match(router, /aria-current/);
81 assert.match(styles, /:focus-visible/);
82 const desktopToggle = styles.match(/\.hamburger\s*\{([^}]*)\}/)?.[1];
83 assert.ok(desktopToggle, 'desktop sidebar toggle styles not found');
84 assert.match(desktopToggle, /display:\s*inline-flex\s*;/,
85 'the sidebar toggle must be visible/focusable on desktop as well as mobile');
86 assert.doesNotMatch(desktopToggle, /display:\s*none\s*;/);
87 const nativeAudit = fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
88 assert.match(nativeAudit, /Desktop sidebar toggle cannot receive keyboard focus/);
89 });
90
91 test('Q01: shared dialogs have ARIA naming, keyboard dismissal and focus restoration contracts', () => {
92 const code = fs.readFileSync(path.join(root, 'src','core','Modal.js'),'utf8');
93 assert.match(code, /setAttribute\('role', 'dialog'\)/);
94 assert.match(code, /setAttribute\('aria-modal', 'true'\)/);
95 assert.match(code, /setAttribute\('aria-labelledby', titleId\)/);
96 assert.match(code, /event\.key === 'Escape'/);
97 assert.match(code, /event\.key !== 'Tab'/);
98 assert.match(code, /previousFocus\.focus/);
99 assert.match(code, /const focusables = this\._focusable\(modal\.card\)/,
100 'initial focus must skip hidden financial inputs');
101 assert.match(code, /focusables\.find\(el => el\.matches\('input, select, textarea'\)\)/);
102 assert.match(code, /\[data-confirm-message\]'\)\.textContent = String\(message \?\? ''\)/,
103 'untrusted confirmation messages must be assigned as text, not HTML');
104 assert.doesNotMatch(code, /\$\{message\}<\/p>/,
105 'financial confirmation message must never be interpolated into innerHTML');
106 assert.match(code, /cancelButton\.textContent = String\(cancelText \?\? ''\)/);
107 assert.match(code, /confirmButton\.textContent = String\(confirmText \?\? ''\)/);
108 assert.doesNotMatch(code, /\$\{(?:cancelText|confirmText)\}<\/button>/,
109 'confirmation button labels must never become executable markup');
110 assert.match(code, /addEventListener\('keydown'/);
111 assert.match(code, /removeEventListener\('keydown'/);
112 });
113
114 test('Q01: form labels are only associated within unambiguous modal groups', () => {
115 const modal=fs.readFileSync(path.join(root,'src','core','Modal.js'),'utf8');
116 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
117 assert.match(modal, /_associateFormLabels\(card\)/);
118 assert.match(modal, /fields\.length !== 1/);
119 assert.match(modal, /labels\.length !== 1/);
120 assert.match(modal, /field\.labels\?\.length/);
121 assert.match(audit, /Modal form labels were missing, ambiguous, or overwrote explicit names/);
122 assert.match(audit, /expense-category-label-missing/);
123 });
124
125 test('Q01: primary search and filter controls have explicit accessible names', () => {
126 for (const [name, count] of [
127 ['InvoicesView',3],['ProductsView',2],['ContactsView',4],['ExpensesView',5]
128 ]) {
129 const source=fs.readFileSync(path.join(root,'src','views',name+'.js'),'utf8');
130 const names=[...source.matchAll(/aria-label="[^"]+"/g)];
131 assert.ok(names.length>=count, name+' lost search/filter accessibility labels');
132 }
133 });
134
135 test('A03: expense table escapes imported values in HTML and inline action arguments', () => {
136 const src=fs.readFileSync(path.join(root,'src','views','ExpensesView.js'),'utf8');
137 const native=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
138 for(const fragment of [
139 'this._esc(Formatters.toPersianDigits(e.date',
140 'this._esc(ExpenseController.getMethodLabel(e.method))',
141 'this._esc(e.refNumber ? Formatters.toPersianDigits(e.refNumber)',
142 'this._esc(JSON.stringify(String(e.id ??',
143 '<option value="${this._esc(c)}"'
144 ]) assert.ok(src.includes(fragment), 'unescaped expense HTML found: '+fragment);
145 assert.ok(native.includes('expenseUnsafeHtmlEscaped:true'));
146 assert.ok(native.includes('Untrusted expense list fields created executable markup'));
147 assert.ok(native.includes('Expense row identifier escaped the safe JS argument'));
148 });
149
150 test('A03: financial list views encode imported record IDs and textual values', () => {
151 const sources=['InvoicesView','ProductsView','ContactsView','TreasuryView','ChequesView'];
152 for(const name of sources){
153 const source=fs.readFileSync(path.join(root,'src','views',name+'.js'),'utf8');
154 assert.ok(source.includes('this._esc(JSON.stringify(String('),
155 name+' lacks HTML-safe JSON encoding for inline record arguments');
156 assert.doesNotMatch(source,/onclick="[^"]*\('\$\{[^}]+\.id\}'\)/,
157 name+' still interpolates raw IDs into JavaScript event handlers');
158 assert.doesNotMatch(source,/<option value="\$\{(?:[a-zA-Z]+)\.id\}"/,
159 name+' still interpolates raw IDs into option attributes');
160 }
161 const invoice=fs.readFileSync(path.join(root,'src','views','InvoicesView.js'),'utf8');
162 assert.ok(invoice.includes('${this._esc(k.label)}'), 'unknown imported invoice kind is not HTML escaped');
163 assert.ok(invoice.includes('renderTable(invoices = cache.invoices)'),
164 'native adversarial test needs an isolated read-only invoice render fixture');
165 const expenses=fs.readFileSync(path.join(root,'src','views','ExpensesView.js'),'utf8');
166 assert.ok(expenses.includes('this._esc(JSON.stringify(String(e.id ??'));
167 });
168
169 test('Q01: remaining financial grid, reporting and settings inputs announce their function', () => {
170 const read=name=>fs.readFileSync(path.join(root,'src','views',name+'.js'),'utf8');
171 const cases=[
172 ['ReportsView',['aria-label="از تاریخ گزارش"','aria-label="تا تاریخ گزارش"']],
173 ['InvoiceFormView',['aria-label="جستجوی کالای ردیف فاکتور"','aria-label="نوع تخفیف ردیف"','aria-label="وضعیت پرداخت فاکتور"']],
174 ['AccountingView',['aria-label="حساب ردیف سند"','aria-label="مبلغ بدهکار ردیف"','aria-label="مبلغ بستانکار ردیف"','aria-label="شرح ردیف سند"','for="acStWarehouse"']],
175 ['TreasuryView',['aria-label="جستجوی تراکنش‌های خزانه"']],
176 ['ChequesView',['aria-label="جستجوی چک"','aria-label="نوع چک"','aria-label="وضعیت چک"']],
177 ['SettingsView',['aria-label="تعداد صفرهای میانبر مثبت"','aria-label="متن تایید پاک کردن داده‌ها"']]
178 ];
179 for(const [name,labels] of cases){
180 const source=read(name);
181 for(const label of labels)assert.ok(source.includes(label),name+' missing programmatic name: '+label);
182 }
183 const runner=fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
184 assert.ok(runner.includes('audit.fieldsMissingProgrammaticLabel <= 5'));
185 });
186
187 test('A02: Excel imports reject destructive replacement before touching master data', () => {
188 const controller=fs.readFileSync(path.join(root,'src','controllers','ExcelController.js'),'utf8');
189 const settings=fs.readFileSync(path.join(root,'src','views','SettingsView.js'),'utf8');
190 assert.equal((controller.match(/if \(mode !== 'merge'\)/g)||[]).length,2,
191 'both contact and product imports must fail closed');
192 assert.doesNotMatch(controller,/if \(mode === 'replace'\)/,
193 'nontransactional delete-then-import must never be reachable');
194 const importModeSelect=settings.split('id="importMode">')[1]?.split('</select>')[0];
195 assert.ok(importModeSelect, 'Excel import mode selector missing');
196 assert.doesNotMatch(importModeSelect,/<option value="replace"/,
197 'destructive Excel option must not be offered; the backup restore option is separate');
198 assert.match(settings,/pending\?\.kind !== kind/);
199 assert.match(settings,/data-excel-import-submit/);
200 assert.doesNotMatch(settings,/_confirmImport\(\$\{JSON\.stringify\(kind\)/,
201 'untrusted filenames must never be embedded as executable inline HTML');
202 });
203
204 test('A03: company switch, posted journals and printable ledger encode untrusted IDs', () => {
205 const settings=fs.readFileSync(path.join(root,'src','views','SettingsView.js'),'utf8');
206 const accounting=fs.readFileSync(path.join(root,'src','views','AccountingView.js'),'utf8');
207 const ledger=fs.readFileSync(path.join(root,'src','views','ContactLedgerModal.js'),'utf8');
208 assert.ok(settings.includes('this._esc(JSON.stringify(String(c.id ??'));
209 assert.ok(accounting.includes('const actionArg = value => html(JSON.stringify(String(value ??'));
210 assert.ok(!accounting.includes("'${html(j.id)}'"));
211 assert.ok(!accounting.includes("'${html(p.id)}'"));
212 assert.ok(!accounting.includes("'${html(s.id)}'"));
213 assert.ok(ledger.includes('this._esc(JSON.stringify(String(contactId ??'));
214 assert.ok(ledger.includes('<title>صورت‌حساب ${this._esc(contact.name)}</title>'));
215 assert.doesNotMatch(ledger,/cdn\.jsdelivr\.net/);
216 assert.ok(ledger.split('this._esc(Formatters.toPersianDigits(r.date').length>=3);
217 });
218
219 test('A02: private Excel preview releases data on cancel and blocks concurrent import', () => {
220 const settings=fs.readFileSync(path.join(root,'src','views','SettingsView.js'),'utf8');
221 assert.ok(settings.includes('let pendingExcelImport = null'));
222 assert.ok(settings.includes('let excelImportBusy = false'));
223 assert.ok(settings.includes('if (excelImportBusy) return;'));
224 assert.ok(settings.includes('if (pendingExcelImport === pending) pendingExcelImport = null;'));
225 assert.ok(settings.includes('submitButton.disabled = true'));
226 assert.ok(settings.includes('onClose: () =>'));
227 assert.doesNotMatch(settings,/window\.__import(?:RawData|Kind)/,
228 'private workbook contents must never be exposed as global window properties');
229 });
230
231 test('Q01: Escape is handled once for nested financial dialogs and shortcut target is topmost', () => {
232 const shortcuts = fs.readFileSync(path.join(root,'src','core','KeyboardShortcuts.js'),'utf8');
233 const modal = fs.readFileSync(path.join(root,'src','core','Modal.js'),'utf8');
234 assert.match(shortcuts, /window\.FINORA\?\.Modal\?\.stack\?\.length/);
235 assert.match(shortcuts, /backdrops\[backdrops\.length - 1\]/);
236 assert.match(modal, /shortcuts\.escapeCloses === false/);
237 assert.match(modal, /this\.close\(\)/);
238 });
239
240 test('Q01: pressing plain Enter on focused Cancel, buttons or inputs must not invoke global save', () => {
241 const shortcuts = fs.readFileSync(path.join(root, 'src','core','KeyboardShortcuts.js'), 'utf8');
242 const nativeAudit = fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'), 'utf8');
243 assert.match(shortcuts, /active !== modal\.querySelector\('\.modal-card'\)/,
244 'plain Enter must only target the dialog surface, never its focused controls');
245 assert.match(shortcuts, /e\.key === 'Enter' && !e\.shiftKey && this\.settings\.enterConfirms && modal/);
246 assert.match(nativeAudit, /enterOnFocusedCancelDoesNotSave:true/);
247 assert.match(nativeAudit, /enterOnInputDoesNotSubmit:true/);
248 assert.match(nativeAudit, /'Enter on focused Cancel was hijacked as financial confirmation'/);
249 });
250
251 test('Q01: installed WebView2 must click synthetic modal Cancel/Confirm and trap Tab both directions', () => {
252 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
253 const native=fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
254 for (const check of [
255 'tabAndShiftTabStayInsideTopDialog:true',
256 'cancelDoesNotConfirmAndRestoresFocus:true',
257 'syntheticConfirmRunsExactlyOnce:true',
258 'syntheticConfirmed!==0','syntheticConfirmed!==1',
259 'confirmationTextEscaped:true',
260 'visibleInputAutoFocused:true',
261 'Dialog initial focus landed outside first visible financial input',
262 'Confirmation message was interpreted as executable HTML',
263 'tabForward.defaultPrevented','tabBackward.defaultPrevented'
264 ]) assert.ok(audit.includes(check),'native modal control evidence missing: '+check);
265 for(const check of [
266 'modalKeyboard.tabAndShiftTabStayInsideTopDialog',
267 'modalKeyboard.cancelDoesNotConfirmAndRestoresFocus',
268 'modalKeyboard.syntheticConfirmRunsExactlyOnce'
269 ]) assert.ok(native.includes(check),'installed native runner must assert: '+check);
270 });
271
272 test('Q01: financial mutations are not mislabeled safe by the static control catalog', () => {
273 const dir=fs.mkdtempSync(path.join(os.tmpdir(),'q01-source-catalog-'));
274 try {
275 const output=path.join(dir,'catalog.json');
276 execFileSync(process.execPath,[path.join(root,'scripts','q01-ui-control-catalog.cjs'),output],{
277 cwd:root,encoding:'utf8',timeout:20000,stdio:['ignore','pipe','pipe']
278 });
279 const catalog=JSON.parse(fs.readFileSync(output,'utf8'));
280 assert.ok(catalog.eventBindings>=200,'unexpectedly few view event bindings');
281 assert.ok(catalog.sensitiveBindings>=40,
282 'financial actions were not classified conservatively; check verb+suffix matcher');
283 assert.equal(catalog.allButtonsClicked,false);
284 for (const name of ['saveJournal','postDraft','deleteDraft',
285 'confirmOpeningPosting','saveCheque','saveProduct','restoreBackup','confirmWipe']) {
286 const matches=catalog.controls.filter(x=>x.action.includes('.'+name+'('));
287 assert.ok(matches.length>0,'sensitive action not discovered: '+name);
288 assert.ok(matches.every(x=>x.category==='sensitive-write-or-export'),
289 'sensitive action incorrectly marked navigation: '+name);
290 assert.ok(matches.every(x=>x.runtimeClicked===false),
291 'source catalog must not claim runtime interaction: '+name);
292 }
293 const safe=catalog.controls.filter(x=>/\.(?:switchTab|_switchTab)\s*\(/.test(x.action));
294 assert.ok(safe.length>0,'navigation controls not discovered');
295 assert.ok(safe.some(x=>x.category==='navigation-or-other'),
296 'all menu actions incorrectly categorized as financial writes');
297 } finally {
298 fs.rmSync(dir,{recursive:true,force:true});
299 }
300 });
301
302 test('Q01: native click audit separates unique action signatures from repeated tab instances', () => {
303 const audit = fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
304 const native = fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
305 for(const key of ['uniqueActionCount','uniqueActionClicked','uniqueActionUnverified',
306 'duplicateInstanceCount','unclassifiedInstances','uniqueActions',
307 'same-control-clicked-in-another-tab-context',
308 'not-reached-or-not-classified-needs-manual-test']){
309 assert.ok(audit.includes(key),'missing unique action audit evidence: '+key);
310 }
311 assert.ok(native.includes('audit.uniqueActionCount <= audit.inventoryCount'),
312 'native runner must not confuse 470 UI instances with unique buttons');
313 assert.ok(native.includes("x.status!=='not-clicked' || !!x.reason"),
314 'every unclicked action occurrence must have a reason');
315 });
316
317 test('Q01: unverified-action Markdown respects deduplicated click evidence and fails closed', () => {
318 const require=createRequire(import.meta.url);
319 const { buildReport }=require(path.join(root,'scripts','q01-native-action-gap-report.cjs'));
320 const synthetic={
321 environment:'installed-Windows-Tauri-WebView2-synthetic-VM',
322 everyActionVerified:false,customerDataUsed:false,
323 uniqueActionCount:2,uniqueActionClicked:1,uniqueActionUnverified:1,
324 uniqueActionDisabled:0,uniqueActionFailed:0,
325 duplicateInstanceCount:1,inventoryCount:3,
326 controls:[{},{},{}],
327 uniqueActions:[
328 {route:'invoices',tag:'button',label:'ثبت نهایی',handler:'InvoiceForm.save()',
329 status:'not-clicked',whyNotVerified:'requires synthetic financial fixture'},
330 {route:'invoices',tag:'button',label:'لغو',handler:'Modal.close()',
331 status:'clicked',whyNotVerified:''}
332 ],
333 problems:[{route:'invoices',kind:'manual-review',label:'fixture needed'}]
334 };
335 const md=buildReport(synthetic);
336 assert.match(md,/ثبت نهایی/);
337 assert.match(md,/requires synthetic financial fixture/);
338 assert.match(md,/امضاهای کنترلی متمایز \| 2/);
339 assert.doesNotMatch(md,/\| لغو \| clicked/,'clicked actions do not belong in gap list');
340 assert.throws(()=>buildReport({...synthetic,everyActionVerified:true}),/UNVERIFIED_INPUT/);
341 assert.throws(()=>buildReport({...synthetic,inventoryCount:500}),/COUNT_MISMATCH/);
342 });