264 lines
12 KiB
TypeScript
264 lines
12 KiB
TypeScript
'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<Location[]>([]);
|
|
const [selectedLocation, setSelectedLocation] = useState<string>('');
|
|
|
|
const [posUsers, setPosUsers] = useState<UserResponse[]>([]);
|
|
const [selectedUser, setSelectedUser] = useState<string>('');
|
|
|
|
const [sessions, setSessions] = useState<PosSession[]>([]);
|
|
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<string, boolean>();
|
|
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 (
|
|
<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 analytics</h1>
|
|
{filtersReady && (
|
|
<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>
|
|
<button
|
|
type="button"
|
|
onClick={() => setReloadKey((current) => current + 1)}
|
|
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>
|
|
</div>
|
|
|
|
<div className={`${shell} p-4`}>
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
|
<label className="block min-w-0">
|
|
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Location</span>
|
|
<CustomSelect
|
|
value={selectedLocation}
|
|
onChange={(value) => {
|
|
setSelectedLocation(value);
|
|
setSelectedUser('');
|
|
}}
|
|
options={locations.map((loc) => ({
|
|
value: loc.location_id,
|
|
label: loc.city ? `${loc.name} · ${loc.city}` : loc.name,
|
|
}))}
|
|
placeholder="Location"
|
|
/>
|
|
</label>
|
|
<label className="block min-w-0">
|
|
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">User</span>
|
|
<CustomSelect
|
|
value={selectedUser}
|
|
onChange={setSelectedUser}
|
|
disabled={!selectedLocation}
|
|
options={availableUsersForLocation.map((user) => {
|
|
const name = [user.first_name, user.last_name].filter(Boolean).join(' ');
|
|
return {
|
|
value: user.user_id,
|
|
label: name && user.email ? `${name} (${user.email})` : name || user.email,
|
|
};
|
|
})}
|
|
placeholder="User"
|
|
/>
|
|
{selectedLocation && availableUsersForLocation.length === 0 && (
|
|
<p className="text-[12px] text-muted-foreground mt-2">No users with POS permissions for this location.</p>
|
|
)}
|
|
</label>
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<div className="py-16 flex justify-center"><Loader2 className="w-6 h-6 text-primary animate-spin" /></div>
|
|
) : filtersReady ? (
|
|
<>
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
|
|
{cards.map((card) => (
|
|
<div key={card.label} className={`${shell} p-4`}>
|
|
<div className="flex items-start justify-between gap-2">
|
|
<div className="min-w-0">
|
|
<p className="text-[13px] text-muted-foreground">{card.label}</p>
|
|
<p className="text-[22px] font-bold text-foreground mt-2 tracking-tight truncate">{card.value}</p>
|
|
<p className="text-[12px] text-muted-foreground mt-2">{card.detail}</p>
|
|
</div>
|
|
<span className="w-9 h-9 rounded-full bg-primary/10 text-primary flex items-center justify-center shrink-0">
|
|
<card.icon className="w-4 h-4" />
|
|
</span>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
<div className={shell}>
|
|
<div className="px-4 py-3 border-b border-border flex flex-wrap items-center justify-between gap-2">
|
|
<h2 className="text-[13px] font-semibold text-foreground">Sessions</h2>
|
|
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${totalVariance === 0 ? 'bg-success/15 text-success' : 'bg-destructive/10 text-destructive'}`}>
|
|
Net variance: {totalVariance >= 0 ? '+' : ''}{inr(totalVariance)}
|
|
</span>
|
|
</div>
|
|
<div className="overflow-x-auto">
|
|
<table className="crm-data-table min-w-[720px]">
|
|
<thead>
|
|
<tr className="border-b border-border">
|
|
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Session ID</th>
|
|
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Status</th>
|
|
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Revenue</th>
|
|
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Cash Sales</th>
|
|
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Variance</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{pager.items.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={5} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No sessions yet</td>
|
|
</tr>
|
|
) : 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 (
|
|
<tr key={sessionId}>
|
|
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">{session.pos_session_id || session.session_id || '—'}</td>
|
|
<td className="px-4 py-2.5">
|
|
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${sessionStatusClass(session.status)}`}>
|
|
{session.status}
|
|
</span>
|
|
</td>
|
|
<td className="px-4 py-2.5 text-right text-[13px] text-foreground">{inr(revenue)}</td>
|
|
<td className="px-4 py-2.5 text-right text-[13px] text-foreground">{inr(session.cash_sales || 0)}</td>
|
|
<td className={`px-4 py-2.5 text-right text-[13px] font-semibold ${variance === 0 ? 'text-muted-foreground' : variance > 0 ? 'text-success' : 'text-destructive'}`}>
|
|
{variance > 0 ? '+' : ''}{inr(variance)}
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
</>
|
|
) : (
|
|
<div className={`${shell} py-16 text-center text-[13px] text-muted-foreground`}>
|
|
Select a location and a user
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|