فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
feat(A02): add atomic validated opening ledger posting for preloaded masters
davoodmehraban89 committed
Oct 16, 2026 at 16:40 UTC
046cfd8b26c0d4a99dfd4ba7dd7734a4044bec8b
1 file changed
+177
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();