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

fix/a02-atomic-excel-master-merge-20261031
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
js 1,130 lines 55.1 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 import { probeHolooBackupZip } from '../core/HolooBackupProbe.mjs';
18
19 let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
20 // Excel workbooks can contain private customer data. Never retain previews on window.
21 let pendingExcelImport = null;
22 let excelImportBusy = false;
23
24 class SettingsViewImpl {
25 async render() {
26 await this.reload();
27 return `
28 <div class="page-title">
29 <h2>تنظیمات</h2>
30 <p>مدیریت اطلاعات شرکت، پشتیبان‌گیری، Excel و تنظیمات سیستم</p>
31 </div>
32
33 <div class="settings-grid">
34 ${this._renderCompanyCard()}
35 ${this._renderInvoiceSettingsCard()}
36 ${this._renderExcelCard()}
37 ${this._renderShortcutsCard()}
38 ${this._renderBackupCard()}
39 ${Auth.isAdmin() ? this._renderHolooBackupCard() : ''}
40 ${Auth.isAdmin() ? this._renderLicenseCard() : ''}
41 ${this._renderStatsCard()}
42 ${Auth.isAdmin() ? this._renderHealthCard() : ''}
43 ${Auth.isAdmin() ? this._renderAuditCard() : ''}
44 ${this._renderThemeCard()}
45 ${this._renderAboutCard()}
46 </div>
47 `;
48 }
49
50 onMount() {
51 window.SettingsView = this;
52 }
53
54 async reload() {
55 const results = await Promise.allSettled([
56 SettingsController.getCompanyInfo(),
57 SettingsController.getInvoiceSettings(),
58 this._collectStats()
59 ]);
60 const defaults = [{}, { numberingMode: 'auto', nextNumber: 1 }, {}];
61 const values = results.map((result, index) => {
62 if (result.status === 'fulfilled') return result.value;
63 console.error('Settings load failed:', index, result.reason);
64 Toast.error('بخشی از تنظیمات بارگذاری نشد: ' + (result.reason?.message || 'خطای نامشخص'));
65 return defaults[index];
66 });
67 [cache.company, cache.invoiceSettings, cache.stats] = values;
68 }
69
70 async _collectStats() {
71 const user = Auth.current();
72 if (!user) return {};
73 const stores = ['products', 'contacts', 'invoices', 'cheques', 'treasury'];
74 const stats = {};
75 for (const s of stores) {
76 try {
77 const list = await StorageService.getByOwner(s, user.id);
78 if (s === 'treasury') {
79 stats.accounts = list.filter(x => x.recordType === 'account').length;
80 stats.transactions = list.filter(x => x.recordType === 'transaction').length;
81 } else {
82 stats[s] = list.length;
83 }
84 } catch (e) {
85 stats[s] = 0;
86 }
87 }
88 return stats;
89 }
90
91 // ============================================================
92 // کارت اطلاعات شرکت
93 // ============================================================
94 _renderCompanyCard() {
95 const c = cache.company;
96 return `
97 <div class="card settings-card">
98 <div class="settings-card-header">
99 <div class="settings-card-icon">🏢</div>
100 <div>
101 <h3 class="settings-card-title">اطلاعات شرکت / فروشگاه</h3>
102 <p class="settings-card-desc">این اطلاعات در سربرگ فاکتورهای چاپی نمایش داده می‌شود</p>
103 </div>
104 </div>
105 ${c.name ? `
106 <div class="company-preview">
107 <div style="font-weight:700;font-size:14px">${this._esc(c.name)}</div>
108 ${c.nationalId ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:3px">شناسه ملی: ${Formatters.toPersianDigits(c.nationalId)}</div>` : ''}
109 ${c.address ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">${this._esc(c.address)}</div>` : ''}
110 ${c.phone ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">تلفن: ${Formatters.phone(c.phone)}</div>` : ''}
111 </div>
112 ` : `
113 <div class="empty-mini">هنوز اطلاعاتی وارد نشده</div>
114 `}
115 <div style="display:flex;gap:8px;flex-wrap:wrap">
116 <button class="btn" onclick="window.SettingsView.openCompanyModal()">${c.name ? '✏️ ویرایش اطلاعات' : '➕ وارد کردن اطلاعات'}</button>
117 <button class="btn" onclick="window.SettingsView.openCompanySwitcher()">🔄 تغییر شرکت</button>
118 ${Auth.isAdmin() ? '<button class="btn" onclick="window.SettingsView.createCompany()">➕ شرکت جدید</button>' : ''}
119 </div>
120 </div>
121 `;
122 }
123
124 _renderInvoiceSettingsCard() {
125 const s = cache.invoiceSettings || { numberingMode: 'auto', nextNumber: 1 };
126 return `
127 <div class="card settings-card">
128 <div class="settings-card-header">
129 <div class="settings-card-icon">🧾</div>
130 <div>
131 <h3 class="settings-card-title">تنظیمات فاکتور</h3>
132 <p class="settings-card-desc">نحوه شماره‌گذاری فاکتورهای جدید</p>
133 </div>
134 </div>
135 <div class="form-group">
136 <label class="form-label" for="invoiceNumberingMode">نحوه شماره‌گذاری</label>
137 <select class="form-control" id="invoiceNumberingMode">
138 <option value="auto" ${s.numberingMode === 'auto' ? 'selected' : ''}>خودکار</option>
139 <option value="manual" ${s.numberingMode === 'manual' ? 'selected' : ''}>دستی</option>
140 </select>
141 </div>
142 <div class="form-group">
143 <label class="form-label" for="invoiceNextNumber">شماره بعدی فاکتور</label>
144 <input class="form-control" id="invoiceNextNumber" type="number" min="1" value="${Number(s.nextNumber) || 1}" />
145 </div>
146 <button class="btn" onclick="window.SettingsView.saveInvoiceSettings()">💾 ذخیره تنظیمات فاکتور</button>
147 </div>
148 `;
149 }
150
151 async saveInvoiceSettings() {
152 const numberingMode = document.getElementById('invoiceNumberingMode').value;
153 const nextNumber = Number(document.getElementById('invoiceNextNumber').value);
154 if (!Number.isInteger(nextNumber) || nextNumber < 1) {
155 Toast.warning('شماره بعدی باید عدد صحیح بزرگ‌تر از صفر باشد');
156 return;
157 }
158 try {
159 cache.invoiceSettings = await SettingsController.saveInvoiceSettings({ numberingMode, nextNumber });
160 Toast.success('تنظیمات فاکتور ذخیره شد');
161 } catch (err) {
162 console.error('Invoice settings save failed:', err);
163 Toast.error('خطا در ذخیره تنظیمات فاکتور: ' + err.message);
164 }
165 }
166
167 // ============================================================
168 // کارت Excel (جدید)
169 // ============================================================
170 _renderExcelCard() {
171 const s = cache.stats;
172 return `
173 <div class="card settings-card" style="border-color:#bbf7d0;background:linear-gradient(135deg,#f0fdf4,#f8fafc)">
174 <div class="settings-card-header">
175 <div class="settings-card-icon" style="background:linear-gradient(135deg,#16a34a,#15803d)">📊</div>
176 <div>
177 <h3 class="settings-card-title">Excel — خروجی و ورودی</h3>
178 <p class="settings-card-desc">داده‌ها را به Excel ببر یا از Excel بیار</p>
179 </div>
180 </div>
181
182 <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">
183 <strong>💡 نکته:</strong> از این بخش می‌تونی کل داده‌ها رو در یه فایل Excel بگیری، یا از یه فایل Excel (که قبلاً آماده کردی) کالا و اشخاص اضافه کنی.
184 </div>
185
186 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px">
187 <button class="btn" style="background:linear-gradient(135deg,#16a34a,#15803d)" onclick="window.SettingsView.exportAllExcel()">
188 📥 خروجی کامل (Excel)
189 </button>
190 <button class="btn btn-secondary" onclick="window.SettingsView.openExportSectionModal()">
191 🎯 خروجی انتخابی
192 </button>
193 </div>
194
195 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
196 <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📤 ورود از Excel</div>
197 <div style="display:flex;gap:10px;flex-wrap:wrap">
198 <button class="btn btn-secondary" onclick="window.SettingsView.importProductsExcel()">
199 📦 ورود کالاها
200 </button>
201 <button class="btn btn-secondary" onclick="window.SettingsView.importContactsExcel()">
202 👥 ورود اشخاص
203 </button>
204 </div>
205 </div>
206
207 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
208 <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📄 قالب‌های نمونه</div>
209 <div style="display:flex;gap:10px;flex-wrap:wrap">
210 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadProductsTemplate()">
211 📋 قالب کالاها
212 </button>
213 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadContactsTemplate()">
214 📋 قالب اشخاص
215 </button>
216 </div>
217 </div>
218 </div>
219 `;
220 }
221
222 async exportAllExcel() {
223 try {
224 Toast.info('در حال آماده‌سازی فایل Excel...');
225 const result = await ExcelController.exportAll();
226 Toast.success(`فایل Excel با ${Formatters.toPersianDigits(result.sheets)} شیت دانلود شد`);
227 } catch (err) {
228 console.error(err);
229 Toast.error('خطا در خروجی: ' + err.message);
230 }
231 }
232
233 openExportSectionModal() {
234 const body = `
235 <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px">کدوم بخش رو می‌خوای به Excel ببری؟</p>
236 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
237 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('products')">
238 <div style="font-size:22px">📦</div>
239 <div style="font-size:12.5px">کالاها</div>
240 </button>
241 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('contacts')">
242 <div style="font-size:22px">👥</div>
243 <div style="font-size:12.5px">اشخاص</div>
244 </button>
245 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('invoices')">
246 <div style="font-size:22px">🧾</div>
247 <div style="font-size:12.5px">فاکتورها</div>
248 </button>
249 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('cheques')">
250 <div style="font-size:22px">💳</div>
251 <div style="font-size:12.5px">چک‌ها</div>
252 </button>
253 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('expenses')">
254 <div style="font-size:22px">💰</div>
255 <div style="font-size:12.5px">هزینه و درآمد</div>
256 </button>
257 </div>
258 `;
259 const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>`;
260 Modal.open({ title: '🎯 خروجی انتخابی به Excel', body, footer, size: 'md' });
261 }
262
263 async _exportSection(section) {
264 try {
265 const result = await ExcelController.exportSection(section);
266 Toast.success(`فایل دانلود شد (${Formatters.number(result.count)} مورد)`);
267 Modal.close();
268 } catch (err) {
269 Toast.error('خطا: ' + err.message);
270 }
271 }
272
273 // ============================================================
274 // ورودی از Excel
275 // ============================================================
276 importProductsExcel() {
277 const input = document.createElement('input');
278 input.type = 'file';
279 input.accept = '.xlsx,.xls';
280 input.onchange = async (e) => {
281 const file = e.target.files[0];
282 if (!file) return;
283 await this._handleImportFile(file, 'products');
284 };
285 input.click();
286 }
287
288 importContactsExcel() {
289 const input = document.createElement('input');
290 input.type = 'file';
291 input.accept = '.xlsx,.xls';
292 input.onchange = async (e) => {
293 const file = e.target.files[0];
294 if (!file) return;
295 await this._handleImportFile(file, 'contacts');
296 };
297 input.click();
298 }
299
300 async _handleImportFile(file, kind) {
301 try {
302 Toast.info('در حال خواندن فایل...');
303 const preview = await ExcelController.previewFile(file);
304
305 const kindLabel = kind === 'products' ? 'کالاها' : 'اشخاص';
306 const sheetsHtml = preview.sheets.map(s => `
307 <div style="padding:8px 12px;background:var(--bg);border-radius:8px;margin-bottom:6px;font-size:12.5px">
308 <strong>${this._esc(s.name)}</strong>
309 <span style="color:var(--text-muted);margin-right:6px">(${Formatters.number(s.count)} سطر)</span>
310 </div>
311 `).join('');
312
313 const body = `
314 <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px">
315 فایل <strong>${this._esc(file.name)}</strong> خونده شد. شیت‌های موجود:
316 </p>
317 ${sheetsHtml}
318 <div class="form-group" style="margin-top:14px">
319 <label class="form-label">حالت ورود</label>
320 <select class="form-control" id="importMode">
321 <option value="merge">🔀 ادغام (Merge) — فقط موارد جدید اضافه می‌شن</option>
322
323 </select>
324 <p style="font-size:12px;color:var(--text-muted);margin-top:8px">حذف و جایگزینی گروهی برای محافظت از سوابق مالی غیرفعال است؛ فقط موارد جدید ادغام می‌شوند.</p>
325 </div>
326 `;
327 const footer = `
328 <button type="button" class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
329 <button type="button" class="btn btn-success" data-excel-import-submit>✅ شروع ایمپورت</button>
330 `;
331 const pending = { kind, rawData: preview.raw, card: null };
332 pendingExcelImport = pending;
333 const modal = Modal.open({
334 title: `📤 ورود ${kindLabel} از Excel`, body, footer, size: 'md',
335 onClose: () => {
336 // Cancel/close releases the private workbook immediately.
337 if (pendingExcelImport === pending) pendingExcelImport = null;
338 }
339 });
340 pending.card = modal.card;
341 modal.card.querySelector('[data-excel-import-submit]').addEventListener('click', () => this._confirmImport(kind));
342 } catch (err) {
343 console.error(err);
344 Toast.error('خطا: ' + err.message);
345 }
346 }
347
348 async _confirmImport(kind) {
349 const mode = document.getElementById('importMode')?.value;
350 const pending = pendingExcelImport;
351 if (excelImportBusy) return;
352 if (mode !== 'merge' || !['products', 'contacts'].includes(kind) || pending?.kind !== kind) {
353 Toast.error('حالت ورود نامعتبر است؛ هیچ اطلاعاتی تغییر نکرد.');
354 return;
355 }
356 const rawData = pending?.rawData;
357
358 if (!rawData) {
359 Toast.error('داده‌ای برای ایمپورت نیست');
360 return;
361 }
362
363 excelImportBusy = true;
364 const submitButton = pending.card?.querySelector('[data-excel-import-submit]');
365 if (submitButton) submitButton.disabled = true;
366 try {
367 Toast.info('در حال ایمپورت...');
368 let result;
369 if (kind === 'products') {
370 result = await ExcelController.importProducts(rawData, { mode });
371 } else {
372 result = await ExcelController.importContacts(rawData, { mode });
373 }
374
375 if (Modal.stack[Modal.stack.length - 1]?.card === pending.card) Modal.close();
376 Toast.success(`ایمپورت انجام شد: ${Formatters.number(result.added)} اضافه، ${Formatters.number(result.skipped)} رد شده`);
377
378 // رفرش KPI ها
379 await this.reload();
380 const grid = document.querySelector('.settings-grid');
381 if (grid) grid.innerHTML = this._renderAllCards();
382 } catch (err) {
383 console.error(err);
384 Toast.error('خطا در ایمپورت: ' + err.message);
385 } finally {
386 excelImportBusy = false;
387 if (pendingExcelImport === pending) pendingExcelImport = null;
388 }
389 }
390
391 async downloadProductsTemplate() {
392 try {
393 await ExcelController.downloadProductsTemplate();
394 } catch (error) {
395 Toast.error('ساخت قالب کالاها ناموفق بود: ' + error.message);
396 }
397 }
398
399 async downloadContactsTemplate() {
400 try {
401 await ExcelController.downloadContactsTemplate();
402 } catch (error) {
403 Toast.error('ساخت قالب اشخاص ناموفق بود: ' + error.message);
404 }
405 }
406
407 // ============================================================
408 // کارت میانبرهای صفحه‌کلید
409 // ============================================================
410 _renderShortcutsCard() {
411 const s = KeyboardShortcuts.settings;
412
413 const toggle = (id, checked, label, hint) => `
414 <label style="display:flex;align-items:flex-start;gap:10px;padding:9px 0;cursor:pointer;border-bottom:1px solid var(--border)">
415 <input type="checkbox" id="${id}" ${checked ? 'checked' : ''} style="margin-top:3px;width:16px;height:16px;cursor:pointer" />
416 <div style="flex:1">
417 <div style="font-size:13px;font-weight:600">${label}</div>
418 <div style="font-size:11px;color:var(--text-muted);margin-top:2px;line-height:1.6">${hint}</div>
419 </div>
420 </label>
421 `;
422
423 return `
424 <div class="card settings-card" style="border-color:#ddd6fe;background:linear-gradient(135deg,#faf5ff,#f8fafc)">
425 <div class="settings-card-header">
426 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">⌨️</div>
427 <div>
428 <h3 class="settings-card-title">میانبرهای صفحه‌کلید</h3>
429 <p class="settings-card-desc">با این میانبرها کار با برنامه سریع‌تر می‌شود</p>
430 </div>
431 </div>
432
433 ${toggle('scEnabled', s.enabled, 'فعال بودن میانبرها', 'کلاً همه‌ی میانبرهای زیر رو روشن یا خاموش می‌کند')}
434 ${toggle('scEnterConfirms', s.enterConfirms, 'تأیید با Enter', 'وقتی توی فرم هستید، Enter مثل دکمه‌ی ذخیره عمل می‌کند. Ctrl+Enter هم توی همه‌ی فیلدها کار می‌کند')}
435 ${toggle('scEscapeCloses', s.escapeCloses, 'بستن با Escape', 'فشار دادن Escape، مودال باز را می‌بندد')}
436 ${toggle('scCtrlSaves', s.ctrlSaves, 'ذخیره با Ctrl+S', 'داخل مودال‌ها، Ctrl+S فرم را ذخیره می‌کند')}
437 ${toggle('scPlusMinusZeros', s.plusMinusZeros, 'ضریب سریع صفر (+ و -)', 'روی فیلدهای مبلغ، کلید + صفر اضافه و کلید − صفر کم می‌کند')}
438
439 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
440 <div class="form-group" style="margin-bottom:0">
441 <label class="form-label">تعداد صفرهای کلید +</label>
442 <input type="text" inputmode="numeric" class="form-control" id="scPlusZeros" aria-label="تعداد صفرهای میانبر مثبت" value="${Formatters.toPersianDigits(s.plusZeros)}" />
443 </div>
444 <div class="form-group" style="margin-bottom:0">
445 <label class="form-label">تعداد صفرهای کلید −</label>
446 <input type="text" inputmode="numeric" class="form-control" id="scMinusZeros" aria-label="تعداد صفرهای میانبر منفی" value="${Formatters.toPersianDigits(s.minusZeros)}" />
447 </div>
448 </div>
449
450 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
451 <button class="btn" onclick="window.SettingsView.saveShortcuts()">💾 ذخیره تنظیمات</button>
452 <button class="btn btn-secondary" onclick="window.SettingsView.resetShortcuts()">↺ بازگشت به پیش‌فرض</button>
453 </div>
454 </div>
455 `;
456 }
457
458 saveShortcuts() {
459 try {
460 const plusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scPlusZeros').value)) || 0;
461 const minusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scMinusZeros').value)) || 0;
462
463 const settings = {
464 enabled: document.getElementById('scEnabled').checked,
465 enterConfirms: document.getElementById('scEnterConfirms').checked,
466 escapeCloses: document.getElementById('scEscapeCloses').checked,
467 ctrlSaves: document.getElementById('scCtrlSaves').checked,
468 plusMinusZeros: document.getElementById('scPlusMinusZeros').checked,
469 plusZeros: Math.max(0, Math.min(12, plusZeros)),
470 minusZeros: Math.max(0, Math.min(12, minusZeros))
471 };
472
473 KeyboardShortcuts.saveSettings(settings);
474 Toast.success('تنظیمات میانبرهای صفحه‌کلید ذخیره شد');
475 } catch (err) {
476 Toast.error('خطا: ' + err.message);
477 }
478 }
479
480 resetShortcuts() {
481 Modal.confirm({
482 title: 'بازگشت به پیش‌فرض',
483 message: 'آیا می‌خواهید همه‌ی تنظیمات میانبرهای صفحه‌کلید به حالت پیش‌فرض برگردد؟',
484 confirmText: 'بازگردان',
485 onConfirm: () => {
486 KeyboardShortcuts.resetSettings();
487 Toast.success('تنظیمات به حالت پیش‌فرض برگشت');
488 const grid = document.querySelector('.settings-grid');
489 if (grid) grid.innerHTML = this._renderAllCards();
490 }
491 });
492 }
493
494
495 // A02: local ZIP metadata intake only; it cannot restore SQL Server databases.
496 _renderHolooBackupCard() {
497 return [
498 '<div class="card settings-card">',
499 ' <div class="settings-card-header">',
500 ' <div class="settings-card-icon">📦</div>',
501 ' <div>',
502 ' <h3 class="settings-card-title">آماده‌سازی انتقال از هلو (آزمایشی)</h3>',
503 ' <p class="settings-card-desc">تشخیص اولیه فایل ZIP، بدون ارسال یا ثبت داده</p>',
504 ' </div>',
505 ' </div>',
506 ' <p style="font-size:12px;line-height:1.9;color:var(--text-muted)">این مرحله فقط ساختار بسته ZIP را شناسایی می‌کند. بازیابی SQL Server، انتقال اطلاعات و تأیید صحت حسابداری هنوز پیاده‌سازی نشده‌اند.</p>',
507 ' <button class="btn btn-secondary" onclick="window.SettingsView.openHolooBackupProbe()">انتخاب بکاپ هلو و بررسی اولیه</button>',
508 ' <button class="btn btn-secondary" style="margin-top:8px" onclick="window.SettingsView.checkHolooMigrationReadiness()">بررسی پیش‌نیازهای رایانه برای انتقال از هلو</button>',
509 '</div>'
510 ].join('');
511 }
512
513 // Native read-only system diagnostics; never installs or configures SQL Server.
514 async checkHolooMigrationReadiness() {
515 if (!Auth.isAdmin()) {
516 Toast.error('فقط مدیر می‌تواند پیش‌نیازهای مهاجرت را بررسی کند');
517 return;
518 }
519 const invoke = globalThis.__TAURI_INTERNALS__?.invoke;
520 if (typeof invoke !== 'function') {
521 Toast.warning('بررسی پیش‌نیازها فقط در نسخه نصب‌شده ویندوز امکان‌پذیر است');
522 return;
523 }
524 try {
525 const report = await invoke('migration_system_readiness');
526 const fmtCount = value => Number.isInteger(value) && value >= 0
527 ? (value === 0 ? 'یافت نشد' : Formatters.number(value) + ' مورد شناسایی شد')
528 : 'امکان تشخیص وجود ندارد';
529 const body = [
530 '<p>این بررسی فقط وضعیت رایانه را می‌خواند؛ چیزی نصب یا تغییر داده نمی‌شود.</p>',
531 '<div style="font-size:12.5px;line-height:2.2">',
532 '<div>ویندوز ۶۴ بیتی: <strong>' + (report.windowsX64 ? 'شناسایی شد' : 'شناسایی نشد') + '</strong></div>',
533 '<div>نمونه‌های SQL Server: <strong>' + fmtCount(report.sqlInstanceCount) + '</strong></div>',
534 '<div>نسخه‌های LocalDB: <strong>' + fmtCount(report.localdbVersionCount) + '</strong></div>',
535 '<div>فضای آزاد درایو داده کاربر: <strong>' +
536 (Number.isSafeInteger(report.freeGibAtUserAppData)
537 ? Formatters.number(report.freeGibAtUserAppData) + ' گیگابایت'
538 : 'قابل تشخیص نیست') + '</strong></div>',
539 '</div>',
540 '<div class="backup-warning" style="margin-top:12px">',
541 '⚠️ شناسایی SQL به معنی سازگاری آن با بکاپ هلو نیست. ',
542 'هنوز SQL Server نصب نشده، فایل هلو بازیابی نشده و ورود اطلاعات مالی فعال نیست.',
543 '</div>'
544 ].join('');
545 Modal.open({
546 title: 'وضعیت پیش‌نیازهای مهاجرت هلو — فقط خواندنی',
547 body,
548 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
549 size: 'md'
550 });
551 } catch {
552 // Avoid exposing native exception text or local configuration details.
553 Toast.error('بررسی پیش‌نیازها انجام نشد؛ هیچ تغییری در سیستم ایجاد نشد');
554 }
555 }
556
557 openHolooBackupProbe() {
558 if (!Auth.isAdmin()) {
559 Toast.error('فقط مدیر می‌تواند بررسی بکاپ هلو را آغاز کند');
560 return;
561 }
562 const input = document.createElement('input');
563 input.type = 'file';
564 input.accept = '.zip';
565 input.onchange = async () => {
566 const file = input.files?.[0];
567 if (!file) return;
568 try {
569 const report = await probeHolooBackupZip(file);
570 Modal.open({
571 title: 'پیش‌بررسی بکاپ هلو — فقط خواندنی',
572 body: [
573 '<p>ساختار اولیه یک فایل ZIP تک‌ورودی شناسایی شد.</p>',
574 '<div style="font-size:12px;line-height:2">',
575 '<div>فایل: <strong>' + this._esc(file.name) + '</strong></div>',
576 '<div>محتوای بسته: <strong>' + this._esc(report.entryName) + '</strong></div>',
577 '<div>حجم فایل داخلی: <strong>' + Formatters.number(report.uncompressedSize) + '</strong> بایت</div>',
578 '</div>',
579 '<div class="backup-warning" style="margin-top:12px">',
580 '⚠️ این نتیجه به معنای صحت بکاپ SQL Server یا امکان انتقال اطلاعات مالی نیست. ',
581 'برای ادامه باید فایل در محیط ایزوله بازیابی و ساختار جداول و مانده‌ها تطبیق داده شود. ',
582 'تا آن زمان هیچ داده‌ای وارد نرم‌افزار نمی‌شود.',
583 '</div>'
584 ].join(''),
585 footer: '<button class="btn" onclick="FINORA.Modal.close()">متوجه شدم</button>',
586 size: 'md'
587 });
588 } catch (error) {
589 const messages = {
590 HOLOO_FILE_REQUIRED: 'فایل انتخاب‌شده معتبر نیست',
591 HOLOO_NOT_ZIP: 'فایل ZIP شناسایی نشد',
592 HOLOO_ENCRYPTED_ZIP: 'بسته رمزگذاری‌شده پشتیبانی نمی‌شود',
593 HOLOO_ZIP_SINGLE_ENTRY_REQUIRED: 'ساختار بسته با نمونه تک‌فایلی مورد انتظار سازگار نیست',
594 HOLOO_ZIP_TOO_LARGE: 'فایل برای پیش‌بررسی محلی بیش از حد بزرگ است'
595 };
596 Toast.error('بکاپ قابل پیش‌بررسی نیست: ' +
597 (messages[error.message] || 'ساختار ZIP نامعتبر یا پشتیبانی‌نشده است'));
598 }
599 };
600 input.click();
601 }
602
603 // ============================================================
604 // کارت بکاپ
605 // ============================================================
606 _renderBackupCard() {
607 return `
608 <div class="card settings-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f8fafc)">
609 <div class="settings-card-header">
610 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
611 <div>
612 <h3 class="settings-card-title">پشتیبان‌گیری رمزگذاری‌شده</h3>
613 <p class="settings-card-desc">اطلاعات عملیاتی و حسابداری شرکت فعال؛ بازیابی بدون بازنویسی کاربران و تنظیمات سراسری</p>
614 </div>
615 </div>
616
617 <div class="backup-warning">
618 ⚠️ <strong>مهم:</strong> قبل از هر تغییر بزرگ در برنامه، حتماً بکاپ بگیرید.
619 </div>
620
621 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
622 <button class="btn" onclick="window.SettingsView.downloadBackup()">
623 📥 دانلود فایل بکاپ
624 </button>
625 <button class="btn btn-secondary" onclick="window.SettingsView.openRestoreModal()">
626 📤 بازیابی از بکاپ
627 </button>
628 </div>
629
630 <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)">
631 <button class="btn btn-danger btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.openWipeModal()">
632 🗑️ پاک کردن کامل داده‌ها
633 </button>
634 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">این عمل قابل بازگشت نیست، حتماً قبلش بکاپ بگیرید</small>
635 </div>
636 </div>
637 `;
638 }
639
640 // ============================================================
641 // ابزار تشخیص مغایرت‌ها (فقط خواندنی و درخواستی)
642 // ============================================================
643 _renderHealthCard() {
644 return `
645 <div class="card settings-card">
646 <div class="settings-card-header">
647 <div class="settings-card-icon">🔎</div>
648 <div>
649 <h3 class="settings-card-title">کنترل سلامت تسویه‌های مالی</h3>
650 <p class="settings-card-desc">بررسی مغایرت فاکتورها، رسیدها و تخصیص‌ها در شرکت فعال؛ بدون تغییر اطلاعات</p>
651 </div>
652 </div>
653 <button class="btn btn-secondary" onclick="window.SettingsView.runFinancialDiagnostics()">
654 بررسی مغایرت‌ها
655 </button>
656 <small style="display:block;margin-top:8px;color:var(--text-muted)">بررسی فقط هنگام درخواست اجرا می‌شود و هیچ سندی را خودکار اصلاح نمی‌کند.</small>
657 </div>
658 `;
659 }
660
661 async runFinancialDiagnostics() {
662 if (!Auth.isAdmin()) { Toast.error('این بررسی فقط برای مدیر مجاز است'); return; }
663 try {
664 Toast.info('در حال بررسی تسویه‌ها...');
665 const report = await inspectSettlementConsistency({ maxIssues: 50 });
666 const names = {
667 ORPHAN_SETTLEMENT: 'تسویه بدون فاکتور معتبر',
668 INVALID_SETTLEMENT_AMOUNT: 'مبلغ نامعتبر تسویه',
669 MISSING_TREASURY_TRANSACTION: 'رسید یا تراکنش خزانه ناموجود',
670 SETTLEMENT_AMOUNT_OVERFLOW: 'سرریز مبلغ تسویه',
671 SETTLEMENT_TOTAL_MISMATCH: 'عدم تطابق مبلغ تسویه با فاکتور',
672 INVALID_INVOICE_AMOUNT: 'مبلغ نامعتبر فاکتور',
673 INVOICE_OVERPAID: 'تسویه بیش از مبلغ فاکتور',
674 INVOICE_REMAINING_MISMATCH: 'مانده فاکتور نادرست',
675 INVOICE_STATUS_MISMATCH: 'وضعیت تسویه ناهماهنگ'
676 };
677 const rows = report.issues.map(issue => `
678 <div style="padding:9px 0;border-bottom:1px solid var(--border)">
679 <strong>${this._esc(names[issue.code] || issue.code)}</strong>
680 <div style="font-size:12px;color:var(--text-muted)">شناسه سند: ${this._esc(issue.documentId)}</div>
681 </div>`).join('');
682 const body = `
683 <p>فاکتورهای کنترل‌شده: <strong>${Formatters.number(report.checkedInvoices)}</strong>
684 | تخصیص‌ها: <strong>${Formatters.number(report.checkedSettlements)}</strong>
685 | مغایرت‌ها: <strong>${Formatters.number(report.issueCount)}</strong></p>
686 <p style="color:var(--text-muted);font-size:12px">این گزارش تشخیصی است؛ پیش از هر اصلاح، سندهای مبنا را بررسی کنید.</p>
687 ${rows || '<p>در کنترل‌های فعلی مغایرتی یافت نشد.</p>'}
688 ${report.truncated ? '<p>فقط ۵۰ مغایرت نخست نمایش داده می‌شود.</p>' : ''}
689 `;
690 Modal.open({ title: 'گزارش کنترل سلامت تسویه‌ها', body,
691 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>', size: 'lg' });
692 } catch (err) {
693 Toast.error('بررسی سلامت تسویه‌ها ناموفق بود: ' + err.message);
694 }
695 }
696
697 // ============================================================
698 // ردپای حسابرسی فقط خواندنی برای مدیر
699 // ============================================================
700 _renderAuditCard() {
701 return `
702 <div class="card settings-card">
703 <div class="settings-card-header">
704 <div class="settings-card-icon">📋</div>
705 <div>
706 <h3 class="settings-card-title">ردپای حسابرسی</h3>
707 <p class="settings-card-desc">نمایش رویدادهای مالی ثبت‌شده از زمان فعال‌شدن ممیزی؛ سوابق قدیمی به‌طور خودکار ممیزی نمی‌شوند</p>
708 </div>
709 </div>
710 <button class="btn btn-secondary" onclick="window.SettingsView.openAuditTrail()">
711 مشاهده رویدادهای شرکت فعال
712 </button>
713 </div>
714 `;
715 }
716
717 async openAuditTrail() {
718 if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; }
719 try {
720 const events = await AuditService.list({ limit: 100 });
721 const labels = {
722 journal_posted: 'ثبت سند مالی',
723 journal_reversed: 'برگشت سند مالی',
724 commercial_journal_posted: 'ثبت رویداد تجاری',
725 period_opened: 'ایجاد دوره مالی',
726 period_closed: 'بستن دوره مالی',
727 draft_created: 'ساخت پیش‌نویس',
728 draft_updated: 'ویرایش پیش‌نویس',
729 draft_posted: 'ثبت قطعی پیش‌نویس',
730 draft_discarded: 'حذف پیش‌نویس',
731 backup_restored: 'بازیابی فایل پشتیبان'
732 };
733 const list = events.map(event => `
734 <div style="padding:10px 0;border-bottom:1px solid var(--border)">
735 <strong>${this._esc(labels[event.eventType] || event.eventType)}</strong>
736 <div style="color:var(--text-muted);font-size:12px">
737 سند: ${this._esc(event.sourceId)} | کاربر: ${this._esc(event.actorId)}
738 </div>
739 <div style="color:var(--text-muted);font-size:11px">
740 ${this._esc(event.businessDate || '')} — ${this._esc(event.occurredAtUtc)}
741 </div>
742 </div>
743 `).join('');
744 Modal.open({ title: 'ردپای حسابرسی شرکت فعال',
745 body: `<p style="font-size:12px;color:var(--text-muted)">تا ۱۰۰ رویداد اخیر؛ فقط از زمان فعال‌سازی ممیزی. اطلاعاتی که پیش از آن ثبت شده‌اند، سابقه ممیزی ساختگی ندارند.</p>${list || '<p>رویدادی یافت نشد.</p>'}`,
746 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
747 size: 'lg' });
748 } catch (err) {
749 Toast.error('نمایش ردپای حسابرسی ناموفق بود: ' + err.message);
750 }
751 }
752
753 // ============================================================
754 // کارت آمار
755 // ============================================================
756 _renderStatsCard() {
757 const s = cache.stats;
758 const items = [
759 { label: 'کالا و خدمات', value: s.products || 0, icon: '📦' },
760 { label: 'اشخاص', value: s.contacts || 0, icon: '👥' },
761 { label: 'فاکتورها', value: s.invoices || 0, icon: '🧾' },
762 { label: 'چک‌ها', value: s.cheques || 0, icon: '💳' },
763 { label: 'حساب‌ها', value: s.accounts || 0, icon: '🏦' },
764 { label: 'تراکنش‌ها', value: s.transactions || 0, icon: '💸' }
765 ];
766 return `
767 <div class="card settings-card">
768 <div class="settings-card-header">
769 <div class="settings-card-icon" style="background:linear-gradient(135deg,#0ea5e9,#0369a1)">📊</div>
770 <div>
771 <h3 class="settings-card-title">آمار داده‌ها</h3>
772 <p class="settings-card-desc">خلاصه‌ی داده‌های ذخیره‌شده در سیستم</p>
773 </div>
774 </div>
775 <div class="stats-grid">
776 ${items.map(i => `
777 <div class="stat-mini">
778 <div style="font-size:18px;margin-bottom:4px">${i.icon}</div>
779 <div style="font-size:18px;font-weight:800;color:var(--primary)">${Formatters.number(i.value)}</div>
780 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${i.label}</div>
781 </div>
782 `).join('')}
783 </div>
784 </div>
785 `;
786 }
787
788 // ============================================================
789 // کارت تم
790 // ============================================================
791 _renderThemeCard() {
792 const current = Theme.current();
793 return `
794 <div class="card settings-card">
795 <div class="settings-card-header">
796 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">🎨</div>
797 <div>
798 <h3 class="settings-card-title">ظاهر و تم</h3>
799 <p class="settings-card-desc">حالت نمایش برنامه</p>
800 </div>
801 </div>
802 <div style="display:flex;gap:10px;margin-top:8px">
803 <button class="btn ${current === 'light' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('light')">☀️ روشن</button>
804 <button class="btn ${current === 'dark' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('dark')">🌙 تاریک</button>
805 </div>
806 </div>
807 `;
808 }
809
810 // ============================================================
811 // کارت درباره
812 // ============================================================
813 _renderAboutCard() {
814 return `
815 <div class="card settings-card">
816 <div class="settings-card-header">
817 <div class="settings-card-icon">ℹ️</div>
818 <div>
819 <h3 class="settings-card-title">درباره فینورا پرو</h3>
820 <p class="settings-card-desc">نسخه ۲.۰.۳</p>
821 </div>
822 </div>
823 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
824 <div><strong>طراح و توسعه‌دهنده:</strong> داوود مهربان</div>
825 <div><strong>تماس:</strong> <span dir="ltr">0912-437-6991</span></div>
826 <div style="margin-top:8px;padding-top:10px;border-top:1px dashed var(--border)">
827 <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>
828 </div>
829 </div>
830 </div>
831 `;
832 }
833
834 _renderLicenseCard() {
835 const state = LicenseService.status();
836 const mode = state.mode === 'licensed' ? 'مجوز امضاشده معتبر' :
837 state.mode === 'license-invalid' ? 'مجوز نامعتبر یا منقضی' : 'نسخه آزمایشی';
838 const machine = this._esc(LicenseService.installationId() || 'نامشخص');
839 const readiness = LicenseService.hasTrustedIssuer()
840 ? 'کلید عمومی صادرکننده فعال است'
841 : 'فعلاً کلید عمومی صدور مجوز در نسخه نصب‌شده تنظیم نشده است';
842 return `
843 <div class="card settings-card">
844 <div class="settings-card-header">
845 <div class="settings-card-icon">🔐</div>
846 <div>
847 <h3 class="settings-card-title">مجوز آفلاین نرم‌افزار</h3>
848 <p class="settings-card-desc">وضعیت: ${this._esc(mode)} — ${state.readOnly ? 'فقط مشاهده' : 'قابل ثبت'}</p>
849 </div>
850 </div>
851 <div style="font-size:12px;line-height:2">
852 <div>شناسه نصب: <code dir="ltr" style="overflow-wrap:anywhere">${machine}</code></div>
853 <div>${this._esc(readiness)}</div>
854 </div>
855 <button class="btn btn-secondary" onclick="window.SettingsView.openSignedLicenseModal()" ${LicenseService.hasTrustedIssuer() ? '' : 'disabled'}>
856 فعال‌سازی با مجوز امضاشده
857 </button>
858 <small style="display:block;margin-top:8px">برای فعال‌سازی، مجوز صادرشده مخصوص همین شناسه نصب لازم است؛ اطلاعات حسابداری در صورت انقضا حذف نمی‌شود.</small>
859 </div>
860 `;
861 }
862
863 openSignedLicenseModal() {
864 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
865 if (!LicenseService.hasTrustedIssuer()) {
866 Toast.error('کلید معتبر صادرکننده در این نسخه نصب نشده است'); return;
867 }
868 Modal.open({
869 title: 'فعال‌سازی مجوز آفلاین',
870 body: '<label for="signedLicenseToken">متن JSON مجوز امضاشده</label>' +
871 '<textarea id="signedLicenseToken" class="form-control" rows="8" spellcheck="false" dir="ltr"></textarea>' +
872 '<p style="font-size:12px">امضای دیجیتال و شناسه دستگاه پیش از هر تغییر اعتبارسنجی می‌شوند.</p>',
873 footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>' +
874 '<button class="btn" onclick="window.SettingsView.applySignedLicense()">اعتبارسنجی و فعال‌سازی</button>',
875 size: 'md'
876 });
877 }
878
879 async applySignedLicense() {
880 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
881 const token = document.getElementById('signedLicenseToken')?.value;
882 if (!token?.trim()) { Toast.error('متن مجوز خالی است'); return; }
883 try {
884 await LicenseService.activateSignedLicense(token.trim());
885 Modal.close();
886 const grid = document.querySelector('.settings-grid');
887 if (grid) grid.innerHTML = this._renderAllCards();
888 Toast.success('مجوز آفلاین معتبر با موفقیت فعال شد');
889 } catch (error) {
890 Toast.error(error.message);
891 }
892 }
893
894 _renderAllCards() {
895 return this._renderCompanyCard()
896 + this._renderInvoiceSettingsCard()
897 + this._renderExcelCard()
898 + this._renderShortcutsCard()
899 + this._renderBackupCard()
900 + (Auth.isAdmin() ? this._renderHolooBackupCard() : '')
901 + (Auth.isAdmin() ? this._renderLicenseCard() : '')
902 + this._renderStatsCard()
903 + (Auth.isAdmin() ? this._renderHealthCard() : '')
904 + (Auth.isAdmin() ? this._renderAuditCard() : '')
905 + this._renderThemeCard()
906 + this._renderAboutCard();
907 }
908
909 // ============================================================
910 // فرم اطلاعات شرکت
911 // ============================================================
912 async openCompanySwitcher() {
913 const companies = await globalThis.FINORA.Company.list();
914 const body = companies.map(c => `<button class="btn" style="width:100%;margin:4px 0" onclick="window.SettingsView.selectCompany(${this._esc(JSON.stringify(String(c.id ?? '')))})">${this._esc(c.name || 'شرکت')}</button>`).join('');
915 Modal.open({ title: 'تغییر شرکت فعال', body: body || '<div class="empty-mini">شرکتی یافت نشد</div>', footer: '', size: 'sm' });
916 }
917
918 async selectCompany(id) {
919 await globalThis.FINORA.Company.select(id); Modal.close(); await this.reload(); Toast.success('شرکت فعال تغییر کرد');
920 }
921
922 async createCompany() {
923 const name = prompt('نام شرکت جدید را وارد کنید:'); if (!name?.trim()) return;
924 const company = await globalThis.FINORA.Company.create({ name: name.trim(), entityType: 'legal' });
925 await globalThis.FINORA.Company.select(company.id); await this.reload(); Toast.success('شرکت جدید ایجاد شد');
926 }
927
928 openCompanyModal() {
929 const c = cache.company;
930 const body = `
931 <div class="form-row">
932 <div class="form-group">
933 <label class="form-label">نوع شخص</label>
934 <select class="form-control" id="coEntityType">
935 <option value="legal" ${c.entityType === 'legal' ? 'selected' : ''}>حقوقی</option>
936 <option value="natural" ${c.entityType === 'natural' ? 'selected' : ''}>حقیقی</option>
937 </select>
938 </div>
939 <div class="form-group">
940 <label class="form-label">نام شرکت / فروشگاه <span class="req">*</span></label>
941 <input type="text" class="form-control" id="coName" value="${this._esc(c.name)}" />
942 </div>
943 </div>
944 <div class="form-row">
945 <div class="form-group">
946 <label class="form-label">شناسه ملی / کد ملی</label>
947 <input type="text" class="form-control" id="coNationalId" value="${this._esc(c.nationalId)}" />
948 </div>
949 <div class="form-group">
950 <label class="form-label">کد اقتصادی</label>
951 <input type="text" class="form-control" id="coEconomicCode" value="${this._esc(c.economicCode)}" />
952 </div>
953 </div>
954 <div class="form-row">
955 <div class="form-group">
956 <label class="form-label">شماره ثبت</label>
957 <input type="text" class="form-control" id="coRegNumber" value="${this._esc(c.regNumber)}" />
958 </div>
959 <div class="form-group">
960 <label class="form-label">کد پستی</label>
961 <input type="text" class="form-control" id="coPostalCode" value="${this._esc(c.postalCode)}" />
962 </div>
963 </div>
964 <div class="form-row">
965 <div class="form-group">
966 <label class="form-label">تلفن</label>
967 <input type="tel" class="form-control" id="coPhone" value="${this._esc(c.phone)}" />
968 </div>
969 <div class="form-group">
970 <label class="form-label">موبایل</label>
971 <input type="tel" class="form-control" id="coMobile" value="${this._esc(c.mobile)}" />
972 </div>
973 </div>
974 <div class="form-group">
975 <label class="form-label">نشانی</label>
976 <textarea class="form-control" id="coAddress" rows="2">${this._esc(c.address)}</textarea>
977 </div>
978 <div class="form-group">
979 <label class="form-label">پاورقی فاکتور</label>
980 <textarea class="form-control" id="coFooter" rows="2" placeholder="مثلاً: از خرید شما سپاسگزاریم">${this._esc(c.footer)}</textarea>
981 </div>
982 `;
983 const footer = `
984 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
985 <button class="btn" onclick="window.SettingsView.saveCompany()">💾 ذخیره</button>
986 `;
987 Modal.open({ title: 'اطلاعات شرکت', body, footer, size: 'md' });
988 }
989
990 async saveCompany() {
991 const data = {
992 name: document.getElementById('coName').value,
993 entityType: document.getElementById('coEntityType').value,
994 nationalId: document.getElementById('coNationalId').value,
995 economicCode: document.getElementById('coEconomicCode').value,
996 regNumber: document.getElementById('coRegNumber').value,
997 postalCode: document.getElementById('coPostalCode').value,
998 phone: document.getElementById('coPhone').value,
999 mobile: document.getElementById('coMobile').value,
1000 address: document.getElementById('coAddress').value,
1001 footer: document.getElementById('coFooter').value
1002 };
1003 if (!data.name.trim()) { Toast.warning('نام الزامی است'); return; }
1004 try {
1005 await SettingsController.saveCompanyInfo(data);
1006 Toast.success('اطلاعات ذخیره شد');
1007 Modal.close();
1008 await this.reload();
1009 const grid = document.querySelector('.settings-grid');
1010 if (grid) grid.innerHTML = this._renderAllCards();
1011 } catch (err) {
1012 Toast.error('خطا: ' + err.message);
1013 }
1014 }
1015
1016 // ============================================================
1017 // بکاپ JSON
1018 // ============================================================
1019 async downloadBackup() {
1020 try {
1021 Toast.info('در حال آماده‌سازی بکاپ...');
1022 const result = await SettingsController.downloadBackup();
1023 Toast.success(`بکاپ دانلود شد (${result.filename})`, 'موفق');
1024 } catch (err) {
1025 Toast.error('خطا در بکاپ: ' + err.message);
1026 }
1027 }
1028
1029 openRestoreModal() {
1030 const body = `
1031 <div class="backup-warning" style="margin-bottom:14px">
1032 ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، فقط رکوردهای دارای شناسه یکسان بازنویسی می‌شوند و سایر داده‌ها حذف نمی‌شوند.
1033 </div>
1034
1035 <div class="form-group">
1036 <label class="form-label">فایل بکاپ رمزگذاری‌شده یا JSON</label>
1037 <input type="file" class="form-control" id="restoreFile" accept=".json,.fbackup,application/json,application/octet-stream" />
1038 </div>
1039
1040 <div class="form-group">
1041 <label class="form-label">حالت بازیابی</label>
1042 <select class="form-control" id="restoreMode">
1043 <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
1044 <option value="replace">🔄 بازنویسی شناسه‌های یکسان (Replace) — بدون حذف سایر رکوردها</option>
1045 </select>
1046 </div>
1047 `;
1048 const footer = `
1049 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
1050 <button class="btn" onclick="window.SettingsView.restoreBackup()">📤 بازیابی</button>
1051 `;
1052 Modal.open({ title: 'بازیابی از بکاپ', body, footer, size: 'md' });
1053 }
1054
1055 async restoreBackup() {
1056 const fileInput = document.getElementById('restoreFile');
1057 const file = fileInput.files[0];
1058 if (!file) { Toast.warning('فایل بکاپ رو انتخاب کنید'); return; }
1059
1060 const mode = document.getElementById('restoreMode').value;
1061
1062 try {
1063 Toast.info('در حال بازیابی...');
1064 const content = await SettingsController.readFileAsText(file);
1065 const counts = await SettingsController.importBackup(content, { mode });
1066 Modal.close();
1067 Toast.success(`بازیابی انجام شد: ${counts.added} مورد اضافه، ${counts.skipped} مورد skip`);
1068 setTimeout(() => location.reload(), 1500);
1069 } catch (err) {
1070 Toast.error('خطا: ' + err.message);
1071 }
1072 }
1073
1074 // ============================================================
1075 // پاک کردن کامل
1076 // ============================================================
1077 openWipeModal() {
1078 const body = `
1079 <div style="text-align:center;padding:10px 0">
1080 <div style="font-size:48px;margin-bottom:12px">⚠️</div>
1081 <h3 style="color:var(--danger);margin-bottom:8px">پاک کردن کامل داده‌ها</h3>
1082 <p style="color:var(--text-muted);font-size:13px;line-height:1.8;margin-bottom:16px">
1083 این عمل همه‌ی کالاها، اشخاص، فاکتورها، چک‌ها، تراکنش‌ها و تنظیمات رو برای همیشه پاک می‌کند.
1084 <br><strong>قابل بازگشت نیست!</strong>
1085 </p>
1086 <p style="font-size:12px;color:var(--danger);margin-bottom:16px">
1087 لطفاً برای تأیید، کلمه‌ی <code style="background:var(--danger);color:#fff;padding:2px 8px;border-radius:4px">حذف</code> رو تایپ کنید
1088 </p>
1089 <input type="text" class="form-control" id="wipeConfirm" aria-label="متن تایید پاک کردن داده‌ها" placeholder="حذف" style="text-align:center;max-width:200px;margin:0 auto" />
1090 </div>
1091 `;
1092 const footer = `
1093 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
1094 <button class="btn btn-danger" onclick="window.SettingsView.confirmWipe()">🗑️ پاک کن</button>
1095 `;
1096 Modal.open({ title: 'تأیید پاک کردن', body, footer, size: 'sm' });
1097 }
1098
1099 async confirmWipe() {
1100 const confirmText = document.getElementById('wipeConfirm').value.trim();
1101 if (confirmText !== 'حذف') {
1102 Toast.warning('متن تأیید اشتباه است');
1103 return;
1104 }
1105 try {
1106 await SettingsController.wipeAll();
1107 Toast.success('همه‌ی داده‌ها پاک شد');
1108 setTimeout(() => location.reload(), 800);
1109 } catch (err) {
1110 Toast.error('خطا: ' + err.message);
1111 }
1112 }
1113
1114 // ============================================================
1115 // Theme
1116 // ============================================================
1117 setTheme(theme) {
1118 Theme.apply(theme);
1119 const grid = document.querySelector('.settings-grid');
1120 if (grid) grid.innerHTML = this._renderAllCards();
1121 }
1122
1123 _esc(s) {
1124 if (!s) return '';
1125 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
1126 }
1127 }
1128
1129 export const SettingsView = new SettingsViewImpl();
1130 window.SettingsView = SettingsView;