function MobileBranchSupplyHistory({ salesUrl, token }) { const [data, setData] = React.useState({ supplies: [], branches: [], loading: true, error: null }); const [branchId, setBranchId] = React.useState(''); const [filterDate, setFilterDate] = React.useState(''); const [imesFilter, setImesFilter] = React.useState(''); const decodeJwt = (tk) => { try { const base64 = tk.split('.')[1] || ''; const json = atob(base64.replace(/-/g, '+').replace(/_/g, '/')); return JSON.parse(json); } catch (_e) { return null; } }; const storedBranchToken = typeof window !== 'undefined' ? (localStorage.getItem('branch_token') || '') : ''; const effectiveToken = token || storedBranchToken || ''; const decodedEffective = effectiveToken ? decodeJwt(effectiveToken) : null; const branchUserDecoded = decodedEffective && decodedEffective.branch_id ? decodedEffective : null; const authedFetch = React.useCallback(async (url, init) => { let res = await fetch(url, { ...(init || {}), headers: { ...((init && init.headers) || {}), Authorization: 'Bearer ' + effectiveToken } }); if (res.status === 401 && storedBranchToken && storedBranchToken !== effectiveToken) { res = await fetch(url, { ...(init || {}), headers: { ...((init && init.headers) || {}), Authorization: 'Bearer ' + storedBranchToken } }); } return res; }, [effectiveToken, storedBranchToken]); const loadData = React.useCallback(async (bid = '') => { try { setData((prev) => ({ ...prev, loading: true, error: null })); const branchesRes = await authedFetch(salesUrl + '/api/branches'); const branchesData = await branchesRes.json(); const url = new URL(salesUrl + '/api/branch-supplies'); if (bid) url.searchParams.set('branch_id', bid); const suppliesRes = await authedFetch(url.toString()); const suppliesData = await suppliesRes.json(); if (!branchesRes.ok) throw new Error(branchesData.message || 'Failed to load branches'); if (!suppliesRes.ok) throw new Error(suppliesData.message || 'Failed to load supplies'); setData({ branches: Array.isArray(branchesData.branches) ? branchesData.branches : [], supplies: Array.isArray(suppliesData.supplies) ? suppliesData.supplies : [], loading: false, error: null }); } catch (error) { if (!branchUserDecoded) { setData((prev) => ({ ...prev, loading: false, error: error.message })); } else { setData((prev) => ({ ...prev, loading: false, error: null })); } } }, [salesUrl, authedFetch, branchUserDecoded]); React.useEffect(() => { loadData(); }, [loadData]); const onBranchChange = (e) => { const id = e.target.value; setBranchId(id); loadData(id); }; const processedData = React.useMemo(() => { const onlyAdmin = (arr) => (Array.isArray(arr) ? arr.filter((s) => String(s.createdByType || '').toLowerCase() === 'admin') : []); const baseArr = !filterDate ? data.supplies : (data.supplies || []).filter((supply) => { const selectedDate = new Date(filterDate).toDateString(); const supplyDate = new Date(supply.createdAt || supply.updatedAt || new Date()).toDateString(); return supplyDate === selectedDate; }); const filtered = onlyAdmin(baseArr); const flat = []; filtered.forEach((s) => { const when = s.createdAt || s.updatedAt || new Date(); const supplier = s.supplier_id?.supplierName || s.supplierName || '-'; (Array.isArray(s.items) ? s.items : []).forEach((it) => { const imesStr = Array.isArray(it.imes) ? it.imes.join(',') : ''; if (imesFilter && imesStr.toLowerCase().indexOf(imesFilter.toLowerCase()) === -1) return; flat.push({ supplier, productNo: it.productNo || it.productId || '-', productName: it.productName || it.name || '-', brand: it.brand || '-', model: it.model || '-', costPrice: it.costPrice ?? it.cost ?? 0, validity: it.validity || null, pct: it.pct ?? null, unitPrice: it.unitSellingPrice ?? it.sellingPrice ?? 0, qty: it.qty ?? 0, value: it.value ?? ((it.unitSellingPrice ?? it.sellingPrice ?? 0) * (it.qty ?? 0)), when }); }); }); return flat; }, [data.supplies, filterDate, imesFilter]); const currency = (n) => new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 2 }).format(n || 0); if (data.loading) { return (
| Supplier | Product No | Product Name | Brand | Model | Cost Price | Product Validity | Selling Price (pct / price) | Unit Price | Supply Qty | Supply Value | Sending Date & Time |
|---|---|---|---|---|---|---|---|---|---|---|---|
| {r.supplier} | {r.productNo} | {r.productName} | {r.brand} | {r.model} | {r.costPrice != null ? currency(r.costPrice) : '-'} | {r.validity ? new Date(r.validity).toLocaleDateString() : '-'} | {r.pct != null ? `${r.pct}% / ${currency(r.unitPrice)}` : '-'} | {currency(r.unitPrice)} | {r.qty} | {currency(r.value)} | {new Date(r.when).toLocaleString()} |