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

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