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 workflows/create-partner-commission (#3961)

Steven Teyb41eb286d7eb
diff --git a/apps/web/app/(ee)/api/cron/utils.ts b/apps/web/app/(ee)/api/cron/utils.ts
index a3f24263c4..fc5258504c 100644
--- a/apps/web/app/(ee)/api/cron/utils.ts
+++ b/apps/web/app/(ee)/api/cron/utils.ts
@@ -11,3 +11,8 @@ export function logAndRespond(
console[logLevel](message);
return new Response(message, { status });
}
+
+export function logAndReturn<T>(value: T): T {
+ console.log(value);
+ return value;
+}
diff --git a/apps/web/app/(ee)/api/partner-profile/referrals/route.ts b/apps/web/app/(ee)/api/partner-profile/referrals/route.ts
index 3f0e0722c6..a8800b09f3 100644
--- a/apps/web/app/(ee)/api/partner-profile/referrals/route.ts
+++ b/apps/web/app/(ee)/api/partner-profile/referrals/route.ts
@@ -2,7 +2,7 @@ import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
import { obfuscateCustomerEmail } from "@/lib/api/partner-profile/obfuscate-customer-email";
import { withPartnerProfile } from "@/lib/auth/partner";
-import { triggerWorkflows } from "@/lib/cron/qstash-workflow";
+import { triggerQStashWorkflow } from "@/lib/cron/qstash-workflow";
import {
getNetworkReferralsQuerySchema,
networkReferralSchema,
@@ -56,8 +56,9 @@ export const GET = withPartnerProfile(async ({ partner, searchParams }) => {
console.log(
"Program enrollment created in the last 1 min, most likely it's a new partner",
);
- await triggerWorkflows({
- workflowId: "partner-approved",
+ await triggerQStashWorkflow({
+ workflowType: "partner-approved",
+ workflowLabel: partner.id,
body: {
programId: NETWORK_PROGRAM_ID,
partnerId: partner.id,
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
index c601cc7b12..d746573c6c 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts
@@ -1,11 +1,10 @@
import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
import { createId } from "@/lib/api/create-id";
-import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-event";
import { includeTags } from "@/lib/api/links/include-tags";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import {
getClickEvent,
@@ -19,7 +18,7 @@ import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
import { Customer } from "@dub/prisma/client";
-import { nanoid, pick } from "@dub/utils";
+import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
@@ -483,9 +482,8 @@ export async function checkoutSessionCompleted(
}),
]);
- // for program links
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
+ let result:
+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link && link.programId && link.partnerId) {
@@ -495,7 +493,7 @@ export async function checkoutSessionCompleted(
mode,
});
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
partnerId: link.partnerId,
@@ -516,10 +514,13 @@ export async function checkoutSessionCompleted(
amount: saleData.amount,
},
},
+ clickEvent: {
+ url: saleData.url,
+ referer: saleData.referer,
+ },
+ isFirstConversion: firstConversionFlag,
});
- const { webhookPartner, programEnrollment } = createdCommission;
-
waitUntil(
Promise.allSettled([
executeWorkflows({
@@ -543,20 +544,6 @@ export async function checkoutSessionCompleted(
programId: link.programId,
eventType: "sale",
}),
-
- webhookPartner &&
- detectAndRecordFraudEvent({
- program: { id: link.programId },
- partner: pick(webhookPartner, ["id", "email", "name"]),
- programEnrollment: pick(programEnrollment, ["status"]),
- customer: {
- ...pick(customer, ["id", "email", "name"]),
- isFirstConversion: firstConversionFlag,
- },
- link: pick(link, ["id"]),
- click: pick(saleData, ["url", "referer"]),
- event: { id: saleData.event_id },
- }),
]),
);
}
@@ -571,7 +558,7 @@ export async function checkoutSessionCompleted(
clickedAt: customer.clickedAt || customer.createdAt,
link: linkUpdated,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata: null,
}),
}),
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
index cafdb9d842..d2caa5d9e5 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts
@@ -1,10 +1,9 @@
import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
-import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-event";
import { includeTags } from "@/lib/api/links/include-tags";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { stripeAppClient } from "@/lib/stripe";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
@@ -13,7 +12,7 @@ import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
-import { nanoid, pick } from "@dub/utils";
+import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
@@ -313,12 +312,12 @@ export async function invoicePaid(
]);
// for program links
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
+ let result:
+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link.programId && link.partnerId) {
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
partnerId: link.partnerId,
@@ -339,10 +338,13 @@ export async function invoicePaid(
amount: saleData.amount,
},
},
+ clickEvent: {
+ url: saleData.url,
+ referer: saleData.referer,
+ },
+ isFirstConversion: firstConversionFlag,
});
- const { webhookPartner, programEnrollment } = createdCommission;
-
waitUntil(
Promise.allSettled([
executeWorkflows({
@@ -366,20 +368,6 @@ export async function invoicePaid(
programId: link.programId,
eventType: "sale",
}),
-
- webhookPartner &&
- detectAndRecordFraudEvent({
- program: { id: link.programId },
- partner: pick(webhookPartner, ["id", "email", "name"]),
- programEnrollment: pick(programEnrollment, ["status"]),
- customer: {
- ...pick(customer, ["id", "email", "name"]),
- isFirstConversion: firstConversionFlag,
- },
- link: pick(link, ["id"]),
- click: pick(saleData, ["url", "referer"]),
- event: { id: saleData.event_id },
- }),
]),
);
}
@@ -394,7 +382,7 @@ export async function invoicePaid(
clickedAt: customer.clickedAt || customer.createdAt,
link: linkUpdated,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata: null,
}),
}),
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts
index eb66275a8d..6a7fa3252f 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts
@@ -2,7 +2,7 @@ import { createId } from "@/lib/api/create-id";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { generateRandomName } from "@/lib/names";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { recordLead } from "@/lib/tinybird";
import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
@@ -153,12 +153,12 @@ export async function attributeViaPromotionCodeId({
(async () => {
const linkUpdated = await incrementLinkLeads(link.id);
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
+ let result:
+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link.programId && link.partnerId) {
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "lead",
programId: link.programId,
partnerId: link.partnerId,
@@ -205,7 +205,7 @@ export async function attributeViaPromotionCodeId({
...leadEvent,
link: linkUpdated,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata: null,
}),
}),
diff --git a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
new file mode 100644
index 0000000000..a1deaae1d4
--- /dev/null
+++ b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts
@@ -0,0 +1,569 @@
+import { createId } from "@/lib/api/create-id";
+import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-event";
+import { notifyPartnerCommission } from "@/lib/api/partners/notify-partner-commission";
+import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
+import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
+import { calculateSaleEarnings } from "@/lib/api/sales/calculate-sale-earnings";
+import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
+import { logger } from "@/lib/axiom/server";
+import { getWorkflowConfig } from "@/lib/cron/qstash-workflow";
+import { constructWebhookPartner } from "@/lib/partners/constuct-webhook-partner";
+import { determinePartnerReward } from "@/lib/partners/determine-partner-reward";
+import { getRewardAmount } from "@/lib/partners/get-reward-amount";
+import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
+import { RewardProps } from "@/lib/types";
+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
+import {
+ CommissionWebhookSchema,
+ createPartnerCommissionSchema,
+} from "@/lib/zod/schemas/commissions";
+import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
+import { prisma } from "@dub/prisma";
+import {
+ Commission,
+ Link,
+ Partner,
+ PartnerGroup,
+ ProgramEnrollment,
+ Reward,
+} from "@dub/prisma/client";
+import { currencyFormatter, log, pick, toCentsNumber } from "@dub/utils";
+import { WorkflowRetryAfterError } from "@upstash/workflow";
+import { serve } from "@upstash/workflow/nextjs";
+import { differenceInMonths } from "date-fns";
+import * as z from "zod/v4";
+import { logAndReturn } from "../../cron/utils";
+
+type Input = z.infer<typeof createPartnerCommissionSchema>;
+
+type ProgramEnrollmentWithReward = ProgramEnrollment & {
+ links: Link[];
+ partner: Partner;
+ partnerGroup: PartnerGroup | null;
+ clickReward?: Reward | null;
+ leadReward?: Reward | null;
+ saleReward?: Reward | null;
+};
+
+type StepFunctionInput = Input & {
+ programEnrollment: ProgramEnrollmentWithReward;
+ isFirstCommission?: boolean;
+};
+
+type StepCreateCommissionOutput = {
+ commission: Pick<Commission, "id"> | null;
+ outputLog: string;
+ isFirstCommission?: boolean;
+};
+
+// POST /api/workflows/create-partner-commission
+export const { POST } = serve<Input>(
+ async (context) => {
+ const input = context.requestPayload;
+ const { event, partnerId, programId, bountySubmissionId } = input;
+
+ const programEnrollment = await getProgramEnrollmentOrThrow({
+ partnerId,
+ programId,
+ include: {
+ links: true,
+ partner: true,
+ partnerGroup: true,
+ ...(event === "click" && { clickReward: true }),
+ ...(event === "lead" && { leadReward: true }),
+ ...(event === "sale" && { saleReward: true }),
+ },
+ });
+
+ // Step 1: Create commission
+ const { commission, isFirstCommission } = await context.run(
+ "create-commission",
+ async () => {
+ return await stepCreateCommission({
+ ...input,
+ programEnrollment,
+ });
+ },
+ );
+
+ // Step 2: Run side effects
+ await context.run("run-side-effects", async () => {
+ return await stepRunSideEffects({
+ ...input,
+ programEnrollment,
+ commission,
+ isFirstCommission,
+ });
+ });
+
+ // Step 3 (optional): Link the created commission to the bounty submission
+ if (commission && bountySubmissionId) {
+ await context.run("set-bounty-commission", async () => {
+ const { count } = await prisma.bountySubmission.updateMany({
+ where: {
+ id: bountySubmissionId,
+ status: "approved",
+ commissionId: null,
+ },
+ data: {
+ commissionId: commission.id,
+ },
+ });
+
+ if (count) {
+ return logAndReturn({
+ outputLog: `Linked commission ${commission.id} to bounty submission ${bountySubmissionId}`,
+ });
+ } else {
+ return logAndReturn({
+ outputLog: `Bounty submission ${bountySubmissionId} not found or already linked to a commission, skipping...`,
+ });
+ }
+ });
+ }
+ },
+ {
+ initialPayloadParser: (requestPayload) => {
+ return createPartnerCommissionSchema.parse(JSON.parse(requestPayload));
+ },
+ failureFunction: async ({
+ context,
+ failStatus,
+ failResponse,
+ failHeaders,
+ }) => {
+ const { correlation } = getWorkflowConfig({
+ workflowType: "create-partner-commission",
+ body: context.requestPayload,
+ });
+
+ logger.error("workflow.failed", {
+ service: "qstash",
+ event: "workflow.failed",
+ workflowType: "create-partner-commission",
+ workflowRunId: context.workflowRunId,
+ failStatus,
+ failResponse,
+ failHeaders,
+ correlation,
+ });
+
+ await logger.flush();
+ },
+ },
+);
+
+async function stepCreateCommission(
+ input: StepFunctionInput,
+): Promise<StepCreateCommissionOutput> {
+ let {
+ event,
+ partnerId,
+ programId,
+ linkId,
+ customerId,
+ eventId,
+ invoiceId,
+ amount,
+ quantity,
+ currency,
+ description,
+ createdAt,
+ status,
+ userId,
+ context,
+ programEnrollment,
+ } = input;
+
+ if (typeof amount !== "number") {
+ amount = 0;
+ }
+
+ let earnings = 0;
+ let reward: RewardProps | null = null;
+ let firstCommission: Pick<
+ Commission,
+ "rewardId" | "status" | "createdAt"
+ > | null = null;
+
+ if (event === "custom") {
+ earnings = amount;
+ amount = 0;
+ } else {
+ if (["lead", "sale"].includes(event) && customerId) {
+ firstCommission = await prisma.commission.findFirst({
+ where: {
+ partnerId,
+ customerId,
+ type: event,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ select: {
+ rewardId: true,
+ status: true,
+ createdAt: true,
+ },
+ });
+
+ const subscriptionStartDate =
+ event === "sale" ? firstCommission?.createdAt ?? new Date() : undefined;
+
+ const subscriptionDurationMonths = subscriptionStartDate
+ ? differenceInMonths(
+ createdAt ?? new Date(), // account for custom commission creation date
+ subscriptionStartDate,
+ )
+ : 0;
+
+ context = {
+ ...context,
+ customer: {
+ ...context?.customer,
+ subscriptionStartDate,
+ subscriptionDurationMonths,
+ },
+ ...(event === "sale" && {
+ sale: {
+ ...context?.sale,
+ type: firstCommission ? "recurring" : "new",
+ },
+ }),
+ };
+ }
+
+ reward = determinePartnerReward({
+ event,
+ programEnrollment,
+ ...(context ? { context } : {}),
+ });
+
+ // if there is no reward, skip commission creation
+ if (!reward) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has no reward for ${event} event, skipping commission creation...`,
+ });
+ }
+
+ // for click events, it's super simple – just multiply the reward amount by the quantity
+ if (event === "click") {
+ earnings = getRewardAmount(reward) * quantity;
+
+ // for lead and sale events, we need to check if this partner-customer combination was recorded already (for deduplication)
+ // for sale rewards specifically, we also need to check:
+ // 1. if the partner has reached the max duration for the reward (if applicable)
+ // 2. if the previous commission were marked as fraud or canceled
+ } else {
+ if (firstCommission) {
+ // if first commission is fraud or canceled, skip commission creation
+ if (["fraud", "canceled"].includes(firstCommission.status)) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has a first commission that is ${firstCommission.status}, skipping commission creation...`,
+ });
+ }
+
+ // for lead events, we need to check if the partner has already been issued a lead reward for this customer
+ if (event === "lead") {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has already been issued a lead reward for this customer ${customerId}, skipping commission creation...`,
+ });
+
+ // for sale rewards, we need to check if partner's reward was updated and different from the first commission's reward
+ // we need to make sure it wasn't changed from one-time to recurring so we don't create a new commission
+ } else {
+ if (
+ firstCommission.rewardId &&
+ firstCommission.rewardId !== reward.id
+ ) {
+ const originalReward = await prisma.reward.findUnique({
+ where: {
+ id: firstCommission.rewardId,
+ },
+ select: {
+ id: true,
+ maxDuration: true,
+ },
+ });
+
+ if (
+ typeof originalReward?.maxDuration === "number" &&
+ originalReward.maxDuration === 0
+ ) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} is only eligible for first-sale commissions based on the original reward ${originalReward.id}, skipping commission creation...`,
+ });
+ }
+ }
+
+ // for sale rewards with a max duration, we need to check if the first commission is within the max duration
+ // if it's beyond the max duration, we should not create a new commission
+ if (typeof reward?.maxDuration === "number") {
+ // One-time sale reward (maxDuration === 0)
+ if (reward.maxDuration === 0) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} is only eligible for first-sale commissions, skipping commission creation...`,
+ });
+ }
+
+ // Recurring sale reward (maxDuration > 0)
+ else {
+ const subscriptionDurationMonths = differenceInMonths(
+ createdAt ?? new Date(), // account for custom commission creation date
+ firstCommission.createdAt,
+ );
+
+ if (subscriptionDurationMonths >= reward.maxDuration) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has reached max duration for ${event} event (subscription duration: ${subscriptionDurationMonths} months, max duration: ${reward.maxDuration} months), skipping commission creation...`,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ // for lead events, we just multiply the reward amount by the quantity
+ if (event === "lead") {
+ earnings = getRewardAmount(reward) * quantity;
+ // for sale events, we need to calculate the earnings based on the sale amount
+ } else {
+ earnings = calculateSaleEarnings({
+ reward,
+ sale: {
+ quantity,
+ amount,
+ },
+ });
+ }
+ }
+ }
+
+ // skip commission creation if the earnings is zero
+ if (earnings === 0) {
+ return logAndReturn({
+ commission: null,
+ outputLog: `Partner ${partnerId} has zero earnings for ${event} event, skipping commission creation...`,
+ });
+ }
+
+ try {
+ const commission = await prisma.commission.create({
+ data: {
+ id: createId({ prefix: "cm_" }),
+ programId,
+ partnerId,
+ rewardId: reward?.id,
+ customerId,
+ linkId,
+ eventId: eventId || null, // empty string should convert to null
+ invoiceId: invoiceId || null, // empty string should convert to null
+ userId,
+ quantity,
+ amount,
+ type: event,
+ currency,
+ earnings,
+ status,
+ description,
+ createdAt,
+ },
+ });
+
+ const isFirstCommission =
+ event !== "custom" ? firstCommission === null : undefined;
+
+ return logAndReturn({
+ commission,
+ isFirstCommission,
+ outputLog: `Created a ${event} commission ${commission.id} (${currencyFormatter(commission.earnings, { currency: commission.currency })}) for ${partnerId}`,
+ });
+ } catch (error) {
+ const outputLog = `Error creating commission - ${error.message}`;
+
+ // only log to Slack if the error is not a unique constraint violation
+ if (error.code !== "P2002") {
+ await log({
+ message: outputLog,
+ type: "errors",
+ mention: true,
+ });
+
+ // Retry after 5 seconds
+ throw new WorkflowRetryAfterError(error.message, "5s");
+ }
+
+ return logAndReturn({
+ commission: null,
+ outputLog,
+ });
+ }
+}
+
+async function stepRunSideEffects(
+ input: StepFunctionInput & {
+ commission: Pick<Commission, "id"> | null;
+ },
+) {
+ const {
+ commission: _commission,
+ programEnrollment,
+ isFirstCommission,
+ programId,
+ partnerId,
+ linkId,
+ eventId,
+ skipWorkflow,
+ clickEvent,
+ isFirstConversion,
+ } = input;
+
+ if (!_commission) {
+ return logAndReturn({
+ outputLog: "Commission was not created. Skipping side effects...",
+ });
+ }
+
+ const commission = await prisma.commission.findUniqueOrThrow({
+ where: {
+ id: _commission.id,
+ },
+ include: {
+ customer: true,
+ link: {
+ select: {
+ id: true,
+ shortLink: true,
+ domain: true,
+ key: true,
+ },
+ },
+ },
+ });
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ id: true,
+ name: true,
+ slug: true,
+ logo: true,
+ supportEmail: true,
+ workspace: {
+ select: {
+ id: true,
+ slug: true,
+ name: true,
+ webhookEnabled: true,
+ },
+ },
+ // if no partner group is found, need to fetch default group to fallback to
+ ...(!programEnrollment.partnerGroup && {
+ groups: {
+ select: {
+ holdingPeriodDays: true,
+ },
+ where: {
+ slug: DEFAULT_PARTNER_GROUP.slug,
+ },
+ },
+ }),
+ },
+ });
+
+ const { workspace } = program;
+ const isClawback = commission.earnings < 0;
+ const shouldTriggerWorkflow = !isClawback && !skipWorkflow;
+
+ const webhookPartner = constructWebhookPartner(programEnrollment, {
+ totalCommissions:
+ toCentsNumber(programEnrollment.totalCommissions) + commission.earnings,
+ });
+
+ const results = await Promise.allSettled([
+ sendWorkspaceWebhook({
+ workspace,
+ trigger: "commission.created",
+ data: CommissionWebhookSchema.parse({
+ ...commission,
+ partner: webhookPartner,
+ }),
+ }),
+
+ sendPartnerPostback({
+ partnerId,
+ event: "commission.created",
+ data: commission,
+ }),
+
+ syncTotalCommissions({
+ partnerId,
+ programId,
+ }),
+
+ !isClawback &&
+ notifyPartnerCommission({
+ program,
+ // fallback to default group if no partner group is found
+ group: programEnrollment.partnerGroup ?? program.groups[0],
+ workspace,
+ commission,
+ isFirstCommission,
+ }),
+
+ // Execute Dub workflows
+ shouldTriggerWorkflow &&
+ executeWorkflows({
+ trigger: "partnerMetricsUpdated",
+ reason: "commission",
+ identity: {
+ workspaceId: workspace.id,
+ programId,
+ partnerId,
+ },
+ metrics: {
+ current: {
+ commissions: commission.earnings,
+ },
+ },
+ }),
+
+ // Run fraud detection
+ commission.customer &&
+ eventId &&
+ clickEvent &&
+ detectAndRecordFraudEvent({
+ program: { id: programId },
+ partner: pick(programEnrollment.partner, ["id", "email", "name"]),
+ programEnrollment: pick(programEnrollment, ["status"]),
+ customer: {
+ ...pick(commission.customer, ["id", "email", "name"]),
+ // only pass along isFirstConversion if it's a boolean
+ ...(typeof isFirstConversion === "boolean" && { isFirstConversion }),
+ },
+ link: { id: linkId },
+ click: pick(clickEvent, ["url", "referer"]),
+ event: { id: eventId },
+ }),
+ ]);
+
+ return [
+ "sendWorkspaceWebhook",
+ "sendPartnerPostback",
+ "syncTotalCommissions",
+ "notifyPartnerCommission",
+ "executeWorkflows",
+ "detectAndRecordFraudEvent",
+ ].map((step, index) => ({
+ step,
+ result: results[index],
+ }));
+}
diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
index 134570b816..136c388d08 100644
--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts
@@ -2,8 +2,9 @@ import { createPartnerDefaultLinks } from "@/lib/api/partners/create-partner-def
import { getGroupRewardsAndBounties } from "@/lib/api/partners/get-group-rewards-and-bounties";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
+import { logger } from "@/lib/axiom/server";
import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";
-import { createWorkflowLogger } from "@/lib/cron/qstash-workflow-logger";
+import { getWorkflowConfig } from "@/lib/cron/qstash-workflow";
import { generateDiscountCodeForPartner } from "@/lib/discounts/generate-discount-code-for-partner";
import { createReferralCommission } from "@/lib/partner-referrals/create-referral-commission";
import { polyfillSocialMediaFields } from "@/lib/social-utils";
@@ -18,13 +19,13 @@ import { NETWORK_PROGRAM_ID } from "@dub/utils";
import { serve } from "@upstash/workflow/nextjs";
import * as z from "zod/v4";
-const payloadSchema = z.object({
+const inputSchema = z.object({
programId: z.string(),
partnerId: z.string(),
userId: z.string(),
});
-type Payload = z.infer<typeof payloadSchema>;
+type Input = z.infer<typeof inputSchema>;
/**
* Partner Approved Workflow
@@ -51,16 +52,11 @@ type Payload = z.infer<typeof payloadSchema>;
*/
// POST /api/workflows/partner-approved
-export const { POST } = serve<Payload>(
+export const { POST } = serve<Input>(
async (context) => {
const input = context.requestPayload;
const { programId, partnerId, userId } = input;
- const logger = createWorkflowLogger({
- workflowId: "partner-approved",
- workflowRunId: context.workflowRunId,
- });
-
const {
program,
partner,
@@ -83,15 +79,10 @@ export const { POST } = serve<Payload>(
// Step 1: Create partner default links
await context.run("create-default-links", async () => {
- logger.info({
- message: "Started executing workflow step 'create-default-links'.",
- data: input,
- });
-
if (!groupId) {
- logger.error({
- message: `The partner ${partnerId} is not associated with any group.`,
- });
+ console.error(
+ `The partner ${partnerId} is not associated with any group.`,
+ );
return;
}
@@ -107,9 +98,7 @@ export const { POST } = serve<Payload>(
});
if (partnerGroupDefaultLinks.length === 0) {
- logger.error({
- message: `Group ${groupId} does not have any default links.`,
- });
+ console.error(`Group ${groupId} does not have any default links.`);
return;
}
@@ -123,9 +112,9 @@ export const { POST } = serve<Payload>(
}
if (partnerGroupDefaultLinks.length === 0) {
- logger.error({
- message: `Already created default links for partner ${partnerId}.`,
- });
+ console.error(
+ `Already created default links for partner ${partnerId}.`,
+ );
return;
}
@@ -162,7 +151,7 @@ export const { POST } = serve<Payload>(
userId,
});
- logger.info({
+ console.info({
message: `Created ${partnerLinks.length} partner default links.`,
data: partnerLinks.map(({ id, url, shortLink }) => ({
id,
@@ -183,11 +172,6 @@ export const { POST } = serve<Payload>(
// Step 2: Auto-provision discount code if enabled
await context.run("create-discount-codes", async () => {
- logger.info({
- message: "Started executing workflow step 'create-discount-codes'.",
- data: input,
- });
-
await generateDiscountCodeForPartner({
workspaceId: program.workspaceId,
partner: {
@@ -200,15 +184,10 @@ export const { POST } = serve<Payload>(
// Step 3: Send email to partner application approved
await context.run("send-email", async () => {
- logger.info({
- message: "Started executing workflow step 'send-email'.",
- data: input,
- });
-
if (!groupId) {
- logger.error({
- message: `The partner ${partnerId} is not associated with any group.`,
- });
+ console.error(
+ `The partner ${partnerId} is not associated with any group.`,
+ );
return;
}
@@ -236,17 +215,12 @@ export const { POST } = serve<Payload>(
});
if (partnerUsers.length === 0) {
- logger.info({
- message: `No partner users found for partner ${partnerId} to send email notification.`,
- });
+ console.log(
+ `No partner users found for partner ${partnerId} to send email notification.`,
+ );
return;
}
- logger.info({
- message: `Sending email notification to ${partnerUsers.length} partner users.`,
- data: partnerUsers,
- });
-
const rewardsAndBounties = await getGroupRewardsAndBounties({
programId,
groupId: programEnrollment.groupId || program.defaultGroupId,
@@ -279,7 +253,7 @@ export const { POST } = serve<Payload>(
);
if (data) {
- logger.info({
+ console.info({
message: `Sent emails to ${partnerUsers.length} partner users.`,
data: data,
});
@@ -292,11 +266,6 @@ export const { POST } = serve<Payload>(
// Step 4: Send webhook to workspace
await context.run("send-webhook", async () => {
- logger.info({
- message: "Started executing workflow step 'send-webhook'.",
- data: input,
- });
-
const partnerPlatforms = await prisma.partnerPlatform.findMany({
where: {
partnerId,
@@ -326,20 +295,10 @@ export const { POST } = serve<Payload>(
trigger: "partner.enrolled",
data: enrolledPartner,
});
-
- logger.info({
- message: `Sent "partner.enrolled" webhook to workspace ${workspace.id}.`,
- });
});
// Step 5: Trigger draft bounty submission creation
await context.run("trigger-draft-bounty-submission-creation", async () => {
- logger.info({
- message:
- "Started executing workflow step 'trigger-draft-bounty-submission-creation'.",
- data: input,
- });
-
await triggerDraftBountySubmissionCreation({
programId,
partnerIds: [partnerId],
@@ -348,12 +307,6 @@ export const { POST } = serve<Payload>(
// Step 6: Execute Dub workflows using the “partnerEnrolled” trigger.
await context.run("execute-workflows", async () => {
- logger.info({
- message:
- "Started executing workflow step 'execute-workflows' for the trigger 'partnerEnrolled'.",
- data: input,
- });
-
await executeWorkflows({
trigger: "partnerEnrolled",
identity: {
@@ -366,12 +319,6 @@ export const { POST } = serve<Payload>(
// Step 7: Create referral commission if enabled
await context.run("create-referral-commission", async () => {
- logger.info({
- message:
- "Started executing workflow step 'create-referral-commission'.",
- data: input,
- });
-
await createReferralCommission({
partnerId,
programId,
@@ -380,7 +327,31 @@ export const { POST } = serve<Payload>(
},
{
initialPayloadParser: (requestPayload) => {
- return payloadSchema.parse(JSON.parse(requestPayload));
+ return inputSchema.parse(JSON.parse(requestPayload));
+ },
+ failureFunction: async ({
+ context,
+ failStatus,
+ failResponse,
+ failHeaders,
+ }) => {
+ const { correlation } = getWorkflowConfig({
+ workflowType: "partner-approved",
+ body: context.requestPayload,
+ });
+
+ logger.error("workflow.failed", {
+ service: "qstash",
+ event: "workflow.failed",
+ workflowType: "partner-approved",
+ workflowRunId: context.workflowRunId,
+ failStatus,
+ failResponse,
+ failHeaders,
+ correlation,
+ });
+
+ await logger.flush();
},
},
);
diff --git a/apps/web/lib/actions/partners/bulk-approve-partners.ts b/apps/web/lib/actions/partners/bulk-approve-partners.ts
index e52dafae35..0eb2e71165 100644
--- a/apps/web/lib/actions/partners/bulk-approve-partners.ts
+++ b/apps/web/lib/actions/partners/bulk-approve-partners.ts
@@ -4,7 +4,7 @@ import { trackActivityLog } from "@/lib/api/activity-log/track-activity-log";
import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { trackApplicationEvents } from "@/lib/application-events/update-application-event";
-import { triggerWorkflows } from "@/lib/cron/qstash-workflow";
+import { triggerQStashWorkflow } from "@/lib/cron/qstash-workflow";
import { throwIfPartnersLimitExceeded } from "@/lib/partners/throw-if-partners-limit-exceeded";
import { bulkApprovePartnersSchema } from "@/lib/zod/schemas/partners";
import { prisma } from "@dub/prisma";
@@ -142,9 +142,10 @@ export const bulkApprovePartnersAction = authActionClient
})),
),
- triggerWorkflows(
+ triggerQStashWorkflow(
updatedEnrollments.map(({ partnerId, programId }) => ({
- workflowId: "partner-approved",
+ workflowType: "partner-approved",
+ workflowLabel: partnerId,
body: {
programId,
partnerId,
diff --git a/apps/web/lib/actions/partners/create-clawback.ts b/apps/web/lib/actions/partners/create-clawback.ts
index 9ee2a04e6e..5372d8d10f 100644
--- a/apps/web/lib/actions/partners/create-clawback.ts
+++ b/apps/web/lib/actions/partners/create-clawback.ts
@@ -2,7 +2,7 @@
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { createClawbackSchema } from "@/lib/zod/schemas/commissions";
import { authActionClient } from "../safe-action";
import { throwIfNoPermission } from "../throw-if-no-permission";
@@ -26,13 +26,13 @@ export const createClawbackAction = authActionClient
include: {},
});
- await createPartnerCommission({
+ await queuePartnerCommissionCreation({
event: "custom",
partnerId,
programId,
description,
amount: -amount,
quantity: 1,
- user,
+ userId: user.id,
});
});
diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.ts
index 120690ca81..515e389ad0 100644
--- a/apps/web/lib/actions/partners/create-manual-commission.ts
+++ b/apps/web/lib/actions/partners/create-manual-commission.ts
@@ -7,16 +7,14 @@ import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-sta
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
-import {
- createPartnerCommission,
- CreatePartnerCommissionProps,
-} from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import {
recordClickZod,
recordClickZodSchema,
} from "@/lib/tinybird/record-click-zod";
import { recordLeadWithTimestamp } from "@/lib/tinybird/record-lead";
import { recordSaleWithTimestamp } from "@/lib/tinybird/record-sale";
+import { CreatePartnerCommissionProps } from "@/lib/types";
import { createCommissionSchema } from "@/lib/zod/schemas/commissions";
import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
@@ -91,14 +89,14 @@ export const createManualCommissionAction = authActionClient
// Create a custom commission
if (commissionType === "custom") {
- await createPartnerCommission({
+ await queuePartnerCommissionCreation({
event: "custom",
partnerId,
programId,
amount: amount ?? 0,
quantity: 1,
createdAt: date ?? new Date(),
- user,
+ userId: user.id,
description,
});
@@ -192,9 +190,9 @@ export const createManualCommissionAction = authActionClient
);
}
- if (stripeCustomerInvoices.length > 12) {
+ if (stripeCustomerInvoices.length > 36) {
throw new Error(
- `Too many Stripe invoices found for customer ${customer.email} (${stripeCustomerInvoices.length}). Please import the invoices manually.`,
+ `Too many Stripe invoices found for customer ${customer.email} (${stripeCustomerInvoices.length}). Please contact support.`,
);
}
@@ -269,9 +267,9 @@ export const createManualCommissionAction = authActionClient
...(stripeCustomerInvoices.find(
(invoice) => invoice.id === saleEvent.invoice_id,
)?.refunded && {
- status: "refunded",
+ status: "refunded" as const,
}),
- user,
+ userId: user.id,
context: {
customer: { country: customer.country },
},
@@ -325,7 +323,7 @@ export const createManualCommissionAction = authActionClient
eventId: leadEventData.event_id,
quantity: 1,
createdAt: new Date(leadEventData.timestamp), // we don't add the "Z" to the timestamp because it's already in UTC
- user,
+ userId: user.id,
context: {
customer: { country: customer.country },
},
@@ -366,7 +364,7 @@ export const createManualCommissionAction = authActionClient
currency: saleEventData.currency,
invoiceId: saleEventData.invoice_id,
createdAt: new Date(saleEventData.timestamp), // we don't add the "Z" to the timestamp because it's already in UTC
- user,
+ userId: user.id,
context: {
customer: { country: customer.country },
sale: { productId },
@@ -383,17 +381,14 @@ export const createManualCommissionAction = authActionClient
const tbRes = await Promise.allSettled(tbEventsToRecord.map((fn) => fn()));
console.log("Recorded events in Tinybird: ", prettyPrint(tbRes));
- let createdCommissions = 0;
+ let queuedCommissions = 0;
// create partner commissions (use a for loop to make sure the commissions are created in the correct order)
- // TODO: migrate to use workflow to support bulk creation
for (const c of commissionsToCreate) {
- const { commission } = await createPartnerCommission(c);
- if (commission) {
- createdCommissions++;
- }
+ await queuePartnerCommissionCreation(c);
+ queuedCommissions++;
}
console.log(
- `Created ${createdCommissions} commissions for partner ${partner.email} (${partner.id}) and customer ${customer.email} (${customer.id})`,
+ `Queued ${queuedCommissions} commissions for partner ${partner.email} (${partner.id}) and customer ${customer.email} (${customer.id})`,
);
waitUntil(
diff --git a/apps/web/lib/api/conversions/track-lead.ts b/apps/web/lib/api/conversions/track-lead.ts
index 518eab1e37..9766018b56 100644
--- a/apps/web/lib/api/conversions/track-lead.ts
+++ b/apps/web/lib/api/conversions/track-lead.ts
@@ -1,9 +1,8 @@
import { createId } from "@/lib/api/create-id";
import { DubApiError } from "@/lib/api/errors";
-import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-event";
import { includeTags } from "@/lib/api/links/include-tags";
import { generateRandomName } from "@/lib/names";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { isStored, storage } from "@/lib/storage";
import { getClickEvent, recordLead } from "@/lib/tinybird";
@@ -17,7 +16,7 @@ import {
} from "@/lib/zod/schemas/leads";
import { prisma } from "@dub/prisma";
import { Link } from "@dub/prisma/client";
-import { nanoid, pick, R2_URL } from "@dub/utils";
+import { nanoid, R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { syncPartnerLinksStats } from "../partners/sync-partner-links-stats";
@@ -287,12 +286,12 @@ export const trackLead = async ({
]);
link = updatedLink; // update the link variable to the latest version
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
- | undefined = undefined;
+ let result: Awaited<
+ ReturnType<typeof queuePartnerCommissionCreation>
+ > | null = null;
if (link.programId && link.partnerId && customer) {
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "lead",
programId: link.programId,
partnerId: link.partnerId,
@@ -306,11 +305,12 @@ export const trackLead = async ({
source,
},
},
+ clickEvent: {
+ url: clickData.url,
+ referer: clickData.referer,
+ },
});
- const { commission, webhookPartner, programEnrollment } =
- createdCommission;
-
await Promise.allSettled([
executeWorkflows({
trigger: "partnerMetricsUpdated",
@@ -332,19 +332,6 @@ export const trackLead = async ({
programId: link.programId,
eventType: "lead",
}),
-
- // only run fraud checks if the commission was created
- commission &&
- webhookPartner &&
- detectAndRecordFraudEvent({
- program: { id: link.programId },
- partner: pick(webhookPartner, ["id", "email", "name"]),
- programEnrollment: pick(programEnrollment, ["status"]),
- customer: pick(customer, ["id", "email", "name"]),
- link: pick(link, ["id"]),
- click: pick(clickData, ["url", "referer"]),
- event: { id: leadEventId },
- }),
]);
}
@@ -356,7 +343,7 @@ export const trackLead = async ({
eventName,
link,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata,
}),
workspace,
diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.ts
index 604e32d5aa..f8661c4f80 100644
--- a/apps/web/lib/api/conversions/track-sale.ts
+++ b/apps/web/lib/api/conversions/track-sale.ts
@@ -1,10 +1,9 @@
import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
import { DubApiError } from "@/lib/api/errors";
-import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-event";
import { includeTags } from "@/lib/api/links/include-tags";
import { generateRandomName } from "@/lib/names";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { isStored, storage } from "@/lib/storage";
import {
@@ -20,6 +19,7 @@ import {
WorkspaceProps,
} from "@/lib/types";
import { redis } from "@/lib/upstash";
+import { publishWorkspaceClicksUsageEvent } from "@/lib/upstash/redis-streams/workspace-clicks-usage";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import {
transformLeadEventData,
@@ -31,7 +31,7 @@ import {
} from "@/lib/zod/schemas/sales";
import { prisma } from "@dub/prisma";
import { Customer } from "@dub/prisma/client";
-import { nanoid, pick, R2_URL } from "@dub/utils";
+import { nanoid, R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
import { createId } from "../create-id";
@@ -442,55 +442,34 @@ const _trackSale = async ({
waitUntil(
(async () => {
- const [_sale, link] = await Promise.all([
- // Record sale event
- recordSale({
- ...saleData,
- timestamp: undefined,
- }),
-
- // Update link conversions, sales, and saleAmount
- prisma.link.update({
- where: {
- id: saleData.link_id,
- },
- data: {
- ...(firstConversionFlag && {
- conversions: {
- increment: 1,
- },
- lastConversionAt: new Date(),
- }),
- sales: {
+ // Update link conversions, sales, and saleAmount
+ const link = await prisma.link.update({
+ where: {
+ id: saleData.link_id,
+ },
+ data: {
+ ...(firstConversionFlag && {
+ conversions: {
increment: 1,
},
- saleAmount: {
- increment: amount,
- },
- },
- include: includeTags,
- }),
-
- // Update workspace events usage
- prisma.project.update({
- where: {
- id: workspace.id,
+ lastConversionAt: new Date(),
+ }),
+ sales: {
+ increment: 1,
},
- data: {
- usage: {
- increment: 1,
- },
+ saleAmount: {
+ increment: amount,
},
- }),
- ]);
+ },
+ include: includeTags,
+ });
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
+ let result:
+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
- // Create partner commission and execute workflows
if (link.programId && link.partnerId) {
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
partnerId: link.partnerId,
@@ -512,10 +491,13 @@ const _trackSale = async ({
amount: saleData.amount,
},
},
+ clickEvent: {
+ url: saleData.url,
+ referer: saleData.referer,
+ },
+ isFirstConversion: firstConversionFlag,
});
- const { webhookPartner, programEnrollment } = createdCommission;
-
await Promise.allSettled([
executeWorkflows({
trigger: "partnerMetricsUpdated",
@@ -538,24 +520,15 @@ const _trackSale = async ({
programId: link.programId,
eventType: "sale",
}),
-
- webhookPartner &&
- detectAndRecordFraudEvent({
- program: { id: link.programId },
- partner: pick(webhookPartner, ["id", "email", "name"]),
- programEnrollment: pick(programEnrollment, ["status"]),
- customer: {
- ...pick(customer, ["id", "email", "name"]),
- isFirstConversion: firstConversionFlag,
- },
- link: pick(link, ["id"]),
- click: pick(saleData, ["url", "referer"]),
- event: { id: saleData.event_id },
- }),
]);
}
await Promise.allSettled([
+ recordSale({
+ ...saleData,
+ timestamp: undefined,
+ }),
+
sendWorkspaceWebhook({
trigger: "sale.created",
data: transformSaleEventData({
@@ -563,7 +536,7 @@ const _trackSale = async ({
clickedAt: customer.clickedAt || customer.createdAt,
link,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata,
}),
workspace,
@@ -583,6 +556,12 @@ const _trackSale = async ({
}),
]
: []),
+
+ publishWorkspaceClicksUsageEvent({
+ linkId: link.id,
+ workspaceId: workspace.id,
+ timestamp: new Date().toISOString(),
+ }),
]);
// Update customer stats + program/partner associations
diff --git a/apps/web/lib/api/partners/applications/approve-partner.ts b/apps/web/lib/api/partners/applications/approve-partner.ts
index a22d30ccf6..2cc40458a9 100644
--- a/apps/web/lib/api/partners/applications/approve-partner.ts
+++ b/apps/web/lib/api/partners/applications/approve-partner.ts
@@ -3,7 +3,7 @@ import { prisma } from "@dub/prisma";
import { ProgramEnrollmentStatus } from "@dub/prisma/client";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
-import { triggerWorkflows } from "../../../cron/qstash-workflow";
+import { triggerQStashWorkflow } from "../../../cron/qstash-workflow";
import { throwIfPartnersLimitExceeded } from "../../../partners/throw-if-partners-limit-exceeded";
import { approvePartnerSchema } from "../../../zod/schemas/partners";
import { trackActivityLog } from "../../activity-log/track-activity-log";
@@ -150,8 +150,9 @@ export async function approvePartner({
partnerIds: [partnerId],
}),
- triggerWorkflows({
- workflowId: "partner-approved",
+ triggerQStashWorkflow({
+ workflowType: "partner-approved",
+ workflowLabel: partnerId,
body: {
programId,
partnerId,
diff --git a/apps/web/lib/bounty/api/approve-bounty-submission.ts b/apps/web/lib/bounty/api/approve-bounty-submission.ts
index 6326c46c35..c7bddecea1 100644
--- a/apps/web/lib/bounty/api/approve-bounty-submission.ts
+++ b/apps/web/lib/bounty/api/approve-bounty-submission.ts
@@ -3,7 +3,7 @@ import { DubApiError } from "@/lib/api/errors";
import { Session } from "@/lib/auth";
import { calculateSocialMetricsRewardAmount } from "@/lib/bounty/rewards";
import { resolveBountyDetails } from "@/lib/bounty/utils";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import {
approveBountySubmissionBodySchema,
BountySubmissionSchema,
@@ -106,23 +106,6 @@ export async function approveBountySubmission({
});
}
- const { commission } = await createPartnerCommission({
- event: "custom",
- partnerId: submission.partnerId,
- programId: submission.programId,
- amount: finalRewardAmount,
- quantity: 1,
- user,
- description: `Commission for successfully completed "${bounty.name}" bounty.`,
- });
-
- if (!commission) {
- throw new DubApiError({
- code: "internal_server_error",
- message: "Failed to create commission for the bounty submission.",
- });
- }
-
const approvedSubmission = await prisma.bountySubmission.update({
where: {
id: submissionId,
@@ -133,7 +116,6 @@ export async function approveBountySubmission({
userId: user.id,
rejectionNote: null,
rejectionReason: null,
- commissionId: commission.id,
},
include: {
partner: {
@@ -154,6 +136,17 @@ export async function approveBountySubmission({
},
});
+ await queuePartnerCommissionCreation({
+ event: "custom",
+ partnerId: submission.partnerId,
+ programId: submission.programId,
+ amount: finalRewardAmount,
+ quantity: 1,
+ userId: user.id,
+ description: `Commission for successfully completed "${bounty.name}" bounty.`,
+ bountySubmissionId: submissionId,
+ });
+
const { program, partner } = approvedSubmission;
waitUntil(
diff --git a/apps/web/lib/cron/index.ts b/apps/web/lib/cron/index.ts
index 87184a66a7..7b9eb8fdc8 100644
--- a/apps/web/lib/cron/index.ts
+++ b/apps/web/lib/cron/index.ts
@@ -1,7 +1,7 @@
import { Client } from "@upstash/qstash";
export const qstash = new Client({
- baseUrl: "https://qstash-us-east-1.upstash.io",
+ baseUrl: process.env.QSTASH_URL || "https://qstash-us-east-1.upstash.io",
token: process.env.QSTASH_TOKEN || "",
});
diff --git a/apps/web/lib/cron/qstash-workflow-logger.ts b/apps/web/lib/cron/qstash-workflow-logger.ts
deleted file mode 100644
index a88195c74a..0000000000
--- a/apps/web/lib/cron/qstash-workflow-logger.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-type LogData = {
- message: string;
- data?: Record<string, any>;
-};
-
-type ErrorData = {
- message: string;
- error?: any;
- data?: Record<string, any>;
-};
-
-// Create a context-aware logger factory
-export function createWorkflowLogger({
- workflowId,
- workflowRunId,
-}: {
- workflowId: string;
- workflowRunId: string;
-}) {
- return {
- info: ({ message, data }: LogData) => {
- console.info(`[Upstash Workflow:${workflowId}] ${message}`, {
- workflowRunId,
- ...data,
- });
- },
-
- error: ({ message, error, data }: ErrorData) => {
- console.error(`[Upstash Workflow:${workflowId}] ${message}`, {
- workflowRunId,
- error: error?.message || error,
- ...data,
- });
- },
- };
-}
diff --git a/apps/web/lib/cron/qstash-workflow.ts b/apps/web/lib/cron/qstash-workflow.ts
index e012f736f9..b0b99a36e5 100644
--- a/apps/web/lib/cron/qstash-workflow.ts
+++ b/apps/web/lib/cron/qstash-workflow.ts
@@ -1,63 +1,110 @@
-import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { logger } from "@/lib/axiom/server";
+import { APP_DOMAIN, pluralize } from "@dub/utils";
+import { FlowControl } from "@upstash/qstash";
import { Client } from "@upstash/workflow";
const client = new Client({
- baseUrl: "https://qstash-us-east-1.upstash.io",
+ baseUrl: process.env.QSTASH_URL || "https://qstash-us-east-1.upstash.io",
token: process.env.QSTASH_TOKEN || "",
});
-const WORKFLOW_RETRIES = 3;
-const WORKFLOW_PARALLELISM = 20;
-
-type WorkflowIds = "partner-approved";
+type WorkflowType = "partner-approved" | "create-partner-commission";
interface QStashWorkflow {
- workflowId: WorkflowIds;
- body?: Record<string, unknown>;
+ workflowType: WorkflowType;
+ workflowLabel: string;
+ body: Record<string, unknown>;
+ flowControl?: FlowControl;
}
// Run workflows
-export async function triggerWorkflows(
+export async function triggerQStashWorkflow(
input: QStashWorkflow | QStashWorkflow[],
) {
- try {
- const workflows = Array.isArray(input) ? input : [input];
-
- const results = await client.trigger(
- workflows.map((workflow) => ({
- url: `${APP_DOMAIN_WITH_NGROK}/api/workflows/${workflow.workflowId}`,
- body: workflow.body,
- retries: WORKFLOW_RETRIES,
- flowControl: {
- key: workflow.workflowId,
- parallelism: WORKFLOW_PARALLELISM,
- },
- })),
- );
-
- if (process.env.NODE_ENV === "development") {
- console.debug("[Upstash] Workflows triggered", {
- count: workflows.length,
- ids: workflows.map((w) => w.workflowId),
- results,
- });
- }
+ const workflows = Array.isArray(input) ? input : [input];
+ const maxRetries = 3;
+
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ try {
+ const response = await client.trigger(
+ workflows.map((workflow) => ({
+ url: `${APP_DOMAIN}/api/workflows/${workflow.workflowType}`,
+ body: workflow.body,
+ label: workflow.workflowLabel,
+ retries: 5,
+ flowControl: workflow.flowControl ?? {
+ key: workflow.workflowType,
+ parallelism: 15,
+ },
+ })),
+ );
+
+ console.log(
+ `${response.length} QStash ${pluralize("workflow", response.length)} triggered`,
+ response,
+ );
+
+ return response;
+ } catch (error) {
+ console.error("QStash workflow trigger failed", { error, workflows });
+
+ if (attempt < maxRetries) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, 1000 * Math.pow(2, attempt)),
+ );
+ continue;
+ }
+
+ for (const workflow of workflows) {
+ const { correlation } = getWorkflowConfig(workflow);
- return results;
- } catch (error) {
- const message =
- error instanceof Error ? error.message : JSON.stringify(error);
+ logger.error("workflow.trigger_failed", {
+ service: "qstash",
+ event: "workflow.trigger_failed",
+ workflowType: workflow.workflowType,
+ errorName: error instanceof Error ? error.name : undefined,
+ errorStack: error instanceof Error ? error.stack : undefined,
+ correlation,
+ });
+ }
- console.error("[Upstash] Failed to trigger workflows", {
- error: message,
- input,
- });
+ await logger.flush();
- await log({
- message: `[Upstash] Failed to trigger QStash workflows. ${message}`,
- type: "errors",
- });
+ return null;
+ }
+ }
+}
+
+export function getWorkflowConfig({
+ workflowType,
+ body,
+}: Omit<QStashWorkflow, "workflowLabel">): {
+ correlation: Record<string, unknown>;
+} {
+ switch (workflowType) {
+ case "partner-approved":
+ return {
+ correlation: {
+ programId: body.programId,
+ partnerId: body.partnerId,
+ userId: body.userId,
+ },
+ };
+
+ case "create-partner-commission": {
+ return {
+ correlation: {
+ programId: body.programId,
+ partnerId: body.partnerId,
+ customerId: body.customerId,
+ bountySubmissionId: body.bountySubmissionId,
+ },
+ };
+ }
- return null;
+ default:
+ return {
+ correlation: {},
+ };
}
}
diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.ts
index 18a5c14b09..3b89c4e8ca 100644
--- a/apps/web/lib/integrations/shopify/create-sale.ts
+++ b/apps/web/lib/integrations/shopify/create-sale.ts
@@ -1,9 +1,8 @@
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
-import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-event";
import { includeTags } from "@/lib/api/links/include-tags";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { recordSale } from "@/lib/tinybird";
import { LeadEventTB } from "@/lib/types";
@@ -11,7 +10,7 @@ import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
-import { nanoid, pick } from "@dub/utils";
+import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { orderSchema } from "./schema";
@@ -132,12 +131,12 @@ export async function createShopifySale({
]);
// for program links
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
+ let result:
+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link.programId && link.partnerId) {
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "sale",
programId: link.programId,
partnerId: link.partnerId,
@@ -157,10 +156,13 @@ export async function createShopifySale({
amount: saleData.amount,
},
},
+ clickEvent: {
+ url: saleData.url,
+ referer: saleData.referer,
+ },
+ isFirstConversion: firstConversionFlag,
});
- const { webhookPartner, programEnrollment } = createdCommission;
-
waitUntil(
Promise.allSettled([
executeWorkflows({
@@ -184,20 +186,6 @@ export async function createShopifySale({
programId: link.programId,
eventType: "sale",
}),
-
- webhookPartner &&
- detectAndRecordFraudEvent({
- program: { id: link.programId },
- partner: pick(webhookPartner, ["id", "email", "name"]),
- programEnrollment: pick(programEnrollment, ["status"]),
- customer: {
- ...pick(customer, ["id", "email", "name"]),
- isFirstConversion: firstConversionFlag,
- },
- link: pick(link, ["id"]),
- click: pick(saleData, ["url", "referer"]),
- event: { id: saleData.event_id },
- }),
]),
);
}
@@ -212,7 +200,7 @@ export async function createShopifySale({
link,
clickedAt: customer.clickedAt || customer.createdAt,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata: null,
}),
}),
diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.ts
index 80dc1e7ddf..0c8e8428c5 100644
--- a/apps/web/lib/integrations/shopify/process-order.ts
+++ b/apps/web/lib/integrations/shopify/process-order.ts
@@ -4,7 +4,7 @@ import { includeTags } from "@/lib/api/links/include-tags";
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { generateRandomName } from "@/lib/names";
-import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";
import { getLeadEvent, recordLead } from "@/lib/tinybird";
import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
@@ -150,12 +150,12 @@ export async function attributeViaDiscountCode({
include: includeTags,
});
- let createdCommission:
- | Awaited<ReturnType<typeof createPartnerCommission>>
+ let result:
+ | Awaited<ReturnType<typeof queuePartnerCommissionCreation>>
| undefined = undefined;
if (link.programId && link.partnerId) {
- createdCommission = await createPartnerCommission({
+ result = await queuePartnerCommissionCreation({
event: "lead",
programId: link.programId,
partnerId: link.partnerId,
@@ -203,7 +203,7 @@ export async function attributeViaDiscountCode({
eventName: "Checkout with discount code",
link: linkUpdated,
customer,
- partner: createdCommission?.webhookPartner,
+ partner: result?.webhookPartner,
metadata: null,
}),
}),
diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.ts
deleted file mode 100644
index 268284d897..0000000000
--- a/apps/web/lib/partners/create-partner-commission.ts
+++ /dev/null
@@ -1,456 +0,0 @@
-import { prisma } from "@dub/prisma";
-import {
- Commission,
- CommissionStatus,
- CommissionType,
-} from "@dub/prisma/client";
-import { currencyFormatter, log, prettyPrint, toCentsNumber } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { differenceInMonths } from "date-fns";
-import { recordAuditLog } from "../api/audit-logs/record-audit-log";
-import { createId } from "../api/create-id";
-import { notifyPartnerCommission } from "../api/partners/notify-partner-commission";
-import { syncTotalCommissions } from "../api/partners/sync-total-commissions";
-import { getProgramEnrollmentOrThrow } from "../api/programs/get-program-enrollment-or-throw";
-import { calculateSaleEarnings } from "../api/sales/calculate-sale-earnings";
-import { executeWorkflows } from "../api/workflows/execute-workflows";
-import { Session } from "../auth";
-import { sendPartnerPostback } from "../postback/send-partner-postback";
-import { RewardContext, RewardProps } from "../types";
-import { sendWorkspaceWebhook } from "../webhook/publish";
-import { CommissionWebhookSchema } from "../zod/schemas/commissions";
-import { DEFAULT_PARTNER_GROUP } from "../zod/schemas/groups";
-import { constructWebhookPartner } from "./constuct-webhook-partner";
-import { determinePartnerReward } from "./determine-partner-reward";
-import { getRewardAmount } from "./get-reward-amount";
-
-export type CreatePartnerCommissionProps = {
- event: CommissionType;
- partnerId: string;
- programId: string;
- linkId?: string;
- customerId?: string;
- eventId?: string;
- invoiceId?: string | null;
- amount?: number;
- quantity: number;
- currency?: string;
- description?: string | null;
- createdAt?: Date;
- user?: Session["user"]; // user who created the manual commission
- context?: RewardContext;
- skipWorkflow?: boolean;
-};
-
-export const createPartnerCommission = async ({
- event,
- partnerId,
- programId,
- linkId,
- customerId,
- eventId,
- invoiceId,
- amount = 0,
- quantity,
- currency,
- description,
- createdAt,
- user,
- context,
- skipWorkflow = false,
-}: CreatePartnerCommissionProps) => {
- let earnings = 0;
- let reward: RewardProps | null = null;
- let status: CommissionStatus = "pending";
-
- const programEnrollment = await getProgramEnrollmentOrThrow({
- partnerId,
- programId,
- include: {
- links: true,
- partner: true,
- partnerGroup: true,
- ...(event === "click" && { clickReward: true }),
- ...(event === "lead" && { leadReward: true }),
- ...(event === "sale" && { saleReward: true }),
- },
- });
-
- let firstCommission: Pick<
- Commission,
- "rewardId" | "status" | "createdAt"
- > | null = null;
-
- if (event === "custom") {
- earnings = amount;
- amount = 0;
- } else {
- if (["lead", "sale"].includes(event) && customerId) {
- firstCommission = await prisma.commission.findFirst({
- where: {
- partnerId,
- customerId,
- type: event,
- },
- orderBy: {
- createdAt: "asc",
- },
- select: {
- rewardId: true,
- status: true,
- createdAt: true,
- },
- });
-
- const subscriptionStartDate =
- event === "sale" ? firstCommission?.createdAt ?? new Date() : undefined;
-
- const subscriptionDurationMonths = subscriptionStartDate
- ? differenceInMonths(
- createdAt ?? new Date(), // account for custom commission creation date
- subscriptionStartDate,
- )
- : 0;
-
- context = {
- ...context,
- customer: {
- ...context?.customer,
- subscriptionStartDate,
- subscriptionDurationMonths,
- },
- ...(event === "sale" && {
- sale: {
- ...context?.sale,
- type: firstCommission ? "recurring" : "new",
- },
- }),
- };
- }
-
- reward = determinePartnerReward({
- event,
- programEnrollment,
- context,
- });
-
- // if there is no reward, skip commission creation
- if (!reward) {
- console.log(
- `Partner ${partnerId} has no reward for ${event} event, skipping commission creation...`,
- );
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
-
- // for click events, it's super simple – just multiply the reward amount by the quantity
- if (event === "click") {
- earnings = getRewardAmount(reward) * quantity;
-
- // for lead and sale events, we need to check if this partner-customer combination was recorded already (for deduplication)
- // for sale rewards specifically, we also need to check:
- // 1. if the partner has reached the max duration for the reward (if applicable)
- // 2. if the previous commission were marked as fraud or canceled
- } else {
- if (firstCommission) {
- // if first commission is fraud or canceled, skip commission creation
- if (["fraud", "canceled"].includes(firstCommission.status)) {
- console.log(
- `Partner ${partnerId} has a first commission that is ${firstCommission.status}, skipping commission creation...`,
- );
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
-
- // for lead events, we need to check if the partner has already been issued a lead reward for this customer
- if (event === "lead") {
- console.log(
- `Partner ${partnerId} has already been issued a lead reward for this customer ${customerId}, skipping commission creation...`,
- );
-
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
-
- // for sale rewards, we need to check if partner's reward was updated and different from the first commission's reward
- // we need to make sure it wasn't changed from one-time to recurring so we don't create a new commission
- } else {
- if (
- firstCommission.rewardId &&
- firstCommission.rewardId !== reward.id
- ) {
- const originalReward = await prisma.reward.findUnique({
- where: {
- id: firstCommission.rewardId,
- },
- select: {
- id: true,
- maxDuration: true,
- },
- });
-
- if (
- typeof originalReward?.maxDuration === "number" &&
- originalReward.maxDuration === 0
- ) {
- console.log(
- `Partner ${partnerId} is only eligible for first-sale commissions based on the original reward ${originalReward.id}, skipping commission creation...`,
- );
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
- }
-
- // for sale rewards with a max duration, we need to check if the first commission is within the max duration
- // if it's beyond the max duration, we should not create a new commission
- if (typeof reward?.maxDuration === "number") {
- // One-time sale reward (maxDuration === 0)
- if (reward.maxDuration === 0) {
- console.log(
- `Partner ${partnerId} is only eligible for first-sale commissions, skipping commission creation...`,
- );
-
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
-
- // Recurring sale reward (maxDuration > 0)
- else {
- const subscriptionDurationMonths = differenceInMonths(
- createdAt ?? new Date(), // account for custom commission creation date
- firstCommission.createdAt,
- );
-
- if (subscriptionDurationMonths >= reward.maxDuration) {
- console.log(
- `Partner ${partnerId} has reached max duration for ${event} event (subscription duration: ${subscriptionDurationMonths} months, max duration: ${reward.maxDuration} months), skipping commission creation...`,
- );
-
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
- }
- }
- }
- }
-
- // for lead events, we just multiply the reward amount by the quantity
- if (event === "lead") {
- earnings = getRewardAmount(reward) * quantity;
- // for sale events, we need to calculate the earnings based on the sale amount
- } else {
- earnings = calculateSaleEarnings({
- reward,
- sale: { quantity, amount },
- });
- }
- }
- }
-
- // skip commission creation if the earnings is zero
- if (earnings === 0) {
- console.log(
- `Partner ${partnerId} has zero earnings for ${event} event, skipping commission creation...`,
- );
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
-
- try {
- const commission = await prisma.commission.create({
- data: {
- id: createId({ prefix: "cm_" }),
- programId,
- partnerId,
- rewardId: reward?.id,
- customerId,
- linkId,
- eventId: eventId || null, // empty string should convert to null
- invoiceId: invoiceId || null, // empty string should convert to null
- userId: user?.id,
- quantity,
- amount,
- type: event,
- currency,
- earnings,
- status,
- description,
- createdAt,
- },
- include: {
- customer: true,
- link: {
- select: {
- id: true,
- shortLink: true,
- domain: true,
- key: true,
- },
- },
- },
- });
-
- console.log(
- `Created a ${event} commission ${commission.id} (${currencyFormatter(commission.earnings, { currency: commission.currency })}) for ${partnerId}: ${prettyPrint(commission)}`,
- );
-
- const webhookPartner = constructWebhookPartner(programEnrollment, {
- // check links metrics
- totalCommissions:
- toCentsNumber(programEnrollment.totalCommissions) + commission.earnings,
- });
-
- waitUntil(
- (async () => {
- const program = await prisma.program.findUniqueOrThrow({
- where: {
- id: programId,
- },
- select: {
- id: true,
- name: true,
- slug: true,
- logo: true,
- supportEmail: true,
- workspace: {
- select: {
- id: true,
- slug: true,
- name: true,
- webhookEnabled: true,
- },
- },
- // if no partner group is found, need to fetch default group to fallback to
- ...(!programEnrollment.partnerGroup && {
- groups: {
- select: {
- holdingPeriodDays: true,
- },
- where: {
- slug: DEFAULT_PARTNER_GROUP.slug,
- },
- },
- }),
- },
- });
-
- const { workspace } = program;
- const isClawback = commission.earnings < 0;
- const shouldTriggerWorkflow = !isClawback && !skipWorkflow;
-
- await Promise.allSettled([
- sendWorkspaceWebhook({
- workspace,
- trigger: "commission.created",
- data: CommissionWebhookSchema.parse({
- ...commission,
- partner: webhookPartner,
- }),
- }),
-
- sendPartnerPostback({
- partnerId,
- event: "commission.created",
- data: {
- ...commission,
- customer: commission.customer,
- },
- }),
-
- syncTotalCommissions({
- partnerId,
- programId,
- }),
-
- !isClawback &&
- notifyPartnerCommission({
- program,
- // fallback to default group if no partner group is found
- group: programEnrollment.partnerGroup ?? program.groups[0],
- workspace,
- commission,
- isFirstCommission: firstCommission === null,
- }),
-
- // We only capture audit logs for manual commissions
- user &&
- recordAuditLog({
- workspaceId: workspace.id,
- programId,
- action: isClawback ? "clawback.created" : "commission.created",
- description: isClawback
- ? `Clawback created for ${partnerId}`
- : `Commission created for ${partnerId}`,
- actor: user,
- targets: [
- {
- type: isClawback ? "clawback" : "commission",
- id: commission.id,
- metadata: commission,
- },
- ],
- }),
-
- shouldTriggerWorkflow &&
- executeWorkflows({
- trigger: "partnerMetricsUpdated",
- reason: "commission",
- identity: {
- workspaceId: workspace.id,
- programId,
- partnerId,
- },
- metrics: {
- current: {
- commissions: commission.earnings,
- },
- },
- }),
- ]);
- })(),
- );
-
- return {
- commission,
- programEnrollment,
- webhookPartner,
- };
- } catch (error) {
- console.error("Error creating commission", error);
-
- // only log to Slack if the error is not a unique constraint violation
- if (error.code !== "P2002") {
- await log({
- message: `Error creating commission - ${error.message}`,
- type: "errors",
- mention: true,
- });
- }
-
- return {
- commission: null,
- programEnrollment,
- webhookPartner: constructWebhookPartner(programEnrollment),
- };
- }
-};
diff --git a/apps/web/lib/partners/queue-partner-commission-creation.ts b/apps/web/lib/partners/queue-partner-commission-creation.ts
new file mode 100644
index 0000000000..b504c46e34
--- /dev/null
+++ b/apps/web/lib/partners/queue-partner-commission-creation.ts
@@ -0,0 +1,38 @@
+import { getProgramEnrollmentOrThrow } from "../api/programs/get-program-enrollment-or-throw";
+import { triggerQStashWorkflow } from "../cron/qstash-workflow";
+import { CreatePartnerCommissionProps } from "../types";
+import { constructWebhookPartner } from "./constuct-webhook-partner";
+
+export const queuePartnerCommissionCreation = async (
+ params: CreatePartnerCommissionProps,
+) => {
+ const { partnerId, programId, customerId, bountySubmissionId } = params;
+
+ const result = await getProgramEnrollmentOrThrow({
+ partnerId,
+ programId,
+ include: {
+ links: true,
+ partner: true,
+ },
+ });
+
+ const { partner, links, ...programEnrollment } = result;
+
+ await triggerQStashWorkflow({
+ workflowType: "create-partner-commission",
+ workflowLabel: bountySubmissionId ?? customerId ?? partnerId,
+ body: params,
+ flowControl: {
+ key: customerId ?? partnerId,
+ parallelism: 1,
+ },
+ });
+
+ return {
+ partner,
+ links,
+ programEnrollment,
+ webhookPartner: constructWebhookPartner(result),
+ };
+};
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 21cac82baf..0f5b07a7b1 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -96,6 +96,7 @@ import {
CommissionDetailSchema,
CommissionEnrichedSchema,
CommissionSchema,
+ createPartnerCommissionSchema,
} from "./zod/schemas/commissions";
import { customerActivityResponseSchema } from "./zod/schemas/customer-activity";
import {
@@ -978,3 +979,7 @@ export type ApplicationAnalyticsByGroup = {
};
export type CommissionProps = z.infer<typeof CommissionSchema>;
+
+export type CreatePartnerCommissionProps = z.infer<
+ typeof createPartnerCommissionSchema
+>;
diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.ts
index c3c264d857..68e9414274 100644
--- a/apps/web/lib/zod/schemas/commissions.ts
+++ b/apps/web/lib/zod/schemas/commissions.ts
@@ -9,7 +9,7 @@ import {
} from "./misc";
import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";
import { PayoutSchema } from "./payouts";
-import { RewardSchema } from "./rewards";
+import { rewardContextSchema, RewardSchema } from "./rewards";
import { UserSchema } from "./users";
import { centsSchema, parseDateSchema } from "./utils";
@@ -431,3 +431,35 @@ export const commissionsExportQuerySchema = getCommissionsQuerySchema
},
),
});
+
+export const createPartnerCommissionSchema = z.object({
+ event: z.enum(CommissionType),
+ partnerId: z.string(),
+ programId: z.string(),
+ linkId: z.string().optional(),
+ customerId: z.string().optional(),
+ eventId: z.string().optional(),
+ invoiceId: z.string().nullish(),
+ amount: z.number().default(0).optional(),
+ quantity: z.number().default(1),
+ currency: z.string().optional(),
+ description: z.string().nullish(),
+ createdAt: z.coerce.date().optional(),
+ status: commissionPatchStatusSchema.optional(), // used for create-manual-commission (import commission as refunded)
+ userId: z.string().optional(),
+ context: rewardContextSchema.optional(),
+ skipWorkflow: z.boolean().default(false).optional(),
+ isFirstConversion: z.boolean().optional(),
+ bountySubmissionId: z
+ .string()
+ .optional()
+ .describe(
+ "The ID of the bounty submission that the commission should be created for.",
+ ),
+ clickEvent: z
+ .object({
+ url: z.string().nullable(),
+ referer: z.string().nullable(),
+ })
+ .optional(),
+});
diff --git a/apps/web/lib/zod/schemas/rewards.ts b/apps/web/lib/zod/schemas/rewards.ts
index 54f4e43503..35fc88450e 100644
--- a/apps/web/lib/zod/schemas/rewards.ts
+++ b/apps/web/lib/zod/schemas/rewards.ts
@@ -411,8 +411,8 @@ export const rewardContextSchema = z.object({
.object({
country: z.string().nullish(),
source: z.enum(CUSTOMER_SOURCES).default("tracked").nullish(),
- signupDate: z.date().nullish(),
- subscriptionStartDate: z.date().nullish(),
+ signupDate: z.coerce.date().nullish(),
+ subscriptionStartDate: z.coerce.date().nullish(),
subscriptionDurationMonths: z.number().nullish(),
})
.optional(),
diff --git a/apps/web/scripts/programs/backfill-reuse-commission.ts b/apps/web/scripts/programs/backfill-reuse-commission.ts
index 8a609bd14e..07a18cd7d8 100644
--- a/apps/web/scripts/programs/backfill-reuse-commission.ts
+++ b/apps/web/scripts/programs/backfill-reuse-commission.ts
@@ -4,10 +4,7 @@ import { updateLinkStatsForImporter } from "@/lib/api/links/update-link-stats-fo
import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";
import { qstash } from "@/lib/cron";
-import {
- createPartnerCommission,
- CreatePartnerCommissionProps,
-} from "@/lib/partners/create-partner-commission";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
import { getCustomerEventsTB } from "@/lib/tinybird/get-customer-events-tb";
import {
recordClickZod,
@@ -15,6 +12,7 @@ import {
} from "@/lib/tinybird/record-click-zod";
import { recordLeadWithTimestamp } from "@/lib/tinybird/record-lead";
import { recordSaleWithTimestamp } from "@/lib/tinybird/record-sale";
+import { CreatePartnerCommissionProps } from "@/lib/types";
import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
import { prisma } from "@dub/prisma";
@@ -130,7 +128,6 @@ async function main() {
eventId: leadEventData.event_id,
quantity: 1,
createdAt: new Date(leadEventData.timestamp + "Z"), // add the "Z" to the timestamp to make it UTC
- user,
context: {
customer: { country: customer.country },
},
@@ -316,7 +313,7 @@ async function main() {
console.log("Commissions to create: ", commissionsToCreate);
await Promise.allSettled(
commissionsToCreate.map((commission) =>
- createPartnerCommission({ ...commission, skipWorkflow: true }),
+ queuePartnerCommissionCreation({ ...commission, skipWorkflow: true }),
),
);
diff --git a/apps/web/tests/fraud/index.test.ts b/apps/web/tests/fraud/index.test.ts
index 21bf74b52a..dd9b5b6e87 100644
--- a/apps/web/tests/fraud/index.test.ts
+++ b/apps/web/tests/fraud/index.test.ts
@@ -1,19 +1,14 @@
import { extractEmailDomain } from "@/lib/email/extract-email-domain";
-import { Customer, TrackLeadResponse } from "@/lib/types";
-import {
- CustomerEmailMatchType,
- fraudEventSchemas,
-} from "@/lib/zod/schemas/fraud";
-import { FraudRuleType, Partner } from "@dub/prisma/client";
-import { randomCustomer, retry } from "tests/utils/helpers";
-import { HttpClient } from "tests/utils/http";
+import { TrackLeadResponse } from "@/lib/types";
+import { CustomerEmailMatchType } from "@/lib/zod/schemas/fraud";
+import { randomCustomer } from "tests/utils/helpers";
import {
E2E_FRAUD_PARTNER,
E2E_FRAUD_REFERRAL_SOURCE_BANNED_DOMAIN,
E2E_TRACK_CLICK_HEADERS,
} from "tests/utils/resource";
-import { describe, expect, test } from "vitest";
-import * as z from "zod/v4";
+import { verifyFraudEvent } from "tests/utils/verify-fraud-event";
+import { describe, test } from "vitest";
import { IntegrationHarness } from "../utils/integration";
describe.concurrent("/fraud/**", async () => {
@@ -269,81 +264,3 @@ describe.concurrent("/fraud/**", async () => {
});
});
});
-
-const verifyFraudEvent = async ({
- http,
- partner,
- customer,
- ruleType,
- metadata,
-}: {
- http: HttpClient;
- partner: Pick<Partner, "id" | "name" | "email" | "image">;
- customer: Pick<Customer, "externalId">;
- ruleType: FraudRuleType;
- metadata?: Record<string, unknown>;
-}) => {
- // Resolve customerId from customerExternalID
- const { data: customers } = await http.get<Customer[]>({
- path: "/customers",
- query: { externalId: customer.externalId },
- });
-
- expect(customers.length).toBeGreaterThan(0);
-
- // Wait until fraud event is available
- const fraudEvent = await waitForFraudEvent({
- http,
- customerId: customers[0].id,
- ruleType,
- });
-
- // Assert fraud event shape
- expect(fraudEvent).toStrictEqual({
- createdAt: expect.any(String),
- partner: expect.objectContaining({
- id: partner.id,
- name: partner.name,
- email: partner.email,
- image: partner.image,
- }),
- ...(metadata && { metadata }),
- customer: expect.objectContaining({
- id: customers[0].id,
- name: customers[0].name,
- email: customers[0].email,
- avatar: customers[0].avatar,
- }),
- });
-};
-
-async function waitForFraudEvent({
- http,
- customerId,
- ruleType,
-}: {
- http: HttpClient;
- customerId: string;
- ruleType: FraudRuleType;
-}) {
- return await retry(
- async () => {
- const { data } = await http.get<
- z.infer<(typeof fraudEventSchemas)[keyof typeof fraudEventSchemas]>[]
- >({
- path: "/fraud/events",
- query: {
- customerId,
- type: ruleType,
- },
- });
-
- if (!data.length) {
- throw new Error("Fraud event not ready.");
- }
-
- return data[0];
- },
- { retries: 10, interval: 600 },
- );
-}
diff --git a/apps/web/tests/utils/verify-commission.ts b/apps/web/tests/utils/verify-commission.ts
index 13cee18ab9..ed5f10c045 100644
--- a/apps/web/tests/utils/verify-commission.ts
+++ b/apps/web/tests/utils/verify-commission.ts
@@ -11,7 +11,7 @@ interface VerifyCommissionProps {
}
const POLL_INTERVAL_MS = 5000; // 5 seconds
-const TIMEOUT_MS = 45000; // 45 seconds
+const TIMEOUT_MS = 60000; // 60 seconds
export const verifyCommission = async ({
http,
@@ -43,7 +43,7 @@ export const verifyCommission = async ({
query.customerId = customerId;
}
- // Poll for commission every 5 seconds, timeout after 45 seconds
+ // Poll for commission every 5 seconds, timeout after 60 seconds
const startTime = Date.now();
while (Date.now() - startTime < TIMEOUT_MS) {
diff --git a/apps/web/tests/utils/verify-fraud-event.ts b/apps/web/tests/utils/verify-fraud-event.ts
new file mode 100644
index 0000000000..0661a607b4
--- /dev/null
+++ b/apps/web/tests/utils/verify-fraud-event.ts
@@ -0,0 +1,82 @@
+import { Customer } from "@/lib/types";
+import { fraudEventSchemas } from "@/lib/zod/schemas/fraud";
+import { FraudRuleType, Partner } from "@dub/prisma/client";
+import { HttpClient } from "tests/utils/http";
+import { expect } from "vitest";
+import * as z from "zod/v4";
+
+const POLL_INTERVAL_MS = 5000; // 5 seconds
+const TIMEOUT_MS = 60000; // 60 seconds
+
+export const verifyFraudEvent = async ({
+ http,
+ partner,
+ customer,
+ ruleType,
+ metadata,
+}: {
+ http: HttpClient;
+ partner: Pick<Partner, "id" | "name" | "email" | "image">;
+ customer: Pick<Customer, "externalId">;
+ ruleType: FraudRuleType;
+ metadata?: Record<string, unknown>;
+}) => {
+ // Resolve customerId from customerExternalID
+ const { data: customers } = await http.get<Customer[]>({
+ path: "/customers",
+ query: { externalId: customer.externalId },
+ });
+
+ expect(customers.length).toBeGreaterThan(0);
+
+ // Poll for fraud event every 5 seconds, timeout after 60 seconds
+ const startTime = Date.now();
+ let fraudEvent:
+ | z.infer<(typeof fraudEventSchemas)[keyof typeof fraudEventSchemas]>
+ | undefined;
+
+ while (Date.now() - startTime < TIMEOUT_MS) {
+ const { status, data } = await http.get<
+ z.infer<(typeof fraudEventSchemas)[keyof typeof fraudEventSchemas]>[]
+ >({
+ path: "/fraud/events",
+ query: {
+ customerId: customers[0].id,
+ type: ruleType,
+ },
+ });
+
+ if (status === 200 && data.length > 0) {
+ fraudEvent = data[0];
+ break;
+ }
+
+ // Wait before next poll
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
+ }
+
+ if (!fraudEvent) {
+ throw new Error(
+ `Fraud event not found within ${TIMEOUT_MS / 1000} seconds. ` +
+ `Query: ${JSON.stringify({ customerId: customers[0].id, type: ruleType })}`,
+ );
+ }
+
+ // Assert fraud event shape
+ expect(fraudEvent).toStrictEqual({
+ createdAt: expect.any(String),
+ partner: expect.objectContaining({
+ id: partner.id,
+ name: partner.name,
+ email: partner.email,
+ image: partner.image,
+ }),
+ ...(metadata && { metadata }),
+ customer: expect.objectContaining({
+ id: customers[0].id,
+ name: customers[0].name,
+ email: customers[0].email,
+ avatar: customers[0].avatar,
+ }),
+ });
+};
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 7bc66d0e7a..4281c4a9cf 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -8,7 +8,7 @@ export default defineConfig({
dir: "./tests",
reporters: ["verbose"],
globals: true,
- testTimeout: 50000,
+ testTimeout: 60000,
env: loadEnv("", process.cwd(), ""),
setupFiles: ["./tests/setupTests.ts"],
},