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

fix/a01-explicit-refund-reason-approval-20261021
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 999 lines 47.4 KB
Raw
1 // ============================================================
2 // SettingsView — صفحه‌ی تنظیمات، بکاپ، شرکت و Excel
3 // ============================================================
4
5 import { SettingsController } from '../controllers/SettingsController.js';
6 import { StorageService } from '../core/StorageService.js';
7 import { Theme } from '../core/Theme.js';
8 import { KeyboardShortcuts } from '../core/KeyboardShortcuts.js';
9 import { Modal } from '../core/Modal.js';
10 import { Toast } from '../core/Toast.js';
11 import { Formatters } from '../utils/Formatters.js';
12 import { Auth } from '../core/Auth.js';
13 import { ExcelController } from '../controllers/ExcelController.js';
14 import { inspectSettlementConsistency } from '../core/FinancialDiagnosticsService.js';
15 import { AuditService } from '../core/AuditService.js';
16 import { LicenseService } from '../core/LicenseService.js';
17
18 let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
19
20 class SettingsViewImpl {
21 async render() {
22 await this.reload();
23 return `
24 <div class="page-title">
25 <h2>تنظیمات</h2>
26 <p>مدیریت اطلاعات شرکت، پشتیبان‌گیری، Excel و تنظیمات سیستم</p>
27 </div>
28
29 <div class="settings-grid">
30 ${this._renderCompanyCard()}
31 ${this._renderInvoiceSettingsCard()}
32 ${this._renderExcelCard()}
33 ${this._renderShortcutsCard()}
34 ${this._renderBackupCard()}
35 ${Auth.isAdmin() ? this._renderLicenseCard() : ''}
36 ${this._renderStatsCard()}
37 ${Auth.isAdmin() ? this._renderHealthCard() : ''}
38 ${Auth.isAdmin() ? this._renderAuditCard() : ''}
39 ${this._renderThemeCard()}
40 ${this._renderAboutCard()}
41 </div>
42 `;
43 }
44
45 onMount() {
46 window.SettingsView = this;
47 }
48
49 async reload() {
50 const results = await Promise.allSettled([
51 SettingsController.getCompanyInfo(),
52 SettingsController.getInvoiceSettings(),
53 this._collectStats()
54 ]);
55 const defaults = [{}, { numberingMode: 'auto', nextNumber: 1 }, {}];
56 const values = results.map((result, index) => {
57 if (result.status === 'fulfilled') return result.value;
58 console.error('Settings load failed:', index, result.reason);
59 Toast.error('بخشی از تنظیمات بارگذاری نشد: ' + (result.reason?.message || 'خطای نامشخص'));
60 return defaults[index];
61 });
62 [cache.company, cache.invoiceSettings, cache.stats] = values;
63 }
64
65 async _collectStats() {
66 const user = Auth.current();
67 if (!user) return {};
68 const stores = ['products', 'contacts', 'invoices', 'cheques', 'treasury'];
69 const stats = {};
70 for (const s of stores) {
71 try {
72 const list = await StorageService.getByOwner(s, user.id);
73 if (s === 'treasury') {
74 stats.accounts = list.filter(x => x.recordType === 'account').length;
75 stats.transactions = list.filter(x => x.recordType === 'transaction').length;
76 } else {
77 stats[s] = list.length;
78 }
79 } catch (e) {
80 stats[s] = 0;
81 }
82 }
83 return stats;
84 }
85
86 // ============================================================
87 // کارت اطلاعات شرکت
88 // ============================================================
89 _renderCompanyCard() {
90 const c = cache.company;
91 return `
92 <div class="card settings-card">
93 <div class="settings-card-header">
94 <div class="settings-card-icon">🏢</div>
95 <div>
96 <h3 class="settings-card-title">اطلاعات شرکت / فروشگاه</h3>
97 <p class="settings-card-desc">این اطلاعات در سربرگ فاکتورهای چاپی نمایش داده می‌شود</p>
98 </div>
99 </div>
100 ${c.name ? `
101 <div class="company-preview">
102 <div style="font-weight:700;font-size:14px">${this._esc(c.name)}</div>
103 ${c.nationalId ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:3px">شناسه ملی: ${Formatters.toPersianDigits(c.nationalId)}</div>` : ''}
104 ${c.address ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">${this._esc(c.address)}</div>` : ''}
105 ${c.phone ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">تلفن: ${Formatters.phone(c.phone)}</div>` : ''}
106 </div>
107 ` : `
108 <div class="empty-mini">هنوز اطلاعاتی وارد نشده</div>
109 `}
110 <div style="display:flex;gap:8px;flex-wrap:wrap">
111 <button class="btn" onclick="window.SettingsView.openCompanyModal()">${c.name ? '✏️ ویرایش اطلاعات' : '➕ وارد کردن اطلاعات'}</button>
112 <button class="btn" onclick="window.SettingsView.openCompanySwitcher()">🔄 تغییر شرکت</button>
113 ${Auth.isAdmin() ? '<button class="btn" onclick="window.SettingsView.createCompany()">➕ شرکت جدید</button>' : ''}
114 </div>
115 </div>
116 `;
117 }
118
119 _renderInvoiceSettingsCard() {
120 const s = cache.invoiceSettings || { numberingMode: 'auto', nextNumber: 1 };
121 return `
122 <div class="card settings-card">
123 <div class="settings-card-header">
124 <div class="settings-card-icon">🧾</div>
125 <div>
126 <h3 class="settings-card-title">تنظیمات فاکتور</h3>
127 <p class="settings-card-desc">نحوه شماره‌گذاری فاکتورهای جدید</p>
128 </div>
129 </div>
130 <div class="form-group">
131 <label class="form-label">نحوه شماره‌گذاری</label>
132 <select class="form-control" id="invoiceNumberingMode">
133 <option value="auto" ${s.numberingMode === 'auto' ? 'selected' : ''}>خودکار</option>
134 <option value="manual" ${s.numberingMode === 'manual' ? 'selected' : ''}>دستی</option>
135 </select>
136 </div>
137 <div class="form-group">
138 <label class="form-label">شماره بعدی فاکتور</label>
139 <input class="form-control" id="invoiceNextNumber" type="number" min="1" value="${Number(s.nextNumber) || 1}" />
140 </div>
141 <button class="btn" onclick="window.SettingsView.saveInvoiceSettings()">💾 ذخیره تنظیمات فاکتور</button>
142 </div>
143 `;
144 }
145
146 async saveInvoiceSettings() {
147 const numberingMode = document.getElementById('invoiceNumberingMode').value;
148 const nextNumber = Number(document.getElementById('invoiceNextNumber').value);
149 if (!Number.isInteger(nextNumber) || nextNumber < 1) {
150 Toast.warning('شماره بعدی باید عدد صحیح بزرگ‌تر از صفر باشد');
151 return;
152 }
153 try {
154 cache.invoiceSettings = await SettingsController.saveInvoiceSettings({ numberingMode, nextNumber });
155 Toast.success('تنظیمات فاکتور ذخیره شد');
156 } catch (err) {
157 console.error('Invoice settings save failed:', err);
158 Toast.error('خطا در ذخیره تنظیمات فاکتور: ' + err.message);
159 }
160 }
161
162 // ============================================================
163 // کارت Excel (جدید)
164 // ============================================================
165 _renderExcelCard() {
166 const s = cache.stats;
167 return `
168 <div class="card settings-card" style="border-color:#bbf7d0;background:linear-gradient(135deg,#f0fdf4,#f8fafc)">
169 <div class="settings-card-header">
170 <div class="settings-card-icon" style="background:linear-gradient(135deg,#16a34a,#15803d)">📊</div>
171 <div>
172 <h3 class="settings-card-title">Excel — خروجی و ورودی</h3>
173 <p class="settings-card-desc">داده‌ها را به Excel ببر یا از Excel بیار</p>
174 </div>
175 </div>
176
177 <div style="font-size:12.5px;color:var(--text-muted);line-height:1.8;margin-bottom:12px;padding:10px 12px;background:rgba(255,255,255,.6);border-radius:8px">
178 <strong>💡 نکته:</strong> از این بخش می‌تونی کل داده‌ها رو در یه فایل Excel بگیری، یا از یه فایل Excel (که قبلاً آماده کردی) کالا و اشخاص اضافه کنی.
179 </div>
180
181 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px">
182 <button class="btn" style="background:linear-gradient(135deg,#16a34a,#15803d)" onclick="window.SettingsView.exportAllExcel()">
183 📥 خروجی کامل (Excel)
184 </button>
185 <button class="btn btn-secondary" onclick="window.SettingsView.openExportSectionModal()">
186 🎯 خروجی انتخابی
187 </button>
188 </div>
189
190 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
191 <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📤 ورود از Excel</div>
192 <div style="display:flex;gap:10px;flex-wrap:wrap">
193 <button class="btn btn-secondary" onclick="window.SettingsView.importProductsExcel()">
194 📦 ورود کالاها
195 </button>
196 <button class="btn btn-secondary" onclick="window.SettingsView.importContactsExcel()">
197 👥 ورود اشخاص
198 </button>
199 </div>
200 </div>
201
202 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
203 <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📄 قالب‌های نمونه</div>
204 <div style="display:flex;gap:10px;flex-wrap:wrap">
205 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadProductsTemplate()">
206 📋 قالب کالاها
207 </button>
208 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadContactsTemplate()">
209 📋 قالب اشخاص
210 </button>
211 </div>
212 </div>
213 </div>
214 `;
215 }
216
217 async exportAllExcel() {
218 try {
219 Toast.info('در حال آماده‌سازی فایل Excel...');
220 const result = await ExcelController.exportAll();
221 Toast.success(`فایل Excel با ${Formatters.toPersianDigits(result.sheets)} شیت دانلود شد`);
222 } catch (err) {
223 console.error(err);
224 Toast.error('خطا در خروجی: ' + err.message);
225 }
226 }
227
228 openExportSectionModal() {
229 const body = `
230 <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px">کدوم بخش رو می‌خوای به Excel ببری؟</p>
231 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
232 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('products')">
233 <div style="font-size:22px">📦</div>
234 <div style="font-size:12.5px">کالاها</div>
235 </button>
236 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('contacts')">
237 <div style="font-size:22px">👥</div>
238 <div style="font-size:12.5px">اشخاص</div>
239 </button>
240 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('invoices')">
241 <div style="font-size:22px">🧾</div>
242 <div style="font-size:12.5px">فاکتورها</div>
243 </button>
244 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('cheques')">
245 <div style="font-size:22px">💳</div>
246 <div style="font-size:12.5px">چک‌ها</div>
247 </button>
248 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('expenses')">
249 <div style="font-size:22px">💰</div>
250 <div style="font-size:12.5px">هزینه و درآمد</div>
251 </button>
252 </div>
253 `;
254 const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>`;
255 Modal.open({ title: '🎯 خروجی انتخابی به Excel', body, footer, size: 'md' });
256 }
257
258 async _exportSection(section) {
259 try {
260 const result = await ExcelController.exportSection(section);
261 Toast.success(`فایل دانلود شد (${Formatters.number(result.count)} مورد)`);
262 Modal.close();
263 } catch (err) {
264 Toast.error('خطا: ' + err.message);
265 }
266 }
267
268 // ============================================================
269 // ورودی از Excel
270 // ============================================================
271 importProductsExcel() {
272 const input = document.createElement('input');
273 input.type = 'file';
274 input.accept = '.xlsx,.xls';
275 input.onchange = async (e) => {
276 const file = e.target.files[0];
277 if (!file) return;
278 await this._handleImportFile(file, 'products');
279 };
280 input.click();
281 }
282
283 importContactsExcel() {
284 const input = document.createElement('input');
285 input.type = 'file';
286 input.accept = '.xlsx,.xls';
287 input.onchange = async (e) => {
288 const file = e.target.files[0];
289 if (!file) return;
290 await this._handleImportFile(file, 'contacts');
291 };
292 input.click();
293 }
294
295 async _handleImportFile(file, kind) {
296 try {
297 Toast.info('در حال خواندن فایل...');
298 const preview = await ExcelController.previewFile(file);
299
300 const kindLabel = kind === 'products' ? 'کالاها' : 'اشخاص';
301 const sheetsHtml = preview.sheets.map(s => `
302 <div style="padding:8px 12px;background:var(--bg);border-radius:8px;margin-bottom:6px;font-size:12.5px">
303 <strong>${this._esc(s.name)}</strong>
304 <span style="color:var(--text-muted);margin-right:6px">(${Formatters.number(s.count)} سطر)</span>
305 </div>
306 `).join('');
307
308 const body = `
309 <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px">
310 فایل <strong>${this._esc(file.name)}</strong> خونده شد. شیت‌های موجود:
311 </p>
312 ${sheetsHtml}
313 <div class="form-group" style="margin-top:14px">
314 <label class="form-label">حالت ورود</label>
315 <select class="form-control" id="importMode">
316 <option value="merge">🔀 ادغام (Merge) — فقط موارد جدید اضافه می‌شن</option>
317 <option value="replace">🔄 جایگزینی (Replace) — همه‌ی ${kindLabel} فعلی پاک و از فایل جایگزین می‌شن</option>
318 </select>
319 </div>
320 `;
321 const footer = `
322 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
323 <button class="btn btn-success" onclick="window.SettingsView._confirmImport(${JSON.stringify(kind).replace(/"/g, "'")}, '${this._esc(file.name)}')">✅ شروع ایمپورت</button>
324 `;
325 Modal.open({ title: `📤 ورود ${kindLabel} از Excel`, body, footer, size: 'md' });
326
327 // ذخیره‌ی موقت داده
328 window.__importRawData = preview.raw;
329 window.__importKind = kind;
330 } catch (err) {
331 console.error(err);
332 Toast.error('خطا: ' + err.message);
333 }
334 }
335
336 async _confirmImport(kind, fileName) {
337 const mode = document.getElementById('importMode').value;
338 const rawData = window.__importRawData;
339
340 if (!rawData) {
341 Toast.error('داده‌ای برای ایمپورت نیست');
342 return;
343 }
344
345 try {
346 Toast.info('در حال ایمپورت...');
347 let result;
348 if (kind === 'products') {
349 result = await ExcelController.importProducts(rawData, { mode });
350 } else {
351 result = await ExcelController.importContacts(rawData, { mode });
352 }
353
354 Modal.close();
355 Toast.success(`ایمپورت انجام شد: ${Formatters.number(result.added)} اضافه، ${Formatters.number(result.skipped)} رد شده`);
356
357 // رفرش KPI ها
358 await this.reload();
359 const grid = document.querySelector('.settings-grid');
360 if (grid) grid.innerHTML = this._renderAllCards();
361 } catch (err) {
362 console.error(err);
363 Toast.error('خطا در ایمپورت: ' + err.message);
364 } finally {
365 window.__importRawData = null;
366 window.__importKind = null;
367 }
368 }
369
370 async downloadProductsTemplate() {
371 try {
372 await ExcelController.downloadProductsTemplate();
373 } catch (error) {
374 Toast.error('ساخت قالب کالاها ناموفق بود: ' + error.message);
375 }
376 }
377
378 async downloadContactsTemplate() {
379 try {
380 await ExcelController.downloadContactsTemplate();
381 } catch (error) {
382 Toast.error('ساخت قالب اشخاص ناموفق بود: ' + error.message);
383 }
384 }
385
386 // ============================================================
387 // کارت میانبرهای صفحه‌کلید
388 // ============================================================
389 _renderShortcutsCard() {
390 const s = KeyboardShortcuts.settings;
391
392 const toggle = (id, checked, label, hint) => `
393 <label style="display:flex;align-items:flex-start;gap:10px;padding:9px 0;cursor:pointer;border-bottom:1px solid var(--border)">
394 <input type="checkbox" id="${id}" ${checked ? 'checked' : ''} style="margin-top:3px;width:16px;height:16px;cursor:pointer" />
395 <div style="flex:1">
396 <div style="font-size:13px;font-weight:600">${label}</div>
397 <div style="font-size:11px;color:var(--text-muted);margin-top:2px;line-height:1.6">${hint}</div>
398 </div>
399 </label>
400 `;
401
402 return `
403 <div class="card settings-card" style="border-color:#ddd6fe;background:linear-gradient(135deg,#faf5ff,#f8fafc)">
404 <div class="settings-card-header">
405 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">⌨️</div>
406 <div>
407 <h3 class="settings-card-title">میانبرهای صفحه‌کلید</h3>
408 <p class="settings-card-desc">با این میانبرها کار با برنامه سریع‌تر می‌شود</p>
409 </div>
410 </div>
411
412 ${toggle('scEnabled', s.enabled, 'فعال بودن میانبرها', 'کلاً همه‌ی میانبرهای زیر رو روشن یا خاموش می‌کند')}
413 ${toggle('scEnterConfirms', s.enterConfirms, 'تأیید با Enter', 'وقتی توی فرم هستید، Enter مثل دکمه‌ی ذخیره عمل می‌کند. Ctrl+Enter هم توی همه‌ی فیلدها کار می‌کند')}
414 ${toggle('scEscapeCloses', s.escapeCloses, 'بستن با Escape', 'فشار دادن Escape، مودال باز را می‌بندد')}
415 ${toggle('scCtrlSaves', s.ctrlSaves, 'ذخیره با Ctrl+S', 'داخل مودال‌ها، Ctrl+S فرم را ذخیره می‌کند')}
416 ${toggle('scPlusMinusZeros', s.plusMinusZeros, 'ضریب سریع صفر (+ و -)', 'روی فیلدهای مبلغ، کلید + صفر اضافه و کلید − صفر کم می‌کند')}
417
418 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
419 <div class="form-group" style="margin-bottom:0">
420 <label class="form-label">تعداد صفرهای کلید +</label>
421 <input type="text" inputmode="numeric" class="form-control" id="scPlusZeros" value="${Formatters.toPersianDigits(s.plusZeros)}" />
422 </div>
423 <div class="form-group" style="margin-bottom:0">
424 <label class="form-label">تعداد صفرهای کلید −</label>
425 <input type="text" inputmode="numeric" class="form-control" id="scMinusZeros" value="${Formatters.toPersianDigits(s.minusZeros)}" />
426 </div>
427 </div>
428
429 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
430 <button class="btn" onclick="window.SettingsView.saveShortcuts()">💾 ذخیره تنظیمات</button>
431 <button class="btn btn-secondary" onclick="window.SettingsView.resetShortcuts()">↺ بازگشت به پیش‌فرض</button>
432 </div>
433 </div>
434 `;
435 }
436
437 saveShortcuts() {
438 try {
439 const plusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scPlusZeros').value)) || 0;
440 const minusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scMinusZeros').value)) || 0;
441
442 const settings = {
443 enabled: document.getElementById('scEnabled').checked,
444 enterConfirms: document.getElementById('scEnterConfirms').checked,
445 escapeCloses: document.getElementById('scEscapeCloses').checked,
446 ctrlSaves: document.getElementById('scCtrlSaves').checked,
447 plusMinusZeros: document.getElementById('scPlusMinusZeros').checked,
448 plusZeros: Math.max(0, Math.min(12, plusZeros)),
449 minusZeros: Math.max(0, Math.min(12, minusZeros))
450 };
451
452 KeyboardShortcuts.saveSettings(settings);
453 Toast.success('تنظیمات میانبرهای صفحه‌کلید ذخیره شد');
454 } catch (err) {
455 Toast.error('خطا: ' + err.message);
456 }
457 }
458
459 resetShortcuts() {
460 Modal.confirm({
461 title: 'بازگشت به پیش‌فرض',
462 message: 'آیا می‌خواهید همه‌ی تنظیمات میانبرهای صفحه‌کلید به حالت پیش‌فرض برگردد؟',
463 confirmText: 'بازگردان',
464 onConfirm: () => {
465 KeyboardShortcuts.resetSettings();
466 Toast.success('تنظیمات به حالت پیش‌فرض برگشت');
467 const grid = document.querySelector('.settings-grid');
468 if (grid) grid.innerHTML = this._renderAllCards();
469 }
470 });
471 }
472
473 // ============================================================
474 // کارت بکاپ
475 // ============================================================
476 _renderBackupCard() {
477 return `
478 <div class="card settings-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f8fafc)">
479 <div class="settings-card-header">
480 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
481 <div>
482 <h3 class="settings-card-title">پشتیبان‌گیری رمزگذاری‌شده</h3>
483 <p class="settings-card-desc">اطلاعات عملیاتی و حسابداری شرکت فعال؛ بازیابی بدون بازنویسی کاربران و تنظیمات سراسری</p>
484 </div>
485 </div>
486
487 <div class="backup-warning">
488 ⚠️ <strong>مهم:</strong> قبل از هر تغییر بزرگ در برنامه، حتماً بکاپ بگیرید.
489 </div>
490
491 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
492 <button class="btn" onclick="window.SettingsView.downloadBackup()">
493 📥 دانلود فایل بکاپ
494 </button>
495 <button class="btn btn-secondary" onclick="window.SettingsView.openRestoreModal()">
496 📤 بازیابی از بکاپ
497 </button>
498 </div>
499
500 <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)">
501 <button class="btn btn-danger btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.openWipeModal()">
502 🗑️ پاک کردن کامل داده‌ها
503 </button>
504 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">این عمل قابل بازگشت نیست، حتماً قبلش بکاپ بگیرید</small>
505 </div>
506 </div>
507 `;
508 }
509
510 // ============================================================
511 // ابزار تشخیص مغایرت‌ها (فقط خواندنی و درخواستی)
512 // ============================================================
513 _renderHealthCard() {
514 return `
515 <div class="card settings-card">
516 <div class="settings-card-header">
517 <div class="settings-card-icon">🔎</div>
518 <div>
519 <h3 class="settings-card-title">کنترل سلامت تسویه‌های مالی</h3>
520 <p class="settings-card-desc">بررسی مغایرت فاکتورها، رسیدها و تخصیص‌ها در شرکت فعال؛ بدون تغییر اطلاعات</p>
521 </div>
522 </div>
523 <button class="btn btn-secondary" onclick="window.SettingsView.runFinancialDiagnostics()">
524 بررسی مغایرت‌ها
525 </button>
526 <small style="display:block;margin-top:8px;color:var(--text-muted)">بررسی فقط هنگام درخواست اجرا می‌شود و هیچ سندی را خودکار اصلاح نمی‌کند.</small>
527 </div>
528 `;
529 }
530
531 async runFinancialDiagnostics() {
532 if (!Auth.isAdmin()) { Toast.error('این بررسی فقط برای مدیر مجاز است'); return; }
533 try {
534 Toast.info('در حال بررسی تسویه‌ها...');
535 const report = await inspectSettlementConsistency({ maxIssues: 50 });
536 const names = {
537 ORPHAN_SETTLEMENT: 'تسویه بدون فاکتور معتبر',
538 INVALID_SETTLEMENT_AMOUNT: 'مبلغ نامعتبر تسویه',
539 MISSING_TREASURY_TRANSACTION: 'رسید یا تراکنش خزانه ناموجود',
540 SETTLEMENT_AMOUNT_OVERFLOW: 'سرریز مبلغ تسویه',
541 SETTLEMENT_TOTAL_MISMATCH: 'عدم تطابق مبلغ تسویه با فاکتور',
542 INVALID_INVOICE_AMOUNT: 'مبلغ نامعتبر فاکتور',
543 INVOICE_OVERPAID: 'تسویه بیش از مبلغ فاکتور',
544 INVOICE_REMAINING_MISMATCH: 'مانده فاکتور نادرست',
545 INVOICE_STATUS_MISMATCH: 'وضعیت تسویه ناهماهنگ'
546 };
547 const rows = report.issues.map(issue => `
548 <div style="padding:9px 0;border-bottom:1px solid var(--border)">
549 <strong>${this._esc(names[issue.code] || issue.code)}</strong>
550 <div style="font-size:12px;color:var(--text-muted)">شناسه سند: ${this._esc(issue.documentId)}</div>
551 </div>`).join('');
552 const body = `
553 <p>فاکتورهای کنترل‌شده: <strong>${Formatters.number(report.checkedInvoices)}</strong>
554 | تخصیص‌ها: <strong>${Formatters.number(report.checkedSettlements)}</strong>
555 | مغایرت‌ها: <strong>${Formatters.number(report.issueCount)}</strong></p>
556 <p style="color:var(--text-muted);font-size:12px">این گزارش تشخیصی است؛ پیش از هر اصلاح، سندهای مبنا را بررسی کنید.</p>
557 ${rows || '<p>در کنترل‌های فعلی مغایرتی یافت نشد.</p>'}
558 ${report.truncated ? '<p>فقط ۵۰ مغایرت نخست نمایش داده می‌شود.</p>' : ''}
559 `;
560 Modal.open({ title: 'گزارش کنترل سلامت تسویه‌ها', body,
561 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>', size: 'lg' });
562 } catch (err) {
563 Toast.error('بررسی سلامت تسویه‌ها ناموفق بود: ' + err.message);
564 }
565 }
566
567 // ============================================================
568 // ردپای حسابرسی فقط خواندنی برای مدیر
569 // ============================================================
570 _renderAuditCard() {
571 return `
572 <div class="card settings-card">
573 <div class="settings-card-header">
574 <div class="settings-card-icon">📋</div>
575 <div>
576 <h3 class="settings-card-title">ردپای حسابرسی</h3>
577 <p class="settings-card-desc">نمایش رویدادهای مالی ثبت‌شده از زمان فعال‌شدن ممیزی؛ سوابق قدیمی به‌طور خودکار ممیزی نمی‌شوند</p>
578 </div>
579 </div>
580 <button class="btn btn-secondary" onclick="window.SettingsView.openAuditTrail()">
581 مشاهده رویدادهای شرکت فعال
582 </button>
583 </div>
584 `;
585 }
586
587 async openAuditTrail() {
588 if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; }
589 try {
590 const events = await AuditService.list({ limit: 100 });
591 const labels = {
592 journal_posted: 'ثبت سند مالی',
593 journal_reversed: 'برگشت سند مالی',
594 commercial_journal_posted: 'ثبت رویداد تجاری',
595 period_opened: 'ایجاد دوره مالی',
596 period_closed: 'بستن دوره مالی',
597 draft_created: 'ساخت پیش‌نویس',
598 draft_updated: 'ویرایش پیش‌نویس',
599 draft_posted: 'ثبت قطعی پیش‌نویس',
600 draft_discarded: 'حذف پیش‌نویس',
601 backup_restored: 'بازیابی فایل پشتیبان'
602 };
603 const list = events.map(event => `
604 <div style="padding:10px 0;border-bottom:1px solid var(--border)">
605 <strong>${this._esc(labels[event.eventType] || event.eventType)}</strong>
606 <div style="color:var(--text-muted);font-size:12px">
607 سند: ${this._esc(event.sourceId)} | کاربر: ${this._esc(event.actorId)}
608 </div>
609 <div style="color:var(--text-muted);font-size:11px">
610 ${this._esc(event.businessDate || '')} — ${this._esc(event.occurredAtUtc)}
611 </div>
612 </div>
613 `).join('');
614 Modal.open({ title: 'ردپای حسابرسی شرکت فعال',
615 body: `<p style="font-size:12px;color:var(--text-muted)">تا ۱۰۰ رویداد اخیر؛ فقط از زمان فعال‌سازی ممیزی. اطلاعاتی که پیش از آن ثبت شده‌اند، سابقه ممیزی ساختگی ندارند.</p>${list || '<p>رویدادی یافت نشد.</p>'}`,
616 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
617 size: 'lg' });
618 } catch (err) {
619 Toast.error('نمایش ردپای حسابرسی ناموفق بود: ' + err.message);
620 }
621 }
622
623 // ============================================================
624 // کارت آمار
625 // ============================================================
626 _renderStatsCard() {
627 const s = cache.stats;
628 const items = [
629 { label: 'کالا و خدمات', value: s.products || 0, icon: '📦' },
630 { label: 'اشخاص', value: s.contacts || 0, icon: '👥' },
631 { label: 'فاکتورها', value: s.invoices || 0, icon: '🧾' },
632 { label: 'چک‌ها', value: s.cheques || 0, icon: '💳' },
633 { label: 'حساب‌ها', value: s.accounts || 0, icon: '🏦' },
634 { label: 'تراکنش‌ها', value: s.transactions || 0, icon: '💸' }
635 ];
636 return `
637 <div class="card settings-card">
638 <div class="settings-card-header">
639 <div class="settings-card-icon" style="background:linear-gradient(135deg,#0ea5e9,#0369a1)">📊</div>
640 <div>
641 <h3 class="settings-card-title">آمار داده‌ها</h3>
642 <p class="settings-card-desc">خلاصه‌ی داده‌های ذخیره‌شده در سیستم</p>
643 </div>
644 </div>
645 <div class="stats-grid">
646 ${items.map(i => `
647 <div class="stat-mini">
648 <div style="font-size:18px;margin-bottom:4px">${i.icon}</div>
649 <div style="font-size:18px;font-weight:800;color:var(--primary)">${Formatters.number(i.value)}</div>
650 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${i.label}</div>
651 </div>
652 `).join('')}
653 </div>
654 </div>
655 `;
656 }
657
658 // ============================================================
659 // کارت تم
660 // ============================================================
661 _renderThemeCard() {
662 const current = Theme.current();
663 return `
664 <div class="card settings-card">
665 <div class="settings-card-header">
666 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">🎨</div>
667 <div>
668 <h3 class="settings-card-title">ظاهر و تم</h3>
669 <p class="settings-card-desc">حالت نمایش برنامه</p>
670 </div>
671 </div>
672 <div style="display:flex;gap:10px;margin-top:8px">
673 <button class="btn ${current === 'light' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('light')">☀️ روشن</button>
674 <button class="btn ${current === 'dark' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('dark')">🌙 تاریک</button>
675 </div>
676 </div>
677 `;
678 }
679
680 // ============================================================
681 // کارت درباره
682 // ============================================================
683 _renderAboutCard() {
684 return `
685 <div class="card settings-card">
686 <div class="settings-card-header">
687 <div class="settings-card-icon">ℹ️</div>
688 <div>
689 <h3 class="settings-card-title">درباره فینورا پرو</h3>
690 <p class="settings-card-desc">نسخه ۲.۰.۳</p>
691 </div>
692 </div>
693 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
694 <div><strong>طراح و توسعه‌دهنده:</strong> داوود مهربان</div>
695 <div><strong>تماس:</strong> <span dir="ltr">0912-437-6991</span></div>
696 <div style="margin-top:8px;padding-top:10px;border-top:1px dashed var(--border)">
697 <a href="https://wa.me/989124376991" target="_blank" class="btn btn-inline" style="background:linear-gradient(135deg,#25D366,#128C7E);font-size:12.5px;min-height:36px">💬 واتس‌اپ پشتیبانی</a>
698 </div>
699 </div>
700 </div>
701 `;
702 }
703
704 _renderLicenseCard() {
705 const state = LicenseService.status();
706 const mode = state.mode === 'licensed' ? 'مجوز امضاشده معتبر' :
707 state.mode === 'license-invalid' ? 'مجوز نامعتبر یا منقضی' : 'نسخه آزمایشی';
708 const machine = this._esc(LicenseService.installationId() || 'نامشخص');
709 const readiness = LicenseService.hasTrustedIssuer()
710 ? 'کلید عمومی صادرکننده فعال است'
711 : 'فعلاً کلید عمومی صدور مجوز در نسخه نصب‌شده تنظیم نشده است';
712 return `
713 <div class="card settings-card">
714 <div class="settings-card-header">
715 <div class="settings-card-icon">🔐</div>
716 <div>
717 <h3 class="settings-card-title">مجوز آفلاین نرم‌افزار</h3>
718 <p class="settings-card-desc">وضعیت: ${this._esc(mode)} — ${state.readOnly ? 'فقط مشاهده' : 'قابل ثبت'}</p>
719 </div>
720 </div>
721 <div style="font-size:12px;line-height:2">
722 <div>شناسه نصب: <code dir="ltr" style="overflow-wrap:anywhere">${machine}</code></div>
723 <div>${this._esc(readiness)}</div>
724 </div>
725 <button class="btn btn-secondary" onclick="window.SettingsView.openSignedLicenseModal()" ${LicenseService.hasTrustedIssuer() ? '' : 'disabled'}>
726 فعال‌سازی با مجوز امضاشده
727 </button>
728 <small style="display:block;margin-top:8px">برای فعال‌سازی، مجوز صادرشده مخصوص همین شناسه نصب لازم است؛ اطلاعات حسابداری در صورت انقضا حذف نمی‌شود.</small>
729 </div>
730 `;
731 }
732
733 openSignedLicenseModal() {
734 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
735 if (!LicenseService.hasTrustedIssuer()) {
736 Toast.error('کلید معتبر صادرکننده در این نسخه نصب نشده است'); return;
737 }
738 Modal.open({
739 title: 'فعال‌سازی مجوز آفلاین',
740 body: '<label for="signedLicenseToken">متن JSON مجوز امضاشده</label>' +
741 '<textarea id="signedLicenseToken" class="form-control" rows="8" spellcheck="false" dir="ltr"></textarea>' +
742 '<p style="font-size:12px">امضای دیجیتال و شناسه دستگاه پیش از هر تغییر اعتبارسنجی می‌شوند.</p>',
743 footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>' +
744 '<button class="btn" onclick="window.SettingsView.applySignedLicense()">اعتبارسنجی و فعال‌سازی</button>',
745 size: 'md'
746 });
747 }
748
749 async applySignedLicense() {
750 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
751 const token = document.getElementById('signedLicenseToken')?.value;
752 if (!token?.trim()) { Toast.error('متن مجوز خالی است'); return; }
753 try {
754 await LicenseService.activateSignedLicense(token.trim());
755 Modal.close();
756 const grid = document.querySelector('.settings-grid');
757 if (grid) grid.innerHTML = this._renderAllCards();
758 Toast.success('مجوز آفلاین معتبر با موفقیت فعال شد');
759 } catch (error) {
760 Toast.error(error.message);
761 }
762 }
763
764 _renderAllCards() {
765 return this._renderCompanyCard()
766 + this._renderInvoiceSettingsCard()
767 + this._renderExcelCard()
768 + this._renderShortcutsCard()
769 + this._renderBackupCard()
770 + (Auth.isAdmin() ? this._renderLicenseCard() : '')
771 + this._renderStatsCard()
772 + (Auth.isAdmin() ? this._renderHealthCard() : '')
773 + (Auth.isAdmin() ? this._renderAuditCard() : '')
774 + this._renderThemeCard()
775 + this._renderAboutCard();
776 }
777
778 // ============================================================
779 // فرم اطلاعات شرکت
780 // ============================================================
781 async openCompanySwitcher() {
782 const companies = await globalThis.FINORA.Company.list();
783 const body = companies.map(c => `<button class="btn" style="width:100%;margin:4px 0" onclick="window.SettingsView.selectCompany('${c.id}')">${this._esc(c.name || 'شرکت')}</button>`).join('');
784 Modal.open({ title: 'تغییر شرکت فعال', body: body || '<div class="empty-mini">شرکتی یافت نشد</div>', footer: '', size: 'sm' });
785 }
786
787 async selectCompany(id) {
788 await globalThis.FINORA.Company.select(id); Modal.close(); await this.reload(); Toast.success('شرکت فعال تغییر کرد');
789 }
790
791 async createCompany() {
792 const name = prompt('نام شرکت جدید را وارد کنید:'); if (!name?.trim()) return;
793 const company = await globalThis.FINORA.Company.create({ name: name.trim(), entityType: 'legal' });
794 await globalThis.FINORA.Company.select(company.id); await this.reload(); Toast.success('شرکت جدید ایجاد شد');
795 }
796
797 openCompanyModal() {
798 const c = cache.company;
799 const body = `
800 <div class="form-row">
801 <div class="form-group">
802 <label class="form-label">نوع شخص</label>
803 <select class="form-control" id="coEntityType">
804 <option value="legal" ${c.entityType === 'legal' ? 'selected' : ''}>حقوقی</option>
805 <option value="natural" ${c.entityType === 'natural' ? 'selected' : ''}>حقیقی</option>
806 </select>
807 </div>
808 <div class="form-group">
809 <label class="form-label">نام شرکت / فروشگاه <span class="req">*</span></label>
810 <input type="text" class="form-control" id="coName" value="${this._esc(c.name)}" />
811 </div>
812 </div>
813 <div class="form-row">
814 <div class="form-group">
815 <label class="form-label">شناسه ملی / کد ملی</label>
816 <input type="text" class="form-control" id="coNationalId" value="${this._esc(c.nationalId)}" />
817 </div>
818 <div class="form-group">
819 <label class="form-label">کد اقتصادی</label>
820 <input type="text" class="form-control" id="coEconomicCode" value="${this._esc(c.economicCode)}" />
821 </div>
822 </div>
823 <div class="form-row">
824 <div class="form-group">
825 <label class="form-label">شماره ثبت</label>
826 <input type="text" class="form-control" id="coRegNumber" value="${this._esc(c.regNumber)}" />
827 </div>
828 <div class="form-group">
829 <label class="form-label">کد پستی</label>
830 <input type="text" class="form-control" id="coPostalCode" value="${this._esc(c.postalCode)}" />
831 </div>
832 </div>
833 <div class="form-row">
834 <div class="form-group">
835 <label class="form-label">تلفن</label>
836 <input type="tel" class="form-control" id="coPhone" value="${this._esc(c.phone)}" />
837 </div>
838 <div class="form-group">
839 <label class="form-label">موبایل</label>
840 <input type="tel" class="form-control" id="coMobile" value="${this._esc(c.mobile)}" />
841 </div>
842 </div>
843 <div class="form-group">
844 <label class="form-label">نشانی</label>
845 <textarea class="form-control" id="coAddress" rows="2">${this._esc(c.address)}</textarea>
846 </div>
847 <div class="form-group">
848 <label class="form-label">پاورقی فاکتور</label>
849 <textarea class="form-control" id="coFooter" rows="2" placeholder="مثلاً: از خرید شما سپاسگزاریم">${this._esc(c.footer)}</textarea>
850 </div>
851 `;
852 const footer = `
853 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
854 <button class="btn" onclick="window.SettingsView.saveCompany()">💾 ذخیره</button>
855 `;
856 Modal.open({ title: 'اطلاعات شرکت', body, footer, size: 'md' });
857 }
858
859 async saveCompany() {
860 const data = {
861 name: document.getElementById('coName').value,
862 entityType: document.getElementById('coEntityType').value,
863 nationalId: document.getElementById('coNationalId').value,
864 economicCode: document.getElementById('coEconomicCode').value,
865 regNumber: document.getElementById('coRegNumber').value,
866 postalCode: document.getElementById('coPostalCode').value,
867 phone: document.getElementById('coPhone').value,
868 mobile: document.getElementById('coMobile').value,
869 address: document.getElementById('coAddress').value,
870 footer: document.getElementById('coFooter').value
871 };
872 if (!data.name.trim()) { Toast.warning('نام الزامی است'); return; }
873 try {
874 await SettingsController.saveCompanyInfo(data);
875 Toast.success('اطلاعات ذخیره شد');
876 Modal.close();
877 await this.reload();
878 const grid = document.querySelector('.settings-grid');
879 if (grid) grid.innerHTML = this._renderAllCards();
880 } catch (err) {
881 Toast.error('خطا: ' + err.message);
882 }
883 }
884
885 // ============================================================
886 // بکاپ JSON
887 // ============================================================
888 async downloadBackup() {
889 try {
890 Toast.info('در حال آماده‌سازی بکاپ...');
891 const result = await SettingsController.downloadBackup();
892 Toast.success(`بکاپ دانلود شد (${result.filename})`, 'موفق');
893 } catch (err) {
894 Toast.error('خطا در بکاپ: ' + err.message);
895 }
896 }
897
898 openRestoreModal() {
899 const body = `
900 <div class="backup-warning" style="margin-bottom:14px">
901 ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، فقط رکوردهای دارای شناسه یکسان بازنویسی می‌شوند و سایر داده‌ها حذف نمی‌شوند.
902 </div>
903
904 <div class="form-group">
905 <label class="form-label">فایل بکاپ رمزگذاری‌شده یا JSON</label>
906 <input type="file" class="form-control" id="restoreFile" accept=".json,.fbackup,application/json,application/octet-stream" />
907 </div>
908
909 <div class="form-group">
910 <label class="form-label">حالت بازیابی</label>
911 <select class="form-control" id="restoreMode">
912 <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
913 <option value="replace">🔄 بازنویسی شناسه‌های یکسان (Replace) — بدون حذف سایر رکوردها</option>
914 </select>
915 </div>
916 `;
917 const footer = `
918 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
919 <button class="btn" onclick="window.SettingsView.restoreBackup()">📤 بازیابی</button>
920 `;
921 Modal.open({ title: 'بازیابی از بکاپ', body, footer, size: 'md' });
922 }
923
924 async restoreBackup() {
925 const fileInput = document.getElementById('restoreFile');
926 const file = fileInput.files[0];
927 if (!file) { Toast.warning('فایل بکاپ رو انتخاب کنید'); return; }
928
929 const mode = document.getElementById('restoreMode').value;
930
931 try {
932 Toast.info('در حال بازیابی...');
933 const content = await SettingsController.readFileAsText(file);
934 const counts = await SettingsController.importBackup(content, { mode });
935 Modal.close();
936 Toast.success(`بازیابی انجام شد: ${counts.added} مورد اضافه، ${counts.skipped} مورد skip`);
937 setTimeout(() => location.reload(), 1500);
938 } catch (err) {
939 Toast.error('خطا: ' + err.message);
940 }
941 }
942
943 // ============================================================
944 // پاک کردن کامل
945 // ============================================================
946 openWipeModal() {
947 const body = `
948 <div style="text-align:center;padding:10px 0">
949 <div style="font-size:48px;margin-bottom:12px">⚠️</div>
950 <h3 style="color:var(--danger);margin-bottom:8px">پاک کردن کامل داده‌ها</h3>
951 <p style="color:var(--text-muted);font-size:13px;line-height:1.8;margin-bottom:16px">
952 این عمل همه‌ی کالاها، اشخاص، فاکتورها، چک‌ها، تراکنش‌ها و تنظیمات رو برای همیشه پاک می‌کند.
953 <br><strong>قابل بازگشت نیست!</strong>
954 </p>
955 <p style="font-size:12px;color:var(--danger);margin-bottom:16px">
956 لطفاً برای تأیید، کلمه‌ی <code style="background:var(--danger);color:#fff;padding:2px 8px;border-radius:4px">حذف</code> رو تایپ کنید
957 </p>
958 <input type="text" class="form-control" id="wipeConfirm" placeholder="حذف" style="text-align:center;max-width:200px;margin:0 auto" />
959 </div>
960 `;
961 const footer = `
962 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
963 <button class="btn btn-danger" onclick="window.SettingsView.confirmWipe()">🗑️ پاک کن</button>
964 `;
965 Modal.open({ title: 'تأیید پاک کردن', body, footer, size: 'sm' });
966 }
967
968 async confirmWipe() {
969 const confirmText = document.getElementById('wipeConfirm').value.trim();
970 if (confirmText !== 'حذف') {
971 Toast.warning('متن تأیید اشتباه است');
972 return;
973 }
974 try {
975 await SettingsController.wipeAll();
976 Toast.success('همه‌ی داده‌ها پاک شد');
977 setTimeout(() => location.reload(), 800);
978 } catch (err) {
979 Toast.error('خطا: ' + err.message);
980 }
981 }
982
983 // ============================================================
984 // Theme
985 // ============================================================
986 setTheme(theme) {
987 Theme.apply(theme);
988 const grid = document.querySelector('.settings-grid');
989 if (grid) grid.innerHTML = this._renderAllCards();
990 }
991
992 _esc(s) {
993 if (!s) return '';
994 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
995 }
996 }
997
998 export const SettingsView = new SettingsViewImpl();
999 window.SettingsView = SettingsView;