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.

Add support for commission.created webhook trigger

Kiran Kb5bd5641050a
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index bf979d9fd9..7498a72587 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -4,6 +4,7 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { getFolders } from "@/lib/folder/get-folders";
import { webhookCache } from "@/lib/webhook/cache";
+import { PARTNERS_WEBHOOK_TRIGGERS } from "@/lib/webhook/constants";
import { transformWebhook } from "@/lib/webhook/transform";
import { toggleWebhooksForWorkspace } from "@/lib/webhook/update-webhook";
import { isLinkLevelWebhook } from "@/lib/webhook/utils";
@@ -125,10 +126,16 @@ export const PATCH = withWorkspace(
}
if (triggers) {
- if (triggers.includes("partner.enrolled") && !workspace.partnersEnabled) {
+ const hasPartnersTriggers = PARTNERS_WEBHOOK_TRIGGERS.some((trigger) =>
+ triggers.includes(trigger),
+ );
+
+ if (hasPartnersTriggers && !workspace.partnersEnabled) {
throw new DubApiError({
code: "bad_request",
- message: `Partners are not enabled on this workspace to use "partner.enrolled" trigger.`,
+ message:
+ "Partners are not enabled on this workspace to use the following triggers: " +
+ PARTNERS_WEBHOOK_TRIGGERS.join(", "),
});
}
}
diff --git a/apps/web/lib/integrations/slack/transform.ts b/apps/web/lib/integrations/slack/transform.ts
index 73c2fb4690..3442a78b9c 100644
--- a/apps/web/lib/integrations/slack/transform.ts
+++ b/apps/web/lib/integrations/slack/transform.ts
@@ -1,10 +1,11 @@
-import { APP_DOMAIN } from "@dub/utils";
+import { APP_DOMAIN, currencyFormatter } from "@dub/utils";
import { LinkWebhookEvent } from "dub/models/components";
import { z } from "zod";
import { WebhookTrigger } from "../../types";
import { webhookPayloadSchema } from "../../webhook/schemas";
import {
ClickEventWebhookData,
+ CommissionEventDataProps,
LeadEventWebhookData,
PartnerEventDataProps,
SaleEventWebhookData,
@@ -233,6 +234,53 @@ const enrolledPartnerTemplate = ({ data }: { data: PartnerEventDataProps }) => {
};
};
+const commissionCreatedTemplate = ({
+ data,
+}: {
+ data: CommissionEventDataProps;
+}) => {
+ const { id, amount, earnings } = data;
+
+ const formattedAmount = currencyFormatter(amount / 100, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ });
+
+ const formattedEarnings = currencyFormatter(earnings / 100, {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ });
+
+ return {
+ blocks: [
+ {
+ type: "section",
+ text: {
+ type: "mrkdwn",
+ text: `*New commission created* :tada:`,
+ },
+ },
+ {
+ type: "section",
+ fields: [
+ {
+ type: "mrkdwn",
+ text: `*Commission ID*\n${id}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Amount*\n${formattedAmount}`,
+ },
+ {
+ type: "mrkdwn",
+ text: `*Earnings*\n${formattedEarnings}`,
+ },
+ ],
+ },
+ ],
+ };
+};
+
const slackTemplates: Record<WebhookTrigger, any> = {
"link.created": createLinkTemplate,
"link.updated": createLinkTemplate,
@@ -241,6 +289,7 @@ const slackTemplates: Record<WebhookTrigger, any> = {
"lead.created": createLeadTemplate,
"sale.created": createSaleTemplate,
"partner.enrolled": enrolledPartnerTemplate,
+ "commission.created": commissionCreatedTemplate,
};
export const formatEventForSlack = (
diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.ts
index 438daade72..1a5465b113 100644
--- a/apps/web/lib/partners/create-partner-commission.ts
+++ b/apps/web/lib/partners/create-partner-commission.ts
@@ -13,6 +13,7 @@ import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
import { calculateSaleEarnings } from "../api/sales/calculate-sale-earnings";
import { Session } from "../auth";
import { RewardProps } from "../types";
+import { sendWorkspaceWebhook } from "../webhook/publish";
import { determinePartnerReward } from "./determine-partner-reward";
export const createPartnerCommission = async ({
@@ -193,12 +194,28 @@ export const createPartnerCommission = async ({
const shouldCaptureAuditLog = user && workspaceId;
const isClawback = earnings < 0;
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: workspaceId,
+ },
+ select: {
+ id: true,
+ webhookEnabled: true,
+ },
+ });
+
await Promise.allSettled([
syncTotalCommissions({
partnerId,
programId,
}),
+ sendWorkspaceWebhook({
+ trigger: "commission.created",
+ data: commission,
+ workspace,
+ }),
+
shouldCaptureAuditLog
? recordAuditLog({
workspaceId,
diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.ts
index 0f1e8c5708..2c115a2fca 100644
--- a/apps/web/lib/webhook/constants.ts
+++ b/apps/web/lib/webhook/constants.ts
@@ -8,6 +8,12 @@ export const WEBHOOK_EVENT_ID_PREFIX = "evt_";
export const WEBHOOK_REDIS_KEY = "dub:webhooks";
+// Only available for Dub Partners
+export const PARTNERS_WEBHOOK_TRIGGERS = [
+ "partner.enrolled",
+ "commission.created",
+] as const;
+
export const WORKSPACE_LEVEL_WEBHOOK_TRIGGERS = [
"link.created",
"link.updated",
@@ -15,6 +21,7 @@ export const WORKSPACE_LEVEL_WEBHOOK_TRIGGERS = [
"lead.created",
"sale.created",
"partner.enrolled",
+ "commission.created",
] as const;
export const LINK_LEVEL_WEBHOOK_TRIGGERS = ["link.clicked"] as const;
@@ -32,6 +39,7 @@ export const WEBHOOK_TRIGGER_DESCRIPTIONS = {
"lead.created": "Lead created",
"sale.created": "Sale created",
"partner.enrolled": "Partner enrolled",
+ "commission.created": "Commission created",
} as const;
export const WEBHOOK_FAILURE_NOTIFY_THRESHOLDS = [5, 10, 15] as const;
diff --git a/apps/web/lib/webhook/create-webhook.ts b/apps/web/lib/webhook/create-webhook.ts
index 01b58573e9..b5b841fa54 100644
--- a/apps/web/lib/webhook/create-webhook.ts
+++ b/apps/web/lib/webhook/create-webhook.ts
@@ -1,7 +1,10 @@
import { createId } from "@/lib/api/create-id";
import { linkCache } from "@/lib/api/links/cache";
import { webhookCache } from "@/lib/webhook/cache";
-import { WEBHOOK_ID_PREFIX } from "@/lib/webhook/constants";
+import {
+ PARTNERS_WEBHOOK_TRIGGERS,
+ WEBHOOK_ID_PREFIX,
+} from "@/lib/webhook/constants";
import { isLinkLevelWebhook } from "@/lib/webhook/utils";
import { prisma } from "@dub/prisma";
import { Project, WebhookReceiver } from "@dub/prisma/client";
@@ -29,8 +32,14 @@ export async function createWebhook({
return;
}
- if (triggers.includes("partner.enrolled") && !workspace.partnersEnabled) {
- return;
+ if (triggers) {
+ const hasPartnersTriggers = PARTNERS_WEBHOOK_TRIGGERS.some((trigger) =>
+ triggers.includes(trigger),
+ );
+
+ if (hasPartnersTriggers && !workspace.partnersEnabled) {
+ return;
+ }
}
const webhook = await prisma.webhook.create({
diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.ts
index 3facf3b1e3..a44a80df49 100644
--- a/apps/web/lib/webhook/publish.ts
+++ b/apps/web/lib/webhook/publish.ts
@@ -2,6 +2,7 @@ import { prisma } from "@dub/prisma";
import { WebhookTrigger, WorkspaceProps } from "../types";
import { sendWebhooks } from "./qstash";
import {
+ CommissionEventDataProps,
LeadEventDataProps,
LinkEventDataProps,
PartnerEventDataProps,
@@ -20,7 +21,8 @@ export const sendWorkspaceWebhook = async ({
| LinkEventDataProps
| LeadEventDataProps
| SaleEventDataProps
- | PartnerEventDataProps;
+ | PartnerEventDataProps
+ | CommissionEventDataProps;
}) => {
if (!workspace.webhookEnabled) {
return;
diff --git a/apps/web/lib/webhook/sample-events/commission-created.json b/apps/web/lib/webhook/sample-events/commission-created.json
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/apps/web/lib/webhook/sample-events/payload.ts b/apps/web/lib/webhook/sample-events/payload.ts
index 999b27aeee..a9e1b31baa 100644
--- a/apps/web/lib/webhook/sample-events/payload.ts
+++ b/apps/web/lib/webhook/sample-events/payload.ts
@@ -1,4 +1,5 @@
import { WebhookTrigger } from "@/lib/types";
+import commissionCreated from "./commission-created.json";
import leadCreated from "./lead-created.json";
import linkClicked from "./link-clicked.json";
import linkCreated from "./link-created.json";
@@ -15,4 +16,5 @@ export const samplePayload: Record<WebhookTrigger, any> = {
"lead.created": leadCreated,
"sale.created": saleCreated,
"partner.enrolled": partnerEnrolled,
+ "commission.created": commissionCreated,
};
diff --git a/apps/web/lib/webhook/schemas.ts b/apps/web/lib/webhook/schemas.ts
index 2420f62ed9..b1e25aa67a 100644
--- a/apps/web/lib/webhook/schemas.ts
+++ b/apps/web/lib/webhook/schemas.ts
@@ -1,5 +1,6 @@
import z from "@/lib/zod";
import { clickEventSchema } from "../zod/schemas/clicks";
+import { CommissionWebhookSchema } from "../zod/schemas/commissions";
import { CustomerSchema } from "../zod/schemas/customers";
import { linkEventSchema } from "../zod/schemas/links";
import { EnrolledPartnerSchema } from "../zod/schemas/partners";
@@ -110,6 +111,18 @@ export const webhookEventSchema = z
ref: "PartnerEnrolledEvent",
description: "Triggered when a partner is enrolled.",
}),
+
+ z
+ .object({
+ id: z.string(),
+ event: z.literal("commission.created"),
+ createdAt: z.string(),
+ data: CommissionWebhookSchema,
+ })
+ .openapi({
+ ref: "CommissionCreatedEvent",
+ description: "Triggered when a partner commission is created.",
+ }),
])
.openapi({
ref: "WebhookEvent",
diff --git a/apps/web/lib/webhook/types.ts b/apps/web/lib/webhook/types.ts
index eaae11481e..da1b1ec8ae 100644
--- a/apps/web/lib/webhook/types.ts
+++ b/apps/web/lib/webhook/types.ts
@@ -1,4 +1,5 @@
import z from "../zod";
+import { CommissionWebhookSchema } from "../zod/schemas/commissions";
import { linkEventSchema } from "../zod/schemas/links";
import { EnrolledPartnerSchema } from "../zod/schemas/partners";
import { WEBHOOK_TRIGGERS } from "./constants";
@@ -21,12 +22,15 @@ export type SaleEventDataProps = z.infer<typeof saleWebhookEventSchema>;
export type PartnerEventDataProps = z.infer<typeof EnrolledPartnerSchema>;
+export type CommissionEventDataProps = z.infer<typeof CommissionWebhookSchema>;
+
export type EventDataProps =
| LinkEventDataProps
| ClickEventDataProps
| LeadEventDataProps
| SaleEventDataProps
- | PartnerEventDataProps;
+ | PartnerEventDataProps
+ | CommissionEventDataProps;
export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index b074d94c5a..196d05debe 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -191,3 +191,8 @@ export const createClawbackSchema = z.object({
CLAWBACK_REASONS.map((r) => r.value) as [string, ...string[]],
),
});
+
+
+// TODO:
+// Extend this with additional fields
+export const CommissionWebhookSchema = CommissionSchema;
\ No newline at end of file
diff --git a/apps/web/tests/webhooks/index.test.ts b/apps/web/tests/webhooks/index.test.ts
index e1f9edb34f..2350a4a0aa 100644
--- a/apps/web/tests/webhooks/index.test.ts
+++ b/apps/web/tests/webhooks/index.test.ts
@@ -40,6 +40,15 @@ const enrolledPartnerSchemaExtended = EnrolledPartnerSchema.extend({
.nullable(),
});
+// TODO: Implement this
+const commissionWebhookEventSchemaExtended = EnrolledPartnerSchema.extend({
+ createdAt: z.string().transform((str) => new Date(str)),
+ payoutsEnabledAt: z
+ .string()
+ .transform((str) => (str ? new Date(str) : null))
+ .nullable(),
+});
+
const eventSchemas: Record<WebhookTrigger, z.ZodSchema> = {
"link.created": linkEventSchema,
"link.updated": linkEventSchema,
@@ -48,6 +57,7 @@ const eventSchemas: Record<WebhookTrigger, z.ZodSchema> = {
"lead.created": leadWebhookEventSchemaExtended,
"sale.created": saleWebhookEventSchemaExtended,
"partner.enrolled": enrolledPartnerSchemaExtended,
+ "commission.created": commissionWebhookEventSchemaExtended,
};
describe("Webhooks", () => {
diff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
index e522b01cde..4627b57776 100644
--- a/apps/web/ui/webhooks/add-edit-webhook-form.tsx
+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
@@ -5,6 +5,7 @@ import useWorkspace from "@/lib/swr/use-workspace";
import { NewWebhook, WebhookProps } from "@/lib/types";
import {
LINK_LEVEL_WEBHOOK_TRIGGERS,
+ PARTNERS_WEBHOOK_TRIGGERS,
WEBHOOK_TRIGGER_DESCRIPTIONS,
WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
} from "@/lib/webhook/constants";
@@ -119,13 +120,10 @@ export default function AddEditWebhookForm({
);
const workspaceLevelTriggers = WORKSPACE_LEVEL_WEBHOOK_TRIGGERS.filter(
- (trigger) => {
- if (trigger === "partner.enrolled") {
- return partnersEnabled;
- }
-
- return true;
- },
+ (trigger) =>
+ PARTNERS_WEBHOOK_TRIGGERS.includes(trigger as any)
+ ? partnersEnabled
+ : true,
);
return (
diff --git a/packages/prisma/schema/commission.prisma b/packages/prisma/schema/commission.prisma
index 099ec1a3e4..d2686775cd 100644
--- a/packages/prisma/schema/commission.prisma
+++ b/packages/prisma/schema/commission.prisma
@@ -16,25 +16,24 @@ enum CommissionType {
}
model Commission {
- id String @id @default(cuid())
+ id String @id @default(cuid())
programId String
partnerId String
linkId String?
payoutId String?
invoiceId String? // only for sales (idempotency key, each sale event is associated with a unique invoice)
customerId String? // only for leads and sales
- eventId String? @unique // only for leads and sales
+ eventId String? @unique // only for leads and sales
description String?
-
- type CommissionType
- amount Int // only for sales (amount of the sale event)
- quantity Int // only for clicks/leads (quantity of the event)
- earnings Int @default(0) // amount earned by the partner
- currency String @default("usd")
- status CommissionStatus @default(pending)
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ type CommissionType
+ amount Int // only for sales (amount of the sale event)
+ quantity Int // only for clicks/leads (quantity of the event)
+ earnings Int @default(0) // amount earned by the partner
+ currency String @default("usd")
+ status CommissionStatus @default(pending)
+ userId String? // user who created the manual commission
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
program Program @relation(fields: [programId], references: [id])
partner Partner @relation(fields: [partnerId], references: [id])