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

fix(A04): preserve posted financial records and original authors on company restore

* fix(A04): prohibit replacing posted commercial and ledger records during company restore * test(A04): protect posted invoices, ledger lines, stock and treasury against backup replace * fix(A04): retain original author of historical ledger and treasury records on restore

davoodmehraban89 committed Oct 16, 2026 at 17:33 UTC 2a9e37b6eced39945ac7e501a10e159b795bd545
2 files changed +135 -1
src/core/CompanyBackupService.js
+41 -1
@@ -14,6 +14,11 @@ export const COMPANY_BACKUP_STORES = Object.freeze([
14 'audit_events', 'document_corrections'
15 ]);
16 const V2_STORES = new Set(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines']);
17 +const HISTORICAL_ACTOR_STORES = new Set([
18 + 'journal_entries', 'journal_lines', 'invoices', 'invoice_items',
19 + 'stock_movements', 'settlements', 'treasury', 'transactions',
20 + 'cheques', 'expenses'
21 +]);
22 const isId = id => typeof id === 'string' && id.trim().length > 0;
23
24 // Backups serialize object fields in arbitrary insertion order. Immutable
@@ -59,7 +64,11 @@ export async function restoreCompanyBackup(data, { companyId, userId, mode = 'me
64 throw new Error('رویداد ممیزی یا اصلاح سند متعلق به شرکت دیگری است');
65 }
66 const row = { ...incoming, companyId };
62 - if (row.ownerUserId && !immutable) row.ownerUserId = userId;
67 + // Never rewrite the original actor of an accounting/treasury event.
68 + // The administrator performing recovery is recorded in backup_restored.
69 + if (row.ownerUserId && !immutable && !HISTORICAL_ACTOR_STORES.has(store)) {
70 + row.ownerUserId = userId;
71 + }
72 if (store === 'journal_entries' && row.sourceType && row.sourceId) {
73 row.sourceKey = journalSourceKey(companyId, row.sourceType, row.sourceId, row.revision || 1);
74 }
@@ -74,6 +83,37 @@ export async function restoreCompanyBackup(data, { companyId, userId, mode = 'me
83 counts.skipped++;
84 continue;
85 }
86 + // Replace mode is NOT permission to rewrite posted commercial or
87 + // accounting facts. A recovery of older data must be append-only for
88 + // finalized documents; superseding them requires a new correction.
89 + let protectedPosted = false;
90 + if (existing) {
91 + protectedPosted =
92 + (store === 'journal_entries' && (existing.status === 'posted' || row.status === 'posted')) ||
93 + (store === 'invoices' && (existing.financePosted || row.financePosted)) ||
94 + (store === 'cheques' && (existing.financePosted || row.financePosted)) ||
95 + (store === 'expenses' && (existing.financePosted || row.financePosted)) ||
96 + (store === 'treasury' && (existing.recordType === 'transaction' || row.recordType === 'transaction')) ||
97 + ['stock_movements', 'settlements', 'transactions'].includes(store);
98 + if (store === 'journal_lines' || store === 'invoice_items') {
99 + const refStore = store === 'journal_lines' ? 'journal_entries' : 'invoices';
100 + const refId = store === 'journal_lines' ? row.journalId : row.invoiceId;
101 + const existingParentId = store === 'journal_lines' ? existing.journalId : existing.invoiceId;
102 + const parent = await tx.get(refStore, refId);
103 + const previousParent = refId === existingParentId ? parent :
104 + await tx.get(refStore, existingParentId);
105 + protectedPosted = store === 'journal_lines'
106 + ? parent?.status === 'posted' || previousParent?.status === 'posted'
107 + : Boolean(parent?.financePosted || previousParent?.financePosted);
108 + }
109 + }
110 + if (existing && protectedPosted) {
111 + if (!sameImmutableRecord(existing, row)) {
112 + throw new Error('بازنویسی سند مالی قطعی از فایل پشتیبان مجاز نیست');
113 + }
114 + counts.skipped++;
115 + continue;
116 + }
117 if (existing && mode === 'merge') {
118 counts.skipped++;
119 continue;
tests/a04-immutable-posted-restore.test.mjs new
+94
@@ -0,0 +1,94 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import 'fake-indexeddb/auto';
4 +import { StorageService } from '../src/core/StorageService.js';
5 +import { Auth } from '../src/core/Auth.js';
6 +import { restoreCompanyBackup } from '../src/core/CompanyBackupService.js';
7 +
8 +const companyId = 'restore-immutable-c1';
9 +const userId = 'restore-immutable-admin';
10 +async function reset() {
11 + await StorageService.clearAll();
12 + Auth.currentUser = { id: userId, username: 'manager', role: 'admin' };
13 + await StorageService.put('companies', { id: companyId, name: 'Company' });
14 +}
15 +const opts = { companyId, userId, mode: 'replace' };
16 +
17 +test('A04: replace cannot rewrite an already posted invoice or overwrite unrelated records', async () => {
18 + await reset();
19 + const original = {
20 + id: 'sale-1', companyId, kind: 'sale', number: '1',
21 + financePosted: true, grandTotal: 1000, paidAmount: 0, remaining: 1000
22 + };
23 + await StorageService.put('invoices', { ...original });
24 + const persisted = await StorageService.get('invoices', original.id);
25 +
26 + await assert.rejects(restoreCompanyBackup({
27 + contacts: [{ id: 'extra-person', companyId, name: 'Must rollback' }],
28 + invoices: [{ ...persisted, grandTotal: 1 }]
29 + }, opts), /بازنویسی سند مالی قطعی/);
30 + assert.deepEqual(await StorageService.get('invoices', original.id), persisted);
31 + assert.equal(await StorageService.get('contacts', 'extra-person'), undefined);
32 + assert.equal((await StorageService.getAll('audit_events')).length, 0);
33 +
34 + const result = await restoreCompanyBackup({ invoices: [{ ...persisted }] }, opts);
35 + assert.equal(result.skipped, 1);
36 + assert.deepEqual(await StorageService.get('invoices', original.id), persisted);
37 + assert.equal((await StorageService.getAll('audit_events')).length, 1,
38 + 'Successful restore is independently audited');
39 +});
40 +
41 +test('A04: replace cannot rewrite a line attached to a posted journal', async () => {
42 + await reset();
43 + await StorageService.put('journal_entries', {
44 + id: 'jn-posted', companyId, status: 'posted', periodId: 'period-1'
45 + });
46 + await StorageService.put('journal_lines', {
47 + id: 'jn-line-1', companyId, journalId: 'jn-posted',
48 + accountId: 'chart-1', debit: 100, credit: 0
49 + });
50 + const original = await StorageService.get('journal_lines', 'jn-line-1');
51 + await assert.rejects(restoreCompanyBackup({
52 + journal_lines: [{ ...original, debit: 999 }]
53 + }, opts), /بازنویسی سند مالی قطعی/);
54 + assert.deepEqual(await StorageService.get('journal_lines', 'jn-line-1'), original);
55 + assert.equal((await StorageService.getAll('audit_events')).length, 0);
56 +});
57 +
58 +test('A04: finalized movements, settlements and treasury transactions cannot be modified via backup', async () => {
59 + await reset();
60 + const scenarios = [
61 + ['stock_movements', { id: 'move-1', companyId, type: 'out', qty: 1 }, { qty: 100 }],
62 + ['settlements', { id: 'settled-1', companyId, invoiceId: 'sale', amount: 5 }, { amount: 999 }],
63 + ['treasury', { id: 'treasury-1', companyId, recordType: 'transaction',
64 + type: 'receipt', amount: 5 }, { amount: 999 }],
65 + ['cheques', { id: 'cheque-1', companyId, financePosted: true,
66 + amount: 5, status: 'pending' }, { status: 'cleared' }]
67 + ];
68 + for (const [store, original, changes] of scenarios) {
69 + await StorageService.put(store, { ...original });
70 + const persisted = await StorageService.get(store, original.id);
71 + await assert.rejects(restoreCompanyBackup({
72 + [store]: [{ ...persisted, ...changes }]
73 + }, opts), /بازنویسی سند مالی قطعی/);
74 + assert.deepEqual(await StorageService.get(store, original.id), persisted);
75 + }
76 + assert.equal((await StorageService.getAll('audit_events')).length, 0);
77 +});
78 +
79 +test('A04: editable draft journals remain replaceable for authorized recovery', async () => {
80 + await reset();
81 + await StorageService.put('journal_entries', {
82 + id: 'draft-1', companyId, status: 'draft',
83 + periodId: 'period-1', description: 'Old draft'
84 + });
85 + // Journal validation requires a complete chart if a journal is included in
86 + // the incoming backup, so we test the permitted edit boundary via a master.
87 + const existing = { id: 'person-1', companyId, name: 'Old' };
88 + await StorageService.put('contacts', { ...existing });
89 + const result = await restoreCompanyBackup({
90 + contacts: [{ ...(await StorageService.get('contacts', existing.id)), name: 'New' }]
91 + }, opts);
92 + assert.equal(result.updated, 1);
93 + assert.equal((await StorageService.get('contacts', existing.id)).name, 'New');
94 +});