Files
zetaloop cd469d3d54 refactor(notifications): fetch from backend API instead of local generation
Rewrite store/notifications.ts to fetch via listNotifications
API and remove local generateId-based notification creation.
The store now acts as a simple cache with fetch/invalidate methods.
Header unread count reads from this API-backed cache.
2026-05-01 17:33:05 +08:00

410 lines
15 KiB
TypeScript

"use client"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"
import { getCurrentUserForLogin, logout as logoutRequest, switchCurrentRole } from "@/lib/api"
import { toApiError } from "@/lib/errors"
import { useMyShop } from "@/lib/hooks/use-my-shop"
import { notifyInfo } from "@/lib/toast"
import type { UserRole } from "@/lib/types"
import { cn } from "@/lib/utils"
import { useAuthStore } from "@/store/auth"
import { useNotificationStore } from "@/store/notifications"
import {
Bell,
Gamepad2,
LogOut,
Menu,
MessageSquare,
Settings,
ShoppingBag,
User,
Wallet,
} from "lucide-react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { useEffect, useState } from "react"
import { canAccessDashboard } from "@/components/role-guard"
const roleLabels = {
consumer: "客户",
player: "打手",
owner: "店主",
admin: "管理员",
} satisfies Record<UserRole, string>
export function Header() {
const [mobileOpen, setMobileOpen] = useState(false)
const pathname = usePathname()
const router = useRouter()
const {
isAuthenticated,
currentRole,
verifiedRoles,
login,
logout: clearAuth,
user,
} = useAuthStore()
const canOpenDashboard = currentRole === "player" || currentRole === "owner"
const { shop: ownerShop } = useMyShop(isAuthenticated && currentRole === "owner")
const fetchNotifications = useNotificationStore((state) => state.fetchNotifications)
useEffect(() => {
if (!isAuthenticated) return
void fetchNotifications()
}, [fetchNotifications, isAuthenticated])
const navLinks =
currentRole === "consumer"
? [
{ href: "/", label: "发现" },
{ href: "/community", label: "社区" },
{ href: "/orders", label: "订单" },
{ href: "/chat", label: "消息" },
]
: [
{ href: "/", label: "发现" },
{ href: "/community", label: "社区" },
{ href: "/orders", label: "订单" },
{ href: "/chat", label: "消息" },
...(canOpenDashboard ? [{ href: "/dashboard", label: "管理后台" }] : []),
]
const availableRoles = (Object.entries(roleLabels) as [UserRole, string][]).filter(([role]) =>
verifiedRoles.includes(role),
)
const handleRoleSwitch = (role: UserRole) => {
if (role === currentRole) {
setMobileOpen(false)
return
}
void (async () => {
try {
await switchCurrentRole(role)
const updated = await getCurrentUserForLogin()
login(updated, updated.verifiedRoles ?? [updated.role])
if (pathname.startsWith("/dashboard") && !canAccessDashboard(role, pathname)) {
router.push(role === "consumer" ? "/" : "/dashboard")
}
} catch (error) {
notifyInfo(toApiError(error).msg)
} finally {
setMobileOpen(false)
}
})()
}
const handleLogout = () => {
void (async () => {
try {
await logoutRequest()
} catch (error) {
notifyInfo(toApiError(error).msg)
} finally {
clearAuth()
useNotificationStore.getState().invalidate()
setMobileOpen(false)
router.push("/")
}
})()
}
const unreadCount = useNotificationStore(
(state) => state.notifications.filter((notification) => !notification.read).length,
)
const profileHref =
currentRole === "player"
? user
? `/player/${user.id}`
: "/settings"
: currentRole === "owner"
? ownerShop
? `/shop/${ownerShop.id}`
: "/dashboard/shop"
: user
? `/user/${user.id}`
: "/settings"
return (
<header className="sticky top-0 z-50 w-full border-b border-border/40 bg-background/80 backdrop-blur-md supports-[backdrop-filter]:bg-background/60">
<div className="container mx-auto flex h-16 items-center justify-between px-4 md:px-6">
<div className="flex items-center gap-6">
<Link href="/" className="flex items-center gap-2 font-bold text-lg shrink-0">
<Gamepad2 className="h-5 w-5" />
</Link>
<nav className="hidden md:flex items-center gap-1">
{navLinks.map((link) => {
const isActive =
pathname === link.href || (link.href !== "/" && pathname.startsWith(link.href))
return (
<Button
key={link.href}
variant={isActive ? "secondary" : "ghost"}
className={!isActive ? "text-muted-foreground" : undefined}
asChild
>
<Link href={link.href}>{link.label}</Link>
</Button>
)
})}
</nav>
</div>
<div className="flex items-center justify-end gap-1">
{isAuthenticated ? (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="hidden md:flex text-xs h-8 text-muted-foreground hover:text-foreground"
>
{roleLabels[currentRole]}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="space-y-1">
<DropdownMenuLabel></DropdownMenuLabel>
<DropdownMenuSeparator />
{availableRoles.map(([role, label]) => (
<DropdownMenuItem
key={role}
onClick={() => handleRoleSwitch(role)}
className={cn(
currentRole === role && "bg-accent text-accent-foreground rounded-md",
)}
>
{label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<Button
variant="ghost"
size="icon"
className="relative h-9 w-9 text-muted-foreground hover:text-foreground"
asChild
>
<Link href="/notifications">
<Bell className="h-4 w-4" />
{unreadCount > 0 && (
<Badge className="absolute -top-1 -right-1 h-4 min-w-4 px-1 flex items-center justify-center text-[10px]">
{unreadCount}
</Badge>
)}
</Link>
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="rounded-full h-9 w-9 text-muted-foreground hover:text-foreground"
>
<Avatar className="h-7 w-7">
<AvatarImage src={user?.avatar} />
<AvatarFallback>{user?.nickname?.[0] ?? "?"}</AvatarFallback>
</Avatar>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuLabel>{user?.nickname ?? "未登录"}</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem asChild>
<Link href={profileHref}>
<User className="mr-2 h-4 w-4" />
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/orders">
<ShoppingBag className="mr-2 h-4 w-4" />
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/chat">
<MessageSquare className="mr-2 h-4 w-4" />
</Link>
</DropdownMenuItem>
<DropdownMenuItem asChild>
<Link href="/wallet">
<Wallet className="mr-2 h-4 w-4" />
</Link>
</DropdownMenuItem>
{canOpenDashboard && (
<DropdownMenuItem asChild>
<Link href="/dashboard">
<Gamepad2 className="mr-2 h-4 w-4" />
</Link>
</DropdownMenuItem>
)}
<DropdownMenuItem asChild>
<Link href="/settings">
<Settings className="mr-2 h-4 w-4" />
</Link>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleLogout}>
<LogOut className="mr-2 h-4 w-4" />
退
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>
) : (
<div className="hidden md:flex items-center gap-1">
<Button variant="ghost" className="text-muted-foreground" asChild>
<Link href="/login"></Link>
</Button>
<Button variant="ghost" className="text-muted-foreground" asChild>
<Link href="/register"></Link>
</Button>
</div>
)}
<Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
<SheetTrigger asChild>
<Button
variant="ghost"
size="icon"
className="md:hidden h-9 w-9 text-muted-foreground hover:text-foreground"
>
<Menu className="h-5 w-5" />
</Button>
</SheetTrigger>
<SheetContent side="right" className="w-72">
<SheetHeader>
<SheetTitle className="flex items-center gap-2">
<Gamepad2 className="h-5 w-5" />
</SheetTitle>
</SheetHeader>
<div className="mt-4 space-y-4">
{isAuthenticated && (
<div className="flex items-center gap-2 px-1">
<Avatar className="h-8 w-8">
<AvatarImage src={user?.avatar} />
<AvatarFallback>{user?.nickname?.[0] ?? "?"}</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{user?.nickname ?? "未登录"}</p>
<p className="text-xs text-muted-foreground">{roleLabels[currentRole]}</p>
</div>
</div>
)}
<nav className="flex flex-col gap-1">
{navLinks.map((link) => {
const isActive =
pathname === link.href ||
(link.href !== "/" && pathname.startsWith(link.href))
return (
<Button
key={link.href}
variant={isActive ? "secondary" : "ghost"}
className={cn("w-full justify-start", !isActive && "text-muted-foreground")}
asChild
>
<Link href={link.href} onClick={() => setMobileOpen(false)}>
{link.label}
</Link>
</Button>
)
})}
{isAuthenticated && (
<>
<Button
variant={pathname === "/wallet" ? "secondary" : "ghost"}
className={cn(
"w-full justify-start",
pathname !== "/wallet" && "text-muted-foreground",
)}
asChild
>
<Link href="/wallet" onClick={() => setMobileOpen(false)}>
</Link>
</Button>
<Button
variant={pathname === "/settings" ? "secondary" : "ghost"}
className={cn(
"w-full justify-start",
pathname !== "/settings" && "text-muted-foreground",
)}
asChild
>
<Link href="/settings" onClick={() => setMobileOpen(false)}>
</Link>
</Button>
</>
)}
</nav>
{isAuthenticated && (
<div className="border-t pt-4">
<p className="px-3 text-xs text-muted-foreground mb-2"></p>
<div className="flex gap-2 px-3">
{availableRoles.map(([role, label]) => (
<Button
key={role}
variant={currentRole === role ? "default" : "outline"}
size="sm"
className="text-xs flex-1"
onClick={() => handleRoleSwitch(role)}
>
{label}
</Button>
))}
</div>
</div>
)}
{!isAuthenticated && (
<div className="border-t pt-4 flex gap-2 px-3">
<Button variant="outline" className="flex-1" asChild>
<Link href="/login" onClick={() => setMobileOpen(false)}>
</Link>
</Button>
<Button className="flex-1" asChild>
<Link href="/register" onClick={() => setMobileOpen(false)}>
</Link>
</Button>
</div>
)}
</div>
</SheetContent>
</Sheet>
</div>
</div>
</header>
)
}