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

Phase 3: Contacts module (customers & suppliers)

Davood Mehraban committed Sep 18, 2026 at 06:50 UTC 52a64ce3b0a6d6e085c0510008054fdcca5ccca1
3 files changed +562 -1
src/controllers/ContactController.js new
+147
@@ -0,0 +1,147 @@
1 +// ============================================================
2 +// ContactController — منطق اشخاص (مشتریان و تامین‌کنندگان)
3 +// ============================================================
4 +
5 +import { StorageService } from '../core/StorageService.js';
6 +import { Auth } from '../core/Auth.js';
7 +
8 +class ContactControllerImpl {
9 + async getAll(filter = {}) {
10 + const user = Auth.current();
11 + if (!user) return [];
12 + let list = await StorageService.getByOwner('contacts', user.id);
13 +
14 + if (filter.search) {
15 + const q = String(filter.search).toLowerCase();
16 + list = list.filter(c =>
17 + (c.name || '').toLowerCase().includes(q) ||
18 + (c.mobile || '').includes(q) ||
19 + (c.phone || '').includes(q) ||
20 + (c.nationalId || '').includes(q) ||
21 + (c.economicCode || '').includes(q)
22 + );
23 + }
24 + if (filter.role && filter.role !== 'all') {
25 + list = list.filter(c => c.role === filter.role || c.role === 'both');
26 + }
27 + if (filter.entityType && filter.entityType !== 'all') {
28 + list = list.filter(c => c.entityType === filter.entityType);
29 + }
30 +
31 + return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
32 + }
33 +
34 + async get(id) {
35 + return await StorageService.get('contacts', id);
36 + }
37 +
38 + async create(data) {
39 + const user = Auth.current();
40 + const contact = {
41 + id: StorageService.uid('contact_'),
42 + ownerUserId: user.id,
43 + entityType: data.entityType || 'natural', // natural | legal
44 + role: data.role || 'customer', // customer | supplier | both
45 + prefix: (data.prefix || '').trim(),
46 + name: (data.name || '').trim(),
47 + mobile: (data.mobile || '').trim(),
48 + phone: (data.phone || '').trim(),
49 + nationalId: (data.nationalId || '').trim(),
50 + economicCode: (data.economicCode || '').trim(),
51 + regNumber: (data.regNumber || '').trim(),
52 + postalCode: (data.postalCode || '').trim(),
53 + address: (data.address || '').trim(),
54 + tags: Array.isArray(data.tags) ? data.tags : [],
55 + note: (data.note || '').trim(),
56 + isActive: true
57 + };
58 + return await StorageService.put('contacts', contact);
59 + }
60 +
61 + async update(id, data) {
62 + const existing = await StorageService.get('contacts', id);
63 + if (!existing) throw new Error('شخص یافت نشد');
64 + const updated = {
65 + ...existing,
66 + entityType: data.entityType || existing.entityType,
67 + role: data.role || existing.role,
68 + prefix: (data.prefix || '').trim(),
69 + name: (data.name || '').trim(),
70 + mobile: (data.mobile || '').trim(),
71 + phone: (data.phone || '').trim(),
72 + nationalId: (data.nationalId || '').trim(),
73 + economicCode: (data.economicCode || '').trim(),
74 + regNumber: (data.regNumber || '').trim(),
75 + postalCode: (data.postalCode || '').trim(),
76 + address: (data.address || '').trim(),
77 + tags: Array.isArray(data.tags) ? data.tags : existing.tags || [],
78 + note: (data.note || '').trim()
79 + };
80 + return await StorageService.put('contacts', updated);
81 + }
82 +
83 + async delete(id) {
84 + return await StorageService.delete('contacts', id);
85 + }
86 +
87 + /**
88 + * محاسبه‌ی مانده حساب از تراکنش‌ها
89 + * فرمول: sum(invoices.grandTotal - receivedAmounts) - sum(payments)
90 + */
91 + async getBalance(contactId) {
92 + const user = Auth.current();
93 + if (!user) return 0;
94 +
95 + const invoices = await StorageService.getByOwner('invoices', user.id);
96 + const transactions = await StorageService.getByOwner('transactions', user.id);
97 +
98 + const contactInvoices = invoices.filter(i => i.contactId === contactId);
99 + const invoiceTotal = contactInvoices.reduce((s, i) => s + (Number(i.grandTotal) || 0), 0);
100 +
101 + // دریافت وجه از مشتری (receipt) مانده رو کم می‌کنه
102 + // پرداخت به تامین‌کننده (payment) مانده رو زیاد می‌کنه
103 + const contactTransactions = transactions.filter(t => t.contactId === contactId);
104 + let receipts = 0, payments = 0;
105 + contactTransactions.forEach(t => {
106 + if (t.type === 'receipt') receipts += Number(t.amount) || 0;
107 + if (t.type === 'payment') payments += Number(t.amount) || 0;
108 + });
109 +
110 + // مانده = فاکتورها - دریافت‌ها + پرداخت‌ها
111 + return invoiceTotal - receipts + payments;
112 + }
113 +
114 + async getBalanceMap(contactIds) {
115 + const user = Auth.current();
116 + const invoices = await StorageService.getByOwner('invoices', user.id);
117 + const transactions = await StorageService.getByOwner('transactions', user.id);
118 + const map = {};
119 + contactIds.forEach(id => map[id] = { invoices: 0, receipts: 0, payments: 0 });
120 +
121 + invoices.forEach(inv => {
122 + if (map[inv.contactId]) map[inv.contactId].invoices += Number(inv.grandTotal) || 0;
123 + });
124 + transactions.forEach(t => {
125 + if (!map[t.contactId]) return;
126 + if (t.type === 'receipt') map[t.contactId].receipts += Number(t.amount) || 0;
127 + if (t.type === 'payment') map[t.contactId].payments += Number(t.amount) || 0;
128 + });
129 +
130 + const result = {};
131 + contactIds.forEach(id => {
132 + const m = map[id];
133 + result[id] = m.invoices - m.receipts + m.payments;
134 + });
135 + return result;
136 + }
137 +
138 + async getAllTags() {
139 + const user = Auth.current();
140 + const all = await StorageService.getByOwner('contacts', user.id);
141 + const set = new Set();
142 + all.forEach(c => (c.tags || []).forEach(t => set.add(t)));
143 + return Array.from(set).sort((a, b) => a.localeCompare(b, 'fa'));
144 + }
145 +}
146 +
147 +export const ContactController = new ContactControllerImpl();
\ No newline at end of file
src/main.js
+6 -1
@@ -2,6 +2,7 @@
2 // Finora Pro — Main Entry Point
3 // ============================================================
4
5 +import { ContactsView } from './views/ContactsView.js';
6 import { ProductsView } from './views/ProductsView.js';
7 import { StorageService } from './core/StorageService.js';
8 import { Theme } from './core/Theme.js';
@@ -105,7 +106,11 @@ function registerRoutes() {
106 render: () => ProductsView.render(),
107 onMount: () => ProductsView.onMount()
108 });
108 - Router.register('contacts', { title: 'اشخاص', render: placeholder('اشخاص', 3) });
109 + Router.register('contacts', {
110 + title: 'اشخاص',
111 + render: () => ContactsView.render(),
112 + onMount: () => ContactsView.onMount()
113 +});
114 Router.register('treasury', { title: 'خزانه و بانک', render: placeholder('خزانه و بانک', 6) });
115 Router.register('cheques', { title: 'چک‌ها', render: placeholder('چک‌ها', 6) });
116 Router.register('expenses', { title: 'هزینه و درآمد', render: placeholder('هزینه و درآمد', 6) });
src/views/ContactsView.js new
+409
@@ -0,0 +1,409 @@
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 +
10 +let currentSearch = '';
11 +let currentRoleFilter = 'all';
12 +let currentTypeFilter = 'all';
13 +let cache = { contacts: [], balances: {}, tags: [] };
14 +
15 +class ContactsViewImpl {
16 + async render() {
17 + await this.reload();
18 + return `
19 + <div class="page-title">
20 + <h2>اشخاص</h2>
21 + <p>مدیریت مشتریان، تامین‌کنندگان و طرف‌حساب‌ها</p>
22 + </div>
23 +
24 + <div class="toolbar">
25 + <div class="search-input-wrap">
26 + <span class="icon">🔍</span>
27 + <input type="text" class="form-control" id="contactSearch" placeholder="جستجو بر اساس نام، تلفن یا کد ملی..." value="${this._esc(currentSearch)}" oninput="window.ContactsView._onSearch(this.value)" />
28 + </div>
29 + <select class="form-control" style="width:auto;min-width:140px" id="roleFilter" onchange="window.ContactsView._onFilterRole(this.value)">
30 + <option value="all" ${currentRoleFilter === 'all' ? 'selected' : ''}>همه نقش‌ها</option>
31 + <option value="customer" ${currentRoleFilter === 'customer' ? 'selected' : ''}>مشتری</option>
32 + <option value="supplier" ${currentRoleFilter === 'supplier' ? 'selected' : ''}>تامین‌کننده</option>
33 + <option value="both" ${currentRoleFilter === 'both' ? 'selected' : ''}>هر دو</option>
34 + </select>
35 + <select class="form-control" style="width:auto;min-width:140px" id="typeFilter" onchange="window.ContactsView._onFilterType(this.value)">
36 + <option value="all" ${currentTypeFilter === 'all' ? 'selected' : ''}>همه انواع</option>
37 + <option value="natural" ${currentTypeFilter === 'natural' ? 'selected' : ''}>حقیقی</option>
38 + <option value="legal" ${currentTypeFilter === 'legal' ? 'selected' : ''}>حقوقی</option>
39 + </select>
40 + <button class="btn" onclick="window.ContactsView.openContactModal()">➕ شخص جدید</button>
41 + </div>
42 +
43 + <div id="contacts-content">${this.renderTable()}</div>
44 + `;
45 + }
46 +
47 + onMount() {
48 + window.ContactsView = this;
49 + }
50 +
51 + async reload() {
52 + cache.contacts = await ContactController.getAll();
53 + cache.tags = await ContactController.getAllTags();
54 + const ids = cache.contacts.map(c => c.id);
55 + cache.balances = await ContactController.getBalanceMap(ids);
56 + }
57 +
58 + renderTable() {
59 + let list = cache.contacts;
60 +
61 + if (currentSearch) {
62 + const q = currentSearch.toLowerCase();
63 + list = list.filter(c =>
64 + (c.name || '').toLowerCase().includes(q) ||
65 + (c.mobile || '').includes(q) ||
66 + (c.phone || '').includes(q) ||
67 + (c.nationalId || '').includes(q)
68 + );
69 + }
70 + if (currentRoleFilter !== 'all') {
71 + list = list.filter(c => c.role === currentRoleFilter || c.role === 'both');
72 + }
73 + if (currentTypeFilter !== 'all') {
74 + list = list.filter(c => c.entityType === currentTypeFilter);
75 + }
76 +
77 + if (list.length === 0) {
78 + return `
79 + <div class="table-wrap">
80 + <table><tbody>
81 + <tr><td>
82 + <div class="empty-state">
83 + <div class="icon">👥</div>
84 + <h3>هیچ شخصی ثبت نشده</h3>
85 + <p>اولین مشتری یا تامین‌کننده‌ی خود را اضافه کنید</p>
86 + <button class="btn" onclick="window.ContactsView.openContactModal()">➕ شخص جدید</button>
87 + </div>
88 + </td></tr>
89 + </tbody></table>
90 + </div>`;
91 + }
92 +
93 + const rows = list.map(c => {
94 + const balance = cache.balances[c.id] || 0;
95 + const isDebtor = balance > 0; // مشتری بدهکار
96 + const isCreditor = balance < 0; // ما بدهکاریم
97 + const balanceColor = isDebtor ? 'var(--danger)' : isCreditor ? 'var(--success)' : 'var(--text-muted)';
98 + const balanceText = balance === 0 ? 'تسویه' :
99 + isDebtor ? Formatters.money(Math.abs(balance)) + ' بدهکار' :
100 + Formatters.money(Math.abs(balance)) + ' بستانکار';
101 +
102 + const roleLabel = c.role === 'customer' ? 'مشتری' :
103 + c.role === 'supplier' ? 'تامین‌کننده' : 'هر دو';
104 + const roleClass = c.role === 'customer' ? 'badge-success' :
105 + c.role === 'supplier' ? 'badge-warning' : 'badge-muted';
106 +
107 + const tags = (c.tags || []).map(t => `<span class="badge badge-muted" style="font-size:10px;margin-left:4px">${this._esc(t)}</span>`).join('');
108 +
109 + return `
110 + <tr>
111 + <td>
112 + <div style="font-weight:600;margin-bottom:2px">${this._esc(c.name)}</div>
113 + ${tags}
114 + </td>
115 + <td>
116 + <span class="badge ${c.entityType === 'legal' ? 'badge-warning' : 'badge-success'}">
117 + ${c.entityType === 'legal' ? 'حقوقی' : 'حقیقی'}
118 + </span>
119 + </td>
120 + <td><span class="badge ${roleClass}">${roleLabel}</span></td>
121 + <td>
122 + ${c.mobile ? `<div>${Formatters.phone(c.mobile)}</div>` : ''}
123 + ${c.phone ? `<small style="color:var(--text-muted)">${Formatters.phone(c.phone)}</small>` : ''}
124 + ${!c.mobile && !c.phone ? '—' : ''}
125 + </td>
126 + <td>${c.nationalId ? Formatters.toPersianDigits(c.nationalId) : '—'}</td>
127 + <td style="font-weight:600;color:${balanceColor}">${balanceText}</td>
128 + <td>
129 + <div class="row-actions">
130 + <button class="icon-btn-sm" title="ویرایش" onclick="window.ContactsView.editContact('${c.id}')">✏️</button>
131 + <button class="icon-btn-sm danger" title="حذف" onclick="window.ContactsView.deleteContact('${c.id}')">🗑️</button>
132 + </div>
133 + </td>
134 + </tr>
135 + `;
136 + }).join('');
137 +
138 + return `
139 + <div class="table-wrap">
140 + <table>
141 + <thead>
142 + <tr>
143 + <th>نام</th>
144 + <th style="width:80px">نوع</th>
145 + <th style="width:110px">نقش</th>
146 + <th style="width:150px">تماس</th>
147 + <th style="width:130px">شناسه / کد ملی</th>
148 + <th style="width:180px">مانده حساب</th>
149 + <th style="width:100px">عملیات</th>
150 + </tr>
151 + </thead>
152 + <tbody>${rows}</tbody>
153 + </table>
154 + </div>
155 + `;
156 + }
157 +
158 + _onSearch(val) {
159 + currentSearch = val;
160 + document.getElementById('contacts-content').innerHTML = this.renderTable();
161 + const input = document.getElementById('contactSearch');
162 + if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
163 + }
164 +
165 + _onFilterRole(val) {
166 + currentRoleFilter = val;
167 + document.getElementById('contacts-content').innerHTML = this.renderTable();
168 + }
169 +
170 + _onFilterType(val) {
171 + currentTypeFilter = val;
172 + document.getElementById('contacts-content').innerHTML = this.renderTable();
173 + }
174 +
175 + // ============================================================
176 + // فرم شخص
177 + // ============================================================
178 + async openContactModal(contactId = null) {
179 + const contact = contactId ? await ContactController.get(contactId) : null;
180 + const isEdit = !!contact;
181 + const data = contact || {
182 + entityType: 'natural', role: 'customer', prefix: '',
183 + name: '', mobile: '', phone: '', nationalId: '',
184 + economicCode: '', regNumber: '', postalCode: '',
185 + address: '', tags: [], note: ''
186 + };
187 +
188 + const tagsChips = cache.tags.map(t => {
189 + const checked = (data.tags || []).includes(t);
190 + 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">
191 + <input type="checkbox" class="tagCheckbox" value="${this._esc(t)}" ${checked ? 'checked' : ''} />
192 + ${this._esc(t)}
193 + </label>`;
194 + }).join('');
195 +
196 + const body = `
197 + <div class="form-row">
198 + <div class="form-group">
199 + <label class="form-label">نوع شخص <span class="req">*</span></label>
200 + <select class="form-control" id="cEntityType" onchange="window.ContactsView._toggleEntityFields(this.value)">
201 + <option value="natural" ${data.entityType === 'natural' ? 'selected' : ''}>شخص حقیقی</option>
202 + <option value="legal" ${data.entityType === 'legal' ? 'selected' : ''}>شخص حقوقی</option>
203 + </select>
204 + </div>
205 + <div class="form-group">
206 + <label class="form-label">نقش <span class="req">*</span></label>
207 + <select class="form-control" id="cRole">
208 + <option value="customer" ${data.role === 'customer' ? 'selected' : ''}>مشتری</option>
209 + <option value="supplier" ${data.role === 'supplier' ? 'selected' : ''}>تامین‌کننده</option>
210 + <option value="both" ${data.role === 'both' ? 'selected' : ''}>هر دو</option>
211 + </select>
212 + </div>
213 + </div>
214 +
215 + <div class="form-row">
216 + <div class="form-group" id="prefixField" style="display:${data.entityType === 'natural' ? 'block' : 'none'}">
217 + <label class="form-label">پیشوند</label>
218 + <select class="form-control" id="cPrefix">
219 + <option value="" ${!data.prefix ? 'selected' : ''}>— بدون پیشوند —</option>
220 + <option value="آقای" ${data.prefix === 'آقای' ? 'selected' : ''}>آقای</option>
221 + <option value="خانم" ${data.prefix === 'خانم' ? 'selected' : ''}>خانم</option>
222 + <option value="فروشگاه" ${data.prefix === 'فروشگاه' ? 'selected' : ''}>فروشگاه</option>
223 + <option value="شرکت" ${data.prefix === 'شرکت' ? 'selected' : ''}>شرکت</option>
224 + <option value="موسسه" ${data.prefix === 'موسسه' ? 'selected' : ''}>موسسه</option>
225 + <option value="سازمان" ${data.prefix === 'سازمان' ? 'selected' : ''}>سازمان</option>
226 + </select>
227 + </div>
228 + <div class="form-group" id="nameField" style="grid-column:${data.entityType === 'natural' ? 'span 1' : 'span 2'}">
229 + <label class="form-label">نام <span class="req">*</span></label>
230 + <input type="text" class="form-control" id="cName" value="${this._esc(data.name)}" placeholder="نام کامل یا نام شرکت" />
231 + </div>
232 + </div>
233 +
234 + <div class="form-row">
235 + <div class="form-group">
236 + <label class="form-label">موبایل</label>
237 + <input type="tel" class="form-control" id="cMobile" value="${this._esc(data.mobile)}" placeholder="۰۹۱۲۳۴۵۶۷۸۹" />
238 + </div>
239 + <div class="form-group">
240 + <label class="form-label">تلفن ثابت</label>
241 + <input type="tel" class="form-control" id="cPhone" value="${this._esc(data.phone)}" />
242 + </div>
243 + </div>
244 +
245 + <div class="form-row">
246 + <div class="form-group">
247 + <label class="form-label" id="nationalIdLabel">${data.entityType === 'legal' ? 'شناسه ملی' : 'کد ملی'}</label>
248 + <input type="text" class="form-control" id="cNationalId" value="${this._esc(data.nationalId)}" />
249 + </div>
250 + <div class="form-group" id="economicField" style="display:${data.entityType === 'legal' ? 'block' : 'none'}">
251 + <label class="form-label">کد اقتصادی</label>
252 + <input type="text" class="form-control" id="cEconomicCode" value="${this._esc(data.economicCode)}" />
253 + </div>
254 + </div>
255 +
256 + <div class="form-row">
257 + <div class="form-group" id="regField" style="display:${data.entityType === 'legal' ? 'block' : 'none'}">
258 + <label class="form-label">شماره ثبت</label>
259 + <input type="text" class="form-control" id="cRegNumber" value="${this._esc(data.regNumber)}" />
260 + </div>
261 + <div class="form-group">
262 + <label class="form-label">کد پستی</label>
263 + <input type="text" class="form-control" id="cPostalCode" value="${this._esc(data.postalCode)}" />
264 + </div>
265 + </div>
266 +
267 + <div class="form-group">
268 + <label class="form-label">نشانی</label>
269 + <textarea class="form-control" id="cAddress" rows="2">${this._esc(data.address)}</textarea>
270 + </div>
271 +
272 + <div class="form-group">
273 + <label class="form-label">برچسب‌ها</label>
274 + <div id="tagsContainer">${tagsChips || '<small style="color:var(--text-muted)">هنوز برچسبی تعریف نشده</small>'}</div>
275 + <div style="display:flex;gap:6px;margin-top:8px">
276 + <input type="text" class="form-control" id="newTagInput" placeholder="برچسب جدید..." style="flex:1" />
277 + <button class="btn btn-secondary" onclick="window.ContactsView.addNewTag()">➕</button>
278 + </div>
279 + </div>
280 +
281 + <div class="form-group">
282 + <label class="form-label">یادداشت</label>
283 + <textarea class="form-control" id="cNote" rows="2">${this._esc(data.note)}</textarea>
284 + </div>
285 + `;
286 +
287 + const footer = `
288 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
289 + <button class="btn" onclick="window.ContactsView.saveContact(${isEdit ? `'${contactId}'` : 'null'})">💾 ذخیره</button>
290 + `;
291 +
292 + Modal.open({
293 + title: isEdit ? 'ویرایش شخص' : 'شخص جدید',
294 + body,
295 + footer,
296 + size: 'md'
297 + });
298 + }
299 +
300 + _toggleEntityFields(type) {
301 + const show = type === 'legal' ? 'block' : 'none';
302 + const prefix = document.getElementById('prefixField');
303 + const nameField = document.getElementById('nameField');
304 + const nationalLabel = document.getElementById('nationalIdLabel');
305 + const economic = document.getElementById('economicField');
306 + const reg = document.getElementById('regField');
307 +
308 + if (prefix) prefix.style.display = type === 'natural' ? 'block' : 'none';
309 + if (nameField) nameField.style.gridColumn = type === 'natural' ? 'span 1' : 'span 2';
310 + if (nationalLabel) nationalLabel.textContent = type === 'legal' ? 'شناسه ملی' : 'کد ملی';
311 + if (economic) economic.style.display = show;
312 + if (reg) reg.style.display = show;
313 + }
314 +
315 + addNewTag() {
316 + const input = document.getElementById('newTagInput');
317 + const tag = input.value.trim();
318 + if (!tag) return;
319 +
320 + const container = document.getElementById('tagsContainer');
321 + if (container.querySelector('small')) container.innerHTML = '';
322 +
323 + // چک تکراری
324 + const existing = Array.from(container.querySelectorAll('.tagCheckbox')).map(cb => cb.value);
325 + if (existing.includes(tag)) {
326 + Toast.warning('این برچسب قبلاً اضافه شده');
327 + return;
328 + }
329 +
330 + const label = document.createElement('label');
331 + 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';
332 + label.innerHTML = `<input type="checkbox" class="tagCheckbox" value="${this._esc(tag)}" checked /> ${this._esc(tag)}`;
333 + container.appendChild(label);
334 + input.value = '';
335 + }
336 +
337 + async saveContact(id) {
338 + const tags = Array.from(document.querySelectorAll('.tagCheckbox'))
339 + .filter(cb => cb.checked)
340 + .map(cb => cb.value);
341 +
342 + const data = {
343 + entityType: document.getElementById('cEntityType').value,
344 + role: document.getElementById('cRole').value,
345 + prefix: document.getElementById('cPrefix')?.value || '',
346 + name: document.getElementById('cName').value,
347 + mobile: document.getElementById('cMobile').value,
348 + phone: document.getElementById('cPhone').value,
349 + nationalId: document.getElementById('cNationalId').value,
350 + economicCode: document.getElementById('cEconomicCode')?.value || '',
351 + regNumber: document.getElementById('cRegNumber')?.value || '',
352 + postalCode: document.getElementById('cPostalCode').value,
353 + address: document.getElementById('cAddress').value,
354 + tags,
355 + note: document.getElementById('cNote').value
356 + };
357 +
358 + if (!data.name.trim()) {
359 + Toast.warning('نام الزامی است');
360 + return;
361 + }
362 +
363 + try {
364 + if (id) {
365 + await ContactController.update(id, data);
366 + Toast.success('شخص با موفقیت ویرایش شد');
367 + } else {
368 + await ContactController.create(data);
369 + Toast.success('شخص با موفقیت ثبت شد');
370 + }
371 + Modal.close();
372 + await this.reload();
373 + document.getElementById('contacts-content').innerHTML = this.renderTable();
374 + } catch (err) {
375 + Toast.error('خطا: ' + err.message);
376 + }
377 + }
378 +
379 + async editContact(id) {
380 + await this.openContactModal(id);
381 + }
382 +
383 + async deleteContact(id) {
384 + const c = cache.contacts.find(x => x.id === id);
385 + Modal.confirm({
386 + title: 'حذف شخص',
387 + message: `آیا از حذف «${this._esc(c?.name || '')}» مطمئن هستید؟`,
388 + confirmText: 'حذف',
389 + danger: true,
390 + onConfirm: async () => {
391 + try {
392 + await ContactController.delete(id);
393 + Toast.success('شخص حذف شد');
394 + await this.reload();
395 + document.getElementById('contacts-content').innerHTML = this.renderTable();
396 + } catch (err) {
397 + Toast.error('خطا: ' + err.message);
398 + }
399 + }
400 + });
401 + }
402 +
403 + _esc(s) {
404 + if (!s) return '';
405 + return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
406 + }
407 +}
408 +
409 +export const ContactsView = new ContactsViewImpl();
\ No newline at end of file