Files
pn-new-crm/src/components/layout/inbox.tsx

263 lines
10 KiB
TypeScript
Raw Normal View History

'use client';
/**
* Unified Inbox - merges the previous AlertBell + NotificationBell into
* a single bell with two tabs:
*
* System - port-wide operational alerts (system-generated, all
* users with `view_alerts` see the same list). Sourced from
* `useAlertList('open')` + `useAlertCount()`.
*
* Personal - per-user notifications (you signed something, someone
* @-mentioned you, your reminder fired, etc.). Sourced from
* `useNotifications` + the /api/v1/notifications endpoint.
*
* The bell icon shows a single combined unread count. The popover opens
* to whichever tab has unread items first; ties Personal.
*
* Replaces the topbar's `<AlertBell />` + `<NotificationBell />`. The two
* old components stay in the tree (untouched) so anything that imports
* them directly (tests, deep-link pages) keeps working - they're simply
* no longer mounted in the topbar.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Bell, ShieldAlert, Inbox as InboxIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { apiFetch } from '@/lib/api/client';
import { useUIStore } from '@/stores/ui-store';
import { cn } from '@/lib/utils';
import { useNotifications } from '@/hooks/use-notifications';
import { NotificationItem } from '@/components/notifications/notification-item';
import { AlertCard, AlertCardEmpty } from '@/components/alerts/alert-card';
import { useAlertCount, useAlertList, useAlertRealtime } from '@/components/alerts/use-alerts';
interface NotificationListResponse {
data: Array<{
id: string;
type: string;
title: string;
description: string | null;
link: string | null;
isRead: boolean;
createdAt: Date;
}>;
total: number;
}
type TabKey = 'personal' | 'system';
export function Inbox() {
const portSlug = useUIStore((s) => s.currentPortSlug);
const [open, setOpen] = useState(false);
// ── System (alerts) ──
const { data: alertCount } = useAlertCount();
const { data: alertList, isLoading: alertsLoading } = useAlertList('open', open);
useAlertRealtime();
const systemTotal = alertCount?.total ?? 0;
const systemCritical = alertCount?.bySeverity.critical ?? 0;
const systemAlerts = alertList?.data ?? [];
const systemTop = systemAlerts.slice(0, 8);
// ── Personal (notifications) ──
const { unreadCount: personalUnread } = useNotifications();
const queryClient = useQueryClient();
const { data: notifData, isLoading: notifLoading } = useQuery<NotificationListResponse>({
queryKey: ['notifications', 'list'],
queryFn: () => apiFetch('/api/v1/notifications?limit=20'),
staleTime: 30_000,
// Only fetch the list when the popover opens - count stays live in the
// background via useNotifications' realtime hook.
enabled: open,
});
const notifications = notifData?.data ?? [];
const markRead = useMutation({
mutationFn: (id: string) => apiFetch(`/api/v1/notifications/${id}`, { method: 'PATCH' }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notifications'] }),
});
const markAllRead = useMutation({
mutationFn: () => apiFetch('/api/v1/notifications/read-all', { method: 'POST' }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['notifications'] }),
});
// ── Combined badge + initial tab ──
const combined = systemTotal + personalUnread;
const initialTab = useMemo<TabKey>(() => {
// Default to whichever side has unread items; tie → Personal (most users
// care about their own pings before system-wide rumblings).
if (systemTotal > 0 && personalUnread === 0) return 'system';
return 'personal';
}, [systemTotal, personalUnread]);
const [activeTab, setActiveTab] = useState<TabKey>(initialTab);
// Re-anchor to the unread side ONLY on the rising edge of `open` (i.e.
// when the popover actually opens). The previous version ran whenever
// `initialTab` changed too, which yanked the tab out from under the
// user any time a new socket event re-derived the initial tab while
// they were actively reading the other one.
const initialTabRef = useRef(initialTab);
fix(compiler): React Compiler safety triage — 5 categories cleared Cleared 4 rule buckets (37 violations, including 5 real bugs) and silenced 1 informational bucket from the Next 16 / react-hooks v7 upgrade. Cleared rules promoted from `warn` back to `error` so new regressions block CI. Real bug fixes: - `interest-contact-log-tab.tsx`: `useMemo` used for side effects (5 setState calls inside a memo body); converted to `useEffect`. - `PieChart.tsx`: cumulative `let angle` mutation in a render-phase `map`; converted to `reduce` so the slice array is built without re-assignment. - `documents-hub.tsx`: `useMemo(() => ({ count: 0 }))` used as a mutable drag counter; converted to `useRef`. - `notes-list.tsx`: `Date.now()` read during render for note-edit countdown (impure) → pinned to a `now` state ticked every 30s. - `onboarding-checklist.tsx` / `user-profile.tsx` / `user-settings.tsx`: `useEffect(() => void load(), [])` with the `load` function declared AFTER the effect — relied on hoisting, trips Compiler's "access before declared" rule. Declared inside the effect. Pattern fixes (intentional cache-via-ref → state or layout-effect): - 6 `ref.current = x` writes during render moved into layout effects (`use-realtime-invalidation`, `settings-form-card`, `inbox`). - 3 `ref.current` reads during render (search totals cache, scanner file ref) rewritten to backed-by-state. - `use-is-mobile.ts` rewritten on `useSyncExternalStore` to avoid the SSR-then-rehydrate setState dance. - `use-notifications.ts` rewritten to write socket pushes directly into the React Query cache via `setQueryData`, removing a local state mirror. Rule config (`eslint.config.mjs`): - `react-hooks/purity` → error (was warn, cleared) - `react-hooks/set-state-in-render` → error (was warn, cleared) - `react-hooks/immutability` → error (was warn, cleared) - `react-hooks/refs` → error (was warn, cleared) - `react-hooks/incompatible-library` → off (informational only) - `react-hooks/set-state-in-effect` → warn (51 remaining, all the useEffect→fetch→setState data-fetch pattern; migration to useQuery tracked in BACKLOG) Verified: tsc clean, eslint 0 errors / 69 warnings (down from 105), vitest 1315/1315, next build green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 23:14:16 +02:00
useEffect(() => {
initialTabRef.current = initialTab;
});
useEffect(() => {
if (open) setActiveTab(initialTabRef.current);
}, [open]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="relative"
aria-label={`Inbox${combined > 0 ? ` (${combined} unread)` : ''}`}
data-testid="inbox-bell"
>
<InboxIcon className="h-5 w-5" aria-hidden />
{combined > 0 ? (
<span
key={combined}
data-testid="inbox-bell-badge"
className={cn(
chore(audit-drain): rip out next-intl, RTL lint, sweeps, polish Drain the long-tail audit queue captured in alpha-uat-master.md. - next-intl ripped out (zero useTranslations callers ever existed): package.json, next.config.ts plugin wrap, src/i18n/, messages/, and the layout NextIntlClientProvider all gone; <html lang="en"> hardcoded. - RTL lint nudge added: warn-only no-restricted-syntax on physical Tailwind utilities (ml-/mr-/pl-/pr-/text-left/text-right/border-l/ border-r/rounded-l-/rounded-r-) inside JSX className literals. Existing ~1,000 sites grandfathered; new code trends toward logical. - Icon-only button accessibility lint: jsx-a11y/control-has-associated- label enabled at warn; 4 empty <th>/<td> action placeholders gain sr-only labels. - Currency: SUPPORTED_CURRENCIES drops the hardcoded English labels; new currencyLabel(code, locale?) helper resolves via Intl.DisplayNames. CurrencySelect + settings-manager migrated. - Date locale sweep: 7 surfaces flip from toLocaleString('en-GB'|'en-US') to toLocaleString(undefined, ...) so dates honour runtime locale. - Dialog/Sheet width: 10 document/EOI/entity-form dialogs gain a lg:max-w-4xl or lg:max-w-5xl step so wide desktops get breathing room. - PaymentsSection collapsed-bar: slim one-line bar showing "Payments - Not received yet" or "Payments - \$X received - N payments - Expand"; per-interest collapse state persists in localStorage; the RecordPayment flow auto-expands. - muted-foreground opacity sweep: 10 text-bearing text-muted-foreground/{60,70,80} hits dropped to plain text-muted-foreground for AA contrast on muted bg. Icon-only (aria-hidden) opacity hits left as-is. - Micro-type bump: text-[10px] and text-[11px] -> text-xs (12px) across 87 files in src/components + src/app. Pure mechanical sweep. - Audit-doc cleanup: alpha-uat-master.md stale 2026-05-25 summary rewritten with cumulative state through today. Items genuinely still open are now a short long-tail list. - New docs/marketing-site-followups.md: Umami Phase 4a/3/5, email pixel E2E verification, and website-cutover work parked here so they don't get lost in the CRM audit doc. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 18:48:46 +02:00
'absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-xs font-bold text-white shadow-sm ring-2 ring-background animate-badge-pop',
// Critical system alerts win the colour war - they need the
// most attention. Otherwise the brand gradient.
systemCritical > 0 ? 'bg-destructive' : 'bg-gradient-brand',
)}
>
{combined > 99 ? '99+' : combined}
</span>
) : null}
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-96 p-0">
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as TabKey)}>
<div className="flex items-center justify-between px-3 pt-3">
<TabsList className="h-8 grid grid-cols-2 w-full">
<TabsTrigger value="personal" className="text-xs gap-1.5">
<Bell className="h-3 w-3" aria-hidden />
Personal
{personalUnread > 0 ? (
chore(audit-drain): rip out next-intl, RTL lint, sweeps, polish Drain the long-tail audit queue captured in alpha-uat-master.md. - next-intl ripped out (zero useTranslations callers ever existed): package.json, next.config.ts plugin wrap, src/i18n/, messages/, and the layout NextIntlClientProvider all gone; <html lang="en"> hardcoded. - RTL lint nudge added: warn-only no-restricted-syntax on physical Tailwind utilities (ml-/mr-/pl-/pr-/text-left/text-right/border-l/ border-r/rounded-l-/rounded-r-) inside JSX className literals. Existing ~1,000 sites grandfathered; new code trends toward logical. - Icon-only button accessibility lint: jsx-a11y/control-has-associated- label enabled at warn; 4 empty <th>/<td> action placeholders gain sr-only labels. - Currency: SUPPORTED_CURRENCIES drops the hardcoded English labels; new currencyLabel(code, locale?) helper resolves via Intl.DisplayNames. CurrencySelect + settings-manager migrated. - Date locale sweep: 7 surfaces flip from toLocaleString('en-GB'|'en-US') to toLocaleString(undefined, ...) so dates honour runtime locale. - Dialog/Sheet width: 10 document/EOI/entity-form dialogs gain a lg:max-w-4xl or lg:max-w-5xl step so wide desktops get breathing room. - PaymentsSection collapsed-bar: slim one-line bar showing "Payments - Not received yet" or "Payments - \$X received - N payments - Expand"; per-interest collapse state persists in localStorage; the RecordPayment flow auto-expands. - muted-foreground opacity sweep: 10 text-bearing text-muted-foreground/{60,70,80} hits dropped to plain text-muted-foreground for AA contrast on muted bg. Icon-only (aria-hidden) opacity hits left as-is. - Micro-type bump: text-[10px] and text-[11px] -> text-xs (12px) across 87 files in src/components + src/app. Pure mechanical sweep. - Audit-doc cleanup: alpha-uat-master.md stale 2026-05-25 summary rewritten with cumulative state through today. Items genuinely still open are now a short long-tail list. - New docs/marketing-site-followups.md: Umami Phase 4a/3/5, email pixel E2E verification, and website-cutover work parked here so they don't get lost in the CRM audit doc. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 18:48:46 +02:00
<span className="ml-1 rounded-full bg-brand/15 px-1.5 text-xs font-semibold text-brand">
{personalUnread > 99 ? '99+' : personalUnread}
</span>
) : null}
</TabsTrigger>
<TabsTrigger value="system" className="text-xs gap-1.5">
<ShieldAlert className="h-3 w-3" aria-hidden />
System
{systemTotal > 0 ? (
<span
className={cn(
chore(audit-drain): rip out next-intl, RTL lint, sweeps, polish Drain the long-tail audit queue captured in alpha-uat-master.md. - next-intl ripped out (zero useTranslations callers ever existed): package.json, next.config.ts plugin wrap, src/i18n/, messages/, and the layout NextIntlClientProvider all gone; <html lang="en"> hardcoded. - RTL lint nudge added: warn-only no-restricted-syntax on physical Tailwind utilities (ml-/mr-/pl-/pr-/text-left/text-right/border-l/ border-r/rounded-l-/rounded-r-) inside JSX className literals. Existing ~1,000 sites grandfathered; new code trends toward logical. - Icon-only button accessibility lint: jsx-a11y/control-has-associated- label enabled at warn; 4 empty <th>/<td> action placeholders gain sr-only labels. - Currency: SUPPORTED_CURRENCIES drops the hardcoded English labels; new currencyLabel(code, locale?) helper resolves via Intl.DisplayNames. CurrencySelect + settings-manager migrated. - Date locale sweep: 7 surfaces flip from toLocaleString('en-GB'|'en-US') to toLocaleString(undefined, ...) so dates honour runtime locale. - Dialog/Sheet width: 10 document/EOI/entity-form dialogs gain a lg:max-w-4xl or lg:max-w-5xl step so wide desktops get breathing room. - PaymentsSection collapsed-bar: slim one-line bar showing "Payments - Not received yet" or "Payments - \$X received - N payments - Expand"; per-interest collapse state persists in localStorage; the RecordPayment flow auto-expands. - muted-foreground opacity sweep: 10 text-bearing text-muted-foreground/{60,70,80} hits dropped to plain text-muted-foreground for AA contrast on muted bg. Icon-only (aria-hidden) opacity hits left as-is. - Micro-type bump: text-[10px] and text-[11px] -> text-xs (12px) across 87 files in src/components + src/app. Pure mechanical sweep. - Audit-doc cleanup: alpha-uat-master.md stale 2026-05-25 summary rewritten with cumulative state through today. Items genuinely still open are now a short long-tail list. - New docs/marketing-site-followups.md: Umami Phase 4a/3/5, email pixel E2E verification, and website-cutover work parked here so they don't get lost in the CRM audit doc. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 18:48:46 +02:00
'ml-1 rounded-full px-1.5 text-xs font-semibold',
systemCritical > 0
? 'bg-destructive/15 text-destructive'
: 'bg-amber-500/15 text-amber-600',
)}
>
{systemTotal > 99 ? '99+' : systemTotal}
</span>
) : null}
</TabsTrigger>
</TabsList>
</div>
{/* ── Personal tab ── */}
<TabsContent value="personal" className="m-0">
<div className="flex items-center justify-between px-4 py-2">
<h4 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Your notifications
</h4>
{personalUnread > 0 ? (
<Button
variant="ghost"
size="sm"
className="h-auto p-0 text-xs text-muted-foreground hover:text-foreground"
onClick={() => markAllRead.mutate()}
disabled={markAllRead.isPending}
>
Mark all read
</Button>
) : (
<Link
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
href={(portSlug ? `/${portSlug}/notifications` : '/notifications') as any}
className="text-xs text-muted-foreground hover:text-foreground"
>
View all
</Link>
)}
</div>
<Separator />
<ScrollArea className="max-h-[400px]">
{notifLoading ? (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
Loading
</div>
) : notifications.length === 0 ? (
<div className="flex flex-col items-center justify-center py-10 text-sm text-muted-foreground">
<Bell className="mb-2 h-8 w-8 opacity-30" aria-hidden />
No notifications
</div>
) : (
<div className="divide-y">
{notifications.map((n) => (
<NotificationItem
key={n.id}
notification={n}
onMarkRead={(id) => markRead.mutate(id)}
/>
))}
</div>
)}
</ScrollArea>
</TabsContent>
{/* ── System tab ── */}
<TabsContent value="system" className="m-0">
<div className="flex items-center justify-between px-4 py-2">
<h4 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
Active alerts
</h4>
<Link
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
href={portSlug ? (`/${portSlug}/alerts` as any) : ('/alerts' as any)}
className="text-xs text-muted-foreground hover:text-foreground"
>
View all
</Link>
</div>
<Separator />
<ScrollArea className="max-h-[400px]">
{alertsLoading ? (
<div className="px-4 py-8 text-center text-sm text-muted-foreground">Loading</div>
) : systemTop.length === 0 ? (
<div className="p-3">
<AlertCardEmpty />
</div>
) : (
<div className="space-y-2 p-3">
{systemTop.map((a) => (
<AlertCard key={a.id} alert={a} />
))}
</div>
)}
</ScrollArea>
</TabsContent>
</Tabs>
</PopoverContent>
</Popover>
);
}