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

feat(A02): atomically post verified opening ledger with audit and rollback

* feat(A02): add atomic validated opening ledger posting for preloaded masters * feat(A02): whitelist atomic opening-ledger audit event * fix(A02): reserve opening balance journal source for controlled service * test(A02): cover company-safe opening journal preview, posting, rollback and audit * docs(A02): document controlled opening ledger input and remaining migration boundaries

davoodmehraban89 committed Oct 16, 2026 at 16:54 UTC 6b3bcf4824d37b6b9d996bb29d56cd93f0b6a443
5 files changed +409 -2
docs/A02_OPENING_LEDGER_SCOPE_FA.md new
+60
@@ -0,0 +1,60 @@
1 +# A02 — ثبت کنترل‌شده دفتر افتتاحیه با اطلاعات پایه موجود
2 +
3 +## وضعیت
4 +
5 +این عملیات **فقط سند دفتر کل افتتاحیه** را از روی داده‌های پایه و مانده‌های
6 +**از قبل ایجادشده** می‌سازد. هیچ فاکتور قدیمی، ریز مانده شخص، گردش انبار،
7 +تراکنش بانک/صندوق یا چک را وارد نمی‌کند. بنابراین پایان کامل مهاجرت A02 نیست.
8 +
9 +## ورودی مورد انتظار
10 +
11 +`OpeningBalanceService.preview(input)` و `commit(input, {confirmation})`
12 +هر دو با یک ساختار ورودی کار می‌کنند:
13 +
14 +```js
15 +{
16 + periodId: 'fp-existing',
17 + openingDate: '1405/01/01',
18 + lines: [
19 + { accountId: 'receivable-id', role: 'receivable', debit: 300, credit: 0 },
20 + { accountId: 'payable-id', role: 'payable', debit: 0, credit: 200 },
21 + { accountId: 'inventory-id', role: 'inventory', debit: 500, credit: 0 },
22 + { accountId: 'cash-ledger-id', role: 'cash', debit: 100, credit: 0 },
23 + { accountId: 'capital-id', role: 'equity', debit: 0, credit: 700 }
24 + ],
25 + contacts: [{ contactId: 'existing-contact', receivable: 300, payable: 200 }],
26 + stock: [{
27 + warehouseId: 'existing-warehouse', productId: 'existing-product',
28 + quantityUnits: 1000, value: 500
29 + }],
30 + cash: [{ accountId: 'existing-treasury-account', balance: 100 }]
31 +}
32 +```
33 +
34 +تمام شناسه‌ها باید متعلق به **شرکت فعال و قابل دسترس** باشند.
35 +`accountId` در `lines` شناسه **حساب دفتر کل** است؛
36 +`accountId` در `cash` شناسه **حساب بانک/صندوق خزانه** است.
37 +آن‌ها را یکی فرض نکنید.
38 +
39 +## گیت‌های قبل از ثبت
40 +
41 +- فقط مدیر مجاز است. بدون `confirmation: 'CONFIRM_OPENING_LEDGER'`
42 + هیچ سندی نوشته نمی‌شود.
43 +- تاریخ افتتاحیه باید با روز اول دوره باز برابر باشد.
44 +- مجموع بدهکار و بستانکار باید هم‌ارز، غیرصفر و شامل ارقام صحیح ریال باشد.
45 +- جمع معین اشخاص، بهای موجودی و مانده بانک/صندوق باید با نقش حساب‌ها برابر باشد.
46 +- مانده انبار و بانک/صندوق باید با رکورد واقعی قبلی یکسان باشند.
47 +- هیچ سند حسابداری قطعی، فاکتور، گردش انبار، چک، انبارگردانی
48 + یا تسویه دیگری از شرکت نباید وجود داشته باشد.
49 +- **در همان تراکنش** دوباره تمام گیت‌ها کنترل می‌شوند؛ فقط سپس
50 + `journal_entries`، `journal_lines`، رسید مختصر افتتاحیه در
51 + `settings` و رویداد `audit_events` ثبت می‌شوند.
52 +- کلید منشأ سند `opening_balance` یکتا است. تکرار و خطای آخر تراکنش
53 + باید تمام نوشته‌ها را برگردانند؛ آزمون تزریق شکست موجود است.
54 +
55 +## محدودیت پذیرش
56 +
57 +قبولی تست `fake-indexeddb` و build ویندوز، اثبات صحت
58 +بازیابی اطلاعات قدیمی مشتریان، اخذ مانده شخص به شخص و چاپ گزارش نیست.
59 +پیش از استفاده تولیدی به ابزار ورود داده، پذیرش حسابداری، آزمون واقعی
60 +ارتقای نسخه و تهیه نسخه پشتیبان رمزگذاری‌شده نیاز است.
src/core/AccountingService.js
+1 -1
@@ -12,7 +12,7 @@ import {
12 } from './AccountingCore.mjs';
13
14 const requireAccountingAdmin = () => { if(!Auth.isAdmin()) throw new Error('ثبت یا ویرایش ساختار حسابداری فقط برای مدیر مجاز است'); };
15 -const RESERVED_SOURCES = new Set(['invoice','treasury','expense','cheque','cheque_status','stocktake']);
15 +const RESERVED_SOURCES = new Set(['invoice','treasury','expense','cheque','cheque_status','stocktake','opening_balance']);
16 const ensureManualSource = type => {
17 if (RESERVED_SOURCES.has(type)) throw new Error('منشأ عملیاتی رزروشده فقط توسط موتور حسابداری یکپارچه ثبت می‌شود');
18 };
src/core/AuditService.js
+2 -1
@@ -5,7 +5,8 @@ import { StorageService } from './StorageService.js';
5 const VALID_TYPES = new Set([
6 'journal_posted', 'journal_reversed', 'period_closed',
7 'commercial_journal_posted', 'draft_posted', 'draft_updated',
8 - 'draft_discarded', 'draft_created', 'period_opened', 'backup_restored'
8 + 'draft_discarded', 'draft_created', 'period_opened', 'backup_restored',
9 + 'opening_posted'
10 ]);
11 const validId = value => typeof value === 'string' && value.trim().length > 0;
12
src/core/OpeningBalanceService.js new
+177
@@ -0,0 +1,177 @@
1 +import { StorageService } from './StorageService.js';
2 +import { DataScope } from './DataScope.js';
3 +import { Auth } from './Auth.js';
4 +import { AuditService } from './AuditService.js';
5 +import {
6 + validateJournal, journalSourceKey
7 +} from './AccountingCore.mjs';
8 +import { previewOpeningBalances } from './OpeningBalanceDryRun.mjs';
9 +
10 +// Only a balanced opening ledger for VERIFIED EXISTING master data is posted.
11 +// This does not import legacy contacts, cash transactions or inventory movements.
12 +// Those must be separately reconciled before any public migration claim.
13 +const STORES = [
14 + 'fiscal_periods', 'account_chart', 'journal_entries', 'journal_lines',
15 + 'contacts', 'products', 'warehouses', 'treasury', 'inventory_balances',
16 + 'invoices', 'stock_movements', 'settlements', 'cheques', 'expenses',
17 + 'stocktakes', 'settings', 'audit_events'
18 +];
19 +
20 +const typeByRole = {
21 + receivable: 'asset',
22 + payable: 'liability',
23 + inventory: 'asset',
24 + cash: 'asset',
25 + equity: 'equity'
26 +};
27 +const assertAdmin = () => {
28 + if (!Auth.isAdmin()) throw Error('پیش‌ثبت افتتاحیه فقط برای مدیر مجاز است');
29 +};
30 +const markerId = (companyId, periodId) =>
31 + 'opening_ledger_v1:' + JSON.stringify([companyId, periodId]);
32 +const owns = (item, companyId, name) => {
33 + if (!item || item.companyId !== companyId) {
34 + throw Error(name + ' در شرکت فعال یافت نشد');
35 + }
36 + return item;
37 +};
38 +
39 +async function examine(tx, companyId, input) {
40 + const period = owns(await tx.get('fiscal_periods', input.periodId),
41 + companyId, 'دوره افتتاحیه');
42 + const journalRows = await tx.getAllByIndex('journal_entries', 'companyId', companyId);
43 + const posted = journalRows.filter(j => j.status === 'posted');
44 + const marker = await tx.get('settings', markerId(companyId, period.id));
45 + const report = previewOpeningBalances({
46 + ...input, companyId, period,
47 + priorPostedJournals: posted.length + (marker ? 1 : 0)
48 + });
49 + const problems = [...report.issues];
50 + if (input.openingDate !== period.startDate) problems.push('NOT_PERIOD_START');
51 +
52 + // Opening must not be silently layered over commercial history or stocktake.
53 + for (const store of ['invoices','stock_movements','settlements','cheques','expenses','stocktakes']) {
54 + const activities = (await tx.getAll(store)).filter(row => row.companyId === companyId);
55 + if (activities.length) problems.push('EXISTING_' + store.toUpperCase());
56 + }
57 + const cashMovements = (await tx.getAll('treasury')).filter(row =>
58 + row.companyId === companyId && row.recordType === 'transaction');
59 + if (cashMovements.length) problems.push('EXISTING_TREASURY_TRANSACTIONS');
60 + for (const row of input.contacts || []) {
61 + owns(await tx.get('contacts', row.contactId), companyId, 'شخص افتتاحیه');
62 + }
63 + for (const row of input.stock || []) {
64 + owns(await tx.get('warehouses', row.warehouseId), companyId, 'انبار افتتاحیه');
65 + owns(await tx.get('products', row.productId), companyId, 'کالای افتتاحیه');
66 + const id = JSON.stringify([companyId, row.warehouseId, row.productId]);
67 + const current = owns(await tx.get('inventory_balances', id), companyId,
68 + 'مانده موجودی');
69 + if (current.quantityUnits !== row.quantityUnits || current.value !== row.value) {
70 + problems.push('LIVE_INVENTORY_MISMATCH');
71 + }
72 + }
73 + for (const row of input.cash || []) {
74 + const account = owns(await tx.get('treasury', row.accountId),
75 + companyId, 'حساب بانکی یا صندوق');
76 + if (account.recordType !== 'account') {
77 + throw Error('مرجع افتتاحیه بانک/صندوق یک حساب خزانه نیست');
78 + }
79 + if (!Number.isSafeInteger(account.initialBalance) ||
80 + account.initialBalance !== row.balance) {
81 + problems.push('LIVE_CASH_MISMATCH');
82 + }
83 + }
84 + const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
85 + const actualById = new Map(accounts.map(row => [row.id, row]));
86 + for (const line of input.lines || []) {
87 + const acct = actualById.get(line.accountId);
88 + if (!acct) throw Error('کدینگ افتتاحیه متعلق به شرکت فعال نیست');
89 + if (line.role in typeByRole && acct.type !== typeByRole[line.role]) {
90 + throw Error('ماهیت حساب با نقش افتتاحیه هماهنگ نیست');
91 + }
92 + }
93 + // All chart rules are enforced even for readonly preview. This rejects
94 + // inactive accounts, group parents, out-of-period dates and overflow.
95 + const validated = validateJournal({
96 + companyId, date: input.openingDate, lines: (input.lines || []).map(row => ({
97 + accountId: row.accountId, debit: row.debit, credit: row.credit
98 + }))
99 + }, accounts, period);
100 + if (validated.debit !== report.journal.debit ||
101 + validated.credit !== report.journal.credit) {
102 + throw Error('گزارش افتتاحیه با سطرهای سند مطابقت ندارد');
103 + }
104 + return { period, report, problems: [...new Set(problems)], validated };
105 +}
106 +
107 +class OpeningBalanceServiceImpl {
108 + async preview(input) {
109 + assertAdmin();
110 + const companyId = await DataScope.companyId();
111 + return StorageService.transaction(STORES, async tx => {
112 + const result = await examine(tx, companyId, input);
113 + return {
114 + ...result.report, issues: result.problems,
115 + readiness: result.problems.length ? 'blocked' : 'ready-for-review',
116 + writePerformed: false
117 + };
118 + }, 'readonly');
119 + }
120 +
121 + async commit(input, { confirmation } = {}) {
122 + assertAdmin();
123 + if (confirmation !== 'CONFIRM_OPENING_LEDGER') {
124 + throw Error('تأیید صریح ثبت قطعی افتتاحیه لازم است');
125 + }
126 + const companyId = await DataScope.companyId();
127 + return StorageService.transaction(STORES, async tx => {
128 + // Re-evaluate inside the SAME write transaction. Never trust a stale
129 + // previous preview if the fiscal period or master data has changed.
130 + const { period, report, problems, validated } =
131 + await examine(tx, companyId, input);
132 + if (problems.length) {
133 + throw Error('افتتاحیه به دلیل مغایرت متوقف شد: ' + problems.join(', '));
134 + }
135 + const id = StorageService.uid('jn_open_');
136 + const sourceKey = journalSourceKey(companyId, 'opening_balance', period.id);
137 + const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
138 + if (existing.length) throw Error('سند افتتاحیه قبلاً ثبت شده است');
139 +
140 + const now = new Date().toISOString();
141 + const userId = Auth.current().id;
142 + const journal = {
143 + id, companyId, periodId: period.id, date: input.openingDate,
144 + status: 'posted', description: 'سند افتتاحیه کنترل‌شده',
145 + sourceKey, sourceType: 'opening_balance', sourceId: period.id,
146 + revision: 1, ...validated, createdBy: userId,
147 + postedBy: userId, postedAt: now
148 + };
149 + await tx.add('journal_entries', journal);
150 + for (const [position, line] of input.lines.entries()) {
151 + await tx.add('journal_lines', {
152 + id: StorageService.uid('jl_open_'), companyId, journalId: id,
153 + position, accountId: line.accountId,
154 + debit: line.debit, credit: line.credit,
155 + description: ''
156 + });
157 + }
158 + await tx.add('settings', {
159 + id: markerId(companyId, period.id), companyId,
160 + schemaVersion: 1, mode: 'existing-master-opening-ledger',
161 + journalId: id, periodId: period.id, createdAt: now, createdBy: userId,
162 + counts: report.sourceCounts, totals: report.journal,
163 + // Deliberately do not store customer names, amounts by contact or
164 + // a second editable copy of sensitive source spreadsheet contents.
165 + reconciled: report.issues.length === 0
166 + });
167 + await AuditService.append(tx, {
168 + companyId, eventType: 'opening_posted', sourceType: 'journal',
169 + sourceId: id, commandKey: 'opening-ledger:' + period.id,
170 + businessDate: input.openingDate, lineCount: input.lines.length
171 + });
172 + return { journalId: id, periodId: period.id, companyId,
173 + totals: report.journal, status: 'posted' };
174 + });
175 + }
176 +}
177 +export const OpeningBalanceService = new OpeningBalanceServiceImpl();
tests/a02-opening-posting-integration.test.mjs new
+169
@@ -0,0 +1,169 @@
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 { OpeningBalanceService } from '../src/core/OpeningBalanceService.js';
6 +import { AccountingService } from '../src/core/AccountingService.js';
7 +import { CompanyService } from '../src/core/CompanyService.js';
8 +import { Auth } from '../src/core/Auth.js';
9 +import { AuditService } from '../src/core/AuditService.js';
10 +
11 +const C = 'opening-c1';
12 +const mkDate = '1405/01/01';
13 +
14 +async function setup() {
15 + await StorageService.clearAll();
16 + Auth.currentUser = { id: 'opening-admin', role: 'admin', username: 'manager' };
17 + await StorageService.put('companies', { id: C, name: 'Synthetic accounting company' });
18 + await StorageService.put('companies', { id: 'opening-c2', name: 'Other company' });
19 + CompanyService.activeCompanyId = C;
20 + const period = await AccountingService.createPeriod({
21 + name: '1405', startDate: mkDate, endDate: '1405/12/29'
22 + });
23 + await AccountingService.seedDefaultChart();
24 + const chart = await AccountingService.listAccounts();
25 + const byCode = code => {
26 + const account = chart.find(row => row.code === code);
27 + assert.ok(account, 'missing chart account ' + code);
28 + return account.id;
29 + };
30 + await StorageService.put('contacts', { id: 'c1-contact', companyId: C, name: 'Example customer' });
31 + await StorageService.put('products', { id: 'c1-stock', companyId: C, name: 'Example product', trackInventory: true });
32 + await StorageService.put('warehouses', { id: 'c1-warehouse', companyId: C, name: 'Example warehouse' });
33 + await StorageService.put('treasury', {
34 + id: 'c1-cash', companyId: C, name: 'Cash account', recordType: 'account', initialBalance: 100
35 + });
36 + await StorageService.put('inventory_balances', {
37 + id: JSON.stringify([C, 'c1-warehouse', 'c1-stock']),
38 + companyId: C, warehouseId: 'c1-warehouse', productId: 'c1-stock',
39 + quantityUnits: 1000, value: 500
40 + });
41 +
42 + return {
43 + period,
44 + input: {
45 + periodId: period.id, openingDate: mkDate,
46 + lines: [
47 + { accountId: byCode('102'), role: 'receivable', debit: 300, credit: 0 },
48 + { accountId: byCode('201'), role: 'payable', debit: 0, credit: 200 },
49 + { accountId: byCode('103'), role: 'inventory', debit: 500, credit: 0 },
50 + { accountId: byCode('101'), role: 'cash', debit: 100, credit: 0 },
51 + { accountId: byCode('301'), role: 'equity', debit: 0, credit: 700 }
52 + ],
53 + contacts: [{ contactId: 'c1-contact', receivable: 300, payable: 200 }],
54 + stock: [{ warehouseId: 'c1-warehouse', productId: 'c1-stock',
55 + quantityUnits: 1000, value: 500 }],
56 + cash: [{ accountId: 'c1-cash', balance: 100 }]
57 + }
58 + };
59 +}
60 +
61 +test('A02: source-scoped opening preview never modifies indexeddb', async () => {
62 + const { input } = await setup();
63 + const before = await StorageService.getAll('journal_entries');
64 + const report = await OpeningBalanceService.preview(input);
65 + assert.equal(report.readiness, 'ready-for-review');
66 + assert.equal(report.journal.debit, 900);
67 + assert.equal(report.journal.credit, 900);
68 + assert.equal(report.writePerformed, false);
69 + assert.deepEqual(await StorageService.getAll('journal_entries'), before);
70 + assert.equal((await AuditService.list()).filter(row => row.eventType === 'opening_posted').length, 0);
71 +});
72 +
73 +test('A02: controlled opening posts balanced journal, marker and audit atomically, then blocks replay', async () => {
74 + const { period, input } = await setup();
75 + await assert.rejects(OpeningBalanceService.commit(input), /تأیید صریح/);
76 + const posted = await OpeningBalanceService.commit(input, {
77 + confirmation: 'CONFIRM_OPENING_LEDGER'
78 + });
79 + assert.equal(posted.status, 'posted');
80 + assert.deepEqual(posted.totals, { debit: 900, credit: 900 });
81 + const journal = await AccountingService.getJournal(posted.journalId);
82 + assert.equal(journal.sourceType, 'opening_balance');
83 + assert.equal(journal.sourceId, period.id);
84 + assert.equal(journal.status, 'posted');
85 + assert.equal(journal.lines.length, 5);
86 + assert.equal(journal.debit, 900);
87 + assert.equal(journal.credit, 900);
88 + const trial = await AccountingService.trialBalance({ periodId: period.id });
89 + assert.deepEqual(trial.totals, { debit: 900, credit: 900 });
90 + const audit = await AuditService.list();
91 + assert.equal(audit.filter(row => row.eventType === 'opening_posted').length, 1);
92 + const marker = (await StorageService.getAll('settings'))
93 + .find(row => row.companyId === C && row.mode === 'existing-master-opening-ledger');
94 + assert.equal(marker.journalId, posted.journalId);
95 + assert.equal(marker.totals.credit, 900);
96 + assert.ok(!JSON.stringify(marker).includes('Example customer'));
97 +
98 + await assert.rejects(OpeningBalanceService.commit(input, {
99 + confirmation: 'CONFIRM_OPENING_LEDGER'
100 + }), /افتتاحیه به دلیل مغایرت/);
101 + assert.equal((await StorageService.getAll('journal_entries')).length, 1);
102 + assert.equal((await AuditService.list()).filter(row => row.eventType === 'opening_posted').length, 1);
103 +});
104 +
105 +test('A02: inconsistent live inventory or cash blocks posting without touching bookkeeping', async () => {
106 + const { input } = await setup();
107 + const item = await StorageService.get('inventory_balances',
108 + JSON.stringify([C, 'c1-warehouse', 'c1-stock']));
109 + await StorageService.put('inventory_balances', { ...item, value: 499 });
110 + const preview = await OpeningBalanceService.preview(input);
111 + assert.ok(preview.issues.includes('LIVE_INVENTORY_MISMATCH'));
112 + await assert.rejects(OpeningBalanceService.commit(input, {
113 + confirmation: 'CONFIRM_OPENING_LEDGER'
114 + }), /LIVE_INVENTORY_MISMATCH/);
115 + assert.equal((await StorageService.getAll('journal_entries')).length, 0);
116 +
117 + await StorageService.put('inventory_balances', { ...item, value: 500 });
118 + const cash = await StorageService.get('treasury', 'c1-cash');
119 + await StorageService.put('treasury', { ...cash, initialBalance: 10 });
120 + assert.ok((await OpeningBalanceService.preview(input)).issues.includes('LIVE_CASH_MISMATCH'));
121 + assert.equal((await StorageService.getAll('journal_entries')).length, 0);
122 +});
123 +
124 +test('A02: commercial history and foreign-company master references block opening', async () => {
125 + const { input } = await setup();
126 + await StorageService.put('invoices', {
127 + id: 'historic-c1-invoice', companyId: C, kind: 'sale', grandTotal: 100
128 + });
129 + assert.ok((await OpeningBalanceService.preview(input)).issues.includes('EXISTING_INVOICES'));
130 + await assert.rejects(OpeningBalanceService.commit(input, {
131 + confirmation: 'CONFIRM_OPENING_LEDGER'
132 + }), /EXISTING_INVOICES/);
133 + await StorageService.delete('invoices', 'historic-c1-invoice');
134 + await StorageService.put('contacts', {
135 + id: 'foreign-customer', companyId: 'opening-c2', name: 'Not accessible'
136 + });
137 + const foreign = structuredClone(input);
138 + foreign.contacts[0].contactId = 'foreign-customer';
139 + await assert.rejects(OpeningBalanceService.preview(foreign), /شرکت فعال/);
140 + assert.equal((await StorageService.getAll('journal_entries')).length, 0);
141 +});
142 +
143 +test('A02: failed audit insert at transaction end rolls back already inserted journal and receipt', async () => {
144 + const { period, input } = await setup();
145 + // This unique command index simulates an audit record already committed
146 + // outside of this posting; the late constraint failure must roll back all.
147 + await StorageService.put('audit_events', {
148 + id: 'existing-opening-key', companyId: C,
149 + commandKey: C + ':opening-ledger:' + period.id,
150 + eventType: 'opening_posted', sourceId: 'prior-event'
151 + });
152 + await assert.rejects(OpeningBalanceService.commit(input, {
153 + confirmation: 'CONFIRM_OPENING_LEDGER'
154 + }));
155 + assert.equal((await StorageService.getAll('journal_entries')).length, 0);
156 + assert.equal((await StorageService.getAll('journal_lines')).length, 0);
157 + assert.equal((await StorageService.getAll('settings'))
158 + .filter(row => row.mode === 'existing-master-opening-ledger').length, 0);
159 +});
160 +
161 +test('A02: ordinary users cannot preview or post ledger opening', async () => {
162 + const { input } = await setup();
163 + Auth.currentUser = { id: 'other-staff', role: 'user', username: 'staff',
164 + companyIds: [C] };
165 + await assert.rejects(OpeningBalanceService.preview(input), /فقط برای مدیر/);
166 + await assert.rejects(OpeningBalanceService.commit(input, {
167 + confirmation: 'CONFIRM_OPENING_LEDGER'
168 + }), /فقط برای مدیر/);
169 +});