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

ci/a06-require-trusted-issuer-for-release
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 413 lines 23.1 KB
Raw
1 // Factor-easyPro V2 / Phase 1: company-scoped, atomic double-entry ledger.
2 // No automatic posting from legacy invoices until Phase 2's unified transaction.
3 import { StorageService } from './StorageService.js';
4 import { DataScope } from './DataScope.js';
5 import { Auth } from './Auth.js';
6 import { AuditService } from './AuditService.js';
7 import { buildLedgerReports } from './LedgerReports.mjs';
8 import { reconcileFinancialData } from './ReconciliationCore.mjs';
9 import {
10 DEFAULT_CHART, assertJalaliDate, validateAccount, validateFiscalPeriod,
11 validateJournal, validateJournalLines, journalSourceKey, reversingLines
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']);
16 const ensureManualSource = type => {
17 if (RESERVED_SOURCES.has(type)) throw new Error('منشأ عملیاتی رزروشده فقط توسط موتور حسابداری یکپارچه ثبت می‌شود');
18 };
19 const uid = prefix => StorageService.uid(prefix);
20 const actor = () => Auth.current()?.id || null;
21 const entriesFor = (tx, companyId) => tx.getAllByIndex('journal_entries', 'companyId', companyId);
22 const periodFor = async (tx, companyId, periodId) => {
23 const period = await tx.get('fiscal_periods', periodId);
24 if (!period || period.companyId !== companyId) throw new Error('دوره مالی این شرکت پیدا نشد');
25 return period;
26 };
27 const ensurePeriodOpen = period => {
28 if (period.closed || period.status === 'closed') throw new Error('دوره مالی بسته است');
29 };
30 const cleanLines = lines => (lines || []).map(line => ({
31 accountId: line.accountId,
32 debit: line.debit,
33 credit: line.credit,
34 description: String(line.description || '').trim()
35 }));
36
37 class AccountingServiceImpl {
38 async financialReports(filter = {}) {
39 const companyId = await DataScope.companyId();
40 if (filter.from) assertJalaliDate(filter.from);
41 if (filter.to) assertJalaliDate(filter.to);
42 return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines', 'fiscal_periods'], async tx => {
43 if (filter.periodId) {
44 const period = await tx.get('fiscal_periods', filter.periodId);
45 if (!period || period.companyId !== companyId) throw new Error('دوره مالی انتخاب‌شده متعلق به شرکت فعال نیست');
46 }
47 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
48 const journals = await tx.getAllByIndex('journal_entries', 'companyId', companyId);
49 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
50 return buildLedgerReports(accounts, journals, lines, filter);
51 }, 'readonly');
52 }
53 // Read-only, company-scoped snapshot. It never rewrites balances or journals.
54 async reconciliationReport() {
55 if (!Auth.isAdmin()) throw new Error('گزارش کنترل مغایرت فقط برای مدیر مجاز است');
56 const companyId = await DataScope.companyId();
57 const stores = ['account_chart','journal_entries','journal_lines','invoices',
58 'settlements','treasury','inventory_balances','stock_movements','settings'];
59 return StorageService.transaction(stores, async tx => {
60 const scoped = async store =>
61 (await tx.getAll(store)).filter(row => row.companyId === companyId);
62 const [accounts,journals,journalLines,invoices,settlements,transactions,
63 inventoryBalances,stockMovements,activation] = await Promise.all([
64 scoped('account_chart'),scoped('journal_entries'),scoped('journal_lines'),
65 scoped('invoices'),scoped('settlements'),scoped('treasury'),
66 scoped('inventory_balances'),scoped('stock_movements'),
67 tx.get('settings','finance_v2_enabled_'+companyId)
68 ]);
69 return reconcileFinancialData({accounts,journals,journalLines,invoices,
70 settlements,transactions,inventoryBalances,stockMovements,
71 integrated:!!activation?.enabled});
72 },'readonly');
73 }
74
75 async listAccounts() {
76 const companyId = await DataScope.companyId();
77 return StorageService.getAllByIndex('account_chart', 'companyId', companyId);
78 }
79
80 async addAccount(data) {
81 requireAccountingAdmin();
82 const companyId = await DataScope.companyId();
83 const account = {
84 id: uid('acc_'), code: String(data.code || '').trim(),
85 name: String(data.name || '').trim(), level: data.level, type: data.type,
86 parentCode: data.parentCode || null, active: data.active !== false,
87 postable: data.postable !== false, companyId, createdBy: actor()
88 };
89 return StorageService.transaction(['account_chart', 'journal_lines'], async tx => {
90 const existing = await tx.getAllByIndex('account_chart', 'companyId', companyId);
91 validateAccount(account, existing);
92 // A posting account may not become a parent after journal lines exist.
93 // Otherwise future postings would be rejected while historical balances remain ambiguous.
94 if (account.parentCode) {
95 const parent = existing.find(a => a.code === account.parentCode);
96 const movements = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
97 if (movements.some(line => line.accountId === parent.id)) {
98 throw new Error('حساب والد گردش مالی دارد؛ افزودن زیرحساب به آن مجاز نیست');
99 }
100 }
101 await tx.put('account_chart', account);
102 return account;
103 });
104 }
105
106 async seedDefaultChart() {
107 requireAccountingAdmin();
108 const companyId = await DataScope.companyId();
109 return StorageService.transaction('account_chart', async tx => {
110 const existing = await tx.getAllByIndex('account_chart', 'companyId', companyId);
111 let added = 0;
112 for (const template of DEFAULT_CHART) {
113 if (existing.some(a => a.code === template.code)) continue;
114 const account = { ...template, companyId, id: uid('acc_'), active: true, createdBy: actor() };
115 validateAccount(account, existing);
116 await tx.put('account_chart', account);
117 existing.push(account);
118 added++;
119 }
120 return { added, total: existing.length };
121 });
122 }
123
124 async listPeriods() {
125 return StorageService.getAllByIndex('fiscal_periods', 'companyId', await DataScope.companyId());
126 }
127
128 async createPeriod(data) {
129 requireAccountingAdmin();
130 const companyId = await DataScope.companyId();
131 const period = {
132 id: uid('fp_'), companyId, name: String(data.name || '').trim(),
133 startDate: data.startDate, endDate: data.endDate,
134 status: 'open', closed: false, createdBy: actor()
135 };
136 if (!period.name) throw new Error('نام دوره مالی الزامی است');
137 return StorageService.transaction(['fiscal_periods', 'audit_events'], async tx => {
138 validateFiscalPeriod(period, await tx.getAllByIndex('fiscal_periods', 'companyId', companyId));
139 await tx.put('fiscal_periods', period);
140 await AuditService.append(tx, { companyId, eventType: 'period_opened',
141 sourceType: 'fiscal_period', sourceId: period.id,
142 commandKey: 'open-period:' + period.id, businessDate: period.startDate });
143 return period;
144 });
145 }
146
147 async closePeriod(periodId) {
148 if (!Auth.isAdmin()) throw new Error('بستن دوره مالی فقط برای مدیر مجاز است');
149 const companyId = await DataScope.companyId();
150 return StorageService.transaction([
151 'fiscal_periods', 'journal_entries', 'journal_lines',
152 'account_chart', 'stocktakes', 'audit_events'
153 ], async tx => {
154 const period = await periodFor(tx, companyId, periodId);
155 ensurePeriodOpen(period);
156 const journals = (await entriesFor(tx, companyId)).filter(j => j.periodId === periodId);
157 if (journals.some(j => j.status !== 'posted')) {
158 throw new Error('دوره دارای اسناد پیش‌نویس است؛ ابتدا تعیین تکلیف شوند');
159 }
160 const stocktakes = (await tx.getAllByIndex('stocktakes', 'companyId', companyId))
161 .filter(row => row.status === 'draft');
162 if (stocktakes.length) {
163 throw new Error('انبارگردانی باز وجود دارد؛ ابتدا شمارش را نهایی کنید');
164 }
165 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
166 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
167 const byJournal = new Map();
168 for (const line of lines) {
169 if (!byJournal.has(line.journalId)) byJournal.set(line.journalId, []);
170 byJournal.get(line.journalId).push(line);
171 }
172 for (const journal of journals) {
173 if (journal.date < period.startDate || journal.date > period.endDate) {
174 throw new Error('دوره شامل سندی با تاریخ خارج از محدوده است');
175 }
176 const rowLines = byJournal.get(journal.id) || [];
177 if (rowLines.length < 2) throw new Error('دوره شامل سند قطعی بدون سطرهای کامل است');
178 validateJournalLines({ companyId, lines: rowLines }, accounts,
179 { requireBalance: true, allowInactive: true, allowParent: true });
180 }
181 const closed = { ...period, status: 'closed', closed: true, closedBy: actor(), closedAt: new Date().toISOString() };
182 await tx.put('fiscal_periods', closed);
183 await AuditService.append(tx, { companyId, eventType: 'period_closed', sourceType: 'fiscal_period',
184 sourceId: periodId, commandKey: 'close-period:' + periodId, businessDate: period.endDate });
185 return closed;
186 });
187 }
188
189 async listJournals({ periodId, status } = {}) {
190 const companyId = await DataScope.companyId();
191 const rows = await StorageService.getAllByIndex('journal_entries', 'companyId', companyId);
192 return rows.filter(j => (!periodId || j.periodId === periodId) && (!status || j.status === status))
193 .sort((a, b) => String(a.date).localeCompare(String(b.date)) || String(a.id).localeCompare(String(b.id)));
194 }
195
196 async getJournal(id) {
197 const companyId = await DataScope.companyId();
198 return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
199 const journal = await tx.get('journal_entries', id);
200 if (!journal || journal.companyId !== companyId) throw new Error('سند در این شرکت یافت نشد');
201 const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id))
202 .filter(l => l.companyId === companyId)
203 .sort((a, b) => a.position - b.position);
204 return { ...journal, lines };
205 }, 'readonly');
206 }
207
208 // Drafts can be unbalanced, but must use valid accounts, dates and integer rial amounts.
209 async saveDraftJournal(data) {
210 requireAccountingAdmin();
211 ensureManualSource(data.sourceType);
212 const companyId = await DataScope.companyId();
213 const id = uid('jn_');
214 const lines = cleanLines(data.lines);
215 const sourceKey = data.sourceType && data.sourceId
216 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
217 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
218 const period = await periodFor(tx, companyId, data.periodId);
219 ensurePeriodOpen(period);
220 assertJalaliDate(data.date);
221 if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
222 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
223 const totals = validateJournalLines({ ...data, lines, companyId }, accounts, { requireBalance: false });
224 if (sourceKey) {
225 const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
226 if (existing.length) throw new Error('برای این منشأ قبلاً سند ثبت شده است');
227 }
228 const journal = { id, companyId, periodId: data.periodId, date: data.date,
229 description: String(data.description || '').trim(), status: 'draft',
230 sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
231 revision: data.revision || 1, ...totals, createdBy: actor() };
232 await tx.put('journal_entries', journal);
233 for (const [position, line] of lines.entries()) {
234 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
235 }
236 await AuditService.append(tx, { companyId, eventType: 'draft_created', sourceType: 'journal',
237 sourceId: journal.id, commandKey: 'draft-create:' + journal.id,
238 businessDate: journal.date, lineCount: lines.length });
239 return journal;
240 });
241 }
242
243 async updateDraftJournal(id, data, { post = false } = {}) {
244 requireAccountingAdmin();
245 const companyId = await DataScope.companyId();
246 const lines = cleanLines(data.lines);
247 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
248 const old = await tx.get('journal_entries', id);
249 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل ویرایش است');
250 const period = await periodFor(tx, companyId, data.periodId);
251 ensurePeriodOpen(period);
252 assertJalaliDate(data.date);
253 if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
254 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
255 const totals = post
256 ? validateJournal({ companyId, date: data.date, lines }, accounts, period)
257 : validateJournalLines({ companyId, lines }, accounts, { requireBalance: false });
258 const journal = {
259 ...old, periodId: data.periodId, date: data.date,
260 description: String(data.description || '').trim(), ...totals,
261 status: post ? 'posted' : 'draft',
262 ...(post ? { postedBy: actor(), postedAt: new Date().toISOString() } : {}),
263 updatedBy: actor(), updatedAt: new Date().toISOString()
264 };
265 const prior = await tx.getAllByIndex('journal_lines', 'journalId', id);
266 for (const line of prior) await tx.delete('journal_lines', line.id);
267 await tx.put('journal_entries', journal);
268 for (const [position, line] of lines.entries()) {
269 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
270 }
271 await AuditService.append(tx, { companyId, eventType: post ? 'draft_posted' : 'draft_updated',
272 sourceType: 'journal', sourceId: journal.id,
273 commandKey: 'draft-change:' + uid('edit_'),
274 businessDate: journal.date, lineCount: lines.length });
275 return journal;
276 });
277 }
278
279 async postJournal(data) {
280 requireAccountingAdmin();
281 ensureManualSource(data.sourceType);
282 const companyId = await DataScope.companyId();
283 const id = uid('jn_');
284 const lines = cleanLines(data.lines);
285 const sourceKey = data.sourceType && data.sourceId
286 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
287 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
288 const period = await periodFor(tx, companyId, data.periodId);
289 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
290 const totals = validateJournal({ companyId, date: data.date, lines }, accounts, period);
291 if (sourceKey) {
292 const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
293 if (existing.length) throw new Error('ثبت دوباره برای این منشأ مجاز نیست');
294 }
295 const journal = { id, companyId, periodId: data.periodId, date: data.date,
296 description: String(data.description || '').trim(), status: 'posted',
297 sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
298 revision: data.revision || 1, ...totals, createdBy: actor(), postedBy: actor(),
299 postedAt: new Date().toISOString() };
300 await tx.put('journal_entries', journal);
301 for (const [position, line] of lines.entries()) {
302 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
303 }
304 await AuditService.append(tx, { companyId, eventType: 'journal_posted', sourceType: 'journal',
305 sourceId: journal.id, commandKey: 'manual-journal:' + (sourceKey || journal.id),
306 businessDate: journal.date, lineCount: lines.length });
307 return journal;
308 });
309 }
310
311 async discardDraftJournal(id) {
312 requireAccountingAdmin();
313 const companyId = await DataScope.companyId();
314 return StorageService.transaction(['journal_entries', 'journal_lines', 'audit_events'], async tx => {
315 const old = await tx.get('journal_entries', id);
316 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل حذف است');
317 const lines = await tx.getAllByIndex('journal_lines', 'journalId', id);
318 for (const line of lines) await tx.delete('journal_lines', line.id);
319 await tx.delete('journal_entries', id);
320 await AuditService.append(tx, { companyId, eventType: 'draft_discarded',
321 sourceType: 'journal', sourceId: id, commandKey: 'draft-discard:' + id,
322 businessDate: old.date, lineCount: lines.length });
323 return true;
324 });
325 }
326
327 async postDraftJournal(id) {
328 requireAccountingAdmin();
329 const companyId = await DataScope.companyId();
330 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
331 const old = await tx.get('journal_entries', id);
332 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('پیش‌نویس قابل ثبت پیدا نشد');
333 const period = await periodFor(tx, companyId, old.periodId);
334 const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id)).filter(l => l.companyId === companyId);
335 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
336 const totals = validateJournal({ companyId, date: old.date, lines }, accounts, period);
337 const journal = { ...old, ...totals, status: 'posted', postedBy: actor(), postedAt: new Date().toISOString() };
338 await tx.put('journal_entries', journal);
339 await AuditService.append(tx, { companyId, eventType: 'draft_posted',
340 sourceType: 'journal', sourceId: id, commandKey: 'draft-finalize:' + id,
341 businessDate: journal.date, lineCount: lines.length });
342 return journal;
343 });
344 }
345
346 async reverseJournal(originalId, { periodId, date, description = '' }) {
347 requireAccountingAdmin();
348 const companyId = await DataScope.companyId();
349 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
350 const original = await tx.get('journal_entries', originalId);
351 if (!original || original.companyId !== companyId || original.status !== 'posted' ||
352 original.reversedById || original.reversalOfId) throw new Error('این سند قابل برگشت نیست');
353 // Reversing commercial GL alone would leave invoice, cash and stock inconsistent.
354 if (['invoice','treasury','expense','cheque','cheque_status','stocktake'].includes(original.sourceType))
355 throw new Error('سند تجاری را نمی‌توان جداگانه معکوس کرد؛ اصلاح باید از سند عملیاتی منشأ انجام شود');
356 const period = await periodFor(tx, companyId, periodId);
357 const oldLines = (await tx.getAllByIndex('journal_lines', 'journalId', originalId))
358 .filter(l => l.companyId === companyId)
359 .sort((a, b) => a.position - b.position);
360 const lines = reversingLines(oldLines);
361 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
362 // Historical reversals remain valid even when source accounts were later deactivated or given children.
363 const totals = validateJournal({ companyId, date, lines }, accounts, period, { allowInactive: true, allowParent: true });
364 const key = journalSourceKey(companyId, 'journal_reversal', originalId);
365 if ((await tx.getAllByIndex('journal_entries', 'sourceKey', key)).length) throw new Error('برگشت سند تکراری است');
366 const id = uid('jn_');
367 const journal = { id, companyId, periodId, date, description: String(description).trim() || `برگشت سند ${originalId}`,
368 status: 'posted', sourceKey: key, sourceType: 'journal_reversal', sourceId: originalId,
369 revision: 1, reversalOfId: originalId, ...totals, createdBy: actor(),
370 postedBy: actor(), postedAt: new Date().toISOString() };
371 await tx.put('journal_entries', journal);
372 for (const [position, line] of lines.entries()) {
373 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
374 }
375 await tx.put('journal_entries', { ...original, reversedById: id, reversedAt: journal.postedAt });
376 await AuditService.append(tx, { companyId, eventType: 'journal_reversed', sourceType: 'journal',
377 sourceId: id, commandKey: 'manual-reversal:' + originalId, businessDate: date,
378 lineCount: lines.length });
379 return journal;
380 });
381 }
382
383 async trialBalance({ periodId } = {}) {
384 const companyId = await DataScope.companyId();
385 return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines'], async tx => {
386 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
387 const journals = (await entriesFor(tx, companyId))
388 .filter(j => j.status === 'posted' && (!periodId || j.periodId === periodId));
389 const valid = new Set(journals.map(j => j.id));
390 const entries = new Map(accounts.map(a => [a.id, {
391 accountId: a.id, code: a.code, name: a.name, debit: 0, credit: 0, balance: 0
392 }]));
393 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
394 for (const line of lines) {
395 if (!valid.has(line.journalId)) continue;
396 const row = entries.get(line.accountId);
397 if (!row) throw new Error('سطر سند به حساب حذف‌شده اشاره دارد');
398 row.debit += line.debit;
399 row.credit += line.credit;
400 if (!Number.isSafeInteger(row.debit) || !Number.isSafeInteger(row.credit)) throw new Error('سرریز مانده حساب');
401 row.balance = row.debit - row.credit;
402 }
403 const rows = [...entries.values()].filter(r => r.debit || r.credit)
404 .sort((a, b) => a.code.localeCompare(b.code, 'fa'));
405 const totals = rows.reduce((sum, r) => ({ debit: sum.debit + r.debit, credit: sum.credit + r.credit }), { debit: 0, credit: 0 });
406 if (!Number.isSafeInteger(totals.debit) || !Number.isSafeInteger(totals.credit) ||
407 totals.debit !== totals.credit) throw new Error('گردش حساب‌ها تراز نیست');
408 return { companyId, periodId: periodId || null, rows, totals };
409 }, 'readonly');
410 }
411 }
412
413 export const AccountingService = new AccountingServiceImpl();