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

fix/p0-verified-financial-percent-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
cjs 1,180 lines 62.2 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 nativePositiveOpeningLedger() {
55 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
56 const check = (value, message) => { if (!value) throw Error(message); };
57 const store = FINORA.Storage;
58 const company = await FINORA.Company.current();
59 check(company?.id && FINORA.Auth.isAdmin(), 'Native A02 posting needs synthetic administrator');
60 const period = (await store.getAll('fiscal_periods'))
61 .find(x => x.companyId === company.id && x.closed === false);
62 const accounts = (await store.getAll('account_chart'))
63 .filter(x => x.companyId === company.id && x.postable !== false);
64 const receivable = accounts.find(x => x.code === '102');
65 const equity = accounts.find(x => x.code === '301');
66 check(period && receivable && equity, 'Synthetic opening prerequisites missing');
67 const person = await window.ContactController.create({
68 name: 'شخص افتتاحیه ساختگی ویندوز', role: 'customer'
69 });
70 const candidate = {
71 periodId: period.id, openingDate: period.startDate,
72 lines: [
73 { accountId: receivable.id, role: 'receivable', debit: 300, credit: 0 },
74 { accountId: equity.id, role: 'equity', debit: 0, credit: 300 }
75 ],
76 contacts: [{ contactId: person.id, receivable: 300, payable: 0 }],
77 stock: [], cash: []
78 };
79 await FINORA.Router.go('accounting');
80 await wait(160);
81 const view = window.AccountingView;
82 await view.switchTab('opening');
83 const attach = () => {
84 const input = document.getElementById('openingFileInput');
85 check(input, 'A02 native JSON picker missing');
86 const file = new File([JSON.stringify(candidate)], 'vm-a02-opening.json',
87 { type: 'application/json' });
88 Object.defineProperty(input, 'files', { configurable: true, value: [file] });
89 };
90 attach();
91 await view.previewOpeningFile();
92 check(view._openingReview?.readiness === 'ready-for-review' &&
93 view._openingReview?.writePerformed === false &&
94 view._openingReview?.issues.length === 0,
95 'Balanced synthetic opening was not ready without writes');
96 const priorPosted = (await store.getAll('journal_entries'))
97 .filter(x => x.companyId === company.id && x.sourceType === 'opening_balance');
98 check(priorPosted.length === 0, 'Preview unexpectedly posted an opening journal');
99 view.confirmOpeningPosting();
100 const confirmation = document.querySelector('.modal-footer [data-action="confirm"]');
101 check(confirmation, 'Opening posting explicit approval was not displayed');
102 confirmation.click();
103 let opening = null;
104 for (let i = 0; i < 80; i++) {
105 opening = (await store.getAll('journal_entries')).find(x =>
106 x.companyId === company.id && x.sourceType === 'opening_balance' &&
107 x.sourceId === period.id && x.status === 'posted');
108 if (opening) break;
109 await wait(100);
110 }
111 check(opening && opening.debit === 300 && opening.credit === 300,
112 'Confirmed synthetic opening was not posted as balanced ledger');
113 const lines = (await store.getAll('journal_lines')).filter(x => x.journalId === opening.id);
114 check(lines.length === 2 && lines.reduce((n, x) => n + x.debit, 0) === 300 &&
115 lines.reduce((n, x) => n + x.credit, 0) === 300,
116 'Opening journal lines do not match the dry-run');
117 const receipt = (await store.getAll('audit_events')).filter(x =>
118 x.companyId === company.id && x.eventType === 'opening_posted' && x.sourceId === opening.id);
119 check(receipt.length === 1 && receipt[0].actorId === FINORA.Auth.current().id,
120 'Opening journal missing unique actor-linked audit receipt');
121 await view.switchTab('opening');
122 attach();
123 await view.previewOpeningFile();
124 check(view._openingReview?.readiness === 'blocked' &&
125 view._openingReview?.issues.includes('EXISTING_POSTED_JOURNALS') &&
126 document.querySelector('#openingPreviewReport button[disabled]'),
127 'A02 second posting attempt not disabled in native UI');
128 check((await store.getAll('journal_entries')).filter(x =>
129 x.companyId === company.id && x.sourceType === 'opening_balance').length === 1,
130 'Repeated opening preview created another posted journal');
131 await view.switchTab('journals');
132 check(!document.querySelector('.toast-error'), 'Native opening workflow displayed unexpected error');
133 return { dryRunFirst: true, postedBalancedOpening: true,
134 actorAuditedOnce: true, repeatPostingBlocked: true };
135 }
136
137 async function purchaseInvoice() {
138 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
139 const check = (value, message) => { if (!value) throw Error(message); };
140 const c = await window.ContactController.create({ name: 'مشتری آزمایشی ویندوز', role: 'both' });
141 const p = await window.ProductController.createProduct({
142 name: 'کالای تست ویندوز', code: 'VM-E2E-100',
143 trackInventory: true, buyPrice: 100, sellPrice: 200
144 });
145 await FINORA.Router.go('invoices');
146 await wait(300);
147 await window.InvoiceFormView.open();
148 await wait(180);
149 check(document.getElementById('invWarehouse'), 'invoice warehouse selector missing');
150 document.getElementById('invKind').value = 'purchase';
151 await window.InvoiceFormView._onKindChange();
152 document.getElementById('invDate').value = '1405/07/18';
153 const contact = document.getElementById('invContactSearch');
154 contact.value = c.name;
155 window.InvoiceFormView._showContactOptions(true);
156 const item = document.querySelector('.contact-option[data-id="' + c.id + '"]');
157 check(item, 'contact autocomplete could not select synthetic contact');
158 item.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
159 const search = document.querySelector('.row-product-search');
160 check(search, 'product autocomplete absent');
161 search.value = p.code;
162 window.InvoiceFormView._showProductOptions(0, true);
163 const chosen = document.querySelector('.product-option[data-id="' + p.id + '"]');
164 check(chosen, 'product autocomplete selection failed');
165 chosen.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
166 // Actual installed WebView2 input event, not merely a pure formatting unit test:
167 // a quantity of 2.5 must not be converted to 25, and grouping must keep dot.
168 const quantityField = document.querySelector('.row-qty');
169 check(quantityField?.dataset.decimals === '3',
170 'Native invoice quantity field lacks the three-decimal precision contract');
171 quantityField.value = '1234.5';
172 quantityField.dispatchEvent(new Event('input', { bubbles: true }));
173 check(quantityField.value === '1,234.5',
174 'Native formatter removed fractional dot or failed live grouping');
175 quantityField.value = '2.5';
176 quantityField.dispatchEvent(new Event('input', { bubbles: true }));
177 check(quantityField.value === '2.5',
178 'Native input silently changed 2.5 to an incorrect financial quantity');
179 // Malformed paste must never silently become a new financial quantity.
180 quantityField.value = '2x5';
181 quantityField.dispatchEvent(new Event('input', { bubbles: true }));
182 check(quantityField.value === '2x5', 'Native formatter silently rewrote an invalid invoice amount');
183 await window.InvoiceFormView._save(false);
184 check(!(await FINORA.Storage.getAll('invoices')).some(x => x.contactId === c.id && x.kind === 'purchase'),
185 'Malformed native invoice quantity committed financial data');
186 // Restore the original synthetic invoice fixture before financial posting.
187 document.querySelector('.row-qty').value = '10';
188 window.InvoiceFormView._onFieldChange(0, 'qty', '10');
189 document.querySelector('.row-price').value = '100';
190 window.InvoiceFormView._onFieldChange(0, 'price', '100');
191 await window.InvoiceFormView._save(false);
192 await wait(160);
193 const invoice = (await FINORA.Storage.getAll('invoices'))
194 .find(x => x.contactId === c.id && x.kind === 'purchase');
195 check(invoice?.financePosted, 'purchase financial posting failed');
196 check((await FINORA.Storage.getAll('journal_entries'))
197 .some(j => j.sourceId === invoice.id && j.status === 'posted'), 'purchase ledger source missing');
198 check((await FINORA.Storage.getAll('stock_movements'))
199 .some(m => m.refId === invoice.id && m.type === 'in'), 'purchase inventory receipt missing');
200 check(!document.querySelector('.modal-backdrop'), 'purchase invoice modal stayed open');
201 return { purchaseAmount: invoice.grandTotal, purchasePosted: true, stockReceived: true };
202 }
203
204 async function saleInvoice() {
205 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
206 const check = (value, message) => { if (!value) throw Error(message); };
207 await FINORA.Router.go('treasury');
208 await wait(200);
209 if (!(await FINORA.Storage.getAll('treasury')).some(t => t.recordType === 'account')) {
210 await window.TreasuryView.openAccountModal();
211 document.getElementById('accName').value = 'صندوق ویندوز';
212 document.getElementById('accInitialBalance').value = '0';
213 await window.TreasuryView.saveAccount(null);
214 }
215 const accounts = (await FINORA.Storage.getAll('treasury')).filter(t => t.recordType === 'account');
216 check(accounts.some(a => a.ledgerAccountId), 'treasury subledger not mapped');
217 const cash = accounts.find(a => a.ledgerAccountId);
218 const contact = (await FINORA.Storage.getAll('contacts'))
219 .find(x => x.name === 'مشتری آزمایشی ویندوز');
220 const product = (await FINORA.Storage.getAll('products'))
221 .find(x => x.code === 'VM-E2E-100');
222 check(contact && product, 'purchase fixtures missing');
223 await FINORA.Router.go('invoices'); await wait(230);
224 await window.InvoiceFormView.open(); await wait(170);
225 document.getElementById('invKind').value = 'sale';
226 await window.InvoiceFormView._onKindChange();
227 document.getElementById('invDate').value = '1405/07/18';
228 const personSearch = document.getElementById('invContactSearch');
229 personSearch.value = contact.name;
230 window.InvoiceFormView._showContactOptions(true);
231 const personOption = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
232 check(personOption, 'sale customer picker failed');
233 personOption.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
234 const prodSearch = document.querySelector('.row-product-search');
235 prodSearch.value = product.code;
236 window.InvoiceFormView._showProductOptions(0, true);
237 const prodOption = document.querySelector('.product-option[data-id="' + product.id + '"]');
238 check(prodOption, 'sale product picker failed');
239 prodOption.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
240 document.querySelector('.row-qty').value = '3';
241 window.InvoiceFormView._onFieldChange(0, 'qty', '3');
242 document.querySelector('.row-price').value = '200';
243 window.InvoiceFormView._onFieldChange(0, 'price', '200');
244 document.getElementById('invPayment').value = 'partial';
245 window.InvoiceFormView._onPaymentChange();
246 document.getElementById('invPaidAmount').value = '200';
247 window.InvoiceFormView._recalc();
248 await window.InvoiceFormView._save(false); await wait(160);
249 const sale = (await FINORA.Storage.getAll('invoices'))
250 .find(i => i.kind === 'sale' && i.contactId === contact.id);
251 check(sale?.financePosted, 'sale was not financially posted');
252 check(sale.paidAmount === 200 && sale.remaining === 400,
253 'sale partial settlement incorrect: ' + JSON.stringify({ paid: sale.paidAmount, remaining: sale.remaining }));
254 const lines = await FINORA.Storage.getAll('journal_lines');
255 check(lines.some(l => l.accountId === cash.ledgerAccountId && l.debit === 200),
256 'partial settlement cash journal missing');
257 check((await FINORA.Storage.getAll('stock_movements'))
258 .some(m => m.refId === sale.id && m.type === 'out'), 'stock issue not posted');
259 return { salePaid: 200, saleRemaining: 400, salePosted: true, cashLedger: true };
260 }
261
262 async function nativeSaleReturnGuardrails() {
263 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
264 const check = (ok, message) => { if (!ok) throw Error(message); };
265 const S = FINORA.Storage;
266 const sale = (await S.getAll('invoices'))
267 .find(i => i.kind === 'sale' && i.financePosted && i.grandTotal === 600);
268 const contact = sale && await S.get('contacts', sale.contactId);
269 const product = (await S.getAll('products')).find(p => p.code === 'VM-E2E-100');
270 check(sale && contact && product, 'Posted original sale fixture is required');
271 const originalAmount = sale.grandTotal;
272 const originalPaid = sale.paidAmount;
273 const buildReturn = async (qty, price) => {
274 await FINORA.Router.go('invoices');
275 await wait(220);
276 await window.InvoiceFormView.open();
277 await wait(160);
278 const kind = document.getElementById('invKind');
279 check(kind, 'Native return invoice form missing');
280 kind.value = 'sale_return';
281 await window.InvoiceFormView._onKindChange();
282 const reference = document.getElementById('invOriginalInvoice');
283 check([...reference.options].some(x => x.value === sale.id),
284 'Posted sale does not appear as the reference invoice');
285 reference.value = sale.id;
286 document.getElementById('invDate').value = '1405/07/18';
287 const contactSearch = document.getElementById('invContactSearch');
288 contactSearch.value = contact.name;
289 window.InvoiceFormView._showContactOptions(true);
290 const contactItem = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
291 check(contactItem, 'Cannot select original customer in return form');
292 contactItem.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
293 const productSearch = document.querySelector('.row-product-search');
294 check(productSearch, 'Return product search field missing');
295 productSearch.value = product.code;
296 window.InvoiceFormView._showProductOptions(0, true);
297 const selected = document.querySelector('.product-option[data-id="' + product.id + '"]');
298 check(selected, 'Original sold product not selectable');
299 selected.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
300 document.querySelector('.row-qty').value = String(qty);
301 window.InvoiceFormView._onFieldChange(0, 'qty', String(qty));
302 document.querySelector('.row-price').value = String(price);
303 window.InvoiceFormView._onFieldChange(0, 'price', String(price));
304 document.getElementById('invPayment').value = 'credit';
305 window.InvoiceFormView._onPaymentChange();
306 await window.InvoiceFormView._save(false);
307 await wait(170);
308 };
309
310 await buildReturn(1, 200);
311 check(!document.querySelector('.toast-error'), 'Valid return showed an unexpected error');
312 const returns = (await S.getAll('invoices')).filter(x =>
313 x.kind === 'sale_return' && x.originalInvoiceId === sale.id);
314 check(returns.length === 1 && returns[0].financePosted &&
315 returns[0].grandTotal === 200 && returns[0].paidAmount === 0,
316 'Native return did not post a separate unpaid credit document');
317 const returned = returns[0];
318 const journal = await S.get('journal_entries', returned.journalId);
319 check(journal?.status === 'posted' && journal.sourceId === returned.id,
320 'Native sales return lacks its own posted ledger journal');
321 const lines = (await S.getAll('journal_lines')).filter(x => x.journalId === journal.id);
322 check(lines.length >= 2 && lines.reduce((n, x) => n + x.debit, 0) > 0 &&
323 lines.reduce((n, x) => n + x.debit, 0) ===
324 lines.reduce((n, x) => n + x.credit, 0),
325 'Return journal has invalid debit/credit balance');
326 check((await S.getAll('stock_movements'))
327 .some(x => x.refId === returned.id && x.type === 'in' && x.productId === product.id),
328 'Native sales return did not receive returned inventory');
329 check((await S.getAll('document_corrections')).some(x =>
330 x.sourceId === sale.id && x.resultId === returned.id),
331 'Return correction did not link to its immutable original');
332 check(!(await S.getAll('treasury')).some(x => x.invoiceId === returned.id &&
333 x.recordType === 'transaction'),
334 'Native return illegally generated an automatic refund');
335 const unchanged = await S.get('invoices', sale.id);
336 check(unchanged.grandTotal === originalAmount && unchanged.paidAmount === originalPaid &&
337 unchanged.financePosted, 'Posted source sale mutated during return');
338 const beforeInvalid = {
339 returns: (await S.getAll('invoices')).filter(x => x.kind === 'sale_return' &&
340 x.originalInvoiceId === sale.id).length,
341 stock: (await S.getAll('stock_movements')).length,
342 audits: (await S.getAll('audit_events')).length
343 };
344
345 // Quantity 3 would exceed the 2 units remaining from the original sale,
346 // while its 300 rial value is still below the remaining financial cap.
347 await buildReturn(3, 100);
348 let error = [...document.querySelectorAll('.toast-error')].find(x =>
349 x.textContent.includes('تعداد مرجوعی'));
350 check(error, 'Over-return quantity did not produce its expected UI rejection');
351 check((await S.getAll('invoices')).filter(x => x.kind === 'sale_return' &&
352 x.originalInvoiceId === sale.id).length === beforeInvalid.returns,
353 'Over-return created an extra financial invoice');
354 check((await S.getAll('stock_movements')).length === beforeInvalid.stock &&
355 (await S.getAll('audit_events')).length === beforeInvalid.audits,
356 'Rejected over-return left stock or audit side effects');
357 error.querySelector('.toast-close')?.click();
358 FINORA.Modal.close();
359 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
360 'Return guardrail left an error toast or modal after expected rejection');
361 return {
362 separatePostedReturn: true,
363 balancedLedgerAndReturnedStock: true,
364 postedOriginalImmutable: true,
365 noAutomaticCashRefund: true,
366 overReturnRejectedWithoutWrites: true
367 };
368 }
369
370 async function nativePurchaseReturnGuardrails() {
371 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
372 const check = (ok,msg) => { if (!ok) throw Error(msg); };
373 const S = FINORA.Storage;
374 const original = (await S.getAll('invoices')).find(x =>
375 x.kind === 'purchase' && x.financePosted && x.grandTotal === 1000);
376 const contact = original && await S.get('contacts', original.contactId);
377 const product = (await S.getAll('products')).find(x => x.code === 'VM-E2E-100');
378 check(original && contact && product, 'A01 purchase-return source fixtures missing');
379 const originalJournal = original.journalId;
380 const makeReturn = async (qty, price) => {
381 await FINORA.Router.go('invoices');
382 await wait(200);
383 await window.InvoiceFormView.open();
384 await wait(140);
385 document.getElementById('invKind').value = 'purchase_return';
386 await window.InvoiceFormView._onKindChange();
387 const source = document.getElementById('invOriginalInvoice');
388 check([...source.options].some(x => x.value === original.id && !x.disabled),
389 'Posted purchase not an eligible source in return form');
390 source.value = original.id;
391 document.getElementById('invDate').value = '1405/07/18';
392 const search = document.getElementById('invContactSearch');
393 search.value = contact.name;
394 window.InvoiceFormView._showContactOptions(true);
395 const option = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
396 check(option, 'Original supplier cannot be selected');
397 option.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
398 const productSearch = document.querySelector('.row-product-search');
399 productSearch.value = product.code;
400 window.InvoiceFormView._showProductOptions(0, true);
401 const prod = document.querySelector('.product-option[data-id="' + product.id + '"]');
402 check(prod, 'Purchased product cannot be selected');
403 prod.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
404 document.querySelector('.row-qty').value = String(qty);
405 window.InvoiceFormView._onFieldChange(0, 'qty', String(qty));
406 document.querySelector('.row-price').value = String(price);
407 window.InvoiceFormView._onFieldChange(0, 'price', String(price));
408 document.getElementById('invPayment').value = 'credit';
409 window.InvoiceFormView._onPaymentChange();
410 await window.InvoiceFormView._save(false);
411 await wait(180);
412 };
413 await makeReturn(1, 100);
414 check(!document.querySelector('.toast-error'), 'Valid supplier return showed unexpected error');
415 const found = (await S.getAll('invoices')).filter(x =>
416 x.kind === 'purchase_return' && x.originalInvoiceId === original.id);
417 check(found.length === 1 && found[0].financePosted &&
418 found[0].paidAmount === 0 && found[0].grandTotal === 100,
419 'Purchase return was not correctly posted without automatic cash receipt');
420 const returned = found[0];
421 const ledger = await S.get('journal_entries', returned.journalId);
422 check(ledger?.status === 'posted' && ledger.sourceId === returned.id,
423 'Purchase return journal link missing');
424 const lines = (await S.getAll('journal_lines')).filter(x => x.journalId === ledger.id);
425 const debit = lines.reduce((n,x)=>n+x.debit,0);
426 const credit = lines.reduce((n,x)=>n+x.credit,0);
427 check(lines.length >= 2 && debit > 0 && debit === credit,
428 'Native purchase return failed ledger balancing');
429 check((await S.getAll('stock_movements')).some(x =>
430 x.refId === returned.id && x.type === 'out' && x.productId === product.id),
431 'Returned purchased inventory did not leave warehouse');
432 check((await S.getAll('document_corrections')).some(x =>
433 x.sourceId === original.id && x.resultId === returned.id),
434 'Supplier return must be a linked correction');
435 check((await S.get('invoices', original.id)).journalId === originalJournal,
436 'Supplier return illegally changed source purchase');
437 check(!(await S.getAll('treasury')).some(x =>
438 x.recordType === 'transaction' && x.invoiceId === returned.id),
439 'Supplier return created unauthorized treasury cash event');
440 const before = {
441 invoices:(await S.getAll('invoices')).length,
442 movements:(await S.getAll('stock_movements')).length,
443 audits:(await S.getAll('audit_events')).length
444 };
445 // 10 more units exceeds the 9 remaining, even though the proposed
446 // 500-rial credit is BELOW the remaining purchase monetary cap.
447 await makeReturn(10, 50);
448 const toast = [...document.querySelectorAll('.toast-error')].find(x =>
449 x.textContent.includes('تعداد مرجوعی'));
450 check(toast, 'Over-quantity supplier return did not fail visibly');
451 check((await S.getAll('invoices')).length === before.invoices &&
452 (await S.getAll('stock_movements')).length === before.movements &&
453 (await S.getAll('audit_events')).length === before.audits,
454 'Rejected supplier return wrote an invoice, stock or audit event');
455 toast.querySelector('.toast-close')?.click();
456 FINORA.Modal.close();
457 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
458 'A01 supplier return negative test left UI error or modal');
459 return { postedSupplierReturn:true, balancedLedger:true, stockIssued:true,
460 originalPurchaseImmutable:true, noAutomaticTreasury:true,
461 overReturnRejectedAtomically:true };
462 }
463
464 async function nativeHistoryClearFailClosed() {
465 const check = (value, message) => { if (!value) throw Error(message); };
466 const store = FINORA.Storage;
467 const company = await FINORA.Company.current();
468 check(company?.id && FINORA.Auth.isAdmin(),
469 'History protection must run in installed VM with synthetic administrator');
470 const preserved = {};
471 for (const name of ['audit_events', 'document_corrections']) {
472 const history = (await store.getAll(name))
473 .filter(row => row.companyId === company.id);
474 check(history.length > 0, 'Native immutable history prerequisite missing: ' + name);
475 preserved[name] = history.map(row => JSON.stringify(row)).sort();
476 const sentinel = 'vm-a03-aborted-clear-' + name;
477 let rejected = false;
478 try {
479 await store.transaction(['contacts', name], async tx => {
480 await tx.putRaw('contacts', {
481 id: sentinel, companyId: company.id,
482 name: 'VM ONLY must roll back before history clear'
483 });
484 await tx.clear(name);
485 });
486 } catch (error) {
487 rejected = String(error).includes('پاک‌سازی مستقیم');
488 }
489 check(rejected, 'Installed IndexedDB accepted a bulk history clear: ' + name);
490 check(!(await store.get('contacts', sentinel)),
491 'Rejected native history-clear transaction committed earlier writes');
492 const after = (await store.getAll(name))
493 .filter(row => row.companyId === company.id)
494 .map(row => JSON.stringify(row)).sort();
495 check(JSON.stringify(after) === JSON.stringify(preserved[name]),
496 'Failed clear mutated immutable history: ' + name);
497 }
498 check(!document.querySelector('.toast-error'),
499 'Native history protection left unrelated UI error');
500 return { immutableAuditClearRejected: true,
501 immutableCorrectionClearRejected: true,
502 bothTransactionsRolledBack: true,
503 historyUnchanged: true };
504 }
505
506 async function nativeInactiveBankSettlementGuard() {
507 const wait=ms=>new Promise(r=>setTimeout(r,ms));
508 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
509 const db=FINORA.Storage,company=await FINORA.Company.current();
510 check(company?.id&&FINORA.Auth.isAdmin(),'A05 native admin required');
511 const contact=(await db.getAll('contacts')).find(c=>c.companyId===company.id&&c.name==='مشتری آزمایشی ویندوز');
512 const active=(await db.getAll('treasury')).find(x=>x.companyId===company.id&&x.recordType==='account'&&x.ledgerAccountId&&x.isActive!==false);
513 check(contact&&active,'Treasury fixtures absent');
514 await FINORA.Router.go('treasury');await wait(180);
515 const tv=window.TreasuryView;
516 await tv.openAccountModal();
517 document.getElementById('accName').value='VM-only inactive bank A05';
518 document.getElementById('accInitialBalance').value='0';
519 await tv.saveAccount(null);
520 const secondary=(await db.getAll('treasury')).find(x=>
521 x.companyId===company.id&&x.recordType==='account'&&x.name==='VM-only inactive bank A05');
522 check(secondary?.ledgerAccountId,'Actual treasury account creation failed');
523 await db.put('treasury',{...secondary,isActive:false});
524 const counts=async()=>({
525 journals:(await db.getAll('journal_entries')).length,
526 payments:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length
527 });
528 const before=await counts();
529 tv.openTransferModal();
530 check(document.getElementById('txToAccount'),'Native transfer form not open');
531 document.getElementById('txDate').value='1405/07/18';
532 document.getElementById('txAmount').value='40';
533 document.getElementById('txFromAccount').value=active.id;
534 document.getElementById('txToAccount').value=secondary.id;
535 await tv._saveTransaction('transfer');
536 let toast=[...document.querySelectorAll('.toast-error')].find(x=>x.textContent.includes('غیرفعال'));
537 check(toast,'Inactive bank transfer did not display rejection');
538 check(JSON.stringify(await counts())===JSON.stringify(before),'Rejected transfer wrote journals or cash');
539 toast.querySelector('.toast-close')?.click();
540 FINORA.Modal.close();
541 check(!document.querySelector('.toast-error'),'Expected transfer toast not dismissed');
542
543 // With no active bank, the real cheque status UI must reject settlement
544 // without changing posted status or writing a cash receipt.
545 await db.put('treasury',{...active,isActive:false});
546 await FINORA.Router.go('cheques');await wait(200);
547 const cv=window.ChequesView;
548 await cv.openChequeModal();
549 check(document.getElementById('chqSayad'),'Native cheque form absent');
550 document.getElementById('chqDirection').value='inbound';
551 document.getElementById('chqContact').value=contact.id;
552 document.getElementById('chqSayad').value='1234567890123489';
553 document.getElementById('chqAmount').value='90';
554 document.getElementById('chqIssueDate').value='1405/07/18';
555 document.getElementById('chqDueDate').value='1405/07/18';
556 await cv.saveCheque(null);
557 const cheque=(await db.getAll('cheques')).find(x=>x.companyId===company.id&&x.sayadNumber==='1234567890123489');
558 check(cheque?.financePosted&&cheque.status==='pending','Native cheque posting failed');
559 const journalCount=(await db.getAll('journal_entries')).length;
560 await cv.changeStatus(cheque.id);
561 check(document.getElementById('newStatus'),'Cheque status form missing');
562 const dateInput=document.getElementById('chqEventDate');
563 check(dateInput,'Native posted cheque must request the financial event date');
564 dateInput.value='1405/07/20'; // intentionally different from the cheque due date
565 document.getElementById('newStatus').value='cleared';
566 cv._onChequeStatusSelection();
567 check(document.getElementById('chqClearingAccount'),
568 'Explicit bank selection was not presented in posted cheque UI');
569 await cv._applyStatusChange(cheque.id);
570 toast=[...document.querySelectorAll('.toast-warning')].find(x=>
571 x.textContent.includes('حساب بانک یا صندوق را انتخاب کنید'));
572 check(toast,'Clearing without selected active bank did not visibly reject');
573 check((await db.get('cheques',cheque.id)).status==='pending'&&
574 (await db.getAll('journal_entries')).length===journalCount&&
575 !(await db.getAll('treasury')).some(t=>t.refChequeId===cheque.id),
576 'Rejected cheque clearance modified ledger or treasury');
577 toast.querySelector('.toast-close')?.click();
578 FINORA.Modal.close();
579 await db.put('treasury',active);
580 await db.put('treasury',{...secondary,isActive:true});
581 await cv.changeStatus(cheque.id);
582 document.getElementById('newStatus').value='cleared';
583 document.getElementById('chqEventDate').value='1405/07/20';
584 cv._onChequeStatusSelection();
585 const selected=document.getElementById('chqClearingAccount');
586 check([...selected.options].some(x=>x.value===secondary.id),
587 'Actual secondary bank not selectable in clearing UI');
588 selected.value=secondary.id; // bank other than the default
589 await cv._applyStatusChange(cheque.id);
590 const approve=document.querySelector('.modal-backdrop:last-of-type [data-action="confirm"]');
591 check(approve&&approve.textContent.includes('تأیید و ثبت وصول'),
592 'Actual bank clearance missing explicit secondary confirmation');
593 check((await db.get('cheques',cheque.id)).status==='pending'&&
594 (await db.getAll('journal_entries')).length===journalCount,
595 'Cheque cleared before approval');
596 approve.click();
597 let cleared;
598 for(let i=0;i<60;i++){
599 cleared=await db.get('cheques',cheque.id);
600 if(cleared?.status==='cleared')break;
601 await wait(100);
602 }
603 const journal=await db.get('journal_entries',cleared.statusJournalId);
604 const settlement=(await db.getAll('treasury')).filter(t=>t.refChequeId===cheque.id);
605 const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal?.id);
606 check(cleared.status==='cleared'&&cleared.dueDate==='1405/07/18'&&
607 cleared.statusBusinessDate==='1405/07/20'&&cleared.clearingAccountId===secondary.id&&
608 cleared.clearingApprovedBy===FINORA.Auth.current().id&&
609 journal?.date==='1405/07/20'&&settlement.length===1&&
610 settlement[0].date==='1405/07/20'&&settlement[0].toAccountId===secondary.id&&
611 lines.some(x=>x.accountId===secondary.ledgerAccountId&&x.debit===90)&&
612 !lines.some(x=>x.accountId===active.ledgerAccountId&&x.debit===90),
613 'Native cheque clearance failed selected non-default bank accounting');
614 check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
615 'A05 native treasury scenario left error toast/modal');
616 return { inactiveTransferRejected:true, invalidTransferRolledBack:true,
617 disabledChequeClearingRejected:true, validChequeClearedExactlyOnce:true,
618 chequeEventDateDifferentFromDueDate:true,
619 explicitNondefaultClearingAccount:true,confirmationRequiredBeforeCash:true };
620 }
621
622 async function nativeChequeThirdPartyEndorsement() {
623 const wait=ms=>new Promise(r=>setTimeout(r,ms));
624 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
625 const db=FINORA.Storage,company=await FINORA.Company.current();
626 check(company?.id&&FINORA.Auth.isAdmin(),'A01 endorsement needs synthetic admin');
627 const drawer=(await db.getAll('contacts')).find(c=>
628 c.companyId===company.id&&c.name==='مشتری آزمایشی ویندوز');
629 check(drawer,'Endorsement drawer fixture missing');
630 const endorsee={id:'vm-a01-endorsee-contact',companyId:company.id,
631 name:'تأمین‌کننده واگذاری آزمایشی',ownerUserId:FINORA.Auth.current().id};
632 await db.put('contacts',endorsee);
633 await FINORA.Router.go('cheques');await wait(130);
634 const view=window.ChequesView;
635 await view.reload();
636 await view.openChequeModal();
637 check(document.getElementById('chqSayad'),'Real native cheque create form missing');
638 document.getElementById('chqDirection').value='inbound';
639 document.getElementById('chqContact').value=drawer.id;
640 document.getElementById('chqSayad').value='1234567890123490';
641 document.getElementById('chqAmount').value='75';
642 document.getElementById('chqIssueDate').value='1405/07/18';
643 document.getElementById('chqDueDate').value='1405/07/18';
644 await view.saveCheque(null);
645 const cheque=(await db.getAll('cheques')).find(c=>
646 c.companyId===company.id&&c.sayadNumber==='1234567890123490');
647 check(cheque?.financePosted&&cheque.status==='pending','Endorsement cheque posting failed');
648 await view.changeStatus(cheque.id);
649 const status=document.getElementById('newStatus');
650 const date=document.getElementById('chqEventDate');
651 const endorseeSelect=document.getElementById('chqEndorsee');
652 check(status&&date&&endorseeSelect,'Actual endorsement choice missing in native UI');
653 status.value='spent';date.value='1405/07/20';
654 view._onChequeStatusSelection();
655 check(document.getElementById('chqEndorseeGroup').style.display!=='none',
656 'Third-party contact selector was hidden');
657 const counts=async()=>({
658 journals:(await db.getAll('journal_entries')).length,
659 corrections:(await db.getAll('document_corrections')).length,
660 audits:(await db.getAll('audit_events')).length
661 });
662 const before=await counts();
663 await view._applyStatusChange(cheque.id);
664 check(!document.querySelector('.modal-footer [data-action="confirm"]'),
665 'Endorsement without selected third party opened approval');
666 check(JSON.stringify(await counts())===JSON.stringify(before)&&
667 (await db.get('cheques',cheque.id)).status==='pending',
668 'Missing endorsee wrote a financial event');
669 const warning=[...document.querySelectorAll('.toast-warning')].find(x=>
670 x.textContent.includes('دریافت‌کننده واگذاری'));
671 check(warning,'Missing endorsee was not visibly rejected');
672 warning.querySelector('.toast-close')?.click();
673 endorseeSelect.value=endorsee.id;
674 await view._applyStatusChange(cheque.id);
675 const confirm=document.querySelector('.modal-backdrop:last-of-type [data-action="confirm"]');
676 check(confirm&&confirm.textContent.includes('تأیید و ثبت واگذاری'),
677 'Native endorsement has no separate explicit approval');
678 check(JSON.stringify(await counts())===JSON.stringify(before)&&
679 (await db.get('cheques',cheque.id)).status==='pending',
680 'Endorsement posted before explicit confirmation');
681 confirm.click();
682 let endorsed;
683 for(let i=0;i<60;i++){
684 endorsed=await db.get('cheques',cheque.id);
685 if(endorsed.status==='spent')break;
686 await wait(100);
687 }
688 check(endorsed?.status==='spent'&&endorsed.endorseeContactId===endorsee.id&&
689 endorsed.endorsementApprovedBy===FINORA.Auth.current().id&&
690 endorsed.statusBusinessDate==='1405/07/20',
691 'Native endorsement did not retain selected third party and approval');
692 const journal=await db.get('journal_entries',endorsed.statusJournalId);
693 const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal?.id);
694 const payable=(await db.getAll('account_chart')).find(x=>
695 x.companyId===company.id&&x.code==='201');
696 const incoming=(await db.getAll('account_chart')).find(x=>
697 x.companyId===company.id&&x.code==='105');
698 check(journal?.date==='1405/07/20'&&lines.some(l=>
699 l.accountId===payable?.id&&l.contactId===endorsee.id&&l.debit===75)&&
700 lines.some(l=>l.accountId===incoming?.id&&l.contactId===drawer.id&&l.credit===75),
701 'Endorsement GL was not correctly split between endorsee and drawer');
702 const correction=(await db.getAll('document_corrections')).find(x=>
703 x.sourceType==='cheque'&&x.sourceId===cheque.id&&x.correctionType==='endorsement');
704 check(correction?.endorseeContactId===endorsee.id&&
705 correction?.correlationId===journal.id&&correction?.approvedBy===FINORA.Auth.current().id,
706 'Native endorsement lacks append-only trace and actor');
707 check(!(await db.getAll('treasury')).some(x=>x.refChequeId===cheque.id),
708 'Endorsement incorrectly created cash settlement');
709 check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
710 'Native endorsement left unexpected error or modal');
711 return {missingEndorseeRejected:true,confirmationRequiredBeforeWrite:true,
712 endorseeLedgerDimensionCorrect:true,drawerChequeAssetPreserved:true,
713 appendOnlyEndorsementCorrelated:true,noPhantomCash:true};
714 }
715
716 async function nativeTreasuryChequeReconciliation() {
717 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
718 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
719 const storage=FINORA.Storage,company=await FINORA.Company.current();
720 check(company?.id&&FINORA.Auth.isAdmin(),'A05 reconciliation requires synthetic admin');
721 await FINORA.Router.go('accounting');await wait(130);
722 const view=window.AccountingView;
723 await view.switchTab('reconciliation');
724 const original=await view.renderReconciliation();
725 check(original.includes('چک‌های مالی'),'Native reconciliation does not show cheque controls');
726 check(!original.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
727 !original.includes('CHEQUE_CLEARING_CASH_COUNT'),
728 'Real posted VM cheque failed reconciliation before fault injection');
729 // Corrupt only a synthetic fixture in the disposable native VM, never
730 // alter a customer accounting record. This probes read-only detection.
731 const id='vm-a05-invalid-cheque-reconciliation';
732 const broken={id,companyId:company.id,financePosted:true,
733 direction:'inbound',status:'cleared',amount:90,journalId:'not-there',
734 statusJournalId:'not-there-either'};
735 await storage.put('cheques',broken);
736 const before=(await storage.getAll('journal_entries')).length;
737 const checked=await view.renderReconciliation();
738 check(checked.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
739 checked.includes('CHEQUE_STATUS_JOURNAL_MISSING')&&
740 checked.includes('CHEQUE_CLEARING_CASH_COUNT'),
741 'Native installed reconciliation failed to report malformed cheque');
742 check((await storage.getAll('journal_entries')).length===before&&
743 (await storage.get('cheques',id))?.status==='cleared',
744 'Read-only reconciliation changed journal or cheque state');
745 await storage.delete('cheques',id);
746 const after=await view.renderReconciliation();
747 check(!after.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
748 !after.includes('CHEQUE_CLEARING_CASH_COUNT'),
749 'Reconciliation still reports synthetic cheque after fixture removal');
750 await view.switchTab('journals');
751 check(!document.querySelector('.toast-error'),'A05 reconciliation left toast');
752 return {livePostedChequeReviewed:true,chequeDiscrepanciesDetected:true,
753 reportingReadOnly:true,fixtureRemoved:true};
754 }
755
756 async function nativeReturnCashSettlementGuardrails() {
757 const wait=ms=>new Promise(r=>setTimeout(r,ms));
758 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
759 const db=FINORA.Storage,company=await FINORA.Company.current();
760 const sale=(await db.getAll('invoices')).find(x=>
761 x.companyId===company.id&&x.kind==='sale'&&x.grandTotal===600);
762 const returned=(await db.getAll('invoices')).find(x=>
763 x.companyId===company.id&&x.kind==='sale_return'&&x.originalInvoiceId===sale?.id);
764 check(sale?.paidAmount===200&&returned?.grandTotal===200,
765 'A01 net-refund native sale/return prerequisite absent');
766 await FINORA.Router.go('treasury');await wait(170);
767 const view=window.TreasuryView;
768 const before=()=>Promise.all(['journal_entries','treasury','settlements'].map(async name=>
769 (await db.getAll(name)).length));
770 const testReceipt=async(amount)=>{
771 await view.openReceiptModal();
772 const sel=document.getElementById('txInvoiceRef');
773 check(sel&&[...sel.options].some(x=>x.value===sale.id),
774 'Real treasury UI does not list the unpaid original sale');
775 sel.value=sale.id;view._onInvoiceSelection();
776 document.getElementById('txAmount').value=String(amount);
777 document.getElementById('txDate').value='1405/07/18';
778 await view._saveTransaction('receipt');
779 };
780 const start=await before();
781 await testReceipt(201);
782 let toast=[...document.querySelectorAll('.toast-error')].find(x=>x.textContent.includes('مانده خالص'));
783 check(toast,'Overcollection after posted return not visibly rejected');
784 check(JSON.stringify(await before())===JSON.stringify(start),
785 'Rejected overcollection wrote a ledger, treasury or settlement');
786 toast.querySelector('.toast-close')?.click();
787 FINORA.Modal.close();
788 await testReceipt(200);
789 check((await db.get('invoices',sale.id)).paidAmount===400,
790 'Allowed residual collection did not reach net post-return amount');
791 await view.openPaymentModal();
792 const sel=document.getElementById('txInvoiceRef');
793 check(sel&&[...sel.options].some(x=>x.value===returned.id),
794 'Real treasury UI cannot select the customer return');
795 sel.value=returned.id;view._onInvoiceSelection();
796 document.getElementById('txAmount').value='1';
797 document.getElementById('txDate').value='1405/07/18';
798 const preRefund=await before();
799 document.getElementById('txReturnReason').value='goods_return';
800 await view._saveTransaction('payment');
801 let approve=document.querySelector('.modal-footer [data-action="confirm"]');
802 check(approve,'Native refund must explicitly ask for confirmation');
803 approve.click();
804 for(let i=0;i<30;i++){
805 toast=[...document.querySelectorAll('.toast-error')].find(x=>
806 x.textContent.includes('بازپرداخت مجاز'));
807 if(toast)break;
808 await wait(100);
809 }
810 check(toast,'Cash refund with zero actual paid customer credit was not rejected');
811 check(JSON.stringify(await before())===JSON.stringify(preRefund),
812 'Rejected customer refund wrote a ledger, treasury or settlement');
813 toast.querySelector('.toast-close')?.click();FINORA.Modal.close();
814 check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
815 'Native A01 cash cap left an error toast/modal');
816
817 // Establish a real, paid customer credit in the installed WebView2 app:
818 // sale 600, cash received 400, total returns 400 -> refund cap 200.
819 // Post a second 200-rial return through the actual invoice UI.
820 const contact=await db.get('contacts',sale.contactId);
821 const product=(await db.getAll('products')).find(p=>p.code==='VM-E2E-100');
822 check(contact&&product,'Native positive refund requires customer and product');
823 await FINORA.Router.go('invoices');await wait(180);
824 await window.InvoiceFormView.open();await wait(160);
825 document.getElementById('invKind').value='sale_return';
826 await window.InvoiceFormView._onKindChange();
827 const original=document.getElementById('invOriginalInvoice');
828 check(original&&[...original.options].some(x=>x.value===sale.id),
829 'Native positive refund original invoice selector absent');
830 original.value=sale.id;
831 document.getElementById('invDate').value='1405/07/18';
832 const contactSearch=document.getElementById('invContactSearch');
833 contactSearch.value=contact.name;
834 window.InvoiceFormView._showContactOptions(true);
835 const contactItem=document.querySelector('.contact-option[data-id="'+contact.id+'"]');
836 check(contactItem,'Native positive refund contact missing');
837 contactItem.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
838 const productSearch=document.querySelector('.row-product-search');
839 productSearch.value=product.code;
840 window.InvoiceFormView._showProductOptions(0,true);
841 const productItem=document.querySelector('.product-option[data-id="'+product.id+'"]');
842 check(productItem,'Native positive refund product missing');
843 productItem.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
844 document.querySelector('.row-qty').value='1';
845 window.InvoiceFormView._onFieldChange(0,'qty','1');
846 document.querySelector('.row-price').value='200';
847 window.InvoiceFormView._onFieldChange(0,'price','200');
848 document.getElementById('invPayment').value='credit';
849 window.InvoiceFormView._onPaymentChange();
850 await window.InvoiceFormView._save(false);await wait(170);
851 check(!document.querySelector('.toast-error'),'Second synthetic return failed in native UI');
852 const second=(await db.getAll('invoices')).find(x=>
853 x.kind==='sale_return'&&x.originalInvoiceId===sale.id&&x.id!==returned.id);
854 check(second?.grandTotal===200&&second.paidAmount===0,
855 'Second posted customer credit document missing');
856 await FINORA.Router.go('treasury');await wait(170);
857 await view.openPaymentModal();
858 const select=document.getElementById('txInvoiceRef');
859 check(select&&[...select.options].some(x=>x.value===second.id),
860 'Native positive refund return not selectable in treasury UI');
861 select.value=second.id;view._onInvoiceSelection();
862 document.getElementById('txAmount').value='100';
863 document.getElementById('txDate').value='1405/07/18';
864 document.getElementById('txReturnReason').value='quality_issue';
865 const beforeApproval=await before();
866 await view._saveTransaction('payment');
867 approve=document.querySelector('.modal-footer [data-action="confirm"]');
868 check(approve,'Native accepted refund missing explicit confirmation dialog');
869 check(JSON.stringify(await before())===JSON.stringify(beforeApproval),
870 'Opening approval dialog must not post cash or journal');
871 approve.click();
872 let refund=null;
873 for(let i=0;i<40;i++){
874 refund=(await db.getAll('treasury')).find(x=>
875 x.recordType==='transaction'&&x.refInvoiceId===second.id&&x.type==='payment');
876 if(refund)break;
877 await wait(100);
878 }
879 check(!document.querySelector('.toast-error'),'Authorized native customer refund failed');
880 const correction=(await db.getAll('document_corrections')).find(x=>
881 x.correctionType==='settlement_refund'&&x.sourceId===second.id&&
882 x.resultId===refund?.id);
883 const audit=(await db.getAll('audit_events')).find(x=>
884 x.sourceId===refund?.journalId&&x.correlationId===correction?.correlationId);
885 check(refund?.amount===100&&correction?.amount===100&&
886 correction.reasonCode==='quality_issue'&&
887 correction.actionCode==='customer_credit_refund'&&
888 correction.approvedBy===FINORA.Auth.current()?.id&&
889 correction.approvalMethod==='explicit_confirmation'&&audit&&
890 (await db.get('invoices',second.id))?.paidAmount===100,
891 'Native refund correction, treasury, audit or invoice linkage is invalid');
892 check(!document.querySelector('.modal-backdrop'),
893 'Native refund left an unexpected payment dialog');
894 return {overcollectionRejectedWithoutWrites:true,netReceiptAccepted:true,
895 nonexistentRefundCreditRejected:true,realTreasuryInvoiceSelector:true,
896 authorizedRefundTracedInInstalledWebView2:true};
897 }
898
899 async function nativeBackupRestore() {
900 const check = (value, message) => { if (!value) throw Error(message); };
901 const S = FINORA.Storage;
902 const company = (await S.getAll('companies'))[0];
903 const temporary = await S.put('contacts', {
904 id: 'native-vm-backup-roundtrip', companyId: company.id, name: 'فقط آزمون بازگردانی'
905 });
906 const snapshot = await S.exportAll();
907 check(snapshot.version === 7 && snapshot.app === 'Factor-easyPro',
908 'invalid native backup envelope');
909 check(snapshot.data.contacts.some(x => x.id === temporary.id),
910 'native backup omitted test contact');
911 check(snapshot.data.users.every(u => !('pwHash' in u) && !('pwSalt' in u)),
912 'native backup leaked user password derivation metadata');
913 await S.delete('contacts', temporary.id);
914 check(!(await S.get('contacts', temporary.id)), 'test contact was not deleted');
915 await S.importAll({
916 app: snapshot.app, version: snapshot.version,
917 data: { contacts: snapshot.data.contacts.filter(c => c.id === temporary.id) }
918 });
919 check((await S.get('contacts', temporary.id))?.name === 'فقط آزمون بازگردانی',
920 'native backup restore did not recover contact');
921
922 const sale = (await S.getAll('invoices')).find(i => i.kind === 'sale' && i.financePosted);
923 check(sale, 'posted sale missing for restore immutability');
924 let denied = false;
925 try {
926 await S.importAll({
927 app: snapshot.app, version: snapshot.version,
928 data: {
929 contacts: [{id:'should-rollback-native',companyId:company.id,name:'Reject'}],
930 invoices: [{...sale,grandTotal:sale.grandTotal+1}]
931 }
932 });
933 } catch (_) { denied = true; }
934 check(denied, 'tampered posted sale backup must fail');
935 check(!(await S.get('contacts','should-rollback-native')),
936 'rejected full backup wrote a contact anyway');
937 check((await S.get('invoices',sale.id)).grandTotal===sale.grandTotal,
938 'tampered posted sale modified the actual financial document');
939 return { backupSchema: snapshot.version, credentialsExcluded: true,
940 contactRoundtrip: true, tamperedInvoiceRejectedAtomically: true };
941 }
942
943 async function invoicePrintLayout() {
944 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
945 const check = (value, message) => { if (!value) throw Error(message); };
946 const sale = (await FINORA.Storage.getAll('invoices'))
947 .find(x => x.kind === 'sale' && x.financePosted);
948 check(sale, 'posted invoice for print preview missing');
949 await FINORA.Router.go('invoices');
950 await wait(200);
951 await window.InvoicesView.printInvoice(sale.id);
952 await wait(320);
953 const dialog = document.querySelector('.modal-backdrop');
954 check(dialog, 'native print settings dialog did not open');
955 const labels = dialog.textContent || '';
956 check(labels.includes('قالب چاپ') && labels.includes('A4'),
957 'RTL print template or paper settings missing');
958 check(document.documentElement.dir === 'rtl',
959 'document is not marked RTL');
960 FINORA.Modal.close();
961 return { rtl: true, printSettings: true, templates: true,
962 physicalPrinterTest: 'not-covered' };
963 }
964
965 async function fiscalCloseGuardrails() {
966 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
967 const check = (ok, message) => { if (!ok) throw Error(message); };
968 const store = FINORA.Storage;
969 const company = await FINORA.Company.current();
970 check(company?.id && FINORA.Auth.isAdmin(), 'Fiscal close test must use a synthetic admin');
971 await FINORA.Router.go('accounting');
972 await wait(180);
973 const view = window.AccountingView;
974 check(view, 'Native accounting view was not mounted');
975 await view.switchTab('periods');
976 const testName = 'A05 VM-only guarded closing period';
977 view.openPeriodModal();
978 check(document.getElementById('acPeriodName'), 'Fiscal period creation form missing');
979 document.getElementById('acPeriodName').value = testName;
980 document.getElementById('acPeriodStart').value = '1404/01/01';
981 document.getElementById('acPeriodEnd').value = '1404/12/29';
982 await view.savePeriod();
983 check(!document.querySelector('.toast-error'), 'Creating isolated fiscal period failed');
984 const period = (await store.getAll('fiscal_periods'))
985 .find(x => x.companyId === company.id && x.name === testName);
986 check(period && period.closed === false, 'Synthetic fiscal period did not persist as open');
987 const warehouses = (await store.getAll('warehouses')).filter(x => x.companyId === company.id);
988 check(warehouses.length, 'Warehouse prerequisite missing');
989 const stocktakeId = 'vm-a05-draft-stocktake';
990 await store.put('stocktakes', {
991 id: stocktakeId, companyId: company.id,
992 warehouseId: warehouses[0].id, status: 'draft'
993 });
994 const auditCount = (await store.getAll('audit_events'))
995 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length;
996 const confirmClose = () => {
997 view.closePeriod(period.id);
998 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
999 check(confirm, 'Real fiscal closure approval dialog missing');
1000 confirm.click();
1001 };
1002 confirmClose();
1003 let message = null;
1004 for (let i = 0; i < 60; i++) {
1005 message = [...document.querySelectorAll('.toast-error')]
1006 .find(x => x.textContent.includes('انبارگردانی باز'));
1007 if (message) break;
1008 await wait(100);
1009 }
1010 check(message, 'Closing with an open stocktake was not rejected visibly');
1011 check((await store.get('fiscal_periods', period.id))?.closed === false,
1012 'Open stocktake allowed fiscal closure');
1013 check((await store.getAll('audit_events'))
1014 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length === auditCount,
1015 'Rejected fiscal closing created an audit receipt');
1016 message.querySelector('.toast-close')?.click();
1017 check(!document.querySelector('.toast-error'), 'Expected fiscal rejection toast remained');
1018 await store.delete('stocktakes', stocktakeId);
1019
1020 // A05: another real fiscal-close attempt must still be blocked while
1021 // there is an unfinished draft ledger in the same isolated period.
1022 const draftId = 'vm-a05-unposted-draft-journal';
1023 await store.put('journal_entries', {
1024 id: draftId, companyId: company.id, periodId: period.id,
1025 date: '1404/06/15', status: 'draft', sourceType: 'manual',
1026 description: 'VM-only pending draft prevents closure'
1027 });
1028 confirmClose();
1029 let draftToast = null;
1030 for (let i = 0; i < 60; i++) {
1031 draftToast = [...document.querySelectorAll('.toast-error')]
1032 .find(x => x.textContent.includes('اسناد پیش‌نویس'));
1033 if (draftToast) break;
1034 await wait(100);
1035 }
1036 check(draftToast, 'Native fiscal closure ignored the pending draft journal');
1037 check((await store.get('fiscal_periods', period.id))?.closed === false,
1038 'Rejected draft-journal closure changed period state');
1039 check((await store.getAll('audit_events'))
1040 .filter(x => x.companyId === company.id &&
1041 x.eventType === 'period_closed').length === auditCount,
1042 'Rejected draft-journal closure wrote a successful close audit');
1043 draftToast.querySelector('.toast-close')?.click();
1044 check(!document.querySelector('.toast-error'),
1045 'Expected unposted-journal rejection toast remained visible');
1046 await store.delete('journal_entries', draftId);
1047 confirmClose();
1048 let closed = null;
1049 for (let i = 0; i < 70; i++) {
1050 closed = await store.get('fiscal_periods', period.id);
1051 if (closed?.closed) break;
1052 await wait(100);
1053 }
1054 check(closed?.closed === true && closed.status === 'closed',
1055 'Approved fiscal close was not committed');
1056 const closureAudits = (await store.getAll('audit_events'))
1057 .filter(x => x.companyId === company.id &&
1058 x.eventType === 'period_closed' && x.sourceId === period.id);
1059 check(closureAudits.length === 1 &&
1060 closureAudits[0].actorId === FINORA.Auth.current().id,
1061 'Successful fiscal closure did not produce exactly one actor-scoped audit');
1062 // Already-closed periods must not be closed again via the actual confirmation
1063 // action, nor silently insert another period_closed audit receipt.
1064 confirmClose();
1065 let closedToast = null;
1066 for (let i = 0; i < 60; i++) {
1067 closedToast = [...document.querySelectorAll('.toast-error')]
1068 .find(x => x.textContent.includes('دوره مالی بسته است'));
1069 if (closedToast) break;
1070 await wait(100);
1071 }
1072 check(closedToast, 'Duplicate native close did not visibly reject');
1073 check((await store.getAll('audit_events'))
1074 .filter(x => x.companyId === company.id &&
1075 x.eventType === 'period_closed' && x.sourceId === period.id).length === 1,
1076 'Duplicate fiscal close created a second audit receipt');
1077 closedToast.querySelector('.toast-close')?.click();
1078 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
1079 'Fiscal guardrail test left an unexpected UI error or modal');
1080 return {
1081 openStocktakeBlocked: true,
1082 draftJournalBlocked: true,
1083 failedCloseRolledBack: true,
1084 successfulCloseCommitted: true,
1085 duplicateCloseRejected: true,
1086 singleAuditReceipt: true
1087 };
1088 }
1089
1090 async function openingDryRunWithExistingActivity() {
1091 const check = (ok, message) => { if (!ok) throw Error(message); };
1092 const store = FINORA.Storage;
1093 const company = await FINORA.Company.current();
1094 check(company?.id && FINORA.Auth.isAdmin(),
1095 'Native A02 opening dry-run requires a synthetic administrator');
1096 await FINORA.Router.go('accounting');
1097 const view = window.AccountingView;
1098 check(view, 'AccountingView missing in actual installed app');
1099 await view.switchTab('opening');
1100 const input = document.getElementById('openingFileInput');
1101 const reportHost = document.getElementById('openingPreviewReport');
1102 check(input && reportHost, 'Opening balance JSON dry-run form is missing');
1103 const periods = (await store.getAll('fiscal_periods'))
1104 .filter(x => x.companyId === company.id);
1105 const period = periods.find(x => !x.closed);
1106 check(period, 'An active period is required for A02 blocked historical migration test');
1107 const priorJournals = (await store.getAll('journal_entries'))
1108 .filter(x => x.companyId === company.id && x.status === 'posted');
1109 check(priorJournals.length > 0,
1110 'Financial activity prerequisite missing: opening must be blocked after posting');
1111 const before = {
1112 entries: (await store.getAll('journal_entries')).length,
1113 lines: (await store.getAll('journal_lines')).length,
1114 events: (await store.getAll('audit_events')).length,
1115 settings: (await store.getAll('settings')).length
1116 };
1117 const fixture = {
1118 periodId: period.id, openingDate: period.startDate,
1119 lines: [], contacts: [], stock: [], cash: []
1120 };
1121 const file = new File([JSON.stringify(fixture)], 'vm-only-a02-opening.json',
1122 { type: 'application/json' });
1123 Object.defineProperty(input, 'files', { configurable: true, value: [file] });
1124 view.resetOpeningPreview();
1125 await view.previewOpeningFile();
1126 const review = view._openingReview;
1127 check(review && review.readiness === 'blocked' && review.writePerformed === false,
1128 'Native opening dry-run failed to block incompatible historical data');
1129 check(review.issues.includes('EXISTING_POSTED_JOURNALS') &&
1130 review.issues.includes('MISSING_OPENING_JOURNAL_LINES'),
1131 'Native blocked opening preview omitted journal issues');
1132 check(reportHost.textContent.includes('ثبت مسدود') &&
1133 reportHost.querySelector('button[disabled]'),
1134 'Native opening UI offered an actionable posting button despite issues');
1135 const after = {
1136 entries: (await store.getAll('journal_entries')).length,
1137 lines: (await store.getAll('journal_lines')).length,
1138 events: (await store.getAll('audit_events')).length,
1139 settings: (await store.getAll('settings')).length
1140 };
1141 check(JSON.stringify(before) === JSON.stringify(after),
1142 'Opening preview wrote to ledger, audit or settings');
1143 check(!document.querySelector('.toast-error'),
1144 'Blocked A02 dry-run unexpectedly threw rather than reporting issues');
1145 await view.switchTab('journals');
1146 return {
1147 priorActivityBlocked: true,
1148 discrepancyCodesVisible: true,
1149 commitActionDisabled: true,
1150 zeroWrites: true
1151 };
1152 }
1153
1154 module.exports = async function nativeFunctionalMatrix(cdp) {
1155 const phases = [
1156 ['activate-accounting-and-inventory', activateAccounting],
1157 ['positive-opening-ledger-and-idempotency', nativePositiveOpeningLedger],
1158 ['purchase-and-post-ledger', purchaseInvoice],
1159 ['partial-sale-and-inventory', saleInvoice],
1160 ['inactive-treasury-cheque-settlement', nativeInactiveBankSettlementGuard],
1161 ['cheque-third-party-endorsement', nativeChequeThirdPartyEndorsement],
1162 ['treasury-cheque-reconciliation-readonly', nativeTreasuryChequeReconciliation],
1163 ['sale-return-immutable-stock-and-ledger', nativeSaleReturnGuardrails],
1164 ['purchase-return-and-stock-guardrails', nativePurchaseReturnGuardrails],
1165 ['return-cash-settlement-net-credit', nativeReturnCashSettlementGuardrails],
1166 ['append-only-history-bulk-clear-protection', nativeHistoryClearFailClosed],
1167 ['backup-and-atomic-rejection', nativeBackupRestore],
1168 ['rtl-invoice-print-settings', invoicePrintLayout],
1169 ['fiscal-close-atomic-guardrails', fiscalCloseGuardrails],
1170 ['opening-dry-run-rejects-existing-postings', openingDryRunWithExistingActivity]
1171 ];
1172 const report = {};
1173 for (const [name, fn] of phases) {
1174 const value = await cdp.evaluate('(' + fn.toString() + ')()');
1175 assert.ok(value && typeof value === 'object', 'invalid native E2E result from ' + name);
1176 report[name] = value;
1177 console.log('NATIVE E2E PASSED: ' + name + ': ' + JSON.stringify(value));
1178 }
1179 return report;
1180 };