Files
star-erp/resources/js/Layouts/AuthenticatedLayout.tsx

553 lines
23 KiB
TypeScript
Raw Normal View History

2026-01-07 08:23:45 +08:00
import {
LayoutDashboard,
2026-01-07 08:23:45 +08:00
ChevronRight,
Package,
ShoppingCart,
Menu,
X,
PanelLeftClose,
PanelLeftOpen,
Boxes,
Warehouse,
Truck,
Contact2,
2026-01-07 14:44:01 +08:00
LogOut,
User,
ChevronDown,
Settings,
Shield,
Users,
FileText,
Wallet,
BarChart3,
FileSpreadsheet
2026-01-07 08:23:45 +08:00
} from "lucide-react";
import { toast, Toaster } from "sonner";
import { useState, useEffect, useMemo } from "react";
import { Link, usePage, Head } from "@inertiajs/react";
2025-12-30 15:03:19 +08:00
import { cn } from "@/lib/utils";
2026-01-07 13:06:49 +08:00
import BreadcrumbNav, { BreadcrumbItemType } from "@/Components/shared/BreadcrumbNav";
2026-01-07 14:44:01 +08:00
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/Components/ui/dropdown-menu";
import { usePermission } from "@/hooks/usePermission";
import ApplicationLogo from "@/Components/ApplicationLogo";
import { generateLightestColor, generateLightColor, generateDarkColor, generateActiveColor } from "@/utils/colorUtils";
import { PageProps } from "@/types/global";
2025-12-30 15:03:19 +08:00
interface MenuItem {
id: string;
label: string;
icon?: React.ReactNode;
route?: string;
children?: MenuItem[];
permission?: string | string[]; // 所需權限(單一或多個,滿足任一即可)
2025-12-30 15:03:19 +08:00
}
2026-01-07 13:06:49 +08:00
export default function AuthenticatedLayout({
children,
breadcrumbs
}: {
children: React.ReactNode,
breadcrumbs?: BreadcrumbItemType[]
}) {
const { url, props } = usePage<PageProps & { [key: string]: any }>();
const branding = props.branding;
const user = props.auth?.user || { name: 'Guest', username: 'guest', roles: [], role_labels: [], permissions: [] };
const { can, canAny } = usePermission();
2026-01-06 16:17:12 +08:00
const [isCollapsed, setIsCollapsed] = useState(() => {
if (typeof window !== "undefined") {
return localStorage.getItem("sidebar-collapsed") === "true";
}
return false;
});
const [isMobileOpen, setIsMobileOpen] = useState(false);
// 完整的菜單定義(含權限配置)
const allMenuItems: MenuItem[] = [
{
id: "dashboard",
label: "儀表板",
icon: <LayoutDashboard className="h-5 w-5" />,
route: "/",
// 儀表板無需特定權限,所有登入使用者皆可存取
},
2025-12-30 15:03:19 +08:00
{
id: "inventory-management",
label: "商品與庫存管理",
2026-01-07 08:23:45 +08:00
icon: <Boxes className="h-5 w-5" />,
permission: ["products.view", "warehouses.view"], // 滿足任一即可看到此群組
2025-12-30 15:03:19 +08:00
children: [
{
id: "product-management",
label: "商品資料管理",
2026-01-07 08:23:45 +08:00
icon: <Package className="h-4 w-4" />,
2025-12-30 15:03:19 +08:00
route: "/products",
permission: "products.view",
2025-12-30 15:03:19 +08:00
},
{
id: "warehouse-management",
label: "倉庫管理",
2026-01-07 08:23:45 +08:00
icon: <Warehouse className="h-4 w-4" />,
2025-12-30 15:03:19 +08:00
route: "/warehouses",
permission: "warehouses.view",
2025-12-30 15:03:19 +08:00
},
],
},
{
id: "vendor-management",
label: "廠商管理",
2026-01-07 08:23:45 +08:00
icon: <Truck className="h-5 w-5" />,
permission: "vendors.view",
2025-12-30 15:03:19 +08:00
children: [
{
id: "vendor-list",
label: "廠商資料管理",
2026-01-07 08:23:45 +08:00
icon: <Contact2 className="h-4 w-4" />,
2025-12-30 15:03:19 +08:00
route: "/vendors",
permission: "vendors.view",
2025-12-30 15:03:19 +08:00
},
],
},
{
id: "purchase-management",
label: "採購管理",
icon: <ShoppingCart className="h-5 w-5" />,
permission: "purchase_orders.view",
2025-12-30 15:03:19 +08:00
children: [
{
id: "purchase-order-list",
label: "採購單管理",
icon: <ShoppingCart className="h-4 w-4" />,
2025-12-30 15:03:19 +08:00
route: "/purchase-orders",
permission: "purchase_orders.view",
2025-12-30 15:03:19 +08:00
},
],
},
{
id: "production-management",
label: "生產管理",
icon: <Boxes className="h-5 w-5" />,
permission: "production_orders.view",
children: [
{
id: "production-order-list",
label: "生產工單",
icon: <Package className="h-4 w-4" />,
route: "/production-orders",
permission: "production_orders.view",
},
],
},
{
id: "finance-management",
label: "財務管理",
icon: <Wallet className="h-5 w-5" />,
permission: "utility_fees.view",
children: [
{
id: "utility-fee-list",
label: "公共事業費",
icon: <FileText className="h-4 w-4" />,
route: "/utility-fees",
permission: "utility_fees.view",
},
],
},
{
id: "report-management",
label: "報表管理",
icon: <BarChart3 className="h-5 w-5" />,
permission: "accounting.view",
children: [
{
id: "accounting-report",
label: "會計報表",
icon: <FileSpreadsheet className="h-4 w-4" />,
route: "/accounting-report",
permission: "accounting.view",
},
],
},
{
id: "system-management",
label: "系統管理",
icon: <Settings className="h-5 w-5" />,
permission: ["users.view", "roles.view"],
children: [
{
id: "user-management",
label: "使用者管理",
icon: <Users className="h-4 w-4" />,
route: "/admin/users",
permission: "users.view",
},
{
id: "role-management",
label: "角色與權限",
icon: <Shield className="h-4 w-4" />,
route: "/admin/roles",
permission: "roles.view",
},
{
id: "activity-log",
label: "操作紀錄",
icon: <FileText className="h-4 w-4" />,
route: "/admin/activity-logs",
permission: "system.view_logs",
},
],
},
2025-12-30 15:03:19 +08:00
];
// 檢查單一項目是否有權限
const hasPermissionForItem = (item: MenuItem): boolean => {
if (!item.permission) return true; // 無指定權限則預設有權限
if (Array.isArray(item.permission)) {
return canAny(item.permission);
}
return can(item.permission);
};
// 過濾菜單:移除無權限的項目,若父層所有子項目都無權限則隱藏父層
const menuItems = useMemo(() => {
return allMenuItems
.map((item) => {
// 如果有子項目,先過濾子項目
if (item.children && item.children.length > 0) {
const filteredChildren = item.children.filter(hasPermissionForItem);
// 若所有子項目都無權限,則隱藏整個群組
if (filteredChildren.length === 0) return null;
return { ...item, children: filteredChildren };
}
// 無子項目的單一選單,直接檢查權限
if (!hasPermissionForItem(item)) return null;
return item;
})
.filter((item): item is MenuItem => item !== null);
}, [can, canAny]);
2025-12-30 15:03:19 +08:00
// 初始化狀態:優先讀取 localStorage
const [expandedItems, setExpandedItems] = useState<string[]>(() => {
try {
const saved = localStorage.getItem("sidebar-expanded-items");
if (saved) return JSON.parse(saved);
} catch (e) {
console.error("Failed to parse sidebar state", e);
}
// 如果沒有存檔,則預設僅展開當前 URL 對應的群組
const activeItem = menuItems.find(item =>
item.children?.some(child => child.route && url.startsWith(child.route))
);
return activeItem ? [activeItem.id] : ["inventory-management"];
});
// 監聽 URL 變化,確保「當前」頁面所屬群組是展開的
// 但不要影響其他群組的狀態(除非使用者手動切換)
useEffect(() => {
const activeItem = menuItems.find(item =>
item.children?.some(child => child.route && url.startsWith(child.route))
);
if (activeItem && !expandedItems.includes(activeItem.id)) {
setExpandedItems(prev => {
const next = [...prev, activeItem.id];
localStorage.setItem("sidebar-expanded-items", JSON.stringify(next));
return next;
});
}
}, [url]);
2026-01-06 16:17:12 +08:00
useEffect(() => {
localStorage.setItem("sidebar-collapsed", String(isCollapsed));
}, [isCollapsed]);
// 全域監聽 flash 訊息並顯示 Toast
useEffect(() => {
// @ts-ignore
if (props.flash?.success) {
// @ts-ignore
toast.success(props.flash.success);
}
// @ts-ignore
if (props.flash?.error) {
// @ts-ignore
toast.error(props.flash.error);
}
}, [props.flash]);
2025-12-30 15:03:19 +08:00
const toggleExpand = (itemId: string) => {
2026-01-06 16:17:12 +08:00
if (isCollapsed) {
setIsCollapsed(false);
if (!expandedItems.includes(itemId)) {
setExpandedItems(prev => [...prev, itemId]);
}
return;
}
2025-12-30 15:03:19 +08:00
setExpandedItems((prev) => {
const next = prev.includes(itemId)
? prev.filter((id) => id !== itemId)
: [...prev, itemId];
localStorage.setItem("sidebar-expanded-items", JSON.stringify(next));
return next;
});
};
const renderMenuItem = (item: MenuItem, level: number = 0) => {
const hasChildren = item.children && item.children.length > 0;
const isExpanded = expandedItems.includes(item.id);
const isActive = item.route
? (item.route === '/' ? url === '/' : url.startsWith(item.route))
: false;
2025-12-30 15:03:19 +08:00
return (
2026-01-06 16:17:12 +08:00
<div key={item.id} className="mb-1">
2025-12-30 15:03:19 +08:00
{hasChildren ? (
<button
onClick={() => toggleExpand(item.id)}
className={cn(
2026-01-06 16:17:12 +08:00
"w-full flex items-center transition-all rounded-lg group",
level === 0 ? "px-3 py-2.5" : "px-3 py-2 pl-10",
level === 0 && !isCollapsed && "hover:bg-slate-100",
isCollapsed && level === 0 && "justify-center px-0 h-10 w-10 mx-auto hover:bg-slate-100"
2025-12-30 15:03:19 +08:00
)}
2026-01-06 16:17:12 +08:00
title={isCollapsed ? item.label : ""}
2025-12-30 15:03:19 +08:00
>
2026-01-06 16:17:12 +08:00
{level === 0 && (
<span className={cn(
"flex-shrink-0 transition-all",
isCollapsed ? "mr-0" : "mr-3 text-slate-500 group-hover:text-slate-900"
)}>
2025-12-30 15:03:19 +08:00
{item.icon}
</span>
)}
2026-01-06 16:17:12 +08:00
{!isCollapsed && (
<>
2026-01-07 08:23:45 +08:00
<span className="flex-1 text-left text-base font-medium text-slate-700 group-hover:text-slate-900 truncate">
2026-01-06 16:17:12 +08:00
{item.label}
</span>
<span className="flex-shrink-0 transition-transform duration-200">
{isExpanded ? (
<ChevronDown className="h-3.5 w-3.5 text-slate-400" />
) : (
<ChevronRight className="h-3.5 w-3.5 text-slate-400" />
)}
</span>
</>
)}
2025-12-30 15:03:19 +08:00
</button>
) : (
<Link
href={item.route || "#"}
2026-01-06 16:17:12 +08:00
onClick={() => setIsMobileOpen(false)}
2025-12-30 15:03:19 +08:00
className={cn(
2026-01-06 16:17:12 +08:00
"w-full flex items-center transition-all rounded-lg group",
level === 0 ? "px-3 py-2.5" : "px-3 py-2",
level > 0 && !isCollapsed && "pl-11",
isActive ? "bg-primary-lightest text-primary-main" : "text-slate-600 hover:bg-slate-100 hover:text-slate-900",
isCollapsed && level === 0 && "justify-center px-0 h-10 w-10 mx-auto"
2025-12-30 15:03:19 +08:00
)}
2026-01-06 16:17:12 +08:00
title={isCollapsed ? item.label : ""}
2025-12-30 15:03:19 +08:00
>
{item.icon && (
2026-01-06 16:17:12 +08:00
<span className={cn(
"flex-shrink-0 transition-all",
isCollapsed ? "mr-0" : "mr-3",
isActive ? "text-primary-main" : "text-slate-500 group-hover:text-slate-900"
)}>
2025-12-30 15:03:19 +08:00
{item.icon}
</span>
)}
2026-01-06 16:17:12 +08:00
{!isCollapsed && (
2026-01-07 08:23:45 +08:00
<span className="text-base font-medium truncate">
2026-01-06 16:17:12 +08:00
{item.label}
</span>
)}
2025-12-30 15:03:19 +08:00
</Link>
)}
2026-01-06 16:17:12 +08:00
{hasChildren && isExpanded && !isCollapsed && (
<div className="mt-1 space-y-1">
2025-12-30 15:03:19 +08:00
{item.children?.map((child) => renderMenuItem(child, level + 1))}
</div>
)}
</div>
);
};
return (
2026-01-06 16:17:12 +08:00
<div className="flex min-h-screen bg-slate-50">
<Head>
<link rel="icon" type="image/png" href="/favicon.png" />
</Head>
<style>{`
:root {
--primary-main: ${branding?.primary_color || '#01ab83'};
--primary-dark: ${generateDarkColor(branding?.primary_color || '#01ab83')};
--primary-light: ${generateLightColor(branding?.primary_color || '#01ab83')};
--primary-lightest: ${generateLightestColor(branding?.primary_color || '#01ab83')};
--button-main-active: ${generateActiveColor(branding?.primary_color || '#01ab83')};
}
`}</style>
2026-01-07 11:39:54 +08:00
{/* Mobile Header -> Global Header */}
<header className="fixed top-0 left-0 right-0 h-16 bg-white border-b border-slate-200 z-[60] flex items-center justify-between px-4 transition-all duration-300">
<div className="flex items-center gap-2">
<button
onClick={() => setIsMobileOpen(!isMobileOpen)}
className="p-2 -ml-2 text-slate-600 hover:bg-slate-100 rounded-lg lg:hidden"
>
{isMobileOpen ? <X className="h-6 w-6" /> : <Menu className="h-6 w-6" />}
</button>
<Link href="/" className="flex items-center gap-2">
<ApplicationLogo className="w-8 h-8 rounded-lg object-contain" />
2026-01-07 11:39:54 +08:00
<span className="font-bold text-slate-900"> ERP</span>
</Link>
</div>
2026-01-07 14:44:01 +08:00
{/* User Menu */}
<DropdownMenu modal={false}>
<DropdownMenuTrigger className="flex items-center gap-2 outline-none group">
<div className="hidden md:flex flex-col items-end mr-1">
<span className="text-sm font-medium text-slate-700 group-hover:text-slate-900 transition-colors">
{user.name} ({user.username})
2026-01-07 14:44:01 +08:00
</span>
<span className="text-xs text-slate-500">
{user.role_labels?.[0] || user.roles?.[0] || '一般用戶'}
2026-01-07 14:44:01 +08:00
</span>
</div>
<div className="h-9 w-9 bg-slate-100 rounded-full flex items-center justify-center text-slate-600 group-hover:bg-primary-lightest group-hover:text-primary-main transition-all">
<User className="h-5 w-5" />
</div>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56 z-[100]" sideOffset={8}>
<DropdownMenuLabel>{user.name} ({user.username})</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link
href={route('profile.edit')}
className="w-full flex items-center cursor-pointer text-slate-600 focus:bg-slate-100 focus:text-slate-900 group"
>
<Settings className="mr-2 h-4 w-4 text-slate-500 group-focus:text-slate-900" />
<span>使</span>
</Link>
</DropdownMenuItem>
2026-01-07 14:44:01 +08:00
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link
href={route('logout')}
method="post"
as="button"
className="w-full flex items-center cursor-pointer text-red-600 focus:text-red-600 focus:bg-red-50"
>
<LogOut className="mr-2 h-4 w-4" />
<span></span>
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
2026-01-06 16:17:12 +08:00
</header>
{/* Sidebar Desktop */}
<aside className={cn(
2026-01-07 11:39:54 +08:00
"fixed left-0 top-0 bottom-0 bg-white border-r border-slate-200 z-50 transition-all duration-300 ease-in-out hidden lg:flex flex-col pt-16",
2026-01-06 16:17:12 +08:00
isCollapsed ? "w-20" : "w-64"
)}>
2026-01-07 11:39:54 +08:00
<div className="hidden h-16 items-center justify-between px-6 border-b border-slate-100">
2026-01-06 16:17:12 +08:00
{!isCollapsed && (
<Link href="/" className="flex items-center gap-2 group">
<ApplicationLogo className="w-8 h-8 rounded-lg object-contain group-hover:scale-110 transition-transform" />
<span className="font-extrabold text-primary-main text-lg tracking-tight"> ERP</span>
2026-01-06 16:17:12 +08:00
</Link>
)}
{isCollapsed && (
<Link href="/" className="w-8 h-8 mx-auto">
<ApplicationLogo className="w-8 h-8 rounded-lg object-contain" />
</Link>
2026-01-06 16:17:12 +08:00
)}
2025-12-30 15:03:19 +08:00
</div>
2026-01-06 16:17:12 +08:00
<div className="flex-1 overflow-y-auto overflow-x-hidden p-4 space-y-6">
<nav className="space-y-1">
{menuItems.map((item) => renderMenuItem(item))}
</nav>
</div>
<div className="p-4 border-t border-slate-100 flex items-center justify-between">
{!isCollapsed && <p className="text-[10px] font-medium text-slate-400 uppercase tracking-wider px-2">Version 1.0.0</p>}
<button
onClick={() => setIsCollapsed(!isCollapsed)}
className={cn(
"p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-50 rounded-lg transition-colors",
isCollapsed && "mx-auto"
)}
title={isCollapsed ? "展開側邊欄" : "縮合側邊欄"}
>
{isCollapsed ? <PanelLeftOpen className="h-5 w-5" /> : <PanelLeftClose className="h-5 w-5" />}
</button>
</div>
2026-01-07 14:44:01 +08:00
</aside >
2026-01-06 16:17:12 +08:00
{/* Mobile Sidebar Overlay */}
2026-01-07 14:44:01 +08:00
{
isMobileOpen && (
<div
className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm z-[70] lg:hidden"
onClick={() => setIsMobileOpen(false)}
/>
)
}
2026-01-06 16:17:12 +08:00
{/* Mobile Sidebar Drawer */}
<aside className={cn(
"fixed left-0 top-0 bottom-0 w-72 bg-white z-[80] transition-transform duration-300 ease-in-out lg:hidden flex flex-col shadow-2xl",
isMobileOpen ? "translate-x-0" : "-translate-x-full"
)}>
<div className="h-16 flex items-center justify-between px-6 border-b border-slate-100">
<Link href="/" className="flex items-center gap-2">
<ApplicationLogo className="w-8 h-8 rounded-lg object-contain" />
<span className="font-extrabold text-primary-main text-lg"> ERP</span>
2026-01-06 16:17:12 +08:00
</Link>
<button onClick={() => setIsMobileOpen(false)} className="p-2 text-slate-400">
<X className="h-5 w-5" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-4">
<nav className="space-y-1">
{menuItems.map((item) => renderMenuItem(item))}
</nav>
2025-12-30 15:03:19 +08:00
</div>
</aside>
2026-01-06 16:17:12 +08:00
{/* Main Content */}
<main className={cn(
2026-01-08 10:08:52 +08:00
"flex-1 flex flex-col transition-all duration-300 min-h-screen overflow-auto",
2026-01-06 16:17:12 +08:00
"lg:ml-64",
isCollapsed && "lg:ml-20",
2026-01-07 11:39:54 +08:00
"pt-16" // Always allow space for header
2026-01-06 16:17:12 +08:00
)}>
<div className="relative">
2026-01-07 13:06:49 +08:00
<div className="container mx-auto px-6 pt-6 max-w-7xl">
{breadcrumbs && breadcrumbs.length > 1 && (
<BreadcrumbNav items={breadcrumbs} className="mb-2" />
)}
</div>
2026-01-06 16:17:12 +08:00
{children}
</div>
2026-01-08 10:08:52 +08:00
<footer className="mt-auto py-6 text-center text-sm text-slate-400">
Copyright &copy; {new Date().getFullYear()} . All rights reserved. Design by
</footer>
2025-12-31 17:48:36 +08:00
<Toaster richColors closeButton position="top-center" />
2025-12-30 15:03:19 +08:00
</main>
2026-01-07 14:44:01 +08:00
</div >
2025-12-30 15:03:19 +08:00
);
}