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

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