// Mobile Supplier Credits - Admin-only view for tracking credit purchases and payments function MobileSupplierCredits({ salesUrl, token }) { const [credits, setCredits] = React.useState([]); const [summary, setSummary] = React.useState([]); const [loading, setLoading] = React.useState(true); const [error, setError] = React.useState(''); const [activeTab, setActiveTab] = React.useState('summary'); const [payModal, setPayModal] = React.useState(null); const [payAmount, setPayAmount] = React.useState(''); const [payNote, setPayNote] = React.useState(''); const [paying, setPaying] = React.useState(false); const getToken = () => { const storedBranchToken = typeof window !== 'undefined' ? (localStorage.getItem('branch_token') || '') : ''; return token || storedBranchToken || ''; }; const loadCredits = async (status) => { try { const effectiveToken = getToken(); let url = salesUrl + '/api/supplier-credits'; if (status && status !== 'all') url += '?status=' + status; const res = await fetch(url, { headers: { Authorization: 'Bearer ' + effectiveToken } }); const data = await res.json(); if (!res.ok) throw new Error(data.message || 'Failed to load credits'); setCredits(data.credits || []); } catch (e) { setError(e.message); } }; const loadSummary = async () => { try { const effectiveToken = getToken(); const res = await fetch(salesUrl + '/api/supplier-credits/summary', { headers: { Authorization: 'Bearer ' + effectiveToken } }); const data = await res.json(); if (!res.ok) throw new Error(data.message || 'Failed to load summary'); setSummary(data.summary || []); } catch (e) { setError(e.message); } }; const loadAll = async () => { setLoading(true); setError(''); await Promise.all([loadSummary(), loadCredits(activeTab === 'pending' ? 'pending' : undefined)]); setLoading(false); }; React.useEffect(() => { loadAll(); }, [activeTab]); const formatCurrency = (n) => new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(n || 0); const totals = summary.reduce((acc, s) => ({ totalCredit: acc.totalCredit + (s.totalCredit || 0), totalPaid: acc.totalPaid + (s.totalPaid || 0), outstanding: acc.outstanding + (s.outstanding || 0), count: acc.count + (s.count || 0) }), { totalCredit: 0, totalPaid: 0, outstanding: 0, count: 0 }); const handlePay = async () => { if (!payModal || !payAmount || Number(payAmount) <= 0) return; setPaying(true); setError(''); try { const effectiveToken = getToken(); const res = await fetch(salesUrl + '/api/supplier-credits/' + payModal._id + '/pay', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + effectiveToken }, body: JSON.stringify({ amount: Number(payAmount), note: payNote }) }); const data = await res.json(); if (!res.ok) throw new Error(data.message || 'Payment failed'); setPayModal(null); setPayAmount(''); setPayNote(''); await loadAll(); } catch (e) { setError(e.message); } finally { setPaying(false); } }; return (
{/* Summary Cards */}

💳 Supplier Credits

Track credit purchases & payments

Total Credit
{formatCurrency(totals.totalCredit)}
Outstanding
0 ? '#dc2626' : '#059669' }}>{formatCurrency(totals.outstanding)}
Total Paid
{formatCurrency(totals.totalPaid)}
{/* Tabs */}
{[['summary', '📊 Summary'], ['all', '📋 All'], ['pending', '⏳ Pending']].map(([id, label]) => ( ))}
{error &&
⚠️ {error}
} {loading ? (
Loading…
) : activeTab === 'summary' ? ( /* Summary - Per Supplier */

Per Supplier

{summary.length === 0 ? (
💳
No Credit Entries
Credit purchases will appear here
) : (
{summary.map((s, i) => (
🏢 {s.supplierName || s.supplier_id?.supplierName || s.supplier_id?.agencyName || 'Unknown'} {s.count} entries
Credit
{formatCurrency(s.totalCredit)}
Paid
{formatCurrency(s.totalPaid)}
Due
0 ? '#dc2626' : '#059669' }}>{formatCurrency(s.outstanding)}
))}
)}
) : ( /* All / Pending */

{activeTab === 'pending' ? '⏳ Pending' : '📋 All Credits'}

{credits.length} entries

{credits.length === 0 ? (
No {activeTab === 'pending' ? 'Pending ' : ''}Credits
) : (
{credits.map((credit) => { const outstanding = (credit.totalAmount || 0) - (credit.paidAmount || 0); return (
🏢 {credit.supplier_id?.supplierName || credit.supplier_id?.agencyName || 'Unknown'}
{credit.status === 'settled' ? '✅ Settled' : credit.status === 'partial' ? '🔶 Partial' : '🔴 Pending'}
{new Date(credit.createdAt).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric' })}
{/* Products Purchased */} {credit.inStock_id?.items && credit.inStock_id.items.length > 0 && (
📦 Products
{credit.inStock_id.items.map((item, ii) => (
{item.productName}{item.brand ? ` (${item.brand})` : ''} × {item.quantity || 1}
))}
)}
Credit
{formatCurrency(credit.totalAmount)}
Paid
{formatCurrency(credit.paidAmount)}
Due
0 ? '#dc2626' : '#059669' }}>{formatCurrency(outstanding)}
{credit.payments && credit.payments.length > 0 && (
Payments
{credit.payments.map((p, pi) => (
{new Date(p.createdAt || p.paidAt).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' })} {p.note ? `- ${p.note}` : ''} {formatCurrency(p.amount)}
))}
)} {credit.status !== 'settled' && ( )}
); })}
)}
)} {/* Payment Modal */} {payModal && (

Record Payment

{payModal.supplier_id?.supplierName || payModal.supplier_id?.agencyName || 'Supplier'} — Due: {formatCurrency((payModal.totalAmount || 0) - (payModal.paidAmount || 0))}

setPayAmount(e.target.value)} placeholder="Enter payment amount" autoFocus />
setPayNote(e.target.value)} placeholder="e.g. Paid via UPI" />
)}
); } window.MobileSupplierCredits = MobileSupplierCredits;