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

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