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

fix(stock): atomic legacy rebuild and document integrated phase A exit

Factor EasyPro QA committed Nov 1, 2026 at 23:05 UTC d50a45e7c5736b28827dd6d793bd3003f709f468
3 files changed +100 -34
docs/PHASE_A_PACK5_INTEGRATED_EXIT_EVIDENCE.md new
+49
@@ -0,0 +1,49 @@
1 +# Phase A package 5: integrated exit evidence (NO-GO)
2 +
3 +## Scope, version and authorization
4 +
5 +- Repository: `davoodmehraban89/Factor-easyPro`.
6 +- Integration ancestry verified by `git merge-base --is-ancestor`: PR #183 head `3d2016749994f8df61d5df9937260522b2a98cd5` and PR #190 head `2933c9e5e0bd5509754f73a97a79c549452d656d` are both ancestors of PR #191 head `0a2f8ff5259f6fa535ae92eca85e2e9987cc8b30`.
7 +- Pack 5 branch: `fix/phase-a-pack5-integrated-evidence-20261101` based on PR #191. Final head is the PR head; all acceptance evidence must be checked against that exact SHA after push.
8 +- PRs #183/#190/#191 remain Draft. No merge into main, public release, private signing key, owner-data modification or independent sign-off is authorized.
9 +
10 +## Technical remediation
11 +
12 +- `InvoiceController._rebuildStockMovements` now performs movement removal and recreation inside a single IndexedDB transaction over `stock_movements` and `products`.
13 +- It validates the active company and product company. A foreign product reference aborts the transaction, preserving existing stock movements.
14 +- New regression cases assert rollback and rejection of a foreign-company invoice. Existing cross-company movement protection remains covered.
15 +- Residual limitation: legacy invoice save and stock rebuild are separate transactions. Do not represent legacy invoice issuance as fully atomic; production finance-posted issuance uses a separate posting path. A migration/upgrade and finance sign-off must evaluate this legacy boundary.
16 +
17 +## Reproducible checks on authorized Windows workstation
18 +
19 +- `npm test`: **427 passed / 427 total / 0 failed** (including migration, backup/restore, accounting, security and stock regression test files).
20 +- `npm run build`: **success**; non-blocking Vite warning for output chunks larger than 500 kB remains.
21 +- `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/a02-powershell-parse-gate.ps1`: **pass**, 8 scripts parsed; no SQL connection, no owner backup imported.
22 +- `node scripts/a08-benchmark.mjs`: synthetic fake-indexeddb, 10,000 products, 50,000 invoices, 5 companies. Company invoice read p50 291.38 ms / p95 382.29 ms; full backup export 390.61 ms; Node RSS 407.3 MiB, heap used 253.05 MiB. **Not native WebView2 or customer performance.**
23 +- `node scripts/verify-phase-a-release.mjs v2.0.3`: **exit code 1 (expected fail-closed)**; release notes still unpublished draft. This is not a passing release gate.
24 +- GitHub CI exact-head results are documented in the draft PR description after verification. Windows local test success is not equivalent to production sign-off.
25 +
26 +## Independent review perspectives (internal only, NOT independent external sign-off)
27 +
28 +1. Financial correctness: payment overrun/concurrency tests and stock-movement cross-company rollback; actual journal, refunds, historic VAT and opening balances still need external reconciliation.
29 +2. Security/data integrity: active-company guard, transaction abort, append-only and backup tests; actual licensing/signing, real backup restore and key custody remain unverified.
30 +3. Windows quality: Vite build, PowerShell parser and GitHub native lab evidence; real destination printer, installed WebView2 soak and hardware power-loss tests remain unverified.
31 +
32 +## Ten-gate acceptance decision
33 +
34 +| Gate | Accepted in manifest | Missing acceptance evidence | Responsible party |
35 +| --- | --- | --- | --- |
36 +| A01 | No | Independent reconciliation of returns, refunds, VAT, inventory and journal against approved financial reference | Independent accountant |
37 +| A02 | No | Authorized isolated Holoo migration and signed opening-balance/count reconciliation | Data owner and migration QA |
38 +| A03 | Yes (previous) | Reconfirm unchanged audit/permission invariants on final integrated SHA; previous acceptance retained | Security QA |
39 +| A04 | Yes (previous) | Reconfirm restore/immutable posting invariants on final integrated SHA; previous acceptance retained | Data integrity QA |
40 +| A05 | No | Signed representative treasury, cheque, period-close and ledger reconciliation | Independent accountant |
41 +| A06 | No | Valid production license/signing and security-owner evidence without exposing keys | Security/release owner |
42 +| A07 | No | Real Windows target install/upgrade and Persian RTL physical printer sign-off | Windows QA / operator |
43 +| A08 | No | Native WebView2 thresholds, extended soak and real failure/recovery evidence | Performance QA |
44 +| INDEPENDENT_QA | No | Named, independent accountant/QA acceptance record and discrepancy resolution | Independent accountant/QA |
45 +| DATA_BACKUP | No | Authorized owner-data encrypted pre-upgrade backup, SHA-256 and witnessed successful restore | Data owner / backup QA |
46 +
47 +Manifest: `docs/PHASE_A_RELEASE_ACCEPTANCE.json` contains **2 accepted / 8 unaccepted**. Existing GitHub CI links for unaccepted gates are supporting engineering evidence, not sign-off. A03/A04 were accepted previously; do not treat their old CI runs as proof of this final SHA without rechecking.
48 +
49 +**Decision: NO-GO.** No phase B production start, merge or public release is justified. All eight open gates require the specified external evidence and/or authorized environment access. Technical package completion is not equivalent to phase-A acceptance.
\ No newline at end of file
src/controllers/InvoiceController.js
+36 -34
@@ -194,43 +194,45 @@ class InvoiceControllerImpl {
194
195 // ثبت حرکات انبار بر اساس نوع سند
196 async _rebuildStockMovements(invoice) {
197 - const user = Auth.current();
198 - const all = await DataScope.list('stock_movements');
199 -
200 - // حذف حرکات قبلی این فاکتور
201 - for (const m of all.filter(x => x.companyId === invoice.companyId && x.refType === 'invoice' && x.refId === invoice.id)) {
202 - await StorageService.delete('stock_movements', m.id);
197 + const companyId = await DataScope.companyId();
198 + if (!invoice || invoice.companyId !== companyId) {
199 + throw new Error('Invoice stock rebuild is restricted to the active company');
200 }
201 + const user = Auth.current();
202 + const inKinds = ['purchase', 'sale_return'];
203 + const direction = inKinds.includes(invoice.kind) ? 'in' : 'out';
204
205 - // تعیین جهت
206 - const inKinds = ['purchase', 'sale_return']; // ورود به انبار
207 - const outKinds = ['sale', 'purchase_return']; // خروج از انبار
208 - const direction = inKinds.includes(invoice.kind) ? 'in' :
209 - outKinds.includes(invoice.kind) ? 'out' : 'out';
210 -
211 - // اگه پیش‌فاکتوره، حرکات ثبت نمی‌شه
212 - if (invoice.isPreInvoice) return;
213 -
214 - for (const item of invoice.items) {
215 - if (!item.productId) continue;
216 - const product = await StorageService.get('products', item.productId);
217 - if (!product || product.trackInventory === false) continue;
218 -
219 - const mv = {
220 - id: StorageService.uid('mv_'),
221 - ownerUserId: user.id,
222 - productId: item.productId,
223 - type: direction,
224 - qty: Number(item.qty) || 0,
225 - refType: 'invoice',
226 - refId: invoice.id,
227 - note: `فاکتور #${invoice.number}`,
228 - date: new Date().toISOString()
229 - };
230 - await StorageService.put('stock_movements', await DataScope.stamp('stock_movements', mv));
231 - }
205 + // Delete and recreate legacy movements in one IndexedDB transaction.
206 + // If a referenced product is invalid, nothing is deleted or inserted.
207 + return StorageService.transaction(['stock_movements', 'products'], async tx => {
208 + const movements = await tx.getAll('stock_movements');
209 + for (const movement of movements.filter(m =>
210 + m.companyId === companyId && m.refType === 'invoice' && m.refId === invoice.id)) {
211 + await tx.delete('stock_movements', movement.id);
212 + }
213 + if (invoice.isPreInvoice) return;
214 + for (const item of invoice.items || []) {
215 + if (!item.productId) continue;
216 + const product = await tx.get('products', item.productId);
217 + if (!product || product.companyId !== companyId) {
218 + throw new Error('Invoice item references a product outside the active company');
219 + }
220 + if (product.trackInventory === false) continue;
221 + await tx.put('stock_movements', {
222 + id: StorageService.uid('mv_'),
223 + ownerUserId: user.id,
224 + companyId,
225 + productId: item.productId,
226 + type: direction,
227 + qty: Number(item.qty) || 0,
228 + refType: 'invoice',
229 + refId: invoice.id,
230 + note: `Invoice #${invoice.number}`,
231 + date: new Date().toISOString()
232 + });
233 + }
234 + });
235 }
233 -
236 async getAll(filter = {}) {
237 const user = Auth.current();
238 let list = await DataScope.list('invoices');
tests/invoice-markpaid-concurrency.test.mjs
+15
@@ -99,4 +99,19 @@ test('legacy stock rebuild never deletes another company movement with same invo
99 await InvoiceController._rebuildStockMovements({ id: 'markpaid-invoice', companyId: 'markpaid-company', kind: 'sale', number: '10', isPreInvoice: true, items: [] });
100 assert.equal(await StorageService.get('stock_movements', 'local-rebuild-movement'), undefined);
101 assert.equal((await StorageService.get('stock_movements', 'foreign-rebuild-movement')).qty, 9);
102 +});
103 +test('legacy rebuild rolls back deletions when product belongs to another company', async () => {
104 + await seed();
105 + await StorageService.put('stock_movements', { id: 'rollback-existing', companyId: 'markpaid-company', refId: 'markpaid-invoice', refType: 'invoice', qty: 7 });
106 + await StorageService.put('products', { id: 'foreign-product', companyId: 'other-company', trackInventory: true });
107 + await assert.rejects(InvoiceController._rebuildStockMovements({ id: 'markpaid-invoice', companyId: 'markpaid-company', kind: 'sale', number: '10', items: [{ productId: 'foreign-product', qty: 1 }] }), /outside the active company/);
108 + assert.equal((await StorageService.get('stock_movements', 'rollback-existing')).qty, 7);
109 + assert.equal((await StorageService.getAll('stock_movements')).length, 1);
110 +});
111 +
112 +test('legacy rebuild rejects cross-company invoice without touching stock', async () => {
113 + await seed();
114 + await StorageService.put('stock_movements', { id: 'protected-movement', companyId: 'other-company', refId: 'markpaid-invoice', refType: 'invoice', qty: 5 });
115 + await assert.rejects(InvoiceController._rebuildStockMovements({ id: 'markpaid-invoice', companyId: 'other-company', isPreInvoice: true, items: [] }), /restricted to the active company/);
116 + assert.equal((await StorageService.get('stock_movements', 'protected-movement')).qty, 5);
117 });
\ No newline at end of file