'use client'; import { useEffect, useState } from 'react'; import { inventoryPosService, PosSession, PosTerminal } from '@/services/api/inventoryPosService'; import { systemConfigService, CrmLocation } from '@/services/api/systemConfigService'; import { Plus, X, RefreshCw, Loader2 } from 'lucide-react'; import { toast } from 'sonner'; import { format } from 'date-fns'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { TablePagination, useClientPagination } from '@/components/ui/TablePagination'; const fieldClass = 'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const primaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer'; const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const textareaClass = 'w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; function formatWhen(iso?: string) { if (!iso) return '—'; const date = new Date(iso); if (Number.isNaN(date.getTime())) return '—'; return format(date, 'dd-MMM-yyyy HH:mm'); } function money(value: number) { return `₹${Number(value || 0).toLocaleString('en-IN')}`; } function sessionStatusClass(status: string) { if (status === 'OPEN') return 'bg-success/15 text-success'; if (status === 'CLOSED') return 'bg-muted text-foreground'; return 'bg-warning/15 text-warning'; } export default function PosSessionsPage() { const [sessions, setSessions] = useState([]); const [locations, setLocations] = useState([]); const [terminals, setTerminals] = useState([]); const [loading, setLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [selectedLocationId, setSelectedLocationId] = useState(''); const [selectedTerminalId, setSelectedTerminalId] = useState(''); const [openingCash, setOpeningCash] = useState(0); const [notes, setNotes] = useState(''); const [isSubmitting, setIsSubmitting] = useState(false); const [closeModalSession, setCloseModalSession] = useState(null); const [closingCash, setClosingCash] = useState(0); const [closeNotes, setCloseNotes] = useState(''); const [isClosing, setIsClosing] = useState(false); const [extendModalSession, setExtendModalSession] = useState(null); const [extendMinutes, setExtendMinutes] = useState(60); const [extendReason, setExtendReason] = useState(''); const [isExtending, setIsExtending] = useState(false); useEffect(() => { loadData(); }, []); useEffect(() => { const checkExpired = () => { const expired = sessions.find(s => s.status === 'OPEN' && s.expires_at && new Date(s.expires_at) <= new Date()); if (expired && !extendModalSession && !closeModalSession) { toast.warning('POS Session has reached its 9-hour limit. Please extend or close it.', { duration: 10000, id: 'expired-session' }); } else if (!expired) { toast.dismiss('expired-session'); } }; checkExpired(); const interval = setInterval(checkExpired, 60000); return () => clearInterval(interval); }, [sessions, extendModalSession, closeModalSession]); useEffect(() => { if (selectedLocationId) { fetchTerminals(selectedLocationId); } }, [selectedLocationId]); const mergeTerminals = (incoming: PosTerminal[]) => { setTerminals((prev) => { const ids = new Set(incoming.map((terminal) => terminal.terminal_id)); return [...incoming, ...prev.filter((terminal) => !ids.has(terminal.terminal_id))]; }); }; const loadData = async () => { try { setLoading(true); const [sessData, locData] = await Promise.all([ inventoryPosService.getPosSessions(), systemConfigService.getLocations(), ]); const nextSessions = Array.isArray(sessData) ? sessData : []; const nextLocations = Array.isArray(locData) ? locData : []; setSessions(nextSessions); setLocations(nextLocations); if (nextLocations.length > 0) { const primary = nextLocations.find(l => l.is_primary) || nextLocations[0]; setSelectedLocationId(primary.location_id); } const locationIds = [...new Set(nextSessions.map((session) => session.location_id).filter(Boolean))] as string[]; if (locationIds.length > 0) { const lists = await Promise.all(locationIds.map((id) => inventoryPosService.getTerminals(id).catch(() => []))); mergeTerminals(lists.flatMap((list) => (Array.isArray(list) ? list : []))); } } catch (err) { console.warn('Failed to load POS session data:', err); setSessions([]); } finally { setLoading(false); } }; const fetchTerminals = async (locationId: string) => { try { const termData = await inventoryPosService.getTerminals(locationId); const next = Array.isArray(termData) ? termData : []; mergeTerminals(next); setSelectedTerminalId(next[0]?.terminal_id || ''); } catch { setSelectedTerminalId(''); } }; const handleOpenSession = async (e: React.FormEvent) => { e.preventDefault(); if (!selectedLocationId) { toast.error('Select a location'); return; } try { setIsSubmitting(true); await inventoryPosService.openPosSession({ location_id: selectedLocationId || undefined, terminal_id: selectedTerminalId || undefined, opening_cash: Number(openingCash) || 0, notes: notes || undefined, }); toast.success('POS Counter Session opened successfully!'); setIsModalOpen(false); setOpeningCash(0); setNotes(''); loadData(); } catch (err: any) { toast.error(err?.message || 'Failed to open POS session'); } finally { setIsSubmitting(false); } }; const handleCloseSession = async (e: React.FormEvent) => { e.preventDefault(); if (!closeModalSession) return; const sessId = closeModalSession.pos_session_id || closeModalSession.session_id; if (!sessId) return; try { setIsClosing(true); await inventoryPosService.closePosSession(sessId, Number(closingCash), closeNotes); toast.success('POS Session closed successfully!'); setCloseModalSession(null); setClosingCash(0); setCloseNotes(''); loadData(); } catch (err: any) { toast.error(err?.message || 'Failed to close POS session'); } finally { setIsClosing(false); } }; const handleExtendSession = async (e: React.FormEvent) => { e.preventDefault(); if (!extendModalSession) return; const sessId = extendModalSession.pos_session_id || extendModalSession.session_id; if (!sessId) return; try { setIsExtending(true); await inventoryPosService.extendPosSession(sessId, { extension_minutes: Number(extendMinutes), reason: extendReason, }); toast.success('POS Session extended successfully!'); setExtendModalSession(null); setExtendReason(''); setExtendMinutes(60); loadData(); } catch (err: any) { toast.error(err?.message || 'Failed to extend POS session. Max extensions reached or server error.'); } finally { setIsExtending(false); } }; const pager = useClientPagination(sessions); const modalTerminals = terminals.filter((terminal) => terminal.location_id === selectedLocationId); return (

POS sessions

{sessions.length}
{loading ? (
) : pager.items.length === 0 ? (
No sessions yet
) : (
{pager.items.map((sess, index) => { const sessId = sess.pos_session_id || sess.session_id || `session-${index}`; const location = locations.find(l => l.location_id === sess.location_id); const terminal = terminals.find(t => t.terminal_id === sess.terminal_id); const locationName = location?.name || '—'; const terminalLabel = terminal?.code || sess.terminal_id || '—'; const totalEcom = Number(sess.ecom_sales_amount || 0); const totalService = Number(sess.service_sales_amount || 0); const courierFee = Number(sess.courier_charges || 0); const cashSales = Number(sess.cash_sales || 0); const upiSales = Number(sess.upi_sales || 0); const cardSales = Number(sess.card_sales || 0); const otherSales = Number(sess.other_sales || 0); const totalTurnover = cashSales + upiSales + cardSales + otherSales; const openCash = Number(sess.opening_cash || sess.opening_balance || 0); const closeCash = sess.closing_cash != null ? Number(sess.closing_cash) : undefined; const expCash = sess.expected_cash != null ? Number(sess.expected_cash) : (openCash + cashSales); const variance = sess.cash_variance != null ? Number(sess.cash_variance) : (closeCash !== undefined ? closeCash - expCash : 0); const expired = sess.status === 'OPEN' && !!sess.expires_at && new Date(sess.expires_at) <= new Date(); const figures = [ { label: 'E-commerce', detail: String(sess.ecom_sales_count || 0), value: money(totalEcom) }, { label: 'Repair', detail: String(sess.service_sales_count || 0), value: money(totalService) }, { label: 'Courier', detail: '', value: money(courierFee) }, { label: 'Cash', detail: '', value: money(cashSales) }, { label: 'UPI', detail: '', value: money(upiSales) }, { label: 'Card', detail: '', value: money(cardSales) }, { label: 'Other', detail: '', value: money(otherSales) }, ]; return (

{locationName}

{terminalLabel} {sess.status} {expired && ( Expired )}

Started {formatWhen(sess.opened_at)} {sess.status === 'OPEN' && sess.expires_at ? ` · Expires ${formatWhen(sess.expires_at)}` : ''} {sess.closed_at ? ` · Closed ${formatWhen(sess.closed_at)}` : ''}

{sess.status === 'OPEN' && (
)}
{figures.map((figure) => (

{figure.label}{figure.detail ? ` (${figure.detail})` : ''}

{figure.value}

))}

Opening cash

{money(openCash)}

Expected cash

{money(expCash)}

Closing cash

{closeCash !== undefined ? money(closeCash) : '—'}

Variance

{closeCash === undefined ? '—' : `${variance >= 0 ? '+' : '−'}₹${Math.abs(variance).toLocaleString('en-IN')}`}

Total {money(totalTurnover)}
); })}
)} {!loading && pager.items.length > 0 && }
{isModalOpen && (

Open session