Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(notifications): add user-scoped notification read, dismiss, delete and summary actions
Khuram Niaz0ba703c8a4ae
diff --git a/__tests__/notification.actions.spec.ts b/__tests__/notification.actions.spec.tsnew file mode 100644index 0000000..a11747e--- /dev/null+++ b/__tests__/notification.actions.spec.ts@@ -0,0 +1,133 @@+import {+ getNotificationSummary,+ getPopoverNotifications,+ getNotificationList,+ markNotificationRead,+ markAllNotificationsRead,+ dismissNotification,+ deleteNotification,+ clearReadNotifications,+} from "@/actions/notification.actions";+import { getCurrentUser } from "@/utils/user.utils";+import prisma from "@/lib/db";++vi.mock("@/lib/db", () => ({+ default: {+ notification: {+ count: vi.fn(),+ findMany: vi.fn(),+ updateMany: vi.fn(),+ deleteMany: vi.fn(),+ },+ },+}));+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));++const db = prisma as any;+const user = { id: "user-1" };++beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(user);+ db.notification.count.mockResolvedValue(0);+ db.notification.findMany.mockResolvedValue([]);+ db.notification.updateMany.mockResolvedValue({ count: 1 });+ db.notification.deleteMany.mockResolvedValue({ count: 1 });+});++describe("reads", () => {+ it("summary counts unread within the retention window, errors separately", async () => {+ db.notification.count.mockResolvedValueOnce(3).mockResolvedValueOnce(1);+ const res = await getNotificationSummary();+ expect(res).toEqual({ success: true, data: { unread: 3, unreadErrors: 1 } });+ const [all, errors] = db.notification.count.mock.calls.map((c: any) => c[0].where);+ expect(all).toMatchObject({ userId: "user-1", readAt: null });+ expect(all.occurredAt.gte).toBeInstanceOf(Date);+ expect(errors.kind).toEqual({ in: ["error", "board"] });+ });++ it("popover excludes dismissed rows and orders newest first", async () => {+ await getPopoverNotifications();+ const args = db.notification.findMany.mock.calls[0][0];+ expect(args.where).toMatchObject({ userId: "user-1", dismissedAt: null });+ expect(args.where.occurredAt.gte).toBeInstanceOf(Date);+ expect(args.orderBy).toEqual([{ occurredAt: "desc" }, { id: "desc" }]);+ expect(args.take).toBe(20);+ });++ it("parses the payload JSON", async () => {+ db.notification.findMany.mockResolvedValue([+ { id: "n1", kind: "run", payload: '{"jobsSaved":2}', automation: { id: "a", name: "A" } },+ ]);+ const res: any = await getPopoverNotifications();+ expect(res.data[0].payload).toEqual({ jobsSaved: 2 });+ });++ it("page list includes dismissed rows and filters by tab and automation", async () => {+ await getNotificationList({ tab: "errors", automationId: "a-1" });+ const where = db.notification.findMany.mock.calls[0][0].where;+ expect(where).not.toHaveProperty("dismissedAt");+ expect(where).toMatchObject({+ userId: "user-1",+ automationId: "a-1",+ kind: { in: ["error", "board"] },+ });+ });++ it("unread tab filters readAt null", async () => {+ await getNotificationList({ tab: "unread" });+ expect(db.notification.findMany.mock.calls[0][0].where.readAt).toBeNull();+ });+});++describe("mutations are scoped to the user", () => {+ it("mark read", async () => {+ await markNotificationRead("n-1");+ expect(db.notification.updateMany).toHaveBeenCalledWith({+ where: { id: "n-1", userId: "user-1", readAt: null },+ data: { readAt: expect.any(Date) },+ });+ });++ it("dismiss also marks read so the badge matches the popover", async () => {+ await dismissNotification("n-1");+ const { where, data } = db.notification.updateMany.mock.calls[0][0];+ expect(where).toEqual({ id: "n-1", userId: "user-1" });+ expect(data.dismissedAt).toBeInstanceOf(Date);+ expect(data.readAt).toBeInstanceOf(Date);+ });++ it("another user's id is a no-op, not an error", async () => {+ db.notification.updateMany.mockResolvedValue({ count: 0 });+ await expect(dismissNotification("someone-elses")).resolves.toEqual({ success: true });+ });++ it("delete", async () => {+ await deleteNotification("n-1");+ expect(db.notification.deleteMany).toHaveBeenCalledWith({+ where: { id: "n-1", userId: "user-1" },+ });+ });++ it("mark all read", async () => {+ await markAllNotificationsRead();+ expect(db.notification.updateMany.mock.calls[0][0].where).toEqual({+ userId: "user-1",+ readAt: null,+ });+ });++ it("clear read deletes only read rows", async () => {+ await clearReadNotifications();+ expect(db.notification.deleteMany).toHaveBeenCalledWith({+ where: { userId: "user-1", readAt: { not: null } },+ });+ });++ it("unauthenticated returns a failure", async () => {+ (getCurrentUser as any).mockResolvedValue(null);+ const res: any = await deleteNotification("n-1");+ expect(res.success).toBe(false);+ expect(db.notification.deleteMany).not.toHaveBeenCalled();+ });+});diff --git a/src/actions/notification.actions.ts b/src/actions/notification.actions.tsnew file mode 100644index 0000000..eed9ce4--- /dev/null+++ b/src/actions/notification.actions.ts@@ -0,0 +1,197 @@+"use server";++import type { Prisma } from "@prisma/client";+import db from "@/lib/db";+import { handleError } from "@/lib/utils";+import { requireUser } from "@/actions/shared";+import { NOTIFICATION_CONSTANTS } from "@/lib/constants";+import { notificationCutoff } from "@/lib/notifications/prune";+import type {+ NotificationItem,+ NotificationTab,+} from "@/models/notification.model";++const ERROR_KINDS = ["error", "board"];++const ITEM_SELECT = {+ id: true,+ kind: true,+ payload: true,+ occurrences: true,+ occurredAt: true,+ createdAt: true,+ readAt: true,+ dismissedAt: true,+ automation: { select: { id: true, name: true } },+} as const;++const ORDER = [{ occurredAt: "desc" as const }, { id: "desc" as const }];++function tabWhere(tab: NotificationTab): Prisma.NotificationWhereInput {+ if (tab === "unread") return { readAt: null };+ if (tab === "errors") return { kind: { in: ERROR_KINDS } };+ if (tab === "runs") return { kind: "run" };+ return {};+}++function toItems(rows: Array<{ payload: string } & Record<string, unknown>>) {+ return rows.map((r) => ({ ...r, payload: JSON.parse(r.payload) })) as NotificationItem[];+}++export async function getNotificationSummary() {+ try {+ const user = await requireUser();+ const base = {+ userId: user.id,+ readAt: null,+ occurredAt: { gte: notificationCutoff() },+ };+ const [unread, unreadErrors] = await Promise.all([+ db.notification.count({ where: base }),+ db.notification.count({ where: { ...base, kind: { in: ERROR_KINDS } } }),+ ]);+ return { success: true, data: { unread, unreadErrors } };+ } catch (error) {+ return handleError(error, "Failed to load notifications.");+ }+}++export async function getPopoverNotifications() {+ try {+ const user = await requireUser();+ const rows = await db.notification.findMany({+ where: {+ userId: user.id,+ dismissedAt: null,+ occurredAt: { gte: notificationCutoff() },+ },+ select: ITEM_SELECT,+ orderBy: ORDER,+ take: NOTIFICATION_CONSTANTS.POPOVER_LIMIT,+ });+ return { success: true, data: toItems(rows) };+ } catch (error) {+ return handleError(error, "Failed to load notifications.");+ }+}++export async function getNotificationList({+ tab,+ automationId,+ skip = 0,+}: {+ tab: NotificationTab;+ automationId?: string;+ skip?: number;+}) {+ try {+ const user = await requireUser();+ const scope: Prisma.NotificationWhereInput = {+ userId: user.id,+ occurredAt: { gte: notificationCutoff() },+ ...(automationId ? { automationId } : {}),+ };+ const where = { ...scope, ...tabWhere(tab) };+ const [rows, total, all, unread, errors, runs] = await Promise.all([+ db.notification.findMany({+ where,+ select: ITEM_SELECT,+ orderBy: ORDER,+ skip,+ take: NOTIFICATION_CONSTANTS.PAGE_SIZE,+ }),+ db.notification.count({ where }),+ db.notification.count({ where: scope }),+ db.notification.count({ where: { ...scope, ...tabWhere("unread") } }),+ db.notification.count({ where: { ...scope, ...tabWhere("errors") } }),+ db.notification.count({ where: { ...scope, ...tabWhere("runs") } }),+ ]);+ return {+ success: true,+ data: { items: toItems(rows), total, counts: { all, unread, errors, runs } },+ };+ } catch (error) {+ return handleError(error, "Failed to load notifications.");+ }+}++// Built from rows that exist, so a pick never yields an empty list.+export async function getNotificationFilterOptions() {+ try {+ const user = await requireUser();+ const options = await db.automation.findMany({+ where: {+ userId: user.id,+ notifications: { some: { occurredAt: { gte: notificationCutoff() } } },+ },+ select: { id: true, name: true },+ orderBy: { name: "asc" },+ });+ return { success: true, data: options };+ } catch (error) {+ return handleError(error, "Failed to load automations.");+ }+}++export async function markNotificationRead(id: string) {+ try {+ const user = await requireUser();+ await db.notification.updateMany({+ where: { id, userId: user.id, readAt: null },+ data: { readAt: new Date() },+ });+ return { success: true };+ } catch (error) {+ return handleError(error, "Failed to update notification.");+ }+}++export async function markAllNotificationsRead() {+ try {+ const user = await requireUser();+ await db.notification.updateMany({+ where: { userId: user.id, readAt: null },+ data: { readAt: new Date() },+ });+ return { success: true };+ } catch (error) {+ return handleError(error, "Failed to update notifications.");+ }+}++// Popover ×: hidden there, kept on the page; read so the badge stays honest.+export async function dismissNotification(id: string) {+ try {+ const user = await requireUser();+ const now = new Date();+ await db.notification.updateMany({+ where: { id, userId: user.id },+ data: { dismissedAt: now, readAt: now },+ });+ return { success: true };+ } catch (error) {+ return handleError(error, "Failed to dismiss notification.");+ }+}++export async function deleteNotification(id: string) {+ try {+ const user = await requireUser();+ await db.notification.deleteMany({ where: { id, userId: user.id } });+ return { success: true };+ } catch (error) {+ return handleError(error, "Failed to delete notification.");+ }+}++export async function clearReadNotifications() {+ try {+ const user = await requireUser();+ await db.notification.deleteMany({+ where: { userId: user.id, readAt: { not: null } },+ });+ return { success: true };+ } catch (error) {+ return handleError(error, "Failed to clear notifications.");+ }+}