refactor(api): extract notification procedures

This commit is contained in:
2026-03-31 20:50:14 +02:00
parent 958d2368c1
commit 6837568ffe
5 changed files with 1986 additions and 908 deletions
@@ -0,0 +1,90 @@
import { TRPCError } from "@trpc/server";
import { describe, expect, it, vi } from "vitest";
import {
getNotificationErrorCandidates,
rethrowNotificationReferenceError,
resolveUserId,
} from "../router/notification-procedure-support.js";
describe("notification procedure support", () => {
it("resolves the current user id from the session email", async () => {
const findUnique = vi.fn().mockResolvedValue({ id: "user_1" });
await expect(resolveUserId({
db: {
user: {
findUnique,
},
},
session: {
user: { email: "person@example.com" },
},
})).resolves.toBe("user_1");
expect(findUnique).toHaveBeenCalledWith({
where: { email: "person@example.com" },
select: { id: true },
});
});
it("rejects when no session email is available", async () => {
await expect(resolveUserId({
db: {
user: {
findUnique: vi.fn(),
},
},
session: {
user: null,
},
})).rejects.toEqual(expect.objectContaining<Partial<TRPCError>>({
code: "UNAUTHORIZED",
}));
});
it("collects nested notification error candidates from causes", () => {
const nested = {
code: "P2003",
meta: { field_name: "senderId" },
};
const candidates = getNotificationErrorCandidates({
cause: {
shape: {
data: {
cause: nested,
},
},
},
});
expect(candidates).toContainEqual(expect.objectContaining({
code: "P2003",
meta: expect.objectContaining({ field_name: "senderId" }),
}));
});
it("rewrites sender foreign-key errors to a not found TRPC error", () => {
const error = {
code: "P2003",
meta: { field_name: "senderId" },
};
try {
rethrowNotificationReferenceError(error);
throw new Error("expected notification reference error");
} catch (caught) {
expect(caught).toBeInstanceOf(TRPCError);
expect(caught).toMatchObject<Partial<TRPCError>>({
code: "NOT_FOUND",
message: "Sender user not found",
});
}
});
it("rethrows unrelated errors unchanged", () => {
const error = new Error("boom");
expect(() => rethrowNotificationReferenceError(error)).toThrow(error);
});
});
@@ -2,15 +2,19 @@ import { SystemRole } from "@capakraken/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { notificationRouter } from "../router/notification.js";
import {
emitBroadcastSent,
emitNotificationCreated,
emitTaskAssigned,
emitTaskCompleted,
emitTaskStatusChanged,
} from "../sse/event-bus.js";
import { createCallerFactory } from "../trpc.js";
const { resolveRecipientsMock } = vi.hoisted(() => ({
resolveRecipientsMock: vi.fn(),
}));
const { sendEmailMock } = vi.hoisted(() => ({
sendEmailMock: vi.fn(),
}));
// Mock the SSE event bus — we don't test real event emission here
vi.mock("../sse/event-bus.js", () => ({
@@ -18,18 +22,22 @@ vi.mock("../sse/event-bus.js", () => ({
emitTaskAssigned: vi.fn(),
emitTaskCompleted: vi.fn(),
emitTaskStatusChanged: vi.fn(),
emitBroadcastSent: vi.fn(),
}));
vi.mock("../lib/notification-targeting.js", () => ({
resolveRecipients: resolveRecipientsMock,
}));
vi.mock("../lib/email.js", () => ({
sendEmail: sendEmailMock,
}));
const createCaller = createCallerFactory(notificationRouter);
beforeEach(() => {
vi.clearAllMocks();
resolveRecipientsMock.mockReset();
sendEmailMock.mockReset();
});
// ── Caller factories ─────────────────────────────────────────────────────────
@@ -290,6 +298,8 @@ describe("notification.create", () => {
// ─── createBroadcast ────────────────────────────────────────────────────────
describe("notification.createBroadcast", () => {
const FUTURE_SCHEDULED_AT = new Date("2099-04-01T10:00:00Z");
it("rejects broadcasts when no recipients match the target", async () => {
resolveRecipientsMock.mockResolvedValue([]);
@@ -326,6 +336,70 @@ describe("notification.createBroadcast", () => {
);
});
it("rejects scheduled broadcasts when no recipients match the target", async () => {
resolveRecipientsMock.mockResolvedValue([]);
const create = vi.fn();
const update = vi.fn();
const db = {
notificationBroadcast: {
create,
update,
},
};
const caller = createManagerCaller(db);
await expect(caller.createBroadcast({
title: "Ops update",
targetType: "all",
scheduledAt: FUTURE_SCHEDULED_AT,
})).rejects.toMatchObject({
code: "BAD_REQUEST",
message: "No recipients matched the broadcast target.",
});
expect(create).not.toHaveBeenCalled();
expect(update).not.toHaveBeenCalled();
expect(resolveRecipientsMock).toHaveBeenCalledWith(
"all",
undefined,
db,
"user_mgr",
);
});
it("rejects scheduled broadcasts with task metadata before persisting anything", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a"]);
const create = vi.fn();
const update = vi.fn();
const db = {
notificationBroadcast: {
create,
update,
},
};
const caller = createManagerCaller(db);
await expect(caller.createBroadcast({
title: "Approval later",
targetType: "all",
category: "TASK",
taskAction: "approve_vacation:vac_1",
dueDate: new Date("2099-04-02T10:00:00Z"),
scheduledAt: FUTURE_SCHEDULED_AT,
})).rejects.toMatchObject({
code: "BAD_REQUEST",
message: "Scheduled broadcasts with task metadata are not supported yet.",
});
expect(resolveRecipientsMock).not.toHaveBeenCalled();
expect(create).not.toHaveBeenCalled();
expect(update).not.toHaveBeenCalled();
});
it("does not partially persist an immediate broadcast when recipient fan-out fails", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
@@ -378,6 +452,242 @@ describe("notification.createBroadcast", () => {
expect(outerCreateNotification).not.toHaveBeenCalled();
});
it("emits recipient SSE only after an immediate broadcast commits", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
const txCreateBroadcast = vi.fn().mockResolvedValue({
id: "broadcast_tx_1",
title: "Ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
});
const txCreateNotification = vi.fn()
.mockResolvedValueOnce({ id: "notif_a", userId: "user_a" })
.mockResolvedValueOnce({ id: "notif_b", userId: "user_b" });
const txUpdateBroadcast = vi.fn().mockResolvedValue({
id: "broadcast_tx_1",
title: "Ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
sentAt: new Date("2026-03-30T10:01:00Z"),
recipientCount: 2,
});
const tx = {
notificationBroadcast: {
create: txCreateBroadcast,
update: txUpdateBroadcast,
},
notification: {
create: txCreateNotification,
},
};
const transaction = vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => callback(tx));
const db = {
$transaction: transaction,
notificationBroadcast: {
create: vi.fn(),
update: vi.fn(),
},
notification: {
create: vi.fn(),
},
};
const caller = createManagerCaller(db);
const result = await caller.createBroadcast({
title: "Ops update",
category: "TASK",
targetType: "all",
taskAction: "acknowledge",
});
expect(transaction).toHaveBeenCalledTimes(1);
expect(txCreateBroadcast).toHaveBeenCalledTimes(1);
expect(txCreateNotification).toHaveBeenCalledTimes(2);
expect(txUpdateBroadcast).toHaveBeenCalledWith({
where: { id: "broadcast_tx_1" },
data: {
sentAt: expect.any(Date),
recipientCount: 2,
},
});
expect(emitNotificationCreated).toHaveBeenNthCalledWith(1, "user_a", "notif_a");
expect(emitNotificationCreated).toHaveBeenNthCalledWith(2, "user_b", "notif_b");
expect(emitTaskAssigned).toHaveBeenNthCalledWith(1, "user_a", "notif_a");
expect(emitTaskAssigned).toHaveBeenNthCalledWith(2, "user_b", "notif_b");
expect(result).toMatchObject({
id: "broadcast_tx_1",
recipientCount: 2,
});
});
it("does not emit recipient SSE when a broadcast is only scheduled", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
const create = vi.fn().mockResolvedValue({
id: "broadcast_sched_1",
title: "Scheduled ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
scheduledAt: FUTURE_SCHEDULED_AT,
recipientCount: 2,
});
const db = {
notificationBroadcast: {
create,
update: vi.fn(),
},
notification: {
create: vi.fn(),
},
};
const caller = createManagerCaller(db);
const result = await caller.createBroadcast({
title: "Scheduled ops update",
targetType: "all",
scheduledAt: FUTURE_SCHEDULED_AT,
});
expect(create).toHaveBeenCalledWith({
data: expect.objectContaining({
senderId: "user_mgr",
title: "Scheduled ops update",
targetType: "all",
scheduledAt: FUTURE_SCHEDULED_AT,
recipientCount: 2,
}),
});
expect(db.notification.create).not.toHaveBeenCalled();
expect(emitNotificationCreated).not.toHaveBeenCalled();
expect(emitTaskAssigned).not.toHaveBeenCalled();
expect(result).toMatchObject({
id: "broadcast_sched_1",
scheduledAt: FUTURE_SCHEDULED_AT,
recipientCount: 2,
});
});
it("sends broadcast emails only after an immediate broadcast transaction commits", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
const txCreateBroadcast = vi.fn().mockResolvedValue({
id: "broadcast_tx_email_1",
title: "Ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
});
const txCreateNotification = vi.fn()
.mockResolvedValueOnce({ id: "notif_a", userId: "user_a" })
.mockResolvedValueOnce({ id: "notif_b", userId: "user_b" });
const txUpdateBroadcast = vi.fn().mockResolvedValue({
id: "broadcast_tx_email_1",
title: "Ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
sentAt: new Date("2026-03-30T10:01:00Z"),
recipientCount: 2,
});
const tx = {
notificationBroadcast: {
create: txCreateBroadcast,
update: txUpdateBroadcast,
},
notification: {
create: txCreateNotification,
},
};
let transactionCommitted = false;
const transaction = vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => {
const result = await callback(tx);
expect(sendEmailMock).not.toHaveBeenCalled();
transactionCommitted = true;
return result;
});
const db = {
$transaction: transaction,
user: {
findUnique: vi.fn()
.mockResolvedValueOnce({ email: "user-a@example.com", name: "User A" })
.mockResolvedValueOnce({ email: "user-b@example.com", name: "User B" }),
},
notificationBroadcast: {
create: vi.fn(),
update: vi.fn(),
},
notification: {
create: vi.fn(),
},
};
const caller = createManagerCaller(db);
const result = await caller.createBroadcast({
title: "Ops update",
body: "Email everyone",
channel: "both",
targetType: "all",
});
await vi.waitFor(() => {
expect(sendEmailMock).toHaveBeenCalledTimes(2);
});
expect(transactionCommitted).toBe(true);
expect(sendEmailMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
to: "user-a@example.com",
subject: "Ops update",
text: "Email everyone",
}));
expect(sendEmailMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
to: "user-b@example.com",
subject: "Ops update",
text: "Email everyone",
}));
expect(result).toMatchObject({
id: "broadcast_tx_email_1",
recipientCount: 2,
});
});
it("does not send emails immediately for scheduled broadcasts", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
const create = vi.fn().mockResolvedValue({
id: "broadcast_sched_email_1",
title: "Scheduled ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
scheduledAt: FUTURE_SCHEDULED_AT,
recipientCount: 2,
});
const db = {
user: {
findUnique: vi.fn(),
},
notificationBroadcast: {
create,
update: vi.fn(),
},
notification: {
create: vi.fn(),
},
};
const caller = createManagerCaller(db);
const result = await caller.createBroadcast({
title: "Scheduled ops update",
body: "Hold until later",
channel: "email",
targetType: "all",
scheduledAt: FUTURE_SCHEDULED_AT,
});
await Promise.resolve();
expect(db.user.findUnique).not.toHaveBeenCalled();
expect(sendEmailMock).not.toHaveBeenCalled();
expect(result).toMatchObject({
id: "broadcast_sched_email_1",
scheduledAt: FUTURE_SCHEDULED_AT,
recipientCount: 2,
});
});
it("rolls back an immediate broadcast when the final broadcast update fails", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
@@ -438,6 +748,572 @@ describe("notification.createBroadcast", () => {
expect(outerCreateNotification).not.toHaveBeenCalled();
expect(emitNotificationCreated).not.toHaveBeenCalled();
expect(emitTaskAssigned).not.toHaveBeenCalled();
expect(emitBroadcastSent).not.toHaveBeenCalled();
});
it("does not send broadcast emails when the immediate transaction fails", async () => {
resolveRecipientsMock.mockResolvedValue(["user_a", "user_b"]);
const txCreateBroadcast = vi.fn().mockResolvedValue({
id: "broadcast_tx_email_fail_1",
title: "Ops update",
createdAt: new Date("2026-03-30T10:00:00Z"),
});
const txCreateNotification = vi.fn()
.mockResolvedValueOnce({ id: "notif_a", userId: "user_a" })
.mockResolvedValueOnce({ id: "notif_b", userId: "user_b" });
const txUpdateBroadcast = vi.fn().mockRejectedValue(new Error("commit failed"));
const tx = {
notificationBroadcast: {
create: txCreateBroadcast,
update: txUpdateBroadcast,
},
notification: {
create: txCreateNotification,
},
};
const db = {
$transaction: vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => callback(tx)),
user: {
findUnique: vi.fn(),
},
notificationBroadcast: {
create: vi.fn(),
update: vi.fn(),
},
notification: {
create: vi.fn(),
},
};
const caller = createManagerCaller(db);
await expect(caller.createBroadcast({
title: "Ops update",
body: "Email everyone",
channel: "email",
targetType: "all",
})).rejects.toThrow("commit failed");
await Promise.resolve();
expect(db.user.findUnique).not.toHaveBeenCalled();
expect(sendEmailMock).not.toHaveBeenCalled();
});
});
// ─── task management ────────────────────────────────────────────────────────
describe("notification.listTasks", () => {
it("lists task and approval notifications for the current user as owner or assignee", async () => {
const tasks = [
sampleNotification({ id: "task_1", category: "TASK", taskStatus: "OPEN" }),
sampleNotification({
id: "approval_1",
category: "APPROVAL",
taskStatus: "IN_PROGRESS",
assigneeId: "user_1",
}),
];
const db = withUserLookup({
notification: {
findMany: vi.fn().mockResolvedValue(tasks),
},
});
const caller = createProtectedCaller(db);
const result = await caller.listTasks({ status: "OPEN", limit: 15 });
expect(result).toEqual(tasks);
expect(db.notification.findMany).toHaveBeenCalledWith({
where: {
OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
category: { in: ["TASK", "APPROVAL"] },
taskStatus: "OPEN",
},
orderBy: [{ priority: "desc" }, { dueDate: "asc" }, { createdAt: "desc" }],
take: 15,
});
});
it("can restrict tasks to those owned by the current user", async () => {
const db = withUserLookup({
notification: {
findMany: vi.fn().mockResolvedValue([]),
},
});
const caller = createProtectedCaller(db);
await caller.listTasks({ includeAssigned: false, limit: 10 });
expect(db.notification.findMany).toHaveBeenCalledWith({
where: {
userId: "user_1",
category: { in: ["TASK", "APPROVAL"] },
},
orderBy: [{ priority: "desc" }, { dueDate: "asc" }, { createdAt: "desc" }],
take: 10,
});
});
});
describe("notification.taskCounts", () => {
it("normalizes grouped task counts and calculates overdue work", async () => {
const groupBy = vi.fn().mockResolvedValue([
{ taskStatus: "OPEN", _count: 4 },
{ taskStatus: "DONE", _count: 2 },
]);
const count = vi.fn().mockResolvedValue(3);
const db = withUserLookup({
notification: {
groupBy,
count,
},
});
const caller = createProtectedCaller(db);
const result = await caller.taskCounts();
expect(result).toEqual({
open: 4,
inProgress: 0,
done: 2,
dismissed: 0,
overdue: 3,
});
expect(groupBy).toHaveBeenCalledWith({
by: ["taskStatus"],
where: {
OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
category: { in: ["TASK", "APPROVAL"] },
},
_count: true,
});
expect(count).toHaveBeenCalledWith({
where: {
OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
category: { in: ["TASK", "APPROVAL"] },
taskStatus: { in: ["OPEN", "IN_PROGRESS"] },
dueDate: { lt: expect.any(Date) },
},
});
});
});
describe("notification.getTaskDetail", () => {
it("returns the selected task detail payload including sender context", async () => {
const task = {
id: "task_1",
title: "Review allocation",
body: "Please verify the plan.",
type: "TASK_CREATED",
priority: "HIGH",
category: "TASK",
taskStatus: "OPEN",
taskAction: "approve_vacation:vac_1",
dueDate: new Date("2026-04-10T09:00:00Z"),
entityId: "vac_1",
entityType: "VACATION",
completedAt: null,
completedBy: null,
createdAt: new Date("2026-04-01T08:00:00Z"),
userId: "user_1",
assigneeId: "user_2",
sender: { id: "user_mgr", name: "Manager", email: "mgr@example.com" },
};
const findFirst = vi.fn().mockResolvedValue(task);
const db = withUserLookup({
notification: {
findFirst,
},
});
const caller = createProtectedCaller(db);
const result = await caller.getTaskDetail({ id: "task_1" });
expect(result).toEqual(task);
expect(findFirst).toHaveBeenCalledWith({
where: {
id: "task_1",
OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
category: { in: ["TASK", "APPROVAL"] },
},
select: {
id: true,
title: true,
body: true,
type: true,
priority: true,
category: true,
taskStatus: true,
taskAction: true,
dueDate: true,
entityId: true,
entityType: true,
completedAt: true,
completedBy: true,
createdAt: true,
userId: true,
assigneeId: true,
sender: { select: { id: true, name: true, email: true } },
},
});
});
it("returns NOT_FOUND when the task is not visible to the current user", async () => {
const db = withUserLookup({
notification: {
findFirst: vi.fn().mockResolvedValue(null),
},
});
const caller = createProtectedCaller(db);
await expect(caller.getTaskDetail({ id: "task_missing" })).rejects.toMatchObject({
code: "NOT_FOUND",
message: "Task not found or you do not have permission",
});
});
});
describe("notification.updateTaskStatus", () => {
it("marks a task as done, records completion metadata, and emits completion events", async () => {
const findFirst = vi.fn().mockResolvedValue({
id: "task_1",
userId: "user_1",
assigneeId: "user_2",
});
const update = vi.fn().mockResolvedValue({
id: "task_1",
taskStatus: "DONE",
completedBy: "user_1",
completedAt: new Date("2026-04-02T10:00:00Z"),
});
const db = withUserLookup({
notification: {
findFirst,
update,
},
});
const caller = createProtectedCaller(db);
const result = await caller.updateTaskStatus({ id: "task_1", status: "DONE" });
expect(result).toMatchObject({
id: "task_1",
taskStatus: "DONE",
completedBy: "user_1",
});
expect(findFirst).toHaveBeenCalledWith({
where: {
id: "task_1",
OR: [{ userId: "user_1" }, { assigneeId: "user_1" }],
},
});
expect(update).toHaveBeenCalledWith({
where: { id: "task_1" },
data: {
taskStatus: "DONE",
completedAt: expect.any(Date),
completedBy: "user_1",
},
});
expect(emitTaskCompleted).toHaveBeenNthCalledWith(1, "user_1", "task_1");
expect(emitTaskCompleted).toHaveBeenNthCalledWith(2, "user_2", "task_1");
expect(emitTaskStatusChanged).not.toHaveBeenCalled();
});
it("emits status-change events for non-terminal task updates", async () => {
const db = withUserLookup({
notification: {
findFirst: vi.fn().mockResolvedValue({
id: "task_2",
userId: "user_1",
assigneeId: "user_3",
}),
update: vi.fn().mockResolvedValue({
id: "task_2",
taskStatus: "IN_PROGRESS",
}),
},
});
const caller = createProtectedCaller(db);
await caller.updateTaskStatus({ id: "task_2", status: "IN_PROGRESS" });
expect(db.notification.update).toHaveBeenCalledWith({
where: { id: "task_2" },
data: { taskStatus: "IN_PROGRESS" },
});
expect(emitTaskStatusChanged).toHaveBeenNthCalledWith(1, "user_1", "task_2");
expect(emitTaskStatusChanged).toHaveBeenNthCalledWith(2, "user_3", "task_2");
});
});
describe("notification.assignTask", () => {
it("reassigns a task and emits the assignment event for the new assignee", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "task_9",
category: "TASK",
assigneeId: "user_2",
});
const update = vi.fn().mockResolvedValue({
id: "task_9",
category: "TASK",
assigneeId: "user_4",
});
const db = {
notification: {
findUnique,
update,
},
};
const caller = createManagerCaller(db);
const result = await caller.assignTask({ id: "task_9", assigneeId: "user_4" });
expect(findUnique).toHaveBeenCalledWith({ where: { id: "task_9" } });
expect(update).toHaveBeenCalledWith({
where: { id: "task_9" },
data: { assigneeId: "user_4" },
});
expect(result).toMatchObject({
id: "task_9",
assigneeId: "user_4",
});
expect(emitTaskAssigned).toHaveBeenCalledWith("user_4", "task_9");
});
});
// ─── reminders ──────────────────────────────────────────────────────────────
describe("notification.createReminder", () => {
it("creates a reminder for the current user and seeds nextRemindAt", async () => {
const remindAt = new Date("2026-04-15T08:30:00Z");
const createdReminder = sampleNotification({
id: "rem_1",
type: "REMINDER",
category: "REMINDER",
title: "Submit report",
remindAt,
nextRemindAt: remindAt,
recurrence: "weekly",
});
const create = vi.fn().mockResolvedValue(createdReminder);
const db = withUserLookup({
notification: {
create,
},
});
const caller = createProtectedCaller(db);
const result = await caller.createReminder({
title: "Submit report",
body: "Finance review",
remindAt,
recurrence: "weekly",
entityId: "project_1",
entityType: "PROJECT",
link: "/projects/project_1",
});
expect(result).toEqual(createdReminder);
expect(create).toHaveBeenCalledWith({
data: {
userId: "user_1",
type: "REMINDER",
category: "REMINDER",
title: "Submit report",
body: "Finance review",
remindAt,
nextRemindAt: remindAt,
recurrence: "weekly",
entityId: "project_1",
entityType: "PROJECT",
link: "/projects/project_1",
channel: "in_app",
},
});
});
});
describe("notification.updateReminder", () => {
it("updates an owned reminder and keeps nextRemindAt in sync with remindAt", async () => {
const remindAt = new Date("2026-05-01T07:00:00Z");
const findFirst = vi.fn().mockResolvedValue({
id: "rem_1",
userId: "user_1",
category: "REMINDER",
});
const update = vi.fn().mockResolvedValue({
id: "rem_1",
title: "Updated reminder",
remindAt,
nextRemindAt: remindAt,
recurrence: null,
});
const db = withUserLookup({
notification: {
findFirst,
update,
},
});
const caller = createProtectedCaller(db);
const result = await caller.updateReminder({
id: "rem_1",
title: "Updated reminder",
remindAt,
recurrence: null,
});
expect(result).toMatchObject({
id: "rem_1",
title: "Updated reminder",
recurrence: null,
});
expect(findFirst).toHaveBeenCalledWith({
where: { id: "rem_1", userId: "user_1", category: "REMINDER" },
});
expect(update).toHaveBeenCalledWith({
where: { id: "rem_1" },
data: {
title: "Updated reminder",
remindAt,
nextRemindAt: remindAt,
recurrence: null,
},
});
});
});
describe("notification.deleteReminder", () => {
it("deletes an owned reminder", async () => {
const findFirst = vi.fn().mockResolvedValue({
id: "rem_1",
userId: "user_1",
category: "REMINDER",
});
const deleteFn = vi.fn().mockResolvedValue({ id: "rem_1" });
const db = withUserLookup({
notification: {
findFirst,
delete: deleteFn,
},
});
const caller = createProtectedCaller(db);
await caller.deleteReminder({ id: "rem_1" });
expect(findFirst).toHaveBeenCalledWith({
where: { id: "rem_1", userId: "user_1", category: "REMINDER" },
});
expect(deleteFn).toHaveBeenCalledWith({ where: { id: "rem_1" } });
});
});
describe("notification.listReminders", () => {
it("lists reminders for the current user ordered by next reminder date", async () => {
const reminders = [
{
id: "rem_1",
userId: "user_1",
category: "REMINDER",
nextRemindAt: new Date("2026-05-01T07:00:00Z"),
},
];
const db = withUserLookup({
notification: {
findMany: vi.fn().mockResolvedValue(reminders),
},
});
const caller = createProtectedCaller(db);
const result = await caller.listReminders({ limit: 10 });
expect(result).toEqual(reminders);
expect(db.notification.findMany).toHaveBeenCalledWith({
where: { userId: "user_1", category: "REMINDER" },
orderBy: { nextRemindAt: "asc" },
take: 10,
});
});
});
// ─── broadcasts and delete ─────────────────────────────────────────────────
describe("notification.getBroadcastById", () => {
it("returns the broadcast including sender context", async () => {
const findUnique = vi.fn().mockResolvedValue({
id: "broadcast_1",
title: "Office update",
sender: { id: "user_mgr", name: "Manager", email: "mgr@example.com" },
});
const db = withUserLookup({
notificationBroadcast: {
findUnique,
},
}, "user_mgr");
const caller = createManagerCaller(db);
const result = await caller.getBroadcastById({ id: "broadcast_1" });
expect(result).toEqual({
id: "broadcast_1",
title: "Office update",
sender: { id: "user_mgr", name: "Manager", email: "mgr@example.com" },
});
expect(findUnique).toHaveBeenCalledWith({
where: { id: "broadcast_1" },
include: {
sender: { select: { id: true, name: true, email: true } },
},
});
});
});
describe("notification.delete", () => {
it("deletes a regular notification owned by the current user", async () => {
const findFirst = vi.fn().mockResolvedValue({
id: "notif_1",
userId: "user_1",
category: "NOTIFICATION",
senderId: "user_mgr",
});
const deleteFn = vi.fn().mockResolvedValue({ id: "notif_1" });
const db = withUserLookup({
notification: {
findFirst,
delete: deleteFn,
},
});
const caller = createProtectedCaller(db);
await caller.delete({ id: "notif_1" });
expect(findFirst).toHaveBeenCalledWith({
where: { id: "notif_1", userId: "user_1" },
});
expect(deleteFn).toHaveBeenCalledWith({ where: { id: "notif_1" } });
});
it("forbids deleting a task created by another user", async () => {
const deleteFn = vi.fn();
const db = withUserLookup({
notification: {
findFirst: vi.fn().mockResolvedValue({
id: "task_1",
userId: "user_1",
category: "TASK",
senderId: "user_mgr",
}),
delete: deleteFn,
},
});
const caller = createProtectedCaller(db);
await expect(caller.delete({ id: "task_1" })).rejects.toMatchObject({
code: "FORBIDDEN",
message: "Cannot delete tasks created by others",
});
expect(deleteFn).not.toHaveBeenCalled();
});
});