feat(notifications): scope notification read state per recipient
Read state is personal to the recipient. Marking a notification read now only ever flips the acting user's own rows — never another user's, even when staff view it via read-all oversight (which would otherwise hide it from its real owner). - add /api/notifications/inbox endpoint that enriches each row with ownerId, ownerName, and isMine so the bell can label "meant for someone else" rows - move mark-read logic into per-user lib helpers (markNotificationsReadForUser, markAllNotificationsReadForUser) and have the actions delegate - surface ownership in the bell UI and skip marking rows that aren't mine
This commit is contained in:
parent
c019e642a3
commit
66e70d3d56
4 changed files with 228 additions and 78 deletions
|
|
@ -3,6 +3,11 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
|
||||
import {
|
||||
markAllNotificationsReadForUser,
|
||||
markNotificationsReadForUser,
|
||||
} from "@/lib/notifications";
|
||||
|
||||
export interface NotificationActionResult {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
|
|
@ -18,29 +23,9 @@ export async function markNotificationsRead(ids: number[]): Promise<Notification
|
|||
|
||||
if (!user) return { success: false, error: "You must be logged in." };
|
||||
|
||||
const cleanIds = [...new Set(ids.filter((id) => Number.isFinite(id) && id > 0))];
|
||||
if (cleanIds.length === 0) return { success: true };
|
||||
|
||||
// Query with access control so users can only touch their own notifications.
|
||||
const found = await payload.find({
|
||||
collection: "user-notifications",
|
||||
where: { id: { in: cleanIds } },
|
||||
limit: Math.min(cleanIds.length, 100),
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
for (const doc of found.docs) {
|
||||
if (!doc.read) {
|
||||
await payload.update({
|
||||
collection: "user-notifications",
|
||||
id: doc.id,
|
||||
data: { read: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Read-state is personal to the recipient: this only ever flips the acting
|
||||
// user's own notifications, never another user's (staff oversight included).
|
||||
await markNotificationsReadForUser(payload, Number(user.id), ids);
|
||||
return { success: true };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update notifications." };
|
||||
|
|
@ -57,23 +42,8 @@ export async function markAllNotificationsRead(): Promise<NotificationActionResu
|
|||
|
||||
if (!user) return { success: false, error: "You must be logged in." };
|
||||
|
||||
const unread = await payload.find({
|
||||
collection: "user-notifications",
|
||||
where: { read: { equals: false } },
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
for (const doc of unread.docs) {
|
||||
await payload.update({
|
||||
collection: "user-notifications",
|
||||
id: doc.id,
|
||||
data: { read: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
}
|
||||
|
||||
// Only the acting user's own unread notifications are marked read.
|
||||
await markAllNotificationsReadForUser(payload, Number(user.id));
|
||||
return { success: true };
|
||||
} catch {
|
||||
return { success: false, error: "Failed to update notifications." };
|
||||
|
|
|
|||
72
src/app/api/notifications/inbox/route.ts
Normal file
72
src/app/api/notifications/inbox/route.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { NextRequest, NextResponse } from "next/server";
|
||||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
/**
|
||||
* GET /api/notifications/inbox
|
||||
*
|
||||
* Bell inbox for the current user. Mirrors the shape the REST endpoint
|
||||
* (/api/user-notifications) returns, but enriches every row with WHO it is
|
||||
* meant for (`ownerId` + `ownerName`) and whether it belongs to the caller
|
||||
* (`isMine`). Staff with read-all oversight see everyone's notifications, so
|
||||
* this is what lets the bell label "meant for someone else" rows. Read access
|
||||
* is still scoped by the collection's own access control (own notifications for
|
||||
* regular users, all for staff).
|
||||
*/
|
||||
interface NotificationRow {
|
||||
id: number;
|
||||
title: string;
|
||||
message: string | null;
|
||||
link: string | null;
|
||||
type: string | null;
|
||||
read: boolean;
|
||||
createdAt: string;
|
||||
ownerId: number;
|
||||
ownerName: string;
|
||||
isMine: boolean;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const payload = await getPayload({ config: await config });
|
||||
const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false });
|
||||
if (!isPayloadUser(user)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
|
||||
try {
|
||||
const userId = Number(user.id);
|
||||
const res = await payload.find({
|
||||
collection: "user-notifications",
|
||||
sort: "-createdAt",
|
||||
limit: 12,
|
||||
depth: 1,
|
||||
overrideAccess: false,
|
||||
user,
|
||||
});
|
||||
|
||||
const notifications = res.docs.map((doc) => {
|
||||
const owner = doc.user;
|
||||
const ownerId = typeof owner === "object" && owner !== null ? owner.id : (owner as number);
|
||||
const isMine = Number(ownerId) === userId;
|
||||
return {
|
||||
id: doc.id,
|
||||
title: doc.title,
|
||||
message: doc.message ?? null,
|
||||
link: doc.link ?? null,
|
||||
type: doc.type ?? null,
|
||||
read: Boolean(doc.read),
|
||||
createdAt: doc.createdAt,
|
||||
ownerId: Number(ownerId),
|
||||
ownerName: typeof owner === "object" && owner !== null ? (owner.username ?? "") : "",
|
||||
isMine,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json({ notifications });
|
||||
} catch (error) {
|
||||
console.error("notifications/inbox: failed to load", error);
|
||||
return NextResponse.json({ error: "Failed to load notifications." }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
|
@ -29,6 +29,14 @@ interface NotificationItem {
|
|||
link?: string | null;
|
||||
read: boolean;
|
||||
createdAt: string;
|
||||
/**
|
||||
* Whether this notification belongs to the current user. When false the
|
||||
* current user (staff with read-all) is viewing someone else's notification;
|
||||
* it can be shown and opened but its read-state must never be changed.
|
||||
*/
|
||||
isMine?: boolean;
|
||||
/** Display name of the user this notification is actually meant for. Only set when `!isMine`. */
|
||||
ownerName?: string | null;
|
||||
}
|
||||
|
||||
function timeAgo(iso: string): string {
|
||||
|
|
@ -58,12 +66,12 @@ export function NotificationsBell() {
|
|||
|
||||
const fetchNotifications = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/user-notifications?limit=12&sort=-createdAt", {
|
||||
const res = await fetch("/api/notifications/inbox?limit=12&sort=-createdAt", {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) throw new Error("Failed to fetch");
|
||||
const data = (await res.json()) as { docs?: NotificationItem[] };
|
||||
setNotifications(data.docs ?? []);
|
||||
const data = (await res.json()) as { notifications?: NotificationItem[] };
|
||||
setNotifications(data.notifications ?? []);
|
||||
setError(false);
|
||||
} catch {
|
||||
setError(true);
|
||||
|
|
@ -83,8 +91,11 @@ export function NotificationsBell() {
|
|||
};
|
||||
}, [fetchNotifications]);
|
||||
|
||||
// Read-state is personal to the recipient. Never let marking one change
|
||||
// another user's read flag — staff are viewing it as an oversight, not as
|
||||
// that user, so flipping it would hide the notification from them.
|
||||
async function handleMarkOne(item: NotificationItem) {
|
||||
if (item.read || marking) return;
|
||||
if (item.read || marking || item.isMine === false) return;
|
||||
setMarking(true);
|
||||
setActionError(null);
|
||||
try {
|
||||
|
|
@ -104,7 +115,9 @@ export function NotificationsBell() {
|
|||
}
|
||||
|
||||
async function handleItemClick(item: NotificationItem) {
|
||||
if (!item.read) await handleMarkOne(item);
|
||||
// Own notifications are marked read on open; others' are only opened, never
|
||||
// marked, so the real owner still sees them as unread.
|
||||
if (!item.read && item.isMine !== false) await handleMarkOne(item);
|
||||
if (item.link) {
|
||||
router.push(item.link);
|
||||
setOpen(false);
|
||||
|
|
@ -118,7 +131,11 @@ export function NotificationsBell() {
|
|||
try {
|
||||
const result = await markAllNotificationsRead();
|
||||
if (result.success) {
|
||||
setNotifications((prev) => prev.map((n) => (n.read ? n : { ...n, read: true })));
|
||||
// Only own rows are guaranteed to have been flipped, so only optimistic-
|
||||
// update those. Staff viewing others' rows must not see them flip to read.
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.isMine === false ? n : { ...n, read: true })),
|
||||
);
|
||||
} else {
|
||||
setActionError(result.error ?? "Failed to update notifications.");
|
||||
}
|
||||
|
|
@ -153,7 +170,7 @@ export function NotificationsBell() {
|
|||
<button
|
||||
onClick={() => void handleMarkAll()}
|
||||
disabled={marking}
|
||||
aria-label="Mark all notifications as read"
|
||||
aria-label="Mark all of my notifications as read"
|
||||
className="text-xs text-muted-foreground hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{marking ? "Marking..." : "Mark all read"}
|
||||
|
|
@ -179,25 +196,28 @@ export function NotificationsBell() {
|
|||
{actionError}
|
||||
</p>
|
||||
)}
|
||||
{notifications.map((item) => (
|
||||
<DropdownMenuItem
|
||||
key={item.id}
|
||||
className={cn(
|
||||
"flex flex-col items-start gap-1 py-2.5",
|
||||
!item.read && "bg-accent/50",
|
||||
)}
|
||||
disabled={marking}
|
||||
onClick={() => void handleItemClick(item)}
|
||||
>
|
||||
<span className="flex w-full items-center justify-between gap-2">
|
||||
<span className="min-w-0 truncate text-sm font-medium">
|
||||
{!item.read && (
|
||||
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
|
||||
)}
|
||||
{item.title}
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-1.5">
|
||||
{!item.read && (
|
||||
{notifications.map((item) => {
|
||||
const isUnread = !item.read;
|
||||
const isForeign = item.isMine === false;
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={item.id}
|
||||
className={cn(
|
||||
"flex flex-col items-start gap-1 py-2.5",
|
||||
isUnread && "bg-accent/50",
|
||||
isForeign && "opacity-80",
|
||||
)}
|
||||
disabled={marking}
|
||||
onClick={() => void handleItemClick(item)}
|
||||
>
|
||||
<span className="flex w-full items-center justify-between gap-2">
|
||||
<span className="min-w-0 truncate text-sm font-medium">
|
||||
{!isForeign && isUnread && (
|
||||
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
|
||||
)}
|
||||
{item.title}
|
||||
</span>
|
||||
{!isForeign && item.read && (
|
||||
<button
|
||||
type="button"
|
||||
title="Mark as read"
|
||||
|
|
@ -211,21 +231,28 @@ export function NotificationsBell() {
|
|||
<CheckIcon className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{timeAgo(item.createdAt)}
|
||||
<span className="flex shrink-0 items-center gap-1.5">
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{timeAgo(item.createdAt)}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
{item.message && (
|
||||
<span className="line-clamp-3 w-full text-xs text-muted-foreground">
|
||||
{item.message}
|
||||
{isForeign && item.ownerName && (
|
||||
<span className="text-[10px] font-medium text-amber-400/90">
|
||||
meant for {item.ownerName}
|
||||
</span>
|
||||
)}
|
||||
{item.message && (
|
||||
<span className="line-clamp-3 w-full text-xs text-muted-foreground">
|
||||
{item.message}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
{notificationLabel(item.type)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-[10px] text-muted-foreground/70">
|
||||
{notificationLabel(item.type)}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -52,6 +52,87 @@ export async function notifyUser(payload: PayloadType, input: NotifyInput): Prom
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the given notifications read, scoped so an actor can only change the
|
||||
* read-state of notifications that belong to THEM.
|
||||
*
|
||||
* Read-state is personal to the recipient. Staff with read-all oversight can
|
||||
* *view* anyone's notifications, but they must never flip another user's read
|
||||
* flag — doing so would hide that notification from its real owner. The ownership
|
||||
* guard (`doc.user === actorUserId`) is what enforces this; `overrideAccess` on
|
||||
* the reads/updates just fetches and writes the rows.
|
||||
*
|
||||
* @returns the ids that were actually flipped from unread to read.
|
||||
*/
|
||||
export async function markNotificationsReadForUser(
|
||||
payload: PayloadType,
|
||||
actorUserId: number,
|
||||
ids: number[],
|
||||
): Promise<number[]> {
|
||||
const cleanIds = [...new Set(ids.filter((id) => Number.isFinite(id) && id > 0))];
|
||||
if (cleanIds.length === 0) return [];
|
||||
|
||||
const found = await payload.find({
|
||||
collection: "user-notifications",
|
||||
where: { id: { in: cleanIds } },
|
||||
limit: cleanIds.length,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const updated: number[] = [];
|
||||
for (const doc of found.docs) {
|
||||
if (Number(doc.user) !== actorUserId) continue;
|
||||
if (!doc.read) {
|
||||
await payload.update({
|
||||
collection: "user-notifications",
|
||||
id: doc.id,
|
||||
data: { read: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
updated.push(doc.id);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark every unread notification that belongs to the actor as read. Never
|
||||
* touches another user's notifications — unlike the old inline "mark all read"
|
||||
* which swept unread rows across every user.
|
||||
*
|
||||
* @returns the ids that were actually flipped from unread to read.
|
||||
*/
|
||||
export async function markAllNotificationsReadForUser(
|
||||
payload: PayloadType,
|
||||
actorUserId: number,
|
||||
): Promise<number[]> {
|
||||
const found = await payload.find({
|
||||
collection: "user-notifications",
|
||||
where: { read: { equals: false } },
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const updated: number[] = [];
|
||||
for (const doc of found.docs) {
|
||||
if (Number(doc.user) !== actorUserId) continue;
|
||||
if (!doc.read) {
|
||||
await payload.update({
|
||||
collection: "user-notifications",
|
||||
id: doc.id,
|
||||
data: { read: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
updated.push(doc.id);
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** Short display label for a notification type, or the raw type when unknown. */
|
||||
export function notificationLabel(type?: string | null): string {
|
||||
switch (type) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue