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

work/a08-memory-stability-20261123
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,954 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 // Error toasts from earlier native scenarios intentionally persist until
900 // dismissed. Assert only this rejected-transfer notice was closed.
901 toast.querySelector('.toast-close')?.click();
902 FINORA.Modal.close();
903 check(!toast.isConnected,'Expected transfer toast not dismissed');
904
905 // With no active bank, the real cheque status UI must reject settlement
906 // without changing posted status or writing a cash receipt.
907 await db.put('treasury',{...active,isActive:false});
908 await FINORA.Router.go('cheques');await wait(200);
909 const cv=window.ChequesView;
910 await cv.openChequeModal();
911 check(document.getElementById('chqSayad'),'Native cheque form absent');
912 document.getElementById('chqDirection').value='inbound';
913 document.getElementById('chqContact').value=contact.id;
914 document.getElementById('chqSayad').value='1234567890123489';
915 document.getElementById('chqAmount').value='90';
916 document.getElementById('chqIssueDate').value='1405/07/18';
917 document.getElementById('chqDueDate').value='1405/07/18';
918 await cv.saveCheque(null);
919 const cheque=(await db.getAll('cheques')).find(x=>x.companyId===company.id&&x.sayadNumber==='1234567890123489');
920 check(cheque?.financePosted&&cheque.status==='pending','Native cheque posting failed');
921 const journalCount=(await db.getAll('journal_entries')).length;
922 await cv.changeStatus(cheque.id);
923 check(document.getElementById('newStatus'),'Cheque status form missing');
924 const dateInput=document.getElementById('chqEventDate');
925 check(dateInput,'Native posted cheque must request the financial event date');
926 dateInput.value='1405/07/20'; // intentionally different from the cheque due date
927 document.getElementById('newStatus').value='cleared';
928 cv._onChequeStatusSelection();
929 check(document.getElementById('chqClearingAccount'),
930 'Explicit bank selection was not presented in posted cheque UI');
931 await cv._applyStatusChange(cheque.id);
932 toast=[...document.querySelectorAll('.toast-warning')].find(x=>
933 x.textContent.includes('حساب بانک یا صندوق را انتخاب کنید'));
934 check(toast,'Clearing without selected active bank did not visibly reject');
935 check((await db.get('cheques',cheque.id)).status==='pending'&&
936 (await db.getAll('journal_entries')).length===journalCount&&
937 !(await db.getAll('treasury')).some(t=>t.refChequeId===cheque.id),
938 'Rejected cheque clearance modified ledger or treasury');
939 toast.querySelector('.toast-close')?.click();
940 FINORA.Modal.close();
941 await db.put('treasury',active);
942 await db.put('treasury',{...secondary,isActive:true});
943 await FINORA.Router.go('treasury');await wait(180);await tv.reload();
944 const transferCountBefore=(await db.getAll('treasury')).filter(x=>
945 x.companyId===company.id&&x.recordType==='transaction'&&x.type==='transfer').length;
946 tv.openTransferModal();
947 check(document.getElementById('txFromAccount')&&document.getElementById('txToAccount'),
948 'Native positive transfer form did not open');
949 document.getElementById('txDate').value='1405/07/21';
950 document.getElementById('txAmount').value='1';
951 document.getElementById('txFromAccount').value=active.id;
952 document.getElementById('txToAccount').value=secondary.id;
953 await tv._saveTransaction('transfer');
954 const transfer=(await db.getAll('treasury')).find(x=>
955 x.companyId===company.id&&x.recordType==='transaction'&&x.type==='transfer'&&
956 x.amount===1&&x.fromAccountId===active.id&&x.toAccountId===secondary.id);
957 check(transfer&&(await db.getAll('treasury')).filter(x=>
958 x.companyId===company.id&&x.recordType==='transaction'&&x.type==='transfer').length===transferCountBefore+1,
959 'Valid transfer between active accounts did not persist exactly once');
960 await FINORA.Router.go('cheques');await wait(180);await cv.reload();
961 await cv.changeStatus(cheque.id);
962 document.getElementById('newStatus').value='cleared';
963 document.getElementById('chqEventDate').value='1405/07/20';
964 cv._onChequeStatusSelection();
965 const selected=document.getElementById('chqClearingAccount');
966 check([...selected.options].some(x=>x.value===secondary.id),
967 'Actual secondary bank not selectable in clearing UI');
968 selected.value=secondary.id; // bank other than the default
969 // The successful transfer above intentionally added a journal entry. Take
970 // a fresh baseline immediately before cheque approval, and scope the cash
971 // assertion to this cheque so unrelated valid postings cannot fail it.
972 const journalCountBeforeApproval=(await db.getAll('journal_entries')).length;
973 const chequeSettlementsBeforeApproval=(await db.getAll('treasury')).filter(t=>
974 t.refChequeId===cheque.id).length;
975 await cv._applyStatusChange(cheque.id);
976 const approve=document.querySelector('.modal-backdrop:last-of-type [data-action="confirm"]');
977 check(approve&&approve.textContent.includes('تأیید و ثبت وصول'),
978 'Actual bank clearance missing explicit secondary confirmation');
979 check((await db.get('cheques',cheque.id)).status==='pending'&&
980 (await db.getAll('journal_entries')).length===journalCountBeforeApproval&&
981 (await db.getAll('treasury')).filter(t=>t.refChequeId===cheque.id).length===
982 chequeSettlementsBeforeApproval,
983 'Cheque cleared before approval');
984 approve.click();
985 let cleared;
986 for(let i=0;i<60;i++){
987 cleared=await db.get('cheques',cheque.id);
988 if(cleared?.status==='cleared')break;
989 await wait(100);
990 }
991 const journal=await db.get('journal_entries',cleared.statusJournalId);
992 const settlement=(await db.getAll('treasury')).filter(t=>t.refChequeId===cheque.id);
993 const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal?.id);
994 check(cleared.status==='cleared'&&cleared.dueDate==='1405/07/18'&&
995 cleared.statusBusinessDate==='1405/07/20'&&cleared.clearingAccountId===secondary.id&&
996 cleared.clearingApprovedBy===FINORA.Auth.current().id&&
997 journal?.date==='1405/07/20'&&settlement.length===1&&
998 settlement[0].date==='1405/07/20'&&settlement[0].toAccountId===secondary.id&&
999 lines.some(x=>x.accountId===secondary.ledgerAccountId&&x.debit===90)&&
1000 !lines.some(x=>x.accountId===active.ledgerAccountId&&x.debit===90),
1001 'Native cheque clearance failed selected non-default bank accounting');
1002 // Earlier deliberately rejected treasury actions can leave independent error
1003 // toasts visible; successful cheque clearance must not be judged by those.
1004 // Financial persistence and exact account/date checks above remain mandatory.
1005 check(!document.querySelector('.modal-backdrop'),
1006 'A05 native treasury scenario left a modal open');
1007 return { inactiveTransferRejected:true, invalidTransferRolledBack:true,
1008 validTransferPosted:true,treasuryAccountCreatedThroughForm:true,treasuryAccountEditPersisted:true,
1009 chequeCreatedThroughForm:true,disabledChequeClearingRejected:true, validChequeClearedExactlyOnce:true,
1010 chequeEventDateDifferentFromDueDate:true,
1011 explicitNondefaultClearingAccount:true,confirmationRequiredBeforeCash:true };
1012 }
1013
1014 async function nativeChequeThirdPartyEndorsement() {
1015 const wait=ms=>new Promise(r=>setTimeout(r,ms));
1016 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1017 const db=FINORA.Storage,company=await FINORA.Company.current();
1018 check(company?.id&&FINORA.Auth.isAdmin(),'A01 endorsement needs synthetic admin');
1019 const drawer=(await db.getAll('contacts')).find(c=>
1020 c.companyId===company.id&&c.name==='مشتری آزمایشی ویندوز');
1021 check(drawer,'Endorsement drawer fixture missing');
1022 const endorsee={id:'vm-a01-endorsee-contact',companyId:company.id,
1023 name:'تأمین‌کننده واگذاری آزمایشی',ownerUserId:FINORA.Auth.current().id};
1024 await db.put('contacts',endorsee);
1025 await FINORA.Router.go('cheques');await wait(130);
1026 const view=window.ChequesView;
1027 await view.reload();
1028 await view.openChequeModal();
1029 check(document.getElementById('chqSayad'),'Real native cheque create form missing');
1030 document.getElementById('chqDirection').value='inbound';
1031 document.getElementById('chqContact').value=drawer.id;
1032 document.getElementById('chqSayad').value='1234567890123490';
1033 document.getElementById('chqAmount').value='75';
1034 document.getElementById('chqIssueDate').value='1405/07/18';
1035 document.getElementById('chqDueDate').value='1405/07/18';
1036 await view.saveCheque(null);
1037 const cheque=(await db.getAll('cheques')).find(c=>
1038 c.companyId===company.id&&c.sayadNumber==='1234567890123490');
1039 check(cheque?.financePosted&&cheque.status==='pending','Endorsement cheque posting failed');
1040 await view.changeStatus(cheque.id);
1041 const status=document.getElementById('newStatus');
1042 const date=document.getElementById('chqEventDate');
1043 const endorseeSelect=document.getElementById('chqEndorsee');
1044 check(status&&date&&endorseeSelect,'Actual endorsement choice missing in native UI');
1045 status.value='spent';date.value='1405/07/20';
1046 view._onChequeStatusSelection();
1047 check(document.getElementById('chqEndorseeGroup').style.display!=='none',
1048 'Third-party contact selector was hidden');
1049 const counts=async()=>({
1050 journals:(await db.getAll('journal_entries')).length,
1051 corrections:(await db.getAll('document_corrections')).length,
1052 audits:(await db.getAll('audit_events')).length
1053 });
1054 const before=await counts();
1055 await view._applyStatusChange(cheque.id);
1056 check(!document.querySelector('.modal-footer [data-action="confirm"]'),
1057 'Endorsement without selected third party opened approval');
1058 check(JSON.stringify(await counts())===JSON.stringify(before)&&
1059 (await db.get('cheques',cheque.id)).status==='pending',
1060 'Missing endorsee wrote a financial event');
1061 const warning=[...document.querySelectorAll('.toast-warning')].find(x=>
1062 x.textContent.includes('دریافت‌کننده واگذاری'));
1063 check(warning,'Missing endorsee was not visibly rejected');
1064 warning.querySelector('.toast-close')?.click();
1065 endorseeSelect.value=endorsee.id;
1066 await view._applyStatusChange(cheque.id);
1067 const confirm=document.querySelector('.modal-backdrop:last-of-type [data-action="confirm"]');
1068 check(confirm&&confirm.textContent.includes('تأیید و ثبت واگذاری'),
1069 'Native endorsement has no separate explicit approval');
1070 check(JSON.stringify(await counts())===JSON.stringify(before)&&
1071 (await db.get('cheques',cheque.id)).status==='pending',
1072 'Endorsement posted before explicit confirmation');
1073 confirm.click();
1074 let endorsed;
1075 for(let i=0;i<60;i++){
1076 endorsed=await db.get('cheques',cheque.id);
1077 if(endorsed.status==='spent')break;
1078 await wait(100);
1079 }
1080 check(endorsed?.status==='spent'&&endorsed.endorseeContactId===endorsee.id&&
1081 endorsed.endorsementApprovedBy===FINORA.Auth.current().id&&
1082 endorsed.statusBusinessDate==='1405/07/20',
1083 'Native endorsement did not retain selected third party and approval');
1084 const journal=await db.get('journal_entries',endorsed.statusJournalId);
1085 const lines=(await db.getAll('journal_lines')).filter(x=>x.journalId===journal?.id);
1086 const payable=(await db.getAll('account_chart')).find(x=>
1087 x.companyId===company.id&&x.code==='201');
1088 const incoming=(await db.getAll('account_chart')).find(x=>
1089 x.companyId===company.id&&x.code==='105');
1090 check(journal?.date==='1405/07/20'&&lines.some(l=>
1091 l.accountId===payable?.id&&l.contactId===endorsee.id&&l.debit===75)&&
1092 lines.some(l=>l.accountId===incoming?.id&&l.contactId===drawer.id&&l.credit===75),
1093 'Endorsement GL was not correctly split between endorsee and drawer');
1094 const correction=(await db.getAll('document_corrections')).find(x=>
1095 x.sourceType==='cheque'&&x.sourceId===cheque.id&&x.correctionType==='endorsement');
1096 check(correction?.endorseeContactId===endorsee.id&&
1097 correction?.correlationId===journal.id&&correction?.approvedBy===FINORA.Auth.current().id,
1098 'Native endorsement lacks append-only trace and actor');
1099 check(!(await db.getAll('treasury')).some(x=>x.refChequeId===cheque.id),
1100 'Endorsement incorrectly created cash settlement');
1101 // Prior deliberately rejected native actions may leave unrelated error toasts.
1102 // The ledger, third-party dimensions, approval and no-cash assertions above
1103 // verify the endorsement itself; require its approval modal to be closed.
1104 check(!document.querySelector('.modal-backdrop'),
1105 'Native endorsement left an approval modal open');
1106 return {missingEndorseeRejected:true,confirmationRequiredBeforeWrite:true,
1107 endorseeLedgerDimensionCorrect:true,drawerChequeAssetPreserved:true,
1108 appendOnlyEndorsementCorrelated:true,noPhantomCash:true};
1109 }
1110
1111 async function nativeTreasuryChequeReconciliation() {
1112 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1113 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1114 const storage=FINORA.Storage,company=await FINORA.Company.current();
1115 check(company?.id&&FINORA.Auth.isAdmin(),'A05 reconciliation requires synthetic admin');
1116 await FINORA.Router.go('accounting');await wait(130);
1117 const view=window.AccountingView;
1118 await view.switchTab('reconciliation');
1119 const original=await view.renderReconciliation();
1120 check(original.includes('چک‌های مالی'),'Native reconciliation does not show cheque controls');
1121 check(!original.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
1122 !original.includes('CHEQUE_CLEARING_CASH_COUNT'),
1123 'Real posted VM cheque failed reconciliation before fault injection');
1124 // Corrupt only a synthetic fixture in the disposable native VM, never
1125 // alter a customer accounting record. This probes read-only detection.
1126 const id='vm-a05-invalid-cheque-reconciliation';
1127 const broken={id,companyId:company.id,financePosted:true,
1128 direction:'inbound',status:'cleared',amount:90,journalId:'not-there',
1129 statusJournalId:'not-there-either'};
1130 await storage.put('cheques',broken);
1131 const before=(await storage.getAll('journal_entries')).length;
1132 const checked=await view.renderReconciliation();
1133 check(checked.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
1134 checked.includes('CHEQUE_STATUS_JOURNAL_MISSING')&&
1135 checked.includes('CHEQUE_CLEARING_CASH_COUNT'),
1136 'Native installed reconciliation failed to report malformed cheque');
1137 check((await storage.getAll('journal_entries')).length===before&&
1138 (await storage.get('cheques',id))?.status==='cleared',
1139 'Read-only reconciliation changed journal or cheque state');
1140 await storage.delete('cheques',id);
1141 const after=await view.renderReconciliation();
1142 check(!after.includes('CHEQUE_SOURCE_JOURNAL_MISSING')&&
1143 !after.includes('CHEQUE_CLEARING_CASH_COUNT'),
1144 'Reconciliation still reports synthetic cheque after fixture removal');
1145 await view.switchTab('journals');
1146 check(!document.querySelector('.toast-error'),'A05 reconciliation left toast');
1147 return {livePostedChequeReviewed:true,chequeDiscrepanciesDetected:true,
1148 reportingReadOnly:true,fixtureRemoved:true};
1149 }
1150
1151 async function nativeReturnCashSettlementGuardrails() {
1152 const wait=ms=>new Promise(r=>setTimeout(r,ms));
1153 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1154 const db=FINORA.Storage,company=await FINORA.Company.current();
1155 const sale=(await db.getAll('invoices')).find(x=>
1156 x.companyId===company.id&&x.kind==='sale'&&x.grandTotal===600);
1157 const returned=(await db.getAll('invoices')).find(x=>
1158 x.companyId===company.id&&x.kind==='sale_return'&&x.originalInvoiceId===sale?.id);
1159 check(sale?.paidAmount===200&&returned?.grandTotal===200,
1160 'A01 net-refund native sale/return prerequisite absent');
1161 await FINORA.Router.go('treasury');await wait(170);
1162 const view=window.TreasuryView;
1163 const before=()=>Promise.all(['journal_entries','treasury','settlements'].map(async name=>
1164 (await db.getAll(name)).length));
1165 const testReceipt=async(amount)=>{
1166 await view.openReceiptModal();
1167 const sel=document.getElementById('txInvoiceRef');
1168 check(sel&&[...sel.options].some(x=>x.value===sale.id),
1169 'Real treasury UI does not list the unpaid original sale');
1170 sel.value=sale.id;view._onInvoiceSelection();
1171 document.getElementById('txAmount').value=String(amount);
1172 document.getElementById('txDate').value='1405/07/18';
1173 await view._saveTransaction('receipt');
1174 };
1175 const start=await before();
1176 await testReceipt(201);
1177 let toast=[...document.querySelectorAll('.toast-error')].find(x=>x.textContent.includes('مانده خالص'));
1178 check(toast,'Overcollection after posted return not visibly rejected');
1179 check(JSON.stringify(await before())===JSON.stringify(start),
1180 'Rejected overcollection wrote a ledger, treasury or settlement');
1181 toast.querySelector('.toast-close')?.click();
1182 FINORA.Modal.close();
1183 await testReceipt(200);
1184 check((await db.get('invoices',sale.id)).paidAmount===400,
1185 'Allowed residual collection did not reach net post-return amount');
1186 await view.openPaymentModal();
1187 const sel=document.getElementById('txInvoiceRef');
1188 // This return was fully offset against the unpaid receivable and has no
1189 // refundable credit. The treasury selector intentionally hides settled
1190 // returns; service-level tests separately enforce the cash refund cap.
1191 check(sel&&![...sel.options].some(x=>x.value===returned.id),
1192 'Zero-credit customer return must not be offered for cash refund');
1193 FINORA.Modal.close();
1194 check(!document.querySelector('.modal-backdrop'),
1195 'Native zero-credit refund guard left payment modal open');
1196
1197 // Establish a real, paid customer credit in the installed WebView2 app:
1198 // sale 600, cash received 400, total returns 400 -> refund cap 200.
1199 // Post a second 200-rial return through the actual invoice UI.
1200 const contact=await db.get('contacts',sale.contactId);
1201 const product=(await db.getAll('products')).find(p=>p.code==='VM-E2E-100');
1202 check(contact&&product,'Native positive refund requires customer and product');
1203 await FINORA.Router.go('invoices');await wait(180);
1204 await window.InvoiceFormView.open();await wait(160);
1205 document.getElementById('invKind').value='sale_return';
1206 await window.InvoiceFormView._onKindChange();
1207 const original=document.getElementById('invOriginalInvoice');
1208 check(original&&[...original.options].some(x=>x.value===sale.id),
1209 'Native positive refund original invoice selector absent');
1210 original.value=sale.id;
1211 document.getElementById('invDate').value='1405/07/18';
1212 const contactSearch=document.getElementById('invContactSearch');
1213 contactSearch.value=contact.name;
1214 window.InvoiceFormView._showContactOptions(true);
1215 const contactItem=document.querySelector('.contact-option[data-id="'+contact.id+'"]');
1216 check(contactItem,'Native positive refund contact missing');
1217 contactItem.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
1218 const productSearch=document.querySelector('.row-product-search');
1219 productSearch.value=product.code;
1220 window.InvoiceFormView._showProductOptions(0,true);
1221 const productItem=document.querySelector('.product-option[data-id="'+product.id+'"]');
1222 check(productItem,'Native positive refund product missing');
1223 productItem.dispatchEvent(new MouseEvent('mousedown',{bubbles:true}));
1224 document.querySelector('.row-qty').value='1';
1225 window.InvoiceFormView._onFieldChange(0,'qty','1');
1226 document.querySelector('.row-price').value='200';
1227 window.InvoiceFormView._onFieldChange(0,'price','200');
1228 document.getElementById('invPayment').value='credit';
1229 window.InvoiceFormView._onPaymentChange();
1230 await window.InvoiceFormView._save(false);await wait(170);
1231 check(!document.querySelector('.toast-error'),'Second synthetic return failed in native UI');
1232 const second=(await db.getAll('invoices')).find(x=>
1233 x.kind==='sale_return'&&x.originalInvoiceId===sale.id&&x.id!==returned.id);
1234 check(second?.grandTotal===200&&second.paidAmount===0,
1235 'Second posted customer credit document missing');
1236 await FINORA.Router.go('treasury');await wait(170);
1237 await view.openPaymentModal();
1238 const select=document.getElementById('txInvoiceRef');
1239 check(select&&[...select.options].some(x=>x.value===second.id),
1240 'Native positive refund return not selectable in treasury UI');
1241 select.value=second.id;view._onInvoiceSelection();
1242 document.getElementById('txAmount').value='100';
1243 document.getElementById('txDate').value='1405/07/18';
1244 document.getElementById('txReturnReason').value='quality_issue';
1245 const beforeApproval=await before();
1246 await view._saveTransaction('payment');
1247 const approve=document.querySelector('.modal-footer [data-action="confirm"]');
1248 check(approve,'Native accepted refund missing explicit confirmation dialog');
1249 check(JSON.stringify(await before())===JSON.stringify(beforeApproval),
1250 'Opening approval dialog must not post cash or journal');
1251 approve.click();
1252 let refund=null;
1253 for(let i=0;i<40;i++){
1254 refund=(await db.getAll('treasury')).find(x=>
1255 x.recordType==='transaction'&&x.refInvoiceId===second.id&&x.type==='payment');
1256 if(refund)break;
1257 await wait(100);
1258 }
1259 check(!document.querySelector('.toast-error'),'Authorized native customer refund failed');
1260 const correction=(await db.getAll('document_corrections')).find(x=>
1261 x.correctionType==='settlement_refund'&&x.sourceId===second.id&&
1262 x.resultId===refund?.id);
1263 const audit=(await db.getAll('audit_events')).find(x=>
1264 x.sourceId===refund?.journalId&&x.correlationId===correction?.correlationId);
1265 check(refund?.amount===100&&correction?.amount===100&&
1266 correction.reasonCode==='quality_issue'&&
1267 correction.actionCode==='customer_credit_refund'&&
1268 correction.approvedBy===FINORA.Auth.current()?.id&&
1269 correction.approvalMethod==='explicit_confirmation'&&audit&&
1270 (await db.get('invoices',second.id))?.paidAmount===100,
1271 'Native refund correction, treasury, audit or invoice linkage is invalid');
1272 check(!document.querySelector('.modal-backdrop'),
1273 'Native refund left an unexpected payment dialog');
1274 return {overcollectionRejectedWithoutWrites:true,netReceiptAccepted:true,
1275 zeroCreditReturnHiddenFromRefundSelector:true,realTreasuryInvoiceSelector:true,
1276 authorizedRefundTracedInInstalledWebView2:true};
1277 }
1278
1279 async function nativeBackupRestore() {
1280 const check = (value, message) => { if (!value) throw Error(message); };
1281 const S = FINORA.Storage;
1282 const company = (await S.getAll('companies'))[0];
1283 const temporary = await S.put('contacts', {
1284 id: 'native-vm-backup-roundtrip', companyId: company.id, name: 'فقط آزمون بازگردانی'
1285 });
1286 const snapshot = await S.exportAll();
1287 check(snapshot.version === 7 && snapshot.app === 'Factor-easyPro',
1288 'invalid native backup envelope');
1289 check(snapshot.data.contacts.some(x => x.id === temporary.id),
1290 'native backup omitted test contact');
1291 check(snapshot.data.users.every(u => !('pwHash' in u) && !('pwSalt' in u)),
1292 'native backup leaked user password derivation metadata');
1293 await S.delete('contacts', temporary.id);
1294 check(!(await S.get('contacts', temporary.id)), 'test contact was not deleted');
1295 await S.importAll({
1296 app: snapshot.app, version: snapshot.version,
1297 data: { contacts: snapshot.data.contacts.filter(c => c.id === temporary.id) }
1298 });
1299 check((await S.get('contacts', temporary.id))?.name === 'فقط آزمون بازگردانی',
1300 'native backup restore did not recover contact');
1301
1302 const sale = (await S.getAll('invoices')).find(i => i.kind === 'sale' && i.financePosted);
1303 check(sale, 'posted sale missing for restore immutability');
1304 let denied = false;
1305 try {
1306 await S.importAll({
1307 app: snapshot.app, version: snapshot.version,
1308 data: {
1309 contacts: [{id:'should-rollback-native',companyId:company.id,name:'Reject'}],
1310 invoices: [{...sale,grandTotal:sale.grandTotal+1}]
1311 }
1312 });
1313 } catch (_) { denied = true; }
1314 check(denied, 'tampered posted sale backup must fail');
1315 check(!(await S.get('contacts','should-rollback-native')),
1316 'rejected full backup wrote a contact anyway');
1317 check((await S.get('invoices',sale.id)).grandTotal===sale.grandTotal,
1318 'tampered posted sale modified the actual financial document');
1319 return { backupSchema: snapshot.version, credentialsExcluded: true,
1320 contactRoundtrip: true, tamperedInvoiceRejectedAtomically: true };
1321 }
1322
1323 async function invoicePrintLayout() {
1324 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
1325 const check = (value, message) => { if (!value) throw Error(message); };
1326 const sale = (await FINORA.Storage.getAll('invoices'))
1327 .find(x => x.kind === 'sale' && x.financePosted);
1328 check(sale, 'posted invoice for print preview missing');
1329 await FINORA.Router.go('invoices');
1330 await wait(200);
1331 await window.InvoicesView.printInvoice(sale.id);
1332 await wait(320);
1333 const dialog = document.querySelector('.modal-backdrop');
1334 check(dialog, 'native print settings dialog did not open');
1335 const labels = dialog.textContent || '';
1336 check(labels.includes('قالب چاپ') && labels.includes('A4'),
1337 'RTL print template or paper settings missing');
1338 check(document.documentElement.dir === 'rtl',
1339 'document is not marked RTL');
1340 FINORA.Modal.close();
1341 return { rtl: true, printSettings: true, templates: true,
1342 physicalPrinterTest: 'not-covered' };
1343 }
1344
1345 async function fiscalCloseGuardrails() {
1346 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
1347 const check = (ok, message) => { if (!ok) throw Error(message); };
1348 const store = FINORA.Storage;
1349 const company = await FINORA.Company.current();
1350 check(company?.id && FINORA.Auth.isAdmin(), 'Fiscal close test must use a synthetic admin');
1351 await FINORA.Router.go('accounting');
1352 await wait(180);
1353 const view = window.AccountingView;
1354 check(view, 'Native accounting view was not mounted');
1355 await view.switchTab('periods');
1356 const testName = 'A05 VM-only guarded closing period';
1357 view.openPeriodModal();
1358 check(document.getElementById('acPeriodName'), 'Fiscal period creation form missing');
1359 document.getElementById('acPeriodName').value = testName;
1360 document.getElementById('acPeriodStart').value = '1404/01/01';
1361 document.getElementById('acPeriodEnd').value = '1404/12/29';
1362 await view.savePeriod();
1363 check(!document.querySelector('.toast-error'), 'Creating isolated fiscal period failed');
1364 const period = (await store.getAll('fiscal_periods'))
1365 .find(x => x.companyId === company.id && x.name === testName);
1366 check(period && period.closed === false, 'Synthetic fiscal period did not persist as open');
1367 const warehouses = (await store.getAll('warehouses')).filter(x => x.companyId === company.id);
1368 check(warehouses.length, 'Warehouse prerequisite missing');
1369 const stocktakeId = 'vm-a05-draft-stocktake';
1370 await store.put('stocktakes', {
1371 id: stocktakeId, companyId: company.id,
1372 warehouseId: warehouses[0].id, status: 'draft'
1373 });
1374 const auditCount = (await store.getAll('audit_events'))
1375 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length;
1376 const confirmClose = () => {
1377 view.closePeriod(period.id);
1378 const confirm = document.querySelector('.modal-footer [data-action="confirm"]');
1379 check(confirm, 'Real fiscal closure approval dialog missing');
1380 confirm.click();
1381 };
1382 confirmClose();
1383 let message = null;
1384 for (let i = 0; i < 60; i++) {
1385 message = [...document.querySelectorAll('.toast-error')]
1386 .find(x => x.textContent.includes('انبارگردانی باز'));
1387 if (message) break;
1388 await wait(100);
1389 }
1390 check(message, 'Closing with an open stocktake was not rejected visibly');
1391 check((await store.get('fiscal_periods', period.id))?.closed === false,
1392 'Open stocktake allowed fiscal closure');
1393 check((await store.getAll('audit_events'))
1394 .filter(x => x.companyId === company.id && x.eventType === 'period_closed').length === auditCount,
1395 'Rejected fiscal closing created an audit receipt');
1396 message.querySelector('.toast-close')?.click();
1397 check(!document.querySelector('.toast-error'), 'Expected fiscal rejection toast remained');
1398 await store.delete('stocktakes', stocktakeId);
1399
1400 // A05: another real fiscal-close attempt must still be blocked while
1401 // there is an unfinished draft ledger in the same isolated period.
1402 const draftId = 'vm-a05-unposted-draft-journal';
1403 await store.put('journal_entries', {
1404 id: draftId, companyId: company.id, periodId: period.id,
1405 date: '1404/06/15', status: 'draft', sourceType: 'manual',
1406 description: 'VM-only pending draft prevents closure'
1407 });
1408 confirmClose();
1409 let draftToast = null;
1410 for (let i = 0; i < 60; i++) {
1411 draftToast = [...document.querySelectorAll('.toast-error')]
1412 .find(x => x.textContent.includes('اسناد پیش‌نویس'));
1413 if (draftToast) break;
1414 await wait(100);
1415 }
1416 check(draftToast, 'Native fiscal closure ignored the pending draft journal');
1417 check((await store.get('fiscal_periods', period.id))?.closed === false,
1418 'Rejected draft-journal closure changed period state');
1419 check((await store.getAll('audit_events'))
1420 .filter(x => x.companyId === company.id &&
1421 x.eventType === 'period_closed').length === auditCount,
1422 'Rejected draft-journal closure wrote a successful close audit');
1423 draftToast.querySelector('.toast-close')?.click();
1424 check(!document.querySelector('.toast-error'),
1425 'Expected unposted-journal rejection toast remained visible');
1426 await store.delete('journal_entries', draftId);
1427 confirmClose();
1428 let closed = null;
1429 for (let i = 0; i < 70; i++) {
1430 closed = await store.get('fiscal_periods', period.id);
1431 if (closed?.closed) break;
1432 await wait(100);
1433 }
1434 check(closed?.closed === true && closed.status === 'closed',
1435 'Approved fiscal close was not committed');
1436 const closureAudits = (await store.getAll('audit_events'))
1437 .filter(x => x.companyId === company.id &&
1438 x.eventType === 'period_closed' && x.sourceId === period.id);
1439 check(closureAudits.length === 1 &&
1440 closureAudits[0].actorId === FINORA.Auth.current().id,
1441 'Successful fiscal closure did not produce exactly one actor-scoped audit');
1442 // Already-closed periods must not be closed again via the actual confirmation
1443 // action, nor silently insert another period_closed audit receipt.
1444 confirmClose();
1445 let closedToast = null;
1446 for (let i = 0; i < 60; i++) {
1447 closedToast = [...document.querySelectorAll('.toast-error')]
1448 .find(x => x.textContent.includes('دوره مالی بسته است'));
1449 if (closedToast) break;
1450 await wait(100);
1451 }
1452 check(closedToast, 'Duplicate native close did not visibly reject');
1453 check((await store.getAll('audit_events'))
1454 .filter(x => x.companyId === company.id &&
1455 x.eventType === 'period_closed' && x.sourceId === period.id).length === 1,
1456 'Duplicate fiscal close created a second audit receipt');
1457 closedToast.querySelector('.toast-close')?.click();
1458 check(!document.querySelector('.toast-error') && !document.querySelector('.modal-backdrop'),
1459 'Fiscal guardrail test left an unexpected UI error or modal');
1460 return {
1461 openStocktakeBlocked: true,
1462 draftJournalBlocked: true,
1463 failedCloseRolledBack: true,
1464 successfulCloseCommitted: true,
1465 duplicateCloseRejected: true,
1466 singleAuditReceipt: true
1467 };
1468 }
1469
1470 async function openingDryRunWithExistingActivity() {
1471 const check = (ok, message) => { if (!ok) throw Error(message); };
1472 const store = FINORA.Storage;
1473 const company = await FINORA.Company.current();
1474 check(company?.id && FINORA.Auth.isAdmin(),
1475 'Native A02 opening dry-run requires a synthetic administrator');
1476 await FINORA.Router.go('accounting');
1477 const view = window.AccountingView;
1478 check(view, 'AccountingView missing in actual installed app');
1479 await view.switchTab('opening');
1480 const input = document.getElementById('openingFileInput');
1481 const reportHost = document.getElementById('openingPreviewReport');
1482 check(input && reportHost, 'Opening balance JSON dry-run form is missing');
1483 const periods = (await store.getAll('fiscal_periods'))
1484 .filter(x => x.companyId === company.id);
1485 const period = periods.find(x => !x.closed);
1486 check(period, 'An active period is required for A02 blocked historical migration test');
1487 const priorJournals = (await store.getAll('journal_entries'))
1488 .filter(x => x.companyId === company.id && x.status === 'posted');
1489 check(priorJournals.length > 0,
1490 'Financial activity prerequisite missing: opening must be blocked after posting');
1491 const before = {
1492 entries: (await store.getAll('journal_entries')).length,
1493 lines: (await store.getAll('journal_lines')).length,
1494 events: (await store.getAll('audit_events')).length,
1495 settings: (await store.getAll('settings')).length
1496 };
1497 const fixture = {
1498 periodId: period.id, openingDate: period.startDate,
1499 lines: [], contacts: [], stock: [], cash: []
1500 };
1501 const file = new File([JSON.stringify(fixture)], 'vm-only-a02-opening.json',
1502 { type: 'application/json' });
1503 Object.defineProperty(input, 'files', { configurable: true, value: [file] });
1504 view.resetOpeningPreview();
1505 await view.previewOpeningFile();
1506 const review = view._openingReview;
1507 check(review && review.readiness === 'blocked' && review.writePerformed === false,
1508 'Native opening dry-run failed to block incompatible historical data');
1509 check(review.issues.includes('EXISTING_POSTED_JOURNALS') &&
1510 review.issues.includes('MISSING_OPENING_JOURNAL_LINES'),
1511 'Native blocked opening preview omitted journal issues');
1512 check(reportHost.textContent.includes('ثبت مسدود') &&
1513 reportHost.querySelector('button[disabled]'),
1514 'Native opening UI offered an actionable posting button despite issues');
1515 const after = {
1516 entries: (await store.getAll('journal_entries')).length,
1517 lines: (await store.getAll('journal_lines')).length,
1518 events: (await store.getAll('audit_events')).length,
1519 settings: (await store.getAll('settings')).length
1520 };
1521 check(JSON.stringify(before) === JSON.stringify(after),
1522 'Opening preview wrote to ledger, audit or settings');
1523 check(!document.querySelector('.toast-error'),
1524 'Blocked A02 dry-run unexpectedly threw rather than reporting issues');
1525 await view.switchTab('journals');
1526 return {
1527 priorActivityBlocked: true,
1528 discrepancyCodesVisible: true,
1529 commitActionDisabled: true,
1530 zeroWrites: true
1531 };
1532 }
1533
1534
1535
1536 async function nativeInvoiceQuickAddAndPrint() {
1537 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1538 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1539 const db=FINORA.Storage,company=await FINORA.Company.current();
1540 check(company?.id&&FINORA.Auth.isAdmin(),'Q01 invoice quick-add test requires the synthetic administrator');
1541 await FINORA.Router.go('invoices');await wait(160);
1542 await window.InvoiceFormView.open();await wait(120);
1543 window.InvoiceFormView._openQuickContact();
1544 document.getElementById('qcName').value='VM-only Q01 quick contact';
1545 document.getElementById('qcMobile').value='09120000001';
1546 await window.InvoiceFormView._saveQuickContact();
1547 const contactId=document.getElementById('invContact').value;
1548 check(contactId&&document.getElementById('invContactSearch').value==='VM-only Q01 quick contact',
1549 'Quick contact was not selected in the parent invoice');
1550 window.InvoiceFormView._openQuickProduct();
1551 document.getElementById('qpCode').value='VM-Q01-QUICK-PRODUCT';
1552 document.getElementById('qpName').value='VM-only Q01 quick service';
1553 document.getElementById('qpUnit').value='عدد';
1554 document.getElementById('qpBuyPrice').value='100';
1555 document.getElementById('qpSellPrice').value='500';
1556 document.getElementById('qpTrackInventory').checked=false;
1557 await window.InvoiceFormView._saveQuickProduct();
1558 const productId=document.querySelector('#itemsBody .row-product')?.value;
1559 check(productId&&document.querySelector('.row-product-search')?.value==='VM-only Q01 quick service',
1560 'Quick product was not selected in the parent invoice');
1561 document.getElementById('invDate').value='1405/07/18';
1562 document.getElementById('invDescription').value='VM-only Q01 quick invoice print';
1563 document.querySelector('.row-qty').value='2';
1564 window.InvoiceFormView._onFieldChange(0,'qty','2');
1565 document.querySelector('.row-price').value='500';
1566 window.InvoiceFormView._onFieldChange(0,'price','500');
1567 await window.InvoiceFormView._save(true);
1568 await wait(550);
1569 const invoice=(await db.getAll('invoices')).find(x=>
1570 x.companyId===company.id&&x.contactId===contactId&&
1571 x.description==='VM-only Q01 quick invoice print');
1572 check(invoice?.financePosted&&invoice.items?.some(x=>x.productId===productId),
1573 'Save-and-print did not commit the quick invoice and its quick-added product');
1574 check(window.InvoicePrint?.currentInvoiceId===invoice.id&&document.getElementById('prPaper'),
1575 'Save-and-print did not open the actual invoice print settings modal');
1576 const original=window.InvoicePrint._openPrintWindow;
1577 let rendered='';
1578 try {
1579 window.InvoicePrint._openPrintWindow=html=>{rendered=String(html);};
1580 await window.InvoicePrint._print();
1581 } finally {
1582 window.InvoicePrint._openPrintWindow=original;
1583 }
1584 check(rendered.includes('dir="rtl"')&&rendered.includes('VM-only Q01 quick contact')&&
1585 rendered.includes('VM-only Q01 quick service'),
1586 'Actual invoice print handler did not render the saved invoice in RTL');
1587 check(!document.querySelector('.modal-backdrop'),'Invoice print test left a modal open');
1588 return {quickContactCreated:true,quickProductCreated:true,saveAndPrintOpened:true,
1589 invoicePrintRendered:true,invoicePosted:true};
1590 }
1591
1592 async function nativeAuxiliaryPrintRendering() {
1593 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1594 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1595 const company=await FINORA.Company.current(),db=FINORA.Storage;
1596 const products=(await db.getAll('products')).filter(x=>x.companyId===company.id);
1597 const contacts=(await db.getAll('contacts')).filter(x=>x.companyId===company.id);
1598 check(products.length>0&&contacts.length>0,'Synthetic product/contact fixtures are missing for print rendering');
1599 const originalOpen=window.open;
1600 let capture=null,productPrints=0,contactPrints=0;
1601 window.open=()=>({
1602 document:{
1603 write(value){capture.html+=String(value);},
1604 close(){capture.closed=true;}
1605 },
1606 focus(){capture.focused=true;},
1607 print(){capture.printed=true;}
1608 });
1609 try {
1610 for(const product of products) {
1611 capture={html:'',closed:false,focused:false,printed:false};
1612 await window.StockKardexModal._printKardex(product.id);
1613 await wait(650);
1614 check(capture.html.includes('<html lang="fa" dir="rtl">')&&
1615 capture.html.includes('کاردکس کالا')&&capture.html.includes(product.name)&&
1616 capture.closed&&capture.printed,
1617 'Kardex print did not produce a complete RTL document for '+product.id);
1618 productPrints++;
1619 }
1620 for(const contact of contacts) {
1621 capture={html:'',closed:false,focused:false,printed:false};
1622 await window.ContactLedgerModal._printLedger(contact.id);
1623 await wait(650);
1624 check(capture.html.includes('<html lang="fa" dir="rtl">')&&
1625 capture.html.includes('صورت‌حساب شخص')&&capture.html.includes(contact.name)&&
1626 capture.closed&&capture.printed,
1627 'Contact ledger print did not produce a complete RTL document for '+contact.id);
1628 contactPrints++;
1629 }
1630 await FINORA.Router.go('reports');await wait(260);
1631 capture={html:'',closed:false,focused:false,printed:false};
1632 window.ReportsView._printReport();
1633 await wait(650);
1634 check(capture.html.includes('<html lang="fa" dir="rtl">')&&
1635 capture.html.includes('گزارش سود و زیان')&&capture.closed&&capture.printed,
1636 'Reports print did not produce a complete RTL document');
1637 } finally {
1638 window.open=originalOpen;
1639 }
1640 return {kardexPrints:productPrints,contactLedgerPrints:contactPrints,
1641 reportsPrintRendered:true,allDocumentsRtl:true,physicalPrinter:'not-tested'};
1642 }
1643
1644 async function nativeExpenseFormAndCategory() {
1645 const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
1646 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1647 const db=FINORA.Storage,company=await FINORA.Company.current();
1648 check(company?.id&&FINORA.Auth.isAdmin(),'Expense UI test requires a synthetic administrator');
1649 await FINORA.Router.go('expenses');await wait(160);
1650 const view=window.ExpensesView;
1651 await view.openExpenseModal();
1652 const originalPrompt=window.prompt;
1653 try {
1654 window.prompt=()=> 'VM-only Q01 expense category';
1655 await view._promptNewCategory();
1656 } finally {
1657 window.prompt=originalPrompt;
1658 }
1659 check(document.getElementById('expCategory')?.value==='VM-only Q01 expense category',
1660 'New expense category was not selected in the form');
1661 document.getElementById('expDate').value='1405/07/18';
1662 document.getElementById('expAmount').value='1234';
1663 document.getElementById('expMethod').value='cash';
1664 document.getElementById('expRef').value='Q01-EXPENSE-001';
1665 document.getElementById('expDesc').value='VM-only Q01 expense form';
1666 await view.saveExpense(null);await wait(180);
1667 const expense=(await db.getAll('expenses')).find(x=>
1668 x.companyId===company.id&&x.refNumber==='Q01-EXPENSE-001');
1669 check(expense?.amount===1234&&expense.kind==='expense'&&
1670 expense.category==='VM-only Q01 expense category'&&expense.financePosted===true,
1671 'Expense UI did not persist and post the synthetic expense');
1672 check((await db.getAll('journal_entries')).some(x=>
1673 x.companyId===company.id&&x.sourceId===expense.id&&x.status==='posted'),
1674 'Expense UI did not create its posted journal');
1675
1676 // A posted expense is immutable through the edit form. Attempt the real UI
1677 // path and prove the record and posted journal remain unchanged.
1678 const postedBeforeEdit = JSON.stringify(await db.get('expenses', expense.id));
1679 await view.editExpense(expense.id);
1680 await wait(60);
1681 document.getElementById('expDesc').value = 'must not overwrite posted expense';
1682 const postedEditSave = [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
1683 .find(button => !button.disabled && /ذخیره/.test(button.textContent));
1684 check(postedEditSave, 'Posted expense edit form save button is missing');
1685 postedEditSave.click();
1686 await wait(100);
1687 check(JSON.stringify(await db.get('expenses', expense.id)) === postedBeforeEdit &&
1688 FINORA.Modal.stack.length === 1 && !!document.querySelector('.toast-error'),
1689 'Posted expense was changed by the direct edit UI path');
1690 FINORA.Modal.close();
1691 document.querySelectorAll('.toast .toast-close').forEach(button => button.click());
1692
1693 const draftId = 'exp_q01_synthetic_edit_draft';
1694 const user = FINORA.Auth.current();
1695 await db.put('expenses', {
1696 id: draftId, companyId: company.id, ownerUserId: user.id,
1697 kind: 'expense', category: 'Q01 draft-only edit', amount: 4321,
1698 date: '1405/07/18', method: 'cash', description: 'before UI edit',
1699 refNumber: 'Q01-EXPENSE-DRAFT-EDIT', financePosted: false
1700 });
1701 try {
1702 await view.editExpense(draftId);
1703 await wait(60);
1704 check(document.getElementById('expDesc')?.value === 'before UI edit',
1705 'Expense edit form did not load the draft fixture');
1706 document.getElementById('expDesc').value = 'after UI edit';
1707 const editSave = [...FINORA.Modal.stack.at(-1).card.querySelectorAll('.modal-footer button')]
1708 .find(button => !button.disabled && /ذخیره/.test(button.textContent));
1709 check(editSave, 'Expense edit save button is missing');
1710 editSave.click();
1711 let edited = null;
1712 for (let i = 0; i < 60; i++) {
1713 edited = await db.get('expenses', draftId);
1714 if (edited?.description === 'after UI edit' && FINORA.Modal.stack.length === 0) break;
1715 await wait(100);
1716 }
1717 check(edited?.description === 'after UI edit' && edited.financePosted === false,
1718 'Draft expense did not persist through the edit form');
1719 } finally {
1720 if (await db.get('expenses', draftId)) await db.delete('expenses', draftId);
1721 }
1722 return {expenseCreatedThroughForm:true,customCategorySelected:true,
1723 expenseJournalPosted:true,postedExpenseEditRejected:true,draftExpenseEditedThroughForm:true};
1724 }
1725
1726 async function nativeAccountingJournalAndExports() {
1727 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1728 const db=FINORA.Storage,company=await FINORA.Company.current();
1729 check(company?.id&&FINORA.Auth.isAdmin(),'Manual journal UI test requires a synthetic administrator');
1730 await FINORA.Router.go('accounting');
1731 const view=window.AccountingView;
1732 await view.refresh();
1733 const period=view.periods.find(x=>!x.closed);
1734 check(period,'An open fiscal period is required for manual journal UI testing');
1735 const postable=view.accounts.filter(a=>a.level!=='group'&&a.active!==false&&
1736 a.postable!==false&&!view.accounts.some(child=>child.parentCode===a.code));
1737 check(postable.length>=2,'Two postable accounts are required for a balanced manual journal');
1738 const used=new Set(view.accounts.map(a=>String(a.code)));
1739 const groupCode=['9','8','7','6','0'].find(x=>!used.has(x));
1740 check(groupCode,'No unused synthetic group account code available');
1741 view.openAccountModal();
1742 document.getElementById('acCode').value=groupCode;
1743 document.getElementById('acName').value='VM-only Q01 journal test group';
1744 document.getElementById('acLevel').value='group';
1745 document.getElementById('acType').value='expense';
1746 view.toggleParent();
1747 await view.saveAccount();
1748 check(view.accounts.some(x=>String(x.code)===groupCode&&x.level==='group'),
1749 'Manual chart-of-accounts form did not persist the synthetic group');
1750 const description='VM-only Q01 manual journal draft';
1751 await view.openJournalModal();
1752 check(document.getElementById('acJournalLines'),'Manual journal form did not open');
1753 const initialRows=document.querySelectorAll('#acJournalLines .ac-journal-line');
1754 check(initialRows.length===2,'Manual journal must start with two rows');
1755 view.addJournalRow();
1756 check(document.querySelectorAll('#acJournalLines .ac-journal-line').length===3,
1757 'Add journal row did not append a third line');
1758 const addedRow = document.querySelectorAll('#acJournalLines .ac-journal-line')[2];
1759 const removeAddedRow = addedRow.querySelector('button[onclick*="closest"]');
1760 check(removeAddedRow, 'Added journal row remove button is missing');
1761 removeAddedRow.click();
1762 check(document.querySelectorAll('#acJournalLines .ac-journal-line').length===2,
1763 'Journal row remove button did not restore the original two-row draft');
1764 document.getElementById('acJournalPeriod').value=period.id;
1765 document.getElementById('acJournalDate').value=period.startDate;
1766 document.getElementById('acJournalDescription').value=description;
1767 const rows=[...document.querySelectorAll('#acJournalLines .ac-journal-line')];
1768 rows[0].querySelector('.ac-line-account').value=postable[0].id;
1769 rows[0].querySelector('.ac-line-debit').value='100';
1770 rows[0].querySelector('.ac-line-credit').value='0';
1771 rows[1].querySelector('.ac-line-account').value=postable[1].id;
1772 rows[1].querySelector('.ac-line-debit').value='0';
1773 rows[1].querySelector('.ac-line-credit').value='100';
1774 await view.saveJournal('draft');
1775 let draft=(await db.getAll('journal_entries')).find(x=>
1776 x.companyId===company.id&&x.description===description&&x.status==='draft');
1777 check(draft,'Manual journal draft did not persist');
1778 const postedDescription='VM-only Q01 manual journal posted';
1779 await view.openJournalModal(draft.id);
1780 document.getElementById('acJournalDescription').value=postedDescription;
1781 await view.saveJournal('posted');
1782 const posted=(await db.getAll('journal_entries')).find(x=>
1783 x.companyId===company.id&&x.description===postedDescription&&x.status==='posted');
1784 check(posted&&posted.debit===100&&posted.credit===100,
1785 'Balanced draft was not posted through the manual journal form');
1786 await view.showJournal(posted.id);
1787 const detailsDialog = FINORA.Modal.stack.at(-1)?.card;
1788 check(detailsDialog?.textContent.includes(postedDescription),
1789 'Posted journal details did not open from the UI');
1790 const closeDetails = detailsDialog.querySelector('.modal-footer button');
1791 check(closeDetails, 'Posted journal details close action is missing');
1792 closeDetails.click();
1793 check(FINORA.Modal.stack.length === 0, 'Posted journal details dialog did not close');
1794 view.openReversal(posted.id);
1795 check(document.getElementById('acReversalId'),'Manual journal reversal form did not open');
1796 document.getElementById('acReversalPeriod').value=period.id;
1797 document.getElementById('acReversalDate').value=period.startDate;
1798 await view.saveReversal();
1799 const originalAfter=await db.get('journal_entries',posted.id);
1800 const reversal=(await db.getAll('journal_entries')).find(x=>
1801 x.companyId===company.id&&x.reversalOfId===posted.id&&x.status==='posted');
1802 check(originalAfter?.reversedById===reversal?.id&&reversal?.debit===100&&reversal?.credit===100,
1803 'Manual journal reversal did not preserve the original and post a balanced reversal');
1804 const downloads=[],originalClick=HTMLAnchorElement.prototype.click,
1805 originalCreateObjectURL=URL.createObjectURL;
1806 try {
1807 URL.createObjectURL=function(blob){
1808 const url=originalCreateObjectURL.call(URL,blob);
1809 downloads.push({blob,url,filename:''});
1810 return url;
1811 };
1812 HTMLAnchorElement.prototype.click=function(){
1813 const item=downloads.find(x=>x.url===this.href);
1814 if(item)item.filename=this.download;
1815 };
1816 await view.exportReports();
1817 await view.exportReconciliation();
1818 check(downloads.length===2,'Accounting report and reconciliation exports did not both download');
1819 const content=await Promise.all(downloads.map(async item=>({
1820 filename:item.filename,text:await item.blob.text()
1821 })));
1822 check(content.some(x=>x.filename==='factor-easypro-ledger.csv'&&
1823 x.text.includes('account_code')&&x.text.includes(postedDescription)),
1824 'Ledger CSV export omitted the posted synthetic journal');
1825 check(content.some(x=>x.filename==='factor-easypro-reconciliation.csv'&&
1826 x.text.includes('code')&&x.text.includes('reference')),
1827 'Reconciliation CSV export omitted its expected schema');
1828 } finally {
1829 URL.createObjectURL=originalCreateObjectURL;
1830 HTMLAnchorElement.prototype.click=originalClick;
1831 }
1832 return {chartAccountCreated:true,journalRowAdded:true,journalRowRemoveButtonClicked:true,
1833 draftJournalSaved:true,journalPosted:true,journalDetailsOpened:true,
1834 reversalFormOpened:true,reversalPosted:true,ledgerCsvExported:true,
1835 reconciliationCsvExported:true};
1836 }
1837
1838 async function nativeInventoryTransferAndStocktake() {
1839 const check=(ok,msg)=>{if(!ok)throw Error(msg);};
1840 const db=FINORA.Storage,company=await FINORA.Company.current();
1841 check(company?.id&&FINORA.Auth.isAdmin(),'Inventory transfer UI test requires a synthetic administrator');
1842 const balances=(await db.getAll('inventory_balances')).filter(x=>
1843 x.companyId===company.id&&x.quantityUnits>0);
1844 check(balances.length,'No positive synthetic inventory balance exists for transfer');
1845 const sourceBalance=balances[0];
1846 const product=await db.get('products',sourceBalance.productId);
1847 const warehouses=(await db.getAll('warehouses')).filter(x=>x.companyId===company.id);
1848 const source=warehouses.find(x=>x.id===sourceBalance.warehouseId);
1849 check(product?.trackInventory!==false&&source,'Transfer source product/warehouse is invalid');
1850 await FINORA.Router.go('accounting');
1851 const view=window.AccountingView;
1852 await view.refresh();
1853 const secondName='VM-only Q01 transfer destination';
1854 view.openWarehouse();
1855 document.getElementById('acWhName').value=secondName;
1856 await view.saveWarehouse();
1857 const destination=(await db.getAll('warehouses')).find(x=>
1858 x.companyId===company.id&&x.name===secondName);
1859 check(destination,'Second warehouse was not created through the UI');
1860 const quantity=Math.min(0.1,sourceBalance.quantityUnits/1000);
1861 const transferUnits=Math.round(quantity*1000);
1862 const beforeRows=await db.getAll('inventory_balances');
1863 const beforeFrom=beforeRows.find(x=>x.companyId===company.id&&
1864 x.warehouseId===source.id&&x.productId===product.id)?.quantityUnits||0;
1865 const beforeTo=beforeRows.find(x=>x.companyId===company.id&&
1866 x.warehouseId===destination.id&&x.productId===product.id)?.quantityUnits||0;
1867 await view.openTransfer();
1868 check(document.getElementById('acTrProduct')&&document.getElementById('acTrFrom')&&
1869 document.getElementById('acTrTo'),'Stock transfer form did not open');
1870 document.getElementById('acTrProduct').value=product.id;
1871 document.getElementById('acTrFrom').value=source.id;
1872 document.getElementById('acTrTo').value=destination.id;
1873 document.getElementById('acTrQty').value=String(quantity);
1874 document.getElementById('acTrDate').value='1405/07/22';
1875 await view.saveTransfer();
1876 const afterRows=await db.getAll('inventory_balances');
1877 const afterFrom=afterRows.find(x=>x.companyId===company.id&&
1878 x.warehouseId===source.id&&x.productId===product.id)?.quantityUnits||0;
1879 const afterTo=afterRows.find(x=>x.companyId===company.id&&
1880 x.warehouseId===destination.id&&x.productId===product.id)?.quantityUnits||0;
1881 check(afterFrom===beforeFrom-transferUnits&&afterTo===beforeTo+transferUnits,
1882 'Stock transfer did not move the exact milli-unit quantity between warehouses');
1883 await view.openStocktakeCreate();
1884 document.getElementById('acStWarehouse').value=source.id;
1885 document.getElementById('acStDate').value='1405/07/23';
1886 await view.createStocktake();
1887 const stocktakeId=document.getElementById('acStocktakeId')?.value;
1888 check(stocktakeId,'Stocktake create action did not open the count sheet');
1889 const countRows=[...document.querySelectorAll('#acTakeRows tr[data-product]')];
1890 check(countRows.length>0,'Stocktake did not snapshot the source warehouse balances');
1891 for(const row of countRows){
1892 const expected=Number(row.querySelector('td:nth-child(2)').textContent.trim());
1893 row.querySelector('.ac-count').value=String(expected);
1894 }
1895 await view.saveStocktake();
1896 await view.openStocktake(stocktakeId);
1897 await view.finishStocktake();
1898 const stocktake=await db.get('stocktakes',stocktakeId);
1899 const lines=await db.getAll('stocktake_lines');
1900 const ownLines=lines.filter(x=>x.companyId===company.id&&x.stocktakeId===stocktakeId);
1901 check(stocktake?.status==='posted'&&ownLines.length>0&&
1902 ownLines.every(x=>x.countedUnits===x.expectedUnits),
1903 'Stocktake did not save all counts and finalize without an inventory delta');
1904 return {secondWarehouseCreated:true,transferPosted:true,exactInventoryMoved:true,
1905 stocktakeCreated:true,stocktakeCountsSaved:true,stocktakeFinalized:true};
1906 }
1907
1908 module.exports = async function nativeFunctionalMatrix(cdp) {
1909 const phases = [
1910 ['legacy-stock-adjustment-form-and-validation', legacyStockAdjustmentFormAndValidation],
1911 ['activate-accounting-and-inventory', activateAccounting],
1912 ['integrated-stock-adjustment-guard', integratedStockAdjustmentGuard],
1913 ['contacts-crud-form-and-tags', nativeContactCrudFormAndTags],
1914 ['products-crud-form-and-nested-classifiers', nativeProductCrudFormAndNestedClassifiers],
1915 ['positive-opening-ledger-and-idempotency', nativePositiveOpeningLedger],
1916 ['purchase-and-post-ledger', purchaseInvoice],
1917 ['partial-sale-and-inventory', saleInvoice],
1918 ['invoice-quick-add-and-save-print', nativeInvoiceQuickAddAndPrint],
1919 ['auxiliary-rtl-print-rendering', nativeAuxiliaryPrintRendering],
1920 ['expense-form-category-and-posting', nativeExpenseFormAndCategory],
1921 ['manual-journal-reversal-and-exports', nativeAccountingJournalAndExports],
1922 ['inventory-transfer-and-stocktake', nativeInventoryTransferAndStocktake],
1923 ['inactive-treasury-cheque-settlement', nativeInactiveBankSettlementGuard],
1924 ['cheque-third-party-endorsement', nativeChequeThirdPartyEndorsement],
1925 ['treasury-cheque-reconciliation-readonly', nativeTreasuryChequeReconciliation],
1926 ['sale-return-immutable-stock-and-ledger', nativeSaleReturnGuardrails],
1927 ['purchase-return-and-stock-guardrails', nativePurchaseReturnGuardrails],
1928 ['return-cash-settlement-net-credit', nativeReturnCashSettlementGuardrails],
1929 ['append-only-history-bulk-clear-protection', nativeHistoryClearFailClosed],
1930 ['backup-and-atomic-rejection', nativeBackupRestore],
1931 ['rtl-invoice-print-settings', invoicePrintLayout],
1932 ['fiscal-close-atomic-guardrails', fiscalCloseGuardrails],
1933 ['opening-dry-run-rejects-existing-postings', openingDryRunWithExistingActivity]
1934 ];
1935 const report = {};
1936 for (const [name, fn] of phases) {
1937 // Toasts are transient global UI state, unlike the persistent accounting
1938 // stores. A previous phase can intentionally produce an error toast while
1939 // verifying that an invalid operation was rejected. Dismiss only those
1940 // completed-phase notices before checking the next phase's own errors.
1941 // Never dismiss modals or change any accounting data at this boundary.
1942 await cdp.evaluate(`(() => {
1943 for (const toast of document.querySelectorAll('.toast-error, .toast-warning')) {
1944 const close = toast.querySelector('.toast-close');
1945 if (close) close.click();
1946 }
1947 })()`);
1948 const value = await cdp.evaluate('(' + fn.toString() + ')()');
1949 assert.ok(value && typeof value === 'object', 'invalid native E2E result from ' + name);
1950 report[name] = value;
1951 console.log('NATIVE E2E PASSED: ' + name + ': ' + JSON.stringify(value));
1952 }
1953 return report;
1954 };