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

planning/holoo-execution-20261013
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 811 lines 37.1 KB
Raw
1 // ============================================================
2 // SettingsView — صفحه‌ی تنظیمات، بکاپ، شرکت و Excel
3 // ============================================================
4
5 import { SettingsController } from '../controllers/SettingsController.js';
6 import { StorageService } from '../core/StorageService.js';
7 import { Theme } from '../core/Theme.js';
8 import { KeyboardShortcuts } from '../core/KeyboardShortcuts.js';
9 import { Modal } from '../core/Modal.js';
10 import { Toast } from '../core/Toast.js';
11 import { Formatters } from '../utils/Formatters.js';
12 import { Auth } from '../core/Auth.js';
13 import { ExcelController } from '../controllers/ExcelController.js';
14
15 let cache = { company: {}, stats: {}, invoiceSettings: { numberingMode: 'auto', nextNumber: 1 } };
16
17 class SettingsViewImpl {
18 async render() {
19 await this.reload();
20 return `
21 <div class="page-title">
22 <h2>تنظیمات</h2>
23 <p>مدیریت اطلاعات شرکت، پشتیبان‌گیری، Excel و تنظیمات سیستم</p>
24 </div>
25
26 <div class="settings-grid">
27 ${this._renderCompanyCard()}
28 ${this._renderInvoiceSettingsCard()}
29 ${this._renderExcelCard()}
30 ${this._renderShortcutsCard()}
31 ${this._renderBackupCard()}
32 ${this._renderStatsCard()}
33 ${this._renderThemeCard()}
34 ${this._renderAboutCard()}
35 </div>
36 `;
37 }
38
39 onMount() {
40 window.SettingsView = this;
41 }
42
43 async reload() {
44 const results = await Promise.allSettled([
45 SettingsController.getCompanyInfo(),
46 SettingsController.getInvoiceSettings(),
47 this._collectStats()
48 ]);
49 const defaults = [{}, { numberingMode: 'auto', nextNumber: 1 }, {}];
50 const values = results.map((result, index) => {
51 if (result.status === 'fulfilled') return result.value;
52 console.error('Settings load failed:', index, result.reason);
53 Toast.error('بخشی از تنظیمات بارگذاری نشد: ' + (result.reason?.message || 'خطای نامشخص'));
54 return defaults[index];
55 });
56 [cache.company, cache.invoiceSettings, cache.stats] = values;
57 }
58
59 async _collectStats() {
60 const user = Auth.current();
61 if (!user) return {};
62 const stores = ['products', 'contacts', 'invoices', 'cheques', 'treasury'];
63 const stats = {};
64 for (const s of stores) {
65 try {
66 const list = await StorageService.getByOwner(s, user.id);
67 if (s === 'treasury') {
68 stats.accounts = list.filter(x => x.recordType === 'account').length;
69 stats.transactions = list.filter(x => x.recordType === 'transaction').length;
70 } else {
71 stats[s] = list.length;
72 }
73 } catch (e) {
74 stats[s] = 0;
75 }
76 }
77 return stats;
78 }
79
80 // ============================================================
81 // کارت اطلاعات شرکت
82 // ============================================================
83 _renderCompanyCard() {
84 const c = cache.company;
85 return `
86 <div class="card settings-card">
87 <div class="settings-card-header">
88 <div class="settings-card-icon">🏢</div>
89 <div>
90 <h3 class="settings-card-title">اطلاعات شرکت / فروشگاه</h3>
91 <p class="settings-card-desc">این اطلاعات در سربرگ فاکتورهای چاپی نمایش داده می‌شود</p>
92 </div>
93 </div>
94 ${c.name ? `
95 <div class="company-preview">
96 <div style="font-weight:700;font-size:14px">${this._esc(c.name)}</div>
97 ${c.nationalId ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:3px">شناسه ملی: ${Formatters.toPersianDigits(c.nationalId)}</div>` : ''}
98 ${c.address ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">${this._esc(c.address)}</div>` : ''}
99 ${c.phone ? `<div style="font-size:11.5px;color:var(--text-muted);margin-top:2px">تلفن: ${Formatters.phone(c.phone)}</div>` : ''}
100 </div>
101 ` : `
102 <div class="empty-mini">هنوز اطلاعاتی وارد نشده</div>
103 `}
104 <div style="display:flex;gap:8px;flex-wrap:wrap">
105 <button class="btn" onclick="window.SettingsView.openCompanyModal()">${c.name ? '✏️ ویرایش اطلاعات' : '➕ وارد کردن اطلاعات'}</button>
106 <button class="btn" onclick="window.SettingsView.openCompanySwitcher()">🔄 تغییر شرکت</button>
107 ${Auth.isAdmin() ? '<button class="btn" onclick="window.SettingsView.createCompany()">➕ شرکت جدید</button>' : ''}
108 </div>
109 </div>
110 `;
111 }
112
113 _renderInvoiceSettingsCard() {
114 const s = cache.invoiceSettings || { numberingMode: 'auto', nextNumber: 1 };
115 return `
116 <div class="card settings-card">
117 <div class="settings-card-header">
118 <div class="settings-card-icon">🧾</div>
119 <div>
120 <h3 class="settings-card-title">تنظیمات فاکتور</h3>
121 <p class="settings-card-desc">نحوه شماره‌گذاری فاکتورهای جدید</p>
122 </div>
123 </div>
124 <div class="form-group">
125 <label class="form-label">نحوه شماره‌گذاری</label>
126 <select class="form-control" id="invoiceNumberingMode">
127 <option value="auto" ${s.numberingMode === 'auto' ? 'selected' : ''}>خودکار</option>
128 <option value="manual" ${s.numberingMode === 'manual' ? 'selected' : ''}>دستی</option>
129 </select>
130 </div>
131 <div class="form-group">
132 <label class="form-label">شماره بعدی فاکتور</label>
133 <input class="form-control" id="invoiceNextNumber" type="number" min="1" value="${Number(s.nextNumber) || 1}" />
134 </div>
135 <button class="btn" onclick="window.SettingsView.saveInvoiceSettings()">💾 ذخیره تنظیمات فاکتور</button>
136 </div>
137 `;
138 }
139
140 async saveInvoiceSettings() {
141 const numberingMode = document.getElementById('invoiceNumberingMode').value;
142 const nextNumber = Number(document.getElementById('invoiceNextNumber').value);
143 if (!Number.isInteger(nextNumber) || nextNumber < 1) {
144 Toast.warning('شماره بعدی باید عدد صحیح بزرگ‌تر از صفر باشد');
145 return;
146 }
147 try {
148 cache.invoiceSettings = await SettingsController.saveInvoiceSettings({ numberingMode, nextNumber });
149 Toast.success('تنظیمات فاکتور ذخیره شد');
150 } catch (err) {
151 console.error('Invoice settings save failed:', err);
152 Toast.error('خطا در ذخیره تنظیمات فاکتور: ' + err.message);
153 }
154 }
155
156 // ============================================================
157 // کارت Excel (جدید)
158 // ============================================================
159 _renderExcelCard() {
160 const s = cache.stats;
161 return `
162 <div class="card settings-card" style="border-color:#bbf7d0;background:linear-gradient(135deg,#f0fdf4,#f8fafc)">
163 <div class="settings-card-header">
164 <div class="settings-card-icon" style="background:linear-gradient(135deg,#16a34a,#15803d)">📊</div>
165 <div>
166 <h3 class="settings-card-title">Excel — خروجی و ورودی</h3>
167 <p class="settings-card-desc">داده‌ها را به Excel ببر یا از Excel بیار</p>
168 </div>
169 </div>
170
171 <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">
172 <strong>💡 نکته:</strong> از این بخش می‌تونی کل داده‌ها رو در یه فایل Excel بگیری، یا از یه فایل Excel (که قبلاً آماده کردی) کالا و اشخاص اضافه کنی.
173 </div>
174
175 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px">
176 <button class="btn" style="background:linear-gradient(135deg,#16a34a,#15803d)" onclick="window.SettingsView.exportAllExcel()">
177 📥 خروجی کامل (Excel)
178 </button>
179 <button class="btn btn-secondary" onclick="window.SettingsView.openExportSectionModal()">
180 🎯 خروجی انتخابی
181 </button>
182 </div>
183
184 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
185 <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📤 ورود از Excel</div>
186 <div style="display:flex;gap:10px;flex-wrap:wrap">
187 <button class="btn btn-secondary" onclick="window.SettingsView.importProductsExcel()">
188 📦 ورود کالاها
189 </button>
190 <button class="btn btn-secondary" onclick="window.SettingsView.importContactsExcel()">
191 👥 ورود اشخاص
192 </button>
193 </div>
194 </div>
195
196 <div style="margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
197 <div style="font-size:12.5px;font-weight:700;margin-bottom:10px;color:#166534">📄 قالب‌های نمونه</div>
198 <div style="display:flex;gap:10px;flex-wrap:wrap">
199 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadProductsTemplate()">
200 📋 قالب کالاها
201 </button>
202 <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.downloadContactsTemplate()">
203 📋 قالب اشخاص
204 </button>
205 </div>
206 </div>
207 </div>
208 `;
209 }
210
211 async exportAllExcel() {
212 try {
213 Toast.info('در حال آماده‌سازی فایل Excel...');
214 const result = await ExcelController.exportAll();
215 Toast.success(`فایل Excel با ${Formatters.toPersianDigits(result.sheets)} شیت دانلود شد`);
216 } catch (err) {
217 console.error(err);
218 Toast.error('خطا در خروجی: ' + err.message);
219 }
220 }
221
222 openExportSectionModal() {
223 const body = `
224 <p style="font-size:13px;color:var(--text-muted);margin-bottom:14px">کدوم بخش رو می‌خوای به Excel ببری؟</p>
225 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
226 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('products')">
227 <div style="font-size:22px">📦</div>
228 <div style="font-size:12.5px">کالاها</div>
229 </button>
230 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('contacts')">
231 <div style="font-size:22px">👥</div>
232 <div style="font-size:12.5px">اشخاص</div>
233 </button>
234 <button class="btn btn-secondary" style="min-height:80px;flex-direction:column;gap:6px" onclick="window.SettingsView._exportSection('invoices')">
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('cheques')">
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('expenses')">
243 <div style="font-size:22px">💰</div>
244 <div style="font-size:12.5px">هزینه و درآمد</div>
245 </button>
246 </div>
247 `;
248 const footer = `<button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>`;
249 Modal.open({ title: '🎯 خروجی انتخابی به Excel', body, footer, size: 'md' });
250 }
251
252 async _exportSection(section) {
253 try {
254 const result = await ExcelController.exportSection(section);
255 Toast.success(`فایل دانلود شد (${Formatters.number(result.count)} مورد)`);
256 Modal.close();
257 } catch (err) {
258 Toast.error('خطا: ' + err.message);
259 }
260 }
261
262 // ============================================================
263 // ورودی از Excel
264 // ============================================================
265 importProductsExcel() {
266 const input = document.createElement('input');
267 input.type = 'file';
268 input.accept = '.xlsx,.xls';
269 input.onchange = async (e) => {
270 const file = e.target.files[0];
271 if (!file) return;
272 await this._handleImportFile(file, 'products');
273 };
274 input.click();
275 }
276
277 importContactsExcel() {
278 const input = document.createElement('input');
279 input.type = 'file';
280 input.accept = '.xlsx,.xls';
281 input.onchange = async (e) => {
282 const file = e.target.files[0];
283 if (!file) return;
284 await this._handleImportFile(file, 'contacts');
285 };
286 input.click();
287 }
288
289 async _handleImportFile(file, kind) {
290 try {
291 Toast.info('در حال خواندن فایل...');
292 const preview = await ExcelController.previewFile(file);
293
294 const kindLabel = kind === 'products' ? 'کالاها' : 'اشخاص';
295 const sheetsHtml = preview.sheets.map(s => `
296 <div style="padding:8px 12px;background:var(--bg);border-radius:8px;margin-bottom:6px;font-size:12.5px">
297 <strong>${this._esc(s.name)}</strong>
298 <span style="color:var(--text-muted);margin-right:6px">(${Formatters.number(s.count)} سطر)</span>
299 </div>
300 `).join('');
301
302 const body = `
303 <p style="font-size:13px;color:var(--text-muted);margin-bottom:12px">
304 فایل <strong>${this._esc(file.name)}</strong> خونده شد. شیت‌های موجود:
305 </p>
306 ${sheetsHtml}
307 <div class="form-group" style="margin-top:14px">
308 <label class="form-label">حالت ورود</label>
309 <select class="form-control" id="importMode">
310 <option value="merge">🔀 ادغام (Merge) — فقط موارد جدید اضافه می‌شن</option>
311 <option value="replace">🔄 جایگزینی (Replace) — همه‌ی ${kindLabel} فعلی پاک و از فایل جایگزین می‌شن</option>
312 </select>
313 </div>
314 `;
315 const footer = `
316 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
317 <button class="btn btn-success" onclick="window.SettingsView._confirmImport(${JSON.stringify(kind).replace(/"/g, "'")}, '${this._esc(file.name)}')">✅ شروع ایمپورت</button>
318 `;
319 Modal.open({ title: `📤 ورود ${kindLabel} از Excel`, body, footer, size: 'md' });
320
321 // ذخیره‌ی موقت داده
322 window.__importRawData = preview.raw;
323 window.__importKind = kind;
324 } catch (err) {
325 console.error(err);
326 Toast.error('خطا: ' + err.message);
327 }
328 }
329
330 async _confirmImport(kind, fileName) {
331 const mode = document.getElementById('importMode').value;
332 const rawData = window.__importRawData;
333
334 if (!rawData) {
335 Toast.error('داده‌ای برای ایمپورت نیست');
336 return;
337 }
338
339 try {
340 Toast.info('در حال ایمپورت...');
341 let result;
342 if (kind === 'products') {
343 result = await ExcelController.importProducts(rawData, { mode });
344 } else {
345 result = await ExcelController.importContacts(rawData, { mode });
346 }
347
348 Modal.close();
349 Toast.success(`ایمپورت انجام شد: ${Formatters.number(result.added)} اضافه، ${Formatters.number(result.skipped)} رد شده`);
350
351 // رفرش KPI ها
352 await this.reload();
353 const grid = document.querySelector('.settings-grid');
354 if (grid) grid.innerHTML = this._renderAllCards();
355 } catch (err) {
356 console.error(err);
357 Toast.error('خطا در ایمپورت: ' + err.message);
358 } finally {
359 window.__importRawData = null;
360 window.__importKind = null;
361 }
362 }
363
364 downloadProductsTemplate() {
365 ExcelController.downloadProductsTemplate();
366 Toast.success('قالب کالاها دانلود شد');
367 }
368
369 downloadContactsTemplate() {
370 ExcelController.downloadContactsTemplate();
371 Toast.success('قالب اشخاص دانلود شد');
372 }
373
374 // ============================================================
375 // کارت میانبرهای صفحه‌کلید
376 // ============================================================
377 _renderShortcutsCard() {
378 const s = KeyboardShortcuts.settings;
379
380 const toggle = (id, checked, label, hint) => `
381 <label style="display:flex;align-items:flex-start;gap:10px;padding:9px 0;cursor:pointer;border-bottom:1px solid var(--border)">
382 <input type="checkbox" id="${id}" ${checked ? 'checked' : ''} style="margin-top:3px;width:16px;height:16px;cursor:pointer" />
383 <div style="flex:1">
384 <div style="font-size:13px;font-weight:600">${label}</div>
385 <div style="font-size:11px;color:var(--text-muted);margin-top:2px;line-height:1.6">${hint}</div>
386 </div>
387 </label>
388 `;
389
390 return `
391 <div class="card settings-card" style="border-color:#ddd6fe;background:linear-gradient(135deg,#faf5ff,#f8fafc)">
392 <div class="settings-card-header">
393 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">⌨️</div>
394 <div>
395 <h3 class="settings-card-title">میانبرهای صفحه‌کلید</h3>
396 <p class="settings-card-desc">با این میانبرها کار با برنامه سریع‌تر می‌شود</p>
397 </div>
398 </div>
399
400 ${toggle('scEnabled', s.enabled, 'فعال بودن میانبرها', 'کلاً همه‌ی میانبرهای زیر رو روشن یا خاموش می‌کند')}
401 ${toggle('scEnterConfirms', s.enterConfirms, 'تأیید با Enter', 'وقتی توی فرم هستید، Enter مثل دکمه‌ی ذخیره عمل می‌کند. Ctrl+Enter هم توی همه‌ی فیلدها کار می‌کند')}
402 ${toggle('scEscapeCloses', s.escapeCloses, 'بستن با Escape', 'فشار دادن Escape، مودال باز را می‌بندد')}
403 ${toggle('scCtrlSaves', s.ctrlSaves, 'ذخیره با Ctrl+S', 'داخل مودال‌ها، Ctrl+S فرم را ذخیره می‌کند')}
404 ${toggle('scPlusMinusZeros', s.plusMinusZeros, 'ضریب سریع صفر (+ و -)', 'روی فیلدهای مبلغ، کلید + صفر اضافه و کلید − صفر کم می‌کند')}
405
406 <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:14px;padding-top:14px;border-top:1px dashed var(--border)">
407 <div class="form-group" style="margin-bottom:0">
408 <label class="form-label">تعداد صفرهای کلید +</label>
409 <input type="text" inputmode="numeric" class="form-control" id="scPlusZeros" value="${Formatters.toPersianDigits(s.plusZeros)}" />
410 </div>
411 <div class="form-group" style="margin-bottom:0">
412 <label class="form-label">تعداد صفرهای کلید −</label>
413 <input type="text" inputmode="numeric" class="form-control" id="scMinusZeros" value="${Formatters.toPersianDigits(s.minusZeros)}" />
414 </div>
415 </div>
416
417 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
418 <button class="btn" onclick="window.SettingsView.saveShortcuts()">💾 ذخیره تنظیمات</button>
419 <button class="btn btn-secondary" onclick="window.SettingsView.resetShortcuts()">↺ بازگشت به پیش‌فرض</button>
420 </div>
421 </div>
422 `;
423 }
424
425 saveShortcuts() {
426 try {
427 const plusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scPlusZeros').value)) || 0;
428 const minusZeros = parseInt(Formatters.toLatinDigits(document.getElementById('scMinusZeros').value)) || 0;
429
430 const settings = {
431 enabled: document.getElementById('scEnabled').checked,
432 enterConfirms: document.getElementById('scEnterConfirms').checked,
433 escapeCloses: document.getElementById('scEscapeCloses').checked,
434 ctrlSaves: document.getElementById('scCtrlSaves').checked,
435 plusMinusZeros: document.getElementById('scPlusMinusZeros').checked,
436 plusZeros: Math.max(0, Math.min(12, plusZeros)),
437 minusZeros: Math.max(0, Math.min(12, minusZeros))
438 };
439
440 KeyboardShortcuts.saveSettings(settings);
441 Toast.success('تنظیمات میانبرهای صفحه‌کلید ذخیره شد');
442 } catch (err) {
443 Toast.error('خطا: ' + err.message);
444 }
445 }
446
447 resetShortcuts() {
448 Modal.confirm({
449 title: 'بازگشت به پیش‌فرض',
450 message: 'آیا می‌خواهید همه‌ی تنظیمات میانبرهای صفحه‌کلید به حالت پیش‌فرض برگردد؟',
451 confirmText: 'بازگردان',
452 onConfirm: () => {
453 KeyboardShortcuts.resetSettings();
454 Toast.success('تنظیمات به حالت پیش‌فرض برگشت');
455 const grid = document.querySelector('.settings-grid');
456 if (grid) grid.innerHTML = this._renderAllCards();
457 }
458 });
459 }
460
461 // ============================================================
462 // کارت بکاپ
463 // ============================================================
464 _renderBackupCard() {
465 return `
466 <div class="card settings-card" style="border-color:#bfdbfe;background:linear-gradient(135deg,#eff6ff,#f8fafc)">
467 <div class="settings-card-header">
468 <div class="settings-card-icon" style="background:linear-gradient(135deg,#3b82f6,#1e40af)">💾</div>
469 <div>
470 <h3 class="settings-card-title">پشتیبان‌گیری رمزگذاری‌شده</h3>
471 <p class="settings-card-desc">اطلاعات عملیاتی و حسابداری شرکت فعال؛ بازیابی بدون بازنویسی کاربران و تنظیمات سراسری</p>
472 </div>
473 </div>
474
475 <div class="backup-warning">
476 ⚠️ <strong>مهم:</strong> قبل از هر تغییر بزرگ در برنامه، حتماً بکاپ بگیرید.
477 </div>
478
479 <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px">
480 <button class="btn" onclick="window.SettingsView.downloadBackup()">
481 📥 دانلود فایل بکاپ
482 </button>
483 <button class="btn btn-secondary" onclick="window.SettingsView.openRestoreModal()">
484 📤 بازیابی از بکاپ
485 </button>
486 </div>
487
488 <div style="margin-top:16px;padding-top:14px;border-top:1px dashed var(--border)">
489 <button class="btn btn-danger btn-inline" style="font-size:12px;min-height:34px" onclick="window.SettingsView.openWipeModal()">
490 🗑️ پاک کردن کامل داده‌ها
491 </button>
492 <small style="color:var(--text-muted);font-size:11px;display:block;margin-top:6px">این عمل قابل بازگشت نیست، حتماً قبلش بکاپ بگیرید</small>
493 </div>
494 </div>
495 `;
496 }
497
498 // ============================================================
499 // کارت آمار
500 // ============================================================
501 _renderStatsCard() {
502 const s = cache.stats;
503 const items = [
504 { label: 'کالا و خدمات', value: s.products || 0, icon: '📦' },
505 { label: 'اشخاص', value: s.contacts || 0, icon: '👥' },
506 { label: 'فاکتورها', value: s.invoices || 0, icon: '🧾' },
507 { label: 'چک‌ها', value: s.cheques || 0, icon: '💳' },
508 { label: 'حساب‌ها', value: s.accounts || 0, icon: '🏦' },
509 { label: 'تراکنش‌ها', value: s.transactions || 0, icon: '💸' }
510 ];
511 return `
512 <div class="card settings-card">
513 <div class="settings-card-header">
514 <div class="settings-card-icon" style="background:linear-gradient(135deg,#0ea5e9,#0369a1)">📊</div>
515 <div>
516 <h3 class="settings-card-title">آمار داده‌ها</h3>
517 <p class="settings-card-desc">خلاصه‌ی داده‌های ذخیره‌شده در سیستم</p>
518 </div>
519 </div>
520 <div class="stats-grid">
521 ${items.map(i => `
522 <div class="stat-mini">
523 <div style="font-size:18px;margin-bottom:4px">${i.icon}</div>
524 <div style="font-size:18px;font-weight:800;color:var(--primary)">${Formatters.number(i.value)}</div>
525 <div style="font-size:11px;color:var(--text-muted);margin-top:2px">${i.label}</div>
526 </div>
527 `).join('')}
528 </div>
529 </div>
530 `;
531 }
532
533 // ============================================================
534 // کارت تم
535 // ============================================================
536 _renderThemeCard() {
537 const current = Theme.current();
538 return `
539 <div class="card settings-card">
540 <div class="settings-card-header">
541 <div class="settings-card-icon" style="background:linear-gradient(135deg,#8b5cf6,#6d28d9)">🎨</div>
542 <div>
543 <h3 class="settings-card-title">ظاهر و تم</h3>
544 <p class="settings-card-desc">حالت نمایش برنامه</p>
545 </div>
546 </div>
547 <div style="display:flex;gap:10px;margin-top:8px">
548 <button class="btn ${current === 'light' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('light')">☀️ روشن</button>
549 <button class="btn ${current === 'dark' ? '' : 'btn-secondary'}" onclick="window.SettingsView.setTheme('dark')">🌙 تاریک</button>
550 </div>
551 </div>
552 `;
553 }
554
555 // ============================================================
556 // کارت درباره
557 // ============================================================
558 _renderAboutCard() {
559 return `
560 <div class="card settings-card">
561 <div class="settings-card-header">
562 <div class="settings-card-icon">ℹ️</div>
563 <div>
564 <h3 class="settings-card-title">درباره فینورا پرو</h3>
565 <p class="settings-card-desc">نسخه ۲.۰.۳</p>
566 </div>
567 </div>
568 <div style="font-size:13px;line-height:1.9;color:var(--text-muted)">
569 <div><strong>طراح و توسعه‌دهنده:</strong> داوود مهربان</div>
570 <div><strong>تماس:</strong> <span dir="ltr">0912-437-6991</span></div>
571 <div style="margin-top:8px;padding-top:10px;border-top:1px dashed var(--border)">
572 <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>
573 </div>
574 </div>
575 </div>
576 `;
577 }
578
579 _renderAllCards() {
580 return this._renderCompanyCard()
581 + this._renderInvoiceSettingsCard()
582 + this._renderExcelCard()
583 + this._renderShortcutsCard()
584 + this._renderBackupCard()
585 + this._renderStatsCard()
586 + this._renderThemeCard()
587 + this._renderAboutCard();
588 }
589
590 // ============================================================
591 // فرم اطلاعات شرکت
592 // ============================================================
593 async openCompanySwitcher() {
594 const companies = await globalThis.FINORA.Company.list();
595 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('');
596 Modal.open({ title: 'تغییر شرکت فعال', body: body || '<div class="empty-mini">شرکتی یافت نشد</div>', footer: '', size: 'sm' });
597 }
598
599 async selectCompany(id) {
600 await globalThis.FINORA.Company.select(id); Modal.close(); await this.reload(); Toast.success('شرکت فعال تغییر کرد');
601 }
602
603 async createCompany() {
604 const name = prompt('نام شرکت جدید را وارد کنید:'); if (!name?.trim()) return;
605 const company = await globalThis.FINORA.Company.create({ name: name.trim(), entityType: 'legal' });
606 await globalThis.FINORA.Company.select(company.id); await this.reload(); Toast.success('شرکت جدید ایجاد شد');
607 }
608
609 openCompanyModal() {
610 const c = cache.company;
611 const body = `
612 <div class="form-row">
613 <div class="form-group">
614 <label class="form-label">نوع شخص</label>
615 <select class="form-control" id="coEntityType">
616 <option value="legal" ${c.entityType === 'legal' ? 'selected' : ''}>حقوقی</option>
617 <option value="natural" ${c.entityType === 'natural' ? 'selected' : ''}>حقیقی</option>
618 </select>
619 </div>
620 <div class="form-group">
621 <label class="form-label">نام شرکت / فروشگاه <span class="req">*</span></label>
622 <input type="text" class="form-control" id="coName" value="${this._esc(c.name)}" />
623 </div>
624 </div>
625 <div class="form-row">
626 <div class="form-group">
627 <label class="form-label">شناسه ملی / کد ملی</label>
628 <input type="text" class="form-control" id="coNationalId" value="${this._esc(c.nationalId)}" />
629 </div>
630 <div class="form-group">
631 <label class="form-label">کد اقتصادی</label>
632 <input type="text" class="form-control" id="coEconomicCode" value="${this._esc(c.economicCode)}" />
633 </div>
634 </div>
635 <div class="form-row">
636 <div class="form-group">
637 <label class="form-label">شماره ثبت</label>
638 <input type="text" class="form-control" id="coRegNumber" value="${this._esc(c.regNumber)}" />
639 </div>
640 <div class="form-group">
641 <label class="form-label">کد پستی</label>
642 <input type="text" class="form-control" id="coPostalCode" value="${this._esc(c.postalCode)}" />
643 </div>
644 </div>
645 <div class="form-row">
646 <div class="form-group">
647 <label class="form-label">تلفن</label>
648 <input type="tel" class="form-control" id="coPhone" value="${this._esc(c.phone)}" />
649 </div>
650 <div class="form-group">
651 <label class="form-label">موبایل</label>
652 <input type="tel" class="form-control" id="coMobile" value="${this._esc(c.mobile)}" />
653 </div>
654 </div>
655 <div class="form-group">
656 <label class="form-label">نشانی</label>
657 <textarea class="form-control" id="coAddress" rows="2">${this._esc(c.address)}</textarea>
658 </div>
659 <div class="form-group">
660 <label class="form-label">پاورقی فاکتور</label>
661 <textarea class="form-control" id="coFooter" rows="2" placeholder="مثلاً: از خرید شما سپاسگزاریم">${this._esc(c.footer)}</textarea>
662 </div>
663 `;
664 const footer = `
665 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
666 <button class="btn" onclick="window.SettingsView.saveCompany()">💾 ذخیره</button>
667 `;
668 Modal.open({ title: 'اطلاعات شرکت', body, footer, size: 'md' });
669 }
670
671 async saveCompany() {
672 const data = {
673 name: document.getElementById('coName').value,
674 entityType: document.getElementById('coEntityType').value,
675 nationalId: document.getElementById('coNationalId').value,
676 economicCode: document.getElementById('coEconomicCode').value,
677 regNumber: document.getElementById('coRegNumber').value,
678 postalCode: document.getElementById('coPostalCode').value,
679 phone: document.getElementById('coPhone').value,
680 mobile: document.getElementById('coMobile').value,
681 address: document.getElementById('coAddress').value,
682 footer: document.getElementById('coFooter').value
683 };
684 if (!data.name.trim()) { Toast.warning('نام الزامی است'); return; }
685 try {
686 await SettingsController.saveCompanyInfo(data);
687 Toast.success('اطلاعات ذخیره شد');
688 Modal.close();
689 await this.reload();
690 const grid = document.querySelector('.settings-grid');
691 if (grid) grid.innerHTML = this._renderAllCards();
692 } catch (err) {
693 Toast.error('خطا: ' + err.message);
694 }
695 }
696
697 // ============================================================
698 // بکاپ JSON
699 // ============================================================
700 async downloadBackup() {
701 try {
702 Toast.info('در حال آماده‌سازی بکاپ...');
703 const result = await SettingsController.downloadBackup();
704 Toast.success(`بکاپ دانلود شد (${result.filename})`, 'موفق');
705 } catch (err) {
706 Toast.error('خطا در بکاپ: ' + err.message);
707 }
708 }
709
710 openRestoreModal() {
711 const body = `
712 <div class="backup-warning" style="margin-bottom:14px">
713 ⚠️ <strong>هشدار:</strong> در حالت Merge، داده‌های تکراری skip می‌شن. در حالت Replace، فقط رکوردهای دارای شناسه یکسان بازنویسی می‌شوند و سایر داده‌ها حذف نمی‌شوند.
714 </div>
715
716 <div class="form-group">
717 <label class="form-label">فایل بکاپ رمزگذاری‌شده یا JSON</label>
718 <input type="file" class="form-control" id="restoreFile" accept=".json,.fbackup,application/json,application/octet-stream" />
719 </div>
720
721 <div class="form-group">
722 <label class="form-label">حالت بازیابی</label>
723 <select class="form-control" id="restoreMode">
724 <option value="merge">🔀 ادغام (Merge) — داده‌های جدید اضافه می‌شن</option>
725 <option value="replace">🔄 بازنویسی شناسه‌های یکسان (Replace) — بدون حذف سایر رکوردها</option>
726 </select>
727 </div>
728 `;
729 const footer = `
730 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
731 <button class="btn" onclick="window.SettingsView.restoreBackup()">📤 بازیابی</button>
732 `;
733 Modal.open({ title: 'بازیابی از بکاپ', body, footer, size: 'md' });
734 }
735
736 async restoreBackup() {
737 const fileInput = document.getElementById('restoreFile');
738 const file = fileInput.files[0];
739 if (!file) { Toast.warning('فایل بکاپ رو انتخاب کنید'); return; }
740
741 const mode = document.getElementById('restoreMode').value;
742
743 try {
744 Toast.info('در حال بازیابی...');
745 const content = await SettingsController.readFileAsText(file);
746 const counts = await SettingsController.importBackup(content, { mode });
747 Modal.close();
748 Toast.success(`بازیابی انجام شد: ${counts.added} مورد اضافه، ${counts.skipped} مورد skip`);
749 setTimeout(() => location.reload(), 1500);
750 } catch (err) {
751 Toast.error('خطا: ' + err.message);
752 }
753 }
754
755 // ============================================================
756 // پاک کردن کامل
757 // ============================================================
758 openWipeModal() {
759 const body = `
760 <div style="text-align:center;padding:10px 0">
761 <div style="font-size:48px;margin-bottom:12px">⚠️</div>
762 <h3 style="color:var(--danger);margin-bottom:8px">پاک کردن کامل داده‌ها</h3>
763 <p style="color:var(--text-muted);font-size:13px;line-height:1.8;margin-bottom:16px">
764 این عمل همه‌ی کالاها، اشخاص، فاکتورها، چک‌ها، تراکنش‌ها و تنظیمات رو برای همیشه پاک می‌کند.
765 <br><strong>قابل بازگشت نیست!</strong>
766 </p>
767 <p style="font-size:12px;color:var(--danger);margin-bottom:16px">
768 لطفاً برای تأیید، کلمه‌ی <code style="background:var(--danger);color:#fff;padding:2px 8px;border-radius:4px">حذف</code> رو تایپ کنید
769 </p>
770 <input type="text" class="form-control" id="wipeConfirm" placeholder="حذف" style="text-align:center;max-width:200px;margin:0 auto" />
771 </div>
772 `;
773 const footer = `
774 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
775 <button class="btn btn-danger" onclick="window.SettingsView.confirmWipe()">🗑️ پاک کن</button>
776 `;
777 Modal.open({ title: 'تأیید پاک کردن', body, footer, size: 'sm' });
778 }
779
780 async confirmWipe() {
781 const confirmText = document.getElementById('wipeConfirm').value.trim();
782 if (confirmText !== 'حذف') {
783 Toast.warning('متن تأیید اشتباه است');
784 return;
785 }
786 try {
787 await SettingsController.wipeAll();
788 Toast.success('همه‌ی داده‌ها پاک شد');
789 setTimeout(() => location.reload(), 800);
790 } catch (err) {
791 Toast.error('خطا: ' + err.message);
792 }
793 }
794
795 // ============================================================
796 // Theme
797 // ============================================================
798 setTheme(theme) {
799 Theme.apply(theme);
800 const grid = document.querySelector('.settings-grid');
801 if (grid) grid.innerHTML = this._renderAllCards();
802 }
803
804 _esc(s) {
805 if (!s) return '';
806 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
807 }
808 }
809
810 export const SettingsView = new SettingsViewImpl();
811 window.SettingsView = SettingsView;