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 config from "@payload-config";
|
||||||
import { getPayload } from "payload";
|
import { getPayload } from "payload";
|
||||||
|
|
||||||
|
import {
|
||||||
|
markAllNotificationsReadForUser,
|
||||||
|
markNotificationsReadForUser,
|
||||||
|
} from "@/lib/notifications";
|
||||||
|
|
||||||
export interface NotificationActionResult {
|
export interface NotificationActionResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
error?: string;
|
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." };
|
if (!user) return { success: false, error: "You must be logged in." };
|
||||||
|
|
||||||
const cleanIds = [...new Set(ids.filter((id) => Number.isFinite(id) && id > 0))];
|
// Read-state is personal to the recipient: this only ever flips the acting
|
||||||
if (cleanIds.length === 0) return { success: true };
|
// user's own notifications, never another user's (staff oversight included).
|
||||||
|
await markNotificationsReadForUser(payload, Number(user.id), ids);
|
||||||
// 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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch {
|
} catch {
|
||||||
return { success: false, error: "Failed to update notifications." };
|
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." };
|
if (!user) return { success: false, error: "You must be logged in." };
|
||||||
|
|
||||||
const unread = await payload.find({
|
// Only the acting user's own unread notifications are marked read.
|
||||||
collection: "user-notifications",
|
await markAllNotificationsReadForUser(payload, Number(user.id));
|
||||||
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch {
|
} catch {
|
||||||
return { success: false, error: "Failed to update notifications." };
|
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;
|
link?: string | null;
|
||||||
read: boolean;
|
read: boolean;
|
||||||
createdAt: string;
|
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 {
|
function timeAgo(iso: string): string {
|
||||||
|
|
@ -58,12 +66,12 @@ export function NotificationsBell() {
|
||||||
|
|
||||||
const fetchNotifications = useCallback(async () => {
|
const fetchNotifications = useCallback(async () => {
|
||||||
try {
|
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",
|
cache: "no-store",
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error("Failed to fetch");
|
if (!res.ok) throw new Error("Failed to fetch");
|
||||||
const data = (await res.json()) as { docs?: NotificationItem[] };
|
const data = (await res.json()) as { notifications?: NotificationItem[] };
|
||||||
setNotifications(data.docs ?? []);
|
setNotifications(data.notifications ?? []);
|
||||||
setError(false);
|
setError(false);
|
||||||
} catch {
|
} catch {
|
||||||
setError(true);
|
setError(true);
|
||||||
|
|
@ -83,8 +91,11 @@ export function NotificationsBell() {
|
||||||
};
|
};
|
||||||
}, [fetchNotifications]);
|
}, [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) {
|
async function handleMarkOne(item: NotificationItem) {
|
||||||
if (item.read || marking) return;
|
if (item.read || marking || item.isMine === false) return;
|
||||||
setMarking(true);
|
setMarking(true);
|
||||||
setActionError(null);
|
setActionError(null);
|
||||||
try {
|
try {
|
||||||
|
|
@ -104,7 +115,9 @@ export function NotificationsBell() {
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleItemClick(item: NotificationItem) {
|
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) {
|
if (item.link) {
|
||||||
router.push(item.link);
|
router.push(item.link);
|
||||||
setOpen(false);
|
setOpen(false);
|
||||||
|
|
@ -118,7 +131,11 @@ export function NotificationsBell() {
|
||||||
try {
|
try {
|
||||||
const result = await markAllNotificationsRead();
|
const result = await markAllNotificationsRead();
|
||||||
if (result.success) {
|
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 {
|
} else {
|
||||||
setActionError(result.error ?? "Failed to update notifications.");
|
setActionError(result.error ?? "Failed to update notifications.");
|
||||||
}
|
}
|
||||||
|
|
@ -153,7 +170,7 @@ export function NotificationsBell() {
|
||||||
<button
|
<button
|
||||||
onClick={() => void handleMarkAll()}
|
onClick={() => void handleMarkAll()}
|
||||||
disabled={marking}
|
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"
|
className="text-xs text-muted-foreground hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
||||||
>
|
>
|
||||||
{marking ? "Marking..." : "Mark all read"}
|
{marking ? "Marking..." : "Mark all read"}
|
||||||
|
|
@ -179,25 +196,28 @@ export function NotificationsBell() {
|
||||||
{actionError}
|
{actionError}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{notifications.map((item) => (
|
{notifications.map((item) => {
|
||||||
<DropdownMenuItem
|
const isUnread = !item.read;
|
||||||
key={item.id}
|
const isForeign = item.isMine === false;
|
||||||
className={cn(
|
return (
|
||||||
"flex flex-col items-start gap-1 py-2.5",
|
<DropdownMenuItem
|
||||||
!item.read && "bg-accent/50",
|
key={item.id}
|
||||||
)}
|
className={cn(
|
||||||
disabled={marking}
|
"flex flex-col items-start gap-1 py-2.5",
|
||||||
onClick={() => void handleItemClick(item)}
|
isUnread && "bg-accent/50",
|
||||||
>
|
isForeign && "opacity-80",
|
||||||
<span className="flex w-full items-center justify-between gap-2">
|
)}
|
||||||
<span className="min-w-0 truncate text-sm font-medium">
|
disabled={marking}
|
||||||
{!item.read && (
|
onClick={() => void handleItemClick(item)}
|
||||||
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
|
>
|
||||||
)}
|
<span className="flex w-full items-center justify-between gap-2">
|
||||||
{item.title}
|
<span className="min-w-0 truncate text-sm font-medium">
|
||||||
</span>
|
{!isForeign && isUnread && (
|
||||||
<span className="flex shrink-0 items-center gap-1.5">
|
<span className="mr-1.5 inline-block size-1.5 rounded-full bg-blue-500 align-middle" />
|
||||||
{!item.read && (
|
)}
|
||||||
|
{item.title}
|
||||||
|
</span>
|
||||||
|
{!isForeign && item.read && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
title="Mark as read"
|
title="Mark as read"
|
||||||
|
|
@ -211,21 +231,28 @@ export function NotificationsBell() {
|
||||||
<CheckIcon className="size-3.5" />
|
<CheckIcon className="size-3.5" />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<span className="text-[10px] text-muted-foreground">
|
<span className="flex shrink-0 items-center gap-1.5">
|
||||||
{timeAgo(item.createdAt)}
|
<span className="text-[10px] text-muted-foreground">
|
||||||
|
{timeAgo(item.createdAt)}
|
||||||
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</span>
|
{isForeign && item.ownerName && (
|
||||||
{item.message && (
|
<span className="text-[10px] font-medium text-amber-400/90">
|
||||||
<span className="line-clamp-3 w-full text-xs text-muted-foreground">
|
meant for {item.ownerName}
|
||||||
{item.message}
|
</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>
|
||||||
)}
|
</DropdownMenuItem>
|
||||||
<span className="text-[10px] text-muted-foreground/70">
|
);
|
||||||
{notificationLabel(item.type)}
|
})}
|
||||||
</span>
|
|
||||||
</DropdownMenuItem>
|
|
||||||
))}
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</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. */
|
/** Short display label for a notification type, or the raw type when unknown. */
|
||||||
export function notificationLabel(type?: string | null): string {
|
export function notificationLabel(type?: string | null): string {
|
||||||
switch (type) {
|
switch (type) {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue