Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Also send clicks and links limit alerts to Slack when a workspace has the integration installed.

Kiran Kb51aef6e151f
diff --git a/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts b/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts
index 530b01d2d0..6bebe79d30 100644
--- a/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts
+++ b/apps/web/app/(ee)/api/cron/streams/update-workspace-links-usage/route.ts
@@ -1,5 +1,8 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { sendLimitEmail } from "@/lib/cron/send-limit-email";
+import {
+ getSlackWebhooks,
+ sendWorkspaceLimitAlert,
+} from "@/lib/cron/send-limit-alert";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
import { prisma } from "@/lib/prisma";
import { WorkspaceProps } from "@/lib/types";
@@ -186,49 +189,54 @@ const processWorkspaceLinksUsageBatch = () =>
let notificationsSent = 0;
if (workspaceIds.length > 0) {
- const sentEmails = await prisma.sentEmail.findMany({
- where: {
- projectId: {
- in: workspaceIds,
- },
- type: {
- in: ["firstLinksLimitEmail", "secondLinksLimitEmail"],
- },
- },
- select: {
- projectId: true,
- type: true,
- },
- });
-
- const sentEmailSet = new Set(
- sentEmails.map((email) => `${email.projectId}:${email.type}`),
- );
-
- const users = await prisma.user.findMany({
- where: {
- projects: {
- some: {
+ const [sentEmails, users, slackWebhookUrlByWorkspace] =
+ await Promise.all([
+ prisma.sentEmail.findMany({
+ where: {
projectId: {
in: workspaceIds,
},
+ type: {
+ in: ["firstLinksLimitEmail", "secondLinksLimitEmail"],
+ },
},
- },
- },
- select: {
- email: true,
- projects: {
+ select: {
+ projectId: true,
+ type: true,
+ },
+ }),
+
+ prisma.user.findMany({
where: {
- projectId: {
- in: workspaceIds,
+ projects: {
+ some: {
+ projectId: {
+ in: workspaceIds,
+ },
+ },
},
},
select: {
- projectId: true,
+ email: true,
+ projects: {
+ where: {
+ projectId: {
+ in: workspaceIds,
+ },
+ },
+ select: {
+ projectId: true,
+ },
+ },
},
- },
- },
- });
+ }),
+
+ getSlackWebhooks(workspaceIds),
+ ]);
+
+ const sentEmailSet = new Set(
+ sentEmails.map((email) => `${email.projectId}:${email.type}`),
+ );
const emailsByWorkspace = new Map<string, string[]>();
for (const user of users) {
@@ -262,10 +270,11 @@ const processWorkspaceLinksUsageBatch = () =>
}
await Promise.allSettled([
- sendLimitEmail({
+ sendWorkspaceLimitAlert({
emails,
workspace: workspace as WorkspaceProps,
type: emailType,
+ slackWebhookUrl: slackWebhookUrlByWorkspace.get(workspace.id),
}),
log({
message: `*${workspace.slug}* has used ${percentage.toString()}% of its links limit for the month.`,
diff --git a/apps/web/app/(ee)/api/cron/usage/utils.ts b/apps/web/app/(ee)/api/cron/usage/utils.ts
index 7be35daf02..a141605390 100644
--- a/apps/web/app/(ee)/api/cron/usage/utils.ts
+++ b/apps/web/app/(ee)/api/cron/usage/utils.ts
@@ -1,6 +1,9 @@
import { getAnalytics } from "@/lib/analytics/get-analytics";
import { qstash } from "@/lib/cron";
-import { sendLimitEmail } from "@/lib/cron/send-limit-email";
+import {
+ getSlackWebhooks,
+ sendWorkspaceLimitAlert,
+} from "@/lib/cron/send-limit-alert";
import { prisma } from "@/lib/prisma";
import { WorkspaceProps } from "@/lib/types";
import { sendBatchEmail } from "@dub/email";
@@ -208,11 +211,16 @@ export const updateUsage = async () => {
({ usage, usageLimit }) => usage > usageLimit,
);
+ const slackWebhookByWorkspace = await getSlackWebhooks(
+ exceedingUsage.map(({ id }) => id),
+ );
+
// Send email to notify overages
await Promise.allSettled(
exceedingUsage.map(async (workspace) => {
const { slug, plan, usage, usageLimit, users, sentEmails } = workspace;
const emails = users.map((user) => user.user.email) as string[];
+ const slackWebhookUrl = slackWebhookByWorkspace.get(workspace.id);
await log({
message: `*${slug}* is over their *${capitalize(
@@ -227,10 +235,11 @@ export const updateUsage = async () => {
(email) => email.type === "firstUsageLimitEmail",
);
if (!sentFirstUsageLimitEmail) {
- sendLimitEmail({
+ sendWorkspaceLimitAlert({
emails,
workspace: workspace as unknown as WorkspaceProps,
type: "firstUsageLimitEmail",
+ slackWebhookUrl,
});
} else {
const sentSecondUsageLimitEmail = sentEmails.some(
@@ -243,10 +252,11 @@ export const updateUsage = async () => {
(1000 * 3600 * 24),
);
if (daysSinceFirstEmail >= 3) {
- sendLimitEmail({
+ sendWorkspaceLimitAlert({
emails,
workspace: workspace as unknown as WorkspaceProps,
type: "secondUsageLimitEmail",
+ slackWebhookUrl,
});
}
}
diff --git a/apps/web/lib/cron/send-limit-alert.ts b/apps/web/lib/cron/send-limit-alert.ts
new file mode 100644
index 0000000000..05337df7f9
--- /dev/null
+++ b/apps/web/lib/cron/send-limit-alert.ts
@@ -0,0 +1,245 @@
+import { prisma } from "@/lib/prisma";
+import { sendBatchEmail } from "@dub/email";
+import ClicksExceeded from "@dub/email/templates/clicks-exceeded";
+import LinksLimitAlert from "@dub/email/templates/links-limit";
+import {
+ APP_DOMAIN,
+ capitalize,
+ nFormatter,
+ SLACK_INTEGRATION_ID,
+} from "@dub/utils";
+import { WorkspaceProps } from "../types";
+
+type LimitEmailType =
+ | "firstUsageLimitEmail"
+ | "secondUsageLimitEmail"
+ | "firstLinksLimitEmail"
+ | "secondLinksLimitEmail";
+
+// Return a map of workspace IDs to Slack webhook URLs
+export const getSlackWebhooks = async (workspaceIds: string[]) => {
+ const slackWebhookByWorkspace = new Map<string, string>();
+
+ if (workspaceIds.length === 0) {
+ return slackWebhookByWorkspace;
+ }
+
+ const slackInstallations = await prisma.installedIntegration.findMany({
+ where: {
+ projectId: {
+ in: workspaceIds,
+ },
+ integrationId: SLACK_INTEGRATION_ID,
+ },
+ select: {
+ projectId: true,
+ webhooks: {
+ where: {
+ disabledAt: null,
+ },
+ select: {
+ url: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ take: 1,
+ },
+ },
+ });
+
+ for (const installation of slackInstallations) {
+ const url = installation.webhooks[0]?.url;
+
+ if (url) {
+ slackWebhookByWorkspace.set(installation.projectId, url);
+ }
+ }
+
+ return slackWebhookByWorkspace;
+};
+
+const formatLimitSlackMessage = ({
+ workspace,
+ type,
+}: {
+ workspace: WorkspaceProps;
+ type: LimitEmailType;
+}) => {
+ const billingUrl = `${APP_DOMAIN}/${workspace.slug}/settings/billing`;
+ const workspaceUrl = `${APP_DOMAIN}/${workspace.slug}`;
+
+ if (type.endsWith("UsageLimitEmail")) {
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*Clicks Limit Exceeded*`,
+ },
+ },
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `Your Dub workspace, <${workspaceUrl}|*${workspace.name}*>, has exceeded the *${capitalize(workspace.plan)} Plan* limit of *${nFormatter(workspace.usageLimit)} link clicks/month*. You have used *${nFormatter(workspace.usage, { digits: 2 })} link clicks* across all your links in your current billing cycle.`,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Usage*\n${nFormatter(workspace.usage, { digits: 2 })}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Limit*\n${nFormatter(workspace.usageLimit)}`,
+ },
+ ],
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: `<${billingUrl}|Upgrade your plan>`,
+ },
+ ],
+ },
+ ],
+ };
+ }
+
+ const percentage = Math.round(
+ (workspace.linksUsage / workspace.linksLimit) * 100,
+ );
+
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*Links Limit Alert*`,
+ },
+ },
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `Your Dub workspace, <${workspaceUrl}|*${workspace.name}*>, has used *${percentage}%* of the monthly links limit included in the ${capitalize(workspace.plan)} plan. You have created a total of *${nFormatter(workspace.linksUsage, { full: true })} links* (out of a maximum of ${nFormatter(workspace.linksLimit, { full: true })} links) in your current billing cycle.`,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Usage*\n${nFormatter(workspace.linksUsage, { full: true })} (${percentage}%)`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Limit*\n${nFormatter(workspace.linksLimit, { full: true })}`,
+ },
+ ],
+ },
+ {
+ type: "context",
+ elements: [
+ {
+ type: "mrkdwn",
+ text: `<${billingUrl}|Upgrade your plan>`,
+ },
+ ],
+ },
+ ],
+ };
+};
+
+const sendLimitSlackAlert = async ({
+ workspace,
+ type,
+ slackWebhookUrl,
+}: {
+ workspace: WorkspaceProps;
+ type: LimitEmailType;
+ slackWebhookUrl: string;
+}) => {
+ try {
+ const response = await fetch(slackWebhookUrl, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(formatLimitSlackMessage({ workspace, type })),
+ });
+
+ if (!response.ok) {
+ console.error(
+ `Failed to send usage limit Slack alert for workspace ${workspace.id}: ${response.status} ${response.statusText}`,
+ );
+ }
+ } catch (error) {
+ console.error(
+ `Failed to send usage limit Slack alert for workspace ${workspace.id}:`,
+ error,
+ );
+ }
+};
+
+export const sendWorkspaceLimitAlert = async ({
+ emails,
+ workspace,
+ type,
+ slackWebhookUrl,
+}: {
+ emails: string[];
+ workspace: WorkspaceProps;
+ type: LimitEmailType;
+ slackWebhookUrl?: string | null;
+}) => {
+ const percentage = Math.round(
+ (workspace.linksUsage / workspace.linksLimit) * 100,
+ );
+
+ return await Promise.allSettled([
+ sendBatchEmail(
+ emails.map((email) => ({
+ subject: type.endsWith("UsageLimitEmail")
+ ? "Dub Alert: Clicks Limit Exceeded"
+ : `Dub Alert: ${workspace.name} has used ${percentage.toString()}% of its links limit for the month.`,
+ to: email,
+ react: type.endsWith("UsageLimitEmail")
+ ? ClicksExceeded({
+ email,
+ workspace,
+ type: type as "firstUsageLimitEmail" | "secondUsageLimitEmail",
+ })
+ : LinksLimitAlert({
+ email,
+ workspace,
+ }),
+ variant: "notifications",
+ })),
+ ),
+
+ prisma.sentEmail.create({
+ data: {
+ projectId: workspace.id,
+ type,
+ },
+ }),
+
+ ...(slackWebhookUrl
+ ? [
+ sendLimitSlackAlert({
+ workspace,
+ type,
+ slackWebhookUrl,
+ }),
+ ]
+ : []),
+ ]);
+};
diff --git a/apps/web/lib/cron/send-limit-email.ts b/apps/web/lib/cron/send-limit-email.ts
deleted file mode 100644
index 1f502016f1..0000000000
--- a/apps/web/lib/cron/send-limit-email.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { sendBatchEmail } from "@dub/email";
-import ClicksExceeded from "@dub/email/templates/clicks-exceeded";
-import LinksLimitAlert from "@dub/email/templates/links-limit";
-import { WorkspaceProps } from "../types";
-
-export const sendLimitEmail = async ({
- emails,
- workspace,
- type,
-}: {
- emails: string[];
- workspace: WorkspaceProps;
- type:
- | "firstUsageLimitEmail"
- | "secondUsageLimitEmail"
- | "firstLinksLimitEmail"
- | "secondLinksLimitEmail";
-}) => {
- const percentage = Math.round(
- (workspace.linksUsage / workspace.linksLimit) * 100,
- );
-
- return await Promise.allSettled([
- sendBatchEmail(
- emails.map((email) => ({
- subject: type.endsWith("UsageLimitEmail")
- ? "Dub Alert: Clicks Limit Exceeded"
- : `Dub Alert: ${workspace.name} has used ${percentage.toString()}% of its links limit for the month.`,
- to: email,
- react: type.endsWith("UsageLimitEmail")
- ? ClicksExceeded({
- email,
- workspace,
- type: type as "firstUsageLimitEmail" | "secondUsageLimitEmail",
- })
- : LinksLimitAlert({
- email,
- workspace,
- }),
- variant: "notifications",
- })),
- ),
- prisma.sentEmail.create({
- data: {
- projectId: workspace.id,
- type,
- },
- }),
- ]);
-};