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.

update slack template

Kiran Kc66ad4501f9e
diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.ts
index da68756419..e1094a3043 100644
--- a/apps/web/lib/webhook/qstash.ts
+++ b/apps/web/lib/webhook/qstash.ts
@@ -1,10 +1,11 @@
import { qstash } from "@/lib/cron";
import { webhookPayloadSchema } from "@/lib/webhook/schemas";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
-import { Webhook } from "@prisma/client";
+import { Webhook, WebhookReceiver } from "@prisma/client";
import { WebhookTrigger } from "../types";
import z from "../zod";
import { createWebhookSignature } from "./signature";
+import { generateSlackMessage } from "./slack-templates";
import { prepareWebhookPayload } from "./transform";
import { EventDataProps } from "./types";
import { identifyWebhookReceiver } from "./utils";
@@ -33,7 +34,7 @@ export const sendWebhooks = async ({
};
// Publish webhook event to QStash
-export const publishWebhookEventToQStash = async ({
+const publishWebhookEventToQStash = async ({
webhook,
payload,
}: {
@@ -45,12 +46,13 @@ export const publishWebhookEventToQStash = async ({
callbackUrl.searchParams.append("eventId", payload.id);
callbackUrl.searchParams.append("event", payload.event);
- const signature = await createWebhookSignature(webhook.secret, payload);
const receiver = identifyWebhookReceiver(webhook.url);
+ const finalPayload = transformPayload({ payload, receiver });
+ const signature = await createWebhookSignature(webhook.secret, finalPayload);
const response = await qstash.publishJSON({
url: webhook.url,
- body: payload,
+ body: finalPayload,
headers: {
"Dub-Signature": signature,
"Upstash-Hide-Headers": "true",
@@ -66,7 +68,17 @@ export const publishWebhookEventToQStash = async ({
return response;
};
-// const finalPayload =
-// receiver === "slack"
-// ? generateLinkTemplate(payload.data, payload.event)
-// : payload;
+// Transform the payload for the receiver
+const transformPayload = ({
+ payload,
+ receiver,
+}: {
+ payload: z.infer<typeof webhookPayloadSchema>;
+ receiver: WebhookReceiver;
+}) => {
+ if (receiver === "slack") {
+ return generateSlackMessage(payload.event, payload.data);
+ }
+
+ return payload;
+};
diff --git a/apps/web/lib/webhook/sample-events/link-clicked.json b/apps/web/lib/webhook/sample-events/link-clicked.json
index 1e4c9ccd5a..b1c6115b74 100644
--- a/apps/web/lib/webhook/sample-events/link-clicked.json
+++ b/apps/web/lib/webhook/sample-events/link-clicked.json
@@ -1,27 +1,28 @@
{
- "timestamp": "2024-08-30T10:16:12.124Z",
- "clickId": "d0UtZqE0BZuBPrJS",
- "url": "https://github.com/dubinc/dub",
- "ip": "63.141.57.109",
- "continent": "NA",
- "country": "US",
- "city": "San Francisco",
- "device": "Desktop",
- "browser": "Chrome",
- "os": "Mac OS",
- "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
- "bot": false,
- "qr": false,
- "referer": "(direct)",
+ "click": {
+ "id": "CvQhPEXvqRYG4mqL",
+ "url": "https://github.com/dubinc",
+ "continent": "AS",
+ "country": "IN",
+ "city": "Thalassery",
+ "device": "Desktop",
+ "browser": "Chrome",
+ "os": "Mac OS",
+ "referer": "(direct)",
+ "refererUrl": "(direct)",
+ "qr": false,
+ "ip": "103.181.40.30"
+ },
"link": {
- "id": "cm0faqkyn0001txvfwjfeq7gl",
+ "id": "cm2a01bzt0001jc3nzycksls1",
"domain": "dub.sh",
- "key": "79ys3WA",
+ "key": "qviSU44",
+ "url": "https://github.com/dubinc",
+ "trackConversion": false,
"externalId": null,
- "url": "https://github.com/dubinc/dub",
- "trackConversion": true,
+ "identifier": null,
"archived": false,
- "expiresAt": null,
+ "expiresAt": "1970-01-01T00:00:00.000Z",
"expiredUrl": null,
"password": null,
"proxy": false,
@@ -35,22 +36,26 @@
"android": null,
"geo": null,
"publicStats": false,
+ "tagId": null,
+ "tags": [],
+ "webhookIds": [],
"comments": null,
- "shortLink": "https://dub.sh/79ys3WA",
- "qrCode": "https://api.dub.co/qr?url=https://dub.sh/79ys3WA?qr=1",
+ "shortLink": "https://dub.sh/qviSU44",
+ "qrCode": "https://api.dub.co/qr?url=https://dub.sh/qviSU44?qr=1",
"utm_source": null,
"utm_medium": null,
"utm_campaign": null,
"utm_term": null,
"utm_content": null,
- "userId": "cm022rkcw0000ikt14mscg9sg",
- "workspaceId": "ws_cm022sis60003ikt1syy7kfhl",
- "clicks": 11,
- "lastClicked": "2024-08-30T07:45:09.000Z",
- "leads": 6,
- "sales": 10,
- "saleAmount": 200000,
- "createdAt": "2024-08-29T13:03:59.098Z",
- "updatedAt": "2024-08-30T10:16:12.126Z"
+ "userId": "clxz1q7c7000hbqx5ckv4r82h",
+ "workspaceId": "ws_clrei1gld0002vs9mzn93p8ik",
+ "clicks": 1,
+ "lastClicked": "2024-10-15T06:35:33.000Z",
+ "leads": 0,
+ "sales": 0,
+ "saleAmount": 0,
+ "createdAt": "2024-10-15T05:24:58.744Z",
+ "updatedAt": "2024-10-15T05:24:58.744Z",
+ "projectId": "clrei1gld0002vs9mzn93p8ik"
}
}
diff --git a/apps/web/lib/webhook/sample-events/sale-created.json b/apps/web/lib/webhook/sample-events/sale-created.json
index 906774dd3b..e73332ca05 100644
--- a/apps/web/lib/webhook/sample-events/sale-created.json
+++ b/apps/web/lib/webhook/sample-events/sale-created.json
@@ -60,5 +60,11 @@
"saleAmount": 20000,
"createdAt": "2024-08-29T13:03:59.098Z",
"updatedAt": "2024-08-30T09:57:50.891Z"
+ },
+ "sale": {
+ "amount": 4500,
+ "currency": "usd",
+ "paymentProcessor": "stripe",
+ "invoiceId": null
}
}
diff --git a/apps/web/lib/webhook/slack-templates.ts b/apps/web/lib/webhook/slack-templates.ts
index 87bd6a20f6..86125546f5 100644
--- a/apps/web/lib/webhook/slack-templates.ts
+++ b/apps/web/lib/webhook/slack-templates.ts
@@ -1,10 +1,18 @@
import { LinkWebhookEvent } from "dub/models/components";
import { WebhookTrigger } from "../types";
+import {
+ ClickEventWebhookData,
+ LeadEventWebhookData,
+ SaleEventWebhookData,
+} from "./types";
-export const generateLinkTemplate = (
- data: LinkWebhookEvent["data"],
- eventType: WebhookTrigger,
-) => {
+const createLinkTemplate = ({
+ data,
+ eventType,
+}: {
+ data: LinkWebhookEvent["data"];
+ eventType: WebhookTrigger;
+}) => {
const eventMessages = {
"link.created": "*New short link created*",
"link.updated": "*Short link updated*",
@@ -37,4 +45,137 @@ export const generateLinkTemplate = (
};
};
-const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+const clickLinkTemplate = ({ data }: { data: ClickEventWebhookData }) => {
+ const { link, click } = data;
+
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*Someone clicked your short link* :eyes:`,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Country*\n${click.country}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Referrer*\n${click.referer}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Short link*\n<${link.shortLink}|${link.shortLink}>`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Destination URL*\n<${link.url}|${link.url}>`,
+ },
+ ],
+ },
+ ],
+ };
+};
+
+const createLeadTemplate = ({ data }: { data: LeadEventWebhookData }) => {
+ const { customer, click, link } = data;
+
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*New lead created* :tada:",
+ },
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Customer:*\n${customer.name}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Email*\n<mailto:${customer.email}|${customer.email}>`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Country*\n${click.country}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Short link*\n<${link.shortLink}|${link.shortLink}>`,
+ },
+ ],
+ },
+ ],
+ };
+};
+
+const createSaleTemplate = ({ data }: { data: SaleEventWebhookData }) => {
+ const { customer, click, sale } = data;
+ const amountInDollars = (sale.amount / 100).toFixed(2);
+
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: "*New sale created* :moneybag:",
+ },
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Customer*\n${customer.name}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Email*\n<mailto:${customer.email}|${customer.email}>`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Country*\n${click.country}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Amount*\n${amountInDollars}`,
+ },
+ ],
+ },
+ ],
+ };
+};
+
+const slackTemplates: Record<WebhookTrigger, any> = {
+ "link.created": createLinkTemplate,
+ "link.updated": createLinkTemplate,
+ "link.deleted": createLinkTemplate,
+ "lead.created": createLeadTemplate,
+ "sale.created": createSaleTemplate,
+ "link.clicked": clickLinkTemplate,
+};
+
+export const generateSlackMessage = (
+ eventType: WebhookTrigger,
+ data: LinkWebhookEvent["data"],
+) => {
+ const template = slackTemplates[eventType];
+
+ if (!template) {
+ throw new Error(`No Slack template found for event type: ${eventType}`);
+ }
+
+ const isLinkEvent = ["link.created", "link.updated", "link.deleted"].includes(
+ eventType,
+ );
+
+ return template({
+ data,
+ ...(isLinkEvent && { eventType }),
+ });
+};
diff --git a/apps/web/lib/webhook/types.ts b/apps/web/lib/webhook/types.ts
index 81c0c82843..3d36491818 100644
--- a/apps/web/lib/webhook/types.ts
+++ b/apps/web/lib/webhook/types.ts
@@ -2,7 +2,11 @@ import z from "../zod";
import { clickEventSchema } from "../zod/schemas/clicks";
import { linkEventSchema } from "../zod/schemas/links";
import { WEBHOOK_TRIGGERS } from "./constants";
-import { leadWebhookEventSchema, saleWebhookEventSchema } from "./schemas";
+import {
+ clickWebhookEventSchema,
+ leadWebhookEventSchema,
+ saleWebhookEventSchema,
+} from "./schemas";
export type LinkEventDataProps = z.infer<typeof linkEventSchema>;
@@ -19,3 +23,9 @@ export type EventDataProps =
| SaleEventDataProps;
export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];
+
+export type ClickEventWebhookData = z.infer<typeof clickWebhookEventSchema>;
+
+export type LeadEventWebhookData = z.infer<typeof leadWebhookEventSchema>;
+
+export type SaleEventWebhookData = z.infer<typeof saleWebhookEventSchema>;