ifixkart-admin/New admin panel/ikixkart-dashboard/app/(admin)/pos-sessions/page.tsx
Adithiyan bbd3a3e959 feat: initial commit — full platform snapshot
- Backend: FastAPI app with all models, services, schemas, routes
- Admin Panel: Next.js dashboard with all modules
  (CRM, POS, repairs, warranties, billing, notifications, etc.)
- Ecommerce: storefront (submodule) + product catalog
- AI Agents: .agents/ skill library for Antigravity IDE
- Docs: architecture, billing, notification gateway markdown
- Submodules: Backend/OpenWA, Ecommerce/File 2/storefront
2026-10-13 12:59:47 +05:30

548 lines
25 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 { CreditCard, DollarSign, Plus, X, Store, Calendar, ShieldAlert, CheckCircle2, Lock } from 'lucide-react';
import { toast } from 'sonner';
export default function PosSessionsPage() {
const [sessions, setSessions] = useState<PosSession[]>([]);
const [locations, setLocations] = useState<CrmLocation[]>([]);
const [terminals, setTerminals] = useState<PosTerminal[]>([]);
const [loading, setLoading] = useState(true);
// New Session Modal State
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);
// Close Session Modal State
const [closeModalSession, setCloseModalSession] = useState<PosSession | null>(null);
const [closingCash, setClosingCash] = useState<number>(0);
const [closeNotes, setCloseNotes] = useState<string>('');
const [isClosing, setIsClosing] = useState(false);
// Extend Session Modal State
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 loadData = async () => {
try {
setLoading(true);
const [sessData, locData] = await Promise.all([
inventoryPosService.getPosSessions(),
systemConfigService.getLocations(),
]);
setSessions(Array.isArray(sessData) ? sessData : []);
setLocations(Array.isArray(locData) ? locData : []);
if (locData && locData.length > 0) {
const primary = locData.find(l => l.is_primary) || locData[0];
setSelectedLocationId(primary.location_id);
}
} 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);
setTerminals(Array.isArray(termData) ? termData : []);
if (termData && termData.length > 0) {
setSelectedTerminalId(termData[0].terminal_id);
} else {
setSelectedTerminalId('');
}
} catch {
setTerminals([]);
}
};
const handleOpenSession = async (e: React.FormEvent) => {
e.preventDefault();
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);
}
};
return (
<div className="p-6 space-y-6">
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 className="text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
<CreditCard className="w-6 h-6 text-primary" />
POS Sessions & Cash Reconciliation Engine
</h1>
<p className="text-sm text-muted-foreground">
Track multi-store counter sessions, e-commerce vs service revenue, payment splits, and cash drawer auditing.
</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-lg text-sm font-semibold hover:bg-primary/90 transition-colors shadow-sm cursor-pointer"
>
<Plus className="w-4 h-4" />
Open New Counter Session
</button>
</div>
{loading ? (
<div className="py-20 text-center text-muted-foreground animate-pulse">Loading POS Sessions & Multi-Store Data...</div>
) : sessions.length === 0 ? (
<div className="py-16 text-center bg-card border border-border rounded-xl">
<CreditCard className="w-10 h-10 text-muted-foreground mx-auto mb-2 opacity-50" />
<h3 className="text-sm font-semibold text-foreground">No active or historical POS counter sessions found</h3>
<p className="text-xs text-muted-foreground mt-1">
Click "+ Open New Counter Session" to assign a store terminal and record sales. Opening cash float is optional (defaults to ₹0).
</p>
</div>
) : (
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{sessions.map((sess) => {
const sessId = sess.pos_session_id || sess.session_id || '';
const locationName = locations.find(l => l.location_id === sess.location_id)?.name || 'Main Counter';
const terminalCode = terminals.find(t => t.terminal_id === sess.terminal_id)?.code || sess.terminal_id || 'POS-01';
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);
return (
<div key={sessId} className="bg-card border border-border rounded-xl p-5 shadow-xs space-y-4">
<div className="flex items-center justify-between border-b border-border pb-3">
<div className="flex items-center gap-2">
<span className="font-mono text-xs font-bold bg-primary/10 text-primary px-2.5 py-1 rounded-md flex items-center gap-1">
<Store className="w-3.5 h-3.5" />
{locationName} ({terminalCode})
</span>
<span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase ${
sess.status === 'OPEN' ? 'bg-emerald-500/10 text-emerald-600' : 'bg-muted text-muted-foreground'
}`}>
{sess.status}
</span>
</div>
{sess.status === 'OPEN' && (
<div className="flex gap-2">
<button
onClick={() => {
setExtendModalSession(sess);
}}
className="text-xs font-semibold text-amber-600 hover:text-amber-700 bg-amber-50 px-2.5 py-1 rounded-md border border-amber-200 cursor-pointer flex items-center gap-1"
>
<ShieldAlert className="w-3.5 h-3.5" /> Extend
</button>
<button
onClick={() => {
setCloseModalSession(sess);
setClosingCash(expCash);
}}
className="text-xs font-semibold text-rose-600 hover:text-rose-700 bg-rose-50 px-2.5 py-1 rounded-md border border-rose-200 cursor-pointer flex items-center gap-1"
>
<Lock className="w-3.5 h-3.5" /> Close Session
</button>
</div>
)}
</div>
{/* Timestamps */}
<div className="flex flex-wrap items-center justify-between text-xs text-muted-foreground bg-muted/20 p-2.5 rounded-lg">
<div className="flex items-center gap-1">
<Calendar className="w-3.5 h-3.5" />
<span>Start: {sess.opened_at ? new Date(sess.opened_at).toLocaleString() : 'N/A'}</span>
</div>
{sess.expires_at && sess.status === 'OPEN' && (
<div className="flex items-center gap-1 text-amber-600 font-medium">
<span>Expires: {new Date(sess.expires_at).toLocaleString()}</span>
</div>
)}
{sess.closed_at && (
<div>
<span>End: {new Date(sess.closed_at).toLocaleString()}</span>
</div>
)}
</div>
{/* Domain Revenue Breakdown */}
<div>
<p className="text-[11px] font-semibold text-muted-foreground uppercase mb-2">Domain Sales Breakdown</p>
<div className="grid grid-cols-3 gap-2 text-center text-xs">
<div className="bg-background border border-border p-2.5 rounded-lg">
<p className="text-[10px] text-muted-foreground font-semibold">E-Commerce ({sess.ecom_sales_count || 0})</p>
<p className="font-bold text-foreground">₹{totalEcom.toLocaleString()}</p>
</div>
<div className="bg-background border border-border p-2.5 rounded-lg">
<p className="text-[10px] text-muted-foreground font-semibold">Repair Service ({sess.service_sales_count || 0})</p>
<p className="font-bold text-foreground">₹{totalService.toLocaleString()}</p>
</div>
<div className="bg-background border border-border p-2.5 rounded-lg">
<p className="text-[10px] text-muted-foreground font-semibold">Courier Charge</p>
<p className="font-bold text-amber-600">₹{courierFee.toLocaleString()}</p>
</div>
</div>
</div>
{/* Payment Method Breakdown */}
<div>
<p className="text-[11px] font-semibold text-muted-foreground uppercase mb-2">Payment Method Breakdown</p>
<div className="grid grid-cols-4 gap-2 text-center text-xs">
<div className="bg-emerald-500/5 border border-emerald-500/20 p-2.5 rounded-lg">
<p className="text-[10px] text-emerald-700 font-semibold">Cash</p>
<p className="font-bold text-emerald-600">₹{cashSales.toLocaleString()}</p>
</div>
<div className="bg-blue-500/5 border border-blue-500/20 p-2.5 rounded-lg">
<p className="text-[10px] text-blue-700 font-semibold">UPI</p>
<p className="font-bold text-blue-600">₹{upiSales.toLocaleString()}</p>
</div>
<div className="bg-purple-500/5 border border-purple-500/20 p-2.5 rounded-lg">
<p className="text-[10px] text-purple-700 font-semibold">Card</p>
<p className="font-bold text-purple-600">₹{cardSales.toLocaleString()}</p>
</div>
<div className="bg-slate-500/5 border border-slate-500/20 p-2.5 rounded-lg">
<p className="text-[10px] text-slate-700 font-semibold">Other</p>
<p className="font-bold text-slate-600">₹{otherSales.toLocaleString()}</p>
</div>
</div>
</div>
{/* Summary & Variance */}
<div className="border-t border-border pt-3 space-y-1 text-xs">
<div className="flex justify-between text-muted-foreground">
<span>Opening Cash Float: ₹{openCash.toLocaleString()}</span>
<span>Expected Drawer Cash: ₹{expCash.toLocaleString()}</span>
</div>
{closeCash !== undefined && (
<div className="flex justify-between font-medium">
<span>Recorded Closing Cash: ₹{closeCash.toLocaleString()}</span>
<span className={variance === 0 ? 'text-emerald-600' : variance > 0 ? 'text-blue-600' : 'text-rose-600 font-bold'}>
Cash Variance: {variance >= 0 ? `+₹${variance}` : `-₹${Math.abs(variance)}`}
</span>
</div>
)}
<div className="flex justify-between items-center pt-2 font-bold text-foreground text-sm border-t border-dashed border-border">
<span>Total Session Revenue:</span>
<span>₹{totalTurnover.toLocaleString()}</span>
</div>
</div>
</div>
);
})}
</div>
)}
{/* Modal: Open POS Session */}
{isModalOpen && (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-xl max-w-md w-full p-6 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-bold text-foreground flex items-center gap-2">
<CreditCard className="w-5 h-5 text-primary" />
Open Counter POS Session
</h3>
<button onClick={() => setIsModalOpen(false)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<form onSubmit={handleOpenSession} className="space-y-4 text-xs">
<div>
<label className="block font-medium mb-1">Store Location *</label>
<select
required
value={selectedLocationId}
onChange={(e) => setSelectedLocationId(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden"
>
{locations.map((loc) => (
<option key={loc.location_id} value={loc.location_id}>
{loc.name} ({loc.code}) {loc.is_primary ? '★ Primary' : ''}
</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">POS Terminal</label>
<select
value={selectedTerminalId}
onChange={(e) => setSelectedTerminalId(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden font-mono"
>
<option value="">-- Main Counter (Default) --</option>
{terminals.map((term) => (
<option key={term.terminal_id} value={term.terminal_id}>
{term.code} - {term.name}
</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">Opening Cash Float (₹) <span className="text-muted-foreground font-normal">(Optional, defaults to ₹0)</span></label>
<input
type="number"
min="0"
step="0.01"
value={openingCash}
onChange={(e) => setOpeningCash(Number(e.target.value))}
placeholder="0"
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden font-bold"
/>
</div>
<div>
<label className="block font-medium mb-1">Session Notes / Handover</label>
<textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="e.g. Shift 1 morning counter opening..."
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden h-20"
/>
</div>
<div className="pt-2 flex justify-end gap-2">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="submit"
disabled={isSubmitting}
className="px-4 py-2 rounded-lg bg-primary text-white font-bold hover:bg-primary/90 flex items-center gap-1.5 cursor-pointer"
>
{isSubmitting ? 'Opening Session...' : 'Open Session Now'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Modal: Close POS Session */}
{closeModalSession && (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-xl max-w-md w-full p-6 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-bold text-foreground flex items-center gap-2">
<Lock className="w-5 h-5 text-rose-600" />
Close POS Session & Audit Cash
</h3>
<button onClick={() => setCloseModalSession(null)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<form onSubmit={handleCloseSession} className="space-y-4 text-xs">
<div>
<label className="block font-medium mb-1">Counted Cash in Drawer (₹) *</label>
<input
type="number"
required
min="0"
step="0.01"
value={closingCash}
onChange={(e) => setClosingCash(Number(e.target.value))}
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden font-bold text-base"
/>
</div>
<div>
<label className="block font-medium mb-1">Closing Notes / Variance Reason</label>
<textarea
value={closeNotes}
onChange={(e) => setCloseNotes(e.target.value)}
placeholder="e.g. Cash drawer verified with shift supervisor..."
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden h-20"
/>
</div>
<div className="pt-2 flex justify-end gap-2">
<button
type="button"
onClick={() => setCloseModalSession(null)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="submit"
disabled={isClosing}
className="px-4 py-2 rounded-lg bg-rose-600 text-white font-bold hover:bg-rose-700 flex items-center gap-1.5 cursor-pointer"
>
{isClosing ? 'Closing Session...' : 'Confirm Session Close'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Modal: Extend POS Session */}
{extendModalSession && (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-xl max-w-md w-full p-6 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-bold text-foreground flex items-center gap-2">
<ShieldAlert className="w-5 h-5 text-amber-600" />
Extend POS Session
</h3>
<button onClick={() => setExtendModalSession(null)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<form onSubmit={handleExtendSession} className="space-y-4 text-xs">
<div>
<label className="block font-medium mb-1">Extension Minutes *</label>
<input
type="number"
required
min="1"
max="480"
value={extendMinutes}
onChange={(e) => setExtendMinutes(Number(e.target.value))}
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden font-bold text-base"
/>
</div>
<div>
<label className="block font-medium mb-1">Reason for Extension *</label>
<textarea
required
value={extendReason}
onChange={(e) => setExtendReason(e.target.value)}
placeholder="e.g. Extra busy shift, supervisor approved..."
className="w-full bg-muted border border-border rounded-lg p-2.5 text-foreground focus:outline-hidden h-20"
/>
</div>
<div className="pt-2 flex justify-end gap-2">
<button
type="button"
onClick={() => setExtendModalSession(null)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="submit"
disabled={isExtending}
className="px-4 py-2 rounded-lg bg-amber-600 text-white font-bold hover:bg-amber-700 flex items-center gap-1.5 cursor-pointer"
>
{isExtending ? 'Extending...' : 'Extend Session'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
);
}