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

fix/phase-a-closure-pack3-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,950 lines 103 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 let periodCreatedByForm = false;
132 if (!view.periods.length) {
133 view.openPeriodModal();
134 check(document.getElementById('acPeriodName'), 'fiscal period form absent');
135 document.getElementById('acPeriodName').value = 'دوره تست ویندوز ۱۴۰۵';
136 document.getElementById('acPeriodStart').value = '1405/01/01';
137 document.getElementById('acPeriodEnd').value = '1405/12/29';
138 await view.savePeriod();
139 periodCreatedByForm = true;
140 }
141 check(view.periods.length > 0, 'period did not persist');
142 await view.switchTab('accounts');
143 if (!view.accounts.some(account => account.code === '402')) {
144 view.seedChart();
145 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
146 check(confirm, 'chart seed approval missing');
147 confirm.click();
148 for (let i = 0; i < 35 && !view.accounts.some(a => a.code === '402'); i++) await wait(150);
149 }
150 check(view.accounts.some(account => account.code === '402'), 'default chart missing account 402');
151 await view.switchTab('integration');
152 if (!document.getElementById('accountingWorkbench')?.textContent.includes('یکپارچه فعال است')) {
153 view.activateRetail();
154 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
155 check(confirm, 'activation approval missing');
156 confirm.click();
157 for (let i = 0; i < 35 && !document.getElementById('accountingWorkbench')?.textContent.includes('یکپارچه فعال است'); i++) await wait(150);
158 }
159 check(document.getElementById('accountingWorkbench')?.textContent.includes('یکپارچه فعال است'),
160 'finance and retail integration not active');
161 view.openWarehouse();
162 check(document.getElementById('acWhName'), 'warehouse form missing');
163 document.getElementById('acWhName').value = 'انبار ماشین مجازی';
164 await view.saveWarehouse();
165 check((await FINORA.Storage.getAll('warehouses')).some(w => w.name === 'انبار ماشین مجازی'),
166 'warehouse did not persist');
167 return { fiscalPeriods: view.periods.length, periodCreatedByForm,
168 accountCount: view.accounts.length, chartAvailable: view.accounts.some(a => a.code === '402'),
169 integration: 'enabled', integrationEnabled: true, warehouse: 'created', warehouseCreatedByForm: true };
170 }
171
172 async function nativeContactCrudFormAndTags() {
173 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
174 const check = (value, message) => { if (!value) throw Error(message); };
175 await FINORA.Router.go('contacts');
176 await wait(180);
177 const view = window.ContactsView;
178 check(view, 'Native contacts view is unavailable');
179 await view.openContactModal();
180 await wait(80);
181 check(document.getElementById('cName') && document.getElementById('newTagInput'),
182 'Native contact creation form is incomplete');
183 const originalName = 'Q01 شخص فرم ساختگی';
184 const updatedName = 'Q01 شخص ویرایش‌شده';
185 const tag = 'Q01-NATIVE-CONTACT-TAG';
186 document.getElementById('cName').value = originalName;
187 document.getElementById('cRole').value = 'both';
188 document.getElementById('newTagInput').value = tag;
189 const addTag = [...document.querySelectorAll('.modal-card button')]
190 .find(button => /ContactsView\.addNewTag/.test(button.getAttribute('onclick') || ''));
191 check(addTag, 'Native contact tag action is missing');
192 addTag.click();
193 check(document.querySelector('.tagCheckbox[value="' + tag + '"]')?.checked,
194 'New contact tag was not added and selected');
195 const saveContact = () => [...document.querySelectorAll('.modal-card .modal-footer button')]
196 .find(button => !button.disabled && /ذخیره/.test(button.textContent));
197 const createButton = saveContact();
198 check(createButton, 'Native contact create button is missing');
199 createButton.click();
200 let created = null;
201 for (let i = 0; i < 60; i++) {
202 created = (await FINORA.Storage.getAll('contacts'))
203 .find(contact => contact.name === originalName);
204 if (created && FINORA.Modal.stack.length === 0) break;
205 await wait(100);
206 }
207 check(created && created.tags.includes(tag),
208 'Contact form did not persist the new contact and selected tag');
209 await view.editContact(created.id);
210 await wait(80);
211 check(document.getElementById('cName')?.value === originalName,
212 'Contact edit form did not load the persisted record');
213 document.getElementById('cName').value = updatedName;
214 check(document.querySelector('.tagCheckbox[value="' + tag + '"]')?.checked,
215 'Contact edit form did not restore the saved tag selection');
216 const updateButton = saveContact();
217 check(updateButton, 'Native contact update button is missing');
218 updateButton.click();
219 let updated = null;
220 for (let i = 0; i < 60; i++) {
221 updated = await FINORA.Storage.get('contacts', created.id);
222 if (updated?.name === updatedName && FINORA.Modal.stack.length === 0) break;
223 await wait(100);
224 }
225 check(updated?.name === updatedName && updated.tags.includes(tag),
226 'Contact form update did not preserve identity and tags');
227 check(!document.querySelector('.toast-error'),
228 'Native contact CRUD form displayed an unexpected error');
229 return { createdThroughForm: true, tagPersisted: true,
230 editedThroughForm: true, stableRecordId: true };
231 }
232
233 async function nativeProductCrudFormAndNestedClassifiers() {
234 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
235 const check = (value, message) => { if (!value) throw Error(message); };
236 await FINORA.Router.go('products');
237 await wait(180);
238 const view = window.ProductsView;
239 check(view, 'Native products view is unavailable');
240 view._switchTab('products');
241 await view.openProductModal();
242 await wait(80);
243 const parentDepth = FINORA.Modal.stack.length;
244 check(parentDepth === 1 && document.getElementById('pName'),
245 'Native product parent form is missing');
246 const unitName = 'Q01-UNIT-UI';
247 const unitButton = document.querySelector('.modal-card button[onclick*="openUnitModal(true)"]');
248 check(unitButton, 'Nested unit creation button is missing');
249 unitButton.click();
250 await wait(60);
251 check(FINORA.Modal.stack.length === parentDepth + 1 &&
252 document.getElementById('uName') && document.getElementById('uSymbol'),
253 'Nested unit form did not open');
254 document.getElementById('uName').value = unitName;
255 document.getElementById('uSymbol').value = 'q1';
256 const saveTopModal = () => [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
257 .find(button => !button.disabled && /ذخیره/.test(button.textContent));
258 const saveUnit = saveTopModal();
259 check(saveUnit, 'Nested unit save action is missing');
260 saveUnit.click();
261 let unitId = '';
262 for (let i = 0; i < 60; i++) {
263 unitId = document.getElementById('pUnit')?.value || '';
264 if (FINORA.Modal.stack.length === parentDepth && unitId &&
265 (await FINORA.Storage.getAll('units')).some(unit => unit.id === unitId && unit.name === unitName)) break;
266 await wait(100);
267 }
268 check(FINORA.Modal.stack.length === parentDepth && unitId &&
269 (await FINORA.Storage.getAll('units')).some(unit => unit.id === unitId && unit.name === unitName),
270 'Saving a nested unit did not restore parent and select persisted unit');
271
272 const categoryName = 'Q01-CATEGORY-UI';
273 const categoryButton = document.querySelector('.modal-card button[onclick*="openCategoryModal(true)"]');
274 check(categoryButton, 'Nested category creation button is missing');
275 categoryButton.click();
276 await wait(60);
277 check(FINORA.Modal.stack.length === parentDepth + 1 &&
278 document.getElementById('cName') && document.getElementById('cParent'),
279 'Nested category form did not open');
280 document.getElementById('cName').value = categoryName;
281 const saveCategory = saveTopModal();
282 check(saveCategory, 'Nested category save action is missing');
283 saveCategory.click();
284 let categoryId = '';
285 for (let i = 0; i < 60; i++) {
286 categoryId = document.getElementById('pCategory')?.value || '';
287 if (FINORA.Modal.stack.length === parentDepth && categoryId &&
288 (await FINORA.Storage.getAll('categories')).some(category => category.id === categoryId && category.name === categoryName)) break;
289 await wait(100);
290 }
291 check(FINORA.Modal.stack.length === parentDepth && categoryId &&
292 (await FINORA.Storage.getAll('categories')).some(category => category.id === categoryId && category.name === categoryName),
293 'Saving a nested category did not restore parent and select persisted category');
294
295 const productName = 'Q01 کالای فرم ساختگی';
296 document.getElementById('pCode').value = 'Q01-UI-PRODUCT';
297 document.getElementById('pName').value = productName;
298 document.getElementById('pBuyPrice').value = '1200';
299 document.getElementById('pSellPrice').value = '2400';
300 document.getElementById('pMinStock').value = '2.125';
301 const saveProduct = saveTopModal();
302 check(saveProduct, 'Native product create button is missing');
303 saveProduct.click();
304 let created = null;
305 for (let i = 0; i < 60; i++) {
306 created = (await FINORA.Storage.getAll('products'))
307 .find(product => product.code === 'Q01-UI-PRODUCT');
308 if (created && FINORA.Modal.stack.length === 0) break;
309 await wait(100);
310 }
311 check(created && created.name === productName && created.unitId === unitId &&
312 created.categoryId === categoryId && created.buyPrice === 1200 &&
313 created.sellPrice === 2400 && created.minStock === 2.125,
314 'Product form failed to persist prices, reorder point, unit or category');
315 await view.editProduct(created.id);
316 await wait(80);
317 check(document.getElementById('pName')?.value === productName,
318 'Product edit form did not load the persisted record');
319 const updatedName = 'Q01 کالای ویرایش‌شده';
320 document.getElementById('pName').value = updatedName;
321 const updateProduct = saveTopModal();
322 check(updateProduct, 'Native product update button is missing');
323 updateProduct.click();
324 let updated = null;
325 for (let i = 0; i < 60; i++) {
326 updated = await FINORA.Storage.get('products', created.id);
327 if (updated?.name === updatedName && FINORA.Modal.stack.length === 0) break;
328 await wait(100);
329 }
330 check(updated?.name === updatedName && updated.unitId === unitId &&
331 updated.categoryId === categoryId && updated.sellPrice === 2400,
332 'Product form update did not preserve selected classifiers and financial fields');
333
334 // Standalone unit/category forms (false flag) and destructive row actions are
335 // tested only against unused synthetic records in this disposable VM.
336 const standaloneUnitName = 'Q01-UNIT-STANDALONE';
337 view._switchTab('units');
338 view.openUnitModal(false);
339 document.getElementById('uName').value = standaloneUnitName;
340 document.getElementById('uSymbol').value = 'q1s';
341 const standaloneUnitSave = saveTopModal();
342 check(standaloneUnitSave, 'Standalone unit save button is missing');
343 standaloneUnitSave.click();
344 let standaloneUnit = null;
345 for (let i = 0; i < 60; i++) {
346 standaloneUnit = (await FINORA.Storage.getAll('units')).find(x => x.name === standaloneUnitName);
347 if (standaloneUnit && FINORA.Modal.stack.length === 0) break;
348 await wait(100);
349 }
350 check(standaloneUnit && FINORA.Modal.stack.length === 0,
351 'Standalone unit did not persist through the unit form');
352 view._switchTab('units');
353 const deleteUnitButton = [...document.querySelectorAll('#products-tab-content button[onclick*="deleteUnit"]')]
354 .find(button => button.getAttribute('onclick').includes(standaloneUnit.id));
355 check(deleteUnitButton, 'Standalone synthetic unit delete action is missing');
356 deleteUnitButton.click();
357 await wait(30);
358 const confirmUnitDelete = FINORA.Modal.stack.at(-1)?.card.querySelector('[data-action="confirm"]');
359 check(confirmUnitDelete, 'Standalone unit delete confirmation is missing');
360 confirmUnitDelete.click();
361 let unitDeleted = false;
362 for (let i = 0; i < 60; i++) {
363 unitDeleted = !(await FINORA.Storage.get('units', standaloneUnit.id));
364 if (unitDeleted && FINORA.Modal.stack.length === 0) break;
365 await wait(100);
366 }
367 check(unitDeleted, 'Standalone synthetic unit was not deleted through its row action');
368
369 const standaloneCategoryName = 'Q01-CATEGORY-STANDALONE';
370 view._switchTab('categories');
371 view.openCategoryModal(false);
372 document.getElementById('cName').value = standaloneCategoryName;
373 const standaloneCategorySave = saveTopModal();
374 check(standaloneCategorySave, 'Standalone category save button is missing');
375 standaloneCategorySave.click();
376 let standaloneCategory = null;
377 for (let i = 0; i < 60; i++) {
378 standaloneCategory = (await FINORA.Storage.getAll('categories')).find(x => x.name === standaloneCategoryName);
379 if (standaloneCategory && FINORA.Modal.stack.length === 0) break;
380 await wait(100);
381 }
382 check(standaloneCategory && FINORA.Modal.stack.length === 0,
383 'Standalone category did not persist through the category form');
384 view._switchTab('categories');
385 const deleteCategoryButton = [...document.querySelectorAll('#products-tab-content button[onclick*="deleteCategory"]')]
386 .find(button => button.getAttribute('onclick').includes(standaloneCategory.id));
387 check(deleteCategoryButton, 'Standalone synthetic category delete action is missing');
388 deleteCategoryButton.click();
389 await wait(30);
390 const confirmCategoryDelete = FINORA.Modal.stack.at(-1)?.card.querySelector('[data-action="confirm"]');
391 check(confirmCategoryDelete, 'Standalone category delete confirmation is missing');
392 confirmCategoryDelete.click();
393 let categoryDeleted = false;
394 for (let i = 0; i < 60; i++) {
395 categoryDeleted = !(await FINORA.Storage.get('categories', standaloneCategory.id));
396 if (categoryDeleted && FINORA.Modal.stack.length === 0) break;
397 await wait(100);
398 }
399 check(categoryDeleted, 'Standalone synthetic category was not deleted through its row action');
400 check(!document.querySelector('.toast-error'),
401 'Native product CRUD form displayed an unexpected error');
402 return { createdThroughForm: true, nestedUnitSavedAndSelected: true,
403 nestedCategorySavedAndSelected: true, fractionalReorderPointPreserved: true,
404 editedThroughForm: true, stableRecordId: true,
405 standaloneUnitCreatedAndDeleted: true, standaloneCategoryCreatedAndDeleted: true };
406 }
407
408 async function nativePositiveOpeningLedger() {
409 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
410 const check = (value, message) => { if (!value) throw Error(message); };
411 const store = FINORA.Storage;
412 const company = await FINORA.Company.current();
413 check(company?.id && FINORA.Auth.isAdmin(), 'Native A02 posting needs synthetic administrator');
414 const period = (await store.getAll('fiscal_periods'))
415 .find(x => x.companyId === company.id && x.closed === false);
416 const accounts = (await store.getAll('account_chart'))
417 .filter(x => x.companyId === company.id && x.postable !== false);
418 const receivable = accounts.find(x => x.code === '102');
419 const equity = accounts.find(x => x.code === '301');
420 check(period && receivable && equity, 'Synthetic opening prerequisites missing');
421 const person = await window.ContactController.create({
422 name: 'شخص افتتاحیه ساختگی ویندوز', role: 'customer'
423 });
424 const candidate = {
425 periodId: period.id, openingDate: period.startDate,
426 lines: [
427 { accountId: receivable.id, role: 'receivable', debit: 300, credit: 0 },
428 { accountId: equity.id, role: 'equity', debit: 0, credit: 300 }
429 ],
430 contacts: [{ contactId: person.id, receivable: 300, payable: 0 }],
431 stock: [], cash: []
432 };
433 await FINORA.Router.go('accounting');
434 await wait(160);
435 const view = window.AccountingView;
436 await view.switchTab('opening');
437 const attach = () => {
438 const input = document.getElementById('openingFileInput');
439 check(input, 'A02 native JSON picker missing');
440 const file = new File([JSON.stringify(candidate)], 'vm-a02-opening.json',
441 { type: 'application/json' });
442 Object.defineProperty(input, 'files', { configurable: true, value: [file] });
443 };
444 attach();
445 await view.previewOpeningFile();
446 check(view._openingReview?.readiness === 'ready-for-review' &&
447 view._openingReview?.writePerformed === false &&
448 view._openingReview?.issues.length === 0,
449 'Balanced synthetic opening was not ready without writes');
450 const priorPosted = (await store.getAll('journal_entries'))
451 .filter(x => x.companyId === company.id && x.sourceType === 'opening_balance');
452 check(priorPosted.length === 0, 'Preview unexpectedly posted an opening journal');
453 view.confirmOpeningPosting();
454 const confirmation = document.querySelector('.modal-footer [data-action="confirm"]');
455 check(confirmation, 'Opening posting explicit approval was not displayed');
456 confirmation.click();
457 let opening = null;
458 for (let i = 0; i < 80; i++) {
459 opening = (await store.getAll('journal_entries')).find(x =>
460 x.companyId === company.id && x.sourceType === 'opening_balance' &&
461 x.sourceId === period.id && x.status === 'posted');
462 if (opening) break;
463 await wait(100);
464 }
465 check(opening && opening.debit === 300 && opening.credit === 300,
466 'Confirmed synthetic opening was not posted as balanced ledger');
467 const lines = (await store.getAll('journal_lines')).filter(x => x.journalId === opening.id);
468 check(lines.length === 2 && lines.reduce((n, x) => n + x.debit, 0) === 300 &&
469 lines.reduce((n, x) => n + x.credit, 0) === 300,
470 'Opening journal lines do not match the dry-run');
471 const receipt = (await store.getAll('audit_events')).filter(x =>
472 x.companyId === company.id && x.eventType === 'opening_posted' && x.sourceId === opening.id);
473 check(receipt.length === 1 && receipt[0].actorId === FINORA.Auth.current().id,
474 'Opening journal missing unique actor-linked audit receipt');
475 await view.switchTab('opening');
476 attach();
477 await view.previewOpeningFile();
478 check(view._openingReview?.readiness === 'blocked' &&
479 view._openingReview?.issues.includes('EXISTING_POSTED_JOURNALS') &&
480 document.querySelector('#openingPreviewReport button[disabled]'),
481 'A02 second posting attempt not disabled in native UI');
482 check((await store.getAll('journal_entries')).filter(x =>
483 x.companyId === company.id && x.sourceType === 'opening_balance').length === 1,
484 'Repeated opening preview created another posted journal');
485 await view.switchTab('journals');
486 check(!document.querySelector('.toast-error'), 'Native opening workflow displayed unexpected error');
487 return { dryRunFirst: true, postedBalancedOpening: true,
488 actorAuditedOnce: true, repeatPostingBlocked: true };
489 }
490
491 async function purchaseInvoice() {
492 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
493 const check = (value, message) => { if (!value) throw Error(message); };
494 const c = await window.ContactController.create({ name: 'مشتری آزمایشی ویندوز', role: 'both' });
495 const p = await window.ProductController.createProduct({
496 name: 'کالای تست ویندوز', code: 'VM-E2E-100',
497 trackInventory: true, buyPrice: 100, sellPrice: 200
498 });
499 await FINORA.Router.go('invoices');
500 await wait(300);
501 await window.InvoiceFormView.open();
502 await wait(180);
503 check(document.getElementById('invWarehouse'), 'invoice warehouse selector missing');
504 document.getElementById('invKind').value = 'purchase';
505 await window.InvoiceFormView._onKindChange();
506 document.getElementById('invDate').value = '1405/07/18';
507 const contact = document.getElementById('invContactSearch');
508 contact.value = c.name;
509 window.InvoiceFormView._showContactOptions(true);
510 const item = document.querySelector('.contact-option[data-id="' + c.id + '"]');
511 check(item, 'contact autocomplete could not select synthetic contact');
512 item.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
513 const search = document.querySelector('.row-product-search');
514 check(search, 'product autocomplete absent');
515 search.value = p.code;
516 window.InvoiceFormView._showProductOptions(0, true);
517 const chosen = document.querySelector('.product-option[data-id="' + p.id + '"]');
518 check(chosen, 'product autocomplete selection failed');
519 chosen.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
520 // Actual installed WebView2 input event, not merely a pure formatting unit test:
521 // a quantity of 2.5 must not be converted to 25, and grouping must keep dot.
522 const quantityField = document.querySelector('.row-qty');
523 check(quantityField?.dataset.decimals === '3',
524 'Native invoice quantity field lacks the three-decimal precision contract');
525 quantityField.value = '1234.5';
526 quantityField.dispatchEvent(new Event('input', { bubbles: true }));
527 check(quantityField.value === '1,234.5',
528 'Native formatter removed fractional dot or failed live grouping');
529 quantityField.value = '2.5';
530 quantityField.dispatchEvent(new Event('input', { bubbles: true }));
531 check(quantityField.value === '2.5',
532 'Native input silently changed 2.5 to an incorrect financial quantity');
533 // Malformed paste must never silently become a new financial quantity.
534 quantityField.value = '2x5';
535 quantityField.dispatchEvent(new Event('input', { bubbles: true }));
536 check(quantityField.value === '2x5', 'Native formatter silently rewrote an invalid invoice amount');
537 await window.InvoiceFormView._save(false);
538 check(!(await FINORA.Storage.getAll('invoices')).some(x => x.contactId === c.id && x.kind === 'purchase'),
539 'Malformed native invoice quantity committed financial data');
540 // Restore the original synthetic invoice fixture before financial posting.
541 document.querySelector('.row-qty').value = '10';
542 window.InvoiceFormView._onFieldChange(0, 'qty', '10');
543 document.querySelector('.row-price').value = '100';
544 window.InvoiceFormView._onFieldChange(0, 'price', '100');
545 await window.InvoiceFormView._save(false);
546 await wait(160);
547 const invoice = (await FINORA.Storage.getAll('invoices'))
548 .find(x => x.contactId === c.id && x.kind === 'purchase');
549 check(invoice?.financePosted, 'purchase financial posting failed');
550 check((await FINORA.Storage.getAll('journal_entries'))
551 .some(j => j.sourceId === invoice.id && j.status === 'posted'), 'purchase ledger source missing');
552 check((await FINORA.Storage.getAll('stock_movements'))
553 .some(m => m.refId === invoice.id && m.type === 'in'), 'purchase inventory receipt missing');
554 check(!document.querySelector('.modal-backdrop'), 'purchase invoice modal stayed open');
555 return { purchaseAmount: invoice.grandTotal, purchasePosted: true, stockReceived: true };
556 }
557
558 async function saleInvoice() {
559 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
560 const check = (value, message) => { if (!value) throw Error(message); };
561 await FINORA.Router.go('treasury');
562 await wait(200);
563 if (!(await FINORA.Storage.getAll('treasury')).some(t => t.recordType === 'account')) {
564 await window.TreasuryView.openAccountModal();
565 document.getElementById('accName').value = 'صندوق ویندوز';
566 document.getElementById('accInitialBalance').value = '0';
567 await window.TreasuryView.saveAccount(null);
568 }
569 const accounts = (await FINORA.Storage.getAll('treasury')).filter(t => t.recordType === 'account');
570 check(accounts.some(a => a.ledgerAccountId), 'treasury subledger not mapped');
571 const cash = accounts.find(a => a.ledgerAccountId);
572 const contact = (await FINORA.Storage.getAll('contacts'))
573 .find(x => x.name === 'مشتری آزمایشی ویندوز');
574 const product = (await FINORA.Storage.getAll('products'))
575 .find(x => x.code === 'VM-E2E-100');
576 check(contact && product, 'purchase fixtures missing');
577 await FINORA.Router.go('invoices'); await wait(230);
578 await window.InvoiceFormView.open(); await wait(170);
579 document.getElementById('invKind').value = 'sale';
580 await window.InvoiceFormView._onKindChange();
581 document.getElementById('invDate').value = '1405/07/18';
582 const personSearch = document.getElementById('invContactSearch');
583 personSearch.value = contact.name;
584 window.InvoiceFormView._showContactOptions(true);
585 const personOption = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
586 check(personOption, 'sale customer picker failed');
587 personOption.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
588 const prodSearch = document.querySelector('.row-product-search');
589 prodSearch.value = product.code;
590 window.InvoiceFormView._showProductOptions(0, true);
591 const prodOption = document.querySelector('.product-option[data-id="' + product.id + '"]');
592 check(prodOption, 'sale product picker failed');
593 prodOption.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
594 document.querySelector('.row-qty').value = '3';
595 window.InvoiceFormView._onFieldChange(0, 'qty', '3');
596 document.querySelector('.row-price').value = '200';
597 window.InvoiceFormView._onFieldChange(0, 'price', '200');
598 document.getElementById('invPayment').value = 'partial';
599 window.InvoiceFormView._onPaymentChange();
600 document.getElementById('invPaidAmount').value = '200';
601 window.InvoiceFormView._recalc();
602 await window.InvoiceFormView._save(false); await wait(160);
603 const sale = (await FINORA.Storage.getAll('invoices'))
604 .find(i => i.kind === 'sale' && i.contactId === contact.id);
605 check(sale?.financePosted, 'sale was not financially posted');
606 check(sale.paidAmount === 200 && sale.remaining === 400,
607 'sale partial settlement incorrect: ' + JSON.stringify({ paid: sale.paidAmount, remaining: sale.remaining }));
608 const lines = await FINORA.Storage.getAll('journal_lines');
609 check(lines.some(l => l.accountId === cash.ledgerAccountId && l.debit === 200),
610 'partial settlement cash journal missing');
611 check((await FINORA.Storage.getAll('stock_movements'))
612 .some(m => m.refId === sale.id && m.type === 'out'), 'stock issue not posted');
613 return { salePaid: 200, saleRemaining: 400, salePosted: true, cashLedger: true };
614 }
615
616 async function nativeSaleReturnGuardrails() {
617 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
618 const check = (ok, message) => { if (!ok) throw Error(message); };
619 const S = FINORA.Storage;
620 const sale = (await S.getAll('invoices'))
621 .find(i => i.kind === 'sale' && i.financePosted && i.grandTotal === 600);
622 const contact = sale && await S.get('contacts', sale.contactId);
623 const product = (await S.getAll('products')).find(p => p.code === 'VM-E2E-100');
624 check(sale && contact && product, 'Posted original sale fixture is required');
625 const originalAmount = sale.grandTotal;
626 const originalPaid = sale.paidAmount;
627 const buildReturn = async (qty, price) => {
628 await FINORA.Router.go('invoices');
629 await wait(220);
630 await window.InvoiceFormView.open();
631 await wait(160);
632 const kind = document.getElementById('invKind');
633 check(kind, 'Native return invoice form missing');
634 kind.value = 'sale_return';
635 await window.InvoiceFormView._onKindChange();
636 const reference = document.getElementById('invOriginalInvoice');
637 check([...reference.options].some(x => x.value === sale.id),
638 'Posted sale does not appear as the reference invoice');
639 reference.value = sale.id;
640 document.getElementById('invDate').value = '1405/07/18';
641 const contactSearch = document.getElementById('invContactSearch');
642 contactSearch.value = contact.name;
643 window.InvoiceFormView._showContactOptions(true);
644 const contactItem = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
645 check(contactItem, 'Cannot select original customer in return form');
646 contactItem.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
647 const productSearch = document.querySelector('.row-product-search');
648 check(productSearch, 'Return product search field missing');
649 productSearch.value = product.code;
650 window.InvoiceFormView._showProductOptions(0, true);
651 const selected = document.querySelector('.product-option[data-id="' + product.id + '"]');
652 check(selected, 'Original sold product not selectable');
653 selected.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
654 document.querySelector('.row-qty').value = String(qty);
655 window.InvoiceFormView._onFieldChange(0, 'qty', String(qty));
656 document.querySelector('.row-price').value = String(price);
657 window.InvoiceFormView._onFieldChange(0, 'price', String(price));
658 document.getElementById('invPayment').value = 'credit';
659 window.InvoiceFormView._onPaymentChange();
660 await window.InvoiceFormView._save(false);
661 await wait(170);
662 };
663
664 await buildReturn(1, 200);
665 check(!document.querySelector('.toast-error'), 'Valid return showed an unexpected error');
666 const returns = (await S.getAll('invoices')).filter(x =>
667 x.kind === 'sale_return' && x.originalInvoiceId === sale.id);
668 check(returns.length === 1 && returns[0].financePosted &&
669 returns[0].grandTotal === 200 && returns[0].paidAmount === 0,
670 'Native return did not post a separate unpaid credit document');
671 const returned = returns[0];
672 const journal = await S.get('journal_entries', returned.journalId);
673 check(journal?.status === 'posted' && journal.sourceId === returned.id,
674 'Native sales return lacks its own posted ledger journal');
675 const lines = (await S.getAll('journal_lines')).filter(x => x.journalId === journal.id);
676 check(lines.length >= 2 && lines.reduce((n, x) => n + x.debit, 0) > 0 &&
677 lines.reduce((n, x) => n + x.debit, 0) ===
678 lines.reduce((n, x) => n + x.credit, 0),
679 'Return journal has invalid debit/credit balance');
680 check((await S.getAll('stock_movements'))
681 .some(x => x.refId === returned.id && x.type === 'in' && x.productId === product.id),
682 'Native sales return did not receive returned inventory');
683 check((await S.getAll('document_corrections')).some(x =>
684 x.sourceId === sale.id && x.resultId === returned.id),
685 'Return correction did not link to its immutable original');
686 check(!(await S.getAll('treasury')).some(x => x.invoiceId === returned.id &&
687 x.recordType === 'transaction'),
688 'Native return illegally generated an automatic refund');
689 const unchanged = await S.get('invoices', sale.id);
690 check(unchanged.grandTotal === originalAmount && unchanged.paidAmount === originalPaid &&
691 unchanged.financePosted, 'Posted source sale mutated during return');
692 const beforeInvalid = {
693 returns: (await S.getAll('invoices')).filter(x => x.kind === 'sale_return' &&
694 x.originalInvoiceId === sale.id).length,
695 stock: (await S.getAll('stock_movements')).length,
696 audits: (await S.getAll('audit_events')).length
697 };
698
699 // Quantity 3 would exceed the 2 units remaining from the original sale,
700 // while its 300 rial value is still below the remaining financial cap.
701 await buildReturn(3, 100);
702 let error = [...document.querySelectorAll('.toast-error')].find(x =>
703 x.textContent.includes('تعداد مرجوعی'));
704 check(error, 'Over-return quantity did not produce its expected UI rejection');
705 check((await S.getAll('invoices')).filter(x => x.kind === 'sale_return' &&
706 x.originalInvoiceId === sale.id).length === beforeInvalid.returns,
707 'Over-return created an extra financial invoice');
708 check((await S.getAll('stock_movements')).length === beforeInvalid.stock &&
709 (await S.getAll('audit_events')).length === beforeInvalid.audits,
710 'Rejected over-return left stock or audit side effects');
711 error.querySelector('.toast-close')?.click();
712 FINORA.Modal.close();
713 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
714 'Return guardrail left an error toast or modal after expected rejection');
715 return {
716 separatePostedReturn: true,
717 balancedLedgerAndReturnedStock: true,
718 postedOriginalImmutable: true,
719 noAutomaticCashRefund: true,
720 overReturnRejectedWithoutWrites: true
721 };
722 }
723
724 async function nativePurchaseReturnGuardrails() {
725 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
726 const check = (ok,msg) => { if (!ok) throw Error(msg); };
727 const S = FINORA.Storage;
728 const original = (await S.getAll('invoices')).find(x =>
729 x.kind === 'purchase' && x.financePosted && x.grandTotal === 1000);
730 const contact = original && await S.get('contacts', original.contactId);
731 const product = (await S.getAll('products')).find(x => x.code === 'VM-E2E-100');
732 check(original && contact && product, 'A01 purchase-return source fixtures missing');
733 const originalJournal = original.journalId;
734 const makeReturn = async (qty, price) => {
735 await FINORA.Router.go('invoices');
736 await wait(200);
737 await window.InvoiceFormView.open();
738 await wait(140);
739 document.getElementById('invKind').value = 'purchase_return';
740 await window.InvoiceFormView._onKindChange();
741 const source = document.getElementById('invOriginalInvoice');
742 check([...source.options].some(x => x.value === original.id && !x.disabled),
743 'Posted purchase not an eligible source in return form');
744 source.value = original.id;
745 document.getElementById('invDate').value = '1405/07/18';
746 const search = document.getElementById('invContactSearch');
747 search.value = contact.name;
748 window.InvoiceFormView._showContactOptions(true);
749 const option = document.querySelector('.contact-option[data-id="' + contact.id + '"]');
750 check(option, 'Original supplier cannot be selected');
751 option.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
752 const productSearch = document.querySelector('.row-product-search');
753 productSearch.value = product.code;
754 window.InvoiceFormView._showProductOptions(0, true);
755 const prod = document.querySelector('.product-option[data-id="' + product.id + '"]');
756 check(prod, 'Purchased product cannot be selected');
757 prod.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
758 document.querySelector('.row-qty').value = String(qty);
759 window.InvoiceFormView._onFieldChange(0, 'qty', String(qty));
760 document.querySelector('.row-price').value = String(price);
761 window.InvoiceFormView._onFieldChange(0, 'price', String(price));
762 document.getElementById('invPayment').value = 'credit';
763 window.InvoiceFormView._onPaymentChange();
764 await window.InvoiceFormView._save(false);
765 await wait(180);
766 };
767 await makeReturn(1, 100);
768 check(!document.querySelector('.toast-error'), 'Valid supplier return showed unexpected error');
769 const found = (await S.getAll('invoices')).filter(x =>
770 x.kind === 'purchase_return' && x.originalInvoiceId === original.id);
771 check(found.length === 1 && found[0].financePosted &&
772 found[0].paidAmount === 0 && found[0].grandTotal === 100,
773 'Purchase return was not correctly posted without automatic cash receipt');
774 const returned = found[0];
775 const ledger = await S.get('journal_entries', returned.journalId);
776 check(ledger?.status === 'posted' && ledger.sourceId === returned.id,
777 'Purchase return journal link missing');
778 const lines = (await S.getAll('journal_lines')).filter(x => x.journalId === ledger.id);
779 const debit = lines.reduce((n,x)=>n+x.debit,0);
780 const credit = lines.reduce((n,x)=>n+x.credit,0);
781 check(lines.length >= 2 && debit > 0 && debit === credit,
782 'Native purchase return failed ledger balancing');
783 check((await S.getAll('stock_movements')).some(x =>
784 x.refId === returned.id && x.type === 'out' && x.productId === product.id),
785 'Returned purchased inventory did not leave warehouse');
786 check((await S.getAll('document_corrections')).some(x =>
787 x.sourceId === original.id && x.resultId === returned.id),
788 'Supplier return must be a linked correction');
789 check((await S.get('invoices', original.id)).journalId === originalJournal,
790 'Supplier return illegally changed source purchase');
791 check(!(await S.getAll('treasury')).some(x =>
792 x.recordType === 'transaction' && x.invoiceId === returned.id),
793 'Supplier return created unauthorized treasury cash event');
794 const before = {
795 invoices:(await S.getAll('invoices')).length,
796 movements:(await S.getAll('stock_movements')).length,
797 audits:(await S.getAll('audit_events')).length
798 };
799 // 10 more units exceeds the 9 remaining, even though the proposed
800 // 500-rial credit is BELOW the remaining purchase monetary cap.
801 await makeReturn(10, 50);
802 const toast = [...document.querySelectorAll('.toast-error')].find(x =>
803 x.textContent.includes('تعداد مرجوعی'));
804 check(toast, 'Over-quantity supplier return did not fail visibly');
805 check((await S.getAll('invoices')).length === before.invoices &&
806 (await S.getAll('stock_movements')).length === before.movements &&
807 (await S.getAll('audit_events')).length === before.audits,
808 'Rejected supplier return wrote an invoice, stock or audit event');
809 toast.querySelector('.toast-close')?.click();
810 FINORA.Modal.close();
811 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
812 'A01 supplier return negative test left UI error or modal');
813 return { postedSupplierReturn:true, balancedLedger:true, stockIssued:true,
814 originalPurchaseImmutable:true, noAutomaticTreasury:true,
815 overReturnRejectedAtomically:true };
816 }
817
818 async function nativeHistoryClearFailClosed() {
819 const check = (value, message) => { if (!value) throw Error(message); };
820 const store = FINORA.Storage;
821 const company = await FINORA.Company.current();
822 check(company?.id && FINORA.Auth.isAdmin(),
823 'History protection must run in installed VM with synthetic administrator');
824 const preserved = {};
825 for (const name of ['audit_events', 'document_corrections']) {
826 const history = (await store.getAll(name))
827 .filter(row => row.companyId === company.id);
828 check(history.length > 0, 'Native immutable history prerequisite missing: ' + name);
829 preserved[name] = history.map(row => JSON.stringify(row)).sort();
830 const sentinel = 'vm-a03-aborted-clear-' + name;
831 let rejected = false;
832 try {
833 await store.transaction(['contacts', name], async tx => {
834 await tx.putRaw('contacts', {
835 id: sentinel, companyId: company.id,
836 name: 'VM ONLY must roll back before history clear'
837 });
838 await tx.clear(name);
839 });
840 } catch (error) {
841 rejected = String(error).includes('پاک‌سازی مستقیم');
842 }
843 check(rejected, 'Installed IndexedDB accepted a bulk history clear: ' + name);
844 check(!(await store.get('contacts', sentinel)),
845 'Rejected native history-clear transaction committed earlier writes');
846 const after = (await store.getAll(name))
847 .filter(row => row.companyId === company.id)
848 .map(row => JSON.stringify(row)).sort();
849 check(JSON.stringify(after) === JSON.stringify(preserved[name]),
850 'Failed clear mutated immutable history: ' + name);
851 }
852 check(!document.querySelector('.toast-error'),
853 'Native history protection left unrelated UI error');
854 return { immutableAuditClearRejected: true,
855 immutableCorrectionClearRejected: true,
856 bothTransactionsRolledBack: true,
857 historyUnchanged: true };
858 }
859
860 async function nativeInactiveBankSettlementGuard() {
861 const wait=ms=>new Promise(r=>setTimeout(r,ms));
862 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
863 const db=FINORA.Storage,company=await FINORA.Company.current();
864 check(company?.id&&FINORA.Auth.isAdmin(),'A05 native admin required');
865 const contact=(await db.getAll('contacts')).find(c=>c.companyId===company.id&&c.name==='مشتری آزمایشی ویندوز');
866 const active=(await db.getAll('treasury')).find(x=>x.companyId===company.id&&x.recordType==='account'&&x.ledgerAccountId&&x.isActive!==false);
867 check(contact&&active,'Treasury fixtures absent');
868 await FINORA.Router.go('treasury');await wait(180);
869 const tv=window.TreasuryView;
870 await tv.openAccountModal();
871 document.getElementById('accName').value='VM-only inactive bank A05';
872 document.getElementById('accInitialBalance').value='0';
873 await tv.saveAccount(null);
874 let secondary=(await db.getAll('treasury')).find(x=>
875 x.companyId===company.id&&x.recordType==='account'&&x.name==='VM-only inactive bank A05');
876 check(secondary?.ledgerAccountId,'Actual treasury account creation failed');
877 await tv.openAccountModal(secondary.id);
878 document.getElementById('accOwnerName').value='VM-only treasury account owner edit';
879 await tv.saveAccount(secondary.id);
880 secondary=await db.get('treasury',secondary.id);
881 check(secondary.ownerName==='VM-only treasury account owner edit',
882 'Treasury account edit did not persist through the installed form');
883 await db.put('treasury',{...secondary,isActive:false});
884 const counts=async()=>({
885 journals:(await db.getAll('journal_entries')).length,
886 payments:(await db.getAll('treasury')).filter(x=>x.recordType==='transaction').length
887 });
888 const before=await counts();
889 tv.openTransferModal();
890 check(document.getElementById('txToAccount'),'Native transfer form not open');
891 document.getElementById('txDate').value='1405/07/18';
892 document.getElementById('txAmount').value='40';
893 document.getElementById('txFromAccount').value=active.id;
894 document.getElementById('txToAccount').value=secondary.id;
895 await tv._saveTransaction('transfer');
896 let toast=[...document.querySelectorAll('.toast-error')].find(x=>x.textContent.includes('غیرفعال'));
897 check(toast,'Inactive bank transfer did not display rejection');
898 check(JSON.stringify(await counts())===JSON.stringify(before),'Rejected transfer wrote journals or cash');
899 toast.querySelector('.toast-close')?.click();
900 FINORA.Modal.close();
901 check(!document.querySelector('.toast-error'),'Expected transfer toast not dismissed');
902
903 // With no active bank, the real cheque status UI must reject settlement
904 // without changing posted status or writing a cash receipt.
905 await db.put('treasury',{...active,isActive:false});
906 await FINORA.Router.go('cheques');await wait(200);
907 const cv=window.ChequesView;
908 await cv.openChequeModal();
909 check(document.getElementById('chqSayad'),'Native cheque form absent');
910 document.getElementById('chqDirection').value='inbound';
911 document.getElementById('chqContact').value=contact.id;
912 document.getElementById('chqSayad').value='1234567890123489';
913 document.getElementById('chqAmount').value='90';
914 document.getElementById('chqIssueDate').value='1405/07/18';
915 document.getElementById('chqDueDate').value='1405/07/18';
916 await cv.saveCheque(null);
917 const cheque=(await db.getAll('cheques')).find(x=>x.companyId===company.id&&x.sayadNumber==='1234567890123489');
918 check(cheque?.financePosted&&cheque.status==='pending','Native cheque posting failed');
919 const journalCount=(await db.getAll('journal_entries')).length;
920 await cv.changeStatus(cheque.id);
921 check(document.getElementById('newStatus'),'Cheque status form missing');
922 const dateInput=document.getElementById('chqEventDate');
923 check(dateInput,'Native posted cheque must request the financial event date');
924 dateInput.value='1405/07/20'; // intentionally different from the cheque due date
925 document.getElementById('newStatus').value='cleared';
926 cv._onChequeStatusSelection();
927 check(document.getElementById('chqClearingAccount'),
928 'Explicit bank selection was not presented in posted cheque UI');
929 await cv._applyStatusChange(cheque.id);
930 toast=[...document.querySelectorAll('.toast-warning')].find(x=>
931 x.textContent.includes('حساب بانک یا صندوق را انتخاب کنید'));
932 check(toast,'Clearing without selected active bank did not visibly reject');
933 check((await db.get('cheques',cheque.id)).status==='pending'&&
934 (await db.getAll('journal_entries')).length===journalCount&&
935 !(await db.getAll('treasury')).some(t=>t.refChequeId===cheque.id),
936 'Rejected cheque clearance modified ledger or treasury');
937 toast.querySelector('.toast-close')?.click();
938 FINORA.Modal.close();
939 await db.put('treasury',active);
940 await db.put('treasury',{...secondary,isActive:true});
941 await FINORA.Router.go('treasury');await wait(180);await tv.reload();
942 const transferCountBefore=(await db.getAll('treasury')).filter(x=>
943 x.companyId===company.id&&x.recordType==='transaction'&&x.type==='transfer').length;
944 tv.openTransferModal();
945 check(document.getElementById('txFromAccount')&&document.getElementById('txToAccount'),
946 'Native positive transfer form did not open');
947 document.getElementById('txDate').value='1405/07/21';
948 document.getElementById('txAmount').value='1';
949 document.getElementById('txFromAccount').value=active.id;
950 document.getElementById('txToAccount').value=secondary.id;
951 await tv._saveTransaction('transfer');
952 const transfer=(await db.getAll('treasury')).find(x=>
953 x.companyId===company.id&&x.recordType==='transaction'&&x.type==='transfer'&&
954 x.amount===1&&x.fromAccountId===active.id&&x.toAccountId===secondary.id);
955 check(transfer&&(await db.getAll('treasury')).filter(x=>
956 x.companyId===company.id&&x.recordType==='transaction'&&x.type==='transfer').length===transferCountBefore+1,
957 'Valid transfer between active accounts did not persist exactly once');
958 await FINORA.Router.go('cheques');await wait(180);await cv.reload();
959 await cv.changeStatus(cheque.id);
960 document.getElementById('newStatus').value='cleared';
961 document.getElementById('chqEventDate').value='1405/07/20';
962 cv._onChequeStatusSelection();
963 const selected=document.getElementById('chqClearingAccount');
964 check([...selected.options].some(x=>x.value===secondary.id),
965 'Actual secondary bank not selectable in clearing UI');
966 selected.value=secondary.id; // bank other than the default
967 // The successful transfer above intentionally added a journal entry. Take
968 // a fresh baseline immediately before cheque approval, and scope the cash
969 // assertion to this cheque so unrelated valid postings cannot fail it.
970 const journalCountBeforeApproval=(await db.getAll('journal_entries')).length;
971 const chequeSettlementsBeforeApproval=(await db.getAll('treasury')).filter(t=>
972 t.refChequeId===cheque.id).length;
973 await cv._applyStatusChange(cheque.id);
974 const approve=document.querySelector('.modal-backdrop:last-of-type [data-action="confirm"]');
975 check(approve&&approve.textContent.includes('تأیید و ثبت وصول'),
976 'Actual bank clearance missing explicit secondary confirmation');
977 check((await db.get('cheques',cheque.id)).status==='pending'&&
978 (await db.getAll('journal_entries')).length===journalCountBeforeApproval&&
979 (await db.getAll('treasury')).filter(t=>t.refChequeId===cheque.id).length===
980 chequeSettlementsBeforeApproval,
981 'Cheque cleared before approval');
982 approve.click();
983 let cleared;
984 for(let i=0;i<60;i++){
985 cleared=await db.get('cheques',cheque.id);
986 if(cleared?.status==='cleared')break;
987 await wait(100);
988 }
989 const journal=await db.get('journal_entries',cleared.statusJournalId);
990 const settlement=(await db.getAll('treasury')).filter(t=>t.refChequeId===cheque.id);
991 const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal?.id);
992 check(cleared.status==='cleared'&&cleared.dueDate==='1405/07/18'&&
993 cleared.statusBusinessDate==='1405/07/20'&&cleared.clearingAccountId===secondary.id&&
994 cleared.clearingApprovedBy===FINORA.Auth.current().id&&
995 journal?.date==='1405/07/20'&&settlement.length===1&&
996 settlement[0].date==='1405/07/20'&&settlement[0].toAccountId===secondary.id&&
997 lines.some(x=>x.accountId===secondary.ledgerAccountId&&x.debit===90)&&
998 !lines.some(x=>x.accountId===active.ledgerAccountId&&x.debit===90),
999 'Native cheque clearance failed selected non-default bank accounting');
1000 check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
1001 'A05 native treasury scenario left error toast/modal');
1002 return { inactiveTransferRejected:true, invalidTransferRolledBack:true,
1003 validTransferPosted:true,treasuryAccountCreatedThroughForm:true,treasuryAccountEditPersisted:true,
1004 chequeCreatedThroughForm:true,disabledChequeClearingRejected:true, validChequeClearedExactlyOnce:true,
1005 chequeEventDateDifferentFromDueDate:true,
1006 explicitNondefaultClearingAccount:true,confirmationRequiredBeforeCash:true };
1007 }
1008
1009 async function nativeChequeThirdPartyEndorsement() {
1010 const wait=ms=>new Promise(r=>setTimeout(r,ms));
1011 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1012 const db=FINORA.Storage,company=await FINORA.Company.current();
1013 check(company?.id&&FINORA.Auth.isAdmin(),'A01 endorsement needs synthetic admin');
1014 const drawer=(await db.getAll('contacts')).find(c=>
1015 c.companyId===company.id&&c.name==='مشتری آزمایشی ویندوز');
1016 check(drawer,'Endorsement drawer fixture missing');
1017 const endorsee={id:'vm-a01-endorsee-contact',companyId:company.id,
1018 name:'تأمین‌کننده واگذاری آزمایشی',ownerUserId:FINORA.Auth.current().id};
1019 await db.put('contacts',endorsee);
1020 await FINORA.Router.go('cheques');await wait(130);
1021 const view=window.ChequesView;
1022 await view.reload();
1023 await view.openChequeModal();
1024 check(document.getElementById('chqSayad'),'Real native cheque create form missing');
1025 document.getElementById('chqDirection').value='inbound';
1026 document.getElementById('chqContact').value=drawer.id;
1027 document.getElementById('chqSayad').value='1234567890123490';
1028 document.getElementById('chqAmount').value='75';
1029 document.getElementById('chqIssueDate').value='1405/07/18';
1030 document.getElementById('chqDueDate').value='1405/07/18';
1031 await view.saveCheque(null);
1032 const cheque=(await db.getAll('cheques')).find(c=>
1033 c.companyId===company.id&&c.sayadNumber==='1234567890123490');
1034 check(cheque?.financePosted&&cheque.status==='pending','Endorsement cheque posting failed');
1035 await view.changeStatus(cheque.id);
1036 const status=document.getElementById('newStatus');
1037 const date=document.getElementById('chqEventDate');
1038 const endorseeSelect=document.getElementById('chqEndorsee');
1039 check(status&&date&&endorseeSelect,'Actual endorsement choice missing in native UI');
1040 status.value='spent';date.value='1405/07/20';
1041 view._onChequeStatusSelection();
1042 check(document.getElementById('chqEndorseeGroup').style.display!=='none',
1043 'Third-party contact selector was hidden');
1044 const counts=async()=>({
1045 journals:(await db.getAll('journal_entries')).length,
1046 corrections:(await db.getAll('document_corrections')).length,
1047 audits:(await db.getAll('audit_events')).length
1048 });
1049 const before=await counts();
1050 await view._applyStatusChange(cheque.id);
1051 check(!document.querySelector('.modal-footer [data-action="confirm"]'),
1052 'Endorsement without selected third party opened approval');
1053 check(JSON.stringify(await counts())===JSON.stringify(before)&&
1054 (await db.get('cheques',cheque.id)).status==='pending',
1055 'Missing endorsee wrote a financial event');
1056 const warning=[...document.querySelectorAll('.toast-warning')].find(x=>
1057 x.textContent.includes('دریافت‌کننده واگذاری'));
1058 check(warning,'Missing endorsee was not visibly rejected');
1059 warning.querySelector('.toast-close')?.click();
1060 endorseeSelect.value=endorsee.id;
1061 await view._applyStatusChange(cheque.id);
1062 const confirm=document.querySelector('.modal-backdrop:last-of-type [data-action="confirm"]');
1063 check(confirm&&confirm.textContent.includes('تأیید و ثبت واگذاری'),
1064 'Native endorsement has no separate explicit approval');
1065 check(JSON.stringify(await counts())===JSON.stringify(before)&&
1066 (await db.get('cheques',cheque.id)).status==='pending',
1067 'Endorsement posted before explicit confirmation');
1068 confirm.click();
1069 let endorsed;
1070 for(let i=0;i<60;i++){
1071 endorsed=await db.get('cheques',cheque.id);
1072 if(endorsed.status==='spent')break;
1073 await wait(100);
1074 }
1075 check(endorsed?.status==='spent'&&endorsed.endorseeContactId===endorsee.id&&
1076 endorsed.endorsementApprovedBy===FINORA.Auth.current().id&&
1077 endorsed.statusBusinessDate==='1405/07/20',
1078 'Native endorsement did not retain selected third party and approval');
1079 const journal=await db.get('journal_entries',endorsed.statusJournalId);
1080 const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal?.id);
1081 const payable=(await db.getAll('account_chart')).find(x=>
1082 x.companyId===company.id&&x.code==='201');
1083 const incoming=(await db.getAll('account_chart')).find(x=>
1084 x.companyId===company.id&&x.code==='105');
1085 check(journal?.date==='1405/07/20'&&lines.some(l=>
1086 l.accountId===payable?.id&&l.contactId===endorsee.id&&l.debit===75)&&
1087 lines.some(l=>l.accountId===incoming?.id&&l.contactId===drawer.id&&l.credit===75),
1088 'Endorsement GL was not correctly split between endorsee and drawer');
1089 const correction=(await db.getAll('document_corrections')).find(x=>
1090 x.sourceType==='cheque'&&x.sourceId===cheque.id&&x.correctionType==='endorsement');
1091 check(correction?.endorseeContactId===endorsee.id&&
1092 correction?.correlationId===journal.id&&correction?.approvedBy===FINORA.Auth.current().id,
1093 'Native endorsement lacks append-only trace and actor');
1094 check(!(await db.getAll('treasury')).some(x=>x.refChequeId===cheque.id),
1095 'Endorsement incorrectly created cash settlement');
1096 check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
1097 'Native endorsement left unexpected error or modal');
1098 return {missingEndorseeRejected:true,confirmationRequiredBeforeWrite:true,
1099 endorseeLedgerDimensionCorrect:true,drawerChequeAssetPreserved:true,
1100 appendOnlyEndorsementCorrelated:true,noPhantomCash:true};
1101 }
1102
1103 async function nativeTreasuryChequeReconciliation() {
1104 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1105 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1106 const storage=FINORA.Storage,company=await FINORA.Company.current();
1107 check(company?.id&&FINORA.Auth.isAdmin(),'A05 reconciliation requires synthetic admin');
1108 await FINORA.Router.go('accounting');await wait(130);
1109 const view=window.AccountingView;
1110 await view.switchTab('reconciliation');
1111 const original=await view.renderReconciliation();
1112 check(original.includes('چک‌های مالی'),'Native reconciliation does not show cheque controls');
1113 check(!original.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
1114 !original.includes('CHEQUE_CLEARING_CASH_COUNT'),
1115 'Real posted VM cheque failed reconciliation before fault injection');
1116 // Corrupt only a synthetic fixture in the disposable native VM, never
1117 // alter a customer accounting record. This probes read-only detection.
1118 const id='vm-a05-invalid-cheque-reconciliation';
1119 const broken={id,companyId:company.id,financePosted:true,
1120 direction:'inbound',status:'cleared',amount:90,journalId:'not-there',
1121 statusJournalId:'not-there-either'};
1122 await storage.put('cheques',broken);
1123 const before=(await storage.getAll('journal_entries')).length;
1124 const checked=await view.renderReconciliation();
1125 check(checked.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
1126 checked.includes('CHEQUE_STATUS_JOURNAL_MISSING')&&
1127 checked.includes('CHEQUE_CLEARING_CASH_COUNT'),
1128 'Native installed reconciliation failed to report malformed cheque');
1129 check((await storage.getAll('journal_entries')).length===before&&
1130 (await storage.get('cheques',id))?.status==='cleared',
1131 'Read-only reconciliation changed journal or cheque state');
1132 await storage.delete('cheques',id);
1133 const after=await view.renderReconciliation();
1134 check(!after.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
1135 !after.includes('CHEQUE_CLEARING_CASH_COUNT'),
1136 'Reconciliation still reports synthetic cheque after fixture removal');
1137 await view.switchTab('journals');
1138 check(!document.querySelector('.toast-error'),'A05 reconciliation left toast');
1139 return {livePostedChequeReviewed:true,chequeDiscrepanciesDetected:true,
1140 reportingReadOnly:true,fixtureRemoved:true};
1141 }
1142
1143 async function nativeReturnCashSettlementGuardrails() {
1144 const wait=ms=>new Promise(r=>setTimeout(r,ms));
1145 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1146 const db=FINORA.Storage,company=await FINORA.Company.current();
1147 const sale=(await db.getAll('invoices')).find(x=>
1148 x.companyId===company.id&&x.kind==='sale'&&x.grandTotal===600);
1149 const returned=(await db.getAll('invoices')).find(x=>
1150 x.companyId===company.id&&x.kind==='sale_return'&&x.originalInvoiceId===sale?.id);
1151 check(sale?.paidAmount===200&&returned?.grandTotal===200,
1152 'A01 net-refund native sale/return prerequisite absent');
1153 await FINORA.Router.go('treasury');await wait(170);
1154 const view=window.TreasuryView;
1155 const before=()=>Promise.all(['journal_entries','treasury','settlements'].map(async name=>
1156 (await db.getAll(name)).length));
1157 const testReceipt=async(amount)=>{
1158 await view.openReceiptModal();
1159 const sel=document.getElementById('txInvoiceRef');
1160 check(sel&&[...sel.options].some(x=>x.value===sale.id),
1161 'Real treasury UI does not list the unpaid original sale');
1162 sel.value=sale.id;view._onInvoiceSelection();
1163 document.getElementById('txAmount').value=String(amount);
1164 document.getElementById('txDate').value='1405/07/18';
1165 await view._saveTransaction('receipt');
1166 };
1167 const start=await before();
1168 await testReceipt(201);
1169 let toast=[...document.querySelectorAll('.toast-error')].find(x=>x.textContent.includes('مانده خالص'));
1170 check(toast,'Overcollection after posted return not visibly rejected');
1171 check(JSON.stringify(await before())===JSON.stringify(start),
1172 'Rejected overcollection wrote a ledger, treasury or settlement');
1173 toast.querySelector('.toast-close')?.click();
1174 FINORA.Modal.close();
1175 await testReceipt(200);
1176 check((await db.get('invoices',sale.id)).paidAmount===400,
1177 'Allowed residual collection did not reach net post-return amount');
1178 await view.openPaymentModal();
1179 const sel=document.getElementById('txInvoiceRef');
1180 check(sel&&[...sel.options].some(x=>x.value===returned.id),
1181 'Real treasury UI cannot select the customer return');
1182 sel.value=returned.id;view._onInvoiceSelection();
1183 document.getElementById('txAmount').value='1';
1184 document.getElementById('txDate').value='1405/07/18';
1185 const preRefund=await before();
1186 document.getElementById('txReturnReason').value='goods_return';
1187 await view._saveTransaction('payment');
1188 let approve=document.querySelector('.modal-footer [data-action="confirm"]');
1189 check(approve,'Native refund must explicitly ask for confirmation');
1190 approve.click();
1191 for(let i=0;i<30;i++){
1192 toast=[...document.querySelectorAll('.toast-error')].find(x=>
1193 x.textContent.includes('بازپرداخت مجاز'));
1194 if(toast)break;
1195 await wait(100);
1196 }
1197 check(toast,'Cash refund with zero actual paid customer credit was not rejected');
1198 check(JSON.stringify(await before())===JSON.stringify(preRefund),
1199 'Rejected customer refund wrote a ledger, treasury or settlement');
1200 toast.querySelector('.toast-close')?.click();FINORA.Modal.close();
1201 check(!document.querySelector('.toast-error')&&!document.querySelector('.modal-backdrop'),
1202 'Native A01 cash cap left an error toast/modal');
1203
1204 // Establish a real, paid customer credit in the installed WebView2 app:
1205 // sale 600, cash received 400, total returns 400 -> refund cap 200.
1206 // Post a second 200-rial return through the actual invoice UI.
1207 const contact=await db.get('contacts',sale.contactId);
1208 const product=(await db.getAll('products')).find(p=>p.code==='VM-E2E-100');
1209 check(contact&&product,'Native positive refund requires customer and product');
1210 await FINORA.Router.go('invoices');await wait(180);
1211 await window.InvoiceFormView.open();await wait(160);
1212 document.getElementById('invKind').value='sale_return';
1213 await window.InvoiceFormView._onKindChange();
1214 const original=document.getElementById('invOriginalInvoice');
1215 check(original&&[...original.options].some(x=>x.value===sale.id),
1216 'Native positive refund original invoice selector absent');
1217 original.value=sale.id;
1218 document.getElementById('invDate').value='1405/07/18';
1219 const contactSearch=document.getElementById('invContactSearch');
1220 contactSearch.value=contact.name;
1221 window.InvoiceFormView._showContactOptions(true);
1222 const contactItem=document.querySelector('.contact-option[data-id="'+contact.id+'"]');
1223 check(contactItem,'Native positive refund contact missing');
1224 contactItem.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
1225 const productSearch=document.querySelector('.row-product-search');
1226 productSearch.value=product.code;
1227 window.InvoiceFormView._showProductOptions(0,true);
1228 const productItem=document.querySelector('.product-option[data-id="'+product.id+'"]');
1229 check(productItem,'Native positive refund product missing');
1230 productItem.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
1231 document.querySelector('.row-qty').value='1';
1232 window.InvoiceFormView._onFieldChange(0,'qty','1');
1233 document.querySelector('.row-price').value='200';
1234 window.InvoiceFormView._onFieldChange(0,'price','200');
1235 document.getElementById('invPayment').value='credit';
1236 window.InvoiceFormView._onPaymentChange();
1237 await window.InvoiceFormView._save(false);await wait(170);
1238 check(!document.querySelector('.toast-error'),'Second synthetic return failed in native UI');
1239 const second=(await db.getAll('invoices')).find(x=>
1240 x.kind==='sale_return'&&x.originalInvoiceId===sale.id&&x.id!==returned.id);
1241 check(second?.grandTotal===200&&second.paidAmount===0,
1242 'Second posted customer credit document missing');
1243 await FINORA.Router.go('treasury');await wait(170);
1244 await view.openPaymentModal();
1245 const select=document.getElementById('txInvoiceRef');
1246 check(select&&[...select.options].some(x=>x.value===second.id),
1247 'Native positive refund return not selectable in treasury UI');
1248 select.value=second.id;view._onInvoiceSelection();
1249 document.getElementById('txAmount').value='100';
1250 document.getElementById('txDate').value='1405/07/18';
1251 document.getElementById('txReturnReason').value='quality_issue';
1252 const beforeApproval=await before();
1253 await view._saveTransaction('payment');
1254 approve=document.querySelector('.modal-footer [data-action="confirm"]');
1255 check(approve,'Native accepted refund missing explicit confirmation dialog');
1256 check(JSON.stringify(await before())===JSON.stringify(beforeApproval),
1257 'Opening approval dialog must not post cash or journal');
1258 approve.click();
1259 let refund=null;
1260 for(let i=0;i<40;i++){
1261 refund=(await db.getAll('treasury')).find(x=>
1262 x.recordType==='transaction'&&x.refInvoiceId===second.id&&x.type==='payment');
1263 if(refund)break;
1264 await wait(100);
1265 }
1266 check(!document.querySelector('.toast-error'),'Authorized native customer refund failed');
1267 const correction=(await db.getAll('document_corrections')).find(x=>
1268 x.correctionType==='settlement_refund'&&x.sourceId===second.id&&
1269 x.resultId===refund?.id);
1270 const audit=(await db.getAll('audit_events')).find(x=>
1271 x.sourceId===refund?.journalId&&x.correlationId===correction?.correlationId);
1272 check(refund?.amount===100&&correction?.amount===100&&
1273 correction.reasonCode==='quality_issue'&&
1274 correction.actionCode==='customer_credit_refund'&&
1275 correction.approvedBy===FINORA.Auth.current()?.id&&
1276 correction.approvalMethod==='explicit_confirmation'&&audit&&
1277 (await db.get('invoices',second.id))?.paidAmount===100,
1278 'Native refund correction, treasury, audit or invoice linkage is invalid');
1279 check(!document.querySelector('.modal-backdrop'),
1280 'Native refund left an unexpected payment dialog');
1281 return {overcollectionRejectedWithoutWrites:true,netReceiptAccepted:true,
1282 nonexistentRefundCreditRejected:true,realTreasuryInvoiceSelector:true,
1283 authorizedRefundTracedInInstalledWebView2:true};
1284 }
1285
1286 async function nativeBackupRestore() {
1287 const check = (value, message) => { if (!value) throw Error(message); };
1288 const S = FINORA.Storage;
1289 const company = (await S.getAll('companies'))[0];
1290 const temporary = await S.put('contacts', {
1291 id: 'native-vm-backup-roundtrip', companyId: company.id, name: 'فقط آزمون بازگردانی'
1292 });
1293 const snapshot = await S.exportAll();
1294 check(snapshot.version === 7 && snapshot.app === 'Factor-easyPro',
1295 'invalid native backup envelope');
1296 check(snapshot.data.contacts.some(x => x.id === temporary.id),
1297 'native backup omitted test contact');
1298 check(snapshot.data.users.every(u => !('pwHash' in u) && !('pwSalt' in u)),
1299 'native backup leaked user password derivation metadata');
1300 await S.delete('contacts', temporary.id);
1301 check(!(await S.get('contacts', temporary.id)), 'test contact was not deleted');
1302 await S.importAll({
1303 app: snapshot.app, version: snapshot.version,
1304 data: { contacts: snapshot.data.contacts.filter(c => c.id === temporary.id) }
1305 });
1306 check((await S.get('contacts', temporary.id))?.name === 'فقط آزمون بازگردانی',
1307 'native backup restore did not recover contact');
1308
1309 const sale = (await S.getAll('invoices')).find(i => i.kind === 'sale' && i.financePosted);
1310 check(sale, 'posted sale missing for restore immutability');
1311 let denied = false;
1312 try {
1313 await S.importAll({
1314 app: snapshot.app, version: snapshot.version,
1315 data: {
1316 contacts: [{id:'should-rollback-native',companyId:company.id,name:'Reject'}],
1317 invoices: [{...sale,grandTotal:sale.grandTotal+1}]
1318 }
1319 });
1320 } catch (_) { denied = true; }
1321 check(denied, 'tampered posted sale backup must fail');
1322 check(!(await S.get('contacts','should-rollback-native')),
1323 'rejected full backup wrote a contact anyway');
1324 check((await S.get('invoices',sale.id)).grandTotal===sale.grandTotal,
1325 'tampered posted sale modified the actual financial document');
1326 return { backupSchema: snapshot.version, credentialsExcluded: true,
1327 contactRoundtrip: true, tamperedInvoiceRejectedAtomically: true };
1328 }
1329
1330 async function invoicePrintLayout() {
1331 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
1332 const check = (value, message) => { if (!value) throw Error(message); };
1333 const sale = (await FINORA.Storage.getAll('invoices'))
1334 .find(x => x.kind === 'sale' && x.financePosted);
1335 check(sale, 'posted invoice for print preview missing');
1336 await FINORA.Router.go('invoices');
1337 await wait(200);
1338 await window.InvoicesView.printInvoice(sale.id);
1339 await wait(320);
1340 const dialog = document.querySelector('.modal-backdrop');
1341 check(dialog, 'native print settings dialog did not open');
1342 const labels = dialog.textContent || '';
1343 check(labels.includes('قالب چاپ') && labels.includes('A4'),
1344 'RTL print template or paper settings missing');
1345 check(document.documentElement.dir === 'rtl',
1346 'document is not marked RTL');
1347 FINORA.Modal.close();
1348 return { rtl: true, printSettings: true, templates: true,
1349 physicalPrinterTest: 'not-covered' };
1350 }
1351
1352 async function fiscalCloseGuardrails() {
1353 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
1354 const check = (ok, message) => { if (!ok) throw Error(message); };
1355 const store = FINORA.Storage;
1356 const company = await FINORA.Company.current();
1357 check(company?.id && FINORA.Auth.isAdmin(), 'Fiscal close test must use a synthetic admin');
1358 await FINORA.Router.go('accounting');
1359 await wait(180);
1360 const view = window.AccountingView;
1361 check(view, 'Native accounting view was not mounted');
1362 await view.switchTab('periods');
1363 const testName = 'A05 VM-only guarded closing period';
1364 view.openPeriodModal();
1365 check(document.getElementById('acPeriodName'), 'Fiscal period creation form missing');
1366 document.getElementById('acPeriodName').value = testName;
1367 document.getElementById('acPeriodStart').value = '1404/01/01';
1368 document.getElementById('acPeriodEnd').value = '1404/12/29';
1369 await view.savePeriod();
1370 check(!document.querySelector('.toast-error'), 'Creating isolated fiscal period failed');
1371 const period = (await store.getAll('fiscal_periods'))
1372 .find(x => x.companyId === company.id && x.name === testName);
1373 check(period && period.closed === false, 'Synthetic fiscal period did not persist as open');
1374 const warehouses = (await store.getAll('warehouses')).filter(x => x.companyId === company.id);
1375 check(warehouses.length, 'Warehouse prerequisite missing');
1376 const stocktakeId = 'vm-a05-draft-stocktake';
1377 await store.put('stocktakes', {
1378 id: stocktakeId, companyId: company.id,
1379 warehouseId: warehouses[0].id, status: 'draft'
1380 });
1381 const auditCount = (await store.getAll('audit_events'))
1382 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length;
1383 const confirmClose = () => {
1384 view.closePeriod(period.id);
1385 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
1386 check(confirm, 'Real fiscal closure approval dialog missing');
1387 confirm.click();
1388 };
1389 confirmClose();
1390 let message = null;
1391 for (let i = 0; i < 60; i++) {
1392 message = [...document.querySelectorAll('.toast-error')]
1393 .find(x => x.textContent.includes('انبارگردانی باز'));
1394 if (message) break;
1395 await wait(100);
1396 }
1397 check(message, 'Closing with an open stocktake was not rejected visibly');
1398 check((await store.get('fiscal_periods', period.id))?.closed === false,
1399 'Open stocktake allowed fiscal closure');
1400 check((await store.getAll('audit_events'))
1401 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length === auditCount,
1402 'Rejected fiscal closing created an audit receipt');
1403 message.querySelector('.toast-close')?.click();
1404 check(!document.querySelector('.toast-error'), 'Expected fiscal rejection toast remained');
1405 await store.delete('stocktakes', stocktakeId);
1406
1407 // A05: another real fiscal-close attempt must still be blocked while
1408 // there is an unfinished draft ledger in the same isolated period.
1409 const draftId = 'vm-a05-unposted-draft-journal';
1410 await store.put('journal_entries', {
1411 id: draftId, companyId: company.id, periodId: period.id,
1412 date: '1404/06/15', status: 'draft', sourceType: 'manual',
1413 description: 'VM-only pending draft prevents closure'
1414 });
1415 confirmClose();
1416 let draftToast = null;
1417 for (let i = 0; i < 60; i++) {
1418 draftToast = [...document.querySelectorAll('.toast-error')]
1419 .find(x => x.textContent.includes('اسناد پیش‌نویس'));
1420 if (draftToast) break;
1421 await wait(100);
1422 }
1423 check(draftToast, 'Native fiscal closure ignored the pending draft journal');
1424 check((await store.get('fiscal_periods', period.id))?.closed === false,
1425 'Rejected draft-journal closure changed period state');
1426 check((await store.getAll('audit_events'))
1427 .filter(x => x.companyId === company.id &&
1428 x.eventType === 'period_closed').length === auditCount,
1429 'Rejected draft-journal closure wrote a successful close audit');
1430 draftToast.querySelector('.toast-close')?.click();
1431 check(!document.querySelector('.toast-error'),
1432 'Expected unposted-journal rejection toast remained visible');
1433 await store.delete('journal_entries', draftId);
1434 confirmClose();
1435 let closed = null;
1436 for (let i = 0; i < 70; i++) {
1437 closed = await store.get('fiscal_periods', period.id);
1438 if (closed?.closed) break;
1439 await wait(100);
1440 }
1441 check(closed?.closed === true && closed.status === 'closed',
1442 'Approved fiscal close was not committed');
1443 const closureAudits = (await store.getAll('audit_events'))
1444 .filter(x => x.companyId === company.id &&
1445 x.eventType === 'period_closed' && x.sourceId === period.id);
1446 check(closureAudits.length === 1 &&
1447 closureAudits[0].actorId === FINORA.Auth.current().id,
1448 'Successful fiscal closure did not produce exactly one actor-scoped audit');
1449 // Already-closed periods must not be closed again via the actual confirmation
1450 // action, nor silently insert another period_closed audit receipt.
1451 confirmClose();
1452 let closedToast = null;
1453 for (let i = 0; i < 60; i++) {
1454 closedToast = [...document.querySelectorAll('.toast-error')]
1455 .find(x => x.textContent.includes('دوره مالی بسته است'));
1456 if (closedToast) break;
1457 await wait(100);
1458 }
1459 check(closedToast, 'Duplicate native close did not visibly reject');
1460 check((await store.getAll('audit_events'))
1461 .filter(x => x.companyId === company.id &&
1462 x.eventType === 'period_closed' && x.sourceId === period.id).length === 1,
1463 'Duplicate fiscal close created a second audit receipt');
1464 closedToast.querySelector('.toast-close')?.click();
1465 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
1466 'Fiscal guardrail test left an unexpected UI error or modal');
1467 return {
1468 openStocktakeBlocked: true,
1469 draftJournalBlocked: true,
1470 failedCloseRolledBack: true,
1471 successfulCloseCommitted: true,
1472 duplicateCloseRejected: true,
1473 singleAuditReceipt: true
1474 };
1475 }
1476
1477 async function openingDryRunWithExistingActivity() {
1478 const check = (ok, message) => { if (!ok) throw Error(message); };
1479 const store = FINORA.Storage;
1480 const company = await FINORA.Company.current();
1481 check(company?.id && FINORA.Auth.isAdmin(),
1482 'Native A02 opening dry-run requires a synthetic administrator');
1483 await FINORA.Router.go('accounting');
1484 const view = window.AccountingView;
1485 check(view, 'AccountingView missing in actual installed app');
1486 await view.switchTab('opening');
1487 const input = document.getElementById('openingFileInput');
1488 const reportHost = document.getElementById('openingPreviewReport');
1489 check(input && reportHost, 'Opening balance JSON dry-run form is missing');
1490 const periods = (await store.getAll('fiscal_periods'))
1491 .filter(x => x.companyId === company.id);
1492 const period = periods.find(x => !x.closed);
1493 check(period, 'An active period is required for A02 blocked historical migration test');
1494 const priorJournals = (await store.getAll('journal_entries'))
1495 .filter(x => x.companyId === company.id && x.status === 'posted');
1496 check(priorJournals.length > 0,
1497 'Financial activity prerequisite missing: opening must be blocked after posting');
1498 const before = {
1499 entries: (await store.getAll('journal_entries')).length,
1500 lines: (await store.getAll('journal_lines')).length,
1501 events: (await store.getAll('audit_events')).length,
1502 settings: (await store.getAll('settings')).length
1503 };
1504 const fixture = {
1505 periodId: period.id, openingDate: period.startDate,
1506 lines: [], contacts: [], stock: [], cash: []
1507 };
1508 const file = new File([JSON.stringify(fixture)], 'vm-only-a02-opening.json',
1509 { type: 'application/json' });
1510 Object.defineProperty(input, 'files', { configurable: true, value: [file] });
1511 view.resetOpeningPreview();
1512 await view.previewOpeningFile();
1513 const review = view._openingReview;
1514 check(review && review.readiness === 'blocked' && review.writePerformed === false,
1515 'Native opening dry-run failed to block incompatible historical data');
1516 check(review.issues.includes('EXISTING_POSTED_JOURNALS') &&
1517 review.issues.includes('MISSING_OPENING_JOURNAL_LINES'),
1518 'Native blocked opening preview omitted journal issues');
1519 check(reportHost.textContent.includes('ثبت مسدود') &&
1520 reportHost.querySelector('button[disabled]'),
1521 'Native opening UI offered an actionable posting button despite issues');
1522 const after = {
1523 entries: (await store.getAll('journal_entries')).length,
1524 lines: (await store.getAll('journal_lines')).length,
1525 events: (await store.getAll('audit_events')).length,
1526 settings: (await store.getAll('settings')).length
1527 };
1528 check(JSON.stringify(before) === JSON.stringify(after),
1529 'Opening preview wrote to ledger, audit or settings');
1530 check(!document.querySelector('.toast-error'),
1531 'Blocked A02 dry-run unexpectedly threw rather than reporting issues');
1532 await view.switchTab('journals');
1533 return {
1534 priorActivityBlocked: true,
1535 discrepancyCodesVisible: true,
1536 commitActionDisabled: true,
1537 zeroWrites: true
1538 };
1539 }
1540
1541
1542
1543 async function nativeInvoiceQuickAddAndPrint() {
1544 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1545 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1546 const db=FINORA.Storage,company=await FINORA.Company.current();
1547 check(company?.id&&FINORA.Auth.isAdmin(),'Q01 invoice quick-add test requires the synthetic administrator');
1548 await FINORA.Router.go('invoices');await wait(160);
1549 await window.InvoiceFormView.open();await wait(120);
1550 window.InvoiceFormView._openQuickContact();
1551 document.getElementById('qcName').value='VM-only Q01 quick contact';
1552 document.getElementById('qcMobile').value='09120000001';
1553 await window.InvoiceFormView._saveQuickContact();
1554 const contactId=document.getElementById('invContact').value;
1555 check(contactId&&document.getElementById('invContactSearch').value==='VM-only Q01 quick contact',
1556 'Quick contact was not selected in the parent invoice');
1557 window.InvoiceFormView._openQuickProduct();
1558 document.getElementById('qpCode').value='VM-Q01-QUICK-PRODUCT';
1559 document.getElementById('qpName').value='VM-only Q01 quick service';
1560 document.getElementById('qpUnit').value='عدد';
1561 document.getElementById('qpBuyPrice').value='100';
1562 document.getElementById('qpSellPrice').value='500';
1563 document.getElementById('qpTrackInventory').checked=false;
1564 await window.InvoiceFormView._saveQuickProduct();
1565 const productId=document.querySelector('#itemsBody .row-product')?.value;
1566 check(productId&&document.querySelector('.row-product-search')?.value==='VM-only Q01 quick service',
1567 'Quick product was not selected in the parent invoice');
1568 document.getElementById('invDate').value='1405/07/18';
1569 document.getElementById('invDescription').value='VM-only Q01 quick invoice print';
1570 document.querySelector('.row-qty').value='2';
1571 window.InvoiceFormView._onFieldChange(0,'qty','2');
1572 document.querySelector('.row-price').value='500';
1573 window.InvoiceFormView._onFieldChange(0,'price','500');
1574 await window.InvoiceFormView._save(true);
1575 await wait(550);
1576 const invoice=(await db.getAll('invoices')).find(x=>
1577 x.companyId===company.id&&x.contactId===contactId&&
1578 x.description==='VM-only Q01 quick invoice print');
1579 check(invoice?.financePosted&&invoice.items?.some(x=>x.productId===productId),
1580 'Save-and-print did not commit the quick invoice and its quick-added product');
1581 check(window.InvoicePrint?.currentInvoiceId===invoice.id&&document.getElementById('prPaper'),
1582 'Save-and-print did not open the actual invoice print settings modal');
1583 const original=window.InvoicePrint._openPrintWindow;
1584 let rendered='';
1585 try {
1586 window.InvoicePrint._openPrintWindow=html=>{rendered=String(html);};
1587 await window.InvoicePrint._print();
1588 } finally {
1589 window.InvoicePrint._openPrintWindow=original;
1590 }
1591 check(rendered.includes('dir="rtl"')&&rendered.includes('VM-only Q01 quick contact')&&
1592 rendered.includes('VM-only Q01 quick service'),
1593 'Actual invoice print handler did not render the saved invoice in RTL');
1594 check(!document.querySelector('.modal-backdrop'),'Invoice print test left a modal open');
1595 return {quickContactCreated:true,quickProductCreated:true,saveAndPrintOpened:true,
1596 invoicePrintRendered:true,invoicePosted:true};
1597 }
1598
1599 async function nativeAuxiliaryPrintRendering() {
1600 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1601 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1602 const company=await FINORA.Company.current(),db=FINORA.Storage;
1603 const products=(await db.getAll('products')).filter(x=>x.companyId===company.id);
1604 const contacts=(await db.getAll('contacts')).filter(x=>x.companyId===company.id);
1605 check(products.length>0&&contacts.length>0,'Synthetic product/contact fixtures are missing for print rendering');
1606 const originalOpen=window.open;
1607 let capture=null,productPrints=0,contactPrints=0;
1608 window.open=()=>({
1609 document:{
1610 write(value){capture.html+=String(value);},
1611 close(){capture.closed=true;}
1612 },
1613 focus(){capture.focused=true;},
1614 print(){capture.printed=true;}
1615 });
1616 try {
1617 for(const product of products) {
1618 capture={html:'',closed:false,focused:false,printed:false};
1619 await window.StockKardexModal._printKardex(product.id);
1620 await wait(650);
1621 check(capture.html.includes('<html lang="fa" dir="rtl">')&&
1622 capture.html.includes('کاردکس کالا')&&capture.html.includes(product.name)&&
1623 capture.closed&&capture.printed,
1624 'Kardex print did not produce a complete RTL document for '+product.id);
1625 productPrints++;
1626 }
1627 for(const contact of contacts) {
1628 capture={html:'',closed:false,focused:false,printed:false};
1629 await window.ContactLedgerModal._printLedger(contact.id);
1630 await wait(650);
1631 check(capture.html.includes('<html lang="fa" dir="rtl">')&&
1632 capture.html.includes('صورت‌حساب شخص')&&capture.html.includes(contact.name)&&
1633 capture.closed&&capture.printed,
1634 'Contact ledger print did not produce a complete RTL document for '+contact.id);
1635 contactPrints++;
1636 }
1637 await FINORA.Router.go('reports');await wait(260);
1638 capture={html:'',closed:false,focused:false,printed:false};
1639 window.ReportsView._printReport();
1640 await wait(650);
1641 check(capture.html.includes('<html lang="fa" dir="rtl">')&&
1642 capture.html.includes('گزارش سود و زیان')&&capture.closed&&capture.printed,
1643 'Reports print did not produce a complete RTL document');
1644 } finally {
1645 window.open=originalOpen;
1646 }
1647 return {kardexPrints:productPrints,contactLedgerPrints:contactPrints,
1648 reportsPrintRendered:true,allDocumentsRtl:true,physicalPrinter:'not-tested'};
1649 }
1650
1651 async function nativeExpenseFormAndCategory() {
1652 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1653 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1654 const db=FINORA.Storage,company=await FINORA.Company.current();
1655 check(company?.id&&FINORA.Auth.isAdmin(),'Expense UI test requires a synthetic administrator');
1656 await FINORA.Router.go('expenses');await wait(160);
1657 const view=window.ExpensesView;
1658 await view.openExpenseModal();
1659 const originalPrompt=window.prompt;
1660 try {
1661 window.prompt=()=> 'VM-only Q01 expense category';
1662 await view._promptNewCategory();
1663 } finally {
1664 window.prompt=originalPrompt;
1665 }
1666 check(document.getElementById('expCategory')?.value==='VM-only Q01 expense category',
1667 'New expense category was not selected in the form');
1668 document.getElementById('expDate').value='1405/07/18';
1669 document.getElementById('expAmount').value='1234';
1670 document.getElementById('expMethod').value='cash';
1671 document.getElementById('expRef').value='Q01-EXPENSE-001';
1672 document.getElementById('expDesc').value='VM-only Q01 expense form';
1673 await view.saveExpense(null);await wait(180);
1674 const expense=(await db.getAll('expenses')).find(x=>
1675 x.companyId===company.id&&x.refNumber==='Q01-EXPENSE-001');
1676 check(expense?.amount===1234&&expense.kind==='expense'&&
1677 expense.category==='VM-only Q01 expense category'&&expense.financePosted===true,
1678 'Expense UI did not persist and post the synthetic expense');
1679 check((await db.getAll('journal_entries')).some(x=>
1680 x.companyId===company.id&&x.sourceId===expense.id&&x.status==='posted'),
1681 'Expense UI did not create its posted journal');
1682
1683 // A posted expense is immutable through the edit form. Attempt the real UI
1684 // path and prove the record and posted journal remain unchanged.
1685 const postedBeforeEdit = JSON.stringify(await db.get('expenses', expense.id));
1686 await view.editExpense(expense.id);
1687 await wait(60);
1688 document.getElementById('expDesc').value = 'must not overwrite posted expense';
1689 const postedEditSave = [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
1690 .find(button => !button.disabled && /ذخیره/.test(button.textContent));
1691 check(postedEditSave, 'Posted expense edit form save button is missing');
1692 postedEditSave.click();
1693 await wait(100);
1694 check(JSON.stringify(await db.get('expenses', expense.id)) === postedBeforeEdit &&
1695 FINORA.Modal.stack.length === 1 && !!document.querySelector('.toast-error'),
1696 'Posted expense was changed by the direct edit UI path');
1697 FINORA.Modal.close();
1698 document.querySelectorAll('.toast .toast-close').forEach(button => button.click());
1699
1700 const draftId = 'exp_q01_synthetic_edit_draft';
1701 const user = FINORA.Auth.current();
1702 await db.put('expenses', {
1703 id: draftId, companyId: company.id, ownerUserId: user.id,
1704 kind: 'expense', category: 'Q01 draft-only edit', amount: 4321,
1705 date: '1405/07/18', method: 'cash', description: 'before UI edit',
1706 refNumber: 'Q01-EXPENSE-DRAFT-EDIT', financePosted: false
1707 });
1708 try {
1709 await view.editExpense(draftId);
1710 await wait(60);
1711 check(document.getElementById('expDesc')?.value === 'before UI edit',
1712 'Expense edit form did not load the draft fixture');
1713 document.getElementById('expDesc').value = 'after UI edit';
1714 const editSave = [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
1715 .find(button => !button.disabled && /ذخیره/.test(button.textContent));
1716 check(editSave, 'Expense edit save button is missing');
1717 editSave.click();
1718 let edited = null;
1719 for (let i = 0; i < 60; i++) {
1720 edited = await db.get('expenses', draftId);
1721 if (edited?.description === 'after UI edit' && FINORA.Modal.stack.length === 0) break;
1722 await wait(100);
1723 }
1724 check(edited?.description === 'after UI edit' && edited.financePosted === false,
1725 'Draft expense did not persist through the edit form');
1726 } finally {
1727 if (await db.get('expenses', draftId)) await db.delete('expenses', draftId);
1728 }
1729 return {expenseCreatedThroughForm:true,customCategorySelected:true,
1730 expenseJournalPosted:true,postedExpenseEditRejected:true,draftExpenseEditedThroughForm:true};
1731 }
1732
1733 async function nativeAccountingJournalAndExports() {
1734 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1735 const db=FINORA.Storage,company=await FINORA.Company.current();
1736 check(company?.id&&FINORA.Auth.isAdmin(),'Manual journal UI test requires a synthetic administrator');
1737 await FINORA.Router.go('accounting');
1738 const view=window.AccountingView;
1739 await view.refresh();
1740 const period=view.periods.find(x=>!x.closed);
1741 check(period,'An open fiscal period is required for manual journal UI testing');
1742 const postable=view.accounts.filter(a=>a.level!=='group'&&a.active!==false&&
1743 a.postable!==false&&!view.accounts.some(child=>child.parentCode===a.code));
1744 check(postable.length>=2,'Two postable accounts are required for a balanced manual journal');
1745 const used=new Set(view.accounts.map(a=>String(a.code)));
1746 const groupCode=['9','8','7','6','0'].find(x=>!used.has(x));
1747 check(groupCode,'No unused synthetic group account code available');
1748 view.openAccountModal();
1749 document.getElementById('acCode').value=groupCode;
1750 document.getElementById('acName').value='VM-only Q01 journal test group';
1751 document.getElementById('acLevel').value='group';
1752 document.getElementById('acType').value='expense';
1753 view.toggleParent();
1754 await view.saveAccount();
1755 check(view.accounts.some(x=>String(x.code)===groupCode&&x.level==='group'),
1756 'Manual chart-of-accounts form did not persist the synthetic group');
1757 const description='VM-only Q01 manual journal draft';
1758 await view.openJournalModal();
1759 check(document.getElementById('acJournalLines'),'Manual journal form did not open');
1760 const initialRows=document.querySelectorAll('#acJournalLines .ac-journal-line');
1761 check(initialRows.length===2,'Manual journal must start with two rows');
1762 view.addJournalRow();
1763 check(document.querySelectorAll('#acJournalLines .ac-journal-line').length===3,
1764 'Add journal row did not append a third line');
1765 const addedRow = document.querySelectorAll('#acJournalLines .ac-journal-line')[2];
1766 const removeAddedRow = addedRow.querySelector('button[onclick*="closest"]');
1767 check(removeAddedRow, 'Added journal row remove button is missing');
1768 removeAddedRow.click();
1769 check(document.querySelectorAll('#acJournalLines .ac-journal-line').length===2,
1770 'Journal row remove button did not restore the original two-row draft');
1771 document.getElementById('acJournalPeriod').value=period.id;
1772 document.getElementById('acJournalDate').value=period.startDate;
1773 document.getElementById('acJournalDescription').value=description;
1774 const rows=[...document.querySelectorAll('#acJournalLines .ac-journal-line')];
1775 rows[0].querySelector('.ac-line-account').value=postable[0].id;
1776 rows[0].querySelector('.ac-line-debit').value='100';
1777 rows[0].querySelector('.ac-line-credit').value='0';
1778 rows[1].querySelector('.ac-line-account').value=postable[1].id;
1779 rows[1].querySelector('.ac-line-debit').value='0';
1780 rows[1].querySelector('.ac-line-credit').value='100';
1781 await view.saveJournal('draft');
1782 let draft=(await db.getAll('journal_entries')).find(x=>
1783 x.companyId===company.id&&x.description===description&&x.status==='draft');
1784 check(draft,'Manual journal draft did not persist');
1785 const postedDescription='VM-only Q01 manual journal posted';
1786 await view.openJournalModal(draft.id);
1787 document.getElementById('acJournalDescription').value=postedDescription;
1788 await view.saveJournal('posted');
1789 const posted=(await db.getAll('journal_entries')).find(x=>
1790 x.companyId===company.id&&x.description===postedDescription&&x.status==='posted');
1791 check(posted&&posted.debit===100&&posted.credit===100,
1792 'Balanced draft was not posted through the manual journal form');
1793 await view.showJournal(posted.id);
1794 const detailsDialog = FINORA.Modal.stack.at(-1)?.card;
1795 check(detailsDialog?.textContent.includes(postedDescription),
1796 'Posted journal details did not open from the UI');
1797 const closeDetails = detailsDialog.querySelector('.modal-footer button');
1798 check(closeDetails, 'Posted journal details close action is missing');
1799 closeDetails.click();
1800 check(FINORA.Modal.stack.length === 0, 'Posted journal details dialog did not close');
1801 view.openReversal(posted.id);
1802 check(document.getElementById('acReversalId'),'Manual journal reversal form did not open');
1803 document.getElementById('acReversalPeriod').value=period.id;
1804 document.getElementById('acReversalDate').value=period.startDate;
1805 await view.saveReversal();
1806 const originalAfter=await db.get('journal_entries',posted.id);
1807 const reversal=(await db.getAll('journal_entries')).find(x=>
1808 x.companyId===company.id&&x.reversalOfId===posted.id&&x.status==='posted');
1809 check(originalAfter?.reversedById===reversal?.id&&reversal?.debit===100&&reversal?.credit===100,
1810 'Manual journal reversal did not preserve the original and post a balanced reversal');
1811 const downloads=[],originalClick=HTMLAnchorElement.prototype.click,
1812 originalCreateObjectURL=URL.createObjectURL;
1813 try {
1814 URL.createObjectURL=function(blob){
1815 const url=originalCreateObjectURL.call(URL,blob);
1816 downloads.push({blob,url,filename:''});
1817 return url;
1818 };
1819 HTMLAnchorElement.prototype.click=function(){
1820 const item=downloads.find(x=>x.url===this.href);
1821 if(item)item.filename=this.download;
1822 };
1823 await view.exportReports();
1824 await view.exportReconciliation();
1825 check(downloads.length===2,'Accounting report and reconciliation exports did not both download');
1826 const content=await Promise.all(downloads.map(async item=>({
1827 filename:item.filename,text:await item.blob.text()
1828 })));
1829 check(content.some(x=>x.filename==='factor-easypro-ledger.csv'&&
1830 x.text.includes('account_code')&&x.text.includes(postedDescription)),
1831 'Ledger CSV export omitted the posted synthetic journal');
1832 check(content.some(x=>x.filename==='factor-easypro-reconciliation.csv'&&
1833 x.text.includes('code')&&x.text.includes('reference')),
1834 'Reconciliation CSV export omitted its expected schema');
1835 } finally {
1836 URL.createObjectURL=originalCreateObjectURL;
1837 HTMLAnchorElement.prototype.click=originalClick;
1838 }
1839 return {chartAccountCreated:true,journalRowAdded:true,journalRowRemoveButtonClicked:true,
1840 draftJournalSaved:true,journalPosted:true,journalDetailsOpened:true,
1841 reversalFormOpened:true,reversalPosted:true,ledgerCsvExported:true,
1842 reconciliationCsvExported:true};
1843 }
1844
1845 async function nativeInventoryTransferAndStocktake() {
1846 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1847 const db=FINORA.Storage,company=await FINORA.Company.current();
1848 check(company?.id&&FINORA.Auth.isAdmin(),'Inventory transfer UI test requires a synthetic administrator');
1849 const balances=(await db.getAll('inventory_balances')).filter(x=>
1850 x.companyId===company.id&&x.quantityUnits>0);
1851 check(balances.length,'No positive synthetic inventory balance exists for transfer');
1852 const sourceBalance=balances[0];
1853 const product=await db.get('products',sourceBalance.productId);
1854 const warehouses=(await db.getAll('warehouses')).filter(x=>x.companyId===company.id);
1855 const source=warehouses.find(x=>x.id===sourceBalance.warehouseId);
1856 check(product?.trackInventory!==false&&source,'Transfer source product/warehouse is invalid');
1857 await FINORA.Router.go('accounting');
1858 const view=window.AccountingView;
1859 await view.refresh();
1860 const secondName='VM-only Q01 transfer destination';
1861 view.openWarehouse();
1862 document.getElementById('acWhName').value=secondName;
1863 await view.saveWarehouse();
1864 const destination=(await db.getAll('warehouses')).find(x=>
1865 x.companyId===company.id&&x.name===secondName);
1866 check(destination,'Second warehouse was not created through the UI');
1867 const quantity=Math.min(0.1,sourceBalance.quantityUnits/1000);
1868 const transferUnits=Math.round(quantity*1000);
1869 const beforeRows=await db.getAll('inventory_balances');
1870 const beforeFrom=beforeRows.find(x=>x.companyId===company.id&&
1871 x.warehouseId===source.id&&x.productId===product.id)?.quantityUnits||0;
1872 const beforeTo=beforeRows.find(x=>x.companyId===company.id&&
1873 x.warehouseId===destination.id&&x.productId===product.id)?.quantityUnits||0;
1874 await view.openTransfer();
1875 check(document.getElementById('acTrProduct')&&document.getElementById('acTrFrom')&&
1876 document.getElementById('acTrTo'),'Stock transfer form did not open');
1877 document.getElementById('acTrProduct').value=product.id;
1878 document.getElementById('acTrFrom').value=source.id;
1879 document.getElementById('acTrTo').value=destination.id;
1880 document.getElementById('acTrQty').value=String(quantity);
1881 document.getElementById('acTrDate').value='1405/07/22';
1882 await view.saveTransfer();
1883 const afterRows=await db.getAll('inventory_balances');
1884 const afterFrom=afterRows.find(x=>x.companyId===company.id&&
1885 x.warehouseId===source.id&&x.productId===product.id)?.quantityUnits||0;
1886 const afterTo=afterRows.find(x=>x.companyId===company.id&&
1887 x.warehouseId===destination.id&&x.productId===product.id)?.quantityUnits||0;
1888 check(afterFrom===beforeFrom-transferUnits&&afterTo===beforeTo+transferUnits,
1889 'Stock transfer did not move the exact milli-unit quantity between warehouses');
1890 await view.openStocktakeCreate();
1891 document.getElementById('acStWarehouse').value=source.id;
1892 document.getElementById('acStDate').value='1405/07/23';
1893 await view.createStocktake();
1894 const stocktakeId=document.getElementById('acStocktakeId')?.value;
1895 check(stocktakeId,'Stocktake create action did not open the count sheet');
1896 const countRows=[...document.querySelectorAll('#acTakeRows tr[data-product]')];
1897 check(countRows.length>0,'Stocktake did not snapshot the source warehouse balances');
1898 for(const row of countRows){
1899 const expected=Number(row.querySelector('td:nth-child(2)').textContent.trim());
1900 row.querySelector('.ac-count').value=String(expected);
1901 }
1902 await view.saveStocktake();
1903 await view.openStocktake(stocktakeId);
1904 await view.finishStocktake();
1905 const stocktake=await db.get('stocktakes',stocktakeId);
1906 const lines=await db.getAll('stocktake_lines');
1907 const ownLines=lines.filter(x=>x.companyId===company.id&&x.stocktakeId===stocktakeId);
1908 check(stocktake?.status==='posted'&&ownLines.length>0&&
1909 ownLines.every(x=>x.countedUnits===x.expectedUnits),
1910 'Stocktake did not save all counts and finalize without an inventory delta');
1911 return {secondWarehouseCreated:true,transferPosted:true,exactInventoryMoved:true,
1912 stocktakeCreated:true,stocktakeCountsSaved:true,stocktakeFinalized:true};
1913 }
1914
1915 module.exports = async function nativeFunctionalMatrix(cdp) {
1916 const phases = [
1917 ['legacy-stock-adjustment-form-and-validation', legacyStockAdjustmentFormAndValidation],
1918 ['activate-accounting-and-inventory', activateAccounting],
1919 ['integrated-stock-adjustment-guard', integratedStockAdjustmentGuard],
1920 ['contacts-crud-form-and-tags', nativeContactCrudFormAndTags],
1921 ['products-crud-form-and-nested-classifiers', nativeProductCrudFormAndNestedClassifiers],
1922 ['positive-opening-ledger-and-idempotency', nativePositiveOpeningLedger],
1923 ['purchase-and-post-ledger', purchaseInvoice],
1924 ['partial-sale-and-inventory', saleInvoice],
1925 ['invoice-quick-add-and-save-print', nativeInvoiceQuickAddAndPrint],
1926 ['auxiliary-rtl-print-rendering', nativeAuxiliaryPrintRendering],
1927 ['expense-form-category-and-posting', nativeExpenseFormAndCategory],
1928 ['manual-journal-reversal-and-exports', nativeAccountingJournalAndExports],
1929 ['inventory-transfer-and-stocktake', nativeInventoryTransferAndStocktake],
1930 ['inactive-treasury-cheque-settlement', nativeInactiveBankSettlementGuard],
1931 ['cheque-third-party-endorsement', nativeChequeThirdPartyEndorsement],
1932 ['treasury-cheque-reconciliation-readonly', nativeTreasuryChequeReconciliation],
1933 ['sale-return-immutable-stock-and-ledger', nativeSaleReturnGuardrails],
1934 ['purchase-return-and-stock-guardrails', nativePurchaseReturnGuardrails],
1935 ['return-cash-settlement-net-credit', nativeReturnCashSettlementGuardrails],
1936 ['append-only-history-bulk-clear-protection', nativeHistoryClearFailClosed],
1937 ['backup-and-atomic-rejection', nativeBackupRestore],
1938 ['rtl-invoice-print-settings', invoicePrintLayout],
1939 ['fiscal-close-atomic-guardrails', fiscalCloseGuardrails],
1940 ['opening-dry-run-rejects-existing-postings', openingDryRunWithExistingActivity]
1941 ];
1942 const report = {};
1943 for (const [name, fn] of phases) {
1944 const value = await cdp.evaluate('(' + fn.toString() + ')()');
1945 assert.ok(value && typeof value === 'object', 'invalid native E2E result from ' + name);
1946 report[name] = value;
1947 console.log('NATIVE E2E PASSED: ' + name + ': ' + JSON.stringify(value));
1948 }
1949 return report;
1950 };