Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const createOrganizationAction = authActionClient

const hasVercelConfig = Boolean(
process.env.NEXT_PUBLIC_VERCEL_URL &&
process.env.VERCEL_AUTH_TOKEN &&
process.env.VERCEL_ACCESS_TOKEN &&
process.env.VERCEL_TEAM_ID &&
process.env.VERCEL_PROJECT_ID
);
Expand Down
2 changes: 0 additions & 2 deletions apps/app/src/components/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { getI18n } from "@/locales/server";
import { Button } from "@bubba/ui/button";
import { Icons } from "@bubba/ui/icons";
import { Skeleton } from "@bubba/ui/skeleton";
import { Inbox } from "@novu/react";
import { useSession } from "next-auth/react";
import Link from "next/link";
import { Suspense } from "react";
import { AssistantButton } from "./assistant/button";
Expand Down
95 changes: 52 additions & 43 deletions apps/app/src/components/notification-center.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,70 +28,73 @@ function NotificationItem({
description,
createdAt,
recordId,
from,
to,
markMessageAsRead,
type,
}: {
id: string;
setOpen: (open: boolean) => void;
description: string;
description: string | undefined;
createdAt: string;
recordId?: string;
from?: string;
to?: string;
recordId: string | undefined;
from: string | undefined;
to: string | undefined;
markMessageAsRead: (id: string) => void;
type?: string;
type: string | undefined;
}) {
return (
<div className="flex items-between justify-between space-x-4 px-3 py-3 hover:bg-secondary">
<Link
className="flex items-between justify-between space-x-4"
onClick={() => setOpen(false)}
href={recordId ? `/tasks/${recordId}` : "#"}
>
<div>
<div className="h-9 w-9 flex items-center justify-center space-y-0 border rounded-full">
<Icons.Match />
</div>
</div>
<div>
<p className="text-sm">{description}</p>
<span className="text-xs text-muted">
{formatDistanceToNow(new Date(createdAt))} ago
</span>
</div>
</Link>
{markMessageAsRead && (
<div>
<Button
size="icon"
variant="secondary"
className="rounded-full bg-transparent hover:bg-[#1A1A1A]"
onClick={() => markMessageAsRead(id)}
switch (type) {
case "task":
return (
<div className="flex items-between justify-between space-x-4 px-3 py-3 hover:bg-secondary">
<Link
className="flex items-between justify-between space-x-4"
onClick={() => setOpen(false)}
href={`${recordId}`}
>
<Icons.Inventory2 />
</Button>
<div>
<div className="h-9 w-9 flex items-center justify-center space-y-0 border rounded-full">
<Icons.Risk />
</div>
</div>
<div>
<p className="text-sm">{description}</p>
<span className="text-xs text-muted">
{formatDistanceToNow(new Date(createdAt))} ago
</span>
</div>
</Link>
{markMessageAsRead && (
<div>
<Button
size="icon"
variant="secondary"
className="rounded-full bg-transparent hover:bg-[#1A1A1A]"
onClick={() => markMessageAsRead(id)}
>
<Icons.Inventory2 />
</Button>
</div>
)}
</div>
)}
</div>
);
);
default:
return null;
}
}

export function NotificationCenter() {
const t = useI18n();

const [isOpen, setOpen] = useState(false);

const {
hasUnseenNotifications,
notifications,
markMessageAsRead,
markAllMessagesAsSeen,
markAllMessagesAsRead,
subscriberId,
} = useNotifications();

console.log(subscriberId);
console.log(notifications);

const unreadNotifications = notifications.filter(
(notification) => !notification.read,
);
Expand Down Expand Up @@ -164,9 +167,12 @@ export function NotificationCenter() {
id={notification.id}
markMessageAsRead={markMessageAsRead}
setOpen={setOpen}
description={notification.payload.description || ""}
description={notification.payload.description}
createdAt={notification.createdAt}
recordId={notification.payload.recordId}
type={notification.payload.type}
from={notification.payload?.from}
to={notification.payload?.to}
/>
);
})}
Expand Down Expand Up @@ -203,9 +209,12 @@ export function NotificationCenter() {
key={notification.id}
id={notification.id}
setOpen={setOpen}
description={notification.payload.description || ""}
description={notification.payload.description}
createdAt={notification.createdAt}
recordId={notification.payload.recordId}
type={notification.payload.type}
from={notification.payload?.from}
to={notification.payload?.to}
markMessageAsRead={markMessageAsRead}
/>
);
Expand Down
4 changes: 2 additions & 2 deletions apps/app/src/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const env = createEnv({
UPLOADTHING_SECRET: z.string(),
DISCORD_WEBHOOK_URL: z.string(),
TRIGGER_SECRET_KEY: z.string(),
VERCEL_AUTH_TOKEN: z.string().optional(),
VERCEL_ACCESS_TOKEN: z.string().optional(),
VERCEL_TEAM_ID: z.string().optional(),
VERCEL_PROJECT_ID: z.string().optional(),
},
Expand Down Expand Up @@ -46,7 +46,7 @@ export const env = createEnv({
TRIGGER_SECRET_KEY: process.env.TRIGGER_SECRET_KEY,
NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
VERCEL_AUTH_TOKEN: process.env.VERCEL_AUTH_TOKEN,
VERCEL_ACCESS_TOKEN: process.env.VERCEL_ACCESS_TOKEN,
VERCEL_TEAM_ID: process.env.VERCEL_TEAM_ID,
VERCEL_PROJECT_ID: process.env.VERCEL_PROJECT_ID,
NEXT_PUBLIC_VERCEL_URL: process.env.NEXT_PUBLIC_VERCEL_URL,
Expand Down
95 changes: 95 additions & 0 deletions apps/app/src/jobs/tasks/notifications/risk-task-notifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { db } from "@bubba/db";
import {
NotificationTypes,
TriggerEvents,
trigger,
} from "@bubba/notifications";
import { logger, schedules } from "@trigger.dev/sdk/v3";
import { formatDistance } from "date-fns";

export const sendRiskTaskNotifications = schedules.task({
id: "send-risk-task-notifications",
run: async () => {
const now = new Date();
const upcomingThreshold = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

logger.info(
`Sending risk task notifications from now: ${now} to ${upcomingThreshold}`,
);

const tasks = await db.riskMitigationTask.findMany({
where: {
dueDate: { gte: now, lte: upcomingThreshold },
status: { in: ["open", "pending"] },
notifiedAt: null,
},
select: {
id: true,
dueDate: true,
notifiedAt: true,
riskId: true,
title: true,
owner: {
select: {
id: true,
email: true,
name: true,
image: true,
organizationId: true,
},
},
},
});

const notifiedTasks = [];

for (const task of tasks) {
const owner = task.owner;

const timeUntilDue = task.dueDate
? formatDistance(task.dueDate, new Date(), {
addSuffix: true,
})
: "soon";

try {
if (!owner || !owner.email || !owner.organizationId) {
logger.warn(`Skipping task ${task.id} - owner ${owner?.id} missing email or organizationId`);
continue;
}

await db.riskMitigationTask.update({
where: { id: task.id },
data: { notifiedAt: new Date() },
});
Comment on lines +61 to +64
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using a transaction for atomic updates.

The task update and notification trigger should be atomic to prevent duplicate notifications if the trigger fails.

       try {
+        await db.$transaction(async (tx) => {
-        await db.riskMitigationTask.update({
+        await tx.riskMitigationTask.update({
           where: { id: task.id },
           data: { notifiedAt: new Date() },
         });

         await trigger({
           name: TriggerEvents.TaskReminderInApp,
           // ... rest of the trigger config
         });
+        });

Also applies to: 66-80


await trigger({
name: TriggerEvents.TaskReminderInApp,
user: {
subscriberId: `${owner.organizationId}_${owner.id}`,
email: owner.email,
fullName: owner.name,
image: owner.image,
organizationId: owner.organizationId,
},
payload: {
description: `${task.title} is due ${timeUntilDue}`,
recordId: `/risk/${task.riskId}/tasks/${task.id}`,
type: NotificationTypes.Task,
},
});


notifiedTasks.push(task.id);
} catch (error) {
logger.error(
`Error processing task ${task.id} for ${owner?.email}: ${error}`,
);
}
}

if (notifiedTasks.length) {
logger.info(`Sent notifications for tasks: ${notifiedTasks.join(", ")}`);
}
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import TaskReminderEmail from "@bubba/email/emails/reminders/task-reminder";
import { TriggerEvents, trigger } from "@bubba/notifications";
import { render } from "@react-email/render";

interface Props {
owner: {
id: string;
fullName?: string;
email: string;
organizationId: string;
};
task: {
recordId: string;
dueDate: string;
};
}

export async function sendTaskEmailNotification({ owner, task }: Props) {
try {
const html = await render(
<TaskReminderEmail
email={owner.email}
name={owner.fullName ?? "there"}
dueDate={task.dueDate}
recordId={task.recordId}
/>,
);

const triggerData = {
name: TriggerEvents.TaskReminderEmail,
payload: {
subject: "Task Reminder",
html,
},
replyTo: owner.email,
user: {
subscriberId: `${owner.organizationId}_${owner.id}`,
organizationId: owner.organizationId,
email: owner.email,
fullName: owner.fullName,
},
};

await trigger(triggerData);
} catch (error) {
console.error("Failed to send task email notification: ", error);
throw error;
}
}
12 changes: 6 additions & 6 deletions apps/app/src/lib/domains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const addDomainToVercel = async (domain: string) => {
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
Authorization: `Bearer ${process.env.VERCEL_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
Expand All @@ -29,7 +29,7 @@ export const removeDomainFromVercelProject = async (domain: string) => {
}`,
{
headers: {
Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
Authorization: `Bearer ${process.env.VERCEL_ACCESS_TOKEN}`,
},
method: "DELETE",
},
Expand All @@ -42,7 +42,7 @@ export const removeDomainFromVercelTeam = async (domain: string) => {
}`,
{
headers: {
Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
Authorization: `Bearer ${process.env.VERCEL_ACCESS_TOKEN}`,
},
method: "DELETE",
},
Expand All @@ -59,7 +59,7 @@ export const getDomainResponse = async (
{
method: "GET",
headers: {
Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
Authorization: `Bearer ${process.env.VERCEL_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
},
Expand All @@ -77,7 +77,7 @@ export const getConfigResponse = async (
{
method: "GET",
headers: {
Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
Authorization: `Bearer ${process.env.VERCEL_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
},
Expand All @@ -94,7 +94,7 @@ export const verifyDomain = async (
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
Authorization: `Bearer ${process.env.VERCEL_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
},
Expand Down
2 changes: 2 additions & 0 deletions apps/app/trigger.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PrismaInstrumentation } from "@prisma/instrumentation";
import { syncVercelEnvVars } from "@trigger.dev/build/extensions/core";
import { prismaExtension } from "@trigger.dev/build/extensions/prisma";
import { puppeteer } from "@trigger.dev/build/extensions/puppeteer";
import { defineConfig } from "@trigger.dev/sdk/v3";
Expand All @@ -15,6 +16,7 @@ export default defineConfig({
schema: "../../packages/db/prisma/schema.prisma",
}),
puppeteer(),
syncVercelEnvVars(),
],
},
retries: {
Expand Down
Binary file modified bun.lockb
Binary file not shown.
Loading