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

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