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

fix/phase-a-backup-record-id-validation-20261014
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 364 lines 19.9 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 { buildLedgerReports } from './LedgerReports.mjs';
7 import { reconcileFinancialData } from './ReconciliationCore.mjs';
8 import {
9 DEFAULT_CHART, assertJalaliDate, validateAccount, validateFiscalPeriod,
10 validateJournal, validateJournalLines, journalSourceKey, reversingLines
11 } from './AccountingCore.mjs';
12
13 const requireAccountingAdmin = () => { if(!Auth.isAdmin()) throw new Error('ثبت یا ویرایش ساختار حسابداری فقط برای مدیر مجاز است'); };
14 const RESERVED_SOURCES = new Set(['invoice','treasury','expense','cheque','cheque_status','stocktake']);
15 const ensureManualSource = type => {
16 if (RESERVED_SOURCES.has(type)) throw new Error('منشأ عملیاتی رزروشده فقط توسط موتور حسابداری یکپارچه ثبت می‌شود');
17 };
18 const uid = prefix => StorageService.uid(prefix);
19 const actor = () => Auth.current()?.id || null;
20 const entriesFor = (tx, companyId) => tx.getAllByIndex('journal_entries', 'companyId', companyId);
21 const periodFor = async (tx, companyId, periodId) => {
22 const period = await tx.get('fiscal_periods', periodId);
23 if (!period || period.companyId !== companyId) throw new Error('دوره مالی این شرکت پیدا نشد');
24 return period;
25 };
26 const ensurePeriodOpen = period => {
27 if (period.closed || period.status === 'closed') throw new Error('دوره مالی بسته است');
28 };
29 const cleanLines = lines => (lines || []).map(line => ({
30 accountId: line.accountId,
31 debit: line.debit,
32 credit: line.credit,
33 description: String(line.description || '').trim()
34 }));
35
36 class AccountingServiceImpl {
37 async financialReports(filter = {}) {
38 const companyId = await DataScope.companyId();
39 if (filter.from) assertJalaliDate(filter.from);
40 if (filter.to) assertJalaliDate(filter.to);
41 return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines', 'fiscal_periods'], async tx => {
42 if (filter.periodId) {
43 const period = await tx.get('fiscal_periods', filter.periodId);
44 if (!period || period.companyId !== companyId) throw new Error('دوره مالی انتخاب‌شده متعلق به شرکت فعال نیست');
45 }
46 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
47 const journals = await tx.getAllByIndex('journal_entries', 'companyId', companyId);
48 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
49 return buildLedgerReports(accounts, journals, lines, filter);
50 }, 'readonly');
51 }
52 // Read-only, company-scoped snapshot. It never rewrites balances or journals.
53 async reconciliationReport() {
54 if (!Auth.isAdmin()) throw new Error('گزارش کنترل مغایرت فقط برای مدیر مجاز است');
55 const companyId = await DataScope.companyId();
56 const stores = ['account_chart','journal_entries','journal_lines','invoices',
57 'settlements','treasury','inventory_balances','stock_movements','settings'];
58 return StorageService.transaction(stores, async tx => {
59 const scoped = async store =>
60 (await tx.getAll(store)).filter(row => row.companyId === companyId);
61 const [accounts,journals,journalLines,invoices,settlements,transactions,
62 inventoryBalances,stockMovements,activation] = await Promise.all([
63 scoped('account_chart'),scoped('journal_entries'),scoped('journal_lines'),
64 scoped('invoices'),scoped('settlements'),scoped('treasury'),
65 scoped('inventory_balances'),scoped('stock_movements'),
66 tx.get('settings','finance_v2_enabled_'+companyId)
67 ]);
68 return reconcileFinancialData({accounts,journals,journalLines,invoices,
69 settlements,transactions,inventoryBalances,stockMovements,
70 integrated:!!activation?.enabled});
71 },'readonly');
72 }
73
74 async listAccounts() {
75 const companyId = await DataScope.companyId();
76 return StorageService.getAllByIndex('account_chart', 'companyId', companyId);
77 }
78
79 async addAccount(data) {
80 requireAccountingAdmin();
81 const companyId = await DataScope.companyId();
82 const account = {
83 id: uid('acc_'), code: String(data.code || '').trim(),
84 name: String(data.name || '').trim(), level: data.level, type: data.type,
85 parentCode: data.parentCode || null, active: data.active !== false,
86 postable: data.postable !== false, companyId, createdBy: actor()
87 };
88 return StorageService.transaction(['account_chart', 'journal_lines'], async tx => {
89 const existing = await tx.getAllByIndex('account_chart', 'companyId', companyId);
90 validateAccount(account, existing);
91 // A posting account may not become a parent after journal lines exist.
92 // Otherwise future postings would be rejected while historical balances remain ambiguous.
93 if (account.parentCode) {
94 const parent = existing.find(a => a.code === account.parentCode);
95 const movements = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
96 if (movements.some(line => line.accountId === parent.id)) {
97 throw new Error('حساب والد گردش مالی دارد؛ افزودن زیرحساب به آن مجاز نیست');
98 }
99 }
100 await tx.put('account_chart', account);
101 return account;
102 });
103 }
104
105 async seedDefaultChart() {
106 requireAccountingAdmin();
107 const companyId = await DataScope.companyId();
108 return StorageService.transaction('account_chart', async tx => {
109 const existing = await tx.getAllByIndex('account_chart', 'companyId', companyId);
110 let added = 0;
111 for (const template of DEFAULT_CHART) {
112 if (existing.some(a => a.code === template.code)) continue;
113 const account = { ...template, companyId, id: uid('acc_'), active: true, createdBy: actor() };
114 validateAccount(account, existing);
115 await tx.put('account_chart', account);
116 existing.push(account);
117 added++;
118 }
119 return { added, total: existing.length };
120 });
121 }
122
123 async listPeriods() {
124 return StorageService.getAllByIndex('fiscal_periods', 'companyId', await DataScope.companyId());
125 }
126
127 async createPeriod(data) {
128 requireAccountingAdmin();
129 const companyId = await DataScope.companyId();
130 const period = {
131 id: uid('fp_'), companyId, name: String(data.name || '').trim(),
132 startDate: data.startDate, endDate: data.endDate,
133 status: 'open', closed: false, createdBy: actor()
134 };
135 if (!period.name) throw new Error('نام دوره مالی الزامی است');
136 return StorageService.transaction('fiscal_periods', async tx => {
137 validateFiscalPeriod(period, await tx.getAllByIndex('fiscal_periods', 'companyId', companyId));
138 await tx.put('fiscal_periods', period);
139 return period;
140 });
141 }
142
143 async closePeriod(periodId) {
144 if (!Auth.isAdmin()) throw new Error('بستن دوره مالی فقط برای مدیر مجاز است');
145 const companyId = await DataScope.companyId();
146 return StorageService.transaction(['fiscal_periods', 'journal_entries'], async tx => {
147 const period = await periodFor(tx, companyId, periodId);
148 ensurePeriodOpen(period);
149 const journals = await entriesFor(tx, companyId);
150 if (journals.some(j => j.periodId === periodId && j.status !== 'posted')) {
151 throw new Error('دوره دارای اسناد پیش‌نویس است؛ ابتدا تعیین تکلیف شوند');
152 }
153 const closed = { ...period, status: 'closed', closed: true, closedBy: actor(), closedAt: new Date().toISOString() };
154 await tx.put('fiscal_periods', closed);
155 return closed;
156 });
157 }
158
159 async listJournals({ periodId, status } = {}) {
160 const companyId = await DataScope.companyId();
161 const rows = await StorageService.getAllByIndex('journal_entries', 'companyId', companyId);
162 return rows.filter(j => (!periodId || j.periodId === periodId) && (!status || j.status === status))
163 .sort((a, b) => String(a.date).localeCompare(String(b.date)) || String(a.id).localeCompare(String(b.id)));
164 }
165
166 async getJournal(id) {
167 const companyId = await DataScope.companyId();
168 return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
169 const journal = await tx.get('journal_entries', id);
170 if (!journal || journal.companyId !== companyId) throw new Error('سند در این شرکت یافت نشد');
171 const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id))
172 .filter(l => l.companyId === companyId)
173 .sort((a, b) => a.position - b.position);
174 return { ...journal, lines };
175 }, 'readonly');
176 }
177
178 // Drafts can be unbalanced, but must use valid accounts, dates and integer rial amounts.
179 async saveDraftJournal(data) {
180 requireAccountingAdmin();
181 ensureManualSource(data.sourceType);
182 const companyId = await DataScope.companyId();
183 const id = uid('jn_');
184 const lines = cleanLines(data.lines);
185 const sourceKey = data.sourceType && data.sourceId
186 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
187 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
188 const period = await periodFor(tx, companyId, data.periodId);
189 ensurePeriodOpen(period);
190 assertJalaliDate(data.date);
191 if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
192 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
193 const totals = validateJournalLines({ ...data, lines, companyId }, accounts, { requireBalance: false });
194 if (sourceKey) {
195 const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
196 if (existing.length) throw new Error('برای این منشأ قبلاً سند ثبت شده است');
197 }
198 const journal = { id, companyId, periodId: data.periodId, date: data.date,
199 description: String(data.description || '').trim(), status: 'draft',
200 sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
201 revision: data.revision || 1, ...totals, createdBy: actor() };
202 await tx.put('journal_entries', journal);
203 for (const [position, line] of lines.entries()) {
204 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
205 }
206 return journal;
207 });
208 }
209
210 async updateDraftJournal(id, data, { post = false } = {}) {
211 requireAccountingAdmin();
212 const companyId = await DataScope.companyId();
213 const lines = cleanLines(data.lines);
214 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
215 const old = await tx.get('journal_entries', id);
216 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل ویرایش است');
217 const period = await periodFor(tx, companyId, data.periodId);
218 ensurePeriodOpen(period);
219 assertJalaliDate(data.date);
220 if (data.date < period.startDate || data.date > period.endDate) throw new Error('تاریخ سند خارج از دوره است');
221 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
222 const totals = post
223 ? validateJournal({ companyId, date: data.date, lines }, accounts, period)
224 : validateJournalLines({ companyId, lines }, accounts, { requireBalance: false });
225 const journal = {
226 ...old, periodId: data.periodId, date: data.date,
227 description: String(data.description || '').trim(), ...totals,
228 status: post ? 'posted' : 'draft',
229 ...(post ? { postedBy: actor(), postedAt: new Date().toISOString() } : {}),
230 updatedBy: actor(), updatedAt: new Date().toISOString()
231 };
232 const prior = await tx.getAllByIndex('journal_lines', 'journalId', id);
233 for (const line of prior) await tx.delete('journal_lines', line.id);
234 await tx.put('journal_entries', journal);
235 for (const [position, line] of lines.entries()) {
236 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
237 }
238 return journal;
239 });
240 }
241
242 async postJournal(data) {
243 requireAccountingAdmin();
244 ensureManualSource(data.sourceType);
245 const companyId = await DataScope.companyId();
246 const id = uid('jn_');
247 const lines = cleanLines(data.lines);
248 const sourceKey = data.sourceType && data.sourceId
249 ? journalSourceKey(companyId, data.sourceType, data.sourceId, data.revision || 1) : undefined;
250 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
251 const period = await periodFor(tx, companyId, data.periodId);
252 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
253 const totals = validateJournal({ companyId, date: data.date, lines }, accounts, period);
254 if (sourceKey) {
255 const existing = await tx.getAllByIndex('journal_entries', 'sourceKey', sourceKey);
256 if (existing.length) throw new Error('ثبت دوباره برای این منشأ مجاز نیست');
257 }
258 const journal = { id, companyId, periodId: data.periodId, date: data.date,
259 description: String(data.description || '').trim(), status: 'posted',
260 sourceKey, sourceType: data.sourceType || null, sourceId: data.sourceId || null,
261 revision: data.revision || 1, ...totals, createdBy: actor(), postedBy: actor(),
262 postedAt: new Date().toISOString() };
263 await tx.put('journal_entries', journal);
264 for (const [position, line] of lines.entries()) {
265 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
266 }
267 return journal;
268 });
269 }
270
271 async discardDraftJournal(id) {
272 requireAccountingAdmin();
273 const companyId = await DataScope.companyId();
274 return StorageService.transaction(['journal_entries', 'journal_lines'], async tx => {
275 const old = await tx.get('journal_entries', id);
276 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('فقط پیش‌نویس این شرکت قابل حذف است');
277 const lines = await tx.getAllByIndex('journal_lines', 'journalId', id);
278 for (const line of lines) await tx.delete('journal_lines', line.id);
279 await tx.delete('journal_entries', id);
280 return true;
281 });
282 }
283
284 async postDraftJournal(id) {
285 requireAccountingAdmin();
286 const companyId = await DataScope.companyId();
287 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
288 const old = await tx.get('journal_entries', id);
289 if (!old || old.companyId !== companyId || old.status !== 'draft') throw new Error('پیش‌نویس قابل ثبت پیدا نشد');
290 const period = await periodFor(tx, companyId, old.periodId);
291 const lines = (await tx.getAllByIndex('journal_lines', 'journalId', id)).filter(l => l.companyId === companyId);
292 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
293 const totals = validateJournal({ companyId, date: old.date, lines }, accounts, period);
294 const journal = { ...old, ...totals, status: 'posted', postedBy: actor(), postedAt: new Date().toISOString() };
295 await tx.put('journal_entries', journal);
296 return journal;
297 });
298 }
299
300 async reverseJournal(originalId, { periodId, date, description = '' }) {
301 requireAccountingAdmin();
302 const companyId = await DataScope.companyId();
303 return StorageService.transaction(['account_chart', 'fiscal_periods', 'journal_entries', 'journal_lines'], async tx => {
304 const original = await tx.get('journal_entries', originalId);
305 if (!original || original.companyId !== companyId || original.status !== 'posted' ||
306 original.reversedById || original.reversalOfId) throw new Error('این سند قابل برگشت نیست');
307 // Reversing commercial GL alone would leave invoice, cash and stock inconsistent.
308 if (['invoice','treasury','expense','cheque','cheque_status','stocktake'].includes(original.sourceType))
309 throw new Error('سند تجاری را نمی‌توان جداگانه معکوس کرد؛ اصلاح باید از سند عملیاتی منشأ انجام شود');
310 const period = await periodFor(tx, companyId, periodId);
311 const oldLines = (await tx.getAllByIndex('journal_lines', 'journalId', originalId))
312 .filter(l => l.companyId === companyId)
313 .sort((a, b) => a.position - b.position);
314 const lines = reversingLines(oldLines);
315 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
316 // Historical reversals remain valid even when source accounts were later deactivated or given children.
317 const totals = validateJournal({ companyId, date, lines }, accounts, period, { allowInactive: true, allowParent: true });
318 const key = journalSourceKey(companyId, 'journal_reversal', originalId);
319 if ((await tx.getAllByIndex('journal_entries', 'sourceKey', key)).length) throw new Error('برگشت سند تکراری است');
320 const id = uid('jn_');
321 const journal = { id, companyId, periodId, date, description: String(description).trim() || `برگشت سند ${originalId}`,
322 status: 'posted', sourceKey: key, sourceType: 'journal_reversal', sourceId: originalId,
323 revision: 1, reversalOfId: originalId, ...totals, createdBy: actor(),
324 postedBy: actor(), postedAt: new Date().toISOString() };
325 await tx.put('journal_entries', journal);
326 for (const [position, line] of lines.entries()) {
327 await tx.put('journal_lines', { ...line, id: uid('jl_'), companyId, journalId: id, position });
328 }
329 await tx.put('journal_entries', { ...original, reversedById: id, reversedAt: journal.postedAt });
330 return journal;
331 });
332 }
333
334 async trialBalance({ periodId } = {}) {
335 const companyId = await DataScope.companyId();
336 return StorageService.transaction(['account_chart', 'journal_entries', 'journal_lines'], async tx => {
337 const accounts = await tx.getAllByIndex('account_chart', 'companyId', companyId);
338 const journals = (await entriesFor(tx, companyId))
339 .filter(j => j.status === 'posted' && (!periodId || j.periodId === periodId));
340 const valid = new Set(journals.map(j => j.id));
341 const entries = new Map(accounts.map(a => [a.id, {
342 accountId: a.id, code: a.code, name: a.name, debit: 0, credit: 0, balance: 0
343 }]));
344 const lines = await tx.getAllByIndex('journal_lines', 'companyId', companyId);
345 for (const line of lines) {
346 if (!valid.has(line.journalId)) continue;
347 const row = entries.get(line.accountId);
348 if (!row) throw new Error('سطر سند به حساب حذف‌شده اشاره دارد');
349 row.debit += line.debit;
350 row.credit += line.credit;
351 if (!Number.isSafeInteger(row.debit) || !Number.isSafeInteger(row.credit)) throw new Error('سرریز مانده حساب');
352 row.balance = row.debit - row.credit;
353 }
354 const rows = [...entries.values()].filter(r => r.debit || r.credit)
355 .sort((a, b) => a.code.localeCompare(b.code, 'fa'));
356 const totals = rows.reduce((sum, r) => ({ debit: sum.debit + r.debit, credit: sum.credit + r.credit }), { debit: 0, credit: 0 });
357 if (!Number.isSafeInteger(totals.debit) || !Number.isSafeInteger(totals.credit) ||
358 totals.debit !== totals.credit) throw new Error('گردش حساب‌ها تراز نیست');
359 return { companyId, periodId: periodId || null, rows, totals };
360 }, 'readonly');
361 }
362 }
363
364 export const AccountingService = new AccountingServiceImpl();