Files
goodgo-platform/apps/web/components/notifications/notification-bell.tsx
Ho Ngoc Hai ad8577e2bd
Some checks failed
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m5s
Deploy / Build API Image (push) Failing after 27s
Deploy / Build Web Image (push) Failing after 12s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 16s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 57s
Deploy / Deploy to Staging (push) Has been cancelled
Deploy / Rollback Staging (push) Has been cancelled
Deploy / Smoke Test Production (push) Has been cancelled
Deploy / Rollback Production (push) Has been cancelled
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 11s
Deploy / Smoke Test Staging (push) Has been cancelled
Deploy / Deploy to Production (push) Has been cancelled
Security Scanning / Trivy Scan — Web Image (push) Failing after 46s
Security Scanning / Trivy Filesystem Scan (push) Has been cancelled
Security Scanning / Security Gate (push) Has been cancelled
Security Scanning / Trivy Scan — AI Services Image (push) Has been cancelled
fix(web): stop flooding console with 401 ApiError during initial load
Five compounding problems caused hundreds of "Console ApiError:
Unauthorized" entries on every load of /dashboard (and friends) while
unauthenticated or while the auth cookie was stale:

1. QueryClient had `throwOnError: true` as a blanket default, so every
   401 from any react-query hook propagated to the nearest error
   boundary instead of staying in the query's `error` state. That
   also invited React to re-render and re-fire the boundary multiple
   times per failing query.

2. React Query retried all failures 3 times with exponential backoff,
   so a single 401 became four requests. 401 isn't fixable by retry,
   so this is just noise.

3. Dashboard layout rendered `<NotificationBell />` unconditionally,
   which polled /notifications/unread-count on mount even when no user
   was signed in → 401 on every mount.

4. Dashboard + Admin layouts had no redirect-to-login guard, so
   protected queries (market-report, heatmap, admin/dashboard, …) all
   mounted and fired against the API before the user ever saw the
   login screen.

5. Admin layout waited on `user` but had no way to distinguish "store
   still initialising" from "user genuinely absent" — so an expired
   cookie left the page stuck on a spinner while the same 401 storm
   played out in the background.

Fixes
- query-client.ts: `throwOnError` and `retry` are now predicates. Only
  5xx / network errors bubble to boundaries and are retried; 4xx
  (auth, validation, not-found) stay in query error state so the
  component can render an empty/auth placeholder.
- auth-store.ts: new `isInitialized` flag set in a finally block at
  the end of `initialize()`. Downstream guards use it to distinguish
  "still booting" from "definitely logged out".
- (dashboard)/layout.tsx: redirects to /login?next=<path> once
  initialised and unauthenticated, and renders a lightweight loading
  screen in the meantime so child queries never mount.
- (admin)/layout.tsx: same guard. Non-ADMIN logged-in users still
  bounce to /dashboard.
- notification-bell.tsx: short-circuits `fetchUnreadCount` when
  `isAuthenticated` is false.

Verified in dev: visiting /vi/dashboard unauthenticated now redirects
to /login?redirect=/dashboard with zero console errors and no
/analytics/… calls to the backend.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 09:41:35 +07:00

193 lines
6.4 KiB
TypeScript

'use client';
import { Bell } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { useAuthStore } from '@/lib/auth-store';
import type { NotificationDto } from '@/lib/notifications-api';
import { useNotificationsStore } from '@/lib/notifications-store';
import { cn } from '@/lib/utils';
export function NotificationBell() {
const {
notifications,
unreadCount,
isOpen,
isLoading,
setOpen,
markAsRead,
markAllAsRead,
fetchUnreadCount,
} = useNotificationsStore();
const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
const router = useRouter();
const dropdownRef = useRef<HTMLDivElement>(null);
// Fetch unread count only when the user is actually signed in — otherwise
// the request returns 401 and floods the dev console with ApiError.
useEffect(() => {
if (!isAuthenticated) return;
fetchUnreadCount();
}, [fetchUnreadCount, isAuthenticated]);
// Close on click outside
useEffect(() => {
if (!isOpen) return;
const handleClick = (e: MouseEvent) => {
if (
dropdownRef.current &&
!dropdownRef.current.contains(e.target as Node)
) {
setOpen(false);
}
};
document.addEventListener('mousedown', handleClick);
return () => document.removeEventListener('mousedown', handleClick);
}, [isOpen, setOpen]);
const handleNotificationClick = async (notification: NotificationDto) => {
if (!notification.isRead) {
await markAsRead(notification.id);
}
if (notification.link) {
router.push(notification.link);
}
setOpen(false);
};
return (
<div className="relative" ref={dropdownRef}>
<Button
variant="ghost"
size="sm"
className="relative h-9 w-9 p-0"
aria-label={`Thông báo${unreadCount > 0 ? ` (${unreadCount} chưa đọc)` : ''}`}
aria-expanded={isOpen}
aria-haspopup="true"
onClick={() => setOpen(!isOpen)}
>
<Bell className="h-4 w-4" aria-hidden="true" />
{unreadCount > 0 && (
<span
className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground"
aria-hidden="true"
>
{unreadCount > 99 ? '99+' : unreadCount}
</span>
)}
</Button>
{isOpen && (
<div
role="menu"
className="absolute right-0 top-full z-50 mt-2 w-80 overflow-hidden rounded-lg border bg-popover shadow-lg"
>
{/* Header */}
<div className="flex items-center justify-between border-b px-4 py-3">
<h3 className="text-sm font-semibold">Thông báo</h3>
{unreadCount > 0 && (
<button
className="text-xs text-primary hover:underline"
onClick={markAllAsRead}
>
Đánh dấu tất cả đã đc
</button>
)}
</div>
{/* List */}
<div className="max-h-80 overflow-y-auto">
{isLoading ? (
<div className="flex items-center justify-center py-8">
<svg
className="h-5 w-5 animate-spin text-muted-foreground"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
/>
</svg>
</div>
) : notifications.length === 0 ? (
<div className="py-8 text-center text-sm text-muted-foreground">
Chưa thông báo
</div>
) : (
notifications.map((notification) => (
<button
key={notification.id}
role="menuitem"
className={cn(
'flex w-full flex-col gap-0.5 border-b px-4 py-3 text-left transition-colors hover:bg-accent last:border-b-0',
!notification.isRead && 'bg-primary/5',
)}
onClick={() => handleNotificationClick(notification)}
>
<div className="flex items-start gap-2">
{!notification.isRead && (
<span className="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-primary" />
)}
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium">
{notification.title}
</p>
<p className="line-clamp-2 text-xs text-muted-foreground">
{notification.body}
</p>
<p className="mt-1 text-[10px] text-muted-foreground">
{formatTimeAgo(notification.createdAt)}
</p>
</div>
</div>
</button>
))
)}
</div>
{/* Footer */}
{notifications.length > 0 && (
<div className="border-t px-4 py-2 text-center">
<button
className="text-xs font-medium text-primary hover:underline"
onClick={() => {
router.push('/notifications');
setOpen(false);
}}
>
Xem tất cả
</button>
</div>
)}
</div>
)}
</div>
);
}
function formatTimeAgo(dateStr: string): string {
const now = Date.now();
const date = new Date(dateStr).getTime();
const diffMs = now - date;
const diffMin = Math.floor(diffMs / 60000);
if (diffMin < 1) return 'Vừa xong';
if (diffMin < 60) return `${diffMin} phút trước`;
const diffHours = Math.floor(diffMin / 60);
if (diffHours < 24) return `${diffHours} giờ trước`;
const diffDays = Math.floor(diffHours / 24);
if (diffDays < 7) return `${diffDays} ngày trước`;
return new Date(dateStr).toLocaleDateString('vi-VN');
}