function StockHistory({ salesUrl, token, branchUser }) { const [supplies, setSupplies] = React.useState([]); const [branches, setBranches] = React.useState([]); const [selectedBranch, setSelectedBranch] = React.useState(''); const [error, setError] = React.useState(''); const [loading, setLoading] = React.useState(false); const [startDate, setStartDate] = React.useState(''); const [endDate, setEndDate] = React.useState(''); const [selected, setSelected] = React.useState(null); const getEffectiveToken = () => { const storedBranchToken = typeof window !== 'undefined' ? (localStorage.getItem('branch_token') || '') : ''; return token || storedBranchToken || ''; }; const loadBranches = async () => { if (branchUser) return; try { const eff = getEffectiveToken(); const res = await fetch((salesUrl || '') + '/api/branches', { headers: { Authorization: 'Bearer ' + eff } }); const d = await res.json(); if (res.ok && Array.isArray(d.branches)) setBranches(d.branches); } catch (e) { // ignore } }; const loadSupplies = async (branchId) => { setLoading(true); setError(''); try { const storedBranchToken = typeof window !== 'undefined' ? (localStorage.getItem('branch_token') || '') : ''; const effectiveToken = token || storedBranchToken || ''; const url = new URL((salesUrl || '') + '/api/branch-supplies'); const bid = branchUser ? (branchUser.branch_id || branchUser._id || branchUser.id) : (branchId || ''); if (bid) url.searchParams.set('branch_id', bid); let res = await fetch(url.toString(), { headers: { Authorization: 'Bearer ' + effectiveToken } }); if (res.status === 401 && storedBranchToken && storedBranchToken !== effectiveToken) { res = await fetch(url.toString(), { headers: { Authorization: 'Bearer ' + storedBranchToken } }); } const data = await res.json(); if (!res.ok) throw new Error(data.message || 'Failed to load supplies'); setSupplies(Array.isArray(data.supplies) ? data.supplies : []); } catch (e) { setError(e.message); } finally { setLoading(false); } }; React.useEffect(() => { loadBranches(); if (branchUser) { const bid = branchUser.branch_id || branchUser._id || branchUser.id || ''; setSelectedBranch(bid); loadSupplies(bid); } else { loadSupplies(''); } }, [token, branchUser]); // Only show supplies that were created by branches (createdByType === 'branch') and match date range const visibleSupplies = React.useMemo(() => { if (!Array.isArray(supplies)) return []; let list = supplies.filter(s => String(s.createdByType || '').toLowerCase() === 'branch'); if (startDate) { try { const start = new Date(startDate); start.setHours(0,0,0,0); list = list.filter(s => { const when = s.createdAt ? new Date(s.createdAt) : null; if (!when) return false; return when.getTime() >= start.getTime(); }); } catch (e) { /* ignore invalid */ } } if (endDate) { try { const end = new Date(endDate); end.setHours(23,59,59,999); list = list.filter(s => { const when = s.createdAt ? new Date(s.createdAt) : null; if (!when) return false; return when.getTime() <= end.getTime(); }); } catch (e) { /* ignore invalid */ } } return list; }, [supplies, startDate, endDate]); return (
{/* Page Header */}

📊 Stock History

Track and manage your inventory supply history across all branches

{/* Statistics Cards */}
đŸ“Ļ
Total Supplies
{visibleSupplies.length}
Supply records found
💰
Total Value
{new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format( visibleSupplies.reduce((sum, s) => sum + ((s.supplierAmount || 0) + (s.gstAmount || 0)), 0) )}
Total supply value
đŸĸ
Active Branches
{new Set(visibleSupplies.map(s => s.branch_id || s.branchName).filter(Boolean)).size}
Branches with supplies
{/* Filters and Actions Section */}
{/* Filters Section */}

🔍 Filters & Search

{!branchUser && (
)}
setStartDate(e.target.value)} style={{ width: '100%', padding: '10px 12px', border: '2px solid #e5e7eb', borderRadius: '8px', fontSize: '14px', outline: 'none' }} />
setEndDate(e.target.value)} style={{ width: '100%', padding: '10px 12px', border: '2px solid #e5e7eb', borderRadius: '8px', fontSize: '14px', outline: 'none' }} />
{/* Action Buttons */}

⚡ Quick Actions

{!branchUser && ( )}
{/* Main Table Section */}

📋 Supply Records

{loading ? 'Loading supplies...' : `Showing ${visibleSupplies.length} supply record${visibleSupplies.length !== 1 ? 's' : ''}`}

{error && (
{error}
)} {loading ? (
âŗ
Loading Supply Records
Please wait while we fetch the data...
) : visibleSupplies.length === 0 ? (
đŸ“Ļ
No Supply Records Found
{startDate || endDate ? 'No supplies found for the selected date range' : 'No supply records available'}
) : (
{visibleSupplies.map(s => ( { try { const eff = getEffectiveToken(); const res = await fetch((salesUrl || '') + '/api/branch-supplies/' + s._id, { headers: { Authorization: 'Bearer ' + eff } }); const d = await res.json(); if (res.ok && d.supply) setSelected(d.supply); else setSelected(s); } catch (e) { setSelected(s); } }} style={{ cursor: 'pointer', borderBottom: '1px solid #f1f5f9', transition: 'background-color 0.2s ease' }} onMouseOver={(e) => e.target.parentElement.style.backgroundColor = '#f8fafc'} onMouseOut={(e) => e.target.parentElement.style.backgroundColor = 'transparent'} > ))}
Supplier Bank Supplier Amount GST Amount Created By Branch Created At
{s.supplierName || s.supplier || '-'}
{s.bankName || s.bank || '-'} {s.supplierAmount != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format(s.supplierAmount) : '-' } {s.gstAmount != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format(s.gstAmount) : '-' } {s.createdByType === 'branch' ? 'Branch' : (s.createdByType === 'admin' ? 'Admin' : (s.createdBy || 'Unknown'))}
{s.branch_name || s.branchName || (s.branch_id ? String(s.branch_id) : '-')}
{s.createdAt ? (
{new Date(s.createdAt).toLocaleDateString()}
{new Date(s.createdAt).toLocaleTimeString()}
) : '-'}
)}
{/* Supply Details Modal */} {selected && (
{/* Modal Header */}

📋 Supply Details

Complete information about this supply record

{/* Supply Summary Section */}

â„šī¸ Supply Information

Supplier
{selected.supplierName || selected.supplier || '-'}
Bank
{selected.bankName || selected.bank || '-'}
Supplier Amount
{selected.supplierAmount != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format(selected.supplierAmount) : '-' }
GST Amount
{selected.gstAmount != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format(selected.gstAmount) : '-' }
Total Amount
{new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format((selected.supplierAmount || 0) + (selected.gstAmount || 0))}
Created Date
{selected.createdAt ? new Date(selected.createdAt).toLocaleDateString() : '-'}
{selected.createdAt ? new Date(selected.createdAt).toLocaleTimeString() : ''}
{/* Items Section */}

đŸ“Ļ Product Items

{Array.isArray(selected.items) ? selected.items.length : 0} items
{Array.isArray(selected.items) && selected.items.length > 0 ? (
{selected.items.map((it, idx) => ( ))}
Product No Product Name Brand Model Qty Cost Price Validity
{it.productNo || it.productId || '-'}
{it.productName || '-'}
{it.brand || '-'} {it.model || '-'} {it.qty != null ? it.qty : (it.quantity != null ? it.quantity : '-')} {it.costPrice != null ? new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format(it.costPrice) : '-' } {it.validity ? new Date(it.validity).toLocaleDateString() : '-'}
) : (
đŸ“Ļ
No Items Found
This supply record doesn't contain any items
)}
)}
); } // Register view window.StockHistory = StockHistory;