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

feat/a03-audit-schema-atomic-events
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 373 lines 20.6 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', async tx => {
138 validateFiscalPeriod(period, await tx.getAllByIndex('fiscal_periods', 'companyId', companyId));
139 await tx.put('fiscal_periods', period);
140 return period;
141 });
142 }
143
144 async closePeriod(periodId) {
145 if (!Auth.isAdmin()) throw new Error('بستن دوره مالی فقط برای مدیر مجاز است');
146 const companyId = await DataScope.companyId();
147 return StorageService.transaction(['fiscal_periods', 'journal_entries', 'audit_events'], async tx => {
148 const period = await periodFor(tx, companyId, periodId);
149 ensurePeriodOpen(period);
150 const journals = await entriesFor(tx, companyId);
151 if (journals.some(j => j.periodId === periodId && j.status !== 'posted')) {
152 throw new Error('دوره دارای اسناد پیش‌نویس است؛ ابتدا تعیین تکلیف شوند');
153 }
154 const closed = { ...period, status: 'closed', closed: true, closedBy: actor(), closedAt: new Date().toISOString() };
155 await tx.put('fiscal_periods', closed);
156 await AuditService.append(tx, { companyId, eventType: 'period_closed', sourceType: 'fiscal_period',
157 sourceId: periodId, commandKey: 'close-period:' + periodId, businessDate: period.endDate });
158 return closed;
159 });
160 }
161
162 async listJournals({ periodId, status } = {}) {
163 const companyId = await DataScope.companyId();
164 const rows = await StorageService.getAllByIndex('journal_entries', 'companyId', companyId);
165 return rows.filter(j => (!periodId || j.periodId === periodId) && (!status || j.status === status))
166 .sort((a, b) => String(a.date).localeCompare(String(b.date)) || String(a.id).localeCompare(String(b.id)));
167 }
168
169 async getJournal(id) {
170 const companyId = await DataScope.companyId();
171 return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
172 const journal = await tx.get('journal_entries', id);
173 if (!journal || journal.companyId !== companyId) throw new Error('سند در این شرکت یافت نشد');
174 const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id))
175 .filter(l => l.companyId === companyId)
176 .sort((a, b) => a.position - b.position);
177 return { ...journal, lines };
178 }, 'readonly');
179 }
180
181 // Drafts can be unbalanced, but must use valid accounts, dates and integer rial amounts.
182 async saveDraftJournal(data) {
183 requireAccountingAdmin();
184 ensureManualSource(data.sourceType);
185 const companyId = await DataScope.companyId();
186 const id = uid('jn_');
187 const lines = cleanLines(data.lines);
188 const sourceKey = data.sourceType && data.sourceId
189 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
190 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
191 const period = await periodFor(tx, companyId, data.periodId);
192 ensurePeriodOpen(period);
193 assertJalaliDate(data.date);
194 if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
195 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
196 const totals = validateJournalLines({ ...data, lines, companyId }, accounts, { requireBalance: false });
197 if (sourceKey) {
198 const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
199 if (existing.length) throw new Error('برای این منشأ قبلاً سند ثبت شده است');
200 }
201 const journal = { id, companyId, periodId: data.periodId, date: data.date,
202 description: String(data.description || '').trim(), status: 'draft',
203 sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
204 revision: data.revision || 1, ...totals, createdBy: actor() };
205 await tx.put('journal_entries', journal);
206 for (const [position, line] of lines.entries()) {
207 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
208 }
209 return journal;
210 });
211 }
212
213 async updateDraftJournal(id, data, { post = false } = {}) {
214 requireAccountingAdmin();
215 const companyId = await DataScope.companyId();
216 const lines = cleanLines(data.lines);
217 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
218 const old = await tx.get('journal_entries', id);
219 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل ویرایش است');
220 const period = await periodFor(tx, companyId, data.periodId);
221 ensurePeriodOpen(period);
222 assertJalaliDate(data.date);
223 if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
224 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
225 const totals = post
226 ? validateJournal({ companyId, date: data.date, lines }, accounts, period)
227 : validateJournalLines({ companyId, lines }, accounts, { requireBalance: false });
228 const journal = {
229 ...old, periodId: data.periodId, date: data.date,
230 description: String(data.description || '').trim(), ...totals,
231 status: post ? 'posted' : 'draft',
232 ...(post ? { postedBy: actor(), postedAt: new Date().toISOString() } : {}),
233 updatedBy: actor(), updatedAt: new Date().toISOString()
234 };
235 const prior = await tx.getAllByIndex('journal_lines', 'journalId', id);
236 for (const line of prior) await tx.delete('journal_lines', line.id);
237 await tx.put('journal_entries', journal);
238 for (const [position, line] of lines.entries()) {
239 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
240 }
241 return journal;
242 });
243 }
244
245 async postJournal(data) {
246 requireAccountingAdmin();
247 ensureManualSource(data.sourceType);
248 const companyId = await DataScope.companyId();
249 const id = uid('jn_');
250 const lines = cleanLines(data.lines);
251 const sourceKey = data.sourceType && data.sourceId
252 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
253 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
254 const period = await periodFor(tx, companyId, data.periodId);
255 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
256 const totals = validateJournal({ companyId, date: data.date, lines }, accounts, period);
257 if (sourceKey) {
258 const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
259 if (existing.length) throw new Error('ثبت دوباره برای این منشأ مجاز نیست');
260 }
261 const journal = { id, companyId, periodId: data.periodId, date: data.date,
262 description: String(data.description || '').trim(), status: 'posted',
263 sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
264 revision: data.revision || 1, ...totals, createdBy: actor(), postedBy: actor(),
265 postedAt: new Date().toISOString() };
266 await tx.put('journal_entries', journal);
267 for (const [position, line] of lines.entries()) {
268 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
269 }
270 await AuditService.append(tx, { companyId, eventType: 'journal_posted', sourceType: 'journal',
271 sourceId: journal.id, commandKey: 'manual-journal:' + (sourceKey || journal.id),
272 businessDate: journal.date, lineCount: lines.length });
273 return journal;
274 });
275 }
276
277 async discardDraftJournal(id) {
278 requireAccountingAdmin();
279 const companyId = await DataScope.companyId();
280 return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
281 const old = await tx.get('journal_entries', id);
282 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل حذف است');
283 const lines = await tx.getAllByIndex('journal_lines', 'journalId', id);
284 for (const line of lines) await tx.delete('journal_lines', line.id);
285 await tx.delete('journal_entries', id);
286 return true;
287 });
288 }
289
290 async postDraftJournal(id) {
291 requireAccountingAdmin();
292 const companyId = await DataScope.companyId();
293 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
294 const old = await tx.get('journal_entries', id);
295 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('پیش‌نویس قابل ثبت پیدا نشد');
296 const period = await periodFor(tx, companyId, old.periodId);
297 const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id)).filter(l => l.companyId === companyId);
298 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
299 const totals = validateJournal({ companyId, date: old.date, lines }, accounts, period);
300 const journal = { ...old, ...totals, status: 'posted', postedBy: actor(), postedAt: new Date().toISOString() };
301 await tx.put('journal_entries', journal);
302 return journal;
303 });
304 }
305
306 async reverseJournal(originalId, { periodId, date, description = '' }) {
307 requireAccountingAdmin();
308 const companyId = await DataScope.companyId();
309 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines', 'audit_events'], async tx => {
310 const original = await tx.get('journal_entries', originalId);
311 if (!original || original.companyId !== companyId || original.status !== 'posted' ||
312 original.reversedById || original.reversalOfId) throw new Error('این سند قابل برگشت نیست');
313 // Reversing commercial GL alone would leave invoice, cash and stock inconsistent.
314 if (['invoice','treasury','expense','cheque','cheque_status','stocktake'].includes(original.sourceType))
315 throw new Error('سند تجاری را نمی‌توان جداگانه معکوس کرد؛ اصلاح باید از سند عملیاتی منشأ انجام شود');
316 const period = await periodFor(tx, companyId, periodId);
317 const oldLines = (await tx.getAllByIndex('journal_lines', 'journalId', originalId))
318 .filter(l => l.companyId === companyId)
319 .sort((a, b) => a.position - b.position);
320 const lines = reversingLines(oldLines);
321 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
322 // Historical reversals remain valid even when source accounts were later deactivated or given children.
323 const totals = validateJournal({ companyId, date, lines }, accounts, period, { allowInactive: true, allowParent: true });
324 const key = journalSourceKey(companyId, 'journal_reversal', originalId);
325 if ((await tx.getAllByIndex('journal_entries', 'sourceKey', key)).length) throw new Error('برگشت سند تکراری است');
326 const id = uid('jn_');
327 const journal = { id, companyId, periodId, date, description: String(description).trim() || `برگشت سند ${originalId}`,
328 status: 'posted', sourceKey: key, sourceType: 'journal_reversal', sourceId: originalId,
329 revision: 1, reversalOfId: originalId, ...totals, createdBy: actor(),
330 postedBy: actor(), postedAt: new Date().toISOString() };
331 await tx.put('journal_entries', journal);
332 for (const [position, line] of lines.entries()) {
333 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
334 }
335 await tx.put('journal_entries', { ...original, reversedById: id, reversedAt: journal.postedAt });
336 await AuditService.append(tx, { companyId, eventType: 'journal_reversed', sourceType: 'journal',
337 sourceId: id, commandKey: 'manual-reversal:' + originalId, businessDate: date,
338 lineCount: lines.length });
339 return journal;
340 });
341 }
342
343 async trialBalance({ periodId } = {}) {
344 const companyId = await DataScope.companyId();
345 return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines'], async tx => {
346 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
347 const journals = (await entriesFor(tx, companyId))
348 .filter(j => j.status === 'posted' && (!periodId || j.periodId === periodId));
349 const valid = new Set(journals.map(j => j.id));
350 const entries = new Map(accounts.map(a => [a.id, {
351 accountId: a.id, code: a.code, name: a.name, debit: 0, credit: 0, balance: 0
352 }]));
353 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
354 for (const line of lines) {
355 if (!valid.has(line.journalId)) continue;
356 const row = entries.get(line.accountId);
357 if (!row) throw new Error('سطر سند به حساب حذف‌شده اشاره دارد');
358 row.debit += line.debit;
359 row.credit += line.credit;
360 if (!Number.isSafeInteger(row.debit) || !Number.isSafeInteger(row.credit)) throw new Error('سرریز مانده حساب');
361 row.balance = row.debit - row.credit;
362 }
363 const rows = [...entries.values()].filter(r => r.debit || r.credit)
364 .sort((a, b) => a.code.localeCompare(b.code, 'fa'));
365 const totals = rows.reduce((sum, r) => ({ debit: sum.debit + r.debit, credit: sum.credit + r.credit }), { debit: 0, credit: 0 });
366 if (!Number.isSafeInteger(totals.debit) || !Number.isSafeInteger(totals.credit) ||
367 totals.debit !== totals.credit) throw new Error('گردش حساب‌ها تراز نیست');
368 return { companyId, periodId: periodId || null, rows, totals };
369 }, 'readonly');
370 }
371 }
372
373 export const AccountingService = new AccountingServiceImpl();