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

test/phase-a-native-encrypted-backup
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 469 lines 21.2 KB
Raw
1 // ============================================================
2 // ContactsView — صفحه‌ی اشخاص
3 // ============================================================
4
5 import { ContactController } from '../controllers/ContactController.js';
6 import { Modal } from '../core/Modal.js';
7 import { Toast } from '../core/Toast.js';
8 import { Formatters } from '../utils/Formatters.js';
9 import { ContactLedgerModal } from './ContactLedgerModal.js';
10
11 let currentSearch = '';
12 let currentRoleFilter = 'all';
13 let currentTypeFilter = 'all';
14 let currentBalanceFilter = ''; // '' | 'debtor' | 'creditor' | 'settled'
15 let cache = { contacts: [], balances: {}, tags: [], globalSummary: {} };
16
17 class ContactsViewImpl {
18 async render() {
19 await this.reload();
20 return `
21 <div class="page-title">
22 <h2>اشخاص</h2>
23 <p>مدیریت مشتریان، تامین‌کنندگان و طرف‌حساب‌ها</p>
24 </div>
25
26 <div class="grid-kpi">
27 <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger)">
28 <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">📥</div>
29 <div style="flex:1">
30 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">کل مطالبات</div>
31 <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.money(cache.globalSummary.totalDebt || 0)}</div>
32 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(cache.globalSummary.debtorsCount || 0)} بدهکار</div>
33 </div>
34 </div>
35
36 <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)">
37 <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">📤</div>
38 <div style="flex:1">
39 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">کل بدهی ما</div>
40 <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.money(cache.globalSummary.totalCredit || 0)}</div>
41 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(cache.globalSummary.creditorsCount || 0)} بستانکار</div>
42 </div>
43 </div>
44
45 <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)">
46 <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">👥</div>
47 <div style="flex:1">
48 <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد اشخاص</div>
49 <div style="font-size:16px;font-weight:800;color:var(--primary)">${Formatters.number(cache.contacts.length)}</div>
50 <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">ثبت‌شده در سیستم</div>
51 </div>
52 </div>
53 </div>
54
55 <div class="toolbar">
56 <div class="search-input-wrap">
57 <span class="icon">🔍</span>
58 <input type="text" class="form-control" id="contactSearch" placeholder="جستجو بر اساس نام، تلفن یا کد ملی..." value="${this._esc(currentSearch)}" oninput="window.ContactsView._onSearch(this.value)" />
59 </div>
60 <select class="form-control" style="width:auto;min-width:130px" id="roleFilter" onchange="window.ContactsView._onFilterRole(this.value)">
61 <option value="all" ${currentRoleFilter === 'all' ? 'selected' : ''}>همه نقش‌ها</option>
62 <option value="customer" ${currentRoleFilter === 'customer' ? 'selected' : ''}>مشتری</option>
63 <option value="supplier" ${currentRoleFilter === 'supplier' ? 'selected' : ''}>تامین‌کننده</option>
64 <option value="both" ${currentRoleFilter === 'both' ? 'selected' : ''}>هر دو</option>
65 </select>
66 <select class="form-control" style="width:auto;min-width:120px" id="typeFilter" onchange="window.ContactsView._onFilterType(this.value)">
67 <option value="all" ${currentTypeFilter === 'all' ? 'selected' : ''}>همه انواع</option>
68 <option value="natural" ${currentTypeFilter === 'natural' ? 'selected' : ''}>حقیقی</option>
69 <option value="legal" ${currentTypeFilter === 'legal' ? 'selected' : ''}>حقوقی</option>
70 </select>
71 <select class="form-control" style="width:auto;min-width:140px" onchange="window.ContactsView._onFilterBalance(this.value)">
72 <option value="" ${currentBalanceFilter === '' ? 'selected' : ''}>همه مانده‌ها</option>
73 <option value="debtor" ${currentBalanceFilter === 'debtor' ? 'selected' : ''}>فقط بدهکاران</option>
74 <option value="creditor" ${currentBalanceFilter === 'creditor' ? 'selected' : ''}>فقط بستانکاران</option>
75 <option value="settled" ${currentBalanceFilter === 'settled' ? 'selected' : ''}>تسویه‌شده</option>
76 </select>
77 <button class="btn" onclick="window.ContactsView.openContactModal()">➕ شخص جدید</button>
78 </div>
79
80 <div id="contacts-content">${this.renderTable()}</div>
81 `;
82 }
83
84 onMount() {
85 window.ContactsView = this;
86 }
87
88 async reload() {
89 cache.contacts = await ContactController.getAll();
90 cache.tags = await ContactController.getAllTags();
91 const ids = cache.contacts.map(c => c.id);
92 cache.balances = await ContactController.getBalanceMap(ids);
93 cache.globalSummary = await ContactController.getGlobalSummary();
94 }
95
96 renderTable() {
97 let list = cache.contacts;
98
99 if (currentSearch) {
100 const q = currentSearch.toLowerCase();
101 list = list.filter(c =>
102 (c.name || '').toLowerCase().includes(q) ||
103 (c.mobile || '').includes(q) ||
104 (c.phone || '').includes(q) ||
105 (c.nationalId || '').includes(q)
106 );
107 }
108 if (currentRoleFilter !== 'all') {
109 list = list.filter(c => c.role === currentRoleFilter || c.role === 'both');
110 }
111 if (currentTypeFilter !== 'all') {
112 list = list.filter(c => c.entityType === currentTypeFilter);
113 }
114 if (currentBalanceFilter) {
115 list = list.filter(c => {
116 const b = cache.balances[c.id] || 0;
117 if (currentBalanceFilter === 'debtor') return b > 0;
118 if (currentBalanceFilter === 'creditor') return b < 0;
119 if (currentBalanceFilter === 'settled') return b === 0;
120 return true;
121 });
122 }
123
124 if (list.length === 0) {
125 return `
126 <div class="table-wrap">
127 <table><tbody>
128 <tr><td>
129 <div class="empty-state">
130 <div class="icon">👥</div>
131 <h3>هیچ شخصی یافت نشد</h3>
132 <p>${currentSearch || currentRoleFilter !== 'all' || currentTypeFilter !== 'all' || currentBalanceFilter ? 'فیلترها را تغییر بده یا شخص جدید اضافه کن' : 'اولین مشتری یا تامین‌کننده‌ی خود را اضافه کنید'}</p>
133 <button class="btn" onclick="window.ContactsView.openContactModal()">➕ شخص جدید</button>
134 </div>
135 </td></tr>
136 </tbody></table>
137 </div>`;
138 }
139
140 const rows = list.map(c => {
141 const balance = cache.balances[c.id] || 0;
142 const isDebtor = balance > 0;
143 const isCreditor = balance < 0;
144 const balanceColor = isDebtor ? 'var(--danger)' : isCreditor ? 'var(--success)' : 'var(--text-muted)';
145 const balanceText = balance === 0 ? 'تسویه' :
146 isDebtor ? Formatters.money(Math.abs(balance)) + ' بدهکار' :
147 Formatters.money(Math.abs(balance)) + ' بستانکار';
148
149 const roleLabel = c.role === 'customer' ? 'مشتری' :
150 c.role === 'supplier' ? 'تامین‌کننده' : 'هر دو';
151 const roleClass = c.role === 'customer' ? 'badge-success' :
152 c.role === 'supplier' ? 'badge-warning' : 'badge-muted';
153
154 const tags = (c.tags || []).map(t => `<span class="badge badge-muted" style="font-size:10px;margin-left:4px">${this._esc(t)}</span>`).join('');
155
156 return `
157 <tr>
158 <td>
159 <div style="font-weight:600;margin-bottom:2px">${this._esc(c.name)}</div>
160 ${tags}
161 </td>
162 <td>
163 <span class="badge ${c.entityType === 'legal' ? 'badge-warning' : 'badge-success'}">
164 ${c.entityType === 'legal' ? 'حقوقی' : 'حقیقی'}
165 </span>
166 </td>
167 <td><span class="badge ${roleClass}">${roleLabel}</span></td>
168 <td>
169 ${c.mobile ? `<div>${Formatters.phone(c.mobile)}</div>` : ''}
170 ${c.phone ? `<small style="color:var(--text-muted)">${Formatters.phone(c.phone)}</small>` : ''}
171 ${!c.mobile && !c.phone ? '—' : ''}
172 </td>
173 <td>${c.nationalId ? Formatters.toPersianDigits(c.nationalId) : '—'}</td>
174 <td style="font-weight:600;color:${balanceColor}">${balanceText}</td>
175 <td>
176 <div class="row-actions">
177 <button class="icon-btn-sm" title="کارت حساب" onclick="window.ContactsView.openLedger('${c.id}')">📒</button>
178 <button class="icon-btn-sm" title="ویرایش" onclick="window.ContactsView.editContact('${c.id}')">✏️</button>
179 <button class="icon-btn-sm danger" title="حذف" onclick="window.ContactsView.deleteContact('${c.id}')">🗑️</button>
180 </div>
181 </td>
182 </tr>
183 `;
184 }).join('');
185
186 return `
187 <div class="table-wrap">
188 <table>
189 <thead>
190 <tr>
191 <th>نام</th>
192 <th style="width:80px">نوع</th>
193 <th style="width:110px">نقش</th>
194 <th style="width:150px">تماس</th>
195 <th style="width:130px">شناسه / کد ملی</th>
196 <th style="width:180px">مانده حساب</th>
197 <th style="width:130px">عملیات</th>
198 </tr>
199 </thead>
200 <tbody>${rows}</tbody>
201 </table>
202 </div>
203 `;
204 }
205
206 _onSearch(val) {
207 currentSearch = val;
208 document.getElementById('contacts-content').innerHTML = this.renderTable();
209 const input = document.getElementById('contactSearch');
210 if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
211 }
212
213 _onFilterRole(val) {
214 currentRoleFilter = val;
215 document.getElementById('contacts-content').innerHTML = this.renderTable();
216 }
217
218 _onFilterType(val) {
219 currentTypeFilter = val;
220 document.getElementById('contacts-content').innerHTML = this.renderTable();
221 }
222
223 _onFilterBalance(val) {
224 currentBalanceFilter = val;
225 document.getElementById('contacts-content').innerHTML = this.renderTable();
226 }
227
228 // ============================================================
229 // کارت حساب
230 // ============================================================
231 openLedger(contactId) {
232 ContactLedgerModal.open(contactId);
233 }
234
235 // ============================================================
236 // فرم شخص
237 // ============================================================
238 async openContactModal(contactId = null) {
239 const contact = contactId ? await ContactController.get(contactId) : null;
240 const isEdit = !!contact;
241 const data = contact || {
242 entityType: 'natural', role: 'customer', prefix: '',
243 name: '', mobile: '', phone: '', nationalId: '',
244 economicCode: '', regNumber: '', postalCode: '',
245 address: '', tags: [], note: ''
246 };
247
248 const tagsChips = cache.tags.map(t => {
249 const checked = (data.tags || []).includes(t);
250 return `<label style="display:inline-flex;align-items:center;gap:4px;padding:4px 10px;background:var(--bg);border:1px solid var(--border);border-radius:20px;font-size:12px;cursor:pointer;margin:3px">
251 <input type="checkbox" class="tagCheckbox" value="${this._esc(t)}" ${checked ? 'checked' : ''} />
252 ${this._esc(t)}
253 </label>`;
254 }).join('');
255
256 const body = `
257 <div class="form-row">
258 <div class="form-group">
259 <label class="form-label">نوع شخص <span class="req">*</span></label>
260 <select class="form-control" id="cEntityType" onchange="window.ContactsView._toggleEntityFields(this.value)">
261 <option value="natural" ${data.entityType === 'natural' ? 'selected' : ''}>شخص حقیقی</option>
262 <option value="legal" ${data.entityType === 'legal' ? 'selected' : ''}>شخص حقوقی</option>
263 </select>
264 </div>
265 <div class="form-group">
266 <label class="form-label">نقش <span class="req">*</span></label>
267 <select class="form-control" id="cRole">
268 <option value="customer" ${data.role === 'customer' ? 'selected' : ''}>مشتری</option>
269 <option value="supplier" ${data.role === 'supplier' ? 'selected' : ''}>تامین‌کننده</option>
270 <option value="both" ${data.role === 'both' ? 'selected' : ''}>هر دو</option>
271 </select>
272 </div>
273 </div>
274
275 <div class="form-row">
276 <div class="form-group" id="prefixField" style="display:${data.entityType === 'natural' ? 'block' : 'none'}">
277 <label class="form-label">پیشوند</label>
278 <select class="form-control" id="cPrefix">
279 <option value="" ${!data.prefix ? 'selected' : ''}>— بدون پیشوند —</option>
280 <option value="آقای" ${data.prefix === 'آقای' ? 'selected' : ''}>آقای</option>
281 <option value="خانم" ${data.prefix === 'خانم' ? 'selected' : ''}>خانم</option>
282 <option value="فروشگاه" ${data.prefix === 'فروشگاه' ? 'selected' : ''}>فروشگاه</option>
283 <option value="شرکت" ${data.prefix === 'شرکت' ? 'selected' : ''}>شرکت</option>
284 <option value="موسسه" ${data.prefix === 'موسسه' ? 'selected' : ''}>موسسه</option>
285 <option value="سازمان" ${data.prefix === 'سازمان' ? 'selected' : ''}>سازمان</option>
286 </select>
287 </div>
288 <div class="form-group" id="nameField" style="grid-column:${data.entityType === 'natural' ? 'span 1' : 'span 2'}">
289 <label class="form-label">نام <span class="req">*</span></label>
290 <input type="text" class="form-control" id="cName" value="${this._esc(data.name)}" placeholder="نام کامل یا نام شرکت" />
291 </div>
292 </div>
293
294 <div class="form-row">
295 <div class="form-group">
296 <label class="form-label">موبایل</label>
297 <input type="tel" class="form-control" id="cMobile" value="${this._esc(data.mobile)}" placeholder="۰۹۱۲۳۴۵۶۷۸۹" />
298 </div>
299 <div class="form-group">
300 <label class="form-label">تلفن ثابت</label>
301 <input type="tel" class="form-control" id="cPhone" value="${this._esc(data.phone)}" />
302 </div>
303 </div>
304
305 <div class="form-row">
306 <div class="form-group">
307 <label class="form-label" id="nationalIdLabel">${data.entityType === 'legal' ? 'شناسه ملی' : 'کد ملی'}</label>
308 <input type="text" class="form-control" id="cNationalId" value="${this._esc(data.nationalId)}" />
309 </div>
310 <div class="form-group" id="economicField" style="display:${data.entityType === 'legal' ? 'block' : 'none'}">
311 <label class="form-label">کد اقتصادی</label>
312 <input type="text" class="form-control" id="cEconomicCode" value="${this._esc(data.economicCode)}" />
313 </div>
314 </div>
315
316 <div class="form-row">
317 <div class="form-group" id="regField" style="display:${data.entityType === 'legal' ? 'block' : 'none'}">
318 <label class="form-label">شماره ثبت</label>
319 <input type="text" class="form-control" id="cRegNumber" value="${this._esc(data.regNumber)}" />
320 </div>
321 <div class="form-group">
322 <label class="form-label">کد پستی</label>
323 <input type="text" class="form-control" id="cPostalCode" value="${this._esc(data.postalCode)}" />
324 </div>
325 </div>
326
327 <div class="form-group">
328 <label class="form-label">نشانی</label>
329 <textarea class="form-control" id="cAddress" rows="2">${this._esc(data.address)}</textarea>
330 </div>
331
332 <div class="form-group">
333 <label class="form-label">برچسب‌ها</label>
334 <div id="tagsContainer">${tagsChips || '<small style="color:var(--text-muted)">هنوز برچسبی تعریف نشده</small>'}</div>
335 <div style="display:flex;gap:6px;margin-top:8px">
336 <input type="text" class="form-control" id="newTagInput" placeholder="برچسب جدید..." style="flex:1" />
337 <button class="btn btn-secondary" onclick="window.ContactsView.addNewTag()">➕</button>
338 </div>
339 </div>
340
341 <div class="form-group">
342 <label class="form-label">یادداشت</label>
343 <textarea class="form-control" id="cNote" rows="2">${this._esc(data.note)}</textarea>
344 </div>
345 `;
346
347 const footer = `
348 <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
349 <button class="btn" onclick="window.ContactsView.saveContact(${isEdit ? `'${contactId}'` : 'null'})">💾 ذخیره</button>
350 `;
351
352 Modal.open({
353 title: isEdit ? 'ویرایش شخص' : 'شخص جدید',
354 body,
355 footer,
356 size: 'md'
357 });
358 }
359
360 _toggleEntityFields(type) {
361 const show = type === 'legal' ? 'block' : 'none';
362 const prefix = document.getElementById('prefixField');
363 const nameField = document.getElementById('nameField');
364 const nationalLabel = document.getElementById('nationalIdLabel');
365 const economic = document.getElementById('economicField');
366 const reg = document.getElementById('regField');
367
368 if (prefix) prefix.style.display = type === 'natural' ? 'block' : 'none';
369 if (nameField) nameField.style.gridColumn = type === 'natural' ? 'span 1' : 'span 2';
370 if (nationalLabel) nationalLabel.textContent = type === 'legal' ? 'شناسه ملی' : 'کد ملی';
371 if (economic) economic.style.display = show;
372 if (reg) reg.style.display = show;
373 }
374
375 addNewTag() {
376 const input = document.getElementById('newTagInput');
377 const tag = input.value.trim();
378 if (!tag) return;
379
380 const container = document.getElementById('tagsContainer');
381 if (container.querySelector('small')) container.innerHTML = '';
382
383 const existing = Array.from(container.querySelectorAll('.tagCheckbox')).map(cb => cb.value);
384 if (existing.includes(tag)) {
385 Toast.warning('این برچسب قبلاً اضافه شده');
386 return;
387 }
388
389 const label = document.createElement('label');
390 label.style.cssText = 'display:inline-flex;align-items:center;gap:4px;padding:4px 10px;background:var(--bg);border:1px solid var(--border);border-radius:20px;font-size:12px;cursor:pointer;margin:3px';
391 label.innerHTML = `<input type="checkbox" class="tagCheckbox" value="${this._esc(tag)}" checked /> ${this._esc(tag)}`;
392 container.appendChild(label);
393 input.value = '';
394 }
395
396 async saveContact(id) {
397 const tags = Array.from(document.querySelectorAll('.tagCheckbox'))
398 .filter(cb => cb.checked)
399 .map(cb => cb.value);
400
401 const data = {
402 entityType: document.getElementById('cEntityType').value,
403 role: document.getElementById('cRole').value,
404 prefix: document.getElementById('cPrefix')?.value || '',
405 name: document.getElementById('cName').value,
406 mobile: document.getElementById('cMobile').value,
407 phone: document.getElementById('cPhone').value,
408 nationalId: document.getElementById('cNationalId').value,
409 economicCode: document.getElementById('cEconomicCode')?.value || '',
410 regNumber: document.getElementById('cRegNumber')?.value || '',
411 postalCode: document.getElementById('cPostalCode').value,
412 address: document.getElementById('cAddress').value,
413 tags,
414 note: document.getElementById('cNote').value
415 };
416
417 if (!data.name.trim()) {
418 Toast.warning('نام الزامی است');
419 return;
420 }
421
422 try {
423 if (id) {
424 await ContactController.update(id, data);
425 Toast.success('شخص با موفقیت ویرایش شد');
426 } else {
427 await ContactController.create(data);
428 Toast.success('شخص با موفقیت ثبت شد');
429 }
430 Modal.close();
431 await this.reload();
432 document.getElementById('contacts-content').innerHTML = this.renderTable();
433 } catch (err) {
434 Toast.error('خطا: ' + err.message);
435 }
436 }
437
438 async editContact(id) {
439 await this.openContactModal(id);
440 }
441
442 async deleteContact(id) {
443 const c = cache.contacts.find(x => x.id === id);
444 Modal.confirm({
445 title: 'حذف شخص',
446 message: `آیا از حذف «${this._esc(c?.name || '')}» مطمئن هستید؟`,
447 confirmText: 'حذف',
448 danger: true,
449 onConfirm: async () => {
450 try {
451 await ContactController.delete(id);
452 Toast.success('شخص حذف شد');
453 await this.reload();
454 document.getElementById('contacts-content').innerHTML = this.renderTable();
455 } catch (err) {
456 Toast.error('خطا: ' + err.message);
457 }
458 }
459 });
460 }
461
462 _esc(s) {
463 if (!s) return '';
464 return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
465 }
466 }
467
468 export const ContactsView = new ContactsViewImpl();
469 window.ContactsView = ContactsView;