'use client'; import React, { useState, useEffect } from 'react'; import { systemConfigService } from '@/services/api/systemConfigService'; import { userService, UserResponse } from '@/services/api/userService'; import { rolePermissionService, RoleResponse } from '@/services/api/rolePermissionService'; import { inventoryPosService, PosSession } from '@/services/api/inventoryPosService'; import { BarChart2, IndianRupee, Banknote, CreditCard, Loader2, RefreshCw } from 'lucide-react'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { TablePagination, useClientPagination } from '@/components/ui/TablePagination'; interface Location { location_id: string; name: string; city?: string; } const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; function inr(value: number) { return `₹${Number(value || 0).toFixed(2)}`; } 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 UserPosAnalyticsPage() { const [locations, setLocations] = useState([]); const [selectedLocation, setSelectedLocation] = useState(''); const [posUsers, setPosUsers] = useState([]); const [selectedUser, setSelectedUser] = useState(''); const [sessions, setSessions] = useState([]); const [loading, setLoading] = useState(false); const [reloadKey, setReloadKey] = useState(0); useEffect(() => { const fetchInitialData = async () => { let locs: Location[] = []; let users: UserResponse[] = []; let roles: RoleResponse[] = []; try { locs = await systemConfigService.getLocations() || []; setLocations(locs); } catch (e) { console.error('Error fetching locations:', e); } try { users = await userService.getAll() || []; } catch (e) { console.error('Error fetching users:', e); } try { roles = await rolePermissionService.getRoles() || []; } catch (e) { console.error('Error fetching roles:', e); } try { const roleHasPos = new Map(); for (const role of roles) { try { const perms = await rolePermissionService.getRolePermissions(role.role_id) || []; const hasPos = perms.some((p: any) => p && (typeof p === 'string' ? p.startsWith('pos.') : p.permission_code?.startsWith('pos.'))); roleHasPos.set(role.role_id, hasPos); } catch (e) { console.error('Error fetching permissions for role', role.role_id, e); } } const filteredUsers = users.filter(u => roleHasPos.get(u.role_id) === true); setPosUsers(filteredUsers); } catch (error) { console.error('Error processing roles/users:', error); } }; fetchInitialData(); }, [reloadKey]); useEffect(() => { const fetchSessions = async () => { if (!selectedLocation || !selectedUser) { setSessions([]); return; } setLoading(true); try { const data = await inventoryPosService.getPosSessions(undefined, selectedLocation, selectedUser); setSessions(Array.isArray(data) ? data : []); } catch (error) { console.error('Error fetching sessions:', error); } finally { setLoading(false); } }; fetchSessions(); }, [selectedLocation, selectedUser, reloadKey]); const totalSessions = sessions.length; const totalRevenue = sessions.reduce((sum, s) => sum + (s.ecom_sales_amount || 0) + (s.service_sales_amount || 0), 0); const totalCash = sessions.reduce((sum, s) => sum + (s.cash_sales || 0), 0); const totalUPI = sessions.reduce((sum, s) => sum + (s.upi_sales || 0), 0); const totalVariance = sessions.reduce((sum, s) => sum + (s.cash_variance || 0), 0); const availableUsersForLocation = posUsers.filter(u => !selectedLocation || !u.location_ids || u.location_ids.length === 0 || u.location_ids.includes(selectedLocation) ); const pager = useClientPagination(sessions); const filtersReady = Boolean(selectedLocation && selectedUser); const cards = [ { label: 'Total sessions', value: String(totalSessions), detail: 'Loaded sessions', icon: BarChart2 }, { label: 'Total revenue', value: inr(totalRevenue), detail: 'E-commerce and repair', icon: IndianRupee }, { label: 'Cash collected', value: inr(totalCash), detail: 'Cash sales', icon: Banknote }, { label: 'UPI collected', value: inr(totalUPI), detail: 'UPI sales', icon: CreditCard }, ]; return (

POS analytics

{filtersReady && ( {sessions.length} )}
{loading ? (
) : filtersReady ? ( <>
{cards.map((card) => (

{card.label}

{card.value}

{card.detail}

))}

Sessions

Net variance: {totalVariance >= 0 ? '+' : ''}{inr(totalVariance)}
{pager.items.length === 0 ? ( ) : pager.items.map((session, index) => { const variance = session.cash_variance || 0; const revenue = (session.ecom_sales_amount || 0) + (session.service_sales_amount || 0); const sessionId = session.pos_session_id || session.session_id || `session-${index}`; return ( ); })}
Session ID Status Revenue Cash Sales Variance
No sessions yet
{session.pos_session_id || session.session_id || '—'} {session.status} {inr(revenue)} {inr(session.cash_sales || 0)} 0 ? 'text-success' : 'text-destructive'}`}> {variance > 0 ? '+' : ''}{inr(variance)}
) : (
Select a location and a user
)}
); }