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

integration/a02-windows-holoo-setup-candidate-20261030
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,111 lines 53.8 KB
Raw
1 // ============================================================
2 // SettingsView — صفحه‌ی تنظیمات، بکاپ، شرکت و Excel
3 // ============================================================
4
5 import { SettingsController } from '../controllers/SettingsController.js';
6 import { StorageService } from '../core/StorageService.js';
7 import { Theme } from '../core/Theme.js';
8 import { KeyboardShortcuts } from '../core/KeyboardShortcuts.js';
9 import { Modal } from '../core/Modal.js';
10 import { Toast } from '../core/Toast.js';
11 import { Formatters } from '../utils/Formatters.js';
12 import { Auth } from '../core/Auth.js';
13 import { ExcelController } from '../controllers/ExcelController.js';
14 import { inspectSettlementConsistency } from '../core/FinancialDiagnosticsService.js';
15 import { AuditService } from '../core/AuditService.js';
16 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">نحوه شماره‌گذاری</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">شماره بعدی فاکتور</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 <option value="replace">🔄 جایگزینی (Replace) — همه‌ی ${kindLabel} فعلی پاک و از فایل جایگزین می‌شن</option>
320 </select>
321 </div>
322 `;
323 const footer = `
324 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
325 <button class="btn btn-success" onclick="window.SettingsView._confirmImport(${JSON.stringify(kind).replace(/"/g, "'")}, '${this._esc(file.name)}')">✅ شروع ایمپورت</button>
326 `;
327 Modal.open({ title: `📤 ورود ${kindLabel} از Excel`, body, footer, size: 'md' });
328
329 // ذخیره‌ی موقت داده
330 window.__importRawData = preview.raw;
331 window.__importKind = kind;
332 } catch (err) {
333 console.error(err);
334 Toast.error('خطا: ' + err.message);
335 }
336 }
337
338 async _confirmImport(kind, fileName) {
339 const mode = document.getElementById('importMode').value;
340 const rawData = window.__importRawData;
341
342 if (!rawData) {
343 Toast.error('داده‌ای برای ایمپورت نیست');
344 return;
345 }
346
347 try {
348 Toast.info('در حال ایمپورت...');
349 let result;
350 if (kind === 'products') {
351 result = await ExcelController.importProducts(rawData, { mode });
352 } else {
353 result = await ExcelController.importContacts(rawData, { mode });
354 }
355
356 Modal.close();
357 Toast.success(`ایمپورت انجام شد: ${Formatters.number(result.added)} اضافه، ${Formatters.number(result.skipped)} رد شده`);
358
359 // رفرش KPI ها
360 await this.reload();
361 const grid = document.querySelector('.settings-grid');
362 if (grid) grid.innerHTML = this._renderAllCards();
363 } catch (err) {
364 console.error(err);
365 Toast.error('خطا در ایمپورت: ' + err.message);
366 } finally {
367 window.__importRawData = null;
368 window.__importKind = null;
369 }
370 }
371
372 async downloadProductsTemplate() {
373 try {
374 await ExcelController.downloadProductsTemplate();
375 } catch (error) {
376 Toast.error('ساخت قالب کالاها ناموفق بود: ' + error.message);
377 }
378 }
379
380 async downloadContactsTemplate() {
381 try {
382 await ExcelController.downloadContactsTemplate();
383 } catch (error) {
384 Toast.error('ساخت قالب اشخاص ناموفق بود: ' + error.message);
385 }
386 }
387
388 // ============================================================
389 // کارت میانبرهای صفحه‌کلید
390 // ============================================================
391 _renderShortcutsCard() {
392 const s = KeyboardShortcuts.settings;
393
394 const toggle = (id, checked, label, hint) => `
395 <label style="display:flex;align-items:flex-start;gap:10px;padding:9px 0;cursor:pointer;border-bottom:1px solid var(--border)">
396 <input type="checkbox" id="${id}" ${checked ? 'checked' : ''} style="margin-top:3px;width:16px;height:16px;cursor:pointer" />
397 <div style="flex:1">
398 <div style="font-size:13px;font-weight:600">${label}</div>
399 <div style="font-size:11px;color:var(--text-muted);margin-top:2px;line-height:1.6">${hint}</div>
400 </div>
401 </label>
402 `;
403
404 return `
405 <div class="card settings-card" style="border-color:#ddd6fe;background:linear-gradient(135deg,#faf5ff,#f8fafc)">
406 <div class="settings-card-header">
407 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">⌨️</div>
408 <div>
409 <h3 class="settings-card-title">میانبرهای صفحه‌کلید</h3>
410 <p class="settings-card-desc">با این میانبرها کار با برنامه سریع‌تر می‌شود</p>
411 </div>
412 </div>
413
414 ${toggle('scEnabled', s.enabled, 'فعال بودن میانبرها', 'کلاً همه‌ی میانبرهای زیر رو روشن یا خاموش می‌کند')}
415 ${toggle('scEnterConfirms', s.enterConfirms, 'تأیید با Enter', 'وقتی توی فرم هستید، Enter مثل دکمه‌ی ذخیره عمل می‌کند. Ctrl+Enter هم توی همه‌ی فیلدها کار می‌کند')}
416 ${toggle('scEscapeCloses', s.escapeCloses, 'بستن با Escape', 'فشار دادن Escape، مودال باز را می‌بندد')}
417 ${toggle('scCtrlSaves', s.ctrlSaves, 'ذخیره با Ctrl+S', 'داخل مودال‌ها، Ctrl+S فرم را ذخیره می‌کند')}
418 ${toggle('scPlusMinusZeros', s.plusMinusZeros, 'ضریب سریع صفر (+ و -)', 'روی فیلدهای مبلغ، کلید + صفر اضافه و کلید − صفر کم می‌کند')}
419
420 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
421 <div class="form-group" style="margin-bottom:0">
422 <label class="form-label">تعداد صفرهای کلید +</label>
423 <input type="text" inputmode="numeric" class="form-control" id="scPlusZeros" value="${Formatters.toPersianDigits(s.plusZeros)}" />
424 </div>
425 <div class="form-group" style="margin-bottom:0">
426 <label class="form-label">تعداد صفرهای کلید −</label>
427 <input type="text" inputmode="numeric" class="form-control" id="scMinusZeros" value="${Formatters.toPersianDigits(s.minusZeros)}" />
428 </div>
429 </div>
430
431 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
432 <button class="btn" onclick="window.SettingsView.saveShortcuts()">💾 ذخیره تنظیمات</button>
433 <button class="btn btn-secondary" onclick="window.SettingsView.resetShortcuts()">↺ بازگشت به پیش‌فرض</button>
434 </div>
435 </div>
436 `;
437 }
438
439 saveShortcuts() {
440 try {
441 const plusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scPlusZeros').value)) || 0;
442 const minusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scMinusZeros').value)) || 0;
443
444 const settings = {
445 enabled: document.getElementById('scEnabled').checked,
446 enterConfirms: document.getElementById('scEnterConfirms').checked,
447 escapeCloses: document.getElementById('scEscapeCloses').checked,
448 ctrlSaves: document.getElementById('scCtrlSaves').checked,
449 plusMinusZeros: document.getElementById('scPlusMinusZeros').checked,
450 plusZeros: Math.max(0, Math.min(12, plusZeros)),
451 minusZeros: Math.max(0, Math.min(12, minusZeros))
452 };
453
454 KeyboardShortcuts.saveSettings(settings);
455 Toast.success('تنظیمات میانبرهای صفحه‌کلید ذخیره شد');
456 } catch (err) {
457 Toast.error('خطا: ' + err.message);
458 }
459 }
460
461 resetShortcuts() {
462 Modal.confirm({
463 title: 'بازگشت به پیش‌فرض',
464 message: 'آیا می‌خواهید همه‌ی تنظیمات میانبرهای صفحه‌کلید به حالت پیش‌فرض برگردد؟',
465 confirmText: 'بازگردان',
466 onConfirm: () => {
467 KeyboardShortcuts.resetSettings();
468 Toast.success('تنظیمات به حالت پیش‌فرض برگشت');
469 const grid = document.querySelector('.settings-grid');
470 if (grid) grid.innerHTML = this._renderAllCards();
471 }
472 });
473 }
474
475
476 // A02: local ZIP metadata intake only; it cannot restore SQL Server databases.
477 _renderHolooBackupCard() {
478 return [
479 '<div class="card settings-card">',
480 ' <div class="settings-card-header">',
481 ' <div class="settings-card-icon">📦</div>',
482 ' <div>',
483 ' <h3 class="settings-card-title">آماده‌سازی انتقال از هلو (آزمایشی)</h3>',
484 ' <p class="settings-card-desc">تشخیص اولیه فایل ZIP، بدون ارسال یا ثبت داده</p>',
485 ' </div>',
486 ' </div>',
487 ' <p style="font-size:12px;line-height:1.9;color:var(--text-muted)">این مرحله فقط ساختار بسته ZIP را شناسایی می‌کند. بازیابی SQL Server، انتقال اطلاعات و تأیید صحت حسابداری هنوز پیاده‌سازی نشده‌اند.</p>',
488 ' <button class="btn btn-secondary" onclick="window.SettingsView.openHolooBackupProbe()">انتخاب بکاپ هلو و بررسی اولیه</button>',
489 ' <button class="btn btn-secondary" style="margin-top:8px" onclick="window.SettingsView.checkHolooMigrationReadiness()">بررسی پیش‌نیازهای رایانه برای انتقال از هلو</button>',
490 '</div>'
491 ].join('');
492 }
493
494 // Native read-only system diagnostics; never installs or configures SQL Server.
495 async checkHolooMigrationReadiness() {
496 if (!Auth.isAdmin()) {
497 Toast.error('فقط مدیر می‌تواند پیش‌نیازهای مهاجرت را بررسی کند');
498 return;
499 }
500 const invoke = globalThis.__TAURI_INTERNALS__?.invoke;
501 if (typeof invoke !== 'function') {
502 Toast.warning('بررسی پیش‌نیازها فقط در نسخه نصب‌شده ویندوز امکان‌پذیر است');
503 return;
504 }
505 try {
506 const report = await invoke('migration_system_readiness');
507 const fmtCount = value => Number.isInteger(value) && value >= 0
508 ? (value === 0 ? 'یافت نشد' : Formatters.number(value) + ' مورد شناسایی شد')
509 : 'امکان تشخیص وجود ندارد';
510 const body = [
511 '<p>این بررسی فقط وضعیت رایانه را می‌خواند؛ چیزی نصب یا تغییر داده نمی‌شود.</p>',
512 '<div style="font-size:12.5px;line-height:2.2">',
513 '<div>ویندوز ۶۴ بیتی: <strong>' + (report.windowsX64 ? 'شناسایی شد' : 'شناسایی نشد') + '</strong></div>',
514 '<div>نمونه‌های SQL Server: <strong>' + fmtCount(report.sqlInstanceCount) + '</strong></div>',
515 '<div>نسخه‌های LocalDB: <strong>' + fmtCount(report.localdbVersionCount) + '</strong></div>',
516 '<div>فضای آزاد درایو داده کاربر: <strong>' +
517 (Number.isSafeInteger(report.freeGibAtUserAppData)
518 ? Formatters.number(report.freeGibAtUserAppData) + ' گیگابایت'
519 : 'قابل تشخیص نیست') + '</strong></div>',
520 '</div>',
521 '<div class="backup-warning" style="margin-top:12px">',
522 '⚠️ شناسایی SQL به معنی سازگاری آن با بکاپ هلو نیست. ',
523 'هنوز SQL Server نصب نشده، فایل هلو بازیابی نشده و ورود اطلاعات مالی فعال نیست.',
524 '</div>'
525 ].join('');
526 Modal.open({
527 title: 'وضعیت پیش‌نیازهای مهاجرت هلو — فقط خواندنی',
528 body,
529 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
530 size: 'md'
531 });
532 } catch {
533 // Avoid exposing native exception text or local configuration details.
534 Toast.error('بررسی پیش‌نیازها انجام نشد؛ هیچ تغییری در سیستم ایجاد نشد');
535 }
536 }
537
538 openHolooBackupProbe() {
539 if (!Auth.isAdmin()) {
540 Toast.error('فقط مدیر می‌تواند بررسی بکاپ هلو را آغاز کند');
541 return;
542 }
543 const input = document.createElement('input');
544 input.type = 'file';
545 input.accept = '.zip';
546 input.onchange = async () => {
547 const file = input.files?.[0];
548 if (!file) return;
549 try {
550 const report = await probeHolooBackupZip(file);
551 Modal.open({
552 title: 'پیش‌بررسی بکاپ هلو — فقط خواندنی',
553 body: [
554 '<p>ساختار اولیه یک فایل ZIP تک‌ورودی شناسایی شد.</p>',
555 '<div style="font-size:12px;line-height:2">',
556 '<div>فایل: <strong>' + this._esc(file.name) + '</strong></div>',
557 '<div>محتوای بسته: <strong>' + this._esc(report.entryName) + '</strong></div>',
558 '<div>حجم فایل داخلی: <strong>' + Formatters.number(report.uncompressedSize) + '</strong> بایت</div>',
559 '</div>',
560 '<div class="backup-warning" style="margin-top:12px">',
561 '⚠️ این نتیجه به معنای صحت بکاپ SQL Server یا امکان انتقال اطلاعات مالی نیست. ',
562 'برای ادامه باید فایل در محیط ایزوله بازیابی و ساختار جداول و مانده‌ها تطبیق داده شود. ',
563 'تا آن زمان هیچ داده‌ای وارد نرم‌افزار نمی‌شود.',
564 '</div>'
565 ].join(''),
566 footer: '<button class="btn" onclick="FINORA.Modal.close()">متوجه شدم</button>',
567 size: 'md'
568 });
569 } catch (error) {
570 const messages = {
571 HOLOO_FILE_REQUIRED: 'فایل انتخاب‌شده معتبر نیست',
572 HOLOO_NOT_ZIP: 'فایل ZIP شناسایی نشد',
573 HOLOO_ENCRYPTED_ZIP: 'بسته رمزگذاری‌شده پشتیبانی نمی‌شود',
574 HOLOO_ZIP_SINGLE_ENTRY_REQUIRED: 'ساختار بسته با نمونه تک‌فایلی مورد انتظار سازگار نیست',
575 HOLOO_ZIP_TOO_LARGE: 'فایل برای پیش‌بررسی محلی بیش از حد بزرگ است'
576 };
577 Toast.error('بکاپ قابل پیش‌بررسی نیست: ' +
578 (messages[error.message] || 'ساختار ZIP نامعتبر یا پشتیبانی‌نشده است'));
579 }
580 };
581 input.click();
582 }
583
584 // ============================================================
585 // کارت بکاپ
586 // ============================================================
587 _renderBackupCard() {
588 return `
589 <div class="card settings-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f8fafc)">
590 <div class="settings-card-header">
591 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
592 <div>
593 <h3 class="settings-card-title">پشتیبان‌گیری رمزگذاری‌شده</h3>
594 <p class="settings-card-desc">اطلاعات عملیاتی و حسابداری شرکت فعال؛ بازیابی بدون بازنویسی کاربران و تنظیمات سراسری</p>
595 </div>
596 </div>
597
598 <div class="backup-warning">
599 ⚠️ <strong>مهم:</strong> قبل از هر تغییر بزرگ در برنامه، حتماً بکاپ بگیرید.
600 </div>
601
602 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
603 <button class="btn" onclick="window.SettingsView.downloadBackup()">
604 📥 دانلود فایل بکاپ
605 </button>
606 <button class="btn btn-secondary" onclick="window.SettingsView.openRestoreModal()">
607 📤 بازیابی از بکاپ
608 </button>
609 </div>
610
611 <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)">
612 <button class="btn btn-danger btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.openWipeModal()">
613 🗑️ پاک کردن کامل داده‌ها
614 </button>
615 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">این عمل قابل بازگشت نیست، حتماً قبلش بکاپ بگیرید</small>
616 </div>
617 </div>
618 `;
619 }
620
621 // ============================================================
622 // ابزار تشخیص مغایرت‌ها (فقط خواندنی و درخواستی)
623 // ============================================================
624 _renderHealthCard() {
625 return `
626 <div class="card settings-card">
627 <div class="settings-card-header">
628 <div class="settings-card-icon">🔎</div>
629 <div>
630 <h3 class="settings-card-title">کنترل سلامت تسویه‌های مالی</h3>
631 <p class="settings-card-desc">بررسی مغایرت فاکتورها، رسیدها و تخصیص‌ها در شرکت فعال؛ بدون تغییر اطلاعات</p>
632 </div>
633 </div>
634 <button class="btn btn-secondary" onclick="window.SettingsView.runFinancialDiagnostics()">
635 بررسی مغایرت‌ها
636 </button>
637 <small style="display:block;margin-top:8px;color:var(--text-muted)">بررسی فقط هنگام درخواست اجرا می‌شود و هیچ سندی را خودکار اصلاح نمی‌کند.</small>
638 </div>
639 `;
640 }
641
642 async runFinancialDiagnostics() {
643 if (!Auth.isAdmin()) { Toast.error('این بررسی فقط برای مدیر مجاز است'); return; }
644 try {
645 Toast.info('در حال بررسی تسویه‌ها...');
646 const report = await inspectSettlementConsistency({ maxIssues: 50 });
647 const names = {
648 ORPHAN_SETTLEMENT: 'تسویه بدون فاکتور معتبر',
649 INVALID_SETTLEMENT_AMOUNT: 'مبلغ نامعتبر تسویه',
650 MISSING_TREASURY_TRANSACTION: 'رسید یا تراکنش خزانه ناموجود',
651 SETTLEMENT_AMOUNT_OVERFLOW: 'سرریز مبلغ تسویه',
652 SETTLEMENT_TOTAL_MISMATCH: 'عدم تطابق مبلغ تسویه با فاکتور',
653 INVALID_INVOICE_AMOUNT: 'مبلغ نامعتبر فاکتور',
654 INVOICE_OVERPAID: 'تسویه بیش از مبلغ فاکتور',
655 INVOICE_REMAINING_MISMATCH: 'مانده فاکتور نادرست',
656 INVOICE_STATUS_MISMATCH: 'وضعیت تسویه ناهماهنگ'
657 };
658 const rows = report.issues.map(issue => `
659 <div style="padding:9px 0;border-bottom:1px solid var(--border)">
660 <strong>${this._esc(names[issue.code] || issue.code)}</strong>
661 <div style="font-size:12px;color:var(--text-muted)">شناسه سند: ${this._esc(issue.documentId)}</div>
662 </div>`).join('');
663 const body = `
664 <p>فاکتورهای کنترل‌شده: <strong>${Formatters.number(report.checkedInvoices)}</strong>
665 | تخصیص‌ها: <strong>${Formatters.number(report.checkedSettlements)}</strong>
666 | مغایرت‌ها: <strong>${Formatters.number(report.issueCount)}</strong></p>
667 <p style="color:var(--text-muted);font-size:12px">این گزارش تشخیصی است؛ پیش از هر اصلاح، سندهای مبنا را بررسی کنید.</p>
668 ${rows || '<p>در کنترل‌های فعلی مغایرتی یافت نشد.</p>'}
669 ${report.truncated ? '<p>فقط ۵۰ مغایرت نخست نمایش داده می‌شود.</p>' : ''}
670 `;
671 Modal.open({ title: 'گزارش کنترل سلامت تسویه‌ها', body,
672 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>', size: 'lg' });
673 } catch (err) {
674 Toast.error('بررسی سلامت تسویه‌ها ناموفق بود: ' + err.message);
675 }
676 }
677
678 // ============================================================
679 // ردپای حسابرسی فقط خواندنی برای مدیر
680 // ============================================================
681 _renderAuditCard() {
682 return `
683 <div class="card settings-card">
684 <div class="settings-card-header">
685 <div class="settings-card-icon">📋</div>
686 <div>
687 <h3 class="settings-card-title">ردپای حسابرسی</h3>
688 <p class="settings-card-desc">نمایش رویدادهای مالی ثبت‌شده از زمان فعال‌شدن ممیزی؛ سوابق قدیمی به‌طور خودکار ممیزی نمی‌شوند</p>
689 </div>
690 </div>
691 <button class="btn btn-secondary" onclick="window.SettingsView.openAuditTrail()">
692 مشاهده رویدادهای شرکت فعال
693 </button>
694 </div>
695 `;
696 }
697
698 async openAuditTrail() {
699 if (!Auth.isAdmin()) { Toast.error('دسترسی فقط برای مدیر مجاز است'); return; }
700 try {
701 const events = await AuditService.list({ limit: 100 });
702 const labels = {
703 journal_posted: 'ثبت سند مالی',
704 journal_reversed: 'برگشت سند مالی',
705 commercial_journal_posted: 'ثبت رویداد تجاری',
706 period_opened: 'ایجاد دوره مالی',
707 period_closed: 'بستن دوره مالی',
708 draft_created: 'ساخت پیش‌نویس',
709 draft_updated: 'ویرایش پیش‌نویس',
710 draft_posted: 'ثبت قطعی پیش‌نویس',
711 draft_discarded: 'حذف پیش‌نویس',
712 backup_restored: 'بازیابی فایل پشتیبان'
713 };
714 const list = events.map(event => `
715 <div style="padding:10px 0;border-bottom:1px solid var(--border)">
716 <strong>${this._esc(labels[event.eventType] || event.eventType)}</strong>
717 <div style="color:var(--text-muted);font-size:12px">
718 سند: ${this._esc(event.sourceId)} | کاربر: ${this._esc(event.actorId)}
719 </div>
720 <div style="color:var(--text-muted);font-size:11px">
721 ${this._esc(event.businessDate || '')} — ${this._esc(event.occurredAtUtc)}
722 </div>
723 </div>
724 `).join('');
725 Modal.open({ title: 'ردپای حسابرسی شرکت فعال',
726 body: `<p style="font-size:12px;color:var(--text-muted)">تا ۱۰۰ رویداد اخیر؛ فقط از زمان فعال‌سازی ممیزی. اطلاعاتی که پیش از آن ثبت شده‌اند، سابقه ممیزی ساختگی ندارند.</p>${list || '<p>رویدادی یافت نشد.</p>'}`,
727 footer: '<button class="btn" onclick="FINORA.Modal.close()">بستن</button>',
728 size: 'lg' });
729 } catch (err) {
730 Toast.error('نمایش ردپای حسابرسی ناموفق بود: ' + err.message);
731 }
732 }
733
734 // ============================================================
735 // کارت آمار
736 // ============================================================
737 _renderStatsCard() {
738 const s = cache.stats;
739 const items = [
740 { label: 'کالا و خدمات', value: s.products || 0, icon: '📦' },
741 { label: 'اشخاص', value: s.contacts || 0, icon: '👥' },
742 { label: 'فاکتورها', value: s.invoices || 0, icon: '🧾' },
743 { label: 'چک‌ها', value: s.cheques || 0, icon: '💳' },
744 { label: 'حساب‌ها', value: s.accounts || 0, icon: '🏦' },
745 { label: 'تراکنش‌ها', value: s.transactions || 0, icon: '💸' }
746 ];
747 return `
748 <div class="card settings-card">
749 <div class="settings-card-header">
750 <div class="settings-card-icon" style="background:linear-gradient(135deg,#0ea5e9,#0369a1)">📊</div>
751 <div>
752 <h3 class="settings-card-title">آمار داده‌ها</h3>
753 <p class="settings-card-desc">خلاصه‌ی داده‌های ذخیره‌شده در سیستم</p>
754 </div>
755 </div>
756 <div class="stats-grid">
757 ${items.map(i => `
758 <div class="stat-mini">
759 <div style="font-size:18px;margin-bottom:4px">${i.icon}</div>
760 <div style="font-size:18px;font-weight:800;color:var(--primary)">${Formatters.number(i.value)}</div>
761 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${i.label}</div>
762 </div>
763 `).join('')}
764 </div>
765 </div>
766 `;
767 }
768
769 // ============================================================
770 // کارت تم
771 // ============================================================
772 _renderThemeCard() {
773 const current = Theme.current();
774 return `
775 <div class="card settings-card">
776 <div class="settings-card-header">
777 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">🎨</div>
778 <div>
779 <h3 class="settings-card-title">ظاهر و تم</h3>
780 <p class="settings-card-desc">حالت نمایش برنامه</p>
781 </div>
782 </div>
783 <div style="display:flex;gap:10px;margin-top:8px">
784 <button class="btn ${current === 'light' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('light')">☀️ روشن</button>
785 <button class="btn ${current === 'dark' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('dark')">🌙 تاریک</button>
786 </div>
787 </div>
788 `;
789 }
790
791 // ============================================================
792 // کارت درباره
793 // ============================================================
794 _renderAboutCard() {
795 return `
796 <div class="card settings-card">
797 <div class="settings-card-header">
798 <div class="settings-card-icon">ℹ️</div>
799 <div>
800 <h3 class="settings-card-title">درباره فینورا پرو</h3>
801 <p class="settings-card-desc">نسخه ۲.۰.۳</p>
802 </div>
803 </div>
804 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
805 <div><strong>طراح و توسعه‌دهنده:</strong> داوود مهربان</div>
806 <div><strong>تماس:</strong> <span dir="ltr">0912-437-6991</span></div>
807 <div style="margin-top:8px;padding-top:10px;border-top:1px dashed var(--border)">
808 <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>
809 </div>
810 </div>
811 </div>
812 `;
813 }
814
815 _renderLicenseCard() {
816 const state = LicenseService.status();
817 const mode = state.mode === 'licensed' ? 'مجوز امضاشده معتبر' :
818 state.mode === 'license-invalid' ? 'مجوز نامعتبر یا منقضی' : 'نسخه آزمایشی';
819 const machine = this._esc(LicenseService.installationId() || 'نامشخص');
820 const readiness = LicenseService.hasTrustedIssuer()
821 ? 'کلید عمومی صادرکننده فعال است'
822 : 'فعلاً کلید عمومی صدور مجوز در نسخه نصب‌شده تنظیم نشده است';
823 return `
824 <div class="card settings-card">
825 <div class="settings-card-header">
826 <div class="settings-card-icon">🔐</div>
827 <div>
828 <h3 class="settings-card-title">مجوز آفلاین نرم‌افزار</h3>
829 <p class="settings-card-desc">وضعیت: ${this._esc(mode)} — ${state.readOnly ? 'فقط مشاهده' : 'قابل ثبت'}</p>
830 </div>
831 </div>
832 <div style="font-size:12px;line-height:2">
833 <div>شناسه نصب: <code dir="ltr" style="overflow-wrap:anywhere">${machine}</code></div>
834 <div>${this._esc(readiness)}</div>
835 </div>
836 <button class="btn btn-secondary" onclick="window.SettingsView.openSignedLicenseModal()" ${LicenseService.hasTrustedIssuer() ? '' : 'disabled'}>
837 فعال‌سازی با مجوز امضاشده
838 </button>
839 <small style="display:block;margin-top:8px">برای فعال‌سازی، مجوز صادرشده مخصوص همین شناسه نصب لازم است؛ اطلاعات حسابداری در صورت انقضا حذف نمی‌شود.</small>
840 </div>
841 `;
842 }
843
844 openSignedLicenseModal() {
845 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
846 if (!LicenseService.hasTrustedIssuer()) {
847 Toast.error('کلید معتبر صادرکننده در این نسخه نصب نشده است'); return;
848 }
849 Modal.open({
850 title: 'فعال‌سازی مجوز آفلاین',
851 body: '<label for="signedLicenseToken">متن JSON مجوز امضاشده</label>' +
852 '<textarea id="signedLicenseToken" class="form-control" rows="8" spellcheck="false" dir="ltr"></textarea>' +
853 '<p style="font-size:12px">امضای دیجیتال و شناسه دستگاه پیش از هر تغییر اعتبارسنجی می‌شوند.</p>',
854 footer: '<button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>' +
855 '<button class="btn" onclick="window.SettingsView.applySignedLicense()">اعتبارسنجی و فعال‌سازی</button>',
856 size: 'md'
857 });
858 }
859
860 async applySignedLicense() {
861 if (!Auth.isAdmin()) { Toast.error('فقط مدیر مجاز است'); return; }
862 const token = document.getElementById('signedLicenseToken')?.value;
863 if (!token?.trim()) { Toast.error('متن مجوز خالی است'); return; }
864 try {
865 await LicenseService.activateSignedLicense(token.trim());
866 Modal.close();
867 const grid = document.querySelector('.settings-grid');
868 if (grid) grid.innerHTML = this._renderAllCards();
869 Toast.success('مجوز آفلاین معتبر با موفقیت فعال شد');
870 } catch (error) {
871 Toast.error(error.message);
872 }
873 }
874
875 _renderAllCards() {
876 return this._renderCompanyCard()
877 + this._renderInvoiceSettingsCard()
878 + this._renderExcelCard()
879 + this._renderShortcutsCard()
880 + this._renderBackupCard()
881 + (Auth.isAdmin() ? this._renderHolooBackupCard() : '')
882 + (Auth.isAdmin() ? this._renderLicenseCard() : '')
883 + this._renderStatsCard()
884 + (Auth.isAdmin() ? this._renderHealthCard() : '')
885 + (Auth.isAdmin() ? this._renderAuditCard() : '')
886 + this._renderThemeCard()
887 + this._renderAboutCard();
888 }
889
890 // ============================================================
891 // فرم اطلاعات شرکت
892 // ============================================================
893 async openCompanySwitcher() {
894 const companies = await globalThis.FINORA.Company.list();
895 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('');
896 Modal.open({ title: 'تغییر شرکت فعال', body: body || '<div class="empty-mini">شرکتی یافت نشد</div>', footer: '', size: 'sm' });
897 }
898
899 async selectCompany(id) {
900 await globalThis.FINORA.Company.select(id); Modal.close(); await this.reload(); Toast.success('شرکت فعال تغییر کرد');
901 }
902
903 async createCompany() {
904 const name = prompt('نام شرکت جدید را وارد کنید:'); if (!name?.trim()) return;
905 const company = await globalThis.FINORA.Company.create({ name: name.trim(), entityType: 'legal' });
906 await globalThis.FINORA.Company.select(company.id); await this.reload(); Toast.success('شرکت جدید ایجاد شد');
907 }
908
909 openCompanyModal() {
910 const c = cache.company;
911 const body = `
912 <div class="form-row">
913 <div class="form-group">
914 <label class="form-label">نوع شخص</label>
915 <select class="form-control" id="coEntityType">
916 <option value="legal" ${c.entityType === 'legal' ? 'selected' : ''}>حقوقی</option>
917 <option value="natural" ${c.entityType === 'natural' ? 'selected' : ''}>حقیقی</option>
918 </select>
919 </div>
920 <div class="form-group">
921 <label class="form-label">نام شرکت / فروشگاه <span class="req">*</span></label>
922 <input type="text" class="form-control" id="coName" value="${this._esc(c.name)}" />
923 </div>
924 </div>
925 <div class="form-row">
926 <div class="form-group">
927 <label class="form-label">شناسه ملی / کد ملی</label>
928 <input type="text" class="form-control" id="coNationalId" value="${this._esc(c.nationalId)}" />
929 </div>
930 <div class="form-group">
931 <label class="form-label">کد اقتصادی</label>
932 <input type="text" class="form-control" id="coEconomicCode" value="${this._esc(c.economicCode)}" />
933 </div>
934 </div>
935 <div class="form-row">
936 <div class="form-group">
937 <label class="form-label">شماره ثبت</label>
938 <input type="text" class="form-control" id="coRegNumber" value="${this._esc(c.regNumber)}" />
939 </div>
940 <div class="form-group">
941 <label class="form-label">کد پستی</label>
942 <input type="text" class="form-control" id="coPostalCode" value="${this._esc(c.postalCode)}" />
943 </div>
944 </div>
945 <div class="form-row">
946 <div class="form-group">
947 <label class="form-label">تلفن</label>
948 <input type="tel" class="form-control" id="coPhone" value="${this._esc(c.phone)}" />
949 </div>
950 <div class="form-group">
951 <label class="form-label">موبایل</label>
952 <input type="tel" class="form-control" id="coMobile" value="${this._esc(c.mobile)}" />
953 </div>
954 </div>
955 <div class="form-group">
956 <label class="form-label">نشانی</label>
957 <textarea class="form-control" id="coAddress" rows="2">${this._esc(c.address)}</textarea>
958 </div>
959 <div class="form-group">
960 <label class="form-label">پاورقی فاکتور</label>
961 <textarea class="form-control" id="coFooter" rows="2" placeholder="مثلاً: از خرید شما سپاسگزاریم">${this._esc(c.footer)}</textarea>
962 </div>
963 `;
964 const footer = `
965 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
966 <button class="btn" onclick="window.SettingsView.saveCompany()">💾 ذخیره</button>
967 `;
968 Modal.open({ title: 'اطلاعات شرکت', body, footer, size: 'md' });
969 }
970
971 async saveCompany() {
972 const data = {
973 name: document.getElementById('coName').value,
974 entityType: document.getElementById('coEntityType').value,
975 nationalId: document.getElementById('coNationalId').value,
976 economicCode: document.getElementById('coEconomicCode').value,
977 regNumber: document.getElementById('coRegNumber').value,
978 postalCode: document.getElementById('coPostalCode').value,
979 phone: document.getElementById('coPhone').value,
980 mobile: document.getElementById('coMobile').value,
981 address: document.getElementById('coAddress').value,
982 footer: document.getElementById('coFooter').value
983 };
984 if (!data.name.trim()) { Toast.warning('نام الزامی است'); return; }
985 try {
986 await SettingsController.saveCompanyInfo(data);
987 Toast.success('اطلاعات ذخیره شد');
988 Modal.close();
989 await this.reload();
990 const grid = document.querySelector('.settings-grid');
991 if (grid) grid.innerHTML = this._renderAllCards();
992 } catch (err) {
993 Toast.error('خطا: ' + err.message);
994 }
995 }
996
997 // ============================================================
998 // بکاپ JSON
999 // ============================================================
1000 async downloadBackup() {
1001 try {
1002 Toast.info('در حال آماده‌سازی بکاپ...');
1003 const result = await SettingsController.downloadBackup();
1004 Toast.success(`بکاپ دانلود شد (${result.filename})`, 'موفق');
1005 } catch (err) {
1006 Toast.error('خطا در بکاپ: ' + err.message);
1007 }
1008 }
1009
1010 openRestoreModal() {
1011 const body = `
1012 <div class="backup-warning" style="margin-bottom:14px">
1013 ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، فقط رکوردهای دارای شناسه یکسان بازنویسی می‌شوند و سایر داده‌ها حذف نمی‌شوند.
1014 </div>
1015
1016 <div class="form-group">
1017 <label class="form-label">فایل بکاپ رمزگذاری‌شده یا JSON</label>
1018 <input type="file" class="form-control" id="restoreFile" accept=".json,.fbackup,application/json,application/octet-stream" />
1019 </div>
1020
1021 <div class="form-group">
1022 <label class="form-label">حالت بازیابی</label>
1023 <select class="form-control" id="restoreMode">
1024 <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
1025 <option value="replace">🔄 بازنویسی شناسه‌های یکسان (Replace) — بدون حذف سایر رکوردها</option>
1026 </select>
1027 </div>
1028 `;
1029 const footer = `
1030 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
1031 <button class="btn" onclick="window.SettingsView.restoreBackup()">📤 بازیابی</button>
1032 `;
1033 Modal.open({ title: 'بازیابی از بکاپ', body, footer, size: 'md' });
1034 }
1035
1036 async restoreBackup() {
1037 const fileInput = document.getElementById('restoreFile');
1038 const file = fileInput.files[0];
1039 if (!file) { Toast.warning('فایل بکاپ رو انتخاب کنید'); return; }
1040
1041 const mode = document.getElementById('restoreMode').value;
1042
1043 try {
1044 Toast.info('در حال بازیابی...');
1045 const content = await SettingsController.readFileAsText(file);
1046 const counts = await SettingsController.importBackup(content, { mode });
1047 Modal.close();
1048 Toast.success(`بازیابی انجام شد: ${counts.added} مورد اضافه، ${counts.skipped} مورد skip`);
1049 setTimeout(() => location.reload(), 1500);
1050 } catch (err) {
1051 Toast.error('خطا: ' + err.message);
1052 }
1053 }
1054
1055 // ============================================================
1056 // پاک کردن کامل
1057 // ============================================================
1058 openWipeModal() {
1059 const body = `
1060 <div style="text-align:center;padding:10px 0">
1061 <div style="font-size:48px;margin-bottom:12px">⚠️</div>
1062 <h3 style="color:var(--danger);margin-bottom:8px">پاک کردن کامل داده‌ها</h3>
1063 <p style="color:var(--text-muted);font-size:13px;line-height:1.8;margin-bottom:16px">
1064 این عمل همه‌ی کالاها، اشخاص، فاکتورها، چک‌ها، تراکنش‌ها و تنظیمات رو برای همیشه پاک می‌کند.
1065 <br><strong>قابل بازگشت نیست!</strong>
1066 </p>
1067 <p style="font-size:12px;color:var(--danger);margin-bottom:16px">
1068 لطفاً برای تأیید، کلمه‌ی <code style="background:var(--danger);color:#fff;padding:2px 8px;border-radius:4px">حذف</code> رو تایپ کنید
1069 </p>
1070 <input type="text" class="form-control" id="wipeConfirm" placeholder="حذف" style="text-align:center;max-width:200px;margin:0 auto" />
1071 </div>
1072 `;
1073 const footer = `
1074 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
1075 <button class="btn btn-danger" onclick="window.SettingsView.confirmWipe()">🗑️ پاک کن</button>
1076 `;
1077 Modal.open({ title: 'تأیید پاک کردن', body, footer, size: 'sm' });
1078 }
1079
1080 async confirmWipe() {
1081 const confirmText = document.getElementById('wipeConfirm').value.trim();
1082 if (confirmText !== 'حذف') {
1083 Toast.warning('متن تأیید اشتباه است');
1084 return;
1085 }
1086 try {
1087 await SettingsController.wipeAll();
1088 Toast.success('همه‌ی داده‌ها پاک شد');
1089 setTimeout(() => location.reload(), 800);
1090 } catch (err) {
1091 Toast.error('خطا: ' + err.message);
1092 }
1093 }
1094
1095 // ============================================================
1096 // Theme
1097 // ============================================================
1098 setTheme(theme) {
1099 Theme.apply(theme);
1100 const grid = document.querySelector('.settings-grid');
1101 if (grid) grid.innerHTML = this._renderAllCards();
1102 }
1103
1104 _esc(s) {
1105 if (!s) return '';
1106 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
1107 }
1108 }
1109
1110 export const SettingsView = new SettingsViewImpl();
1111 window.SettingsView = SettingsView;