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

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
mjs 425 lines 25.4 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('A01: financial confirm never executes twice after Confirm/Cancel or while hidden', () => {
115 const modal=fs.readFileSync(path.join(root,'src','core','Modal.js'),'utf8');
116 const native=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
117 const runner=fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
118 assert.ok(modal.includes('let settled = false'));
119 assert.ok(modal.includes('this.stack[this.stack.length - 1] === modal'));
120 assert.equal(modal.split('if (settled || !isActive()) return;').length-1, 2);
121 for(const token of ['confirmClick.click();','staleConfirm?.click()',
122 "hiddenParent?.querySelector('[data-action=\"confirm\"]')?.click()",
123 'staleFinancialConfirmIgnored:true']) {
124 assert.ok(native.includes(token),'missing one-shot UI probe: '+token);
125 }
126 assert.ok(runner.includes('modalKeyboard.staleFinancialConfirmIgnored'));
127 });
128
129 test('Q01: native audit verifies safe routes, filters, edit previews and cancel-only destructive prompts', () => {
130 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
131 for(const token of ['safeNavigate','safeFilter','safeOpen','safeConfirm',
132 'confirm-request','confirm-cancel','confirmation-prompt-missing',
133 'cancel-mutated-persistent-data','FINORA.Storage.getAll(store)',
134 'safe-action-vanished','editInvoice','editProduct','editContact',
135 'editCheque','runFinancialDiagnostics','checkHolooMigrationReadiness']) {
136 assert.ok(audit.includes(token),'native action audit missing coverage contract: '+token);
137 }
138 assert.match(audit,/const confirmStores=\['users','companies','contacts','products'/);
139 assert.match(audit,/category !== 'open' && category !== 'confirm-request'/);
140 assert.match(audit,/_togglePreInvoice\|_setStockFilter\|_clearFilters/);
141 });
142
143 test('Q01: form labels are only associated within unambiguous modal groups', () => {
144 const modal=fs.readFileSync(path.join(root,'src','core','Modal.js'),'utf8');
145 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
146 assert.match(modal, /_associateFormLabels\(card\)/);
147 assert.match(modal, /fields\.length !== 1/);
148 assert.match(modal, /labels\.length !== 1/);
149 assert.match(modal, /field\.labels\?\.length/);
150 assert.match(audit, /Modal form labels were missing, ambiguous, or overwrote explicit names/);
151 assert.match(audit, /expense-category-label-missing/);
152 });
153
154 test('Q01: primary search and filter controls have explicit accessible names', () => {
155 for (const [name, count] of [
156 ['InvoicesView',3],['ProductsView',2],['ContactsView',4],['ExpensesView',5]
157 ]) {
158 const source=fs.readFileSync(path.join(root,'src','views',name+'.js'),'utf8');
159 const names=[...source.matchAll(/aria-label="[^"]+"/g)];
160 assert.ok(names.length>=count, name+' lost search/filter accessibility labels');
161 }
162 });
163
164 test('A03: expense table escapes imported values in HTML and inline action arguments', () => {
165 const src=fs.readFileSync(path.join(root,'src','views','ExpensesView.js'),'utf8');
166 const native=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
167 for(const fragment of [
168 'this._esc(Formatters.toPersianDigits(e.date',
169 'this._esc(ExpenseController.getMethodLabel(e.method))',
170 'this._esc(e.refNumber ? Formatters.toPersianDigits(e.refNumber)',
171 'this._esc(JSON.stringify(String(e.id ??',
172 '<option value="${this._esc(c)}"'
173 ]) assert.ok(src.includes(fragment), 'unescaped expense HTML found: '+fragment);
174 assert.ok(native.includes('expenseUnsafeHtmlEscaped:true'));
175 assert.ok(native.includes('Untrusted expense list fields created executable markup'));
176 // The first category option is the legitimate 'all' filter, never the injected row.
177 assert.match(native, /filter\(option=>option\.value===hostileCategory\)/);
178 assert.match(native, /matchingOptions\.length!==1/);
179 assert.doesNotMatch(native, /select\[aria-label="سرفصل سند"\] option'\)\?\.value!==hostileCategory/);
180 assert.ok(native.includes('Expense row identifier escaped the safe JS argument'));
181 });
182
183 test('A03: financial list views encode imported record IDs and textual values', () => {
184 const sources=['InvoicesView','ProductsView','ContactsView','TreasuryView','ChequesView'];
185 for(const name of sources){
186 const source=fs.readFileSync(path.join(root,'src','views',name+'.js'),'utf8');
187 assert.ok(source.includes('this._esc(JSON.stringify(String('),
188 name+' lacks HTML-safe JSON encoding for inline record arguments');
189 assert.doesNotMatch(source,/onclick="[^"]*\('\$\{[^}]+\.id\}'\)/,
190 name+' still interpolates raw IDs into JavaScript event handlers');
191 assert.doesNotMatch(source,/<option value="\$\{(?:[a-zA-Z]+)\.id\}"/,
192 name+' still interpolates raw IDs into option attributes');
193 }
194 const invoice=fs.readFileSync(path.join(root,'src','views','InvoicesView.js'),'utf8');
195 assert.ok(invoice.includes('${this._esc(k.label)}'), 'unknown imported invoice kind is not HTML escaped');
196 assert.ok(invoice.includes('renderTable(invoices = cache.invoices)'),
197 'native adversarial test needs an isolated read-only invoice render fixture');
198 const expenses=fs.readFileSync(path.join(root,'src','views','ExpensesView.js'),'utf8');
199 assert.ok(expenses.includes('this._esc(JSON.stringify(String(e.id ??'));
200 });
201
202 test('Q01: remaining financial grid, reporting and settings inputs announce their function', () => {
203 const read=name=>fs.readFileSync(path.join(root,'src','views',name+'.js'),'utf8');
204 const cases=[
205 ['ReportsView',['aria-label="از تاریخ گزارش"','aria-label="تا تاریخ گزارش"']],
206 ['InvoiceFormView',['aria-label="جستجوی کالای ردیف فاکتور"','aria-label="نوع تخفیف ردیف"','aria-label="وضعیت پرداخت فاکتور"']],
207 ['AccountingView',['aria-label="حساب ردیف سند"','aria-label="مبلغ بدهکار ردیف"','aria-label="مبلغ بستانکار ردیف"','aria-label="شرح ردیف سند"','for="acStWarehouse"']],
208 ['TreasuryView',['aria-label="جستجوی تراکنش‌های خزانه"']],
209 ['ChequesView',['aria-label="جستجوی چک"','aria-label="نوع چک"','aria-label="وضعیت چک"']],
210 ['SettingsView',['aria-label="تعداد صفرهای میانبر مثبت"','aria-label="متن تایید پاک کردن داده‌ها"']]
211 ];
212 for(const [name,labels] of cases){
213 const source=read(name);
214 for(const label of labels)assert.ok(source.includes(label),name+' missing programmatic name: '+label);
215 }
216 const runner=fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
217 assert.ok(runner.includes('audit.fieldsMissingProgrammaticLabel <= 5'));
218 });
219
220 test('A02: Excel imports reject destructive replacement before touching master data', () => {
221 const controller=fs.readFileSync(path.join(root,'src','controllers','ExcelController.js'),'utf8');
222 const settings=fs.readFileSync(path.join(root,'src','views','SettingsView.js'),'utf8');
223 assert.equal((controller.match(/if \(mode !== 'merge'\)/g)||[]).length,2,
224 'both contact and product imports must fail closed');
225 assert.doesNotMatch(controller,/if \(mode === 'replace'\)/,
226 'nontransactional delete-then-import must never be reachable');
227 const importModeSelect=settings.split('id="importMode">')[1]?.split('</select>')[0];
228 assert.ok(importModeSelect, 'Excel import mode selector missing');
229 assert.doesNotMatch(importModeSelect,/<option value="replace"/,
230 'destructive Excel option must not be offered; the backup restore option is separate');
231 assert.match(settings,/pending\?\.kind !== kind/);
232 assert.match(settings,/data-excel-import-submit/);
233 assert.doesNotMatch(settings,/_confirmImport\(\$\{JSON\.stringify\(kind\)/,
234 'untrusted filenames must never be embedded as executable inline HTML');
235 });
236
237 test('A03: company switch, posted journals and printable ledger encode untrusted IDs', () => {
238 const settings=fs.readFileSync(path.join(root,'src','views','SettingsView.js'),'utf8');
239 const accounting=fs.readFileSync(path.join(root,'src','views','AccountingView.js'),'utf8');
240 const ledger=fs.readFileSync(path.join(root,'src','views','ContactLedgerModal.js'),'utf8');
241 assert.ok(settings.includes('this._esc(JSON.stringify(String(c.id ??'));
242 assert.ok(accounting.includes('const actionArg = value => html(JSON.stringify(String(value ??'));
243 assert.ok(!accounting.includes("'${html(j.id)}'"));
244 assert.ok(!accounting.includes("'${html(p.id)}'"));
245 assert.ok(!accounting.includes("'${html(s.id)}'"));
246 assert.ok(ledger.includes('this._esc(JSON.stringify(String(contactId ??'));
247 assert.ok(ledger.includes('<title>صورت‌حساب ${this._esc(contact.name)}</title>'));
248 assert.doesNotMatch(ledger,/cdn\.jsdelivr\.net/);
249 assert.ok(ledger.split('this._esc(Formatters.toPersianDigits(r.date').length>=3);
250 });
251
252 test('A02: private Excel preview releases data on cancel and blocks concurrent import', () => {
253 const settings=fs.readFileSync(path.join(root,'src','views','SettingsView.js'),'utf8');
254 assert.ok(settings.includes('let pendingExcelImport = null'));
255 assert.ok(settings.includes('let excelImportBusy = false'));
256 assert.ok(settings.includes('if (excelImportBusy) return;'));
257 assert.ok(settings.includes('if (pendingExcelImport === pending) pendingExcelImport = null;'));
258 assert.ok(settings.includes('submitButton.disabled = true'));
259 assert.ok(settings.includes('onClose: () =>'));
260 assert.doesNotMatch(settings,/window\.__import(?:RawData|Kind)/,
261 'private workbook contents must never be exposed as global window properties');
262 });
263
264 test('Q01: Escape is handled once for nested financial dialogs and shortcut target is topmost', () => {
265 const shortcuts = fs.readFileSync(path.join(root,'src','core','KeyboardShortcuts.js'),'utf8');
266 const modal = fs.readFileSync(path.join(root,'src','core','Modal.js'),'utf8');
267 assert.match(shortcuts, /window\.FINORA\?\.Modal\?\.stack\?\.length/);
268 assert.match(shortcuts, /backdrops\[backdrops\.length - 1\]/);
269 assert.match(modal, /shortcuts\.escapeCloses === false/);
270 assert.match(modal, /this\.close\(\)/);
271 });
272
273 test('Q01: pressing plain Enter on focused Cancel, buttons or inputs must not invoke global save', () => {
274 const shortcuts = fs.readFileSync(path.join(root, 'src','core','KeyboardShortcuts.js'), 'utf8');
275 const nativeAudit = fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'), 'utf8');
276 assert.match(shortcuts, /active !== modal\.querySelector\('\.modal-card'\)/,
277 'plain Enter must only target the dialog surface, never its focused controls');
278 assert.match(shortcuts, /e\.key === 'Enter' && !e\.shiftKey && this\.settings\.enterConfirms && modal/);
279 assert.match(nativeAudit, /enterOnFocusedCancelDoesNotSave:true/);
280 assert.match(nativeAudit, /enterOnInputDoesNotSubmit:true/);
281 assert.match(nativeAudit, /'Enter on focused Cancel was hijacked as financial confirmation'/);
282 });
283
284 test('Q01: installed WebView2 must click synthetic modal Cancel/Confirm and trap Tab both directions', () => {
285 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
286 const native=fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
287 for (const check of [
288 'tabAndShiftTabStayInsideTopDialog:true',
289 'cancelDoesNotConfirmAndRestoresFocus:true',
290 'syntheticConfirmRunsExactlyOnce:true',
291 'syntheticConfirmed!==0','syntheticConfirmed!==1',
292 'confirmationTextEscaped:true',
293 'visibleInputAutoFocused:true',
294 'Dialog initial focus landed outside first visible financial input',
295 'Confirmation message was interpreted as executable HTML',
296 'tabForward.defaultPrevented','tabBackward.defaultPrevented'
297 ]) assert.ok(audit.includes(check),'native modal control evidence missing: '+check);
298 for(const check of [
299 'modalKeyboard.tabAndShiftTabStayInsideTopDialog',
300 'modalKeyboard.cancelDoesNotConfirmAndRestoresFocus',
301 'modalKeyboard.syntheticConfirmRunsExactlyOnce'
302 ]) assert.ok(native.includes(check),'installed native runner must assert: '+check);
303 });
304
305 test('Q01: financial mutations are not mislabeled safe by the static control catalog', () => {
306 const dir=fs.mkdtempSync(path.join(os.tmpdir(),'q01-source-catalog-'));
307 try {
308 const output=path.join(dir,'catalog.json');
309 execFileSync(process.execPath,[path.join(root,'scripts','q01-ui-control-catalog.cjs'),output],{
310 cwd:root,encoding:'utf8',timeout:20000,stdio:['ignore','pipe','pipe']
311 });
312 const catalog=JSON.parse(fs.readFileSync(output,'utf8'));
313 assert.ok(catalog.eventBindings>=200,'unexpectedly few view event bindings');
314 assert.ok(catalog.sensitiveBindings>=40,
315 'financial actions were not classified conservatively; check verb+suffix matcher');
316 assert.equal(catalog.allButtonsClicked,false);
317 for (const name of ['saveJournal','postDraft','deleteDraft',
318 'confirmOpeningPosting','saveCheque','saveProduct','restoreBackup','confirmWipe']) {
319 const matches=catalog.controls.filter(x=>x.action.includes('.'+name+'('));
320 assert.ok(matches.length>0,'sensitive action not discovered: '+name);
321 assert.ok(matches.every(x=>x.category==='sensitive-write-or-export'),
322 'sensitive action incorrectly marked navigation: '+name);
323 assert.ok(matches.every(x=>x.runtimeClicked===false),
324 'source catalog must not claim runtime interaction: '+name);
325 }
326 const safe=catalog.controls.filter(x=>/\.(?:switchTab|_switchTab)\s*\(/.test(x.action));
327 assert.ok(safe.length>0,'navigation controls not discovered');
328 assert.ok(safe.some(x=>x.category==='navigation-or-other'),
329 'all menu actions incorrectly categorized as financial writes');
330 } finally {
331 fs.rmSync(dir,{recursive:true,force:true});
332 }
333 });
334
335 test('Q01: native UI audit has no duplicate safeConfirm lexical declaration', () => {
336 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
337 assert.equal(audit.split('const safeConfirmAction =').length-1,1,
338 'safeConfirmAction matcher must be declared exactly once');
339 assert.equal(audit.split('const safeConfirm =').length-1,0,
340 'the matcher must not collide with modal fixture variable names');
341 assert.ok(audit.includes('const safeConfirmDialog=FINORA.Modal.stack'));
342 assert.ok(audit.includes('safeConfirmDialog.querySelector'));
343 });
344
345 test('Q01: filter clicks are deferred until row-scoped confirmation and editor probes finish', () => {
346 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
347 const queue=audit.indexOf('const deferredSafeActions=[]');
348 const confirm=audit.indexOf('const confirmActions=');
349 const open=audit.indexOf('const openActions=');
350 const deferred=audit.indexOf('for(const group of deferredSafeActions)');
351 assert.ok(queue>=0 && confirm>queue && open>confirm && deferred>open,
352 'filters must not hide row targets before edit/delete confirmation probes');
353 assert.ok(audit.includes('safe-tab-vanished'));
354 assert.ok(audit.includes('safe-action-vanished'));
355 assert.ok(audit.includes("const safeTab = /\\.(?:_switchTab|switchTab)"));
356 assert.ok(audit.includes("_switchPeriod|_setPreset"));
357 assert.ok(audit.includes("tabAction:tabActions[0]||null"));
358 assert.ok(audit.includes("const pending=[...group.actions]"));
359 assert.ok(audit.includes("for(const candidate of clickables(target()).filter(x=>"));
360 assert.doesNotMatch(audit,/safeOpen = .*changeStatus|safeOpen = .*_printInvoice/);
361 });
362
363 test('Q01: safe navigation audit distinguishes same-handler controls by label and tag', () => {
364 const audit=fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
365 assert.ok(audit.includes('handler:handler(el),label:name(el),tag:el.tagName.toLowerCase()'));
366 assert.ok(audit.includes('handler(x)===action.handler && name(x)===action.label'));
367 assert.ok(audit.includes('tab.click();await wait(160);'));
368 assert.ok(audit.includes("safeNavigate.test(action.handler)?'navigation':'filter'"));
369 });
370
371 test('Q01: native WebView2 runner validates the exact injected audit source before execution', () => {
372 const runner=fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
373 assert.ok(runner.includes("auditSource.split('const safeConfirmAction =').length-1,1"));
374 assert.ok(runner.includes("auditSource.includes('const deferredSafeActions=[]')"));
375 assert.ok(runner.includes("auditSource.includes('for(const group of deferredSafeActions)')"));
376 });
377
378 test('Q01: partial-payment amount field has an explicit associated label', () => {
379 const view=fs.readFileSync(path.join(root,'src','views','InvoiceFormView.js'),'utf8');
380 assert.match(view,/label for="invPaidAmount"/);
381 assert.match(view,/id="invPaidAmount"/);
382 assert.match(view,/مبلغ پرداخت‌شده/);
383 });
384
385 test('Q01: native click audit separates unique action signatures from repeated tab instances', () => {
386 const audit = fs.readFileSync(path.join(root,'tests','windows-vm-ui-interaction-audit-browser.js'),'utf8');
387 const native = fs.readFileSync(path.join(root,'tests','windows-vm-installed-tauri-cdp.cjs'),'utf8');
388 for(const key of ['uniqueActionCount','uniqueActionClicked','uniqueActionUnverified',
389 'duplicateInstanceCount','unclassifiedInstances','uniqueActions',
390 'same-control-clicked-in-another-tab-context',
391 'not-reached-or-not-classified-needs-manual-test']){
392 assert.ok(audit.includes(key),'missing unique action audit evidence: '+key);
393 }
394 assert.ok(native.includes('audit.uniqueActionCount <= audit.inventoryCount'),
395 'native runner must not confuse 470 UI instances with unique buttons');
396 assert.ok(native.includes("x.status!=='not-clicked' || !!x.reason"),
397 'every unclicked action occurrence must have a reason');
398 });
399
400 test('Q01: unverified-action Markdown respects deduplicated click evidence and fails closed', () => {
401 const require=createRequire(import.meta.url);
402 const { buildReport }=require(path.join(root,'scripts','q01-native-action-gap-report.cjs'));
403 const synthetic={
404 environment:'installed-Windows-Tauri-WebView2-synthetic-VM',
405 everyActionVerified:false,customerDataUsed:false,
406 uniqueActionCount:2,uniqueActionClicked:1,uniqueActionUnverified:1,
407 uniqueActionDisabled:0,uniqueActionFailed:0,
408 duplicateInstanceCount:1,inventoryCount:3,
409 controls:[{},{},{}],
410 uniqueActions:[
411 {route:'invoices',tag:'button',label:'ثبت نهایی',handler:'InvoiceForm.save()',
412 status:'not-clicked',whyNotVerified:'requires synthetic financial fixture'},
413 {route:'invoices',tag:'button',label:'لغو',handler:'Modal.close()',
414 status:'clicked',whyNotVerified:''}
415 ],
416 problems:[{route:'invoices',kind:'manual-review',label:'fixture needed'}]
417 };
418 const md=buildReport(synthetic);
419 assert.match(md,/ثبت نهایی/);
420 assert.match(md,/requires synthetic financial fixture/);
421 assert.match(md,/امضاهای کنترلی متمایز \| 2/);
422 assert.doesNotMatch(md,/\| لغو \| clicked/,'clicked actions do not belong in gap list');
423 assert.throws(()=>buildReport({...synthetic,everyActionVerified:true}),/UNVERIFIED_INPUT/);
424 assert.throws(()=>buildReport({...synthetic,inventoryCount:500}),/COUNT_MISMATCH/);
425 });