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

fix/a02-atomic-excel-master-merge-20261031
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 748 lines 50.5 KB
Raw
1 // Factor-easyPro V2 / Phase 1: isolated accounting workbench.
2 // Existing invoice, inventory and treasury workflows are deliberately untouched.
3 import { AccountingService as Ledger } from '../core/AccountingService.js';
4 import { OpeningBalanceService } from '../core/OpeningBalanceService.js';
5 import { RetailPostingService as Retail } from '../core/RetailPostingService.js';
6 import { DataScope } from '../core/DataScope.js';
7 import { Auth } from '../core/Auth.js';
8 import { Modal } from '../core/Modal.js';
9 import { Toast } from '../core/Toast.js';
10 import { Formatters } from '../utils/Formatters.js';
11 import { Jalali } from '../utils/Jalali.js';
12 import { ACCOUNT_LEVELS, ACCOUNT_TYPES } from '../core/AccountingCore.mjs';
13
14 const levelNames = { group: 'گروه', general: 'کل', subsidiary: 'معین', detail: 'تفصیلی' };
15 const typeNames = { asset: 'دارایی', liability: 'بدهی', equity: 'حقوق مالکانه', revenue: 'درآمد', expense: 'هزینه' };
16 const html = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
17 // Encode both JavaScript argument quotes and the enclosing HTML attribute.
18 const actionArg = value => html(JSON.stringify(String(value ?? '')));
19 const digits = input => String(input ?? '').replace(/[۰-۹]/g, c => String(c.charCodeAt(0) - 1776)).replace(/[٠-٩]/g, c => String(c.charCodeAt(0) - 1632));
20 const rial = input => {
21 const raw = digits(input).replace(/[,_،\s]/g, '');
22 if (!raw) return 0;
23 if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw))) throw new Error('مبلغ باید عدد صحیح و غیرمنفی به ریال باشد');
24 return Number(raw);
25 };
26 const safeDate = () => Jalali.today();
27
28 class AccountingViewImpl {
29 constructor() {
30 this.tab = 'journals';
31 this.accounts = [];
32 this.periods = [];
33 this.journals = [];
34 this.reportFilter = {periodId:'',from:'',to:''};
35 this.busy = false;
36 }
37 async reload() {
38 [this.accounts, this.periods, this.journals] = await Promise.all([
39 Ledger.listAccounts(), Ledger.listPeriods(), Ledger.listJournals()
40 ]);
41 }
42 async render() {
43 await this.reload();
44 const tabs = [
45 ['journals', 'اسناد حسابداری'],
46 ['accounts', 'کدینگ حساب‌ها'],
47 ['periods', 'دوره‌های مالی'],
48 ['trial', 'تراز آزمایشی'],
49 ['reports', 'گزارش‌های مالی'],
50 ...(Auth.isAdmin() ? [['reconciliation','کنترل مغایرت']] : []),
51 ...(Auth.isAdmin() ? [['opening','افتتاحیه کنترل‌شده']] : []),
52 ['integration', 'عملیات یکپارچه و انبار']
53 ];
54 return `<div class="page-title"><h2>حسابداری دوبل</h2>
55 <p>گردش‌های مالی و موجودی برای شرکت‌های فعال‌شده به‌صورت اتمیک ثبت می‌شوند؛ داده‌های قدیمی بدون مهاجرت تأییدشده تغییر نمی‌کنند.</p></div>
56 <div class="toolbar" style="gap:8px;flex-wrap:wrap">
57 ${tabs.map(([id, label]) => `<button class="btn ${this.tab === id ? '' : 'btn-secondary'}" onclick="window.AccountingView.switchTab('${id}')">${label}</button>`).join('')}
58 </div>
59 <div id="accountingWorkbench">${await this.body()}</div>`;
60 }
61 onMount() { window.AccountingView = this; }
62 async switchTab(tab) {
63 this.tab = tab;
64 await this.refresh();
65 }
66 async refresh() {
67 try {
68 await this.reload();
69 const host = document.getElementById('accountingWorkbench');
70 if (host) host.innerHTML = await this.body();
71 } catch (error) {
72 Toast.error('خطای حسابداری: ' + error.message);
73 }
74 }
75 async body() {
76 switch (this.tab) {
77 case 'accounts': return this.renderAccounts();
78 case 'periods': return this.renderPeriods();
79 case 'trial': return this.renderTrial();
80 case 'reports': return this.renderReports();
81 case 'reconciliation': return this.renderReconciliation();
82 case 'opening': return Auth.isAdmin() ? this.renderOpening() : '<p>دسترسی مجاز نیست.</p>';
83 case 'integration': return this.renderIntegration();
84 default: return this.renderJournals();
85 }
86 }
87 renderOpening() {
88 if (!Auth.isAdmin()) return '<p>دسترسی مجاز نیست.</p>';
89 return `
90 <section class="card" style="max-width:850px">
91 <h3>ثبت دفتر افتتاحیه — فقط داده‌های پایه موجود</h3>
92 <p style="line-height:1.9">
93 پیش از هر ثبت، باید اشخاص، حساب‌ها، موجودی انبار و بانک/صندوق در شرکت فعال
94 ایجاد و کنترل شده باشند. این صفحه <strong>هیچ داده قدیمی را وارد نمی‌کند</strong>
95 و فقط یک سند دفتر کل افتتاحیه تراز و تأییدشده ثبت می‌کند.
96 </p>
97 <p style="color:var(--text-muted);font-size:12px">
98 فایل JSON باید حاوی periodId، openingDate، lines، contacts، stock و cash
99 مطابق قرارداد docs/A02_OPENING_LEDGER_SCOPE_FA.md باشد.
100 فایل برای بررسی در حافظه خوانده می‌شود و بدون تأیید شما نوشته نخواهد شد.
101 </p>
102 <div class="form-group">
103 <label class="form-label" for="openingFileInput">فایل افتتاحیه برای بررسی</label>
104 <input id="openingFileInput" class="form-control" type="file"
105 accept=".json,application/json"
106 onchange="window.AccountingView.resetOpeningPreview()" />
107 </div>
108 <button class="btn btn-secondary" onclick="window.AccountingView.previewOpeningFile()">
109 کنترل مانده‌ها و دوره (بدون ثبت)
110 </button>
111 <div id="openingPreviewReport" style="margin-top:16px" role="status">
112 <p>هنوز فایلی بررسی نشده است.</p>
113 </div>
114 </section>
115 `;
116 }
117
118 resetOpeningPreview() {
119 this._openingCandidate = null;
120 this._openingReview = null;
121 const host = document.getElementById('openingPreviewReport');
122 if (host) host.textContent = 'فایل تغییر کرد؛ لازم است دوباره بررسی شود.';
123 }
124
125 async previewOpeningFile() {
126 if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; }
127 const file = document.getElementById('openingFileInput')?.files?.[0];
128 if (!file || file.size > 1024 * 1024) {
129 Toast.error('یک فایل JSON معتبر و حداکثر ۱ مگابایتی انتخاب کنید');
130 return;
131 }
132 const host = document.getElementById('openingPreviewReport');
133 this._openingCandidate = null;
134 this._openingReview = null;
135 try {
136 const raw = await file.text();
137 const candidate = JSON.parse(raw);
138 if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
139 throw Error('ساختار فایل ورودی نامعتبر است');
140 }
141 const review = await OpeningBalanceService.preview(candidate);
142 this._openingCandidate = candidate;
143 this._openingReview = review;
144 if (host) {
145 const issues = review.issues.map(code => `<li>${html(code)}</li>`).join('');
146 host.innerHTML = `
147 <p><strong>وضعیت:</strong>
148 ${review.readiness === 'ready-for-review' ? 'آماده تأیید' : 'ثبت مسدود'}
149 </p>
150 <p>بدهکار: ${Formatters.number(review.journal.debit)} ریال
151 | بستانکار: ${Formatters.number(review.journal.credit)} ریال</p>
152 ${issues ? `<ul style="color:var(--danger)">${issues}</ul>` :
153 '<p>در کنترل‌های فعلی مغایرتی یافت نشد.</p>'}
154 <button class="btn btn-danger" ${review.readiness === 'ready-for-review' ? '' : 'disabled'}
155 onclick="window.AccountingView.confirmOpeningPosting()">
156 ثبت قطعی سند افتتاحیه
157 </button>
158 <p style="font-size:12px;color:var(--text-muted)">
159 در زمان ثبت، تمام کنترل‌ها دوباره در یک تراکنش انجام می‌شوند.
160 بدون تأیید صریح هیچ داده‌ای نوشته نخواهد شد.
161 </p>
162 `;
163 }
164 } catch (error) {
165 if (host) host.textContent = 'بررسی افتتاحیه ناموفق بود: ' + error.message;
166 Toast.error('بررسی افتتاحیه متوقف شد: ' + error.message);
167 }
168 }
169
170 confirmOpeningPosting() {
171 if (!Auth.isAdmin() || this._openingReview?.readiness !== 'ready-for-review' ||
172 !this._openingCandidate) {
173 Toast.error('ابتدا فایل افتتاحیه را بدون مغایرت بررسی کنید');
174 return;
175 }
176 Modal.confirm({
177 title: 'تأیید ثبت قطعی افتتاحیه',
178 message: 'این عملیات سند دفتر کل افتتاحیه و رویداد حسابرسی ثبت می‌کند. داده‌های پایه باید قبلاً کنترل و پشتیبان‌گیری شده باشند. آیا ثبت قطعی را تأیید می‌کنید؟',
179 confirmText: 'تأیید ثبت قطعی',
180 danger: true,
181 onConfirm: async () => {
182 const candidate = this._openingCandidate;
183 this._openingCandidate = null;
184 this._openingReview = null;
185 try {
186 const result = await OpeningBalanceService.commit(candidate, {
187 confirmation: 'CONFIRM_OPENING_LEDGER'
188 });
189 Toast.success('سند افتتاحیه ' + result.journalId + ' با موفقیت ثبت شد');
190 this.tab = 'journals';
191 await this.refresh();
192 } catch (error) {
193 Toast.error('ثبت افتتاحیه انجام نشد: ' + error.message);
194 }
195 }
196 });
197 }
198
199 openPeriods() {
200 this.tab = 'periods';
201 return this.refresh();
202 }
203 renderPeriods() {
204 const rows = this.periods.map(p => `<tr>
205 <td><strong>${html(p.name)}</strong></td>
206 <td>${html(p.startDate)}</td><td>${html(p.endDate)}</td>
207 <td><span class="badge ${p.closed ? 'badge-muted' : 'badge-success'}">${p.closed ? 'بسته' : 'باز'}</span></td>
208 <td>${p.closed ? '—' : `<button class="btn btn-secondary" onclick="window.AccountingView.closePeriod(${actionArg(p.id)})">بستن دوره</button>`}</td></tr>`).join('');
209 return `<div class="card">
210 <div class="toolbar"><strong>دوره‌های مالی</strong>
211 <button class="btn" onclick="window.AccountingView.openPeriodModal()">افزودن دوره مالی</button></div>
212 <div class="table-wrap"><table><thead><tr><th>نام دوره</th><th>شروع</th><th>پایان</th><th>وضعیت</th><th>عملیات</th></tr></thead>
213 <tbody>${rows || '<tr><td colspan="5">هنوز دوره مالی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`;
214 }
215 renderAccounts() {
216 const rows = this.accounts.slice().sort((a, b) => String(a.code).localeCompare(String(b.code), 'fa')).map(a => `<tr>
217 <td>${html(a.code)}</td><td>${html(a.name)}</td><td>${levelNames[a.level] || html(a.level)}</td>
218 <td>${typeNames[a.type] || html(a.type)}</td><td>${html(a.parentCode || '—')}</td>
219 <td>${a.active === false ? 'غیرفعال' : 'فعال'}</td></tr>`).join('');
220 return `<div class="card">
221 <div class="toolbar"><strong>سرفصل‌های حسابداری</strong>
222 <button class="btn btn-secondary" onclick="window.AccountingView.seedChart()">ایجاد کدینگ پیشنهادی</button>
223 <button class="btn" onclick="window.AccountingView.openAccountModal()">افزودن حساب</button></div>
224 <p style="font-size:12px;color:var(--text-muted);margin:10px 0">کدینگ پیشنهادی مختص این پروژه است و رونوشتی از کدینگ اختصاصی هلو نیست. حساب دارای زیرمجموعه قابل انتخاب در سند نیست.</p>
225 <div class="table-wrap"><table><thead><tr><th>کد</th><th>نام</th><th>سطح</th><th>ماهیت</th><th>والد</th><th>وضعیت</th></tr></thead>
226 <tbody>${rows || '<tr><td colspan="6">حسابی تعریف نشده است.</td></tr>'}</tbody></table></div></div>`;
227 }
228 renderJournals() {
229 const rows = this.journals.slice().reverse().map(j => `<tr>
230 <td>${html(j.date)}</td><td>${html(j.description || '—')}</td>
231 <td>${this.periods.find(p => p.id === j.periodId)?.name ? html(this.periods.find(p => p.id === j.periodId).name) : '—'}</td>
232 <td>${Formatters.number(j.debit || 0)}</td><td>${Formatters.number(j.credit || 0)}</td>
233 <td><span class="badge ${j.status === 'posted' ? 'badge-success' : 'badge-warning'}">${j.status === 'posted' ? 'قطعی' : 'پیش‌نویس'}</span>${j.reversedById ? ' / برگشت‌خورده' : ''}</td>
234 <td style="white-space:nowrap">
235 <button class="btn btn-secondary" onclick="window.AccountingView.showJournal(${actionArg(j.id)})">مشاهده</button>
236 ${j.status === 'draft' ? `<button class="btn btn-secondary" onclick="window.AccountingView.openJournalModal(${actionArg(j.id)})">ویرایش</button>
237 <button class="btn" onclick="window.AccountingView.postDraft(${actionArg(j.id)})">قطعی</button>
238 <button class="btn btn-secondary" onclick="window.AccountingView.deleteDraft(${actionArg(j.id)})">حذف پیش‌نویس</button>` : ''}
239 ${j.status === 'posted' && !j.reversedById && !j.reversalOfId
240 ? `<button class="btn btn-secondary" onclick="window.AccountingView.openReversal(${actionArg(j.id)})">برگشت</button>` : ''}
241 </td></tr>`).join('');
242 return `<div class="card">
243 <div class="toolbar"><strong>اسناد حسابداری مستقل</strong>
244 <button class="btn" onclick="window.AccountingView.openJournalModal()">ایجاد سند دستی</button></div>
245 <p style="font-size:12px;color:var(--text-muted);margin:10px 0">اسناد این قسمت فعلاً مستقل از فاکتورها هستند. برای ثبت سند حداقل یک دوره باز و حساب قابل ثبت لازم است.</p>
246 <div class="table-wrap"><table><thead><tr>
247 <th>تاریخ</th><th>شرح</th><th>دوره</th><th>بدهکار (ریال)</th><th>بستانکار (ریال)</th><th>وضعیت</th><th>عملیات</th>
248 </tr></thead><tbody>${rows || '<tr><td colspan="7">سندی ثبت نشده است.</td></tr>'}</tbody></table></div></div>`;
249 }
250 async renderTrial() {
251 if (!this.periods.length) return '<div class="card">ابتدا دوره مالی تعریف کنید.</div>';
252 const periodId = this.selectedTrialPeriod && this.periods.some(p => p.id === this.selectedTrialPeriod)
253 ? this.selectedTrialPeriod : this.periods[0].id;
254 this.selectedTrialPeriod = periodId;
255 const result = await Ledger.trialBalance({ periodId });
256 const opts = this.periods.map(p => `<option value="${html(p.id)}" ${p.id === periodId ? 'selected' : ''}>${html(p.name)}</option>`).join('');
257 const rows = result.rows.map(r => `<tr><td>${html(r.code)}</td><td>${html(r.name)}</td>
258 <td>${Formatters.number(r.debit)}</td><td>${Formatters.number(r.credit)}</td><td>${Formatters.number(r.balance)}</td></tr>`).join('');
259 return `<div class="card"><div class="toolbar"><strong>تراز آزمایشی اسناد قطعی</strong>
260 <select class="form-control" style="max-width:210px" aria-label="دوره تراز آزمایشی" onchange="window.AccountingView.setTrialPeriod(this.value)">${opts}</select></div>
261 <div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>گردش بدهکار</th><th>گردش بستانکار</th><th>مانده بدهکار - بستانکار</th></tr></thead>
262 <tbody>${rows || '<tr><td colspan="5">گردشی وجود ندارد.</td></tr>'}</tbody>
263 <tfoot><tr><th colspan="2">جمع</th><th>${Formatters.number(result.totals.debit)}</th><th>${Formatters.number(result.totals.credit)}</th><th>۰</th></tr></tfoot>
264 </table></div></div>`;
265 }
266 async renderReports() {
267 const r = await Ledger.financialReports(this.reportFilter);
268 const filter=this.reportFilter;
269 const periodOptions=this.periods.map(p=>`<option value="${html(p.id)}" ${p.id===filter.periodId?'selected':''}>${html(p.name)}</option>`).join('');
270 const rows = r.trial.map(x => `<tr><td>${html(x.code)}</td><td>${html(x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td><td>${Formatters.number(x.balance)}</td></tr>`).join('');
271 const detail = r.detail.map(x => `<tr><td>${html(x.date)}</td><td>${html(x.description)}</td><td>${html(x.code+' — '+x.name)}</td><td>${Formatters.number(x.debit)}</td><td>${Formatters.number(x.credit)}</td></tr>`).join('');
272 return `<div class="card"><div class="toolbar"><strong>گزارش‌های مبتنی بر اسناد قطعی دفتر کل</strong>
273 <button class="btn btn-secondary" onclick="window.AccountingView.exportReports()">خروجی CSV</button></div>
274 <div class="toolbar" style="margin:8px 0;flex-wrap:wrap;gap:8px">
275 <label>دوره مالی <select class="form-control" style="min-width:140px" onchange="window.AccountingView.setReportFilter('periodId',this.value)">
276 <option value="">تمام دوره‌ها</option>${periodOptions}</select></label>
277 <label>از تاریخ <input class="form-control" style="width:135px" placeholder="۱۴۰۵/۰۱/۰۱" value="${html(filter.from)}"
278 onchange="window.AccountingView.setReportFilter('from',this.value)"></label>
279 <label>تا تاریخ <input class="form-control" style="width:135px" placeholder="۱۴۰۵/۱۲/۲۹" value="${html(filter.to)}"
280 onchange="window.AccountingView.setReportFilter('to',this.value)"></label>
281 </div>
282 <p style="font-size:12px;color:var(--text-muted)">سود و زیان و ریز اسناد براساس فیلتر محاسبه می‌شوند. ترازنامه تا تاریخ انتهای بازه، تجمعی است.</p>
283 <p>درآمد: ${Formatters.number(r.profitLoss.revenue)} ریال | هزینه و بهای تمام‌شده: ${Formatters.number(r.profitLoss.expenses)} ریال | سود خالص: ${Formatters.number(r.profitLoss.netProfit)} ریال</p>
284 <p>دارایی: ${Formatters.number(r.balanceSheet.assets)} | بدهی: ${Formatters.number(r.balanceSheet.liabilities)} | حقوق مالکانه با سود جاری: ${Formatters.number(r.balanceSheet.equityWithProfit)} | اختلاف ترازنامه: ${Formatters.number(r.balanceSheet.difference)}</p>
285 <h3>تراز حساب‌ها</h3><div class="table-wrap"><table><thead><tr><th>کد</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>مانده</th></tr></thead><tbody>${rows||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div>
286 <h3>روزنامه و ریز دفتر کل</h3><div class="table-wrap"><table><thead><tr><th>تاریخ</th><th>شرح</th><th>حساب</th><th>بدهکار</th><th>بستانکار</th></tr></thead><tbody>${detail||'<tr><td colspan="5">بدون گردش</td></tr>'}</tbody></table></div></div>`;
287 }
288 async exportReports() {
289 try {
290 const r = await Ledger.financialReports(this.reportFilter);
291 const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"';
292 const csv = [['date','description','account_code','account_name','debit_irr','credit_irr'],...r.detail.map(x=>[x.date,x.description,x.code,x.name,x.debit,x.credit])].map(a=>a.map(esc).join(',')).join('\r\n');
293 const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'});
294 const url = URL.createObjectURL(blob);
295 const a=document.createElement('a');a.href=url;a.download='factor-easypro-ledger.csv';document.body.appendChild(a);a.click();a.remove();
296 setTimeout(()=>URL.revokeObjectURL(url),3000);
297 } catch(error) { Toast.error(error.message); }
298 }
299 async renderReconciliation() {
300 if (!Auth.isAdmin()) return '<div class="card">دسترسی به کنترل مغایرت فقط برای مدیر مجاز است.</div>';
301 const report = await Ledger.reconciliationReport();
302 const counts = report.counts, totals = report.totals;
303 const rows = report.issues.slice(0,200).map(item => `<tr>
304 <td>${html(item.code)}</td><td>${html(item.reference||'—')}</td>
305 <td>${html(item.message)}</td>
306 <td>${html(item.expected === null ? '—' : Formatters.number(item.expected))}</td>
307 <td>${html(item.actual === null ? '—' : Formatters.number(item.actual))}</td></tr>`).join('');
308 return `<div class="card">
309 <div class="toolbar"><strong>کنترل مغایرت اسناد، تسویه‌ها، چک‌ها و موجودی</strong>
310 <button class="btn btn-secondary" onclick="window.AccountingView.exportReconciliation()">خروجی CSV</button>
311 <button class="btn btn-secondary" onclick="window.AccountingView.refresh()">بررسی مجدد</button>
312 </div>
313 <p style="margin:10px 0;line-height:1.9">این بررسی فقط خواندنی است و هیچ مبلغ یا سندی را اصلاح نمی‌کند.
314 ${report.integrated ? 'مغایرت حساب موجودی (۱۰۳) نیز بررسی شده است.' : 'حسابداری یکپارچه غیرفعال است؛ تطبیق انبار و دفتر کل انجام نمی‌شود.'}</p>
315 <p><strong>اسناد قطعی:</strong> ${Formatters.number(counts.journals)} |
316 <strong>فاکتورهای مالی:</strong> ${Formatters.number(counts.invoices)} |
317 <strong>تسویه‌ها:</strong> ${Formatters.number(counts.settlements)} |
318 <strong>چک‌های مالی:</strong> ${Formatters.number(counts.cheques)} |
319 <strong>مغایرت‌های شناسایی‌شده:</strong> ${Formatters.number(counts.issues)}</p>
320 ${report.integrated ? `<p>ارزش موجودی انبار: ${Formatters.number(totals.inventoryBook)} ریال |
321 مانده دفتر کل موجودی: ${Formatters.number(totals.inventoryLedger)} ریال</p>` : ''}
322 ${!rows ? '<p style="margin:14px 0;color:var(--text-muted)">در کنترل‌های فعلی مغایرتی مشاهده نشد. این نتیجه جایگزین حسابرسی مستقل نیست.</p>' : ''}
323 <div class="table-wrap"><table><thead><tr>
324 <th>نوع کنترل</th><th>مرجع</th><th>شرح مغایرت</th><th>انتظار</th><th>مقدار فعلی</th>
325 </tr></thead><tbody>${rows}</tbody></table></div>
326 ${counts.issues>200 ? '<p>فقط ۲۰۰ ردیف نخست نمایش داده شده‌اند؛ برای همه ردیف‌ها خروجی CSV بگیرید.</p>' : ''}
327 </div>`;
328 }
329
330 async exportReconciliation() {
331 try {
332 if (!Auth.isAdmin()) throw Error('دسترسی مجاز نیست');
333 const result = await Ledger.reconciliationReport();
334 const esc = v => '"'+String(v??'').replace(/"/g,'""')+'"';
335 const rows = [['code','reference','message','expected','actual'],
336 ...result.issues.map(x=>[x.code,x.reference,x.message,x.expected,x.actual])];
337 const csv = rows.map(line=>line.map(esc).join(',')).join('\r\n');
338 const blob = new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'});
339 const url=URL.createObjectURL(blob);
340 const a=document.createElement('a');a.href=url;a.download='factor-easypro-reconciliation.csv';
341 document.body.appendChild(a);a.click();a.remove();
342 setTimeout(()=>URL.revokeObjectURL(url),3000);
343 } catch(error){Toast.error('خروجی مغایرت: '+error.message);}
344 }
345
346 setReportFilter(key,value) {
347 if (!['periodId','from','to'].includes(key)) return;
348 this.reportFilter={...this.reportFilter,[key]:key==='periodId'?value:digits(value).trim()};
349 return this.refresh();
350 }
351 setTrialPeriod(id) { this.selectedTrialPeriod = id; return this.refresh(); }
352 openPeriodModal() {
353 const body = `<div class="form-group"><label class="form-label">نام دوره</label>
354 <input id="acPeriodName" class="form-control" value="سال مالی جدید"></div>
355 <div class="form-row"><div class="form-group"><label class="form-label">از تاریخ شمسی</label>
356 <input id="acPeriodStart" class="form-control" placeholder="1405/01/01"></div>
357 <div class="form-group"><label class="form-label">تا تاریخ شمسی</label>
358 <input id="acPeriodEnd" class="form-control" placeholder="1405/12/29"></div></div>`;
359 const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.savePeriod()">ذخیره دوره</button>';
360 Modal.open({ title: 'دوره مالی جدید', body, footer, size: 'sm', closeOnBackdrop: false });
361 }
362 async savePeriod() {
363 if (this.busy) return;
364 this.busy = true;
365 try {
366 await Ledger.createPeriod({
367 name: document.getElementById('acPeriodName').value,
368 startDate: digits(document.getElementById('acPeriodStart').value).trim(),
369 endDate: digits(document.getElementById('acPeriodEnd').value).trim()
370 });
371 Modal.close();
372 Toast.success('دوره مالی ایجاد شد');
373 await this.refresh();
374 } catch (error) { Toast.error(error.message); }
375 finally { this.busy = false; }
376 }
377 closePeriod(id) {
378 Modal.confirm({ title: 'بستن دوره مالی', danger: true,
379 message: 'بعد از بستن، ثبت یا برگشت سند در این دوره مجاز نیست. ابتدا پشتیبان تهیه کرده و پیش‌نویس‌ها را تعیین تکلیف کنید.',
380 confirmText: 'بستن قطعی دوره', onConfirm: async () => {
381 try {
382 await Ledger.closePeriod(id);
383 Toast.success('دوره مالی بسته شد');
384 await this.refresh();
385 } catch (error) { Toast.error(error.message); }
386 }
387 });
388 }
389 seedChart() {
390 Modal.confirm({ title: 'ایجاد کدینگ پیشنهادی', message:
391 'سرفصل‌های پایه نمونه به شرکت فعال اضافه می‌شوند؛ حساب‌های قبلی حذف یا تغییر نمی‌کنند. ادامه می‌دهید؟',
392 onConfirm: async () => {
393 try {
394 const r = await Ledger.seedDefaultChart();
395 Toast.success(`${r.added} سرفصل جدید ایجاد شد`);
396 await this.refresh();
397 } catch (error) { Toast.error(error.message); }
398 }
399 });
400 }
401 openAccountModal() {
402 const parents = this.accounts.map(a => `<option value="${html(a.code)}">${html(a.code + ' — ' + a.name)}</option>`).join('');
403 const levelOptions = ACCOUNT_LEVELS.map(l => `<option value="${l}">${levelNames[l]}</option>`).join('');
404 const typeOptions = ACCOUNT_TYPES.map(t => `<option value="${t}">${typeNames[t]}</option>`).join('');
405 const body = `<div class="form-row"><div class="form-group"><label class="form-label">کد حساب</label>
406 <input class="form-control" id="acCode" inputmode="text"></div>
407 <div class="form-group"><label class="form-label">عنوان</label>
408 <input class="form-control" id="acName"></div></div>
409 <div class="form-row"><div class="form-group"><label class="form-label">سطح</label>
410 <select class="form-control" id="acLevel" onchange="window.AccountingView.toggleParent()">${levelOptions}</select></div>
411 <div class="form-group"><label class="form-label">ماهیت</label>
412 <select class="form-control" id="acType">${typeOptions}</select></div></div>
413 <div class="form-group" id="acParentGroup" style="display:none"><label class="form-label">کد حساب والد</label>
414 <select class="form-control" id="acParent"><option value="">انتخاب والد</option>${parents}</select></div>`;
415 const footer = '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveAccount()">ثبت حساب</button>';
416 Modal.open({ title: 'حساب جدید', body, footer, size: 'sm', closeOnBackdrop: false });
417 }
418 toggleParent() {
419 document.getElementById('acParentGroup').style.display = document.getElementById('acLevel').value === 'group' ? 'none' : '';
420 }
421 async saveAccount() {
422 if (this.busy) return;
423 this.busy = true;
424 try {
425 await Ledger.addAccount({
426 code: digits(document.getElementById('acCode').value).trim(),
427 name: document.getElementById('acName').value.trim(),
428 level: document.getElementById('acLevel').value,
429 type: document.getElementById('acType').value,
430 parentCode: document.getElementById('acLevel').value === 'group' ? null : document.getElementById('acParent').value
431 });
432 Modal.close();
433 Toast.success('حساب اضافه شد');
434 await this.refresh();
435 } catch (error) { Toast.error(error.message); }
436 finally { this.busy = false; }
437 }
438 accountOptions(selected = '') {
439 const postable = this.accounts.filter(a => a.level !== 'group' && a.active !== false && a.postable !== false &&
440 !this.accounts.some(child => child.parentCode === a.code));
441 return '<option value="">انتخاب حساب</option>' + postable.map(a => `<option value="${html(a.id)}" ${a.id === selected ? 'selected' : ''}>${html(a.code + ' — ' + a.name)}</option>`).join('');
442 }
443 journalRow(line = {}) {
444 return `<tr class="ac-journal-line">
445 <td><select class="form-control ac-line-account" aria-label="حساب ردیف سند">${this.accountOptions(line.accountId)}</select></td>
446 <td><input class="form-control ac-line-debit" aria-label="مبلغ بدهکار ردیف" inputmode="text" placeholder="۰" value="${html(line.debit ?? '0')}"></td>
447 <td><input class="form-control ac-line-credit" aria-label="مبلغ بستانکار ردیف" inputmode="text" placeholder="۰" value="${html(line.credit ?? '0')}"></td>
448 <td><input class="form-control ac-line-note" aria-label="شرح ردیف سند" value="${html(line.description || '')}"></td>
449 <td><button class="btn btn-secondary" onclick="this.closest('tr').remove()">حذف</button></td>
450 </tr>`;
451 }
452 async openJournalModal(id = null) {
453 if (!this.periods.some(p => !p.closed)) {
454 Toast.warning('ابتدا یک دوره مالی باز تعریف کنید');
455 return;
456 }
457 if (!this.accounts.some(a => a.level !== 'group')) {
458 Toast.warning('ابتدا کدینگ حسابداری را تعریف کنید');
459 return;
460 }
461 try {
462 const draft = id ? await Ledger.getJournal(id) : null;
463 if (draft && draft.status !== 'draft') throw new Error('تنها اسناد پیش‌نویس قابل ویرایش‌اند');
464 const periods = this.periods.filter(p => !p.closed);
465 const selected = draft?.periodId || periods.find(p => safeDate() >= p.startDate && safeDate() <= p.endDate)?.id || periods[0].id;
466 const options = periods.map(p => `<option value="${html(p.id)}" ${p.id === selected ? 'selected' : ''}>${html(p.name)}</option>`).join('');
467 const body = `<input id="acDraftId" type="hidden" value="${html(id || '')}">
468 <div class="form-row"><div class="form-group"><label class="form-label">دوره مالی</label>
469 <select id="acJournalPeriod" class="form-control">${options}</select></div>
470 <div class="form-group"><label class="form-label">تاریخ شمسی</label>
471 <input id="acJournalDate" class="form-control" value="${html(draft?.date || safeDate())}"></div></div>
472 <div class="form-group"><label class="form-label">شرح سند</label>
473 <input id="acJournalDescription" class="form-control" value="${html(draft?.description || '')}"></div>
474 <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار (ریال)</th>
475 <th>بستانکار (ریال)</th><th>شرح ردیف</th><th>عملیات</th></tr></thead>
476 <tbody id="acJournalLines">${(draft?.lines?.length ? draft.lines : [{}, {}]).map(l => this.journalRow(l)).join('')}</tbody>
477 </table></div><button class="btn btn-secondary" style="margin-top:10px" onclick="window.AccountingView.addJournalRow()">افزودن ردیف</button>
478 <p style="font-size:12px;color:var(--text-muted);margin-top:10px">مبالغ باید عدد صحیح به ریال باشند. پیش‌نویس می‌تواند نامتوازن باشد؛ سند قطعی باید تراز شود.</p>`;
479 const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
480 <button class="btn btn-secondary" onclick="window.AccountingView.saveJournal('draft')">ذخیره پیش‌نویس</button>
481 <button class="btn" onclick="window.AccountingView.saveJournal('posted')">ثبت قطعی</button>`;
482 Modal.open({ title: id ? 'ویرایش پیش‌نویس' : 'سند حسابداری دستی', body, footer, size: 'lg', closeOnBackdrop: false });
483 } catch (error) { Toast.error(error.message); }
484 }
485 addJournalRow() {
486 document.getElementById('acJournalLines')?.insertAdjacentHTML('beforeend', this.journalRow());
487 }
488 readJournalForm() {
489 const lines = [...document.querySelectorAll('#acJournalLines .ac-journal-line')].map(row => ({
490 accountId: row.querySelector('.ac-line-account').value,
491 debit: rial(row.querySelector('.ac-line-debit').value),
492 credit: rial(row.querySelector('.ac-line-credit').value),
493 description: row.querySelector('.ac-line-note').value.trim()
494 }));
495 return {
496 periodId: document.getElementById('acJournalPeriod').value,
497 date: digits(document.getElementById('acJournalDate').value).trim(),
498 description: document.getElementById('acJournalDescription').value.trim(),
499 lines
500 };
501 }
502 async saveJournal(mode) {
503 if (this.busy) return;
504 this.busy = true;
505 try {
506 const draftId = document.getElementById('acDraftId').value;
507 const data = this.readJournalForm();
508 if (draftId) {
509 await Ledger.updateDraftJournal(draftId, data, { post: mode === 'posted' });
510 } else if (mode === 'posted') {
511 await Ledger.postJournal(data);
512 } else {
513 await Ledger.saveDraftJournal(data);
514 }
515 Modal.close();
516 Toast.success(mode === 'posted' ? 'سند حسابداری قطعی شد' : 'پیش‌نویس ذخیره شد');
517 await this.refresh();
518 } catch (error) { Toast.error('خطای ثبت سند: ' + error.message); }
519 finally { this.busy = false; }
520 }
521 deleteDraft(id) {
522 Modal.confirm({ title: 'حذف پیش‌نویس', danger: true,
523 message: 'فقط سند پیش‌نویس و ردیف‌های آن حذف می‌شوند. سند قطعی هرگز از این مسیر حذف نخواهد شد.',
524 confirmText: 'حذف پیش‌نویس', onConfirm: async () => {
525 try {
526 await Ledger.discardDraftJournal(id);
527 Toast.success('پیش‌نویس حذف شد');
528 await this.refresh();
529 } catch (error) { Toast.error(error.message); }
530 }
531 });
532 }
533 async postDraft(id) {
534 Modal.confirm({ title: 'قطعی‌سازی سند', message: 'پس از قطعی شدن امکان ویرایش مستقیم وجود ندارد. ادامه می‌دهید؟',
535 confirmText: 'ثبت قطعی', onConfirm: async () => {
536 try {
537 await Ledger.postDraftJournal(id);
538 Toast.success('سند قطعی شد');
539 await this.refresh();
540 } catch (error) { Toast.error(error.message); }
541 }
542 });
543 }
544 async showJournal(id) {
545 try {
546 const j = await Ledger.getJournal(id);
547 const lines = j.lines.map(l => {
548 const a = this.accounts.find(x => x.id === l.accountId);
549 return `<tr><td>${html(a ? a.code + ' — ' + a.name : l.accountId)}</td>
550 <td>${Formatters.number(l.debit)}</td><td>${Formatters.number(l.credit)}</td><td>${html(l.description)}</td></tr>`;
551 }).join('');
552 Modal.open({ title: 'جزئیات سند حسابداری', size: 'lg',
553 body: `<p style="margin-bottom:10px">تاریخ: ${html(j.date)} | وضعیت: ${html(j.status)} | شرح: ${html(j.description)}</p>
554 <div class="table-wrap"><table><thead><tr><th>حساب</th><th>بدهکار</th><th>بستانکار</th><th>شرح</th></tr></thead>
555 <tbody>${lines}</tbody><tfoot><tr><th>جمع</th><th>${Formatters.number(j.debit)}</th><th>${Formatters.number(j.credit)}</th><th></th></tr></tfoot></table></div>`,
556 footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>'
557 });
558 } catch (error) { Toast.error(error.message); }
559 }
560 async renderIntegration() {
561 const active = await Retail.isEnabled();
562 if (!active) return `<div class="card">
563 <h3>اتصال یکپارچه خرید، فروش و حسابداری</h3>
564 <p style="line-height:2;margin:12px 0">فعال‌سازی فقط برای شرکت بدون گردش مالی قبلی مجاز است. اگر شرکت سابقه فاکتور، انبار یا خزانه دارد، ابتدا مانده افتتاحیه و مهاجرت آن باید تأیید شود. داده‌های قبلی پاک یا تبدیل خودکار نمی‌شوند.</p>
565 <p style="line-height:2;margin-bottom:14px">پیش از فعال‌سازی، دوره مالی باز بسازید و دکمه «ایجاد کدینگ پیشنهادی» را از تب کدینگ اجرا کنید.</p>
566 <button class="btn" onclick="window.AccountingView.activateRetail()">فعال‌سازی حسابداری یکپارچه برای شرکت خالی</button></div>`;
567 const [warehouses, balances, stocktakes, products] = await Promise.all([
568 Retail.warehouses(),Retail.stockBalances(),Retail.getStocktakes(),DataScope.list('products')
569 ]);
570 const names = Object.fromEntries(products.map(p=>[p.id,p.name]));
571 const warehouseNames = Object.fromEntries(warehouses.map(w=>[w.id,w.name]));
572 const stockRows = balances.map(b=>`<tr><td>${html(names[b.productId]||b.productId)}</td>
573 <td>${html(warehouseNames[b.warehouseId]||b.warehouseId)}</td>
574 <td>${Formatters.number(b.quantityUnits/1000)}</td><td>${Formatters.number(b.value)} ریال</td></tr>`).join('');
575 const takeRows=stocktakes.map(s=>`<tr><td>${html(warehouseNames[s.warehouseId]||s.warehouseId)}</td>
576 <td>${html(s.date)}</td><td>${s.status==='draft'?'در انتظار شمارش':'قطعی'}</td>
577 <td><button class="btn btn-secondary" onclick="window.AccountingView.openStocktake(${actionArg(s.id)})">مشاهده و شمارش</button></td></tr>`).join('');
578 return `<div class="card"><div class="toolbar"><strong>حسابداری یکپارچه فعال است</strong>
579 <button class="btn" onclick="window.AccountingView.openWarehouse()">انبار جدید</button>
580 <button class="btn btn-secondary" onclick="window.AccountingView.openTransfer()">انتقال کالا</button>
581 <button class="btn" onclick="window.AccountingView.openStocktakeCreate()">انبارگردانی جدید</button></div>
582 <p style="margin:10px 0">فاکتور جدید، دریافت و پرداخت، هزینه و چک به دفتر حسابداری متصل‌اند. تغییر اسناد قطعی فقط با فرآیند اصلاح و برگشت مجاز است.</p>
583 <h4>موجودی و ارزش انبار</h4><div class="table-wrap"><table><thead><tr><th>کالا</th><th>انبار</th><th>مقدار</th><th>ارزش (ریال)</th></tr></thead>
584 <tbody>${stockRows||'<tr><td colspan="4">موجودی ثبت نشده است.</td></tr>'}</tbody></table></div>
585 <h4 style="margin-top:16px">جلسات انبارگردانی</h4><div class="table-wrap"><table><thead><tr><th>انبار</th><th>تاریخ</th><th>وضعیت</th><th>عملیات</th></tr></thead>
586 <tbody>${takeRows||'<tr><td colspan="4">جلسه‌ای وجود ندارد.</td></tr>'}</tbody></table></div></div>`;
587 }
588 activateRetail() {
589 Modal.confirm({title:'فعال‌سازی ثبت مالی یکپارچه',danger:true,
590 message:'این کار گردش جدید فروش، خرید، خزانه و انبار را به حسابداری دوبل متصل می‌کند. شرکت دارای گردش قبلی بدون مهاجرت تأییدشده فعال نمی‌شود. ابتدا نسخه پشتیبان بگیرید.',
591 confirmText:'فعال‌سازی برای شرکت خالی',
592 onConfirm:async()=>{
593 try{await Retail.activate();Toast.success('ثبت یکپارچه فعال شد');await this.refresh()}
594 catch(e){Toast.error(e.message)}
595 }});
596 }
597 openWarehouse() {
598 Modal.open({title:'ایجاد انبار',size:'sm',closeOnBackdrop:false,
599 body:'<label class="form-label" for="acWhName">نام انبار</label><input id="acWhName" class="form-control">',
600 footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveWarehouse()">ثبت انبار</button>'});
601 }
602 async saveWarehouse() {
603 if(this.busy)return;this.busy=true;
604 try{await Retail.addWarehouse(document.getElementById('acWhName').value);
605 Modal.close();Toast.success('انبار ایجاد شد');await this.refresh()}
606 catch(e){Toast.error(e.message)}finally{this.busy=false}
607 }
608 async openTransfer() {
609 try {
610 const [warehouses,products]=await Promise.all([Retail.warehouses(),DataScope.list('products')]);
611 if(warehouses.length<2){Toast.warning('برای انتقال کالا حداقل دو انبار لازم است');return}
612 const opts=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join('');
613 const prod=products.filter(p=>p.trackInventory!==false)
614 .map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join('');
615 Modal.open({title:'انتقال کالا بین انبارها',size:'sm',closeOnBackdrop:false,
616 body:`<div class="form-group"><label class="form-label">کالا</label><select class="form-control" id="acTrProduct">${prod}</select></div>
617 <div class="form-group"><label class="form-label">انبار مبدا</label><select class="form-control" id="acTrFrom">${opts}</select></div>
618 <div class="form-group"><label class="form-label">انبار مقصد</label><select class="form-control" id="acTrTo">${opts}</select></div>
619 <div class="form-group"><label class="form-label">مقدار</label><input id="acTrQty" class="form-control" value="1"></div>
620 <div class="form-group"><label class="form-label">تاریخ</label><input id="acTrDate" class="form-control" value="${safeDate()}"></div>`,
621 footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveTransfer()">ثبت انتقال</button>'});
622 }catch(e){Toast.error(e.message)}
623 }
624 async saveTransfer() {
625 if(this.busy)return;this.busy=true;
626 try {
627 await Retail.transferStock({
628 productId:document.getElementById('acTrProduct').value,
629 fromWarehouseId:document.getElementById('acTrFrom').value,
630 toWarehouseId:document.getElementById('acTrTo').value,
631 quantity:Number(digits(document.getElementById('acTrQty').value)),
632 date:digits(document.getElementById('acTrDate').value)});
633 Modal.close();Toast.success('انتقال انبار ثبت شد');await this.refresh();
634 }catch(e){Toast.error(e.message)}finally{this.busy=false}
635 }
636 async openStocktakeCreate() {
637 try {
638 const warehouses=await Retail.warehouses();
639 const options=warehouses.map(w=>`<option value="${html(w.id)}">${html(w.name)}</option>`).join('');
640 Modal.open({title:'شروع شمارش انبار',size:'sm',closeOnBackdrop:false,
641 body:`<label class="form-label" for="acStWarehouse">انبار</label><select class="form-control" id="acStWarehouse">${options}</select>
642 <label class="form-label" for="acStDate">تاریخ شمسی</label><input class="form-control" id="acStDate" value="${safeDate()}">
643 <p style="margin-top:12px">موجودی مبنا ثابت ثبت می‌شود؛ برای تأیید، شمارش همه اقلام ضروری است.</p>`,
644 footer:'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.createStocktake()">ایجاد جلسه</button>'});
645 }catch(e){Toast.error(e.message)}
646 }
647 async createStocktake() {
648 if(this.busy)return;this.busy=true;
649 try {
650 const take=await Retail.newStocktake({warehouseId:document.getElementById('acStWarehouse').value,
651 date:digits(document.getElementById('acStDate').value)});
652 Modal.close();Toast.success('جلسه شمارش ایجاد شد');await this.refresh();await this.openStocktake(take.id);
653 }catch(e){Toast.error(e.message)}finally{this.busy=false}
654 }
655 async openStocktake(id) {
656 try {
657 const sessions=await Retail.getStocktakes(),take=sessions.find(s=>s.id===id);
658 if(!take)throw Error('جلسه شمارش یافت نشد');
659 const lines=await Retail.getStocktakeLines(id),products=await DataScope.list('products');
660 const names=Object.fromEntries(products.map(p=>[p.id,p.name]));
661 const extras=products.filter(p=>p.trackInventory!==false&&!lines.some(l=>l.productId===p.id));
662 const extraOptions=extras.map(p=>`<option value="${html(p.id)}">${html(p.name)}</option>`).join('');
663 const existing=lines.map(l=>`<tr data-product="${html(l.productId)}">
664 <td>${html(names[l.productId]||l.productId)}</td><td>${l.expectedUnits/1000}</td>
665 <td><input class="form-control ac-count" value="${l.countedUnits===null?'':l.countedUnits/1000}" ${take.status!=='draft'?'disabled':''}></td>
666 <td><input class="form-control ac-cost" placeholder="ریال" value="${l.unitCost??''}" ${take.status!=='draft'?'disabled':''}></td></tr>`).join('');
667 Modal.open({title:'برگه انبارگردانی',size:'lg',closeOnBackdrop:false,
668 body:`<input type="hidden" id="acStocktakeId" value="${html(id)}">
669 <p style="margin-bottom:10px">مقدار شمارش واقعی و در صورت مازاد کالای بدون مانده، قیمت تمام‌شده واحد را وارد کنید.</p>
670 <div class="table-wrap"><table><thead><tr><th>کالا</th><th>مبنای سیستم</th><th>شمارش واقعی</th><th>بهای واحد مازاد</th></tr></thead>
671 <tbody id="acTakeRows">${existing}</tbody></table></div>
672 ${take.status==='draft'&&extras.length?`<div style="display:flex;gap:8px;margin-top:12px;align-items:center">
673 <select class="form-control" id="acTakeNewProduct">${extraOptions}</select>
674 <button class="btn btn-secondary" onclick="window.AccountingView.addStocktakeProduct()">افزودن کالای جدید به شمارش</button>
675 </div>`:''}`,
676 footer:take.status==='draft'?'<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button><button class="btn" onclick="window.AccountingView.saveStocktake()">ذخیره شمارش</button><button class="btn btn-secondary" onclick="window.AccountingView.finishStocktake()">تأیید نهایی</button>':
677 '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>'});
678 }catch(e){Toast.error(e.message)}
679 }
680 addStocktakeProduct() {
681 const selector=document.getElementById('acTakeNewProduct');
682 if(!selector?.value)return;
683 const id=selector.value;
684 const label=selector.selectedOptions[0]?.textContent||id;
685 const body=document.getElementById('acTakeRows');
686 if(!body||body.querySelector('[data-product="'+id+'"]'))return;
687 body.insertAdjacentHTML('beforeend',`<tr data-product="${html(id)}">
688 <td>${html(label)}</td><td>۰</td>
689 <td><input class="form-control ac-count" value="0"></td>
690 <td><input class="form-control ac-cost" placeholder="ریال"></td></tr>`);
691 selector.selectedOptions[0]?.remove();
692 }
693 async persistStocktakeCounts(id) {
694 for(const row of document.querySelectorAll('#acTakeRows tr[data-product]')){
695 const count=digits(row.querySelector('.ac-count').value).trim();
696 const cost=digits(row.querySelector('.ac-cost').value).trim();
697 if(!count)throw Error('برای همه اقلام مقدار شمارش را وارد کنید');
698 await Retail.countStocktake(id,row.dataset.product,Number(count),cost?Number(cost):null);
699 }
700 }
701 async saveStocktake() {
702 if(this.busy)return;this.busy=true;
703 try {
704 const id=document.getElementById('acStocktakeId').value;
705 await this.persistStocktakeCounts(id);
706 Modal.close();Toast.success('شمارش ثبت شد');await this.refresh();
707 }catch(e){Toast.error(e.message)}finally{this.busy=false}
708 }
709 async finishStocktake() {
710 if(this.busy)return;this.busy=true;
711 try {
712 const id=document.getElementById('acStocktakeId').value;
713 await this.persistStocktakeCounts(id);
714 await Retail.finalizeStocktake(id);
715 Modal.close();Toast.success('انبارگردانی تأیید و سند تعدیل ثبت شد');await this.refresh();
716 }catch(e){Toast.error(e.message)}finally{this.busy=false}
717 }
718 openReversal(id) {
719 const periods = this.periods.filter(p => !p.closed);
720 if (!periods.length) { Toast.error('دوره باز برای ثبت سند برگشت وجود ندارد'); return; }
721 const opts = periods.map(p => `<option value="${html(p.id)}">${html(p.name)}</option>`).join('');
722 Modal.open({ title: 'ثبت سند معکوس', size: 'sm', closeOnBackdrop: false,
723 body: `<input type="hidden" id="acReversalId" value="${html(id)}">
724 <p style="font-size:12px;margin-bottom:10px">این عملیات سندی جداگانه با بدهکار/بستانکار معکوس می‌سازد و سند اصلی حذف نمی‌شود.</p>
725 <div class="form-group"><label class="form-label">دوره باز</label>
726 <select class="form-control" id="acReversalPeriod">${opts}</select></div>
727 <div class="form-group"><label class="form-label">تاریخ برگشت</label>
728 <input class="form-control" id="acReversalDate" value="${html(safeDate())}"></div>`,
729 footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button><button class="btn" onclick="window.AccountingView.saveReversal()">ثبت سند برگشت</button>'
730 });
731 }
732 async saveReversal() {
733 if (this.busy) return;
734 this.busy = true;
735 try {
736 await Ledger.reverseJournal(document.getElementById('acReversalId').value, {
737 periodId: document.getElementById('acReversalPeriod').value,
738 date: digits(document.getElementById('acReversalDate').value).trim()
739 });
740 Modal.close();
741 Toast.success('سند برگشت مستقل ثبت شد');
742 await this.refresh();
743 } catch (error) { Toast.error(error.message); }
744 finally { this.busy = false; }
745 }
746 }
747
748 export const AccountingView = new AccountingViewImpl();