d0f04f13f8
Phase N.1 — Data Model: - Extend Notification model with category, priority, task fields (status, action, assignee, dueDate, completedAt/By), reminder fields (remindAt, recurrence, nextRemindAt), and targeting metadata (sourceId, senderId, channel) - Add NotificationCategory, NotificationPriority, TaskStatus enums - Add NotificationBroadcast model for group notifications - Shared types with parseTaskAction()/buildTaskAction() helpers Phase N.2 — API: - Extend notification router: listTasks, taskCounts, updateTaskStatus, createReminder/update/delete/list, createBroadcast/listBroadcasts, createTask, assignTask, delete - Broadcast targeting: resolve recipients by user/role/project/orgUnit/all - Task-action registry: approve_vacation, reject_vacation, confirm_assignment - Reminder scheduler: 60s poll interval, recurring support, catch-up on start - SSE events: TASK_ASSIGNED, TASK_COMPLETED, TASK_STATUS_CHANGED, REMINDER_DUE, BROADCAST_SENT Phase N.3 — AI Assistant: - 7 new tools: list_tasks, get_task_detail, update_task_status, execute_task_action, create_reminder, create_task_for_user, send_broadcast - execute_task_action dispatches to task-action registry with per-action permission checks, marks tasks as completed by AI Phase N.4 — Frontend: - Enhanced NotificationBell with task badge, tabs (All/Tasks/Reminders) - TaskCard component with priority badges, due dates, action buttons - ReminderModal for creating/editing personal reminders - BroadcastModal for targeted group notifications (manager+) - NotificationCenter full-page with 5 tabs and bulk actions - TaskWidget dashboard widget showing open tasks - Admin broadcast management page - AppShell nav links for Notifications and Broadcasts - SSE hook handlers for task/reminder events Phase N.5 — Auto-Tasks: - Vacation create → APPROVAL tasks for all managers - Vacation approve/reject → mark approval tasks as DONE - Demand create → TASK for managers to fill staffing needs Co-Authored-By: claude-flow <ruv@ruv.net>
650 lines
24 KiB
TypeScript
650 lines
24 KiB
TypeScript
import { z } from "zod";
|
|
import { TRPCError } from "@trpc/server";
|
|
import { createTRPCRouter, managerProcedure, protectedProcedure } from "../trpc.js";
|
|
import {
|
|
emitNotificationCreated,
|
|
emitTaskAssigned,
|
|
emitTaskCompleted,
|
|
emitTaskStatusChanged,
|
|
emitBroadcastSent,
|
|
} from "../sse/event-bus.js";
|
|
import { resolveRecipients } from "../lib/notification-targeting.js";
|
|
import { sendEmail } from "../lib/email.js";
|
|
|
|
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
|
|
|
/** Resolve the DB user id from the session email. Throws UNAUTHORIZED if not found. */
|
|
async function resolveUserId(ctx: {
|
|
db: {
|
|
user: {
|
|
findUnique: (args: {
|
|
where: { email: string };
|
|
select: { id: true };
|
|
}) => Promise<{ id: string } | null>;
|
|
};
|
|
};
|
|
session: { user?: { email?: string | null } | null };
|
|
}): Promise<string> {
|
|
const email = ctx.session.user?.email;
|
|
if (!email) throw new TRPCError({ code: "UNAUTHORIZED" });
|
|
const user = await ctx.db.user.findUnique({
|
|
where: { email },
|
|
select: { id: true },
|
|
});
|
|
if (!user) throw new TRPCError({ code: "UNAUTHORIZED" });
|
|
return user.id;
|
|
}
|
|
|
|
/** Send email notification (non-blocking). */
|
|
async function sendNotificationEmail(
|
|
db: { user: { findUnique: (args: { where: { id: string }; select: { email: true; name: true } }) => Promise<{ email: string; name: string | null } | null> } },
|
|
userId: string,
|
|
title: string,
|
|
body?: string | null,
|
|
): Promise<void> {
|
|
try {
|
|
const user = await db.user.findUnique({
|
|
where: { id: userId },
|
|
select: { email: true, name: true },
|
|
});
|
|
if (!user) return;
|
|
void sendEmail({
|
|
to: user.email,
|
|
subject: title,
|
|
text: body ?? title,
|
|
...(body !== undefined && body !== null ? { html: `<p>${body}</p>` } : {}),
|
|
});
|
|
} catch {
|
|
// Non-blocking — swallow errors
|
|
}
|
|
}
|
|
|
|
// ─── Zod Enums ────────────────────────────────────────────────────────────────
|
|
|
|
const categoryEnum = z.enum(["NOTIFICATION", "REMINDER", "TASK", "APPROVAL"]);
|
|
const priorityEnum = z.enum(["LOW", "NORMAL", "HIGH", "URGENT"]);
|
|
const taskStatusEnum = z.enum(["OPEN", "IN_PROGRESS", "DONE", "DISMISSED"]);
|
|
const channelEnum = z.enum(["in_app", "email", "both"]);
|
|
const recurrenceEnum = z.enum(["daily", "weekly", "monthly"]);
|
|
const targetTypeEnum = z.enum(["user", "role", "project", "orgUnit", "all"]);
|
|
|
|
// ─── Router ───────────────────────────────────────────────────────────────────
|
|
|
|
export const notificationRouter = createTRPCRouter({
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// EXISTING (enhanced)
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
/** List notifications for the current user with optional filters */
|
|
list: protectedProcedure
|
|
.input(
|
|
z.object({
|
|
unreadOnly: z.boolean().optional(),
|
|
category: categoryEnum.optional(),
|
|
taskStatus: taskStatusEnum.optional(),
|
|
priority: priorityEnum.optional(),
|
|
limit: z.number().min(1).max(100).default(50),
|
|
}),
|
|
)
|
|
.query(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
return ctx.db.notification.findMany({
|
|
where: {
|
|
userId,
|
|
...(input.unreadOnly ? { readAt: null } : {}),
|
|
...(input.category !== undefined ? { category: input.category } : {}),
|
|
...(input.taskStatus !== undefined ? { taskStatus: input.taskStatus } : {}),
|
|
...(input.priority !== undefined ? { priority: input.priority } : {}),
|
|
},
|
|
orderBy: { createdAt: "desc" },
|
|
take: input.limit,
|
|
});
|
|
}),
|
|
|
|
/** Count unread notifications */
|
|
unreadCount: protectedProcedure.query(async ({ ctx }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
return ctx.db.notification.count({
|
|
where: { userId, readAt: null },
|
|
});
|
|
}),
|
|
|
|
/** Mark one or all as read */
|
|
markRead: protectedProcedure
|
|
.input(z.object({ id: z.string().optional() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
const now = new Date();
|
|
if (input.id) {
|
|
await ctx.db.notification.update({
|
|
where: { id: input.id, userId },
|
|
data: { readAt: now },
|
|
});
|
|
} else {
|
|
await ctx.db.notification.updateMany({
|
|
where: { userId, readAt: null },
|
|
data: { readAt: now },
|
|
});
|
|
}
|
|
}),
|
|
|
|
/** Create a notification (enhanced with all new fields) */
|
|
create: managerProcedure
|
|
.input(
|
|
z.object({
|
|
userId: z.string(),
|
|
type: z.string(),
|
|
title: z.string(),
|
|
body: z.string().optional(),
|
|
entityId: z.string().optional(),
|
|
entityType: z.string().optional(),
|
|
// New fields
|
|
category: categoryEnum.optional(),
|
|
priority: priorityEnum.optional(),
|
|
link: z.string().optional(),
|
|
taskStatus: taskStatusEnum.optional(),
|
|
taskAction: z.string().optional(),
|
|
assigneeId: z.string().optional(),
|
|
dueDate: z.date().optional(),
|
|
channel: channelEnum.optional(),
|
|
senderId: z.string().optional(),
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const currentUserId = ctx.dbUser.id;
|
|
|
|
const n = await ctx.db.notification.create({
|
|
data: {
|
|
userId: input.userId,
|
|
type: input.type,
|
|
title: input.title,
|
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
...(input.entityId !== undefined ? { entityId: input.entityId } : {}),
|
|
...(input.entityType !== undefined ? { entityType: input.entityType } : {}),
|
|
...(input.category !== undefined ? { category: input.category } : {}),
|
|
...(input.priority !== undefined ? { priority: input.priority } : {}),
|
|
...(input.link !== undefined ? { link: input.link } : {}),
|
|
...(input.taskStatus !== undefined ? { taskStatus: input.taskStatus } : {}),
|
|
...(input.taskAction !== undefined ? { taskAction: input.taskAction } : {}),
|
|
...(input.assigneeId !== undefined ? { assigneeId: input.assigneeId } : {}),
|
|
...(input.dueDate !== undefined ? { dueDate: input.dueDate } : {}),
|
|
...(input.channel !== undefined ? { channel: input.channel } : {}),
|
|
senderId: input.senderId ?? currentUserId,
|
|
},
|
|
});
|
|
|
|
emitNotificationCreated(input.userId, n.id);
|
|
|
|
// Emit task-specific events
|
|
if (input.category === "TASK" || input.category === "APPROVAL") {
|
|
emitTaskAssigned(input.userId, n.id);
|
|
}
|
|
|
|
// Email if channel includes email
|
|
const channel = input.channel ?? "in_app";
|
|
if (channel === "email" || channel === "both") {
|
|
void sendNotificationEmail(ctx.db, input.userId, input.title, input.body);
|
|
}
|
|
|
|
return n;
|
|
}),
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// TASK MANAGEMENT
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
/** List tasks for the current user (as owner or assignee) */
|
|
listTasks: protectedProcedure
|
|
.input(
|
|
z.object({
|
|
status: taskStatusEnum.optional(),
|
|
includeAssigned: z.boolean().default(true),
|
|
limit: z.number().min(1).max(100).default(20),
|
|
}),
|
|
)
|
|
.query(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
const userFilter = input.includeAssigned
|
|
? { OR: [{ userId }, { assigneeId: userId }] }
|
|
: { userId };
|
|
|
|
return ctx.db.notification.findMany({
|
|
where: {
|
|
...userFilter,
|
|
category: { in: ["TASK", "APPROVAL"] },
|
|
...(input.status !== undefined ? { taskStatus: input.status } : {}),
|
|
},
|
|
orderBy: [{ priority: "desc" }, { dueDate: "asc" }, { createdAt: "desc" }],
|
|
take: input.limit,
|
|
});
|
|
}),
|
|
|
|
/** Get task counts for the current user */
|
|
taskCounts: protectedProcedure.query(async ({ ctx }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
const now = new Date();
|
|
|
|
const where = {
|
|
OR: [{ userId }, { assigneeId: userId }],
|
|
category: { in: ["TASK" as const, "APPROVAL" as const] },
|
|
};
|
|
|
|
const [open, inProgress, done, dismissed, overdue] = await Promise.all([
|
|
ctx.db.notification.count({ where: { ...where, taskStatus: "OPEN" } }),
|
|
ctx.db.notification.count({ where: { ...where, taskStatus: "IN_PROGRESS" } }),
|
|
ctx.db.notification.count({ where: { ...where, taskStatus: "DONE" } }),
|
|
ctx.db.notification.count({ where: { ...where, taskStatus: "DISMISSED" } }),
|
|
ctx.db.notification.count({
|
|
where: {
|
|
...where,
|
|
taskStatus: { in: ["OPEN", "IN_PROGRESS"] },
|
|
dueDate: { lt: now },
|
|
},
|
|
}),
|
|
]);
|
|
|
|
return { open, inProgress, done, dismissed, overdue };
|
|
}),
|
|
|
|
/** Update task status */
|
|
updateTaskStatus: protectedProcedure
|
|
.input(
|
|
z.object({
|
|
id: z.string(),
|
|
status: taskStatusEnum,
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
// Only allow if userId or assigneeId matches
|
|
const existing = await ctx.db.notification.findFirst({
|
|
where: {
|
|
id: input.id,
|
|
OR: [{ userId }, { assigneeId: userId }],
|
|
},
|
|
});
|
|
|
|
if (!existing) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Task not found or you do not have permission",
|
|
});
|
|
}
|
|
|
|
const isCompleting = input.status === "DONE";
|
|
|
|
const updated = await ctx.db.notification.update({
|
|
where: { id: input.id },
|
|
data: {
|
|
taskStatus: input.status,
|
|
...(isCompleting ? { completedAt: new Date(), completedBy: userId } : {}),
|
|
},
|
|
});
|
|
|
|
if (isCompleting) {
|
|
emitTaskCompleted(existing.userId, updated.id);
|
|
// Also notify assignee if different
|
|
if (existing.assigneeId && existing.assigneeId !== existing.userId) {
|
|
emitTaskCompleted(existing.assigneeId, updated.id);
|
|
}
|
|
} else {
|
|
emitTaskStatusChanged(existing.userId, updated.id);
|
|
if (existing.assigneeId && existing.assigneeId !== existing.userId) {
|
|
emitTaskStatusChanged(existing.assigneeId, updated.id);
|
|
}
|
|
}
|
|
|
|
return updated;
|
|
}),
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// REMINDERS
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
/** Create a personal reminder */
|
|
createReminder: protectedProcedure
|
|
.input(
|
|
z.object({
|
|
title: z.string().min(1).max(200),
|
|
body: z.string().max(2000).optional(),
|
|
remindAt: z.date(),
|
|
recurrence: recurrenceEnum.optional(),
|
|
entityId: z.string().optional(),
|
|
entityType: z.string().optional(),
|
|
link: z.string().optional(),
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
return ctx.db.notification.create({
|
|
data: {
|
|
userId,
|
|
type: "REMINDER",
|
|
category: "REMINDER",
|
|
title: input.title,
|
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
remindAt: input.remindAt,
|
|
nextRemindAt: input.remindAt,
|
|
...(input.recurrence !== undefined ? { recurrence: input.recurrence } : {}),
|
|
...(input.entityId !== undefined ? { entityId: input.entityId } : {}),
|
|
...(input.entityType !== undefined ? { entityType: input.entityType } : {}),
|
|
...(input.link !== undefined ? { link: input.link } : {}),
|
|
channel: "in_app",
|
|
},
|
|
});
|
|
}),
|
|
|
|
/** Update a personal reminder */
|
|
updateReminder: protectedProcedure
|
|
.input(
|
|
z.object({
|
|
id: z.string(),
|
|
title: z.string().min(1).max(200).optional(),
|
|
body: z.string().max(2000).optional(),
|
|
remindAt: z.date().optional(),
|
|
recurrence: recurrenceEnum.nullish(),
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
// Verify ownership
|
|
const existing = await ctx.db.notification.findFirst({
|
|
where: { id: input.id, userId, category: "REMINDER" },
|
|
});
|
|
if (!existing) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Reminder not found or you do not have permission",
|
|
});
|
|
}
|
|
|
|
return ctx.db.notification.update({
|
|
where: { id: input.id },
|
|
data: {
|
|
...(input.title !== undefined ? { title: input.title } : {}),
|
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
...(input.remindAt !== undefined
|
|
? { remindAt: input.remindAt, nextRemindAt: input.remindAt }
|
|
: {}),
|
|
// recurrence can be set to null (clear it) or a new value
|
|
...(input.recurrence !== undefined
|
|
? { recurrence: input.recurrence }
|
|
: {}),
|
|
},
|
|
});
|
|
}),
|
|
|
|
/** Delete a personal reminder */
|
|
deleteReminder: protectedProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
const existing = await ctx.db.notification.findFirst({
|
|
where: { id: input.id, userId, category: "REMINDER" },
|
|
});
|
|
if (!existing) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Reminder not found or you do not have permission",
|
|
});
|
|
}
|
|
|
|
await ctx.db.notification.delete({ where: { id: input.id } });
|
|
}),
|
|
|
|
/** List personal reminders */
|
|
listReminders: protectedProcedure
|
|
.input(z.object({ limit: z.number().min(1).max(100).default(20) }))
|
|
.query(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
return ctx.db.notification.findMany({
|
|
where: { userId, category: "REMINDER" },
|
|
orderBy: { nextRemindAt: "asc" },
|
|
take: input.limit,
|
|
});
|
|
}),
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// BROADCASTS (Manager+)
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
/** Create and send a broadcast notification */
|
|
createBroadcast: managerProcedure
|
|
.input(
|
|
z.object({
|
|
title: z.string().min(1).max(200),
|
|
body: z.string().max(2000).optional(),
|
|
link: z.string().optional(),
|
|
category: categoryEnum.default("NOTIFICATION"),
|
|
priority: priorityEnum.default("NORMAL"),
|
|
channel: channelEnum.default("in_app"),
|
|
targetType: targetTypeEnum,
|
|
targetValue: z.string().optional(),
|
|
scheduledAt: z.date().optional(),
|
|
taskAction: z.string().optional(),
|
|
dueDate: z.date().optional(),
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const senderId = ctx.dbUser.id;
|
|
|
|
// 1. Create broadcast record
|
|
const broadcast = await ctx.db.notificationBroadcast.create({
|
|
data: {
|
|
senderId,
|
|
title: input.title,
|
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
...(input.link !== undefined ? { link: input.link } : {}),
|
|
category: input.category,
|
|
priority: input.priority,
|
|
channel: input.channel,
|
|
targetType: input.targetType,
|
|
...(input.targetValue !== undefined ? { targetValue: input.targetValue } : {}),
|
|
...(input.scheduledAt !== undefined ? { scheduledAt: input.scheduledAt } : {}),
|
|
},
|
|
});
|
|
|
|
// 2. If scheduled in the future, just return the broadcast
|
|
if (input.scheduledAt && input.scheduledAt > new Date()) {
|
|
return broadcast;
|
|
}
|
|
|
|
// 3. Resolve recipients
|
|
const recipientIds = await resolveRecipients(
|
|
input.targetType,
|
|
input.targetValue,
|
|
ctx.db,
|
|
senderId,
|
|
);
|
|
|
|
// 4. Create individual notifications for each recipient
|
|
const isTask = input.category === "TASK" || input.category === "APPROVAL";
|
|
|
|
const notifications = await Promise.all(
|
|
recipientIds.map((recipientUserId) =>
|
|
ctx.db.notification.create({
|
|
data: {
|
|
userId: recipientUserId,
|
|
type: `BROADCAST_${input.category}`,
|
|
title: input.title,
|
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
...(input.link !== undefined ? { link: input.link } : {}),
|
|
category: input.category,
|
|
priority: input.priority,
|
|
channel: input.channel,
|
|
sourceId: broadcast.id,
|
|
senderId,
|
|
...(isTask ? { taskStatus: "OPEN" as const } : {}),
|
|
...(input.taskAction !== undefined ? { taskAction: input.taskAction } : {}),
|
|
...(input.dueDate !== undefined ? { dueDate: input.dueDate } : {}),
|
|
},
|
|
}),
|
|
),
|
|
);
|
|
|
|
// 5. Update broadcast with sent info
|
|
await ctx.db.notificationBroadcast.update({
|
|
where: { id: broadcast.id },
|
|
data: {
|
|
sentAt: new Date(),
|
|
recipientCount: notifications.length,
|
|
},
|
|
});
|
|
|
|
// 6. Emit SSE events
|
|
for (const n of notifications) {
|
|
emitNotificationCreated(n.userId, n.id);
|
|
if (isTask) {
|
|
emitTaskAssigned(n.userId, n.id);
|
|
}
|
|
}
|
|
emitBroadcastSent(broadcast.id, notifications.length);
|
|
|
|
// 7. Send emails if channel includes email (non-blocking)
|
|
if (input.channel === "email" || input.channel === "both") {
|
|
for (const n of notifications) {
|
|
void sendNotificationEmail(ctx.db, n.userId, input.title, input.body);
|
|
}
|
|
}
|
|
|
|
return { ...broadcast, recipientCount: notifications.length, sentAt: new Date() };
|
|
}),
|
|
|
|
/** List broadcasts */
|
|
listBroadcasts: managerProcedure
|
|
.input(z.object({ limit: z.number().min(1).max(50).default(20) }))
|
|
.query(async ({ ctx, input }) => {
|
|
return ctx.db.notificationBroadcast.findMany({
|
|
orderBy: { createdAt: "desc" },
|
|
take: input.limit,
|
|
include: {
|
|
sender: { select: { id: true, name: true, email: true } },
|
|
},
|
|
});
|
|
}),
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// TASK CREATION (Manager+)
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
/** Create a task for a specific user */
|
|
createTask: managerProcedure
|
|
.input(
|
|
z.object({
|
|
userId: z.string(),
|
|
title: z.string().min(1).max(200),
|
|
body: z.string().max(2000).optional(),
|
|
priority: priorityEnum.default("NORMAL"),
|
|
dueDate: z.date().optional(),
|
|
taskAction: z.string().optional(),
|
|
entityId: z.string().optional(),
|
|
entityType: z.string().optional(),
|
|
link: z.string().optional(),
|
|
channel: channelEnum.default("in_app"),
|
|
}),
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const senderId = ctx.dbUser.id;
|
|
|
|
const n = await ctx.db.notification.create({
|
|
data: {
|
|
userId: input.userId,
|
|
type: "TASK_CREATED",
|
|
category: "TASK",
|
|
taskStatus: "OPEN",
|
|
title: input.title,
|
|
priority: input.priority,
|
|
senderId,
|
|
channel: input.channel,
|
|
...(input.body !== undefined ? { body: input.body } : {}),
|
|
...(input.dueDate !== undefined ? { dueDate: input.dueDate } : {}),
|
|
...(input.taskAction !== undefined ? { taskAction: input.taskAction } : {}),
|
|
...(input.entityId !== undefined ? { entityId: input.entityId } : {}),
|
|
...(input.entityType !== undefined ? { entityType: input.entityType } : {}),
|
|
...(input.link !== undefined ? { link: input.link } : {}),
|
|
},
|
|
});
|
|
|
|
emitNotificationCreated(input.userId, n.id);
|
|
emitTaskAssigned(input.userId, n.id);
|
|
|
|
// Send email if channel includes email
|
|
if (input.channel === "email" || input.channel === "both") {
|
|
void sendNotificationEmail(ctx.db, input.userId, input.title, input.body);
|
|
}
|
|
|
|
return n;
|
|
}),
|
|
|
|
/** Reassign a task to another user */
|
|
assignTask: managerProcedure
|
|
.input(z.object({ id: z.string(), assigneeId: z.string() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
const existing = await ctx.db.notification.findUnique({
|
|
where: { id: input.id },
|
|
});
|
|
|
|
if (!existing) {
|
|
throw new TRPCError({ code: "NOT_FOUND", message: "Task not found" });
|
|
}
|
|
|
|
if (existing.category !== "TASK" && existing.category !== "APPROVAL") {
|
|
throw new TRPCError({
|
|
code: "BAD_REQUEST",
|
|
message: "Only tasks and approvals can be assigned",
|
|
});
|
|
}
|
|
|
|
const updated = await ctx.db.notification.update({
|
|
where: { id: input.id },
|
|
data: { assigneeId: input.assigneeId },
|
|
});
|
|
|
|
emitTaskAssigned(input.assigneeId, updated.id);
|
|
|
|
return updated;
|
|
}),
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
// DELETE
|
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
|
|
/** Delete own notification */
|
|
delete: protectedProcedure
|
|
.input(z.object({ id: z.string() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
const userId = await resolveUserId(ctx);
|
|
|
|
const existing = await ctx.db.notification.findFirst({
|
|
where: { id: input.id, userId },
|
|
});
|
|
|
|
if (!existing) {
|
|
throw new TRPCError({
|
|
code: "NOT_FOUND",
|
|
message: "Notification not found",
|
|
});
|
|
}
|
|
|
|
// Cannot delete tasks created by others (senderId differs)
|
|
if (
|
|
(existing.category === "TASK" || existing.category === "APPROVAL") &&
|
|
existing.senderId &&
|
|
existing.senderId !== userId
|
|
) {
|
|
throw new TRPCError({
|
|
code: "FORBIDDEN",
|
|
message: "Cannot delete tasks created by others",
|
|
});
|
|
}
|
|
|
|
await ctx.db.notification.delete({ where: { id: input.id } });
|
|
}),
|
|
});
|