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

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