فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
Phase 2: Products module + Modal click fix
Davood Mehraban committed
Sep 18, 2026 at 06:36 UTC
557806f8258b0e4464668405bd598c06b3caf30b
6 files changed
+1018
-3
src/controllers/ProductController.js
new
+187
@@ -0,0 +1,187 @@
1
+// ============================================================
2
+// ProductController — منطق کالا، واحد، گروه
3
+// ============================================================
4
+
5
+import { StorageService } from '../core/StorageService.js';
6
+import { Auth } from '../core/Auth.js';
7
+
8
+class ProductControllerImpl {
9
+ // ----- واحدها -----
10
+ async getUnits() {
11
+ const user = Auth.current();
12
+ if (!user) return [];
13
+ const all = await StorageService.getByOwner('units', user.id);
14
+ return all.sort((a, b) => (a.name || '').localeCompare(b.name || '', 'fa'));
15
+ }
16
+
17
+ async createUnit(name, symbol = '') {
18
+ const user = Auth.current();
19
+ const unit = {
20
+ id: StorageService.uid('unit_'),
21
+ ownerUserId: user.id,
22
+ name: (name || '').trim(),
23
+ symbol: (symbol || '').trim()
24
+ };
25
+ return await StorageService.put('units', unit);
26
+ }
27
+
28
+ async deleteUnit(id) {
29
+ return await StorageService.delete('units', id);
30
+ }
31
+
32
+ // ----- گروهها -----
33
+ async getCategories() {
34
+ const user = Auth.current();
35
+ const all = await StorageService.getByOwner('categories', user.id);
36
+ return all.sort((a, b) => (a.name || '').localeCompare(b.name || '', 'fa'));
37
+ }
38
+
39
+ async createCategory(name, parentId = null) {
40
+ const user = Auth.current();
41
+ const cat = {
42
+ id: StorageService.uid('cat_'),
43
+ ownerUserId: user.id,
44
+ parentId,
45
+ name: (name || '').trim()
46
+ };
47
+ return await StorageService.put('categories', cat);
48
+ }
49
+
50
+ async deleteCategory(id) {
51
+ return await StorageService.delete('categories', id);
52
+ }
53
+
54
+ // ----- کالاها -----
55
+ async getProducts(filter = {}) {
56
+ const user = Auth.current();
57
+ let list = await StorageService.getByOwner('products', user.id);
58
+
59
+ if (filter.search) {
60
+ const q = String(filter.search).toLowerCase();
61
+ list = list.filter(p =>
62
+ (p.name || '').toLowerCase().includes(q) ||
63
+ (p.code || '').toLowerCase().includes(q) ||
64
+ (p.barcode || '').toLowerCase().includes(q)
65
+ );
66
+ }
67
+ if (filter.categoryId) {
68
+ list = list.filter(p => p.categoryId === filter.categoryId);
69
+ }
70
+ if (filter.type === 'good') {
71
+ list = list.filter(p => p.trackInventory !== false);
72
+ }
73
+ if (filter.type === 'service') {
74
+ list = list.filter(p => p.trackInventory === false);
75
+ }
76
+
77
+ return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
78
+ }
79
+
80
+ async getProduct(id) {
81
+ return await StorageService.get('products', id);
82
+ }
83
+
84
+ async createProduct(data) {
85
+ const user = Auth.current();
86
+ const product = {
87
+ id: StorageService.uid('prod_'),
88
+ ownerUserId: user.id,
89
+ code: (data.code || '').trim(),
90
+ barcode: (data.barcode || '').trim(),
91
+ name: (data.name || '').trim(),
92
+ categoryId: data.categoryId || null,
93
+ unitId: data.unitId || null,
94
+ buyPrice: Number(data.buyPrice) || 0,
95
+ sellPrice: Number(data.sellPrice) || 0,
96
+ trackInventory: data.trackInventory !== false,
97
+ isActiveSell: data.isActiveSell !== false,
98
+ isActiveBuy: data.isActiveBuy !== false,
99
+ description: (data.description || '').trim()
100
+ };
101
+ return await StorageService.put('products', product);
102
+ }
103
+
104
+ async updateProduct(id, data) {
105
+ const existing = await StorageService.get('products', id);
106
+ if (!existing) throw new Error('کالا یافت نشد');
107
+ const updated = {
108
+ ...existing,
109
+ code: (data.code || '').trim(),
110
+ barcode: (data.barcode || '').trim(),
111
+ name: (data.name || '').trim(),
112
+ categoryId: data.categoryId || null,
113
+ unitId: data.unitId || null,
114
+ buyPrice: Number(data.buyPrice) || 0,
115
+ sellPrice: Number(data.sellPrice) || 0,
116
+ trackInventory: data.trackInventory !== false,
117
+ isActiveSell: data.isActiveSell !== false,
118
+ isActiveBuy: data.isActiveBuy !== false,
119
+ description: (data.description || '').trim()
120
+ };
121
+ return await StorageService.put('products', updated);
122
+ }
123
+
124
+ async deleteProduct(id) {
125
+ const user = Auth.current();
126
+ const movements = await StorageService.getByOwner('stock_movements', user.id);
127
+ const related = movements.filter(m => m.productId === id);
128
+ for (const m of related) {
129
+ await StorageService.delete('stock_movements', m.id);
130
+ }
131
+ return await StorageService.delete('products', id);
132
+ }
133
+
134
+ // ----- موجودی -----
135
+ async getStock(productId) {
136
+ const user = Auth.current();
137
+ const movements = await StorageService.getByOwner('stock_movements', user.id);
138
+ const productMoves = movements.filter(m => m.productId === productId);
139
+ let stock = 0;
140
+ productMoves.forEach(m => {
141
+ if (m.type === 'in') stock += Number(m.qty) || 0;
142
+ else if (m.type === 'out') stock -= Number(m.qty) || 0;
143
+ else if (m.type === 'adjust') stock = Number(m.qty) || 0;
144
+ });
145
+ return stock;
146
+ }
147
+
148
+ async getStockMap(productIds) {
149
+ const user = Auth.current();
150
+ const movements = await StorageService.getByOwner('stock_movements', user.id);
151
+ const map = {};
152
+ productIds.forEach(id => map[id] = 0);
153
+ movements.forEach(m => {
154
+ if (!(m.productId in map)) return;
155
+ if (m.type === 'in') map[m.productId] += Number(m.qty) || 0;
156
+ else if (m.type === 'out') map[m.productId] -= Number(m.qty) || 0;
157
+ else if (m.type === 'adjust') map[m.productId] = Number(m.qty) || 0;
158
+ });
159
+ return map;
160
+ }
161
+
162
+ async addStockMovement(productId, type, qty, refType = 'manual', refId = null, note = '') {
163
+ const user = Auth.current();
164
+ const movement = {
165
+ id: StorageService.uid('mv_'),
166
+ ownerUserId: user.id,
167
+ productId,
168
+ type,
169
+ qty: Number(qty) || 0,
170
+ refType,
171
+ refId,
172
+ note,
173
+ date: new Date().toISOString()
174
+ };
175
+ return await StorageService.put('stock_movements', movement);
176
+ }
177
+
178
+ async getMovements(productId) {
179
+ const user = Auth.current();
180
+ const all = await StorageService.getByOwner('stock_movements', user.id);
181
+ return all
182
+ .filter(m => m.productId === productId)
183
+ .sort((a, b) => (b.date || '').localeCompare(a.date || ''));
184
+ }
185
+}
186
+
187
+export const ProductController = new ProductControllerImpl();
\ No newline at end of file
src/core/Modal.js
new
+95
@@ -0,0 +1,95 @@
1
+// ============================================================
2
+// Modal — سیستم پنجرهی شناور
3
+// ============================================================
4
+
5
+class ModalManager {
6
+ constructor() {
7
+ this.stack = [];
8
+ }
9
+
10
+ _create(options) {
11
+ const { title, body, footer, size = 'md', onClose, closeOnBackdrop = true } = options;
12
+
13
+ const backdrop = document.createElement('div');
14
+ backdrop.className = 'modal-backdrop';
15
+
16
+ // Fix: کلیک فقط زمانی معنی داره که هم mousedown و هم mouseup روی خود backdrop باشه
17
+ // (نه وقتی که کاربر داره داخل فرم متن select میکنه و موس به بیرون کشیده میشه)
18
+ if (closeOnBackdrop) {
19
+ let mouseDownTarget = null;
20
+ backdrop.addEventListener('mousedown', (e) => {
21
+ mouseDownTarget = e.target;
22
+ });
23
+ backdrop.addEventListener('mouseup', (e) => {
24
+ if (e.target === backdrop && mouseDownTarget === backdrop) {
25
+ this.close();
26
+ }
27
+ mouseDownTarget = null;
28
+ });
29
+ }
30
+
31
+ const card = document.createElement('div');
32
+ card.className = `modal-card modal-${size}`;
33
+ card.innerHTML = `
34
+ <div class="modal-header">
35
+ <div class="modal-title">${title}</div>
36
+ <button class="modal-close" aria-label="بستن">×</button>
37
+ </div>
38
+ <div class="modal-body"></div>
39
+ ${footer ? '<div class="modal-footer"></div>' : ''}
40
+ `;
41
+
42
+ const bodyEl = card.querySelector('.modal-body');
43
+ if (typeof body === 'string') bodyEl.innerHTML = body;
44
+ else if (body instanceof HTMLElement) bodyEl.appendChild(body);
45
+
46
+ if (footer) {
47
+ const footerEl = card.querySelector('.modal-footer');
48
+ if (typeof footer === 'string') footerEl.innerHTML = footer;
49
+ else if (footer instanceof HTMLElement) footerEl.appendChild(footer);
50
+ }
51
+
52
+ card.querySelector('.modal-close').onclick = () => this.close();
53
+ backdrop.appendChild(card);
54
+ return { backdrop, card, onClose };
55
+ }
56
+
57
+ open(options) {
58
+ const modal = this._create(options);
59
+ document.body.appendChild(modal.backdrop);
60
+ document.body.style.overflow = 'hidden';
61
+ this.stack.push(modal);
62
+ return modal;
63
+ }
64
+
65
+ close() {
66
+ const modal = this.stack.pop();
67
+ if (!modal) return;
68
+ modal.backdrop.remove();
69
+ if (this.stack.length === 0) {
70
+ document.body.style.overflow = '';
71
+ }
72
+ if (modal.onClose) modal.onClose();
73
+ }
74
+
75
+ closeAll() {
76
+ while (this.stack.length) this.close();
77
+ }
78
+
79
+ confirm({ title, message, confirmText = 'تأیید', cancelText = 'انصراف', danger = false, onConfirm }) {
80
+ const body = `<p style="font-size:13.5px;line-height:1.8">${message}</p>`;
81
+ const footer = `
82
+ <button class="btn btn-secondary" data-action="cancel">${cancelText}</button>
83
+ <button class="btn ${danger ? 'btn-danger' : ''}" data-action="confirm">${confirmText}</button>
84
+ `;
85
+ const modal = this.open({ title, body, footer, size: 'sm' });
86
+ const footerEl = modal.card.querySelector('.modal-footer');
87
+ footerEl.querySelector('[data-action="cancel"]').onclick = () => this.close();
88
+ footerEl.querySelector('[data-action="confirm"]').onclick = () => {
89
+ this.close();
90
+ if (onConfirm) onConfirm();
91
+ };
92
+ }
93
+}
94
+
95
+export const Modal = new ModalManager();
\ No newline at end of file
src/core/StorageService.js
+2
-1
@@ -3,10 +3,11 @@
3
// ============================================================
4
5
const DB_NAME = 'finora_pro_db';
6
-const DB_VERSION = 1;
6
+const DB_VERSION = 2;
7
8
const STORES = [
9
'users', 'companies', 'contacts', 'products',
10
+ 'units', 'categories',
11
'invoices', 'invoice_items', 'stock_movements',
12
'transactions', 'cheques', 'expenses',
13
'settings', 'logs'
src/main.js
+6
-1
@@ -2,6 +2,7 @@
2
// Finora Pro — Main Entry Point
3
// ============================================================
4
5
+import { ProductsView } from './views/ProductsView.js';
6
import { StorageService } from './core/StorageService.js';
7
import { Theme } from './core/Theme.js';
8
import { Toast } from './core/Toast.js';
@@ -99,7 +100,11 @@ function registerRoutes() {
100
});
101
102
Router.register('invoices', { title: 'فاکتورها', render: placeholder('فاکتورها', 4) });
102
- Router.register('products', { title: 'کالا و انبار', render: placeholder('کالا و انبار', 2) });
103
+ Router.register('products', {
104
+ title: 'کالا و انبار',
105
+ render: () => ProductsView.render(),
106
+ onMount: () => ProductsView.onMount()
107
+});
108
Router.register('contacts', { title: 'اشخاص', render: placeholder('اشخاص', 3) });
109
Router.register('treasury', { title: 'خزانه و بانک', render: placeholder('خزانه و بانک', 6) });
110
Router.register('cheques', { title: 'چکها', render: placeholder('چکها', 6) });
src/styles/main.css
+229
-1
@@ -298,4 +298,232 @@ a { color: inherit; }
298
::-webkit-scrollbar { width: 8px; height: 8px; }
299
::-webkit-scrollbar-track { background: var(--bg); }
300
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
301
-::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
\ No newline at end of file
301
+::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
302
+/* ===== Tables ===== */
303
+.table-wrap {
304
+ background: var(--card-bg);
305
+ border: 1px solid var(--border);
306
+ border-radius: var(--radius);
307
+ overflow: hidden;
308
+}
309
+.table-wrap table {
310
+ width: 100%;
311
+ border-collapse: collapse;
312
+}
313
+.table-wrap th {
314
+ background: var(--bg);
315
+ padding: 12px 14px;
316
+ text-align: right;
317
+ font-size: 12.5px;
318
+ font-weight: 700;
319
+ color: var(--text-muted);
320
+ border-bottom: 1px solid var(--border);
321
+ white-space: nowrap;
322
+}
323
+.table-wrap td {
324
+ padding: 12px 14px;
325
+ border-bottom: 1px solid var(--border);
326
+ font-size: 13px;
327
+ vertical-align: middle;
328
+}
329
+.table-wrap tr:last-child td { border-bottom: none; }
330
+.table-wrap tr:hover td { background: var(--bg); }
331
+
332
+/* ===== Form ===== */
333
+.form-group { margin-bottom: 14px; }
334
+.form-label {
335
+ display: block;
336
+ font-size: 12.5px;
337
+ font-weight: 600;
338
+ color: var(--text-muted);
339
+ margin-bottom: 6px;
340
+}
341
+.form-label .req { color: var(--danger); }
342
+.form-control {
343
+ width: 100%;
344
+ min-height: 42px;
345
+ padding: 9px 12px;
346
+ border: 1px solid var(--border);
347
+ border-radius: 9px;
348
+ background: var(--card-bg);
349
+ color: var(--text);
350
+ font-size: 13.5px;
351
+ font-family: inherit;
352
+ outline: none;
353
+ transition: border-color .15s;
354
+}
355
+.form-control:focus {
356
+ border-color: var(--primary);
357
+ box-shadow: 0 0 0 3px var(--primary-light);
358
+}
359
+.form-row {
360
+ display: grid;
361
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
362
+ gap: 12px;
363
+}
364
+textarea.form-control { min-height: 80px; resize: vertical; }
365
+
366
+/* ===== Modal ===== */
367
+.modal-backdrop {
368
+ position: fixed;
369
+ inset: 0;
370
+ background: rgba(15,23,42,.6);
371
+ backdrop-filter: blur(4px);
372
+ display: flex;
373
+ align-items: center;
374
+ justify-content: center;
375
+ padding: 20px;
376
+ z-index: 9999;
377
+ animation: fadeIn .2s ease;
378
+}
379
+@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
380
+.modal-card {
381
+ background: var(--card-bg);
382
+ border-radius: 14px;
383
+ box-shadow: 0 25px 50px -12px rgba(0,0,0,.25);
384
+ max-height: 90vh;
385
+ display: flex;
386
+ flex-direction: column;
387
+ animation: scaleIn .2s ease;
388
+}
389
+.modal-card.modal-sm { width: 100%; max-width: 420px; }
390
+.modal-card.modal-md { width: 100%; max-width: 620px; }
391
+.modal-card.modal-lg { width: 100%; max-width: 900px; }
392
+@keyframes scaleIn {
393
+ from { transform: scale(.95); opacity: 0; }
394
+ to { transform: scale(1); opacity: 1; }
395
+}
396
+.modal-header {
397
+ padding: 16px 20px;
398
+ border-bottom: 1px solid var(--border);
399
+ display: flex;
400
+ align-items: center;
401
+ justify-content: space-between;
402
+ gap: 10px;
403
+}
404
+.modal-title { font-size: 15px; font-weight: 700; }
405
+.modal-close {
406
+ background: none; border: none;
407
+ font-size: 22px; color: var(--text-muted);
408
+ width: 32px; height: 32px;
409
+ border-radius: 8px;
410
+ display: flex; align-items: center; justify-content: center;
411
+}
412
+.modal-close:hover { background: var(--bg); }
413
+.modal-body { padding: 20px; overflow-y: auto; flex: 1; }
414
+.modal-footer {
415
+ padding: 14px 20px;
416
+ border-top: 1px solid var(--border);
417
+ display: flex; gap: 10px; justify-content: flex-end;
418
+}
419
+
420
+/* ===== Tabs ===== */
421
+.tabs {
422
+ display: flex;
423
+ gap: 4px;
424
+ margin-bottom: 16px;
425
+ border-bottom: 1px solid var(--border);
426
+}
427
+.tab-btn {
428
+ background: none; border: none;
429
+ padding: 10px 16px;
430
+ font-size: 13.5px;
431
+ font-weight: 600;
432
+ color: var(--text-muted);
433
+ cursor: pointer;
434
+ border-bottom: 2px solid transparent;
435
+ margin-bottom: -1px;
436
+ font-family: inherit;
437
+ transition: all .15s;
438
+}
439
+.tab-btn:hover { color: var(--text); }
440
+.tab-btn.active {
441
+ color: var(--primary);
442
+ border-bottom-color: var(--primary);
443
+}
444
+
445
+/* ===== Badge ===== */
446
+.badge {
447
+ display: inline-block;
448
+ padding: 3px 8px;
449
+ border-radius: 6px;
450
+ font-size: 11px;
451
+ font-weight: 600;
452
+}
453
+.badge-success { background: #d1fae5; color: #065f46; }
454
+.badge-muted { background: var(--bg); color: var(--text-muted); }
455
+.badge-warning { background: #fef3c7; color: #92400e; }
456
+.badge-danger { background: #fee2e2; color: #991b1b; }
457
+
458
+/* ===== Empty state ===== */
459
+.empty-state {
460
+ text-align: center;
461
+ padding: 60px 20px;
462
+ color: var(--text-muted);
463
+}
464
+.empty-state .icon { font-size: 64px; margin-bottom: 16px; opacity: .4; }
465
+.empty-state h3 {
466
+ font-size: 16px; font-weight: 700;
467
+ margin-bottom: 8px; color: var(--text);
468
+}
469
+.empty-state p { font-size: 13px; margin-bottom: 20px; }
470
+
471
+/* ===== Toolbar ===== */
472
+.toolbar {
473
+ display: flex; gap: 10px;
474
+ align-items: center; flex-wrap: wrap;
475
+ margin-bottom: 16px;
476
+}
477
+.search-input-wrap {
478
+ position: relative; flex: 1; min-width: 200px;
479
+}
480
+.search-input-wrap .icon {
481
+ position: absolute;
482
+ right: 12px; top: 50%;
483
+ transform: translateY(-50%);
484
+ color: var(--text-muted);
485
+ pointer-events: none;
486
+}
487
+.search-input-wrap input { padding-right: 38px; }
488
+
489
+/* ===== Table actions ===== */
490
+.row-actions {
491
+ display: flex; gap: 4px; justify-content: flex-end;
492
+}
493
+.icon-btn-sm {
494
+ background: none;
495
+ border: 1px solid var(--border);
496
+ width: 32px; height: 32px;
497
+ border-radius: 8px;
498
+ display: flex; align-items: center; justify-content: center;
499
+ font-size: 13px; color: var(--text-muted);
500
+ cursor: pointer; transition: all .15s;
501
+}
502
+.icon-btn-sm:hover {
503
+ background: var(--bg);
504
+ border-color: var(--primary);
505
+ color: var(--primary);
506
+}
507
+.icon-btn-sm.danger:hover {
508
+ border-color: var(--danger); color: var(--danger);
509
+}
510
+
511
+/* ===== Inline add button ===== */
512
+.btn-add-inline {
513
+ background: var(--primary-light);
514
+ color: var(--primary);
515
+ border: 1px dashed var(--primary);
516
+ padding: 8px 12px;
517
+ border-radius: 8px;
518
+ font-size: 12.5px;
519
+ font-weight: 600;
520
+ width: 100%;
521
+ margin-top: 6px;
522
+ cursor: pointer;
523
+ font-family: inherit;
524
+ transition: all .15s;
525
+}
526
+.btn-add-inline:hover {
527
+ background: var(--primary);
528
+ color: #fff;
529
+}
\ No newline at end of file
src/views/ProductsView.js
new
+499
@@ -0,0 +1,499 @@
1
+// ============================================================
2
+// ProductsView — صفحهی کالا، واحد، گروه
3
+// ============================================================
4
+
5
+import { ProductController } from '../controllers/ProductController.js';
6
+import { Modal } from '../core/Modal.js';
7
+import { Toast } from '../core/Toast.js';
8
+import { Formatters } from '../utils/Formatters.js';
9
+import { numberToWords } from '../utils/NumberToWords.js';
10
+
11
+let currentTab = 'products';
12
+let currentSearch = '';
13
+let cache = { products: [], units: [], categories: [], stockMap: {} };
14
+
15
+class ProductsViewImpl {
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="tabs">
25
+ <button class="tab-btn ${currentTab === 'products' ? 'active' : ''}" onclick="window.ProductsView._switchTab('products')">
26
+ 📦 کالاها و خدمات
27
+ </button>
28
+ <button class="tab-btn ${currentTab === 'units' ? 'active' : ''}" onclick="window.ProductsView._switchTab('units')">
29
+ 📏 واحدها
30
+ </button>
31
+ <button class="tab-btn ${currentTab === 'categories' ? 'active' : ''}" onclick="window.ProductsView._switchTab('categories')">
32
+ 🗂️ گروهها
33
+ </button>
34
+ </div>
35
+
36
+ <div id="products-tab-content">
37
+ ${this.renderTabContent()}
38
+ </div>
39
+ `;
40
+ }
41
+
42
+ onMount() {
43
+ window.ProductsView = this;
44
+ }
45
+
46
+ async reload() {
47
+ cache.products = await ProductController.getProducts();
48
+ cache.units = await ProductController.getUnits();
49
+ cache.categories = await ProductController.getCategories();
50
+ const ids = cache.products.map(p => p.id);
51
+ cache.stockMap = await ProductController.getStockMap(ids);
52
+ }
53
+
54
+ renderTabContent() {
55
+ if (currentTab === 'products') return this.renderProductsTab();
56
+ if (currentTab === 'units') return this.renderUnitsTab();
57
+ if (currentTab === 'categories') return this.renderCategoriesTab();
58
+ return '';
59
+ }
60
+
61
+ _switchTab(tab) {
62
+ currentTab = tab;
63
+ const el = document.getElementById('products-tab-content');
64
+ if (el) {
65
+ document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
66
+ event.target.classList.add('active');
67
+ el.innerHTML = this.renderTabContent();
68
+ }
69
+ }
70
+
71
+ // ============================================================
72
+ // کالاها
73
+ // ============================================================
74
+ renderProductsTab() {
75
+ const filtered = currentSearch
76
+ ? cache.products.filter(p => {
77
+ const q = currentSearch.toLowerCase();
78
+ return (p.name || '').toLowerCase().includes(q)
79
+ || (p.code || '').toLowerCase().includes(q)
80
+ || (p.barcode || '').toLowerCase().includes(q);
81
+ })
82
+ : cache.products;
83
+
84
+ let rowsHtml = '';
85
+ if (filtered.length === 0) {
86
+ rowsHtml = `
87
+ <tr><td colspan="7">
88
+ <div class="empty-state">
89
+ <div class="icon">📦</div>
90
+ <h3>هیچ کالایی ثبت نشده</h3>
91
+ <p>اولین کالا یا خدمات خود را اضافه کنید</p>
92
+ </div>
93
+ </td></tr>`;
94
+ } else {
95
+ rowsHtml = filtered.map(p => {
96
+ const unit = cache.units.find(u => u.id === p.unitId);
97
+ const cat = cache.categories.find(c => c.id === p.categoryId);
98
+ const stock = cache.stockMap[p.id] || 0;
99
+ const isService = p.trackInventory === false;
100
+ return `
101
+ <tr>
102
+ <td><strong>${this._esc(p.code || '—')}</strong></td>
103
+ <td>
104
+ <div style="font-weight:600">${this._esc(p.name)}</div>
105
+ ${cat ? `<small style="color:var(--text-muted);font-size:11px">${this._esc(cat.name)}</small>` : ''}
106
+ </td>
107
+ <td>${unit ? this._esc(unit.name) : '—'}</td>
108
+ <td>${Formatters.money(p.buyPrice)}</td>
109
+ <td>${Formatters.money(p.sellPrice)}</td>
110
+ <td>
111
+ ${isService
112
+ ? '<span class="badge badge-muted">خدمت</span>'
113
+ : `<strong style="color:${stock > 0 ? 'var(--success)' : stock < 0 ? 'var(--danger)' : 'var(--text-muted)'}">${Formatters.number(stock)}</strong>`
114
+ }
115
+ </td>
116
+ <td>
117
+ <div class="row-actions">
118
+ <button class="icon-btn-sm" title="ویرایش" onclick="window.ProductsView.editProduct('${p.id}')">✏️</button>
119
+ <button class="icon-btn-sm danger" title="حذف" onclick="window.ProductsView.deleteProduct('${p.id}')">🗑️</button>
120
+ </div>
121
+ </td>
122
+ </tr>
123
+ `;
124
+ }).join('');
125
+ }
126
+
127
+ return `
128
+ <div class="toolbar">
129
+ <div class="search-input-wrap">
130
+ <span class="icon">🔍</span>
131
+ <input type="text" class="form-control" id="productSearch" placeholder="جستجو بر اساس نام، کد یا بارکد..." value="${this._esc(currentSearch)}" oninput="window.ProductsView._onSearch(this.value)" />
132
+ </div>
133
+ <button class="btn" onclick="window.ProductsView.openProductModal()">➕ کالای جدید</button>
134
+ </div>
135
+
136
+ <div class="table-wrap">
137
+ <table>
138
+ <thead>
139
+ <tr>
140
+ <th style="width:100px">کد</th>
141
+ <th>نام</th>
142
+ <th style="width:90px">واحد</th>
143
+ <th style="width:130px">خرید</th>
144
+ <th style="width:130px">فروش</th>
145
+ <th style="width:90px">موجودی</th>
146
+ <th style="width:100px">عملیات</th>
147
+ </tr>
148
+ </thead>
149
+ <tbody>${rowsHtml}</tbody>
150
+ </table>
151
+ </div>
152
+ `;
153
+ }
154
+
155
+ _onSearch(val) {
156
+ currentSearch = val;
157
+ const el = document.getElementById('products-tab-content');
158
+ if (el) el.innerHTML = this.renderProductsTab();
159
+ const input = document.getElementById('productSearch');
160
+ if (input) { input.focus(); input.setSelectionRange(val.length, val.length); }
161
+ }
162
+
163
+ // ============================================================
164
+ // واحدها
165
+ // ============================================================
166
+ renderUnitsTab() {
167
+ let rowsHtml = '';
168
+ if (cache.units.length === 0) {
169
+ rowsHtml = `<tr><td colspan="3"><div class="empty-state"><div class="icon">📏</div><h3>واحدی ثبت نشده</h3><p>واحدهای اندازهگیری مثل عدد، کیلوگرم، متر را اضافه کنید</p></div></td></tr>`;
170
+ } else {
171
+ rowsHtml = cache.units.map(u => `
172
+ <tr>
173
+ <td><strong>${this._esc(u.name)}</strong></td>
174
+ <td>${this._esc(u.symbol || '—')}</td>
175
+ <td>
176
+ <div class="row-actions">
177
+ <button class="icon-btn-sm danger" title="حذف" onclick="window.ProductsView.deleteUnit('${u.id}')">🗑️</button>
178
+ </div>
179
+ </td>
180
+ </tr>
181
+ `).join('');
182
+ }
183
+ return `
184
+ <div class="toolbar">
185
+ <button class="btn" onclick="window.ProductsView.openUnitModal()">➕ واحد جدید</button>
186
+ </div>
187
+ <div class="table-wrap">
188
+ <table>
189
+ <thead><tr><th>نام واحد</th><th>نماد</th><th style="width:100px">عملیات</th></tr></thead>
190
+ <tbody>${rowsHtml}</tbody>
191
+ </table>
192
+ </div>
193
+ `;
194
+ }
195
+
196
+ // ============================================================
197
+ // گروهها
198
+ // ============================================================
199
+ renderCategoriesTab() {
200
+ let rowsHtml = '';
201
+ if (cache.categories.length === 0) {
202
+ rowsHtml = `<tr><td colspan="3"><div class="empty-state"><div class="icon">🗂️</div><h3>گروهی ثبت نشده</h3><p>کالاها را در گروههای مختلف دستهبندی کنید</p></div></td></tr>`;
203
+ } else {
204
+ rowsHtml = cache.categories.map(c => {
205
+ const parent = c.parentId ? cache.categories.find(x => x.id === c.parentId) : null;
206
+ return `
207
+ <tr>
208
+ <td><strong>${this._esc(c.name)}</strong></td>
209
+ <td>${parent ? this._esc(parent.name) : '<span class="badge badge-muted">بدون والد</span>'}</td>
210
+ <td>
211
+ <div class="row-actions">
212
+ <button class="icon-btn-sm danger" title="حذف" onclick="window.ProductsView.deleteCategory('${c.id}')">🗑️</button>
213
+ </div>
214
+ </td>
215
+ </tr>
216
+ `;
217
+ }).join('');
218
+ }
219
+ return `
220
+ <div class="toolbar">
221
+ <button class="btn" onclick="window.ProductsView.openCategoryModal()">➕ گروه جدید</button>
222
+ </div>
223
+ <div class="table-wrap">
224
+ <table>
225
+ <thead><tr><th>نام گروه</th><th>گروه والد</th><th style="width:100px">عملیات</th></tr></thead>
226
+ <tbody>${rowsHtml}</tbody>
227
+ </table>
228
+ </div>
229
+ `;
230
+ }
231
+
232
+ // ============================================================
233
+ // فرم کالا
234
+ // ============================================================
235
+ async openProductModal(productId = null) {
236
+ const product = productId ? await ProductController.getProduct(productId) : null;
237
+ const isEdit = !!product;
238
+ const data = product || {
239
+ code: '', barcode: '', name: '', categoryId: null, unitId: null,
240
+ buyPrice: 0, sellPrice: 0, trackInventory: true,
241
+ isActiveSell: true, isActiveBuy: true, description: ''
242
+ };
243
+
244
+ const unitOptions = cache.units.map(u =>
245
+ `<option value="${u.id}" ${data.unitId === u.id ? 'selected' : ''}>${this._esc(u.name)}</option>`
246
+ ).join('');
247
+
248
+ const catOptions = cache.categories.map(c =>
249
+ `<option value="${c.id}" ${data.categoryId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>`
250
+ ).join('');
251
+
252
+ const body = `
253
+ <div class="form-row">
254
+ <div class="form-group">
255
+ <label class="form-label">کد کالا</label>
256
+ <input type="text" class="form-control" id="pCode" value="${this._esc(data.code)}" placeholder="مثلاً ۱۰۱" />
257
+ </div>
258
+ <div class="form-group">
259
+ <label class="form-label">بارکد</label>
260
+ <input type="text" class="form-control" id="pBarcode" value="${this._esc(data.barcode)}" />
261
+ </div>
262
+ </div>
263
+
264
+ <div class="form-group">
265
+ <label class="form-label">نام کالا / خدمت <span class="req">*</span></label>
266
+ <input type="text" class="form-control" id="pName" value="${this._esc(data.name)}" placeholder="مثلاً هارد سرور" />
267
+ </div>
268
+
269
+ <div class="form-row">
270
+ <div class="form-group">
271
+ <label class="form-label">واحد</label>
272
+ <select class="form-control" id="pUnit">${unitOptions}</select>
273
+ <button class="btn-add-inline" onclick="window.ProductsView.openUnitModal(true)">➕ واحد جدید</button>
274
+ </div>
275
+ <div class="form-group">
276
+ <label class="form-label">گروه</label>
277
+ <select class="form-control" id="pCategory">${catOptions}</select>
278
+ <button class="btn-add-inline" onclick="window.ProductsView.openCategoryModal(true)">➕ گروه جدید</button>
279
+ </div>
280
+ </div>
281
+
282
+ <div class="form-row">
283
+ <div class="form-group">
284
+ <label class="form-label">قیمت خرید (ریال)</label>
285
+ <input type="number" class="form-control" id="pBuyPrice" value="${data.buyPrice || 0}" min="0" />
286
+ </div>
287
+ <div class="form-group">
288
+ <label class="form-label">قیمت فروش (ریال)</label>
289
+ <input type="number" class="form-control" id="pSellPrice" value="${data.sellPrice || 0}" min="0" />
290
+ </div>
291
+ </div>
292
+
293
+ <div class="form-group">
294
+ <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
295
+ <input type="checkbox" id="pTrackInventory" ${data.trackInventory !== false ? 'checked' : ''} />
296
+ <span style="font-size:13px">پیگیری موجودی انبار</span>
297
+ </label>
298
+ <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:2px;padding-right:24px">
299
+ اگه این گزینه رو بردارید، این مورد به عنوان «خدمت» ثبت میشه و موجودی براش محاسبه نمیشه.
300
+ </small>
301
+ </div>
302
+
303
+ <div class="form-group">
304
+ <label class="form-label">توضیحات</label>
305
+ <textarea class="form-control" id="pDescription" placeholder="توضیحات اضافی...">${this._esc(data.description)}</textarea>
306
+ </div>
307
+ `;
308
+
309
+ const footer = `
310
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
311
+ <button class="btn" onclick="window.ProductsView.saveProduct(${isEdit ? `'${productId}'` : 'null'})">💾 ذخیره</button>
312
+ `;
313
+
314
+ Modal.open({
315
+ title: isEdit ? 'ویرایش کالا' : 'کالای جدید',
316
+ body,
317
+ footer,
318
+ size: 'md'
319
+ });
320
+ }
321
+
322
+ async saveProduct(id) {
323
+ const data = {
324
+ code: document.getElementById('pCode').value,
325
+ barcode: document.getElementById('pBarcode').value,
326
+ name: document.getElementById('pName').value,
327
+ unitId: document.getElementById('pUnit').value || null,
328
+ categoryId: document.getElementById('pCategory').value || null,
329
+ buyPrice: document.getElementById('pBuyPrice').value,
330
+ sellPrice: document.getElementById('pSellPrice').value,
331
+ trackInventory: document.getElementById('pTrackInventory').checked,
332
+ description: document.getElementById('pDescription').value
333
+ };
334
+
335
+ if (!data.name.trim()) {
336
+ Toast.warning('نام کالا الزامی است');
337
+ return;
338
+ }
339
+
340
+ try {
341
+ if (id) {
342
+ await ProductController.updateProduct(id, data);
343
+ Toast.success('کالا با موفقیت ویرایش شد');
344
+ } else {
345
+ await ProductController.createProduct(data);
346
+ Toast.success('کالا با موفقیت ثبت شد');
347
+ }
348
+ Modal.close();
349
+ await this.reload();
350
+ document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
351
+ } catch (err) {
352
+ Toast.error('خطا در ذخیرهسازی: ' + err.message);
353
+ }
354
+ }
355
+
356
+ async deleteProduct(id) {
357
+ const product = cache.products.find(p => p.id === id);
358
+ Modal.confirm({
359
+ title: 'حذف کالا',
360
+ message: `آیا از حذف «${this._esc(product?.name || '')}» مطمئن هستید؟ این عمل قابل بازگشت نیست.`,
361
+ confirmText: 'حذف',
362
+ danger: true,
363
+ onConfirm: async () => {
364
+ try {
365
+ await ProductController.deleteProduct(id);
366
+ Toast.success('کالا حذف شد');
367
+ await this.reload();
368
+ document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
369
+ } catch (err) {
370
+ Toast.error('خطا در حذف: ' + err.message);
371
+ }
372
+ }
373
+ });
374
+ }
375
+
376
+ // ============================================================
377
+ // فرم واحد
378
+ // ============================================================
379
+ openUnitModal(fromProductForm = false) {
380
+ const body = `
381
+ <div class="form-group">
382
+ <label class="form-label">نام واحد <span class="req">*</span></label>
383
+ <input type="text" class="form-control" id="uName" placeholder="مثلاً عدد، کیلوگرم، متر، بسته" />
384
+ </div>
385
+ <div class="form-group">
386
+ <label class="form-label">نماد (اختیاری)</label>
387
+ <input type="text" class="form-control" id="uSymbol" placeholder="مثلاً kg، m" />
388
+ </div>
389
+ `;
390
+ const footer = `
391
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
392
+ <button class="btn" onclick="window.ProductsView.saveUnit(${fromProductForm})">💾 ذخیره</button>
393
+ `;
394
+ Modal.open({ title: 'واحد جدید', body, footer, size: 'sm' });
395
+ }
396
+
397
+ async saveUnit(fromProductForm) {
398
+ const name = document.getElementById('uName').value;
399
+ const symbol = document.getElementById('uSymbol').value;
400
+ if (!name.trim()) { Toast.warning('نام واحد الزامی است'); return; }
401
+ try {
402
+ await ProductController.createUnit(name, symbol);
403
+ Toast.success('واحد ثبت شد');
404
+ Modal.close();
405
+ await this.reload();
406
+ if (fromProductForm) {
407
+ // به فرم کالا برگرد و dropdown رو refresh کن
408
+ Toast.info('واحد اضافه شد. لطفاً فرم کالا رو دوباره باز کنید');
409
+ } else {
410
+ document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
411
+ }
412
+ } catch (err) {
413
+ Toast.error('خطا: ' + err.message);
414
+ }
415
+ }
416
+
417
+ async deleteUnit(id) {
418
+ Modal.confirm({
419
+ title: 'حذف واحد',
420
+ message: 'آیا از حذف این واحد مطمئن هستید؟',
421
+ confirmText: 'حذف',
422
+ danger: true,
423
+ onConfirm: async () => {
424
+ await ProductController.deleteUnit(id);
425
+ Toast.success('واحد حذف شد');
426
+ await this.reload();
427
+ document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
428
+ }
429
+ });
430
+ }
431
+
432
+ // ============================================================
433
+ // فرم گروه
434
+ // ============================================================
435
+ openCategoryModal(fromProductForm = false) {
436
+ const parentOptions = cache.categories.map(c =>
437
+ `<option value="${c.id}">${this._esc(c.name)}</option>`
438
+ ).join('');
439
+ const body = `
440
+ <div class="form-group">
441
+ <label class="form-label">نام گروه <span class="req">*</span></label>
442
+ <input type="text" class="form-control" id="cName" placeholder="مثلاً لوازم اداری" />
443
+ </div>
444
+ <div class="form-group">
445
+ <label class="form-label">گروه والد (اختیاری)</label>
446
+ <select class="form-control" id="cParent">
447
+ <option value="">— بدون والد —</option>
448
+ ${parentOptions}
449
+ </select>
450
+ </div>
451
+ `;
452
+ const footer = `
453
+ <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
454
+ <button class="btn" onclick="window.ProductsView.saveCategory(${fromProductForm})">💾 ذخیره</button>
455
+ `;
456
+ Modal.open({ title: 'گروه جدید', body, footer, size: 'sm' });
457
+ }
458
+
459
+ async saveCategory(fromProductForm) {
460
+ const name = document.getElementById('cName').value;
461
+ const parentId = document.getElementById('cParent').value || null;
462
+ if (!name.trim()) { Toast.warning('نام گروه الزامی است'); return; }
463
+ try {
464
+ await ProductController.createCategory(name, parentId);
465
+ Toast.success('گروه ثبت شد');
466
+ Modal.close();
467
+ await this.reload();
468
+ if (fromProductForm) {
469
+ Toast.info('گروه اضافه شد. لطفاً فرم کالا رو دوباره باز کنید');
470
+ } else {
471
+ document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
472
+ }
473
+ } catch (err) {
474
+ Toast.error('خطا: ' + err.message);
475
+ }
476
+ }
477
+
478
+ async deleteCategory(id) {
479
+ Modal.confirm({
480
+ title: 'حذف گروه',
481
+ message: 'آیا از حذف این گروه مطمئن هستید؟',
482
+ confirmText: 'حذف',
483
+ danger: true,
484
+ onConfirm: async () => {
485
+ await ProductController.deleteCategory(id);
486
+ Toast.success('گروه حذف شد');
487
+ await this.reload();
488
+ document.getElementById('products-tab-content').innerHTML = this.renderTabContent();
489
+ }
490
+ });
491
+ }
492
+
493
+ _esc(s) {
494
+ if (!s) return '';
495
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
496
+ }
497
+}
498
+
499
+export const ProductsView = new ProductsViewImpl();
\ No newline at end of file