522 lines
23 KiB
TypeScript
522 lines
23 KiB
TypeScript
'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<PosSession[]>([]);
|
||
const [locations, setLocations] = useState<CrmLocation[]>([]);
|
||
const [terminals, setTerminals] = useState<PosTerminal[]>([]);
|
||
const [loading, setLoading] = useState(true);
|
||
|
||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||
const [selectedLocationId, setSelectedLocationId] = useState<string>('');
|
||
const [selectedTerminalId, setSelectedTerminalId] = useState<string>('');
|
||
const [openingCash, setOpeningCash] = useState<number>(0);
|
||
const [notes, setNotes] = useState<string>('');
|
||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||
|
||
const [closeModalSession, setCloseModalSession] = useState<PosSession | null>(null);
|
||
const [closingCash, setClosingCash] = useState<number>(0);
|
||
const [closeNotes, setCloseNotes] = useState<string>('');
|
||
const [isClosing, setIsClosing] = useState(false);
|
||
|
||
const [extendModalSession, setExtendModalSession] = useState<PosSession | null>(null);
|
||
const [extendMinutes, setExtendMinutes] = useState<number>(60);
|
||
const [extendReason, setExtendReason] = useState<string>('');
|
||
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 (
|
||
<div className="flex flex-col gap-5 min-w-0">
|
||
<div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
|
||
<div className="flex items-center gap-2 min-w-0">
|
||
<h1 className="text-lg font-semibold text-foreground">POS sessions</h1>
|
||
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
|
||
{sessions.length}
|
||
</span>
|
||
</div>
|
||
<div className="flex items-center gap-2">
|
||
<button type="button" onClick={loadData} className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer flex items-center justify-center" title="Reload">
|
||
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
|
||
</button>
|
||
<button type="button" onClick={() => setIsModalOpen(true)} className={primaryButton}>
|
||
<Plus className="w-3.5 h-3.5" />
|
||
Open session
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div className={shell}>
|
||
{loading ? (
|
||
<div className="py-16 flex justify-center"><Loader2 className="w-6 h-6 text-primary animate-spin" /></div>
|
||
) : pager.items.length === 0 ? (
|
||
<div className="py-16 text-center text-[13px] text-muted-foreground">No sessions yet</div>
|
||
) : (
|
||
<div className="divide-y divide-border">
|
||
{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 (
|
||
<article key={sessId} className="p-4 space-y-4">
|
||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||
<div className="min-w-0">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<p className="text-[13px] font-semibold text-foreground">{locationName}</p>
|
||
<span className="text-[12px] text-muted-foreground">{terminalLabel}</span>
|
||
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${sessionStatusClass(sess.status)}`}>
|
||
{sess.status}
|
||
</span>
|
||
{expired && (
|
||
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-warning/15 text-warning">
|
||
Expired
|
||
</span>
|
||
)}
|
||
</div>
|
||
<p className="mt-1 text-[12px] text-muted-foreground">
|
||
Started {formatWhen(sess.opened_at)}
|
||
{sess.status === 'OPEN' && sess.expires_at ? ` · Expires ${formatWhen(sess.expires_at)}` : ''}
|
||
{sess.closed_at ? ` · Closed ${formatWhen(sess.closed_at)}` : ''}
|
||
</p>
|
||
</div>
|
||
{sess.status === 'OPEN' && (
|
||
<div className="flex items-center gap-2">
|
||
<button type="button" onClick={() => setExtendModalSession(sess)} className={secondaryButton}>
|
||
Extend
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
setCloseModalSession(sess);
|
||
setClosingCash(expCash);
|
||
}}
|
||
className={primaryButton}
|
||
>
|
||
Close
|
||
</button>
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-2">
|
||
{figures.map((figure) => (
|
||
<div key={figure.label} className="border border-border crm-radius-control bg-muted/40 px-3 py-2">
|
||
<p className="text-[11px] text-muted-foreground">{figure.label}{figure.detail ? ` (${figure.detail})` : ''}</p>
|
||
<p className="text-[13px] font-semibold text-foreground mt-0.5">{figure.value}</p>
|
||
</div>
|
||
))}
|
||
</div>
|
||
|
||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3 text-[13px]">
|
||
<div>
|
||
<p className="text-[11px] text-muted-foreground">Opening cash</p>
|
||
<p className="font-medium text-foreground">{money(openCash)}</p>
|
||
</div>
|
||
<div>
|
||
<p className="text-[11px] text-muted-foreground">Expected cash</p>
|
||
<p className="font-medium text-foreground">{money(expCash)}</p>
|
||
</div>
|
||
<div>
|
||
<p className="text-[11px] text-muted-foreground">Closing cash</p>
|
||
<p className="font-medium text-foreground">{closeCash !== undefined ? money(closeCash) : '—'}</p>
|
||
</div>
|
||
<div>
|
||
<p className="text-[11px] text-muted-foreground">Variance</p>
|
||
<p className={`font-semibold ${closeCash === undefined ? 'text-muted-foreground' : variance === 0 ? 'text-success' : variance < 0 ? 'text-destructive' : 'text-foreground'}`}>
|
||
{closeCash === undefined ? '—' : `${variance >= 0 ? '+' : '−'}₹${Math.abs(variance).toLocaleString('en-IN')}`}
|
||
</p>
|
||
</div>
|
||
</div>
|
||
|
||
<div className="flex items-center justify-between border-t border-border pt-3 text-[13px]">
|
||
<span className="text-muted-foreground">Total</span>
|
||
<span className="font-semibold text-foreground">{money(totalTurnover)}</span>
|
||
</div>
|
||
</article>
|
||
);
|
||
})}
|
||
</div>
|
||
)}
|
||
{!loading && pager.items.length > 0 && <TablePagination {...pager} />}
|
||
</div>
|
||
|
||
{isModalOpen && (
|
||
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
|
||
<div className="bg-card border border-border crm-radius-section shadow-xl max-w-md w-full p-5 space-y-4">
|
||
<div className="flex items-center justify-between">
|
||
<h3 className="text-base font-semibold text-foreground">Open session</h3>
|
||
<button type="button" onClick={() => setIsModalOpen(false)} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
|
||
<X className="w-4 h-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<form onSubmit={handleOpenSession} className="space-y-3">
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Location</span>
|
||
<CustomSelect
|
||
value={selectedLocationId}
|
||
onChange={setSelectedLocationId}
|
||
options={locations.map((loc) => ({
|
||
value: loc.location_id,
|
||
label: loc.is_primary ? `${loc.name} (${loc.code}) · Primary` : `${loc.name} (${loc.code})`,
|
||
}))}
|
||
placeholder="Location"
|
||
/>
|
||
</label>
|
||
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Terminal</span>
|
||
<CustomSelect
|
||
value={selectedTerminalId}
|
||
onChange={setSelectedTerminalId}
|
||
options={[
|
||
{ value: '', label: 'No terminal' },
|
||
...modalTerminals.map((term) => ({
|
||
value: term.terminal_id,
|
||
label: term.name ? `${term.code} · ${term.name}` : term.code,
|
||
})),
|
||
]}
|
||
placeholder="Terminal"
|
||
/>
|
||
</label>
|
||
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Opening cash</span>
|
||
<input
|
||
type="number"
|
||
min="0"
|
||
step="0.01"
|
||
value={openingCash}
|
||
onChange={(e) => setOpeningCash(Number(e.target.value))}
|
||
className={fieldClass}
|
||
/>
|
||
</label>
|
||
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Notes</span>
|
||
<textarea
|
||
value={notes}
|
||
onChange={(e) => setNotes(e.target.value)}
|
||
rows={3}
|
||
className={textareaClass}
|
||
/>
|
||
</label>
|
||
|
||
<div className="pt-1 flex justify-end gap-2">
|
||
<button type="button" onClick={() => setIsModalOpen(false)} className={secondaryButton}>
|
||
Cancel
|
||
</button>
|
||
<button type="submit" disabled={isSubmitting} className={primaryButton}>
|
||
{isSubmitting ? 'Opening...' : 'Open session'}
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{closeModalSession && (
|
||
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
|
||
<div className="bg-card border border-border crm-radius-section shadow-xl max-w-md w-full p-5 space-y-4">
|
||
<div className="flex items-center justify-between">
|
||
<h3 className="text-base font-semibold text-foreground">Close session</h3>
|
||
<button type="button" onClick={() => setCloseModalSession(null)} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
|
||
<X className="w-4 h-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<form onSubmit={handleCloseSession} className="space-y-3">
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Counted cash</span>
|
||
<input
|
||
type="number"
|
||
required
|
||
min="0"
|
||
step="0.01"
|
||
value={closingCash}
|
||
onChange={(e) => setClosingCash(Number(e.target.value))}
|
||
className={fieldClass}
|
||
/>
|
||
</label>
|
||
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Notes</span>
|
||
<textarea
|
||
value={closeNotes}
|
||
onChange={(e) => setCloseNotes(e.target.value)}
|
||
rows={3}
|
||
className={textareaClass}
|
||
/>
|
||
</label>
|
||
|
||
<div className="pt-1 flex justify-end gap-2">
|
||
<button type="button" onClick={() => setCloseModalSession(null)} className={secondaryButton}>
|
||
Cancel
|
||
</button>
|
||
<button type="submit" disabled={isClosing} className={primaryButton}>
|
||
{isClosing ? 'Closing...' : 'Close session'}
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
)}
|
||
|
||
{extendModalSession && (
|
||
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
|
||
<div className="bg-card border border-border crm-radius-section shadow-xl max-w-md w-full p-5 space-y-4">
|
||
<div className="flex items-center justify-between">
|
||
<h3 className="text-base font-semibold text-foreground">Extend session</h3>
|
||
<button type="button" onClick={() => setExtendModalSession(null)} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
|
||
<X className="w-4 h-4" />
|
||
</button>
|
||
</div>
|
||
|
||
<form onSubmit={handleExtendSession} className="space-y-3">
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Minutes</span>
|
||
<input
|
||
type="number"
|
||
required
|
||
min="1"
|
||
max="480"
|
||
value={extendMinutes}
|
||
onChange={(e) => setExtendMinutes(Number(e.target.value))}
|
||
className={fieldClass}
|
||
/>
|
||
</label>
|
||
|
||
<label className="block">
|
||
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Reason</span>
|
||
<textarea
|
||
required
|
||
value={extendReason}
|
||
onChange={(e) => setExtendReason(e.target.value)}
|
||
rows={3}
|
||
className={textareaClass}
|
||
/>
|
||
</label>
|
||
|
||
<div className="pt-1 flex justify-end gap-2">
|
||
<button type="button" onClick={() => setExtendModalSession(null)} className={secondaryButton}>
|
||
Cancel
|
||
</button>
|
||
<button type="submit" disabled={isExtending} className={primaryButton}>
|
||
{isExtending ? 'Extending...' : 'Extend session'}
|
||
</button>
|
||
</div>
|
||
</form>
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|