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

test/a07-native-multipage-print-engine
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
cjs 494 lines 25 KB
Raw
1 'use strict';
2 // Browser-side functions are stringified and executed in the INSTALLED Tauri
3 // WebView2. Every write is synthetic and isolated to a disposable CI VM.
4 const assert = require('node:assert/strict');
5
6 async function activateAccounting() {
7 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
8 const check = (value, message) => { if (!value) throw Error(message); };
9 check(!document.getElementById('finoraAuthOverlay'), 'admin login must finish');
10 await FINORA.Router.go('accounting');
11 await wait(220);
12 const view = window.AccountingView;
13 check(view && document.getElementById('pageContent')?.textContent.includes('حسابداری دوبل'),
14 'actual accounting route missing');
15 await view.switchTab('periods');
16 if (!view.periods.length) {
17 view.openPeriodModal();
18 check(document.getElementById('acPeriodName'), 'fiscal period form absent');
19 document.getElementById('acPeriodName').value = 'دوره تست ویندوز ۱۴۰۵';
20 document.getElementById('acPeriodStart').value = '1405/01/01';
21 document.getElementById('acPeriodEnd').value = '1405/12/29';
22 await view.savePeriod();
23 }
24 check(view.periods.length > 0, 'period did not persist');
25 await view.switchTab('accounts');
26 if (!view.accounts.some(account => account.code === '402')) {
27 view.seedChart();
28 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
29 check(confirm, 'chart seed approval missing');
30 confirm.click();
31 for (let i = 0; i < 35 && !view.accounts.some(a => a.code === '402'); i++) await wait(150);
32 }
33 check(view.accounts.some(account => account.code === '402'), 'default chart missing account 402');
34 await view.switchTab('integration');
35 if (!document.getElementById('accountingWorkbench')?.textContent.includes('یکپارچه فعال است')) {
36 view.activateRetail();
37 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
38 check(confirm, 'activation approval missing');
39 confirm.click();
40 for (let i = 0; i < 35 && !document.getElementById('accountingWorkbench')?.textContent.includes('یکپارچه فعال است'); i++) await wait(150);
41 }
42 check(document.getElementById('accountingWorkbench')?.textContent.includes('یکپارچه فعال است'),
43 'finance and retail integration not active');
44 view.openWarehouse();
45 check(document.getElementById('acWhName'), 'warehouse form missing');
46 document.getElementById('acWhName').value = 'انبار ماشین مجازی';
47 await view.saveWarehouse();
48 check((await FINORA.Storage.getAll('warehouses')).some(w => w.name === 'انبار ماشین مجازی'),
49 'warehouse did not persist');
50 return { fiscalPeriods: view.periods.length, accountCount: view.accounts.length,
51 integration: 'enabled', warehouse: 'created' };
52 }
53
54 async function purchaseInvoice() {
55 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
56 const check = (value, message) => { if (!value) throw Error(message); };
57 const c = await window.ContactController.create({ name: 'مشتری آزمایشی ویندوز', role: 'both' });
58 const p = await window.ProductController.createProduct({
59 name: 'کالای تست ویندوز', code: 'VM-E2E-100',
60 trackInventory: true, buyPrice: 100, sellPrice: 200
61 });
62 await FINORA.Router.go('invoices');
63 await wait(300);
64 await window.InvoiceFormView.open();
65 await wait(180);
66 check(document.getElementById('invWarehouse'), 'invoice warehouse selector missing');
67 document.getElementById('invKind').value = 'purchase';
68 await window.InvoiceFormView._onKindChange();
69 document.getElementById('invDate').value = '1405/07/18';
70 const contact = document.getElementById('invContactSearch');
71 contact.value = c.name;
72 window.InvoiceFormView._showContactOptions(true);
73 const item = document.querySelector('.contact-option[data-id="' + c.id + '"]');
74 check(item, 'contact autocomplete could not select synthetic contact');
75 item.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
76 const search = document.querySelector('.row-product-search');
77 check(search, 'product autocomplete absent');
78 search.value = p.code;
79 window.InvoiceFormView._showProductOptions(0, true);
80 const chosen = document.querySelector('.product-option[data-id="' + p.id + '"]');
81 check(chosen, 'product autocomplete selection failed');
82 chosen.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
83 document.querySelector('.row-qty').value = '10';
84 window.InvoiceFormView._onFieldChange(0, 'qty', '10');
85 document.querySelector('.row-price').value = '100';
86 window.InvoiceFormView._onFieldChange(0, 'price', '100');
87 await window.InvoiceFormView._save(false);
88 await wait(160);
89 const invoice = (await FINORA.Storage.getAll('invoices'))
90 .find(x => x.contactId === c.id && x.kind === 'purchase');
91 check(invoice?.financePosted, 'purchase financial posting failed');
92 check((await FINORA.Storage.getAll('journal_entries'))
93 .some(j => j.sourceId === invoice.id && j.status === 'posted'), 'purchase ledger source missing');
94 check((await FINORA.Storage.getAll('stock_movements'))
95 .some(m => m.refId === invoice.id && m.type === 'in'), 'purchase inventory receipt missing');
96 check(!document.querySelector('.modal-backdrop'), 'purchase invoice modal stayed open');
97 return { purchaseAmount: invoice.grandTotal, purchasePosted: true, stockReceived: true };
98 }
99
100 async function saleInvoice() {
101 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
102 const check = (value, message) => { if (!value) throw Error(message); };
103 await FINORA.Router.go('treasury');
104 await wait(200);
105 if (!(await FINORA.Storage.getAll('treasury')).some(t => t.recordType === 'account')) {
106 await window.TreasuryView.openAccountModal();
107 document.getElementById('accName').value = 'صندوق ویندوز';
108 document.getElementById('accInitialBalance').value = '0';
109 await window.TreasuryView.saveAccount(null);
110 }
111 const accounts = (await FINORA.Storage.getAll('treasury')).filter(t => t.recordType === 'account');
112 check(accounts.some(a => a.ledgerAccountId), 'treasury subledger not mapped');
113 const cash = accounts.find(a => a.ledgerAccountId);
114 const contact = (await FINORA.Storage.getAll('contacts'))
115 .find(x => x.name === 'مشتری آزمایشی ویندوز');
116 const product = (await FINORA.Storage.getAll('products'))
117 .find(x => x.code === 'VM-E2E-100');
118 check(contact && product, 'purchase fixtures missing');
119 await FINORA.Router.go('invoices'); await wait(230);
120 await window.InvoiceFormView.open(); await wait(170);
121 document.getElementById('invKind').value = 'sale';
122 await window.InvoiceFormView._onKindChange();
123 document.getElementById('invDate').value = '1405/07/18';
124 const personSearch = document.getElementById('invContactSearch');
125 personSearch.value = contact.name;
126 window.InvoiceFormView._showContactOptions(true);
127 const personOption = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
128 check(personOption, 'sale customer picker failed');
129 personOption.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
130 const prodSearch = document.querySelector('.row-product-search');
131 prodSearch.value = product.code;
132 window.InvoiceFormView._showProductOptions(0, true);
133 const prodOption = document.querySelector('.product-option[data-id="' + product.id + '"]');
134 check(prodOption, 'sale product picker failed');
135 prodOption.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
136 document.querySelector('.row-qty').value = '3';
137 window.InvoiceFormView._onFieldChange(0, 'qty', '3');
138 document.querySelector('.row-price').value = '200';
139 window.InvoiceFormView._onFieldChange(0, 'price', '200');
140 document.getElementById('invPayment').value = 'partial';
141 window.InvoiceFormView._onPaymentChange();
142 document.getElementById('invPaidAmount').value = '200';
143 window.InvoiceFormView._recalc();
144 await window.InvoiceFormView._save(false); await wait(160);
145 const sale = (await FINORA.Storage.getAll('invoices'))
146 .find(i => i.kind === 'sale' && i.contactId === contact.id);
147 check(sale?.financePosted, 'sale was not financially posted');
148 check(sale.paidAmount === 200 && sale.remaining === 400,
149 'sale partial settlement incorrect: ' + JSON.stringify({ paid: sale.paidAmount, remaining: sale.remaining }));
150 const lines = await FINORA.Storage.getAll('journal_lines');
151 check(lines.some(l => l.accountId === cash.ledgerAccountId && l.debit === 200),
152 'partial settlement cash journal missing');
153 check((await FINORA.Storage.getAll('stock_movements'))
154 .some(m => m.refId === sale.id && m.type === 'out'), 'stock issue not posted');
155 return { salePaid: 200, saleRemaining: 400, salePosted: true, cashLedger: true };
156 }
157
158 async function nativeSaleReturnGuardrails() {
159 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
160 const check = (ok, message) => { if (!ok) throw Error(message); };
161 const S = FINORA.Storage;
162 const sale = (await S.getAll('invoices'))
163 .find(i => i.kind === 'sale' && i.financePosted && i.grandTotal === 600);
164 const contact = sale && await S.get('contacts', sale.contactId);
165 const product = (await S.getAll('products')).find(p => p.code === 'VM-E2E-100');
166 check(sale && contact && product, 'Posted original sale fixture is required');
167 const originalAmount = sale.grandTotal;
168 const originalPaid = sale.paidAmount;
169 const buildReturn = async (qty, price) => {
170 await FINORA.Router.go('invoices');
171 await wait(220);
172 await window.InvoiceFormView.open();
173 await wait(160);
174 const kind = document.getElementById('invKind');
175 check(kind, 'Native return invoice form missing');
176 kind.value = 'sale_return';
177 await window.InvoiceFormView._onKindChange();
178 const reference = document.getElementById('invOriginalInvoice');
179 check([...reference.options].some(x => x.value === sale.id),
180 'Posted sale does not appear as the reference invoice');
181 reference.value = sale.id;
182 document.getElementById('invDate').value = '1405/07/18';
183 const contactSearch = document.getElementById('invContactSearch');
184 contactSearch.value = contact.name;
185 window.InvoiceFormView._showContactOptions(true);
186 const contactItem = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
187 check(contactItem, 'Cannot select original customer in return form');
188 contactItem.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
189 const productSearch = document.querySelector('.row-product-search');
190 check(productSearch, 'Return product search field missing');
191 productSearch.value = product.code;
192 window.InvoiceFormView._showProductOptions(0, true);
193 const selected = document.querySelector('.product-option[data-id="' + product.id + '"]');
194 check(selected, 'Original sold product not selectable');
195 selected.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
196 document.querySelector('.row-qty').value = String(qty);
197 window.InvoiceFormView._onFieldChange(0, 'qty', String(qty));
198 document.querySelector('.row-price').value = String(price);
199 window.InvoiceFormView._onFieldChange(0, 'price', String(price));
200 document.getElementById('invPayment').value = 'credit';
201 window.InvoiceFormView._onPaymentChange();
202 await window.InvoiceFormView._save(false);
203 await wait(170);
204 };
205
206 await buildReturn(1, 200);
207 check(!document.querySelector('.toast-error'), 'Valid return showed an unexpected error');
208 const returns = (await S.getAll('invoices')).filter(x =>
209 x.kind === 'sale_return' && x.originalInvoiceId === sale.id);
210 check(returns.length === 1 && returns[0].financePosted &&
211 returns[0].grandTotal === 200 && returns[0].paidAmount === 0,
212 'Native return did not post a separate unpaid credit document');
213 const returned = returns[0];
214 const journal = await S.get('journal_entries', returned.journalId);
215 check(journal?.status === 'posted' && journal.sourceId === returned.id,
216 'Native sales return lacks its own posted ledger journal');
217 const lines = (await S.getAll('journal_lines')).filter(x => x.journalId === journal.id);
218 check(lines.length >= 2 && lines.reduce((n, x) => n + x.debit, 0) > 0 &&
219 lines.reduce((n, x) => n + x.debit, 0) ===
220 lines.reduce((n, x) => n + x.credit, 0),
221 'Return journal has invalid debit/credit balance');
222 check((await S.getAll('stock_movements'))
223 .some(x => x.refId === returned.id && x.type === 'in' && x.productId === product.id),
224 'Native sales return did not receive returned inventory');
225 check((await S.getAll('document_corrections')).some(x =>
226 x.sourceId === sale.id && x.resultId === returned.id),
227 'Return correction did not link to its immutable original');
228 check(!(await S.getAll('treasury')).some(x => x.invoiceId === returned.id &&
229 x.recordType === 'transaction'),
230 'Native return illegally generated an automatic refund');
231 const unchanged = await S.get('invoices', sale.id);
232 check(unchanged.grandTotal === originalAmount && unchanged.paidAmount === originalPaid &&
233 unchanged.financePosted, 'Posted source sale mutated during return');
234 const beforeInvalid = {
235 returns: (await S.getAll('invoices')).filter(x => x.kind === 'sale_return' &&
236 x.originalInvoiceId === sale.id).length,
237 stock: (await S.getAll('stock_movements')).length,
238 audits: (await S.getAll('audit_events')).length
239 };
240
241 // Quantity 3 would exceed the 2 units remaining from the original sale,
242 // while its 300 rial value is still below the remaining financial cap.
243 await buildReturn(3, 100);
244 let error = [...document.querySelectorAll('.toast-error')].find(x =>
245 x.textContent.includes('تعداد مرجوعی'));
246 check(error, 'Over-return quantity did not produce its expected UI rejection');
247 check((await S.getAll('invoices')).filter(x => x.kind === 'sale_return' &&
248 x.originalInvoiceId === sale.id).length === beforeInvalid.returns,
249 'Over-return created an extra financial invoice');
250 check((await S.getAll('stock_movements')).length === beforeInvalid.stock &&
251 (await S.getAll('audit_events')).length === beforeInvalid.audits,
252 'Rejected over-return left stock or audit side effects');
253 error.querySelector('.toast-close')?.click();
254 FINORA.Modal.close();
255 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
256 'Return guardrail left an error toast or modal after expected rejection');
257 return {
258 separatePostedReturn: true,
259 balancedLedgerAndReturnedStock: true,
260 postedOriginalImmutable: true,
261 noAutomaticCashRefund: true,
262 overReturnRejectedWithoutWrites: true
263 };
264 }
265
266 async function nativeBackupRestore() {
267 const check = (value, message) => { if (!value) throw Error(message); };
268 const S = FINORA.Storage;
269 const company = (await S.getAll('companies'))[0];
270 const temporary = await S.put('contacts', {
271 id: 'native-vm-backup-roundtrip', companyId: company.id, name: 'فقط آزمون بازگردانی'
272 });
273 const snapshot = await S.exportAll();
274 check(snapshot.version === 7 && snapshot.app === 'Factor-easyPro',
275 'invalid native backup envelope');
276 check(snapshot.data.contacts.some(x => x.id === temporary.id),
277 'native backup omitted test contact');
278 check(snapshot.data.users.every(u => !('pwHash' in u) && !('pwSalt' in u)),
279 'native backup leaked user password derivation metadata');
280 await S.delete('contacts', temporary.id);
281 check(!(await S.get('contacts', temporary.id)), 'test contact was not deleted');
282 await S.importAll({
283 app: snapshot.app, version: snapshot.version,
284 data: { contacts: snapshot.data.contacts.filter(c => c.id === temporary.id) }
285 });
286 check((await S.get('contacts', temporary.id))?.name === 'فقط آزمون بازگردانی',
287 'native backup restore did not recover contact');
288
289 const sale = (await S.getAll('invoices')).find(i => i.kind === 'sale' && i.financePosted);
290 check(sale, 'posted sale missing for restore immutability');
291 let denied = false;
292 try {
293 await S.importAll({
294 app: snapshot.app, version: snapshot.version,
295 data: {
296 contacts: [{id:'should-rollback-native',companyId:company.id,name:'Reject'}],
297 invoices: [{...sale,grandTotal:sale.grandTotal+1}]
298 }
299 });
300 } catch (_) { denied = true; }
301 check(denied, 'tampered posted sale backup must fail');
302 check(!(await S.get('contacts','should-rollback-native')),
303 'rejected full backup wrote a contact anyway');
304 check((await S.get('invoices',sale.id)).grandTotal===sale.grandTotal,
305 'tampered posted sale modified the actual financial document');
306 return { backupSchema: snapshot.version, credentialsExcluded: true,
307 contactRoundtrip: true, tamperedInvoiceRejectedAtomically: true };
308 }
309
310 async function invoicePrintLayout() {
311 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
312 const check = (value, message) => { if (!value) throw Error(message); };
313 const sale = (await FINORA.Storage.getAll('invoices'))
314 .find(x => x.kind === 'sale' && x.financePosted);
315 check(sale, 'posted invoice for print preview missing');
316 await FINORA.Router.go('invoices');
317 await wait(200);
318 await window.InvoicesView.printInvoice(sale.id);
319 await wait(320);
320 const dialog = document.querySelector('.modal-backdrop');
321 check(dialog, 'native print settings dialog did not open');
322 const labels = dialog.textContent || '';
323 check(labels.includes('قالب چاپ') && labels.includes('A4'),
324 'RTL print template or paper settings missing');
325 check(document.documentElement.dir === 'rtl',
326 'document is not marked RTL');
327 FINORA.Modal.close();
328 return { rtl: true, printSettings: true, templates: true,
329 physicalPrinterTest: 'not-covered' };
330 }
331
332 async function fiscalCloseGuardrails() {
333 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
334 const check = (ok, message) => { if (!ok) throw Error(message); };
335 const store = FINORA.Storage;
336 const company = await FINORA.Company.current();
337 check(company?.id && FINORA.Auth.isAdmin(), 'Fiscal close test must use a synthetic admin');
338 await FINORA.Router.go('accounting');
339 await wait(180);
340 const view = window.AccountingView;
341 check(view, 'Native accounting view was not mounted');
342 await view.switchTab('periods');
343 const testName = 'A05 VM-only guarded closing period';
344 view.openPeriodModal();
345 check(document.getElementById('acPeriodName'), 'Fiscal period creation form missing');
346 document.getElementById('acPeriodName').value = testName;
347 document.getElementById('acPeriodStart').value = '1404/01/01';
348 document.getElementById('acPeriodEnd').value = '1404/12/29';
349 await view.savePeriod();
350 check(!document.querySelector('.toast-error'), 'Creating isolated fiscal period failed');
351 const period = (await store.getAll('fiscal_periods'))
352 .find(x => x.companyId === company.id && x.name === testName);
353 check(period && period.closed === false, 'Synthetic fiscal period did not persist as open');
354 const warehouses = (await store.getAll('warehouses')).filter(x => x.companyId === company.id);
355 check(warehouses.length, 'Warehouse prerequisite missing');
356 const stocktakeId = 'vm-a05-draft-stocktake';
357 await store.put('stocktakes', {
358 id: stocktakeId, companyId: company.id,
359 warehouseId: warehouses[0].id, status: 'draft'
360 });
361 const auditCount = (await store.getAll('audit_events'))
362 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length;
363 const confirmClose = () => {
364 view.closePeriod(period.id);
365 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
366 check(confirm, 'Real fiscal closure approval dialog missing');
367 confirm.click();
368 };
369 confirmClose();
370 let message = null;
371 for (let i = 0; i < 60; i++) {
372 message = [...document.querySelectorAll('.toast-error')]
373 .find(x => x.textContent.includes('انبارگردانی باز'));
374 if (message) break;
375 await wait(100);
376 }
377 check(message, 'Closing with an open stocktake was not rejected visibly');
378 check((await store.get('fiscal_periods', period.id))?.closed === false,
379 'Open stocktake allowed fiscal closure');
380 check((await store.getAll('audit_events'))
381 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length === auditCount,
382 'Rejected fiscal closing created an audit receipt');
383 message.querySelector('.toast-close')?.click();
384 check(!document.querySelector('.toast-error'), 'Expected fiscal rejection toast remained');
385 await store.delete('stocktakes', stocktakeId);
386 confirmClose();
387 let closed = null;
388 for (let i = 0; i < 70; i++) {
389 closed = await store.get('fiscal_periods', period.id);
390 if (closed?.closed) break;
391 await wait(100);
392 }
393 check(closed?.closed === true && closed.status === 'closed',
394 'Approved fiscal close was not committed');
395 const closureAudits = (await store.getAll('audit_events'))
396 .filter(x => x.companyId === company.id &&
397 x.eventType === 'period_closed' && x.sourceId === period.id);
398 check(closureAudits.length === 1 &&
399 closureAudits[0].actorId === FINORA.Auth.current().id,
400 'Successful fiscal closure did not produce exactly one actor-scoped audit');
401 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
402 'Fiscal guardrail test left an unexpected UI error or modal');
403 return {
404 openStocktakeBlocked: true,
405 failedCloseRolledBack: true,
406 successfulCloseCommitted: true,
407 singleAuditReceipt: true
408 };
409 }
410
411 async function openingDryRunWithExistingActivity() {
412 const check = (ok, message) => { if (!ok) throw Error(message); };
413 const store = FINORA.Storage;
414 const company = await FINORA.Company.current();
415 check(company?.id && FINORA.Auth.isAdmin(),
416 'Native A02 opening dry-run requires a synthetic administrator');
417 await FINORA.Router.go('accounting');
418 const view = window.AccountingView;
419 check(view, 'AccountingView missing in actual installed app');
420 await view.switchTab('opening');
421 const input = document.getElementById('openingFileInput');
422 const reportHost = document.getElementById('openingPreviewReport');
423 check(input && reportHost, 'Opening balance JSON dry-run form is missing');
424 const periods = (await store.getAll('fiscal_periods'))
425 .filter(x => x.companyId === company.id);
426 const period = periods.find(x => !x.closed);
427 check(period, 'An active period is required for A02 blocked historical migration test');
428 const priorJournals = (await store.getAll('journal_entries'))
429 .filter(x => x.companyId === company.id && x.status === 'posted');
430 check(priorJournals.length > 0,
431 'Financial activity prerequisite missing: opening must be blocked after posting');
432 const before = {
433 entries: (await store.getAll('journal_entries')).length,
434 lines: (await store.getAll('journal_lines')).length,
435 events: (await store.getAll('audit_events')).length,
436 settings: (await store.getAll('settings')).length
437 };
438 const fixture = {
439 periodId: period.id, openingDate: period.startDate,
440 lines: [], contacts: [], stock: [], cash: []
441 };
442 const file = new File([JSON.stringify(fixture)], 'vm-only-a02-opening.json',
443 { type: 'application/json' });
444 Object.defineProperty(input, 'files', { configurable: true, value: [file] });
445 view.resetOpeningPreview();
446 await view.previewOpeningFile();
447 const review = view._openingReview;
448 check(review && review.readiness === 'blocked' && review.writePerformed === false,
449 'Native opening dry-run failed to block incompatible historical data');
450 check(review.issues.includes('EXISTING_POSTED_JOURNALS') &&
451 review.issues.includes('MISSING_OPENING_JOURNAL_LINES'),
452 'Native blocked opening preview omitted journal issues');
453 check(reportHost.textContent.includes('ثبت مسدود') &&
454 reportHost.querySelector('button[disabled]'),
455 'Native opening UI offered an actionable posting button despite issues');
456 const after = {
457 entries: (await store.getAll('journal_entries')).length,
458 lines: (await store.getAll('journal_lines')).length,
459 events: (await store.getAll('audit_events')).length,
460 settings: (await store.getAll('settings')).length
461 };
462 check(JSON.stringify(before) === JSON.stringify(after),
463 'Opening preview wrote to ledger, audit or settings');
464 check(!document.querySelector('.toast-error'),
465 'Blocked A02 dry-run unexpectedly threw rather than reporting issues');
466 await view.switchTab('journals');
467 return {
468 priorActivityBlocked: true,
469 discrepancyCodesVisible: true,
470 commitActionDisabled: true,
471 zeroWrites: true
472 };
473 }
474
475 module.exports = async function nativeFunctionalMatrix(cdp) {
476 const phases = [
477 ['activate-accounting-and-inventory', activateAccounting],
478 ['purchase-and-post-ledger', purchaseInvoice],
479 ['partial-sale-and-inventory', saleInvoice],
480 ['sale-return-immutable-stock-and-ledger', nativeSaleReturnGuardrails],
481 ['backup-and-atomic-rejection', nativeBackupRestore],
482 ['rtl-invoice-print-settings', invoicePrintLayout],
483 ['fiscal-close-atomic-guardrails', fiscalCloseGuardrails],
484 ['opening-dry-run-rejects-existing-postings', openingDryRunWithExistingActivity]
485 ];
486 const report = {};
487 for (const [name, fn] of phases) {
488 const value = await cdp.evaluate('(' + fn.toString() + ')()');
489 assert.ok(value && typeof value === 'object', 'invalid native E2E result from ' + name);
490 report[name] = value;
491 console.log('NATIVE E2E PASSED: ' + name + ': ' + JSON.stringify(value));
492 }
493 return report;
494 };