فینورا پرو - سامانه جامع حسابداری و صدور فاکتور
docs/finora-master-execution-playbook
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
| 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 | import { NumberInput } from '../utils/NumberInput.js'; |
| 11 | import { StockKardexModal } from './StockKardexModal.js'; |
| 12 | |
| 13 | let currentTab = 'products'; |
| 14 | let currentSearch = ''; |
| 15 | let currentStockFilter = ''; // '' | 'low' | 'out' | 'ok' |
| 16 | let cache = { |
| 17 | products: [], |
| 18 | units: [], |
| 19 | categories: [], |
| 20 | stockMap: {}, |
| 21 | lowStockCount: 0, |
| 22 | outOfStockCount: 0, |
| 23 | totalStockValue: { totalBuyValue: 0, totalSellValue: 0, potentialProfit: 0 } |
| 24 | }; |
| 25 | |
| 26 | class ProductsViewImpl { |
| 27 | async render() { |
| 28 | await this.reload(); |
| 29 | return ` |
| 30 | <div class="page-title"> |
| 31 | <h2>کالا و انبار</h2> |
| 32 | <p>مدیریت کالاها، خدمات، واحدها، گروهها و موجودی انبار</p> |
| 33 | </div> |
| 34 | |
| 35 | <div class="tabs"> |
| 36 | <button class="tab-btn ${currentTab === 'products' ? 'active' : ''}" onclick="window.ProductsView._switchTab('products', event)"> |
| 37 | 📦 کالاها و خدمات |
| 38 | </button> |
| 39 | <button class="tab-btn ${currentTab === 'units' ? 'active' : ''}" onclick="window.ProductsView._switchTab('units', event)"> |
| 40 | 📏 واحدها |
| 41 | </button> |
| 42 | <button class="tab-btn ${currentTab === 'categories' ? 'active' : ''}" onclick="window.ProductsView._switchTab('categories', event)"> |
| 43 | 🗂️ گروهها |
| 44 | </button> |
| 45 | </div> |
| 46 | |
| 47 | <div id="products-tab-content"> |
| 48 | ${this.renderTabContent()} |
| 49 | </div> |
| 50 | `; |
| 51 | } |
| 52 | |
| 53 | onMount() { |
| 54 | window.ProductsView = this; |
| 55 | } |
| 56 | |
| 57 | async reload() { |
| 58 | cache.products = await ProductController.getProducts(); |
| 59 | cache.units = await ProductController.getUnits(); |
| 60 | cache.categories = await ProductController.getCategories(); |
| 61 | const ids = cache.products.map(p => p.id); |
| 62 | cache.stockMap = await ProductController.getStockMap(ids); |
| 63 | |
| 64 | // محاسبه KPI ها |
| 65 | let lowCount = 0, outCount = 0; |
| 66 | cache.products.forEach(p => { |
| 67 | if (p.trackInventory === false) return; |
| 68 | const s = cache.stockMap[p.id] || 0; |
| 69 | const min = Number(p.minStock) || 0; |
| 70 | if (s <= 0) outCount++; |
| 71 | else if (s <= min) lowCount++; |
| 72 | }); |
| 73 | cache.lowStockCount = lowCount; |
| 74 | cache.outOfStockCount = outCount; |
| 75 | |
| 76 | try { |
| 77 | cache.totalStockValue = await ProductController.getTotalStockValue(); |
| 78 | } catch (e) { |
| 79 | cache.totalStockValue = { totalBuyValue: 0, totalSellValue: 0, potentialProfit: 0 }; |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | renderTabContent() { |
| 84 | if (currentTab === 'products') return this.renderProductsTab(); |
| 85 | if (currentTab === 'units') return this.renderUnitsTab(); |
| 86 | if (currentTab === 'categories') return this.renderCategoriesTab(); |
| 87 | return ''; |
| 88 | } |
| 89 | |
| 90 | _switchTab(tab, evt) { |
| 91 | currentTab = tab; |
| 92 | const el = document.getElementById('products-tab-content'); |
| 93 | if (el) { |
| 94 | document.querySelectorAll('.tabs .tab-btn').forEach(btn => btn.classList.remove('active')); |
| 95 | const target = (evt && evt.target) ? evt.target.closest('.tab-btn') : null; |
| 96 | if (target) target.classList.add('active'); |
| 97 | el.innerHTML = this.renderTabContent(); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | // ============================================================ |
| 102 | // تب کالاها |
| 103 | // ============================================================ |
| 104 | renderProductsTab() { |
| 105 | let filtered = cache.products; |
| 106 | |
| 107 | if (currentSearch) { |
| 108 | const q = currentSearch.toLowerCase(); |
| 109 | filtered = filtered.filter(p => |
| 110 | (p.name || '').toLowerCase().includes(q) |
| 111 | || (p.code || '').toLowerCase().includes(q) |
| 112 | || (p.barcode || '').toLowerCase().includes(q) |
| 113 | ); |
| 114 | } |
| 115 | |
| 116 | if (currentStockFilter) { |
| 117 | filtered = filtered.filter(p => { |
| 118 | if (p.trackInventory === false) return false; |
| 119 | const s = cache.stockMap[p.id] || 0; |
| 120 | const min = Number(p.minStock) || 0; |
| 121 | if (currentStockFilter === 'low') return s <= min && s > 0; |
| 122 | if (currentStockFilter === 'out') return s <= 0; |
| 123 | if (currentStockFilter === 'ok') return s > min; |
| 124 | return true; |
| 125 | }); |
| 126 | } |
| 127 | |
| 128 | let rowsHtml = ''; |
| 129 | if (filtered.length === 0) { |
| 130 | rowsHtml = ` |
| 131 | <tr><td colspan="7"> |
| 132 | <div class="empty-state"> |
| 133 | <div class="icon">📦</div> |
| 134 | <h3>هیچ کالایی یافت نشد</h3> |
| 135 | <p>${currentSearch || currentStockFilter ? 'فیلتر رو تغییر بده یا کالای جدید اضافه کن' : 'اولین کالا یا خدمات خود را اضافه کنید'}</p> |
| 136 | </div> |
| 137 | </td></tr>`; |
| 138 | } else { |
| 139 | rowsHtml = filtered.map(p => { |
| 140 | const unit = cache.units.find(u => u.id === p.unitId); |
| 141 | const cat = cache.categories.find(c => c.id === p.categoryId); |
| 142 | const stock = cache.stockMap[p.id] || 0; |
| 143 | const minStock = Number(p.minStock) || 0; |
| 144 | const isService = p.trackInventory === false; |
| 145 | |
| 146 | let stockHtml; |
| 147 | if (isService) { |
| 148 | stockHtml = '<span class="badge badge-muted">خدمت</span>'; |
| 149 | } else if (stock <= 0) { |
| 150 | stockHtml = `<strong style="color:var(--danger)">${Formatters.number(stock)}</strong> <span class="badge badge-danger" style="font-size:9px">تمام</span>`; |
| 151 | } else if (stock <= minStock) { |
| 152 | stockHtml = `<strong style="color:var(--warning)">${Formatters.number(stock)}</strong> <span class="badge badge-warning" style="font-size:9px">کم</span>`; |
| 153 | } else { |
| 154 | stockHtml = `<strong style="color:var(--success)">${Formatters.number(stock)}</strong>`; |
| 155 | } |
| 156 | |
| 157 | return ` |
| 158 | <tr> |
| 159 | <td><strong>${this._esc(p.code || '—')}</strong></td> |
| 160 | <td> |
| 161 | <div style="font-weight:600">${this._esc(p.name)}</div> |
| 162 | ${cat ? `<small style="color:var(--text-muted);font-size:11px">${this._esc(cat.name)}</small>` : ''} |
| 163 | </td> |
| 164 | <td>${unit ? this._esc(unit.name) : (p.unit ? this._esc(p.unit) : '—')}</td> |
| 165 | <td>${Formatters.money(p.buyPrice)}</td> |
| 166 | <td>${Formatters.money(p.sellPrice)}</td> |
| 167 | <td>${stockHtml}</td> |
| 168 | <td> |
| 169 | <div class="row-actions"> |
| 170 | ${!isService ? `<button class="icon-btn-sm" title="کاردکس انبار" onclick="window.ProductsView.openKardex('${p.id}')">📊</button>` : ''} |
| 171 | <button class="icon-btn-sm" title="ویرایش" onclick="window.ProductsView.editProduct('${p.id}')">✏️</button> |
| 172 | <button class="icon-btn-sm danger" title="حذف" onclick="window.ProductsView.deleteProduct('${p.id}')">🗑️</button> |
| 173 | </div> |
| 174 | </td> |
| 175 | </tr> |
| 176 | `; |
| 177 | }).join(''); |
| 178 | } |
| 179 | |
| 180 | const totalStockVal = cache.totalStockValue.totalBuyValue || 0; |
| 181 | const totalSellVal = cache.totalStockValue.totalSellValue || 0; |
| 182 | |
| 183 | return ` |
| 184 | <div class="grid-kpi"> |
| 185 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--primary)"> |
| 186 | <div class="kpi-card-icon" style="background:#eff6ff;color:var(--primary)">📦</div> |
| 187 | <div style="flex:1"> |
| 188 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">تعداد کالا</div> |
| 189 | <div style="font-size:17px;font-weight:800;color:var(--primary)">${Formatters.number(cache.products.length)}</div> |
| 190 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">${Formatters.number(cache.products.filter(p => p.trackInventory !== false).length)} فیزیکی</div> |
| 191 | </div> |
| 192 | </div> |
| 193 | |
| 194 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--success)"> |
| 195 | <div class="kpi-card-icon" style="background:#ecfdf5;color:var(--success)">💰</div> |
| 196 | <div style="flex:1"> |
| 197 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">ارزش موجودی (خرید)</div> |
| 198 | <div style="font-size:14px;font-weight:800;color:var(--success)">${Formatters.money(totalStockVal)}</div> |
| 199 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">فروش: ${Formatters.money(totalSellVal)}</div> |
| 200 | </div> |
| 201 | </div> |
| 202 | |
| 203 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--warning);cursor:${cache.lowStockCount > 0 ? 'pointer' : 'default'}" onclick="window.ProductsView._setStockFilter('low')"> |
| 204 | <div class="kpi-card-icon" style="background:#fffbeb;color:var(--warning)">⚠️</div> |
| 205 | <div style="flex:1"> |
| 206 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">کالاهای کمموجود</div> |
| 207 | <div style="font-size:17px;font-weight:800;color:var(--warning)">${Formatters.number(cache.lowStockCount)}</div> |
| 208 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">زیر نقطه سفارش</div> |
| 209 | </div> |
| 210 | </div> |
| 211 | |
| 212 | <div class="card kpi-card" style="margin:0;border-top:3px solid var(--danger);cursor:${cache.outOfStockCount > 0 ? 'pointer' : 'default'}" onclick="window.ProductsView._setStockFilter('out')"> |
| 213 | <div class="kpi-card-icon" style="background:#fef2f2;color:var(--danger)">🚨</div> |
| 214 | <div style="flex:1"> |
| 215 | <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">کالاهای تمامشده</div> |
| 216 | <div style="font-size:17px;font-weight:800;color:var(--danger)">${Formatters.number(cache.outOfStockCount)}</div> |
| 217 | <div style="font-size:10.5px;color:var(--text-muted);margin-top:2px">موجودی صفر</div> |
| 218 | </div> |
| 219 | </div> |
| 220 | </div> |
| 221 | |
| 222 | <div class="toolbar"> |
| 223 | <div class="search-input-wrap"> |
| 224 | <span class="icon">🔍</span> |
| 225 | <input type="text" class="form-control" id="productSearch" placeholder="جستجو بر اساس نام، کد یا بارکد..." value="${this._esc(currentSearch)}" oninput="window.ProductsView._onSearch(this.value)" /> |
| 226 | </div> |
| 227 | <select class="form-control" style="width:auto;min-width:160px" onchange="window.ProductsView._setStockFilter(this.value)"> |
| 228 | <option value="" ${currentStockFilter === '' ? 'selected' : ''}>همه کالاها</option> |
| 229 | <option value="low" ${currentStockFilter === 'low' ? 'selected' : ''}>⚠️ کمموجود</option> |
| 230 | <option value="out" ${currentStockFilter === 'out' ? 'selected' : ''}>🚨 تمامشده</option> |
| 231 | <option value="ok" ${currentStockFilter === 'ok' ? 'selected' : ''}>✅ موجودی سالم</option> |
| 232 | </select> |
| 233 | <button class="btn" onclick="window.ProductsView.openProductModal()">➕ کالای جدید</button> |
| 234 | </div> |
| 235 | |
| 236 | <div class="table-wrap"> |
| 237 | <table> |
| 238 | <thead> |
| 239 | <tr> |
| 240 | <th style="width:100px">کد</th> |
| 241 | <th>نام</th> |
| 242 | <th style="width:90px">واحد</th> |
| 243 | <th style="width:130px">خرید</th> |
| 244 | <th style="width:130px">فروش</th> |
| 245 | <th style="width:120px">موجودی</th> |
| 246 | <th style="width:130px">عملیات</th> |
| 247 | </tr> |
| 248 | </thead> |
| 249 | <tbody>${rowsHtml}</tbody> |
| 250 | </table> |
| 251 | </div> |
| 252 | `; |
| 253 | } |
| 254 | |
| 255 | _onSearch(val) { |
| 256 | currentSearch = val; |
| 257 | const el = document.getElementById('products-tab-content'); |
| 258 | if (el) el.innerHTML = this.renderProductsTab(); |
| 259 | const input = document.getElementById('productSearch'); |
| 260 | if (input) { input.focus(); input.setSelectionRange(val.length, val.length); } |
| 261 | } |
| 262 | |
| 263 | _setStockFilter(filter) { |
| 264 | currentStockFilter = filter; |
| 265 | const el = document.getElementById('products-tab-content'); |
| 266 | if (el) el.innerHTML = this.renderProductsTab(); |
| 267 | } |
| 268 | |
| 269 | // ============================================================ |
| 270 | // واحدها |
| 271 | // ============================================================ |
| 272 | renderUnitsTab() { |
| 273 | let rowsHtml = ''; |
| 274 | if (cache.units.length === 0) { |
| 275 | rowsHtml = `<tr><td colspan="3"><div class="empty-state"><div class="icon">📏</div><h3>واحدی ثبت نشده</h3><p>واحدهای اندازهگیری مثل عدد، کیلوگرم، متر را اضافه کنید</p></div></td></tr>`; |
| 276 | } else { |
| 277 | rowsHtml = cache.units.map(u => ` |
| 278 | <tr> |
| 279 | <td><strong>${this._esc(u.name)}</strong></td> |
| 280 | <td>${this._esc(u.symbol || '—')}</td> |
| 281 | <td> |
| 282 | <div class="row-actions"> |
| 283 | <button class="icon-btn-sm danger" title="حذف" onclick="window.ProductsView.deleteUnit('${u.id}')">🗑️</button> |
| 284 | </div> |
| 285 | </td> |
| 286 | </tr> |
| 287 | `).join(''); |
| 288 | } |
| 289 | return ` |
| 290 | <div class="toolbar"> |
| 291 | <button class="btn" onclick="window.ProductsView.openUnitModal()">➕ واحد جدید</button> |
| 292 | </div> |
| 293 | <div class="table-wrap"> |
| 294 | <table> |
| 295 | <thead><tr><th>نام واحد</th><th>نماد</th><th style="width:100px">عملیات</th></tr></thead> |
| 296 | <tbody>${rowsHtml}</tbody> |
| 297 | </table> |
| 298 | </div> |
| 299 | `; |
| 300 | } |
| 301 | |
| 302 | // ============================================================ |
| 303 | // گروهها |
| 304 | // ============================================================ |
| 305 | renderCategoriesTab() { |
| 306 | let rowsHtml = ''; |
| 307 | if (cache.categories.length === 0) { |
| 308 | rowsHtml = `<tr><td colspan="3"><div class="empty-state"><div class="icon">🗂️</div><h3>گروهی ثبت نشده</h3><p>کالاها را در گروههای مختلف دستهبندی کنید</p></div></td></tr>`; |
| 309 | } else { |
| 310 | rowsHtml = cache.categories.map(c => { |
| 311 | const parent = c.parentId ? cache.categories.find(x => x.id === c.parentId) : null; |
| 312 | return ` |
| 313 | <tr> |
| 314 | <td><strong>${this._esc(c.name)}</strong></td> |
| 315 | <td>${parent ? this._esc(parent.name) : '<span class="badge badge-muted">بدون والد</span>'}</td> |
| 316 | <td> |
| 317 | <div class="row-actions"> |
| 318 | <button class="icon-btn-sm danger" title="حذف" onclick="window.ProductsView.deleteCategory('${c.id}')">🗑️</button> |
| 319 | </div> |
| 320 | </td> |
| 321 | </tr> |
| 322 | `; |
| 323 | }).join(''); |
| 324 | } |
| 325 | return ` |
| 326 | <div class="toolbar"> |
| 327 | <button class="btn" onclick="window.ProductsView.openCategoryModal()">➕ گروه جدید</button> |
| 328 | </div> |
| 329 | <div class="table-wrap"> |
| 330 | <table> |
| 331 | <thead><tr><th>نام گروه</th><th>گروه والد</th><th style="width:100px">عملیات</th></tr></thead> |
| 332 | <tbody>${rowsHtml}</tbody> |
| 333 | </table> |
| 334 | </div> |
| 335 | `; |
| 336 | } |
| 337 | |
| 338 | // ============================================================ |
| 339 | // فرم کالا |
| 340 | // ============================================================ |
| 341 | async openProductModal(productId = null) { |
| 342 | const product = productId ? await ProductController.getProduct(productId) : null; |
| 343 | const isEdit = !!product; |
| 344 | const data = product || { |
| 345 | code: '', barcode: '', name: '', categoryId: null, unitId: null, |
| 346 | buyPrice: 0, sellPrice: 0, trackInventory: true, |
| 347 | isActiveSell: true, isActiveBuy: true, minStock: 0, description: '' |
| 348 | }; |
| 349 | |
| 350 | const unitOptions = cache.units.map(u => |
| 351 | `<option value="${u.id}" ${data.unitId === u.id ? 'selected' : ''}>${this._esc(u.name)}</option>` |
| 352 | ).join(''); |
| 353 | |
| 354 | const catOptions = cache.categories.map(c => |
| 355 | `<option value="${c.id}" ${data.categoryId === c.id ? 'selected' : ''}>${this._esc(c.name)}</option>` |
| 356 | ).join(''); |
| 357 | |
| 358 | const body = ` |
| 359 | <div class="form-row"> |
| 360 | <div class="form-group"> |
| 361 | <label class="form-label">کد کالا</label> |
| 362 | <input type="text" class="form-control" id="pCode" value="${this._esc(data.code)}" placeholder="مثلاً ۱۰۱" /> |
| 363 | </div> |
| 364 | <div class="form-group"> |
| 365 | <label class="form-label">بارکد</label> |
| 366 | <input type="text" class="form-control" id="pBarcode" value="${this._esc(data.barcode)}" /> |
| 367 | </div> |
| 368 | </div> |
| 369 | |
| 370 | <div class="form-group"> |
| 371 | <label class="form-label">نام کالا / خدمت <span class="req">*</span></label> |
| 372 | <input type="text" class="form-control" id="pName" value="${this._esc(data.name)}" placeholder="مثلاً هارد سرور" /> |
| 373 | </div> |
| 374 | |
| 375 | <div class="form-row"> |
| 376 | <div class="form-group"> |
| 377 | <label class="form-label">واحد</label> |
| 378 | <select class="form-control" id="pUnit">${unitOptions}</select> |
| 379 | <button class="btn-add-inline" onclick="window.ProductsView.openUnitModal(true)">➕ واحد جدید</button> |
| 380 | </div> |
| 381 | <div class="form-group"> |
| 382 | <label class="form-label">گروه</label> |
| 383 | <select class="form-control" id="pCategory">${catOptions}</select> |
| 384 | <button class="btn-add-inline" onclick="window.ProductsView.openCategoryModal(true)">➕ گروه جدید</button> |
| 385 | </div> |
| 386 | </div> |
| 387 | |
| 388 | <div class="form-row"> |
| 389 | <div class="form-group"> |
| 390 | <label class="form-label">قیمت خرید (ریال)</label> |
| 391 | <input type="text" inputmode="numeric" class="form-control" id="pBuyPrice" value="${NumberInput.format(data.buyPrice || 0)}" /> |
| 392 | </div> |
| 393 | <div class="form-group"> |
| 394 | <label class="form-label">قیمت فروش (ریال)</label> |
| 395 | <input type="text" inputmode="numeric" class="form-control" id="pSellPrice" value="${NumberInput.format(data.sellPrice || 0)}" /> |
| 396 | </div> |
| 397 | </div> |
| 398 | |
| 399 | <div class="form-group"> |
| 400 | <label style="display:flex;align-items:center;gap:8px;cursor:pointer"> |
| 401 | <input type="checkbox" id="pTrackInventory" ${data.trackInventory !== false ? 'checked' : ''} onchange="window.ProductsView._toggleMinStock()" /> |
| 402 | <span style="font-size:13px">پیگیری موجودی انبار</span> |
| 403 | </label> |
| 404 | <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:2px;padding-right:24px"> |
| 405 | اگه این گزینه رو بردارید، این مورد به عنوان «خدمت» ثبت میشه و موجودی براش محاسبه نمیشه. |
| 406 | </small> |
| 407 | </div> |
| 408 | |
| 409 | <div class="form-group" id="minStockBox" style="display:${data.trackInventory !== false ? 'block' : 'none'}"> |
| 410 | <label class="form-label">نقطه سفارش (حداقل موجودی)</label> |
| 411 | <input type="text" inputmode="numeric" class="form-control" id="pMinStock" value="${NumberInput.format(data.minStock || 0)}" /> |
| 412 | <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px"> |
| 413 | وقتی موجودی به این عدد یا کمتر رسید، هشدار «کمموجود» نمایش داده میشه. |
| 414 | </small> |
| 415 | </div> |
| 416 | |
| 417 | <div class="form-group"> |
| 418 | <label class="form-label">توضیحات</label> |
| 419 | <textarea class="form-control" id="pDescription" placeholder="توضیحات اضافی...">${this._esc(data.description)}</textarea> |
| 420 | </div> |
| 421 | `; |
| 422 | |
| 423 | const footer = ` |
| 424 | <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button> |
| 425 | <button class="btn" onclick="window.ProductsView.saveProduct(${isEdit ? `'${productId}'` : 'null'})">💾 ذخیره</button> |
| 426 | `; |
| 427 | |
| 428 | Modal.open({ |
| 429 | title: isEdit ? 'ویرایش کالا' : 'کالای جدید', |
| 430 | body, |
| 431 | footer, |
| 432 | size: 'md' |
| 433 | }); |
| 434 | } |
| 435 | |
| 436 | _toggleMinStock() { |
| 437 | const checked = document.getElementById('pTrackInventory').checked; |
| 438 | document.getElementById('minStockBox').style.display = checked ? 'block' : 'none'; |
| 439 | } |
| 440 | |
| 441 | // ⬇️ متد ویرایش کالا |
| 442 | async editProduct(id) { |
| 443 | await this.openProductModal(id); |
| 444 | } |
| 445 | |
| 446 | async saveProduct(id) { |
| 447 | const data = { |
| 448 | code: document.getElementById('pCode').value, |
| 449 | barcode: document.getElementById('pBarcode').value, |
| 450 | name: document.getElementById('pName').value, |
| 451 | unitId: document.getElementById('pUnit').value || null, |
| 452 | categoryId: document.getElementById('pCategory').value || null, |
| 453 | buyPrice: NumberInput.parse(document.getElementById('pBuyPrice').value), |
| 454 | sellPrice: NumberInput.parse(document.getElementById('pSellPrice').value), |
| 455 | trackInventory: document.getElementById('pTrackInventory').checked, |
| 456 | minStock: NumberInput.parse(document.getElementById('pMinStock')?.value || '0'), |
| 457 | description: document.getElementById('pDescription').value |
| 458 | }; |
| 459 | |
| 460 | if (!data.name.trim()) { |
| 461 | Toast.warning('نام کالا الزامی است'); |
| 462 | return; |
| 463 | } |
| 464 | |
| 465 | try { |
| 466 | if (id) { |
| 467 | await ProductController.updateProduct(id, data); |
| 468 | Toast.success('کالا با موفقیت ویرایش شد'); |
| 469 | } else { |
| 470 | await ProductController.createProduct(data); |
| 471 | Toast.success('کالا با موفقیت ثبت شد'); |
| 472 | } |
| 473 | Modal.close(); |
| 474 | await this.reload(); |
| 475 | document.getElementById('products-tab-content').innerHTML = this.renderTabContent(); |
| 476 | } catch (err) { |
| 477 | Toast.error('خطا در ذخیرهسازی: ' + err.message); |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | async deleteProduct(id) { |
| 482 | const product = cache.products.find(p => p.id === id); |
| 483 | Modal.confirm({ |
| 484 | title: 'حذف کالا', |
| 485 | message: `آیا از حذف «${this._esc(product?.name || '')}» مطمئن هستید؟ این عمل قابل بازگشت نیست.`, |
| 486 | confirmText: 'حذف', |
| 487 | danger: true, |
| 488 | onConfirm: async () => { |
| 489 | try { |
| 490 | await ProductController.deleteProduct(id); |
| 491 | Toast.success('کالا حذف شد'); |
| 492 | await this.reload(); |
| 493 | document.getElementById('products-tab-content').innerHTML = this.renderTabContent(); |
| 494 | } catch (err) { |
| 495 | Toast.error('خطا در حذف: ' + err.message); |
| 496 | } |
| 497 | } |
| 498 | }); |
| 499 | } |
| 500 | |
| 501 | // ============================================================ |
| 502 | // کاردکس |
| 503 | // ============================================================ |
| 504 | openKardex(productId) { |
| 505 | StockKardexModal.open(productId); |
| 506 | } |
| 507 | |
| 508 | // ============================================================ |
| 509 | // فرم واحد |
| 510 | // ============================================================ |
| 511 | openUnitModal(fromProductForm = false) { |
| 512 | const body = ` |
| 513 | <div class="form-group"> |
| 514 | <label class="form-label">نام واحد <span class="req">*</span></label> |
| 515 | <input type="text" class="form-control" id="uName" placeholder="مثلاً عدد، کیلوگرم، متر، بسته" /> |
| 516 | </div> |
| 517 | <div class="form-group"> |
| 518 | <label class="form-label">نماد (اختیاری)</label> |
| 519 | <input type="text" class="form-control" id="uSymbol" placeholder="مثلاً kg، m" /> |
| 520 | </div> |
| 521 | `; |
| 522 | const footer = ` |
| 523 | <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button> |
| 524 | <button class="btn" onclick="window.ProductsView.saveUnit(${fromProductForm})">💾 ذخیره</button> |
| 525 | `; |
| 526 | Modal.open({ title: 'واحد جدید', body, footer, size: 'sm' }); |
| 527 | } |
| 528 | |
| 529 | async saveUnit(fromProductForm) { |
| 530 | const name = document.getElementById('uName').value; |
| 531 | const symbol = document.getElementById('uSymbol').value; |
| 532 | if (!name.trim()) { Toast.warning('نام واحد الزامی است'); return; } |
| 533 | |
| 534 | try { |
| 535 | const newUnit = await ProductController.createUnit(name, symbol); |
| 536 | Toast.success('واحد ثبت شد'); |
| 537 | |
| 538 | Modal.close(); |
| 539 | cache.units = await ProductController.getUnits(); |
| 540 | |
| 541 | if (fromProductForm) { |
| 542 | const unitSelect = document.getElementById('pUnit'); |
| 543 | if (unitSelect) { |
| 544 | unitSelect.innerHTML = cache.units.map(u => |
| 545 | `<option value="${u.id}">${this._esc(u.name)}</option>` |
| 546 | ).join(''); |
| 547 | unitSelect.value = newUnit.id; |
| 548 | } |
| 549 | } else { |
| 550 | const el = document.getElementById('products-tab-content'); |
| 551 | if (el) el.innerHTML = this.renderTabContent(); |
| 552 | } |
| 553 | } catch (err) { |
| 554 | Toast.error('خطا: ' + err.message); |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | async deleteUnit(id) { |
| 559 | Modal.confirm({ |
| 560 | title: 'حذف واحد', |
| 561 | message: 'آیا از حذف این واحد مطمئن هستید؟', |
| 562 | confirmText: 'حذف', |
| 563 | danger: true, |
| 564 | onConfirm: async () => { |
| 565 | await ProductController.deleteUnit(id); |
| 566 | Toast.success('واحد حذف شد'); |
| 567 | await this.reload(); |
| 568 | document.getElementById('products-tab-content').innerHTML = this.renderTabContent(); |
| 569 | } |
| 570 | }); |
| 571 | } |
| 572 | |
| 573 | // ============================================================ |
| 574 | // فرم گروه |
| 575 | // ============================================================ |
| 576 | openCategoryModal(fromProductForm = false) { |
| 577 | const parentOptions = cache.categories.map(c => |
| 578 | `<option value="${c.id}">${this._esc(c.name)}</option>` |
| 579 | ).join(''); |
| 580 | const body = ` |
| 581 | <div class="form-group"> |
| 582 | <label class="form-label">نام گروه <span class="req">*</span></label> |
| 583 | <input type="text" class="form-control" id="cName" placeholder="مثلاً لوازم اداری" /> |
| 584 | </div> |
| 585 | <div class="form-group"> |
| 586 | <label class="form-label">گروه والد (اختیاری)</label> |
| 587 | <select class="form-control" id="cParent"> |
| 588 | <option value="">— بدون والد —</option> |
| 589 | ${parentOptions} |
| 590 | </select> |
| 591 | </div> |
| 592 | `; |
| 593 | const footer = ` |
| 594 | <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button> |
| 595 | <button class="btn" onclick="window.ProductsView.saveCategory(${fromProductForm})">💾 ذخیره</button> |
| 596 | `; |
| 597 | Modal.open({ title: 'گروه جدید', body, footer, size: 'sm' }); |
| 598 | } |
| 599 | |
| 600 | async saveCategory(fromProductForm) { |
| 601 | const name = document.getElementById('cName').value; |
| 602 | const parentId = document.getElementById('cParent').value || null; |
| 603 | if (!name.trim()) { Toast.warning('نام گروه الزامی است'); return; } |
| 604 | |
| 605 | try { |
| 606 | const newCategory = await ProductController.createCategory(name, parentId); |
| 607 | Toast.success('گروه ثبت شد'); |
| 608 | |
| 609 | Modal.close(); |
| 610 | cache.categories = await ProductController.getCategories(); |
| 611 | |
| 612 | if (fromProductForm) { |
| 613 | const catSelect = document.getElementById('pCategory'); |
| 614 | if (catSelect) { |
| 615 | catSelect.innerHTML = cache.categories.map(c => |
| 616 | `<option value="${c.id}">${this._esc(c.name)}</option>` |
| 617 | ).join(''); |
| 618 | catSelect.value = newCategory.id; |
| 619 | } |
| 620 | } else { |
| 621 | const el = document.getElementById('products-tab-content'); |
| 622 | if (el) el.innerHTML = this.renderTabContent(); |
| 623 | } |
| 624 | } catch (err) { |
| 625 | Toast.error('خطا: ' + err.message); |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | async deleteCategory(id) { |
| 630 | Modal.confirm({ |
| 631 | title: 'حذف گروه', |
| 632 | message: 'آیا از حذف این گروه مطمئن هستید؟', |
| 633 | confirmText: 'حذف', |
| 634 | danger: true, |
| 635 | onConfirm: async () => { |
| 636 | await ProductController.deleteCategory(id); |
| 637 | Toast.success('گروه حذف شد'); |
| 638 | await this.reload(); |
| 639 | document.getElementById('products-tab-content').innerHTML = this.renderTabContent(); |
| 640 | } |
| 641 | }); |
| 642 | } |
| 643 | |
| 644 | _esc(s) { |
| 645 | if (!s) return ''; |
| 646 | return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | export const ProductsView = new ProductsViewImpl(); |
| 651 | window.ProductsView = ProductsView; |