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

Phase 9: Stock Kardex, low stock alerts, min stock, stock value KPI

Davood Mehraban committed Sep 18, 2026 at 20:48 UTC b5bcf64e3d51d4cbb53056ceb30ca85333d03a4a
3 files changed +621 -45
src/controllers/ProductController.js
+118 -10
@@ -64,14 +64,34 @@ class ProductControllerImpl {
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);
67 + if (filter.categoryId) list = list.filter(p => p.categoryId === filter.categoryId);
68 + if (filter.type === 'good') list = list.filter(p => p.trackInventory !== false);
69 + if (filter.type === 'service') list = list.filter(p => p.trackInventory === false);
70 +
71 + // فیلترهای جدید فاز ۹
72 + if (filter.stockStatus) {
73 + const ids = list.map(p => p.id);
74 + const stockMap = await this.getStockMap(ids);
75 + if (filter.stockStatus === 'low') {
76 + list = list.filter(p => {
77 + if (p.trackInventory === false) return false;
78 + const s = stockMap[p.id] || 0;
79 + const min = Number(p.minStock) || 0;
80 + return s <= min && s > 0;
81 + });
82 + } else if (filter.stockStatus === 'out') {
83 + list = list.filter(p => {
84 + if (p.trackInventory === false) return false;
85 + return (stockMap[p.id] || 0) <= 0;
86 + });
87 + } else if (filter.stockStatus === 'ok') {
88 + list = list.filter(p => {
89 + if (p.trackInventory === false) return false;
90 + const s = stockMap[p.id] || 0;
91 + const min = Number(p.minStock) || 0;
92 + return s > min;
93 + });
94 + }
95 }
96
97 return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
@@ -91,11 +111,13 @@ class ProductControllerImpl {
111 name: (data.name || '').trim(),
112 categoryId: data.categoryId || null,
113 unitId: data.unitId || null,
114 + unit: data.unit || 'عدد',
115 buyPrice: Number(data.buyPrice) || 0,
116 sellPrice: Number(data.sellPrice) || 0,
117 trackInventory: data.trackInventory !== false,
118 isActiveSell: data.isActiveSell !== false,
119 isActiveBuy: data.isActiveBuy !== false,
120 + minStock: Number(data.minStock) || 0,
121 description: (data.description || '').trim()
122 };
123 return await StorageService.put('products', product);
@@ -111,11 +133,13 @@ class ProductControllerImpl {
133 name: (data.name || '').trim(),
134 categoryId: data.categoryId || null,
135 unitId: data.unitId || null,
136 + unit: data.unit || existing.unit || 'عدد',
137 buyPrice: Number(data.buyPrice) || 0,
138 sellPrice: Number(data.sellPrice) || 0,
139 trackInventory: data.trackInventory !== false,
140 isActiveSell: data.isActiveSell !== false,
141 isActiveBuy: data.isActiveBuy !== false,
142 + minStock: Number(data.minStock) || 0,
143 description: (data.description || '').trim()
144 };
145 return await StorageService.put('products', updated);
@@ -180,8 +204,92 @@ class ProductControllerImpl {
204 const all = await StorageService.getByOwner('stock_movements', user.id);
205 return all
206 .filter(m => m.productId === productId)
183 - .sort((a, b) => (b.date || '').localeCompare(a.date || ''));
207 + .sort((a, b) => (a.date || '').localeCompare(b.date || ''));
208 + }
209 +
210 + // ============================================================
211 + // متدهای جدید فاز ۹
212 + // ============================================================
213 +
214 + /**
215 + * کاردکس کامل یک کالا با موجودی تجمعی
216 + */
217 + async getKardex(productId) {
218 + const movements = await this.getMovements(productId);
219 + let runningBalance = 0;
220 + let totalIn = 0, totalOut = 0;
221 + const rows = movements.map(m => {
222 + const qty = Number(m.qty) || 0;
223 + if (m.type === 'in') { runningBalance += qty; totalIn += qty; }
224 + else if (m.type === 'out') { runningBalance -= qty; totalOut += qty; }
225 + else if (m.type === 'adjust') { runningBalance = qty; }
226 + return {
227 + id: m.id,
228 + date: m.date,
229 + type: m.type,
230 + qty,
231 + balance: runningBalance,
232 + refType: m.refType,
233 + refId: m.refId,
234 + note: m.note || ''
235 + };
236 + });
237 + return { rows, totalIn, totalOut, finalBalance: runningBalance };
238 + }
239 +
240 + /**
241 + * کالاهای زیر نقطه سفارش
242 + */
243 + async getLowStockProducts() {
244 + const products = await this.getProducts({ type: 'good' });
245 + const ids = products.map(p => p.id);
246 + const stockMap = await this.getStockMap(ids);
247 + return products.filter(p => {
248 + const s = stockMap[p.id] || 0;
249 + const min = Number(p.minStock) || 0;
250 + return s <= min;
251 + }).map(p => ({
252 + ...p,
253 + currentStock: stockMap[p.id] || 0,
254 + minStock: Number(p.minStock) || 0,
255 + deficit: Math.max(0, (Number(p.minStock) || 0) - (stockMap[p.id] || 0))
256 + }));
257 + }
258 +
259 + /**
260 + * جمع ارزش موجودی انبار (بر اساس قیمت خرید و فروش)
261 + */
262 + async getTotalStockValue() {
263 + const products = await this.getProducts({ type: 'good' });
264 + const ids = products.map(p => p.id);
265 + const stockMap = await this.getStockMap(ids);
266 + let totalBuyValue = 0, totalSellValue = 0;
267 + products.forEach(p => {
268 + const stock = stockMap[p.id] || 0;
269 + if (stock > 0) {
270 + totalBuyValue += stock * (Number(p.buyPrice) || 0);
271 + totalSellValue += stock * (Number(p.sellPrice) || 0);
272 + }
273 + });
274 + return { totalBuyValue, totalSellValue, potentialProfit: totalSellValue - totalBuyValue };
275 + }
276 +
277 + /**
278 + * خلاصه‌ی حرکات انبار
279 + */
280 + async getMovementSummary() {
281 + const user = Auth.current();
282 + if (!user) return { total: 0, in: 0, out: 0, adjust: 0 };
283 + const all = await StorageService.getByOwner('stock_movements', user.id);
284 + const summary = { total: all.length, in: 0, out: 0, adjust: 0 };
285 + all.forEach(m => {
286 + if (m.type === 'in') summary.in++;
287 + else if (m.type === 'out') summary.out++;
288 + else if (m.type === 'adjust') summary.adjust++;
289 + });
290 + return summary;
291 }
292 }
293
187 -export const ProductController = new ProductControllerImpl();
\ No newline at end of file
294 +export const ProductController = new ProductControllerImpl();
295 +window.ProductController = ProductController;
\ No newline at end of file
src/views/ProductsView.js
+150 -35
@@ -8,10 +8,20 @@ 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 = '';
14 -let cache = { products: [], units: [], categories: [], stockMap: {} };
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() {
@@ -19,7 +29,7 @@ class ProductsViewImpl {
29 return `
30 <div class="page-title">
31 <h2>کالا و انبار</h2>
22 - <p>مدیریت کالاها، خدمات، واحدها و گروه‌ها</p>
32 + <p>مدیریت کالاها، خدمات، واحدها، گروه‌ها و موجودی انبار</p>
33 </div>
34
35 <div class="tabs">
@@ -50,6 +60,24 @@ class ProductsViewImpl {
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() {
@@ -71,17 +99,31 @@ class ProductsViewImpl {
99 }
100
101 // ============================================================
74 - // کالاها
102 + // تب کالاها
103 // ============================================================
104 renderProductsTab() {
77 - const filtered = currentSearch
78 - ? cache.products.filter(p => {
79 - const q = currentSearch.toLowerCase();
80 - return (p.name || '').toLowerCase().includes(q)
81 - || (p.code || '').toLowerCase().includes(q)
82 - || (p.barcode || '').toLowerCase().includes(q);
83 - })
84 - : cache.products;
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) {
@@ -89,8 +131,8 @@ class ProductsViewImpl {
131 <tr><td colspan="7">
132 <div class="empty-state">
133 <div class="icon">📦</div>
92 - <h3>هیچ کالایی ثبت نشده</h3>
93 - <p>اولین کالا یا خدمات خود را اضافه کنید</p>
134 + <h3>هیچ کالایی یافت نشد</h3>
135 + <p>${currentSearch || currentStockFilter ? 'فیلتر رو تغییر بده یا کالای جدید اضافه کن' : 'اولین کالا یا خدمات خود را اضافه کنید'}</p>
136 </div>
137 </td></tr>`;
138 } else {
@@ -98,7 +140,20 @@ class ProductsViewImpl {
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>
@@ -106,17 +161,13 @@ class ProductsViewImpl {
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>
109 - <td>${unit ? this._esc(unit.name) : '—'}</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>
112 - <td>
113 - ${isService
114 - ? '<span class="badge badge-muted">خدمت</span>'
115 - : `<strong style="color:${stock > 0 ? 'var(--success)' : stock < 0 ? 'var(--danger)' : 'var(--text-muted)'}">${Formatters.number(stock)}</strong>`
116 - }
117 - </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>
@@ -126,12 +177,59 @@ class ProductsViewImpl {
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
@@ -144,8 +242,8 @@ class ProductsViewImpl {
242 <th style="width:90px">واحد</th>
243 <th style="width:130px">خرید</th>
244 <th style="width:130px">فروش</th>
147 - <th style="width:90px">موجودی</th>
148 - <th style="width:100px">عملیات</th>
245 + <th style="width:120px">موجودی</th>
246 + <th style="width:130px">عملیات</th>
247 </tr>
248 </thead>
249 <tbody>${rowsHtml}</tbody>
@@ -162,6 +260,12 @@ class ProductsViewImpl {
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 // ============================================================
@@ -240,7 +344,7 @@ class ProductsViewImpl {
344 const data = product || {
345 code: '', barcode: '', name: '', categoryId: null, unitId: null,
346 buyPrice: 0, sellPrice: 0, trackInventory: true,
243 - isActiveSell: true, isActiveBuy: true, description: ''
347 + isActiveSell: true, isActiveBuy: true, minStock: 0, description: ''
348 };
349
350 const unitOptions = cache.units.map(u =>
@@ -294,7 +398,7 @@ class ProductsViewImpl {
398
399 <div class="form-group">
400 <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
297 - <input type="checkbox" id="pTrackInventory" ${data.trackInventory !== false ? 'checked' : ''} />
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">
@@ -302,6 +406,14 @@ class ProductsViewImpl {
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>
@@ -321,6 +433,12 @@ class ProductsViewImpl {
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 }
@@ -335,6 +453,7 @@ class ProductsViewImpl {
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
@@ -379,6 +498,13 @@ class ProductsViewImpl {
498 });
499 }
500
501 + // ============================================================
502 + // کاردکس
503 + // ============================================================
504 + openKardex(productId) {
505 + StockKardexModal.open(productId);
506 + }
507 +
508 // ============================================================
509 // فرم واحد
510 // ============================================================
@@ -409,24 +535,18 @@ class ProductsViewImpl {
535 const newUnit = await ProductController.createUnit(name, symbol);
536 Toast.success('واحد ثبت شد');
537
412 - // بستن مودال واحد (برمی‌گرده به مودال کالا اگه باز بود)
538 Modal.close();
414 -
415 - // cache واحدها رو به‌روز کن
539 cache.units = await ProductController.getUnits();
540
541 if (fromProductForm) {
419 - // ⬇️ اصلاح اصلی: dropdown واحد توی فرم کالا رو به‌روز کن
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('');
425 - // واحد جدید رو انتخاب کن
547 unitSelect.value = newUnit.id;
548 }
549 } else {
429 - // توی تب واحدها هستیم، جدول رو رفرش کن
550 const el = document.getElementById('products-tab-content');
551 if (el) el.innerHTML = this.renderTabContent();
552 }
@@ -486,20 +606,15 @@ class ProductsViewImpl {
606 const newCategory = await ProductController.createCategory(name, parentId);
607 Toast.success('گروه ثبت شد');
608
489 - // بستن مودال گروه
609 Modal.close();
491 -
492 - // cache گروه‌ها رو به‌روز کن
610 cache.categories = await ProductController.getCategories();
611
612 if (fromProductForm) {
496 - // ⬇️ اصلاح اصلی: dropdown گروه توی فرم کالا رو به‌روز کن
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('');
502 - // گروه جدید رو انتخاب کن
618 catSelect.value = newCategory.id;
619 }
620 } else {
src/views/StockKardexModal.js new
+353
@@ -0,0 +1,353 @@
1 +// ============================================================
2 +// StockKardexModal — مودال کاردکس کالا و اصلاح موجودی
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 { NumberInput } from '../utils/NumberInput.js';
10 +import { Jalali } from '../utils/Jalali.js';
11 +
12 +class StockKardexModalImpl {
13 + /**
14 + * باز کردن مودال کاردکس برای یک کالا
15 + */
16 + async open(productId) {
17 + const product = await ProductController.getProduct(productId);
18 + if (!product) { Toast.error('کالا یافت نشد'); return; }
19 +
20 + const kardex = await ProductController.getKardex(productId);
21 +
22 + const body = this._buildBody(product, kardex);
23 + const footer = this._buildFooter(product);
24 +
25 + Modal.open({
26 + title: `📊 کاردکس کالا: ${product.name}`,
27 + body,
28 + footer,
29 + size: 'lg'
30 + });
31 +
32 + window.__kardexProductId = productId;
33 + }
34 +
35 + _buildBody(product, kardex) {
36 + const isService = product.trackInventory === false;
37 + const minStock = Number(product.minStock) || 0;
38 + const currentStock = kardex.finalBalance;
39 + const isLow = !isService && currentStock <= minStock && currentStock > 0;
40 + const isOut = !isService && currentStock <= 0;
41 +
42 + let statusBadge = '';
43 + if (isService) statusBadge = '<span class="badge badge-muted">خدمت</span>';
44 + else if (isOut) statusBadge = '<span class="badge badge-danger">تمام‌شده</span>';
45 + else if (isLow) statusBadge = '<span class="badge badge-warning">کم‌موجود</span>';
46 + else statusBadge = '<span class="badge badge-success">موجود</span>';
47 +
48 + const rowsHtml = kardex.rows.length === 0
49 + ? `<tr><td colspan="7" style="text-align:center;padding:30px;color:var(--text-muted)">
50 + <div style="font-size:40px;margin-bottom:8px;opacity:.4">📭</div>
51 + هیچ حرکتی برای این کالا ثبت نشده
52 + </td></tr>`
53 + : [...kardex.rows].reverse().map(r => {
54 + const typeInfo = {
55 + in: { label: '📥 ورود', cls: 'badge-success', color: 'var(--success)' },
56 + out: { label: '📤 خروج', cls: 'badge-danger', color: 'var(--danger)' },
57 + adjust: { label: '⚙️ اصلاح', cls: 'badge-warning', color: 'var(--warning)' }
58 + }[r.type] || { label: r.type, cls: 'badge-muted', color: 'var(--text-muted)' };
59 +
60 + const isIn = r.type === 'in';
61 + const isOut = r.type === 'out';
62 + const isAdjust = r.type === 'adjust';
63 +
64 + const refLabel = this._refLabel(r.refType, r.refId);
65 +
66 + return `
67 + <tr>
68 + <td style="width:110px;font-size:11.5px">${this._formatDate(r.date)}</td>
69 + <td><span class="badge ${typeInfo.cls}">${typeInfo.label}</span></td>
70 + <td style="width:80px;text-align:center;font-weight:700;color:var(--success)">
71 + ${isIn ? Formatters.number(r.qty) : '—'}
72 + </td>
73 + <td style="width:80px;text-align:center;font-weight:700;color:var(--danger)">
74 + ${isOut ? Formatters.number(r.qty) : '—'}
75 + </td>
76 + <td style="width:100px;text-align:center;font-weight:800;color:${r.balance > 0 ? 'var(--primary)' : 'var(--text-muted)'}">
77 + ${Formatters.number(r.balance)}
78 + </td>
79 + <td style="width:140px;font-size:11.5px;color:var(--text-muted)">
80 + ${refLabel}
81 + </td>
82 + <td style="font-size:11.5px;color:var(--text-muted)">
83 + ${this._esc(r.note || '—')}
84 + </td>
85 + </tr>
86 + `;
87 + }).join('');
88 +
89 + return `
90 + <div class="grid-kpi" style="margin-bottom:14px">
91 + <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--primary)">
92 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">موجودی فعلی</div>
93 + <div style="font-size:18px;font-weight:800;color:${isOut ? 'var(--danger)' : isLow ? 'var(--warning)' : 'var(--success)'}">
94 + ${isService ? '—' : Formatters.number(currentStock)}
95 + <span style="font-size:11px;font-weight:500;color:var(--text-muted)">${product.unit || 'عدد'}</span>
96 + </div>
97 + <div style="margin-top:4px">${statusBadge}</div>
98 + </div>
99 +
100 + <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--success)">
101 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">جمع ورودی‌ها</div>
102 + <div style="font-size:16px;font-weight:800;color:var(--success)">${Formatters.number(kardex.totalIn)}</div>
103 + <div style="font-size:10.5px;color:var(--text-muted);margin-top:4px">${product.unit || 'عدد'}</div>
104 + </div>
105 +
106 + <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--danger)">
107 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">جمع خروجی‌ها</div>
108 + <div style="font-size:16px;font-weight:800;color:var(--danger)">${Formatters.number(kardex.totalOut)}</div>
109 + <div style="font-size:10.5px;color:var(--text-muted);margin-top:4px">${product.unit || 'عدد'}</div>
110 + </div>
111 +
112 + <div class="card" style="margin:0;padding:12px 14px;border-top:3px solid var(--warning)">
113 + <div style="font-size:11px;color:var(--text-muted);margin-bottom:4px">نقطه سفارش</div>
114 + <div style="font-size:16px;font-weight:800;color:var(--warning)">${Formatters.number(minStock)}</div>
115 + <div style="font-size:10.5px;color:var(--text-muted);margin-top:4px">${product.unit || 'عدد'}</div>
116 + </div>
117 + </div>
118 +
119 + <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;flex-wrap:wrap;gap:8px">
120 + <div style="font-size:12.5px;color:var(--text-muted)">
121 + ریز حرکات انبار (${Formatters.toPersianDigits(kardex.rows.length)} مورد)
122 + </div>
123 + <button class="btn btn-secondary btn-inline" style="font-size:12px;min-height:34px;padding:4px 12px" onclick="window.StockKardexModal.openAdjustModal('${product.id}')">
124 + ⚙️ اصلاح دستی موجودی
125 + </button>
126 + </div>
127 +
128 + <div class="table-wrap" style="max-height:400px;overflow-y:auto">
129 + <table style="min-width:700px">
130 + <thead style="position:sticky;top:0;z-index:2">
131 + <tr>
132 + <th>تاریخ</th>
133 + <th style="width:90px">نوع</th>
134 + <th style="width:80px;text-align:center">ورودی</th>
135 + <th style="width:80px;text-align:center">خروجی</th>
136 + <th style="width:100px;text-align:center">موجودی</th>
137 + <th style="width:140px">مرجع</th>
138 + <th>یادداشت</th>
139 + </tr>
140 + </thead>
141 + <tbody>${rowsHtml}</tbody>
142 + </table>
143 + </div>
144 + `;
145 + }
146 +
147 + _buildFooter(product) {
148 + return `
149 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">بستن</button>
150 + <button class="btn" onclick="window.StockKardexModal._printKardex('${product.id}')">🖨️ چاپ کاردکس</button>
151 + `;
152 + }
153 +
154 + // ============================================================
155 + // فرم اصلاح موجودی
156 + // ============================================================
157 + async openAdjustModal(productId) {
158 + const product = await ProductController.getProduct(productId);
159 + if (!product) return;
160 + const currentStock = await ProductController.getStock(productId);
161 +
162 + const body = `
163 + <div style="background:#fffbeb;border:1px solid #fcd34d;border-radius:10px;padding:12px 14px;margin-bottom:14px;font-size:12.5px;color:#78350f;line-height:1.7">
164 + ⚠️ <strong>توجه:</strong> این کار برای اصلاح موجودی انبار استفاده می‌شه — مثلاً وقتی که انبارگردانی کردی و موجودی واقعی با سیستم فرق داره.
165 + <br>
166 + موجودی ثبت‌شده در سیستم: <strong>${Formatters.number(currentStock)} ${this._esc(product.unit || 'عدد')}</strong>
167 + </div>
168 +
169 + <div class="form-group">
170 + <label class="form-label">موجودی واقعی جدید <span class="req">*</span></label>
171 + <input type="text" inputmode="numeric" class="form-control" id="adjQty" value="${NumberInput.format(currentStock)}" />
172 + <small style="color:var(--text-muted);font-size:11.5px;display:block;margin-top:4px">
173 + عددی که اینجا وارد می‌کنی، به‌عنوان موجودی نهایی تنظیم می‌شه.
174 + </small>
175 + </div>
176 +
177 + <div class="form-group">
178 + <label class="form-label">دلیل / یادداشت</label>
179 + <textarea class="form-control" id="adjNote" rows="2" placeholder="مثلاً: انبارگردانی پایان ماه، مغایرت در شمارش"></textarea>
180 + </div>
181 + `;
182 +
183 + const footer = `
184 + <button class="btn btn-secondary" onclick="FINORA.Modal.close()">انصراف</button>
185 + <button class="btn btn-warning" onclick="window.StockKardexModal.saveAdjust('${productId}')">⚙️ ثبت اصلاح</button>
186 + `;
187 +
188 + Modal.open({ title: '⚙️ اصلاح دستی موجودی', body, footer, size: 'sm' });
189 + }
190 +
191 + async saveAdjust(productId) {
192 + const newQty = NumberInput.parse(document.getElementById('adjQty').value);
193 + const note = (document.getElementById('adjNote').value || '').trim();
194 +
195 + if (isNaN(newQty) || newQty < 0) {
196 + Toast.warning('موجودی معتبر نیست');
197 + return;
198 + }
199 +
200 + try {
201 + await ProductController.addStockMovement(
202 + productId,
203 + 'adjust',
204 + newQty,
205 + 'manual',
206 + null,
207 + note || 'اصلاح دستی موجودی'
208 + );
209 +
210 + Toast.success('موجودی اصلاح شد');
211 +
212 + // بستن و باز کردن مجدد کاردکس
213 + Modal.close();
214 + setTimeout(() => this.open(productId), 300);
215 +
216 + // رفرش جدول کالاها اگه بازه
217 + if (window.ProductsView && window.ProductsView.reload) {
218 + window.ProductsView.reload().then(() => {
219 + const el = document.getElementById('products-tab-content');
220 + if (el && window.ProductsView.renderTabContent) {
221 + el.innerHTML = window.ProductsView.renderTabContent();
222 + }
223 + });
224 + }
225 + } catch (err) {
226 + console.error(err);
227 + Toast.error('خطا: ' + err.message);
228 + }
229 + }
230 +
231 + // ============================================================
232 + // چاپ کاردکس
233 + // ============================================================
234 + async _printKardex(productId) {
235 + const product = await ProductController.getProduct(productId);
236 + if (!product) return;
237 + const kardex = await ProductController.getKardex(productId);
238 +
239 + const rowsHtml = [...kardex.rows].reverse().map(r => {
240 + const isIn = r.type === 'in';
241 + const isOut = r.type === 'out';
242 + const typeLabel = isIn ? 'ورود' : isOut ? 'خروج' : 'اصلاح';
243 + return `
244 + <tr>
245 + <td>${this._formatDate(r.date)}</td>
246 + <td>${typeLabel}</td>
247 + <td>${isIn ? Formatters.number(r.qty) : '—'}</td>
248 + <td>${isOut ? Formatters.number(r.qty) : '—'}</td>
249 + <td>${Formatters.number(r.balance)}</td>
250 + <td>${this._refLabel(r.refType, r.refId)}</td>
251 + <td>${this._esc(r.note || '')}</td>
252 + </tr>
253 + `;
254 + }).join('');
255 +
256 + const printWin = window.open('', '_blank', 'width=900,height=700');
257 + if (!printWin) { Toast.error('پاپ‌آپ را فعال کنید'); return; }
258 +
259 + printWin.document.write(`
260 + <!DOCTYPE html>
261 + <html lang="fa" dir="rtl">
262 + <head>
263 + <meta charset="UTF-8" />
264 + <title>کاردکس ${product.name}</title>
265 + <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/misc/Farsi-Digits/Vazirmatn-FD-font-face.css" />
266 + <style>
267 + @page { size: A4 portrait; margin: 10mm; }
268 + * { box-sizing: border-box; margin: 0; padding: 0; }
269 + html, body { direction: rtl; text-align: right; font-family: 'Vazirmatn FD', Tahoma, sans-serif; background: #fff; color: #000; }
270 + body { padding: 10px; }
271 + h1 { font-size: 18px; color: #0d9488; text-align: center; margin-bottom: 6px; }
272 + .info { text-align: center; font-size: 12px; color: #64748b; margin-bottom: 16px; }
273 + .summary { display: flex; gap: 10px; margin-bottom: 16px; }
274 + .summary > div { flex: 1; border: 1px solid #cbd5e1; border-radius: 8px; padding: 10px; text-align: center; }
275 + .summary .val { font-size: 18px; font-weight: 800; color: #0d9488; margin-top: 4px; }
276 + .summary .lbl { font-size: 11px; color: #64748b; }
277 + table { width: 100%; border-collapse: collapse; }
278 + th, td { padding: 7px 9px; border: 1px solid #cbd5e1; text-align: right; font-size: 11.5px; }
279 + th { background: #f1f5f9; font-weight: 700; }
280 + .footer { margin-top: 20px; text-align: center; font-size: 10px; color: #94a3b8; padding-top: 10px; border-top: 1px dashed #cbd5e1; }
281 + </style>
282 + </head>
283 + <body>
284 + <h1>کاردکس کالا</h1>
285 + <div class="info">
286 + ${this._esc(product.name)}${product.code ? ' - کد: ' + Formatters.toPersianDigits(product.code) : ''} | تاریخ چاپ: ${Jalali.today()}
287 + </div>
288 + <div class="summary">
289 + <div>
290 + <div class="lbl">موجودی فعلی</div>
291 + <div class="val">${Formatters.number(kardex.finalBalance)}</div>
292 + </div>
293 + <div>
294 + <div class="lbl">جمع ورودی</div>
295 + <div class="val" style="color: #059669">${Formatters.number(kardex.totalIn)}</div>
296 + </div>
297 + <div>
298 + <div class="lbl">جمع خروجی</div>
299 + <div class="val" style="color: #dc2626">${Formatters.number(kardex.totalOut)}</div>
300 + </div>
301 + </div>
302 + <table>
303 + <thead>
304 + <tr>
305 + <th>تاریخ</th>
306 + <th>نوع</th>
307 + <th>ورودی</th>
308 + <th>خروجی</th>
309 + <th>موجودی</th>
310 + <th>مرجع</th>
311 + <th>یادداشت</th>
312 + </tr>
313 + </thead>
314 + <tbody>${rowsHtml}</tbody>
315 + </table>
316 + <div class="footer">فینورا پرو - سامانه مدیریت کسب‌وکار</div>
317 + </body>
318 + </html>
319 + `);
320 + printWin.document.close();
321 + setTimeout(() => { printWin.focus(); printWin.print(); }, 500);
322 + }
323 +
324 + // ============================================================
325 + // Helpers
326 + // ============================================================
327 + _formatDate(isoStr) {
328 + if (!isoStr) return '—';
329 + try {
330 + const d = new Date(isoStr);
331 + const jalali = Jalali.fromDate(d);
332 + const time = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
333 + return Formatters.toPersianDigits(`${jalali.year}/${String(jalali.month).padStart(2, '0')}/${String(jalali.day).padStart(2, '0')} - ${time}`);
334 + } catch (e) {
335 + return '—';
336 + }
337 + }
338 +
339 + _refLabel(refType, refId) {
340 + if (!refType || refType === 'manual') return '<span style="color:var(--text-muted)">دستی</span>';
341 + if (refType === 'invoice') return `فاکتور`;
342 + if (refType === 'purchase') return `خرید`;
343 + return refType;
344 + }
345 +
346 + _esc(s) {
347 + if (!s) return '';
348 + return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
349 + }
350 +}
351 +
352 +export const StockKardexModal = new StockKardexModalImpl();
353 +window.StockKardexModal = StockKardexModal;
\ No newline at end of file