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

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