feat(notifications): in-app bell with real-time badge and per-recipient messages

Schema (migration: 20260516104351_notification_isread_link):
- Notification.isRead Boolean @default(false) — tracks unread state
- Notification.link String? — deep-link URL for each notification

lib/notifier.ts:
- buildInAppBody(): per-recipient message text, context-aware
  e.g. managers see "Maria Santos submitted PO-2024-12345 for your review"
       submitters see "Your PO-2024-12345 has been approved"
       accounts see "PO-2024-12345 approved — ready for payment"
- buildInAppLink(): routes to the correct page per recipient role
  (submitter → /po/[id] or /po/[id]/receipt; manager → /approvals/[id];
   accounts → /payments; etc.)
- Notifications written with both body and link on every event

API:
- GET /api/notifications — returns { unreadCount, notifications[] } for
  the session user; last 20 ordered by sentAt desc
- PATCH /api/notifications/read — marks all (or specific ids) as read

NotificationBell (components/layout/notification-bell.tsx):
- Bell icon in header with red unread count badge
- Polls /api/notifications every 30 seconds
- When unread count increases vs previous tick: bounces the bell icon
  and pulses the badge for 3 seconds to signal a new arrival
- Click opens dropdown panel:
  - Unread items highlighted with blue-dot indicator and bolder text
  - Each item is a Link to the notification's deep-link URL
  - "Mark all read" button in panel header
  - Auto-marks all as read when panel opens (optimistic update + API call)
  - Closes on outside click
  - "Showing 20 most recent" footer when list is at limit

Header: receives initialUnreadCount and initialNotifications as props
Portal layout: fetches initial notification data server-side to avoid
a loading flash on first render; dates serialised to ISO strings

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Hardik 2026-05-16 16:16:06 +05:30
parent 3556b1425f
commit f0b49c4b96
8 changed files with 389 additions and 9 deletions

View file

@ -1,4 +1,5 @@
import { auth } from "@/auth"; import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { Sidebar } from "@/components/layout/sidebar"; import { Sidebar } from "@/components/layout/sidebar";
import { Header } from "@/components/layout/header"; import { Header } from "@/components/layout/header";
@ -11,11 +12,33 @@ export default async function PortalLayout({
const session = await auth(); const session = await auth();
if (!session?.user) redirect("/login"); if (!session?.user) redirect("/login");
const [notifications, unreadCount] = await Promise.all([
db.notification.findMany({
where: { userId: session.user.id },
orderBy: { sentAt: "desc" },
take: 20,
select: { id: true, body: true, link: true, isRead: true, sentAt: true, poId: true },
}),
db.notification.count({
where: { userId: session.user.id, isRead: false },
}),
]);
// Dates must be serialised before being passed to Client Components
const serialisedNotifications = notifications.map((n) => ({
...n,
sentAt: n.sentAt.toISOString(),
}));
return ( return (
<div className="flex h-screen overflow-hidden bg-neutral-50"> <div className="flex h-screen overflow-hidden bg-neutral-50">
<Sidebar userRole={session.user.role} /> <Sidebar userRole={session.user.role} />
<div className="flex flex-1 flex-col overflow-hidden"> <div className="flex flex-1 flex-col overflow-hidden">
<Header user={session.user} /> <Header
user={session.user}
initialUnreadCount={unreadCount}
initialNotifications={serialisedNotifications}
/>
<main className="flex-1 overflow-y-auto p-6">{children}</main> <main className="flex-1 overflow-y-auto p-6">{children}</main>
</div> </div>
</div> </div>

View file

@ -0,0 +1,32 @@
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { NextRequest, NextResponse } from "next/server";
// PATCH /api/notifications/read
// Body: { ids?: string[] } — if omitted, mark all unread as read
export async function PATCH(request: NextRequest) {
const session = await auth();
if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let ids: string[] | undefined;
try {
const body = await request.json();
ids = body.ids;
} catch {
// no body — mark all
}
if (ids && ids.length > 0) {
await db.notification.updateMany({
where: { id: { in: ids }, userId: session.user.id },
data: { isRead: true },
});
} else {
await db.notification.updateMany({
where: { userId: session.user.id, isRead: false },
data: { isRead: true },
});
}
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,29 @@
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { NextResponse } from "next/server";
export async function GET() {
const session = await auth();
if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const [notifications, unreadCount] = await Promise.all([
db.notification.findMany({
where: { userId: session.user.id },
orderBy: { sentAt: "desc" },
take: 20,
select: {
id: true,
body: true,
link: true,
isRead: true,
sentAt: true,
poId: true,
},
}),
db.notification.count({
where: { userId: session.user.id, isRead: false },
}),
]);
return NextResponse.json({ notifications, unreadCount });
}

View file

@ -4,6 +4,7 @@ import { signOut } from "next-auth/react";
import { LogOut } from "lucide-react"; import { LogOut } from "lucide-react";
import type { Role } from "@prisma/client"; import type { Role } from "@prisma/client";
import { CartIcon } from "./cart-icon"; import { CartIcon } from "./cart-icon";
import { NotificationBell } from "./notification-bell";
const ROLE_LABELS: Record<Role, string> = { const ROLE_LABELS: Record<Role, string> = {
TECHNICAL: "Technical", TECHNICAL: "Technical",
@ -17,16 +18,31 @@ const ROLE_LABELS: Record<Role, string> = {
const CART_ROLES: Role[] = ["TECHNICAL", "MANNING", "SUPERUSER", "MANAGER"]; const CART_ROLES: Role[] = ["TECHNICAL", "MANNING", "SUPERUSER", "MANAGER"];
interface HeaderProps { interface NotificationItem {
user: { name: string; email: string; role: Role }; id: string;
body: string;
link: string | null;
isRead: boolean;
sentAt: string;
poId: string | null;
} }
export function Header({ user }: HeaderProps) { interface HeaderProps {
user: { name: string; email: string; role: Role };
initialUnreadCount: number;
initialNotifications: NotificationItem[];
}
export function Header({ user, initialUnreadCount, initialNotifications }: HeaderProps) {
return ( return (
<header className="flex h-16 items-center justify-between border-b border-neutral-200 bg-white px-6"> <header className="flex h-16 items-center justify-between border-b border-neutral-200 bg-white px-6">
<div /> <div />
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{CART_ROLES.includes(user.role) && <CartIcon />} {CART_ROLES.includes(user.role) && <CartIcon />}
<NotificationBell
initialUnreadCount={initialUnreadCount}
initialNotifications={initialNotifications}
/>
<div className="text-right ml-2"> <div className="text-right ml-2">
<p className="text-sm font-medium text-neutral-900">{user.name}</p> <p className="text-sm font-medium text-neutral-900">{user.name}</p>
<p className="text-xs text-neutral-500">{ROLE_LABELS[user.role]}</p> <p className="text-xs text-neutral-500">{ROLE_LABELS[user.role]}</p>

View file

@ -0,0 +1,191 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Bell } from "lucide-react";
interface NotificationItem {
id: string;
body: string;
link: string | null;
isRead: boolean;
sentAt: string;
poId: string | null;
}
interface Props {
initialUnreadCount: number;
initialNotifications: NotificationItem[];
}
function timeAgo(dateStr: string): string {
const diff = Date.now() - new Date(dateStr).getTime();
const mins = Math.floor(diff / 60_000);
if (mins < 1) return "just now";
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
return `${Math.floor(hrs / 24)}d ago`;
}
export function NotificationBell({ initialUnreadCount, initialNotifications }: Props) {
const [open, setOpen] = useState(false);
const [unreadCount, setUnreadCount] = useState(initialUnreadCount);
const [notifications, setNotifications] = useState<NotificationItem[]>(initialNotifications);
const [newArrival, setNewArrival] = useState(false);
const prevCountRef = useRef(initialUnreadCount);
const panelRef = useRef<HTMLDivElement>(null);
// ── Poll for new notifications every 30 s ───────────────────────────────────
const fetchNotifications = useCallback(async () => {
try {
const res = await fetch("/api/notifications", { cache: "no-store" });
if (!res.ok) return;
const data: { unreadCount: number; notifications: NotificationItem[] } = await res.json();
setNotifications(data.notifications);
if (data.unreadCount > prevCountRef.current) {
// New notification arrived — flash the bell
setNewArrival(true);
setTimeout(() => setNewArrival(false), 3000);
}
prevCountRef.current = data.unreadCount;
setUnreadCount(data.unreadCount);
} catch {
// network error — silently ignore
}
}, []);
useEffect(() => {
const id = setInterval(fetchNotifications, 30_000);
return () => clearInterval(id);
}, [fetchNotifications]);
// ── Close on outside click ──────────────────────────────────────────────────
useEffect(() => {
function handleClick(e: MouseEvent) {
if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
// ── Mark all read when panel opens ─────────────────────────────────────────
async function handleOpen() {
const next = !open;
setOpen(next);
if (next && unreadCount > 0) {
setUnreadCount(0);
prevCountRef.current = 0;
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
await fetch("/api/notifications/read", { method: "PATCH" });
}
}
return (
<div ref={panelRef} className="relative">
{/* Bell button */}
<button
onClick={handleOpen}
className={`relative flex items-center justify-center rounded-lg p-2 transition-colors ${
open
? "bg-neutral-100 text-neutral-700"
: "text-neutral-500 hover:bg-neutral-100 hover:text-neutral-700"
}`}
title="Notifications"
aria-label={`Notifications${unreadCount > 0 ? ` (${unreadCount} unread)` : ""}`}
>
<Bell
className={`h-5 w-5 transition-transform ${newArrival ? "animate-bounce" : ""}`}
/>
{unreadCount > 0 && (
<span
className={`absolute -top-0.5 -right-0.5 flex h-4.5 min-w-[18px] items-center justify-center rounded-full bg-danger px-1 text-[10px] font-bold leading-none text-white ${
newArrival ? "animate-pulse" : ""
}`}
>
{unreadCount > 99 ? "99+" : unreadCount}
</span>
)}
</button>
{/* Dropdown panel */}
{open && (
<div className="absolute right-0 top-full mt-2 w-96 rounded-xl border border-neutral-200 bg-white shadow-xl z-50 overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between border-b border-neutral-100 px-4 py-3">
<h3 className="text-sm font-semibold text-neutral-900">Notifications</h3>
{notifications.length > 0 && (
<button
onClick={async () => {
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
setUnreadCount(0);
prevCountRef.current = 0;
await fetch("/api/notifications/read", { method: "PATCH" });
}}
className="text-xs text-primary-600 hover:text-primary-700 font-medium"
>
Mark all read
</button>
)}
</div>
{/* List */}
<div className="max-h-[480px] overflow-y-auto divide-y divide-neutral-50">
{notifications.length === 0 ? (
<div className="px-4 py-10 text-center text-sm text-neutral-400">
No notifications yet
</div>
) : (
notifications.map((n) => {
const content = (
<div
className={`flex items-start gap-3 px-4 py-3.5 transition-colors hover:bg-neutral-50 ${
!n.isRead ? "bg-primary-50/40" : ""
}`}
>
{/* Unread dot */}
<span
className={`mt-1.5 h-2 w-2 shrink-0 rounded-full transition-colors ${
!n.isRead ? "bg-primary-500" : "bg-transparent"
}`}
/>
<div className="flex-1 min-w-0">
<p className={`text-sm leading-snug ${!n.isRead ? "font-medium text-neutral-900" : "text-neutral-700"}`}>
{n.body}
</p>
<p className="text-xs text-neutral-400 mt-0.5">{timeAgo(n.sentAt)}</p>
</div>
</div>
);
return n.link ? (
<Link
key={n.id}
href={n.link}
onClick={() => setOpen(false)}
className="block"
>
{content}
</Link>
) : (
<div key={n.id}>{content}</div>
);
})
)}
</div>
{/* Footer */}
{notifications.length === 20 && (
<div className="border-t border-neutral-100 px-4 py-2 text-center">
<span className="text-xs text-neutral-400">Showing 20 most recent</span>
</div>
)}
</div>
)}
</div>
);
}

View file

@ -31,10 +31,13 @@ export async function notify({ event, po, recipients, note }: NotifyParams) {
await Promise.allSettled( await Promise.allSettled(
recipients.map(async (recipient) => { recipients.map(async (recipient) => {
const body = buildInAppBody(event, po, recipient);
const link = buildInAppLink(event, po, recipient);
let status = "sent"; let status = "sent";
if (isDev) { if (isDev) {
console.log( console.log(
`\n📧 [DEV EMAIL] To: ${recipient.email}\n Subject: ${subject}\n Body: ${buildBody(event, po, note)}\n` `\n📧 [DEV EMAIL] To: ${recipient.email}\n Subject: ${subject}\n Body: ${buildEmailBody(event, po, note)}\n`
); );
} else { } else {
try { try {
@ -49,13 +52,92 @@ export async function notify({ event, po, recipients, note }: NotifyParams) {
status = "failed"; status = "failed";
} }
} }
await db.notification.create({ await db.notification.create({
data: { subject, body: subject, status, poId: po.id, userId: recipient.id }, data: { subject, body, link, status, poId: po.id, userId: recipient.id },
}); });
}) })
); );
} }
// ── In-app message ────────────────────────────────────────────────────────────
function buildInAppBody(
event: NotificationEvent,
po: PurchaseOrder & { submitter: User },
recipient: User
): string {
const pn = po.poNumber;
const submitter = po.submitter.name;
switch (event) {
case "PO_SUBMITTED":
// Manager sees who submitted; submitter gets a confirmation
return recipient.id === po.submitterId
? `Your PO ${pn} has been submitted for review`
: `${submitter} submitted PO ${pn} for your review`;
case "PO_APPROVED":
case "PO_APPROVED_WITH_NOTE":
return recipient.id === po.submitterId
? `Your PO ${pn} has been approved`
: `PO ${pn} approved — ready for payment`;
case "PO_REJECTED":
return `Your PO ${pn} has been rejected`;
case "EDITS_REQUESTED":
return `Edits requested on your PO ${pn}`;
case "VENDOR_ID_REQUESTED":
return `Vendor ID needed before PO ${pn} can be approved`;
case "VENDOR_ID_PROVIDED":
return `Vendor ID provided for PO ${pn} — ready to review`;
case "PAYMENT_PROCESSING":
return `Payment is being processed for PO ${pn}`;
case "PAYMENT_SENT":
return `Payment confirmed for PO ${pn} — please confirm receipt`;
case "RECEIPT_CONFIRMED":
return `Receipt confirmed — PO ${pn} is now closed`;
default:
return `Update on PO ${pn}`;
}
}
function buildInAppLink(
event: NotificationEvent,
po: PurchaseOrder & { submitter: User },
recipient: User
): string {
switch (event) {
case "PO_SUBMITTED":
return recipient.id === po.submitterId ? `/po/${po.id}` : `/approvals/${po.id}`;
case "PO_APPROVED":
case "PO_APPROVED_WITH_NOTE":
return recipient.id === po.submitterId ? `/po/${po.id}` : `/payments`;
case "PO_REJECTED":
case "EDITS_REQUESTED":
case "VENDOR_ID_REQUESTED":
return `/po/${po.id}`;
case "VENDOR_ID_PROVIDED":
return `/approvals/${po.id}`;
case "PAYMENT_PROCESSING":
case "RECEIPT_CONFIRMED":
return `/po/${po.id}`;
case "PAYMENT_SENT":
return `/po/${po.id}/receipt`;
default:
return `/po/${po.id}`;
}
}
// ── Email subject ─────────────────────────────────────────────────────────────
function buildSubject(event: NotificationEvent, poNumber: string): string | null { function buildSubject(event: NotificationEvent, poNumber: string): string | null {
const base = `PO ${poNumber}`; const base = `PO ${poNumber}`;
const map: Record<NotificationEvent, string> = { const map: Record<NotificationEvent, string> = {
@ -73,6 +155,8 @@ function buildSubject(event: NotificationEvent, poNumber: string): string | null
return map[event] ?? null; return map[event] ?? null;
} }
// ── Email HTML ────────────────────────────────────────────────────────────────
function buildHtml( function buildHtml(
event: NotificationEvent, event: NotificationEvent,
po: PurchaseOrder & { submitter: User }, po: PurchaseOrder & { submitter: User },
@ -87,7 +171,7 @@ function buildHtml(
<span style="font-size:20px;font-weight:700;color:#1d4ed8;">Pelagia Portal</span> <span style="font-size:20px;font-weight:700;color:#1d4ed8;">Pelagia Portal</span>
</div> </div>
<p style="margin:0 0 16px;">Hi ${recipient.name},</p> <p style="margin:0 0 16px;">Hi ${recipient.name},</p>
<p style="margin:0 0 24px;">${buildBody(event, po, note)}</p> <p style="margin:0 0 24px;">${buildEmailBody(event, po, note)}</p>
<div style="background:#f3f4f6;border-radius:8px;padding:16px;font-size:13px;color:#374151;"> <div style="background:#f3f4f6;border-radius:8px;padding:16px;font-size:13px;color:#374151;">
<strong>PO Number:</strong> ${po.poNumber}<br/> <strong>PO Number:</strong> ${po.poNumber}<br/>
<strong>Title:</strong> ${po.title}<br/> <strong>Title:</strong> ${po.title}<br/>
@ -100,7 +184,7 @@ function buildHtml(
</html>`; </html>`;
} }
function buildBody( function buildEmailBody(
event: NotificationEvent, event: NotificationEvent,
po: PurchaseOrder & { submitter: User }, po: PurchaseOrder & { submitter: User },
note?: string note?: string
@ -120,7 +204,7 @@ function buildBody(
case "EDITS_REQUESTED": case "EDITS_REQUESTED":
return `Edits have been requested on <strong>${po.poNumber}</strong>. Please update the order and resubmit.${noteHtml}`; return `Edits have been requested on <strong>${po.poNumber}</strong>. Please update the order and resubmit.${noteHtml}`;
case "VENDOR_ID_REQUESTED": case "VENDOR_ID_REQUESTED":
return `A vendor ID is required before <strong>${po.poNumber}</strong> can be approved. Please update the PO with the correct vendor details.`; return `A vendor ID is required before <strong>${po.poNumber}</strong> can be approved.`;
case "VENDOR_ID_PROVIDED": case "VENDOR_ID_PROVIDED":
return `The vendor ID has been provided for <strong>${po.poNumber}</strong>. It is ready for your review.`; return `The vendor ID has been provided for <strong>${po.poNumber}</strong>. It is ready for your review.`;
case "PAYMENT_PROCESSING": case "PAYMENT_PROCESSING":

View file

@ -0,0 +1,3 @@
-- AlterTable
ALTER TABLE "Notification" ADD COLUMN "isRead" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "link" TEXT;

View file

@ -327,6 +327,8 @@ model Notification {
id String @id @default(cuid()) id String @id @default(cuid())
subject String subject String
body String body String
link String?
isRead Boolean @default(false)
sentAt DateTime @default(now()) sentAt DateTime @default(now())
status String @default("sent") status String @default("sent")