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

feat/a06-signed-offline-license-activation
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 993 lines 47.2 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 downloadProductsTemplate() {
371 ExcelController.downloadProductsTemplate();
372 Toast.success('قالب کالاها دانلود شد');
373 }
374
375 downloadContactsTemplate() {
376 ExcelController.downloadContactsTemplate();
377 Toast.success('قالب اشخاص دانلود شد');
378 }
379
380 // ============================================================
381 // کارت میانبرهای صفحه‌کلید
382 // ============================================================
383 _renderShortcutsCard() {
384 const s = KeyboardShortcuts.settings;
385
386 const toggle = (id, checked, label, hint) => `
387 <label style="display:flex;align-items:flex-start;gap:10px;padding:9px 0;cursor:pointer;border-bottom:1px solid var(--border)">
388 <input type="checkbox" id="${id}" ${checked ? 'checked' : ''} style="margin-top:3px;width:16px;height:16px;cursor:pointer" />
389 <div style="flex:1">
390 <div style="font-size:13px;font-weight:600">${label}</div>
391 <div style="font-size:11px;color:var(--text-muted);margin-top:2px;line-height:1.6">${hint}</div>
392 </div>
393 </label>
394 `;
395
396 return `
397 <div class="card settings-card" style="border-color:#ddd6fe;background:linear-gradient(135deg,#faf5ff,#f8fafc)">
398 <div class="settings-card-header">
399 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">⌨️</div>
400 <div>
401 <h3 class="settings-card-title">میانبرهای صفحه‌کلید</h3>
402 <p class="settings-card-desc">با این میانبرها کار با برنامه سریع‌تر می‌شود</p>
403 </div>
404 </div>
405
406 ${toggle('scEnabled', s.enabled, 'فعال بودن میانبرها', 'کلاً همه‌ی میانبرهای زیر رو روشن یا خاموش می‌کند')}
407 ${toggle('scEnterConfirms', s.enterConfirms, 'تأیید با Enter', 'وقتی توی فرم هستید، Enter مثل دکمه‌ی ذخیره عمل می‌کند. Ctrl+Enter هم توی همه‌ی فیلدها کار می‌کند')}
408 ${toggle('scEscapeCloses', s.escapeCloses, 'بستن با Escape', 'فشار دادن Escape، مودال باز را می‌بندد')}
409 ${toggle('scCtrlSaves', s.ctrlSaves, 'ذخیره با Ctrl+S', 'داخل مودال‌ها، Ctrl+S فرم را ذخیره می‌کند')}
410 ${toggle('scPlusMinusZeros', s.plusMinusZeros, 'ضریب سریع صفر (+ و -)', 'روی فیلدهای مبلغ، کلید + صفر اضافه و کلید − صفر کم می‌کند')}
411
412 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
413 <div class="form-group" style="margin-bottom:0">
414 <label class="form-label">تعداد صفرهای کلید +</label>
415 <input type="text" inputmode="numeric" class="form-control" id="scPlusZeros" value="${Formatters.toPersianDigits(s.plusZeros)}" />
416 </div>
417 <div class="form-group" style="margin-bottom:0">
418 <label class="form-label">تعداد صفرهای کلید −</label>
419 <input type="text" inputmode="numeric" class="form-control" id="scMinusZeros" value="${Formatters.toPersianDigits(s.minusZeros)}" />
420 </div>
421 </div>
422
423 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
424 <button class="btn" onclick="window.SettingsView.saveShortcuts()">💾 ذخیره تنظیمات</button>
425 <button class="btn btn-secondary" onclick="window.SettingsView.resetShortcuts()">↺ بازگشت به پیش‌فرض</button>
426 </div>
427 </div>
428 `;
429 }
430
431 saveShortcuts() {
432 try {
433 const plusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scPlusZeros').value)) || 0;
434 const minusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scMinusZeros').value)) || 0;
435
436 const settings = {
437 enabled: document.getElementById('scEnabled').checked,
438 enterConfirms: document.getElementById('scEnterConfirms').checked,
439 escapeCloses: document.getElementById('scEscapeCloses').checked,
440 ctrlSaves: document.getElementById('scCtrlSaves').checked,
441 plusMinusZeros: document.getElementById('scPlusMinusZeros').checked,
442 plusZeros: Math.max(0, Math.min(12, plusZeros)),
443 minusZeros: Math.max(0, Math.min(12, minusZeros))
444 };
445
446 KeyboardShortcuts.saveSettings(settings);
447 Toast.success('تنظیمات میانبرهای صفحه‌کلید ذخیره شد');
448 } catch (err) {
449 Toast.error('خطا: ' + err.message);
450 }
451 }
452
453 resetShortcuts() {
454 Modal.confirm({
455 title: 'بازگشت به پیش‌فرض',
456 message: 'آیا می‌خواهید همه‌ی تنظیمات میانبرهای صفحه‌کلید به حالت پیش‌فرض برگردد؟',
457 confirmText: 'بازگردان',
458 onConfirm: () => {
459 KeyboardShortcuts.resetSettings();
460 Toast.success('تنظیمات به حالت پیش‌فرض برگشت');
461 const grid = document.querySelector('.settings-grid');
462 if (grid) grid.innerHTML = this._renderAllCards();
463 }
464 });
465 }
466
467 // ============================================================
468 // کارت بکاپ
469 // ============================================================
470 _renderBackupCard() {
471 return `
472 <div class="card settings-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f8fafc)">
473 <div class="settings-card-header">
474 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
475 <div>
476 <h3 class="settings-card-title">پشتیبان‌گیری رمزگذاری‌شده</h3>
477 <p class="settings-card-desc">اطلاعات عملیاتی و حسابداری شرکت فعال؛ بازیابی بدون بازنویسی کاربران و تنظیمات سراسری</p>
478 </div>
479 </div>
480
481 <div class="backup-warning">
482 ⚠️ <strong>مهم:</strong> قبل از هر تغییر بزرگ در برنامه، حتماً بکاپ بگیرید.
483 </div>
484
485 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
486 <button class="btn" onclick="window.SettingsView.downloadBackup()">
487 📥 دانلود فایل بکاپ
488 </button>
489 <button class="btn btn-secondary" onclick="window.SettingsView.openRestoreModal()">
490 📤 بازیابی از بکاپ
491 </button>
492 </div>
493
494 <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)">
495 <button class="btn btn-danger btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.openWipeModal()">
496 🗑️ پاک کردن کامل داده‌ها
497 </button>
498 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">این عمل قابل بازگشت نیست، حتماً قبلش بکاپ بگیرید</small>
499 </div>
500 </div>
501 `;
502 }
503
504 // ============================================================
505 // ابزار تشخیص مغایرت‌ها (فقط خواندنی و درخواستی)
506 // ============================================================
507 _renderHealthCard() {
508 return `
509 <div class="card settings-card">
510 <div class="settings-card-header">
511 <div class="settings-card-icon">🔎</div>
512 <div>
513 <h3 class="settings-card-title">کنترل سلامت تسویه‌های مالی</h3>
514 <p class="settings-card-desc">بررسی مغایرت فاکتورها، رسیدها و تخصیص‌ها در شرکت فعال؛ بدون تغییر اطلاعات</p>
515 </div>
516 </div>
517 <button class="btn btn-secondary" onclick="window.SettingsView.runFinancialDiagnostics()">
518 بررسی مغایرت‌ها
519 </button>
520 <small style="display:block;margin-top:8px;color:var(--text-muted)">بررسی فقط هنگام درخواست اجرا می‌شود و هیچ سندی را خودکار اصلاح نمی‌کند.</small>
521 </div>
522 `;
523 }
524
525 async runFinancialDiagnostics() {
526 if (!Auth.isAdmin()) { Toast.error('این بررسی فقط برای مدیر مجاز است'); return; }
527 try {
528 Toast.info('در حال بررسی تسویه‌ها...');
529 const report = await inspectSettlementConsistency({ maxIssues: 50 });
530 const names = {
531 ORPHAN_SETTLEMENT: 'تسویه بدون فاکتور معتبر',
532 INVALID_SETTLEMENT_AMOUNT: 'مبلغ نامعتبر تسویه',
533 MISSING_TREASURY_TRANSACTION: 'رسید یا تراکنش خزانه ناموجود',
534 SETTLEMENT_AMOUNT_OVERFLOW: 'سرریز مبلغ تسویه',
535 SETTLEMENT_TOTAL_MISMATCH: 'عدم تطابق مبلغ تسویه با فاکتور',
536 INVALID_INVOICE_AMOUNT: 'مبلغ نامعتبر فاکتور',
537 INVOICE_OVERPAID: 'تسویه بیش از مبلغ فاکتور',
538 INVOICE_REMAINING_MISMATCH: 'مانده فاکتور نادرست',
539 INVOICE_STATUS_MISMATCH: 'وضعیت تسویه ناهماهنگ'
540 };
541 const rows = report.issues.map(issue => `
542 <div style="padding:9px 0;border-bottom:1px solid var(--border)">
543 <strong>${this._esc(names[issue.code] || issue.code)}</strong>
544 <div style="font-size:12px;color:var(--text-muted)">شناسه سند: ${this._esc(issue.documentId)}</div>
545 </div>`).join('');
546 const body = `
547 <p>فاکتورهای کنترل‌شده: <strong>${Formatters.number(report.checkedInvoices)}</strong>
548 | تخصیص‌ها: <strong>${Formatters.number(report.checkedSettlements)}</strong>
549 | مغایرت‌ها: <strong>${Formatters.number(report.issueCount)}</strong></p>
550 <p style="color:var(--text-muted);font-size:12px">این گزارش تشخیصی است؛ پیش از هر اصلاح، سندهای مبنا را بررسی کنید.</p>
551 ${rows || '<p>در کنترل‌های فعلی مغایرتی یافت نشد.</p>'}
552 ${report.truncated ? '<p>فقط ۵۰ مغایرت نخست نمایش داده می‌شود.</p>' : ''}
553 `;
554 Modal.open({ title: 'گزارش کنترل سلامت تسویه‌ها', body,
555 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>', size: 'lg' });
556 } catch (err) {
557 Toast.error('بررسی سلامت تسویه‌ها ناموفق بود: ' + err.message);
558 }
559 }
560
561 // ============================================================
562 // ردپای حسابرسی فقط خواندنی برای مدیر
563 // ============================================================
564 _renderAuditCard() {
565 return `
566 <div class="card settings-card">
567 <div class="settings-card-header">
568 <div class="settings-card-icon">📋</div>
569 <div>
570 <h3 class="settings-card-title">ردپای حسابرسی</h3>
571 <p class="settings-card-desc">نمایش رویدادهای مالی ثبت‌شده از زمان فعال‌شدن ممیزی؛ سوابق قدیمی به‌طور خودکار ممیزی نمی‌شوند</p>
572 </div>
573 </div>
574 <button class="btn btn-secondary" onclick="window.SettingsView.openAuditTrail()">
575 مشاهده رویدادهای شرکت فعال
576 </button>
577 </div>
578 `;
579 }
580
581 async openAuditTrail() {
582 if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; }
583 try {
584 const events = await AuditService.list({ limit: 100 });
585 const labels = {
586 journal_posted: 'ثبت سند مالی',
587 journal_reversed: 'برگشت سند مالی',
588 commercial_journal_posted: 'ثبت رویداد تجاری',
589 period_opened: 'ایجاد دوره مالی',
590 period_closed: 'بستن دوره مالی',
591 draft_created: 'ساخت پیش‌نویس',
592 draft_updated: 'ویرایش پیش‌نویس',
593 draft_posted: 'ثبت قطعی پیش‌نویس',
594 draft_discarded: 'حذف پیش‌نویس',
595 backup_restored: 'بازیابی فایل پشتیبان'
596 };
597 const list = events.map(event => `
598 <div style="padding:10px 0;border-bottom:1px solid var(--border)">
599 <strong>${this._esc(labels[event.eventType] || event.eventType)}</strong>
600 <div style="color:var(--text-muted);font-size:12px">
601 سند: ${this._esc(event.sourceId)} | کاربر: ${this._esc(event.actorId)}
602 </div>
603 <div style="color:var(--text-muted);font-size:11px">
604 ${this._esc(event.businessDate || '')} — ${this._esc(event.occurredAtUtc)}
605 </div>
606 </div>
607 `).join('');
608 Modal.open({ title: 'ردپای حسابرسی شرکت فعال',
609 body: `<p style="font-size:12px;color:var(--text-muted)">تا ۱۰۰ رویداد اخیر؛ فقط از زمان فعال‌سازی ممیزی. اطلاعاتی که پیش از آن ثبت شده‌اند، سابقه ممیزی ساختگی ندارند.</p>${list || '<p>رویدادی یافت نشد.</p>'}`,
610 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
611 size: 'lg' });
612 } catch (err) {
613 Toast.error('نمایش ردپای حسابرسی ناموفق بود: ' + err.message);
614 }
615 }
616
617 // ============================================================
618 // کارت آمار
619 // ============================================================
620 _renderStatsCard() {
621 const s = cache.stats;
622 const items = [
623 { label: 'کالا و خدمات', value: s.products || 0, icon: '📦' },
624 { label: 'اشخاص', value: s.contacts || 0, icon: '👥' },
625 { label: 'فاکتورها', value: s.invoices || 0, icon: '🧾' },
626 { label: 'چک‌ها', value: s.cheques || 0, icon: '💳' },
627 { label: 'حساب‌ها', value: s.accounts || 0, icon: '🏦' },
628 { label: 'تراکنش‌ها', value: s.transactions || 0, icon: '💸' }
629 ];
630 return `
631 <div class="card settings-card">
632 <div class="settings-card-header">
633 <div class="settings-card-icon" style="background:linear-gradient(135deg,#0ea5e9,#0369a1)">📊</div>
634 <div>
635 <h3 class="settings-card-title">آمار داده‌ها</h3>
636 <p class="settings-card-desc">خلاصه‌ی داده‌های ذخیره‌شده در سیستم</p>
637 </div>
638 </div>
639 <div class="stats-grid">
640 ${items.map(i => `
641 <div class="stat-mini">
642 <div style="font-size:18px;margin-bottom:4px">${i.icon}</div>
643 <div style="font-size:18px;font-weight:800;color:var(--primary)">${Formatters.number(i.value)}</div>
644 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${i.label}</div>
645 </div>
646 `).join('')}
647 </div>
648 </div>
649 `;
650 }
651
652 // ============================================================
653 // کارت تم
654 // ============================================================
655 _renderThemeCard() {
656 const current = Theme.current();
657 return `
658 <div class="card settings-card">
659 <div class="settings-card-header">
660 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">🎨</div>
661 <div>
662 <h3 class="settings-card-title">ظاهر و تم</h3>
663 <p class="settings-card-desc">حالت نمایش برنامه</p>
664 </div>
665 </div>
666 <div style="display:flex;gap:10px;margin-top:8px">
667 <button class="btn ${current === 'light' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('light')">☀️ روشن</button>
668 <button class="btn ${current === 'dark' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('dark')">🌙 تاریک</button>
669 </div>
670 </div>
671 `;
672 }
673
674 // ============================================================
675 // کارت درباره
676 // ============================================================
677 _renderAboutCard() {
678 return `
679 <div class="card settings-card">
680 <div class="settings-card-header">
681 <div class="settings-card-icon">ℹ️</div>
682 <div>
683 <h3 class="settings-card-title">درباره فینورا پرو</h3>
684 <p class="settings-card-desc">نسخه ۲.۰.۳</p>
685 </div>
686 </div>
687 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
688 <div><strong>طراح و توسعه‌دهنده:</strong> داوود مهربان</div>
689 <div><strong>تماس:</strong> <span dir="ltr">0912-437-6991</span></div>
690 <div style="margin-top:8px;padding-top:10px;border-top:1px dashed var(--border)">
691 <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>
692 </div>
693 </div>
694 </div>
695 `;
696 }
697
698 _renderLicenseCard() {
699 const state = LicenseService.status();
700 const mode = state.mode === 'licensed' ? 'مجوز امضاشده معتبر' :
701 state.mode === 'license-invalid' ? 'مجوز نامعتبر یا منقضی' : 'نسخه آزمایشی';
702 const machine = this._esc(LicenseService.installationId() || 'نامشخص');
703 const readiness = LicenseService.hasTrustedIssuer()
704 ? 'کلید عمومی صادرکننده فعال است'
705 : 'فعلاً کلید عمومی صدور مجوز در نسخه نصب‌شده تنظیم نشده است';
706 return `
707 <div class="card settings-card">
708 <div class="settings-card-header">
709 <div class="settings-card-icon">🔐</div>
710 <div>
711 <h3 class="settings-card-title">مجوز آفلاین نرم‌افزار</h3>
712 <p class="settings-card-desc">وضعیت: ${this._esc(mode)} — ${state.readOnly ? 'فقط مشاهده' : 'قابل ثبت'}</p>
713 </div>
714 </div>
715 <div style="font-size:12px;line-height:2">
716 <div>شناسه نصب: <code dir="ltr" style="overflow-wrap:anywhere">${machine}</code></div>
717 <div>${this._esc(readiness)}</div>
718 </div>
719 <button class="btn btn-secondary" onclick="window.SettingsView.openSignedLicenseModal()" ${LicenseService.hasTrustedIssuer() ? '' : 'disabled'}>
720 فعال‌سازی با مجوز امضاشده
721 </button>
722 <small style="display:block;margin-top:8px">برای فعال‌سازی، مجوز صادرشده مخصوص همین شناسه نصب لازم است؛ اطلاعات حسابداری در صورت انقضا حذف نمی‌شود.</small>
723 </div>
724 `;
725 }
726
727 openSignedLicenseModal() {
728 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
729 if (!LicenseService.hasTrustedIssuer()) {
730 Toast.error('کلید معتبر صادرکننده در این نسخه نصب نشده است'); return;
731 }
732 Modal.open({
733 title: 'فعال‌سازی مجوز آفلاین',
734 body: '<label for="signedLicenseToken">متن JSON مجوز امضاشده</label>' +
735 '<textarea id="signedLicenseToken" class="form-control" rows="8" spellcheck="false" dir="ltr"></textarea>' +
736 '<p style="font-size:12px">امضای دیجیتال و شناسه دستگاه پیش از هر تغییر اعتبارسنجی می‌شوند.</p>',
737 footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>' +
738 '<button class="btn" onclick="window.SettingsView.applySignedLicense()">اعتبارسنجی و فعال‌سازی</button>',
739 size: 'md'
740 });
741 }
742
743 async applySignedLicense() {
744 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
745 const token = document.getElementById('signedLicenseToken')?.value;
746 if (!token?.trim()) { Toast.error('متن مجوز خالی است'); return; }
747 try {
748 await LicenseService.activateSignedLicense(token.trim());
749 Modal.close();
750 const grid = document.querySelector('.settings-grid');
751 if (grid) grid.innerHTML = this._renderAllCards();
752 Toast.success('مجوز آفلاین معتبر با موفقیت فعال شد');
753 } catch (error) {
754 Toast.error(error.message);
755 }
756 }
757
758 _renderAllCards() {
759 return this._renderCompanyCard()
760 + this._renderInvoiceSettingsCard()
761 + this._renderExcelCard()
762 + this._renderShortcutsCard()
763 + this._renderBackupCard()
764 + (Auth.isAdmin() ? this._renderLicenseCard() : '')
765 + this._renderStatsCard()
766 + (Auth.isAdmin() ? this._renderHealthCard() : '')
767 + (Auth.isAdmin() ? this._renderAuditCard() : '')
768 + this._renderThemeCard()
769 + this._renderAboutCard();
770 }
771
772 // ============================================================
773 // فرم اطلاعات شرکت
774 // ============================================================
775 async openCompanySwitcher() {
776 const companies = await globalThis.FINORA.Company.list();
777 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('');
778 Modal.open({ title: 'تغییر شرکت فعال', body: body || '<div class="empty-mini">شرکتی یافت نشد</div>', footer: '', size: 'sm' });
779 }
780
781 async selectCompany(id) {
782 await globalThis.FINORA.Company.select(id); Modal.close(); await this.reload(); Toast.success('شرکت فعال تغییر کرد');
783 }
784
785 async createCompany() {
786 const name = prompt('نام شرکت جدید را وارد کنید:'); if (!name?.trim()) return;
787 const company = await globalThis.FINORA.Company.create({ name: name.trim(), entityType: 'legal' });
788 await globalThis.FINORA.Company.select(company.id); await this.reload(); Toast.success('شرکت جدید ایجاد شد');
789 }
790
791 openCompanyModal() {
792 const c = cache.company;
793 const body = `
794 <div class="form-row">
795 <div class="form-group">
796 <label class="form-label">نوع شخص</label>
797 <select class="form-control" id="coEntityType">
798 <option value="legal" ${c.entityType === 'legal' ? 'selected' : ''}>حقوقی</option>
799 <option value="natural" ${c.entityType === 'natural' ? 'selected' : ''}>حقیقی</option>
800 </select>
801 </div>
802 <div class="form-group">
803 <label class="form-label">نام شرکت / فروشگاه <span class="req">*</span></label>
804 <input type="text" class="form-control" id="coName" value="${this._esc(c.name)}" />
805 </div>
806 </div>
807 <div class="form-row">
808 <div class="form-group">
809 <label class="form-label">شناسه ملی / کد ملی</label>
810 <input type="text" class="form-control" id="coNationalId" value="${this._esc(c.nationalId)}" />
811 </div>
812 <div class="form-group">
813 <label class="form-label">کد اقتصادی</label>
814 <input type="text" class="form-control" id="coEconomicCode" value="${this._esc(c.economicCode)}" />
815 </div>
816 </div>
817 <div class="form-row">
818 <div class="form-group">
819 <label class="form-label">شماره ثبت</label>
820 <input type="text" class="form-control" id="coRegNumber" value="${this._esc(c.regNumber)}" />
821 </div>
822 <div class="form-group">
823 <label class="form-label">کد پستی</label>
824 <input type="text" class="form-control" id="coPostalCode" value="${this._esc(c.postalCode)}" />
825 </div>
826 </div>
827 <div class="form-row">
828 <div class="form-group">
829 <label class="form-label">تلفن</label>
830 <input type="tel" class="form-control" id="coPhone" value="${this._esc(c.phone)}" />
831 </div>
832 <div class="form-group">
833 <label class="form-label">موبایل</label>
834 <input type="tel" class="form-control" id="coMobile" value="${this._esc(c.mobile)}" />
835 </div>
836 </div>
837 <div class="form-group">
838 <label class="form-label">نشانی</label>
839 <textarea class="form-control" id="coAddress" rows="2">${this._esc(c.address)}</textarea>
840 </div>
841 <div class="form-group">
842 <label class="form-label">پاورقی فاکتور</label>
843 <textarea class="form-control" id="coFooter" rows="2" placeholder="مثلاً: از خرید شما سپاسگزاریم">${this._esc(c.footer)}</textarea>
844 </div>
845 `;
846 const footer = `
847 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
848 <button class="btn" onclick="window.SettingsView.saveCompany()">💾 ذخیره</button>
849 `;
850 Modal.open({ title: 'اطلاعات شرکت', body, footer, size: 'md' });
851 }
852
853 async saveCompany() {
854 const data = {
855 name: document.getElementById('coName').value,
856 entityType: document.getElementById('coEntityType').value,
857 nationalId: document.getElementById('coNationalId').value,
858 economicCode: document.getElementById('coEconomicCode').value,
859 regNumber: document.getElementById('coRegNumber').value,
860 postalCode: document.getElementById('coPostalCode').value,
861 phone: document.getElementById('coPhone').value,
862 mobile: document.getElementById('coMobile').value,
863 address: document.getElementById('coAddress').value,
864 footer: document.getElementById('coFooter').value
865 };
866 if (!data.name.trim()) { Toast.warning('نام الزامی است'); return; }
867 try {
868 await SettingsController.saveCompanyInfo(data);
869 Toast.success('اطلاعات ذخیره شد');
870 Modal.close();
871 await this.reload();
872 const grid = document.querySelector('.settings-grid');
873 if (grid) grid.innerHTML = this._renderAllCards();
874 } catch (err) {
875 Toast.error('خطا: ' + err.message);
876 }
877 }
878
879 // ============================================================
880 // بکاپ JSON
881 // ============================================================
882 async downloadBackup() {
883 try {
884 Toast.info('در حال آماده‌سازی بکاپ...');
885 const result = await SettingsController.downloadBackup();
886 Toast.success(`بکاپ دانلود شد (${result.filename})`, 'موفق');
887 } catch (err) {
888 Toast.error('خطا در بکاپ: ' + err.message);
889 }
890 }
891
892 openRestoreModal() {
893 const body = `
894 <div class="backup-warning" style="margin-bottom:14px">
895 ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، فقط رکوردهای دارای شناسه یکسان بازنویسی می‌شوند و سایر داده‌ها حذف نمی‌شوند.
896 </div>
897
898 <div class="form-group">
899 <label class="form-label">فایل بکاپ رمزگذاری‌شده یا JSON</label>
900 <input type="file" class="form-control" id="restoreFile" accept=".json,.fbackup,application/json,application/octet-stream" />
901 </div>
902
903 <div class="form-group">
904 <label class="form-label">حالت بازیابی</label>
905 <select class="form-control" id="restoreMode">
906 <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
907 <option value="replace">🔄 بازنویسی شناسه‌های یکسان (Replace) — بدون حذف سایر رکوردها</option>
908 </select>
909 </div>
910 `;
911 const footer = `
912 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
913 <button class="btn" onclick="window.SettingsView.restoreBackup()">📤 بازیابی</button>
914 `;
915 Modal.open({ title: 'بازیابی از بکاپ', body, footer, size: 'md' });
916 }
917
918 async restoreBackup() {
919 const fileInput = document.getElementById('restoreFile');
920 const file = fileInput.files[0];
921 if (!file) { Toast.warning('فایل بکاپ رو انتخاب کنید'); return; }
922
923 const mode = document.getElementById('restoreMode').value;
924
925 try {
926 Toast.info('در حال بازیابی...');
927 const content = await SettingsController.readFileAsText(file);
928 const counts = await SettingsController.importBackup(content, { mode });
929 Modal.close();
930 Toast.success(`بازیابی انجام شد: ${counts.added} مورد اضافه، ${counts.skipped} مورد skip`);
931 setTimeout(() => location.reload(), 1500);
932 } catch (err) {
933 Toast.error('خطا: ' + err.message);
934 }
935 }
936
937 // ============================================================
938 // پاک کردن کامل
939 // ============================================================
940 openWipeModal() {
941 const body = `
942 <div style="text-align:center;padding:10px 0">
943 <div style="font-size:48px;margin-bottom:12px">⚠️</div>
944 <h3 style="color:var(--danger);margin-bottom:8px">پاک کردن کامل داده‌ها</h3>
945 <p style="color:var(--text-muted);font-size:13px;line-height:1.8;margin-bottom:16px">
946 این عمل همه‌ی کالاها، اشخاص، فاکتورها، چک‌ها، تراکنش‌ها و تنظیمات رو برای همیشه پاک می‌کند.
947 <br><strong>قابل بازگشت نیست!</strong>
948 </p>
949 <p style="font-size:12px;color:var(--danger);margin-bottom:16px">
950 لطفاً برای تأیید، کلمه‌ی <code style="background:var(--danger);color:#fff;padding:2px 8px;border-radius:4px">حذف</code> رو تایپ کنید
951 </p>
952 <input type="text" class="form-control" id="wipeConfirm" placeholder="حذف" style="text-align:center;max-width:200px;margin:0 auto" />
953 </div>
954 `;
955 const footer = `
956 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
957 <button class="btn btn-danger" onclick="window.SettingsView.confirmWipe()">🗑️ پاک کن</button>
958 `;
959 Modal.open({ title: 'تأیید پاک کردن', body, footer, size: 'sm' });
960 }
961
962 async confirmWipe() {
963 const confirmText = document.getElementById('wipeConfirm').value.trim();
964 if (confirmText !== 'حذف') {
965 Toast.warning('متن تأیید اشتباه است');
966 return;
967 }
968 try {
969 await SettingsController.wipeAll();
970 Toast.success('همه‌ی داده‌ها پاک شد');
971 setTimeout(() => location.reload(), 800);
972 } catch (err) {
973 Toast.error('خطا: ' + err.message);
974 }
975 }
976
977 // ============================================================
978 // Theme
979 // ============================================================
980 setTheme(theme) {
981 Theme.apply(theme);
982 const grid = document.querySelector('.settings-grid');
983 if (grid) grid.innerHTML = this._renderAllCards();
984 }
985
986 _esc(s) {
987 if (!s) return '';
988 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
989 }
990 }
991
992 export const SettingsView = new SettingsViewImpl();
993 window.SettingsView = SettingsView;