fix(admin): resolve repair tickets crash, fix Unknown Unknown user labels, and add dashboard timeout guard

This commit is contained in:
iFixKart Dev 2026-11-16 17:34:38 +05:30
parent c9b414e7d7
commit 6527831bdd
6 changed files with 115 additions and 42 deletions

View file

@ -79,12 +79,17 @@ export default function RepairTicketsPage() {
} }
}; };
const filteredTickets = tickets.filter( const filteredTickets = (tickets || []).filter((t) => {
(t) => const q = (searchImei || '').toLowerCase().trim();
t.imei_serial.includes(searchImei) || if (!q) return true;
t.ticket_number.toLowerCase().includes(searchImei.toLowerCase()) || const imei = (t.imei_serial || '').toLowerCase();
t.customer_name.toLowerCase().includes(searchImei.toLowerCase()) const num = (t.ticket_number || '').toLowerCase();
); const cust = (t.customer_name || '').toLowerCase();
const brand = (t.brand_name || '').toLowerCase();
const model = (t.model_name || '').toLowerCase();
const desc = (t.problem_description || t.issue_description || '').toLowerCase();
return imei.includes(q) || num.includes(q) || cust.includes(q) || brand.includes(q) || model.includes(q) || desc.includes(q);
});
return ( return (
<div className="flex flex-col gap-5 min-w-0"> <div className="flex flex-col gap-5 min-w-0">
@ -125,7 +130,13 @@ export default function RepairTicketsPage() {
) : ( ) : (
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-4"> <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-5 gap-4">
{STAGES.map((stage) => { {STAGES.map((stage) => {
const stageTickets = filteredTickets.filter((t) => t.status === stage); const stageTickets = filteredTickets.filter((t) => {
const currentStage = (t.stage || t.status || '').toUpperCase();
return currentStage === stage.toUpperCase() ||
(stage === 'INTAKE' && (currentStage === 'RECEIVED' || currentStage === 'INTAKE')) ||
(stage === 'REPAIRING' && (currentStage === 'UNDER_REPAIR' || currentStage === 'PART_PENDING')) ||
(stage === 'COMPLETED' && (currentStage === 'READY_FOR_DELIVERY' || currentStage === 'QC_TESTING'));
});
return ( return (
<div key={stage} className={`${shell} p-3 flex flex-col min-h-[500px]`}> <div key={stage} className={`${shell} p-3 flex flex-col min-h-[500px]`}>
@ -145,7 +156,7 @@ export default function RepairTicketsPage() {
className="p-3 bg-background border border-border crm-radius-control hover:border-primary transition-colors cursor-pointer" className="p-3 bg-background border border-border crm-radius-control hover:border-primary transition-colors cursor-pointer"
> >
<div className="flex items-center justify-between gap-2 mb-1.5"> <div className="flex items-center justify-between gap-2 mb-1.5">
<span className="text-[13px] font-semibold text-foreground">{t.ticket_number}</span> <span className="text-[13px] font-semibold text-foreground">{t.ticket_number || 'TKT-PENDING'}</span>
<span <span
className={`inline-flex items-center px-2 py-0.5 crm-radius-badge text-[11px] font-semibold ${ className={`inline-flex items-center px-2 py-0.5 crm-radius-badge text-[11px] font-semibold ${
t.priority === 'URGENT' t.priority === 'URGENT'
@ -155,23 +166,27 @@ export default function RepairTicketsPage() {
: 'bg-muted text-muted-foreground' : 'bg-muted text-muted-foreground'
}`} }`}
> >
{t.priority} {t.priority || 'NORMAL'}
</span> </span>
</div> </div>
<div className="text-[13px] font-medium text-foreground flex items-center gap-1.5 mb-1"> <div className="text-[13px] font-medium text-foreground flex items-center gap-1.5 mb-1">
<Smartphone className="w-3.5 h-3.5 text-muted-foreground shrink-0" /> <Smartphone className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
{t.brand_name} {t.model_name} {(t.brand_name || t.model_name)
? `${t.brand_name || ''} ${t.model_name || ''}`.trim()
: (t.device_id ? `Device #${t.device_id.slice(-6)}` : 'Customer Device')}
</div> </div>
<p className="text-[13px] text-muted-foreground line-clamp-2 mb-2"> <p className="text-[13px] text-muted-foreground line-clamp-2 mb-2">
{t.problem_description} {t.problem_description || t.issue_description || 'No description provided'}
</p> </p>
<div className="border-t border-border pt-2 flex items-center justify-between gap-2 text-[12px] text-muted-foreground"> <div className="border-t border-border pt-2 flex items-center justify-between gap-2 text-[12px] text-muted-foreground">
<div className="flex items-center gap-1 min-w-0"> <div className="flex items-center gap-1 min-w-0">
<ShieldCheck className="w-3.5 h-3.5 text-success shrink-0" /> <ShieldCheck className="w-3.5 h-3.5 text-success shrink-0" />
<span className="font-mono truncate">{t.imei_serial.slice(-6)}</span> <span className="font-mono truncate">
{t.imei_serial ? t.imei_serial.slice(-6) : (t.device_id ? t.device_id.slice(-6) : (t.ticket_number || 'N/A').slice(-6))}
</span>
</div> </div>
{t.sla_due_at && ( {t.sla_due_at && (
<div className="flex items-center gap-1 text-warning font-semibold shrink-0"> <div className="flex items-center gap-1 text-warning font-semibold shrink-0">

View file

@ -91,9 +91,9 @@ export default function StaffDirectoryPage() {
return () => document.removeEventListener('mousedown', onPointerDown); return () => document.removeEventListener('mousedown', onPointerDown);
}, [openMenuId]); }, [openMenuId]);
const getRoleName = (roleId: string) => ROLES.find((r) => r.id === roleId)?.name || 'Staff Member'; const getRoleName = (roleId: string, user?: UserResponse) => user?.role_name || ROLES.find((r) => r.id === roleId)?.name || 'Staff Member';
const getDeptName = (deptId: string) => DEPARTMENTS.find((d) => d.id === deptId)?.name || 'Operations'; const getDeptName = (deptId: string, user?: UserResponse) => user?.department_name || DEPARTMENTS.find((d) => d.id === deptId)?.name || 'General';
const getDesigName = (desigId: string) => DESIGNATIONS.find((d) => d.id === desigId)?.name || ''; const getDesigName = (desigId: string, user?: UserResponse) => user?.designation_name || DESIGNATIONS.find((d) => d.id === desigId)?.name || '';
const sortedUsers = useMemo(() => { const sortedUsers = useMemo(() => {
const q = search.trim().toLowerCase(); const q = search.trim().toLowerCase();
@ -360,7 +360,7 @@ export default function StaffDirectoryPage() {
</p> </p>
<p className="flex items-center gap-2 min-w-0"> <p className="flex items-center gap-2 min-w-0">
<MapPin className="w-3.5 h-3.5 shrink-0" /> <MapPin className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">{getDeptName(user.department_id)}</span> <span className="truncate">{getDeptName(user.department_id, user)}</span>
</p> </p>
</div> </div>
@ -436,7 +436,7 @@ export default function StaffDirectoryPage() {
</div> </div>
</td> </td>
<td className="px-5 py-3.5 text-[13px] text-foreground">{getRoleName(user.role_id)}</td> <td className="px-5 py-3.5 text-[13px] text-foreground">{getRoleName(user.role_id)}</td>
<td className="px-5 py-3.5 text-[13px] text-muted-foreground">{getDeptName(user.department_id)}</td> <td className="px-5 py-3.5 text-[13px] text-muted-foreground">{getDeptName(user.department_id, user)}</td>
<td className="px-5 py-3.5 text-[13px] text-muted-foreground">{user.email}</td> <td className="px-5 py-3.5 text-[13px] text-muted-foreground">{user.email}</td>
<td className="px-5 py-3.5 text-[13px] text-muted-foreground"> <td className="px-5 py-3.5 text-[13px] text-muted-foreground">
{user.last_activity || 'No recent activity'} {user.last_activity || 'No recent activity'}

View file

@ -161,6 +161,8 @@ export default function UsersPage() {
const [formErrors, setFormErrors] = useState<Record<string, string>>({}); const [formErrors, setFormErrors] = useState<Record<string, string>>({});
const [availableRoles, setAvailableRoles] = useState<{ id: string; name: string }[]>(ROLES); const [availableRoles, setAvailableRoles] = useState<{ id: string; name: string }[]>(ROLES);
const [availableDepartments, setAvailableDepartments] = useState<{ id: string; name: string }[]>(DEPARTMENTS);
const [availableDesignations, setAvailableDesignations] = useState<{ id: string; name: string }[]>(DESIGNATIONS);
const [availableLocations, setAvailableLocations] = useState<{ location_id: string; name: string }[]>([]); const [availableLocations, setAvailableLocations] = useState<{ location_id: string; name: string }[]>([]);
const fetchUsers = async () => { const fetchUsers = async () => {
@ -180,6 +182,20 @@ export default function UsersPage() {
} }
} catch { } } catch { }
try {
const dynDepts = await userService.getDepartments();
if (dynDepts && dynDepts.length > 0) {
setAvailableDepartments(dynDepts);
}
} catch { }
try {
const dynDesigs = await userService.getDesignations();
if (dynDesigs && dynDesigs.length > 0) {
setAvailableDesignations(dynDesigs);
}
} catch { }
try { try {
const locs = await systemConfigService.getLocations(); const locs = await systemConfigService.getLocations();
if (locs) setAvailableLocations(locs); if (locs) setAvailableLocations(locs);
@ -203,9 +219,20 @@ export default function UsersPage() {
return () => document.removeEventListener('mousedown', onPointerDown); return () => document.removeEventListener('mousedown', onPointerDown);
}, [showFilters]); }, [showFilters]);
const getRoleName = (id: string) => availableRoles.find(r => r.id === id || r.name.toLowerCase() === id.toLowerCase())?.name || id || 'Unknown'; const getRoleName = (id: string, user?: UserResponse) => {
const getDeptName = (id: string) => DEPARTMENTS.find(d => d.id === id)?.name || 'Unknown'; if (user?.role_name) return user.role_name;
const getDesigName = (id: string) => DESIGNATIONS.find(d => d.id === id)?.name || 'Unknown'; return availableRoles.find(r => r.id === id || r.name.toLowerCase() === id?.toLowerCase())?.name || id || 'Staff';
};
const getDeptName = (id?: string, user?: UserResponse) => {
if (user?.department_name) return user.department_name;
if (!id) return '';
return availableDepartments.find(d => d.id === id || d.name.toLowerCase() === id?.toLowerCase())?.name || '';
};
const getDesigName = (id?: string, user?: UserResponse) => {
if (user?.designation_name) return user.designation_name;
if (!id) return '';
return availableDesignations.find(d => d.id === id || d.name.toLowerCase() === id?.toLowerCase())?.name || '';
};
// Validation Form Checks // Validation Form Checks
const validateForm = (data: Partial<UserCreate>, isEdit = false): boolean => { const validateForm = (data: Partial<UserCreate>, isEdit = false): boolean => {
@ -921,7 +948,7 @@ export default function UsersPage() {
<p className="text-[13px] font-semibold text-foreground truncate"> <p className="text-[13px] font-semibold text-foreground truncate">
{user.first_name} {user.last_name} {user.first_name} {user.last_name}
</p> </p>
<p className="text-[11px] text-muted-foreground truncate">{getRoleName(user.role_id)}</p> <p className="text-[11px] text-muted-foreground truncate">{getRoleName(user.role_id, user)}</p>
</div> </div>
</div> </div>
{renderStatusBadge(user.is_active)} {renderStatusBadge(user.is_active)}
@ -929,7 +956,17 @@ export default function UsersPage() {
<div className="mt-3 space-y-1.5 text-[12px] text-muted-foreground"> <div className="mt-3 space-y-1.5 text-[12px] text-muted-foreground">
<p className="flex items-center gap-1.5 truncate"><Mail className="w-3.5 h-3.5 shrink-0" />{user.email}</p> <p className="flex items-center gap-1.5 truncate"><Mail className="w-3.5 h-3.5 shrink-0" />{user.email}</p>
<p className="flex items-center gap-1.5 truncate"><Phone className="w-3.5 h-3.5 shrink-0" />{user.phone || '—'}</p> <p className="flex items-center gap-1.5 truncate"><Phone className="w-3.5 h-3.5 shrink-0" />{user.phone || '—'}</p>
<p className="truncate">{getDeptName(user.department_id)} · {getDesigName(user.designation_id)}</p> {(() => {
const dept = getDeptName(user.department_id, user);
const desig = getDesigName(user.designation_id, user);
if (dept && desig) {
return <p className="truncate text-[12px] text-muted-foreground">{dept} · {desig}</p>;
} else if (dept || desig) {
return <p className="truncate text-[12px] text-muted-foreground">{dept || desig}</p>;
} else {
return <p className="truncate text-[12px] text-muted-foreground">{getRoleName(user.role_id, user)}</p>;
}
})()}
</div> </div>
<div className="mt-3 flex items-center justify-end gap-1"> <div className="mt-3 flex items-center justify-end gap-1">
<button type="button" onClick={() => handleViewClick(user)} className="w-8 h-8 crm-radius-control hover:bg-muted cursor-pointer flex items-center justify-center" title="View details"> <button type="button" onClick={() => handleViewClick(user)} className="w-8 h-8 crm-radius-control hover:bg-muted cursor-pointer flex items-center justify-center" title="View details">
@ -1036,10 +1073,10 @@ export default function UsersPage() {
{visibleColumns.roleDept && ( {visibleColumns.roleDept && (
<td className="px-5 py-3.5"> <td className="px-5 py-3.5">
<span className="text-[13px] font-semibold text-foreground block"> <span className="text-[13px] font-semibold text-foreground block">
{getRoleName(user.role_id)} {getRoleName(user.role_id, user)}
</span> </span>
<span className="text-[11px] text-muted-foreground block"> <span className="text-[11px] text-muted-foreground block">
{getDeptName(user.department_id)} {getDeptName(user.department_id, user) || getDesigName(user.designation_id, user) || '—'}
</span> </span>
</td> </td>
)} )}
@ -1450,15 +1487,15 @@ export default function UsersPage() {
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div> <div>
<p className={labelClass}>Role</p> <p className={labelClass}>Role</p>
<p className="text-[13px] font-semibold text-foreground">{getRoleName(selectedUser.role_id)}</p> <p className="text-[13px] font-semibold text-foreground">{getRoleName(selectedUser.role_id, selectedUser)}</p>
</div> </div>
<div> <div>
<p className={labelClass}>Department</p> <p className={labelClass}>Department</p>
<p className="text-[13px] font-semibold text-foreground">{getDeptName(selectedUser.department_id)}</p> <p className="text-[13px] font-semibold text-foreground">{getDeptName(selectedUser.department_id, selectedUser) || 'General'}</p>
</div> </div>
<div> <div>
<p className={labelClass}>Designation</p> <p className={labelClass}>Designation</p>
<p className="text-[13px] font-semibold text-foreground">{getDesigName(selectedUser.designation_id)}</p> <p className="text-[13px] font-semibold text-foreground">{getDesigName(selectedUser.designation_id, selectedUser) || getRoleName(selectedUser.role_id, selectedUser)}</p>
</div> </div>
<div> <div>
<p className={labelClass}>Status</p> <p className={labelClass}>Status</p>

View file

@ -18,6 +18,13 @@ import {
EMPTY_ACTIVITY, EMPTY_ACTIVITY,
} from '@/components/dashboard/DashboardShared'; } from '@/components/dashboard/DashboardShared';
const withTimeout = <T>(promise: Promise<T>, ms = 3500, fallback: T): Promise<T> => {
return Promise.race([
promise,
new Promise<T>((resolve) => setTimeout(() => resolve(fallback), ms)),
]);
};
export function useDashboardData() { export function useDashboardData() {
const [stats, setStats] = useState<DashboardStats | null>(null); const [stats, setStats] = useState<DashboardStats | null>(null);
const [sessions, setSessions] = useState<SessionInfo[]>([]); const [sessions, setSessions] = useState<SessionInfo[]>([]);
@ -44,12 +51,12 @@ export function useDashboardData() {
else setRefreshing(true); else setRefreshing(true);
try { try {
const [statsRes, ordersRes, productsRes, categoriesRes, brandsRes, sessionsRes] = await Promise.allSettled([ const [statsRes, ordersRes, productsRes, categoriesRes, brandsRes, sessionsRes] = await Promise.allSettled([
adminService.getDashboardStats().catch(() => null), withTimeout(adminService.getDashboardStats().catch(() => null), 3500, null),
apiFetch<any[]>('/api/v1/admin/orders').catch(() => []), withTimeout(apiFetch<any[]>('/api/v1/admin/orders').catch(() => []), 3500, []),
apiFetch<any>('/api/v1/catalog/products/all?limit=25').catch(() => []), withTimeout(apiFetch<any>('/api/v1/catalog/products/all?limit=25').catch(() => []), 3500, []),
apiFetch<any[]>('/api/v1/catalog/categories/all').catch(() => []), withTimeout(apiFetch<any[]>('/api/v1/catalog/categories/all').catch(() => []), 3500, []),
apiFetch<any[]>('/api/v1/catalog/brands/all').catch(() => []), withTimeout(apiFetch<any[]>('/api/v1/catalog/brands/all').catch(() => []), 3500, []),
adminService.listSessions(0, 50).catch(() => ({ sessions: [] })), withTimeout(adminService.listSessions(0, 50).catch(() => ({ sessions: [] })), 3500, { sessions: [] }),
]); ]);
const liveStats = statsRes.status === 'fulfilled' ? statsRes.value : null; const liveStats = statsRes.status === 'fulfilled' ? statsRes.value : null;

View file

@ -5,17 +5,20 @@ export interface RepairTicket {
tenant_id: string; tenant_id: string;
ticket_number: string; ticket_number: string;
customer_id: string; customer_id: string;
customer_name: string; customer_name?: string;
customer_phone: string; customer_phone?: string;
imei_serial: string; imei_serial?: string;
brand_name: string; brand_name?: string;
model_name: string; model_name?: string;
problem_description: string; problem_description?: string;
status: string; // INTAKE, DIAGNOSING, REPAIRING, COMPLETED, DELIVERED issue_description?: string;
priority: string; status?: string;
stage?: string;
priority?: string;
device_id?: string;
assigned_technician_id?: string; assigned_technician_id?: string;
sla_due_at?: string; sla_due_at?: string;
created_at: string; created_at?: string;
} }
export const repairService = { export const repairService = {

View file

@ -15,6 +15,9 @@ export interface UserResponse {
department_id: string; department_id: string;
designation_id: string; designation_id: string;
role_id: string; role_id: string;
department_name?: string | null;
designation_name?: string | null;
role_name?: string | null;
manager_id: string | null; manager_id: string | null;
is_active: boolean; is_active: boolean;
email_verified: boolean; email_verified: boolean;
@ -88,4 +91,12 @@ export const userService = {
method: 'DELETE', method: 'DELETE',
}); });
}, },
async getDepartments(): Promise<{ id: string; name: string; description?: string }[]> {
return apiFetch<{ id: string; name: string; description?: string }[]>('/api/v1/users/departments/all');
},
async getDesignations(): Promise<{ id: string; name: string; description?: string }[]> {
return apiFetch<{ id: string; name: string; description?: string }[]>('/api/v1/users/designations/all');
},
}; };