ifixkart-admin/components/layouts/Sidebar.tsx

415 lines
15 KiB
TypeScript

'use client';
import { useEffect, useState, useMemo, type ComponentType } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { parseJwt, getAccessToken } from '@/services/api/client';
import { isRouteAllowed, getDefaultDashboardForRole } from '@/lib/rbac';
import {
LayoutDashboard,
Users,
Shield,
ChevronLeft,
ChevronDown,
Wrench,
Package,
Megaphone,
Warehouse,
Receipt,
BarChart3,
FileSpreadsheet,
Layers,
} from 'lucide-react';
import { cn } from '@/lib/utils';
interface SidebarProps {
collapsed: boolean;
onToggle: () => void;
overlay?: boolean;
variant?: 'vertical' | 'horizontal';
detached?: boolean;
}
type NavChild = { name: string; href: string };
type NavGroup = {
name: string;
icon: ComponentType<{ className?: string }>;
children: NavChild[];
};
const NAV_GROUPS: NavGroup[] = [
{
name: 'Dashboard',
icon: LayoutDashboard,
children: [
{ name: 'Main Overview', href: '/dashboard' },
{ name: 'Executive C-Suite', href: '/dashboard/executive' },
{ name: 'Store Manager', href: '/dashboard/store-manager' },
{ name: 'Technician Workshop', href: '/dashboard/technician' },
{ name: 'B2B Wholesale', href: '/dashboard/b2b' },
{ name: 'Product Analytics', href: '/products/dashboard' },
],
},
{
name: 'CRM & Sales Pipeline',
icon: Users,
children: [
{ name: 'Leads', href: '/crm-leads' },
{ name: 'Deals', href: '/crm-deals' },
{ name: 'Quotations', href: '/crm-quotations' },
{ name: 'Tasks', href: '/crm-todos' },
{ name: 'Calendar', href: '/crm-calendar' },
{ name: 'WhatsApp', href: '/whatsapp-web' },
{ name: 'Customers', href: '/customers' },
{ name: 'Repair customers', href: '/customers/service' },
],
},
{
name: 'Catalog Management',
icon: Package,
children: [
{ name: 'Product Categories', href: '/categories' },
{ name: 'Brands', href: '/brands' },
{ name: 'Device Series', href: '/series' },
{ name: 'Device Models', href: '/models' },
{ name: 'Products', href: '/products' },
{ name: 'Master Attributes', href: '/attributes' },
{ name: 'Bulk Product Import', href: '/migration' },
],
},
{
name: 'Marketing',
icon: Megaphone,
children: [
{ name: 'Google Merchant Center', href: '/merchant-center' },
{ name: 'Social Media Publisher', href: '/social-media' },
{ name: 'Google Analytics GA4', href: '/analytics/google' },
{ name: 'Homepage Layout', href: '/storefront-sections' },
{ name: 'Storefront CMS', href: '/storefront-cms' },
{ name: 'Customer Reviews', href: '/reviews-moderation' },
],
},
{
name: 'Inventory and Purchase',
icon: Warehouse,
children: [
{ name: 'Stock Ledger', href: '/inventory' },
{ name: 'Multi-Warehouse Routing', href: '/warehouses' },
{ name: 'Supplier Purchase Orders', href: '/purchases' },
],
},
{
name: 'Sales and Billings',
icon: Receipt,
children: [
{ name: 'Customer Store Orders', href: '/orders' },
{ name: 'Razorpay Dashboard', href: '/razorpay-dashboard' },
{ name: 'Shiprocket Logistics', href: '/logistics' },
{ name: 'Warranties', href: '/warranties' },
{ name: 'Refunds & Returns', href: '/refunds' },
{ name: 'Sales Invoices', href: '/invoices' },
{ name: 'B2B Bulk Quotations', href: '/bulk-quotations' },
{ name: 'POS Sessions & Cash', href: '/pos-sessions' },
{ name: 'User POS Analytics', href: '/user-pos-analytics' },
],
},
{
name: 'Repair and Services',
icon: Wrench,
children: [
{ name: '5-Stage Repair Queue', href: '/repair-tickets' },
{ name: 'Service Catalog Manager', href: '/service-catalog' },
{ name: 'Service Jobs Queue', href: '/services' },
{ name: 'Walk-In Device Queue', href: '/services/intake' },
{ name: 'Technician Workspace', href: '/technician' },
{ name: 'Service Quotations', href: '/service-quotes' },
{ name: 'Service Invoices', href: '/service-invoices' },
],
},
{
name: 'Reports & Intelligence',
icon: FileSpreadsheet,
children: [
{ name: 'AI Prediction Lab (Swarm)', href: '/simulation' },
{ name: 'Reporting Hub (Export)', href: '/reports' },
],
},
{
name: 'User Management',
icon: Users,
children: [
{ name: 'Manage Users', href: '/users' },
{ name: 'Roles & Permissions', href: '/roles' },
{ name: 'Staff Directory', href: '/staff-directory' },
{ name: 'User Activity Logs', href: '/activity-logs' },
],
},
{
name: 'Integrations Hub',
icon: Layers,
children: [
{ name: 'All Integrations', href: '/integrations' },
{ name: 'WhatsApp Hub (OpenWA & WATI)', href: '/integrations/whatsapp' },
{ name: 'Transactional Email', href: '/integrations/email' },
{ name: 'Google Analytics GA4', href: '/integrations/google-analytics' },
{ name: 'Meta Ads & Graph API', href: '/integrations/meta-ads' },
{ name: 'Knowlarity Telephony', href: '/integrations/call' },
{ name: 'Shiprocket Logistics', href: '/integrations/shipping' },
],
},
{
name: 'System Infrastructure',
icon: Shield,
children: [
{ name: 'Store Configuration', href: '/store-config' },
{ name: 'WhatsApp & Notification Gateway', href: '/notifications-gateway' },
{ name: 'Notification Templates', href: '/notification-templates' },
{ name: 'Security & Sessions', href: '/security' },
{ name: 'System Settings', href: '/settings' },
],
},
];
function pathMatches(href: string, pathname: string) {
if (pathname === href) return true;
if (href === '/integrations' && pathname === '/integrations') return true;
if (href.startsWith('/integrations/') && pathname.startsWith(href)) return true;
if (href === '/products' && pathname.startsWith('/products/') && pathname !== '/products/dashboard') {
return true;
}
if (href === '/services' && pathname.startsWith('/services/') && !pathname.startsWith('/services/intake')) {
return true;
}
if (href === '/crm-leads' && pathname.startsWith('/crm-leads')) return true;
return false;
}
function groupHasActive(group: NavGroup, pathname: string) {
return group.children.some((child) => pathMatches(child.href, pathname));
}
export function Sidebar({ collapsed, onToggle, overlay = false, variant = 'vertical', detached = false }: SidebarProps) {
const pathname = usePathname();
const router = useRouter();
const [mounted, setMounted] = useState(false);
const [userRole, setUserRole] = useState<string>('');
const [openGroups, setOpenGroups] = useState<string[]>([]);
useEffect(() => {
setMounted(true);
const token = getAccessToken();
if (token) {
const payload = parseJwt(token);
if (payload && typeof payload.role === 'string') {
setUserRole(payload.role.toLowerCase());
}
} else {
setUserRole('');
}
}, [pathname]);
const groups = useMemo(() => {
if (!mounted || !userRole) {
return NAV_GROUPS;
}
return NAV_GROUPS.map((group) => {
const allowedChildren = group.children.filter((child) => isRouteAllowed(child.href, userRole));
return {
...group,
children: allowedChildren,
};
}).filter((group) => group.children.length > 0);
}, [userRole, mounted]);
useEffect(() => {
if (!mounted) return;
const active = groups.find((group) => groupHasActive(group, pathname));
if (active) {
setOpenGroups((current) => (current.includes(active.name) ? current : [...current, active.name]));
}
}, [pathname, userRole, mounted, groups]);
const prefetchHref = (href: string) => {
if (href !== pathname) router.prefetch(href);
};
const toggleGroup = (name: string) => {
if (variant === 'horizontal') {
setOpenGroups((current) => (current.includes(name) ? [] : [name]));
return;
}
if (collapsed) {
onToggle();
setOpenGroups((current) => (current.includes(name) ? current : [...current, name]));
return;
}
setOpenGroups((current) =>
current.includes(name) ? current.filter((item) => item !== name) : [...current, name]
);
};
if (variant === 'horizontal') {
return (
<nav className="border-b border-border bg-card px-2 py-2 flex flex-wrap gap-1">
{groups.map((group) => {
const Icon = group.icon;
const open = openGroups.includes(group.name);
const active = groupHasActive(group, pathname);
return (
<div key={group.name} className="relative">
<button
type="button"
onClick={() => toggleGroup(group.name)}
className={cn(
'h-9 px-2.5 crm-radius-control inline-flex items-center gap-1.5 text-[13px] font-medium cursor-pointer',
open || active ? 'bg-primary/10 text-primary' : 'text-foreground hover:bg-muted'
)}
>
<Icon className="w-3.5 h-3.5" />
<span className="whitespace-nowrap">{group.name}</span>
<ChevronDown className={cn('w-3.5 h-3.5 transition-transform', open && 'rotate-180')} />
</button>
{open && (
<div className="absolute left-0 top-full z-30 mt-1 min-w-[220px] rounded-lg border border-border bg-card py-1 shadow-md">
{group.children.map((child) => {
const childActive = pathMatches(child.href, pathname);
return (
<Link
key={child.href}
href={child.href}
prefetch={false}
onMouseEnter={() => prefetchHref(child.href)}
onFocus={() => prefetchHref(child.href)}
onClick={() => setOpenGroups([])}
className={cn(
'block px-3 py-2 text-[13px] whitespace-nowrap',
childActive ? 'text-primary font-semibold' : 'text-foreground hover:bg-muted'
)}
>
{child.name}
</Link>
);
})}
</div>
)}
</div>
);
})}
</nav>
);
}
return (
<aside
className={cn(
'theme-sidebar flex flex-col bg-card border-r border-border transition-[width] duration-200 ease-out shrink-0',
detached ? 'h-full rounded-xl border shadow-md' : 'h-screen',
overlay && 'fixed left-0 top-0 z-20',
collapsed ? 'w-[70px] min-w-[70px] max-w-[70px]' : overlay ? 'w-[min(260px,85vw)] max-w-[85vw]' : 'w-[260px] min-w-[260px] max-w-[260px]'
)}
>
<div
className={cn(
'relative flex items-center h-14 shrink-0 border-b border-border',
collapsed ? 'justify-center px-2' : 'justify-between px-4'
)}
>
<Link href={getDefaultDashboardForRole(userRole)} className="flex items-center gap-2.5 min-w-0">
<div className="w-8 h-8 crm-radius-icon flex items-center justify-center shrink-0 bg-primary">
<Wrench className="w-4 h-4 text-white" />
</div>
{!collapsed && (
<span className="text-[15px] font-semibold text-foreground tracking-tight truncate">iFixKart</span>
)}
</Link>
<button
type="button"
onClick={onToggle}
className={cn(
'w-[22px] h-[22px] rounded-full flex items-center justify-center hover:bg-muted cursor-pointer transition-colors border border-border bg-card',
collapsed && 'absolute -right-2.5 top-1/2 -translate-y-1/2 rotate-180 z-10'
)}
aria-label="Toggle sidebar"
>
<ChevronLeft className="w-3.5 h-3.5 text-muted-foreground" />
</button>
</div>
<nav className={cn('flex-1 overflow-y-auto py-3', collapsed ? 'px-2' : 'px-3')}>
<div className="flex flex-col gap-1">
{groups.map((group) => {
const Icon = group.icon;
const open = !collapsed && openGroups.includes(group.name);
const active = groupHasActive(group, pathname);
const highlighted = open || active;
return (
<div key={group.name}>
<button
type="button"
title={collapsed ? group.name : undefined}
onClick={() => toggleGroup(group.name)}
className={cn(
'w-full flex items-center crm-radius-section text-[13px] font-medium cursor-pointer transition-colors',
collapsed ? 'justify-center p-1' : 'gap-2.5 px-2 py-1.5',
highlighted ? 'bg-primary/10 text-primary' : 'text-foreground hover:bg-muted'
)}
>
<span
className={cn(
'w-8 h-8 crm-radius-icon flex items-center justify-center shrink-0',
highlighted ? 'bg-primary text-white' : 'bg-muted text-muted-foreground'
)}
>
<Icon className="w-4 h-4" />
</span>
{!collapsed && (
<>
<span className="flex-1 text-left truncate">{group.name}</span>
<ChevronDown className={cn('w-3.5 h-3.5 shrink-0 transition-transform', open && 'rotate-180')} />
</>
)}
</button>
{open && (
<div className="relative ml-[26px] mt-1 mb-1 pl-4">
<span className="absolute left-0 top-1 bottom-2 border-l border-dashed border-border" />
<div className="flex flex-col">
{group.children.map((child) => {
const childActive = pathMatches(child.href, pathname);
return (
<Link
key={child.href}
href={child.href}
prefetch={false}
onMouseEnter={() => prefetchHref(child.href)}
onFocus={() => prefetchHref(child.href)}
className={cn(
'relative flex items-center gap-2.5 py-[7px] text-[13px] transition-colors min-w-0',
childActive
? 'text-primary font-semibold'
: 'text-muted-foreground hover:text-foreground'
)}
>
<span
className={cn(
'w-1.5 h-1.5 rounded-full shrink-0',
childActive ? 'bg-primary' : 'bg-[#c5cad3]'
)}
/>
<span className="truncate">{child.name}</span>
</Link>
);
})}
</div>
</div>
)}
</div>
);
})}
</div>
</nav>
</aside>
);
}