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

feat(A02): add deterministic historical opening balance preflight

* feat(A02): add non-mutating opening balance preflight for historical companies * fix(A02): require valid Jalali opening and fiscal period dates * test(A02): validate balanced opening, discrepancies, duplicates, periods and no writes

davoodmehraban89 committed Oct 14, 2026 at 23:37 UTC f4964fd8c33ac7e91fe7064bfb8dd63cd7510563
2 files changed +177
src/core/OpeningBalanceDryRun.mjs new
+107
@@ -0,0 +1,107 @@
1 +import { assertJalaliDate } from './AccountingCore.mjs';
2 +
3 +/**
4 + * Deterministic preflight for a historical-company opening balance import.
5 + * IMPORTANT: No database access or writes, journal posting or activation here.
6 + * The application must never infer opening balances from incomplete legacy
7 + * invoices or silently change cash and inventory during import.
8 + */
9 +const id = value => typeof value === 'string' && value.trim() !== '';
10 +const rial = (value, label, { signed = false } = {}) => {
11 + if (!Number.isSafeInteger(value) || (!signed && value < 0)) {
12 + throw new RangeError(label + ' باید ریال صحیح و معتبر باشد');
13 + }
14 + return value;
15 +};
16 +const plus = (a, b, label) => {
17 + const result = a + b;
18 + if (!Number.isSafeInteger(result)) throw new RangeError('سرریز ' + label);
19 + return result;
20 +};
21 +function unique(rows, key, label) {
22 + const seen = new Set();
23 + for (const row of rows) {
24 + const value = key(row);
25 + if (!id(value) || seen.has(value)) throw Error('شناسه ناقص یا تکراری ' + label);
26 + seen.add(value);
27 + }
28 +}
29 +function rows(input, name) {
30 + if (!Array.isArray(input)) throw TypeError('فهرست ' + name + ' نامعتبر است');
31 + return input;
32 +}
33 +
34 +export function previewOpeningBalances({
35 + companyId, openingDate, period,
36 + lines = [], contacts = [], stock = [], cash = [],
37 + priorPostedJournals = 0
38 +} = {}) {
39 + if (!id(companyId) || !period || period.companyId !== companyId ||
40 + period.closed || period.status === 'closed' ||
41 + typeof openingDate !== 'string' ||
42 + !/^1[34-5]\d{2}\/\d{2}\/\d{2}$/.test(openingDate) ||
43 + openingDate < period.startDate || openingDate > period.endDate) {
44 + throw Error('شرکت، دوره یا تاریخ افتتاحیه نامعتبر است');
45 + }
46 + assertJalaliDate(openingDate);
47 + assertJalaliDate(period.startDate);
48 + assertJalaliDate(period.endDate);
49 + for (const group of [lines, contacts, stock, cash]) rows(group, 'افتتاحیه');
50 + unique(lines, r => r.accountId, 'حساب افتتاحیه');
51 + unique(contacts, r => r.contactId, 'شخص');
52 + unique(stock, r => JSON.stringify([r.warehouseId, r.productId]), 'موجودی انبار');
53 + unique(cash, r => r.accountId, 'بانک یا صندوق');
54 +
55 + const allowedRoles = new Set(['receivable', 'payable', 'inventory', 'cash', 'equity', 'other']);
56 + const financial = { debit: 0, credit: 0 };
57 + const roleNet = { receivable: 0, payable: 0, inventory: 0, cash: 0 };
58 + for (const row of lines) {
59 + if (!allowedRoles.has(row.role)) throw Error('نقش حساب افتتاحیه نامعتبر است');
60 + const debit = rial(row.debit, 'بدهکار');
61 + const credit = rial(row.credit, 'بستانکار');
62 + if (debit && credit) throw Error('حساب همزمان بدهکار و بستانکار نمی‌شود');
63 + financial.debit = plus(financial.debit, debit, 'جمع بدهکار');
64 + financial.credit = plus(financial.credit, credit, 'جمع بستانکار');
65 + if (row.role in roleNet) {
66 + const normal = row.role === 'payable' ? credit - debit : debit - credit;
67 + roleNet[row.role] = plus(roleNet[row.role], normal, 'مانده نقش');
68 + }
69 + }
70 +
71 + const sources = { receivable: 0, payable: 0, inventory: 0, cash: 0 };
72 + for (const row of contacts) {
73 + sources.receivable = plus(sources.receivable, rial(row.receivable, 'طلب اشخاص'), 'طلب اشخاص');
74 + sources.payable = plus(sources.payable, rial(row.payable, 'بدهی اشخاص'), 'بدهی اشخاص');
75 + }
76 + for (const row of stock) {
77 + if (!id(row.warehouseId) || !id(row.productId) ||
78 + !Number.isSafeInteger(row.quantityUnits) || row.quantityUnits < 0) {
79 + throw Error('موجودی افتتاحیه کالا نامعتبر است');
80 + }
81 + sources.inventory = plus(sources.inventory, rial(row.value, 'ارزش موجودی'), 'ارزش موجودی');
82 + }
83 + for (const row of cash) {
84 + sources.cash = plus(sources.cash, rial(row.balance, 'مانده صندوق', { signed: true }), 'مانده نقد');
85 + }
86 + if (!Number.isSafeInteger(priorPostedJournals) || priorPostedJournals < 0) {
87 + throw Error('تعداد اسناد پیشین نامعتبر است');
88 + }
89 + const issues = [];
90 + if (priorPostedJournals > 0) issues.push('EXISTING_POSTED_JOURNALS');
91 + if (!lines.length) issues.push('MISSING_OPENING_JOURNAL_LINES');
92 + if (financial.debit !== financial.credit) issues.push('UNBALANCED_OPENING_JOURNAL');
93 + const differences = {};
94 + for (const role of Object.keys(sources)) {
95 + differences[role] = sources[role] - roleNet[role];
96 + if (!Number.isSafeInteger(differences[role])) throw new RangeError('سرریز اختلاف افتتاحیه');
97 + if (differences[role] !== 0) issues.push('OPENING_' + role.toUpperCase() + '_MISMATCH');
98 + }
99 + return Object.freeze({
100 + companyId, openingDate, readiness: issues.length === 0 ? 'ready-for-review' : 'blocked',
101 + issues: Object.freeze(issues), journal: Object.freeze(financial),
102 + sources: Object.freeze(sources), differences: Object.freeze(differences),
103 + sourceCounts: Object.freeze({ contacts: contacts.length, stock: stock.length,
104 + cash: cash.length, lines: lines.length }),
105 + writePerformed: false
106 + });
107 +}
tests/a02-opening-balance-dry-run.test.mjs new
+70
@@ -0,0 +1,70 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { previewOpeningBalances } from '../src/core/OpeningBalanceDryRun.mjs';
4 +
5 +const period = { companyId: 'c1', startDate: '1405/01/01', endDate: '1405/12/29',
6 + status: 'open', closed: false };
7 +const fixture = () => ({
8 + companyId: 'c1', openingDate: '1405/01/01', period,
9 + lines: [
10 + { accountId: 'a-rec', role: 'receivable', debit: 300, credit: 0 },
11 + { accountId: 'a-pay', role: 'payable', debit: 0, credit: 200 },
12 + { accountId: 'a-stock', role: 'inventory', debit: 500, credit: 0 },
13 + { accountId: 'a-cash', role: 'cash', debit: 100, credit: 0 },
14 + { accountId: 'a-equity', role: 'equity', debit: 0, credit: 700 }
15 + ],
16 + contacts: [{ contactId: 'customer', receivable: 300, payable: 200 }],
17 + stock: [{ warehouseId: 'warehouse', productId: 'sku', quantityUnits: 1000, value: 500 }],
18 + cash: [{ accountId: 'cash-1', balance: 100 }],
19 + priorPostedJournals: 0
20 +});
21 +
22 +test('A02: balanced opening dataset is ready for explicit review without changing anything', () => {
23 + const input = fixture();
24 + const old = structuredClone(input);
25 + const result = previewOpeningBalances(input);
26 + assert.equal(result.readiness, 'ready-for-review');
27 + assert.deepEqual(result.issues, []);
28 + assert.equal(result.journal.debit, 900);
29 + assert.equal(result.journal.credit, 900);
30 + assert.deepEqual(result.differences, { receivable: 0, payable: 0, inventory: 0, cash: 0 });
31 + assert.equal(result.writePerformed, false);
32 + assert.deepEqual(input, old);
33 + assert.equal(Object.isFrozen(result), true);
34 +});
35 +
36 +test('A02: mismatched inventory blocks activation even if journal is balanced', () => {
37 + const input = fixture();
38 + input.stock[0].value = 499;
39 + const result = previewOpeningBalances(input);
40 + assert.equal(result.readiness, 'blocked');
41 + assert.ok(result.issues.includes('OPENING_INVENTORY_MISMATCH'));
42 + assert.equal(result.differences.inventory, -1);
43 + assert.deepEqual(input.stock[0], { warehouseId: 'warehouse', productId: 'sku',
44 + quantityUnits: 1000, value: 499 });
45 +});
46 +
47 +test('A02: unbalanced journal and existing posted transactions must block write', () => {
48 + const input = fixture();
49 + input.lines[4].credit = 699;
50 + input.priorPostedJournals = 1;
51 + const report = previewOpeningBalances(input);
52 + assert.deepEqual(report.issues, ['EXISTING_POSTED_JOURNALS', 'UNBALANCED_OPENING_JOURNAL']);
53 +});
54 +
55 +test('A02: reject cross-company, closed period, date error, duplicate and integer overflow', () => {
56 + const invalid = [
57 + { companyId: 'c2' }, { period: { ...period, status: 'closed' } },
58 + { openingDate: '1405/13/31' }, { openingDate: '1406/01/01' },
59 + { priorPostedJournals: -1 },
60 + { lines: [...fixture().lines, fixture().lines[0]] },
61 + { stock: [...fixture().stock, fixture().stock[0]] },
62 + { contacts: [...fixture().contacts, fixture().contacts[0]] },
63 + { cash: [{ accountId: 'cash-1', balance: Infinity }] },
64 + { stock: [{ ...fixture().stock[0], quantityUnits: -1 }] },
65 + { lines: fixture().lines.map(x => ({ ...x, debit: Number.MAX_SAFE_INTEGER })) }
66 + ];
67 + for (const patch of invalid) {
68 + assert.throws(() => previewOpeningBalances({ ...fixture(), ...patch }));
69 + }
70 +});