The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add POST /api/commissions for manual commission creation (#3968)
Kiran K1392b1184455
diff --git a/apps/web/app/(ee)/api/commissions/route.ts b/apps/web/app/(ee)/api/commissions/route.tsindex d999975ce6..15ec5f9fc7 100644--- a/apps/web/app/(ee)/api/commissions/route.ts+++ b/apps/web/app/(ee)/api/commissions/route.ts@@ -1,10 +1,14 @@+import { createManualCommissions } from "@/lib/api/commissions/create-manual-commissions";import { getCommissions } from "@/lib/api/commissions/get-commissions";import { transformCustomerForCommission } from "@/lib/api/customers/transform-customer";import { DubApiError } from "@/lib/api/errors";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";+import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import {CommissionEnrichedSchema,+ createCommissionResponseSchema,+ createManualCommissionBodySchema,getCommissionsQuerySchema,} from "@/lib/zod/schemas/commissions";import { prisma } from "@dub/prisma";@@ -75,3 +79,46 @@ export const GET = withWorkspace(async ({ workspace, searchParams }) => {),);});++// POST /api/commissions - create manual commission+export const POST = withWorkspace(+ async ({ workspace, session, req }) => {+ const programId = getDefaultProgramIdOrThrow(workspace);++ const body = createManualCommissionBodySchema.parse(+ await parseRequestBody(req),+ );++ console.time("createManualCommissions");++ await createManualCommissions({+ ...body,+ workspace,+ programId,+ user: session.user,+ });++ console.timeEnd("createManualCommissions");++ return NextResponse.json(+ createCommissionResponseSchema.parse({+ success: true,+ message: "Your commissions are being created and will appear shortly.",+ }),+ {+ status: 202,+ },+ );+ },+ {+ requiredPlan: [+ "business",+ "business plus",+ "business extra",+ "business max",+ "advanced",+ "enterprise",+ ],+ requiredRoles: ["owner", "member"],+ },+);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.tsindex 9b4e655c8a..d3a5cdaa01 100644--- a/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts+++ b/apps/web/app/(ee)/api/workflows/create-partner-commission/route.ts@@ -1,3 +1,4 @@+import { triggerAggregateDueCommissionsCronJob } from "@/lib/actions/partners/trigger-aggregate-due-commissions";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";@@ -432,6 +433,8 @@ async function stepRunSideEffects(skipWorkflow,clickEvent,isFirstConversion,+ userId,+ triggerAggregateDueCommissions,} = input;if (!_commission) {@@ -563,6 +566,10 @@ async function stepRunSideEffects(click: pick(clickEvent, ["url", "referer"]),event: { id: eventId },}),++ // Aggregate due commissions immediately for manual commission+ triggerAggregateDueCommissions &&+ triggerAggregateDueCommissionsCronJob(programId),]);return [diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsxindex 4d3bbe2b8c..e006a9a77c 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/commissions/create-commission-sheet.tsx@@ -1,9 +1,12 @@-import { createManualCommissionAction } from "@/lib/actions/partners/create-manual-commission";import { handleMoneyKeyDown } from "@/lib/form-utils";import { mutatePrefix } from "@/lib/swr/mutate";+import { useApiMutation } from "@/lib/swr/use-api-mutation";import useRewards from "@/lib/swr/use-rewards";import useWorkspace from "@/lib/swr/use-workspace";-import { createCommissionSchema } from "@/lib/zod/schemas/commissions";+import {+ createCommissionResponseSchema,+ createManualCommissionBodySchema,+} from "@/lib/zod/schemas/commissions";import { StripeCustomerInvoiceSchema } from "@/lib/zod/schemas/customers";import { CustomerSelector } from "@/ui/customers/customer-selector";import { PartnerLinkSelector } from "@/ui/partners/partner-link-selector";@@ -27,7 +30,6 @@ import {ToggleGroup,} from "@dub/ui";import { cn, currencyFormatter, formatDate } from "@dub/utils";-import { useAction } from "next-safe-action/hooks";import { useParams } from "next/navigation";import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";import { Controller, useForm } from "react-hook-form";@@ -39,7 +41,27 @@ interface CreateCommissionSheetProps {setIsOpen: Dispatch<SetStateAction<boolean>>;}-type FormData = z.infer<typeof createCommissionSchema>;+// Flatten the discriminated union for react-hook-form compatibility.+// The form renders all possible fields; onSubmit builds the correct variant.+type CreateCommissionBody = z.infer<typeof createManualCommissionBodySchema>;+type CustomBody = Extract<CreateCommissionBody, { type: "custom" }>;+type LeadBody = Extract<CreateCommissionBody, { type: "lead" }>;+type SaleBody = Extract<CreateCommissionBody, { type: "sale" }>;++type FormData = {+ partnerId: CustomBody["partnerId"];+ amount: CustomBody["amount"] | null;+ date: CustomBody["date"];+ description: CustomBody["description"];+ customerId: LeadBody["customerId"];+ linkId: LeadBody["linkId"];+ leadEventDate: LeadBody["leadEventDate"];+ leadEventName: LeadBody["leadEventName"];+ saleAmount: SaleBody["saleAmount"];+ saleEventDate: SaleBody["saleEventDate"];+ invoiceId: SaleBody["invoiceId"];+ productId: SaleBody["productId"];+};type StripeInvoiceFromApi = z.infer<typeof StripeCustomerInvoiceSchema>;@@ -74,7 +96,7 @@ function CreateCommissionSheetContent({const [hasCustomLeadEventDate, setHasCustomLeadEventDate] = useState(false);const [hasCustomLeadEventName, setHasCustomLeadEventName] = useState(false);- const [useExistingEvents, setUseExistingEvents] = useState(false);+ const [importStripeInvoices, setImportStripeInvoices] = useState(false);const [commissionType, setCommissionType] =useState<CommissionType>("custom");@@ -111,7 +133,6 @@ function CreateCommissionSheetContent({saleEventDate,saleAmount,leadEventDate,- description,] = watch(["partnerId","date",@@ -121,7 +142,6 @@ function CreateCommissionSheetContent({"saleEventDate","saleAmount","leadEventDate",- "description",]);const { rewards } = useRewards();@@ -172,7 +192,10 @@ function CreateCommissionSheetContent({isLoading: isStripeInvoicesLoading,error: stripeInvoicesError,} = useSWR(- customerId && useExistingEvents && commissionType === "sale" && workspaceId+ customerId &&+ importStripeInvoices &&+ commissionType === "sale" &&+ workspaceId? `/api/customers/${customerId}/stripe-invoices?workspaceId=${workspaceId}`: null,fetcherStripeInvoices,@@ -217,16 +240,8 @@ function CreateCommissionSheetContent({}}, [commissionType]);- const { executeAsync, isPending } = useAction(createManualCommissionAction, {- onSuccess: async () => {- toast.success("A commission has been created for the partner!");- setIsOpen(false);- await mutatePrefix(`/api/commissions?workspaceId=${workspaceId}`);- },- onError({ error }) {- toast.error(error.serverError);- },- });+ const { makeRequest, isSubmitting } =+ useApiMutation<z.infer<typeof createCommissionResponseSchema>>();const onSubmit = async (data: FormData) => {if (!workspaceId || !defaultProgramId) {@@ -234,27 +249,62 @@ function CreateCommissionSheetContent({return;}- const date = data.date ? new Date(data.date).toISOString() : null;-- const saleEventDate = data.saleEventDate- ? new Date(data.saleEventDate).toISOString()- : null;+ let body: Record<string, unknown>;- const leadEventDate = data.leadEventDate- ? new Date(data.leadEventDate).toISOString()- : null;+ if (commissionType === "custom") {+ body = {+ type: "custom",+ partnerId,+ amount: data.amount ? Math.round(data.amount * 100) : 0,+ date: data.date ? data.date.toISOString() : null,+ description: data.description || null,+ };+ } else if (commissionType === "lead") {+ body = {+ type: "lead",+ partnerId,+ customerId: data.customerId,+ linkId: data.linkId,+ leadEventDate: data.leadEventDate+ ? data.leadEventDate.toISOString()+ : null,+ leadEventName: data.leadEventName || null,+ };+ } else {+ body = {+ type: "sale",+ partnerId,+ customerId: data.customerId,+ linkId: data.linkId,+ importStripeInvoices,+ ...(importStripeInvoices+ ? {+ saleAmount: null,+ saleEventDate: null,+ invoiceId: null,+ productId: null,+ }+ : {+ saleAmount: data.saleAmount+ ? Math.round(data.saleAmount * 100)+ : null,+ saleEventDate: data.saleEventDate+ ? data.saleEventDate.toISOString()+ : null,+ invoiceId: data.invoiceId || null,+ productId: data.productId || null,+ }),+ };+ }- await executeAsync({- ...data,- commissionType,- partnerId,- workspaceId,- date,- amount: data.amount ? data.amount * 100 : null,- saleAmount: data.saleAmount ? data.saleAmount * 100 : null,- saleEventDate,- leadEventDate,- useExistingEvents,+ await makeRequest("/api/commissions", {+ method: "POST",+ body,+ onSuccess: async ({ message }) => {+ toast.success(message);+ setIsOpen(false);+ await mutatePrefix("/api/commissions");+ },});};@@ -274,7 +324,7 @@ function CreateCommissionSheetContent({}if (commissionType === "sale") {- if (useExistingEvents) {+ if (importStripeInvoices) {if (isStripeInvoicesLoading) {return "Loading Stripe invoices...";}@@ -301,7 +351,7 @@ function CreateCommissionSheetContent({customerId,amount, // custom commission amountsaleAmount, // sale commission amount- useExistingEvents,+ importStripeInvoices,noStripeCustomerId,unimportedStripeInvoices.length,isStripeInvoicesLoading,@@ -591,9 +641,9 @@ function CreateCommissionSheetContent({optionClassName="h-8 flex items-center justify-center rounded-md flex-1 text-sm normal-case"indicatorClassName="bg-white"options={eventSourceOptions}- selected={useExistingEvents ? "existing" : "new"}+ selected={importStripeInvoices ? "existing" : "new"}selectAction={(value: string) =>- setUseExistingEvents(value === "existing")+ setImportStripeInvoices(value === "existing")}/><p className="mt-2 text-xs text-neutral-500">@@ -601,7 +651,7 @@ function CreateCommissionSheetContent({eventSourceOptions.find((option) =>option.value ===- (useExistingEvents ? "existing" : "new"),+ (importStripeInvoices ? "existing" : "new"),)?.description}</p>@@ -610,7 +660,7 @@ function CreateCommissionSheetContent({{/* Stripe invoices for sale + use existing */}{customerId &&- useExistingEvents &&+ importStripeInvoices &&commissionType === "sale" && (<div className="space-y-3">{isStripeInvoicesLoading ? (@@ -714,7 +764,7 @@ function CreateCommissionSheetContent({)}{customerId &&- !useExistingEvents &&+ !importStripeInvoices &&(commissionType === "lead" ? (<><AnimatedSizeContainer@@ -1007,7 +1057,7 @@ function CreateCommissionSheetContent({onClick={() => setIsOpen(false)}text="Cancel"className="w-fit"- disabled={isPending}+ disabled={isSubmitting}/><Button@@ -1015,7 +1065,7 @@ function CreateCommissionSheetContent({variant="primary"text={`Create commission${unimportedStripeInvoices.length > 0 ? "s" : ""}`}className="w-fit"- loading={isPending}+ loading={isSubmitting}disabledTooltip={submitDisabledMessage}/></div>diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.tsdeleted file mode 100644index 515e389ad0..0000000000--- a/apps/web/lib/actions/partners/create-manual-commission.ts+++ /dev/null@@ -1,491 +0,0 @@-"use server";--import { isFirstConversion } from "@/lib/analytics/is-first-conversion";-import { getCustomerStripeInvoices } from "@/lib/api/customers/get-customer-stripe-invoices";-import { updateLinkStatsForImporter } from "@/lib/api/links/update-link-stats-for-importer";-import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";-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 { 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";-import { prisma } from "@dub/prisma";-import { nanoid, prettyPrint } from "@dub/utils";-import { COUNTRIES_TO_CONTINENTS } from "@dub/utils/src";-import { waitUntil } from "@vercel/functions";-import * as z from "zod/v4";-import { authActionClient } from "../safe-action";-import { throwIfNoPermission } from "../throw-if-no-permission";-import { triggerAggregateDueCommissionsCronJob } from "./trigger-aggregate-due-commissions";--const leadEventSchemaTBWithTimestamp = leadEventSchemaTB.extend({- timestamp: z.string(),-});--const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({- timestamp: z.string(),-});--export const createManualCommissionAction = authActionClient- .inputSchema(createCommissionSchema)- .action(async ({ parsedInput, ctx }) => {- const { workspace, user } = ctx;-- throwIfNoPermission({- role: workspace.role,- requiredRoles: ["owner", "member"],- });-- const {- partnerId,- commissionType,- // custom commission attributes- date,- amount,- description,- // customer attributes (for lead and sale commissions)- customerId,- linkId,- // lead attributes- leadEventDate,- leadEventName,- // sale attributes- useExistingEvents,- saleEventDate,- saleAmount,- invoiceId,- productId,- } = parsedInput;-- const programId = getDefaultProgramIdOrThrow(workspace);-- const [{ partner, links }, customer] = await Promise.all([- getProgramEnrollmentOrThrow({- programId,- partnerId,- include: {- partner: true,- links: true,- },- }),-- customerId- ? prisma.customer.findUniqueOrThrow({- where: {- id: customerId,- },- })- : Promise.resolve(null),- ]);-- // Create a custom commission- if (commissionType === "custom") {- await queuePartnerCommissionCreation({- event: "custom",- partnerId,- programId,- amount: amount ?? 0,- quantity: 1,- createdAt: date ?? new Date(),- userId: user.id,- description,- });-- waitUntil(triggerAggregateDueCommissionsCronJob(programId));-- return;- }-- if (!customer || customer.projectId !== workspace.id) {- throw new Error(- `Customer${customerId ? ` with customerId ${customerId}` : ""} not found.`,- );- }-- const link = links.find((l) => l.id === linkId);-- if (!link) {- throw new Error(- `Link ${linkId} does not belong to partner ${partner.email} (${partnerId}).`,- );- }-- if (invoiceId) {- const commission = await prisma.commission.findUnique({- where: {- invoiceId_programId: {- invoiceId,- programId,- },- },- select: {- id: true,- },- });-- if (commission) {- throw new Error(- `There is already a commission for the invoice ${invoiceId}.`,- );- }- }-- const tbEventsToRecord: Array<() => Promise<unknown>> = []; // a list of promises of events to record in Tinybird- const commissionsToCreate: CreatePartnerCommissionProps[] = [];-- // keep track of click event to update customer later- let clickId: string | undefined = undefined;- let clickedAt: Date | undefined = undefined;-- // keep track of link stats to update later- let totalSales = 0;- let totalSaleAmount = 0;- let lastLeadAt: Date | undefined = undefined;- let lastConversionAt: Date | undefined = undefined;-- // If we're using existing events (Stripe invoice for sale)- if (useExistingEvents) {- if (commissionType !== "sale") {- throw new Error(- "You can only use existing events for recurring sale commissions.",- );- }-- if (!workspace.stripeConnectId) {- throw new Error(- "Your workspace isn't connected to Stripe yet. Please install the Stripe integration under /settings/integrations/stripe to proceed.",- );- }-- if (!customer.stripeCustomerId) {- throw new Error(- `Customer ${customer.id} doesn't have a Stripe customer ID. Add one in the customer profile before proceeding.`,- );- }-- const stripeCustomerInvoices = await getCustomerStripeInvoices({- stripeCustomerId: customer.stripeCustomerId,- stripeConnectId: workspace.stripeConnectId,- programId,- }).then((invoices) =>- invoices- // filter out invoices that are already associated with a commission on Dub- .filter((invoice) => !invoice.dubCommissionId)- // sort invoices by created date ascending- .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime()),- );-- if (stripeCustomerInvoices.length === 0) {- throw new Error(- `No unimported Stripe invoices found for customer ${customer.email} (${customer.stripeCustomerId}).`,- );- }-- if (stripeCustomerInvoices.length > 36) {- throw new Error(- `Too many Stripe invoices found for customer ${customer.email} (${stripeCustomerInvoices.length}). Please contact support.`,- );- }-- console.log("Stripe invoices to import: ");- console.table(stripeCustomerInvoices);-- // use the first ever stripe invoice created date as the last lead and conversion dates- lastLeadAt = stripeCustomerInvoices[0].createdAt;- lastConversionAt = stripeCustomerInvoices[0].createdAt;-- clickId = nanoid(16);- clickedAt = new Date(lastLeadAt.getTime() - 5 * 60 * 1000);-- const customerCountry = customer.country?.toUpperCase();-- const generatedClickEvent = recordClickZodSchema.parse({- timestamp: clickedAt.toISOString(),- identity_hash: customer.externalId || customer.id,- click_id: clickId,- link_id: link.id,- url: link.url,- ip: "127.0.0.1",- country: customerCountry ?? "Unknown",- continent: customerCountry- ? COUNTRIES_TO_CONTINENTS[customerCountry] ?? "Unknown"- : "Unknown",- });-- tbEventsToRecord.push(() => recordClickZod(generatedClickEvent));-- const leadEventData = leadEventSchemaTBWithTimestamp.parse({- ...generatedClickEvent,- event_id: nanoid(16),- event_name: "Sign up",- customer_id: customer.id,- timestamp: lastLeadAt.toISOString(),- });-- tbEventsToRecord.push(() => recordLeadWithTimestamp(leadEventData));-- const saleEventData = stripeCustomerInvoices.map((invoice) =>- saleEventSchemaTBWithTimestamp.parse({- ...generatedClickEvent,- event_id: nanoid(16),- invoice_id: invoice.id,- event_name: "Invoice paid",- amount: invoice.amount,- customer_id: customer.id,- payment_processor: "stripe",- currency: "usd",- timestamp: invoice.createdAt.toISOString(),- metadata: JSON.stringify(invoice.metadata),- }),- );-- tbEventsToRecord.push(() => recordSaleWithTimestamp(saleEventData));-- commissionsToCreate.push(- ...saleEventData.map((saleEvent) => ({- event: "sale" as const,- programId,- partnerId,- linkId: link.id,- customerId: customer.id,- eventId: saleEvent.event_id,- quantity: 1,- amount: saleEvent.amount,- currency: saleEvent.currency,- invoiceId: saleEvent.invoice_id,- createdAt: new Date(saleEvent.timestamp),- // if the invoice payment was refunded on Stripe, set the commission status to refunded as well- ...(stripeCustomerInvoices.find(- (invoice) => invoice.id === saleEvent.invoice_id,- )?.refunded && {- status: "refunded" as const,- }),- userId: user.id,- context: {- customer: { country: customer.country },- },- })),- );- totalSales = saleEventData.length;- totalSaleAmount = saleEventData.reduce(- (acc, saleEvent) => acc + saleEvent.amount,- 0,- );- } else {- const finalLeadEventDate = leadEventDate ?? saleEventDate ?? new Date();- clickId = nanoid(16);- clickedAt = new Date(finalLeadEventDate.getTime() - 5 * 60 * 1000);-- // Record click event- const generatedClickEvent = recordClickZodSchema.parse({- timestamp: clickedAt.toISOString(),- identity_hash: customer.externalId || customer.id,- click_id: clickId,- link_id: link.id,- url: link.url,- ip: "127.0.0.1",- continent: customer.country- ? COUNTRIES_TO_CONTINENTS[customer.country.toUpperCase()] || ""- : "",- });-- tbEventsToRecord.push(() => recordClickZod(generatedClickEvent));-- // Record lead event- const leadEventData = leadEventSchemaTBWithTimestamp.parse({- ...generatedClickEvent,- event_id: nanoid(16),- event_name: leadEventName || "Sign up",- customer_id: customer.id,- timestamp: finalLeadEventDate.toISOString(),- });-- console.log("New lead event to record: ", leadEventData);-- tbEventsToRecord.push(() => recordLeadWithTimestamp(leadEventData));-- if (commissionType === "lead") {- commissionsToCreate.push({- event: "lead" as const,- programId,- partnerId,- linkId: link.id,- customerId: customer.id,- 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- userId: user.id,- context: {- customer: { country: customer.country },- },- });- // Track the lead event timestamp for link stats update- lastLeadAt = new Date(leadEventData.timestamp);- }-- // Prepare sale event if requested- if (saleAmount) {- const saleEventData = saleEventSchemaTBWithTimestamp.parse({- ...generatedClickEvent,- event_id: nanoid(16),- invoice_id: invoiceId ?? "",- event_name: "Purchase",- amount: saleAmount,- customer_id: customer.id,- payment_processor: "custom",- currency: "usd",- timestamp: new Date(saleEventDate ?? Date.now()).toISOString(),- metadata: productId ? JSON.stringify({ productId }) : undefined,- });-- console.log("New sale event to record: ", saleEventData);-- tbEventsToRecord.push(() => recordSaleWithTimestamp(saleEventData));-- if (commissionType === "sale") {- commissionsToCreate.push({- event: "sale" as const,- programId,- partnerId,- linkId: link.id,- customerId: customer.id,- eventId: saleEventData.event_id,- quantity: 1,- amount: saleEventData.amount,- 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- userId: user.id,- context: {- customer: { country: customer.country },- sale: { productId },- },- });- totalSales++;- totalSaleAmount += saleEventData.amount;- lastConversionAt = new Date(saleEventData.timestamp);- }- }- }-- // record events in Tinybird- const tbRes = await Promise.allSettled(tbEventsToRecord.map((fn) => fn()));- console.log("Recorded events in Tinybird: ", prettyPrint(tbRes));-- let queuedCommissions = 0;- // create partner commissions (use a for loop to make sure the commissions are created in the correct order)- for (const c of commissionsToCreate) {- await queuePartnerCommissionCreation(c);- queuedCommissions++;- }- console.log(- `Queued ${queuedCommissions} commissions for partner ${partner.email} (${partner.id}) and customer ${customer.email} (${customer.id})`,- );-- waitUntil(- (async () => {- const firstConversionFlag =- commissionType === "sale" &&- isFirstConversion({- customer,- linkId: link.id,- });-- await Promise.allSettled([- prisma.link.update({- where: {- id: link.id,- },- data: {- // we'll always create click + lead events, so need to increment the stats- clicks: {- increment: 1,- },- leads: {- increment: 1,- },- lastLeadAt: updateLinkStatsForImporter({- currentTimestamp: link.lastLeadAt,- newTimestamp: lastLeadAt || new Date(),- }),- ...(firstConversionFlag && {- conversions: {- increment: 1,- },- lastConversionAt: updateLinkStatsForImporter({- currentTimestamp: link.lastConversionAt,- newTimestamp: lastConversionAt || new Date(),- }),- }),- sales: {- increment: totalSales,- },- saleAmount: {- increment: totalSaleAmount,- },- },- }),- prisma.customer.update({- where: {- id: customer.id,- },- data: {- linkId: link.id,- programId: link.programId,- partnerId: link.partnerId,- clickId,- clickedAt,- sales: {- increment: totalSales,- },- saleAmount: {- increment: totalSaleAmount,- },- firstSaleAt: customer.firstSaleAt- ? undefined- : lastConversionAt ?? new Date(),- },- }),- ]);-- // execute workflows- if (["lead", "sale"].includes(commissionType)) {- await Promise.allSettled([- executeWorkflows({- trigger: "partnerMetricsUpdated",- reason: "commission",- identity: {- workspaceId: workspace.id,- programId,- partnerId,- },- metrics: {- current: {- leads: commissionType === "lead" ? 1 : 0,- saleAmount: saleAmount ?? totalSaleAmount,- conversions: firstConversionFlag ? 1 : 0,- },- },- }),-- syncPartnerLinksStats({- partnerId,- programId,- eventType: commissionType as "lead" | "sale",- }),- ]);- }-- await triggerAggregateDueCommissionsCronJob(programId);- })(),- );- });diff --git a/apps/web/lib/api/commissions/create-manual-commissions.ts b/apps/web/lib/api/commissions/create-manual-commissions.tsnew file mode 100644index 0000000000..a434600a69--- /dev/null+++ b/apps/web/lib/api/commissions/create-manual-commissions.ts@@ -0,0 +1,697 @@+import { isFirstConversion } from "@/lib/analytics/is-first-conversion";+import { Session } from "@/lib/auth";+import { generateRandomName } from "@/lib/names";+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";+import { isStored, storage } from "@/lib/storage";+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 { createManualCommissionBodySchema } from "@/lib/zod/schemas/commissions";+import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";+import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";+import { prisma } from "@dub/prisma";+import {+ CommissionType,+ Customer,+ Link,+ Partner,+ Project,+} from "@dub/prisma/client";+import { COUNTRIES_TO_CONTINENTS, nanoid, R2_URL } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import * as z from "zod/v4";+import { createId } from "../create-id";+import { getCustomerStripeInvoices } from "../customers/get-customer-stripe-invoices";+import { DubApiError } from "../errors";+import { updateLinkStatsForImporter } from "../links/update-link-stats-for-importer";+import { syncPartnerLinksStats } from "../partners/sync-partner-links-stats";+import { getProgramEnrollmentOrThrow } from "../programs/get-program-enrollment-or-throw";+import { executeWorkflows } from "../workflows/execute-workflows";++type CreateCommissionsArgs = z.infer<+ typeof createManualCommissionBodySchema+> & {+ workspace: Pick<Project, "id" | "slug" | "stripeConnectId">;+ programId: string;+ user: Session["user"];+};++type ResolveLinkAndCustomerArgs = CreateCommissionsArgs & {+ workspace: Pick<Project, "id" | "stripeConnectId">;+ partner: Pick<Partner, "id" | "email">;+ links: Link[];+};++type RecordEventsArgs = CreateCommissionsArgs & {+ workspace: Pick<Project, "id" | "stripeConnectId">;+ partner: Pick<Partner, "id" | "email">;+ targetLink: Link;+ targetCustomer: Customer;+};++type ExecuteSideEffectsArgs = CreateCommissionsArgs & {+ clickEvent: { id: string; timestamp: string };+ leadEvent: { id: string; timestamp: string };+ saleEvents: Pick<+ z.infer<typeof saleEventSchemaTBWithTimestamp>,+ "timestamp" | "amount"+ >[];+ targetLink: Link;+ targetCustomer: Customer;+ isFirstConversion?: boolean;+};++const leadEventSchemaTBWithTimestamp = leadEventSchemaTB.extend({+ timestamp: z.string(),+});++const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({+ timestamp: z.string(),+});++export async function createManualCommissions(args: CreateCommissionsArgs) {+ const { workspace, programId, partnerId, type, user } = args;++ const { partner, links } = await getProgramEnrollmentOrThrow({+ programId,+ partnerId,+ include: {+ partner: true,+ links: true,+ },+ });++ // Custom commission+ if (type === "custom") {+ const { amount, date, description, user } = args;++ await queuePartnerCommissionCreation({+ event: "custom",+ programId,+ partnerId,+ amount,+ quantity: 1,+ createdAt: date ?? new Date(),+ description,+ userId: user.id,+ triggerAggregateDueCommissions: true,+ });++ return;+ }++ // Lead & sale commissions+ const { targetLink, targetCustomer, isFirstConversion } =+ await resolveLinkAndCustomer({+ ...args,+ links,+ partner,+ });++ if (type === "sale") {+ const {+ importStripeInvoices,+ saleAmount,+ saleEventDate,+ invoiceId,+ productId,+ } = args;++ if (!importStripeInvoices && !saleAmount) {+ throw new DubApiError({+ code: "bad_request",+ message: "Either saleAmount or importStripeInvoices must be provided.",+ });+ }++ const hasManualSaleFields =+ saleAmount || saleEventDate || invoiceId || productId;++ if (importStripeInvoices) {+ if (hasManualSaleFields) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "saleAmount, saleEventDate, invoiceId, and productId cannot be provided when importStripeInvoices is enabled.",+ });+ }++ if (!workspace.stripeConnectId) {+ throw new DubApiError({+ code: "bad_request",+ message: `Your workspace isn't connected to Stripe yet. Please install the Stripe integration to continue: https://app.dub.co/${workspace.slug}/settings/integrations/stripe`,+ });+ }++ if (targetCustomer && !targetCustomer.stripeCustomerId) {+ throw new DubApiError({+ code: "bad_request",+ message: `Customer ${targetCustomer.id} does not have a Stripe Customer ID configured. Please update the customer record at https://app.dub.co/${workspace.slug}/program/customers/${targetCustomer.id}`,+ });+ }+ }++ if (invoiceId) {+ const commission = await prisma.commission.findUnique({+ where: {+ invoiceId_programId: {+ invoiceId,+ programId,+ },+ },+ select: {+ id: true,+ },+ });++ if (commission) {+ throw new DubApiError({+ code: "conflict",+ message: `There is already a commission for the invoice ${invoiceId}.`,+ });+ }+ }+ }++ const { clickEvent, leadEvent, saleEvents } = await recordEvents({+ ...args,+ partner,+ targetLink,+ targetCustomer,+ });++ const commissionsToCreate: CreatePartnerCommissionProps[] = [];++ // Lead commission+ if (type === CommissionType.lead) {+ commissionsToCreate.push({+ event: CommissionType.lead,+ programId,+ partnerId,+ linkId: targetLink.id,+ customerId: targetCustomer.id,+ eventId: leadEvent.id,+ quantity: 1,+ // we don't add the "Z" to the timestamp because it's already in UTC+ createdAt: new Date(leadEvent.timestamp),+ userId: user.id,+ context: {+ customer: {+ country: targetCustomer.country,+ },+ },+ });+ }++ // Sale commissions+ else if (type === CommissionType.sale) {+ commissionsToCreate.push(+ ...saleEvents.map((saleEvent) => ({+ event: CommissionType.sale,+ programId,+ partnerId,+ linkId: targetLink.id,+ customerId: targetCustomer.id,+ quantity: 1,+ eventId: saleEvent.id,+ amount: saleEvent.amount,+ currency: saleEvent.currency,+ invoiceId: saleEvent.invoiceId,+ // if the invoice payment was refunded on Stripe, set the commission status to refunded as well+ createdAt: new Date(saleEvent.timestamp),+ ...(saleEvent.status === "refunded" && {+ status: "refunded" as const,+ }),+ userId: user.id,+ context: {+ customer: {+ country: targetCustomer.country,+ signupDate: targetCustomer.createdAt,+ },+ sale: {+ productId: saleEvent.productId,+ amount: saleEvent.amount,+ },+ },+ isFirstConversion,+ })),+ );+ }++ for (const [index, commissionToCreate] of commissionsToCreate.entries()) {+ await queuePartnerCommissionCreation({+ ...commissionToCreate,+ triggerAggregateDueCommissions: index === commissionsToCreate.length - 1, // trigger the job once per batch+ });+ }++ waitUntil(+ executeSideEffects({+ ...args,+ targetLink,+ targetCustomer,+ clickEvent,+ leadEvent,+ saleEvents,+ isFirstConversion,+ }),+ );+}++async function resolveLinkAndCustomer(args: ResolveLinkAndCustomerArgs) {+ const { type } = args;++ // Just to make TypeScript happy+ if (type === "custom") {+ throw new Error("Error");+ }++ let targetLink: Link;+ let targetCustomer: Customer | null = null;+ const { workspace, partner, links, linkId, customerId, customer } = args;++ if (links.length === 0) {+ throw new DubApiError({+ code: "bad_request",+ message: `Partner ${partner.email} (${partner.id}) has no links.`,+ });+ }++ if (!customerId && !customer) {+ throw new DubApiError({+ code: "bad_request",+ message: "Either customerId or customer must be provided.",+ });+ }++ if (customerId && customer) {+ throw new DubApiError({+ code: "bad_request",+ message: "Either customerId or customer must be provided, not both.",+ });+ }++ if (linkId) {+ const link = links.find((l) => l.id === linkId);++ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: `Link ${linkId} does not belong to partner ${partner.email} (${partner.id}).`,+ });+ }++ targetLink = link;+ } else {+ // If linkId is not provided, default to the link with the most revenue+ targetLink = links.sort(+ (a, b) => Number(b.saleAmount) - Number(a.saleAmount),+ )[0];+ }++ // Find an existing customer+ if (customerId) {+ targetCustomer = await prisma.customer.findUnique({+ where: {+ id: customerId,+ },+ });++ if (!targetCustomer) {+ throw new DubApiError({+ code: "not_found",+ message: `Customer ${customerId} not found.`,+ });+ }++ if (targetCustomer.projectId !== workspace.id) {+ throw new DubApiError({+ code: "bad_request",+ message: `Customer ${customerId} does not belong to the workspace.`,+ });+ }+ }++ // Create or update the customer+ else if (customer) {+ const { name, email, avatar, country, externalId, stripeCustomerId } =+ customer;++ const customerId = createId({ prefix: "cus_" });+ const finalCustomerName = name || email || generateRandomName();+ const finalCustomerAvatar =+ avatar && !isStored(avatar)+ ? `${R2_URL}/customers/${customerId}/avatar_${nanoid(7)}`+ : avatar;++ targetCustomer = await prisma.customer.upsert({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId,+ },+ },+ create: {+ id: customerId,+ name: finalCustomerName,+ email,+ avatar: finalCustomerAvatar,+ externalId,+ stripeCustomerId,+ linkId: targetLink.id,+ country,+ projectId: workspace.id,+ projectConnectId: workspace.stripeConnectId,+ },+ update: {+ name: finalCustomerName,+ email,+ avatar: finalCustomerAvatar,+ country,+ stripeCustomerId,+ },+ });++ if (avatar && !isStored(avatar) && finalCustomerAvatar) {+ await storage.upload({+ key: finalCustomerAvatar.replace(`${R2_URL}/`, ""),+ body: avatar,+ opts: {+ width: 128,+ height: 128,+ },+ });+ }+ }++ if (!targetCustomer) {+ throw new DubApiError({+ code: "bad_request",+ message: "Failed to resolve customer from the request.",+ });+ }++ return {+ targetLink,+ targetCustomer,+ ...(type === "sale" && {+ isFirstConversion: isFirstConversion({+ customer: targetCustomer,+ linkId: targetLink.id,+ }),+ }),+ };+}++async function recordEvents(args: RecordEventsArgs) {+ const { type } = args;++ // Just to make TypeScript happy+ if (type === "custom") {+ throw new Error("Error");+ }++ let finalLeadEventDate: Date;+ let stripeCustomerInvoices: Awaited<+ ReturnType<typeof getCustomerStripeInvoices>+ > = [];+ const { workspace, programId, targetLink, targetCustomer } = args;++ if (type === "lead") {+ finalLeadEventDate = args.leadEventDate ?? new Date();+ } else if (args.importStripeInvoices) {+ stripeCustomerInvoices = await getCustomerStripeInvoices({+ stripeCustomerId: targetCustomer.stripeCustomerId!,+ stripeConnectId: workspace.stripeConnectId!,+ programId,+ });++ // Filter out invoices that are already associated with a commission on Dub+ stripeCustomerInvoices = stripeCustomerInvoices.filter(+ (invoice) => !invoice.dubCommissionId,+ );++ if (stripeCustomerInvoices.length === 0) {+ throw new DubApiError({+ code: "bad_request",+ message: "No unimported Stripe invoices found for customer.",+ });+ }++ // Sort invoices by created date ascending+ stripeCustomerInvoices.sort(+ (a, b) => a.createdAt.getTime() - b.createdAt.getTime(),+ );++ finalLeadEventDate = stripeCustomerInvoices[0].createdAt;+ } else {+ finalLeadEventDate = args.saleEventDate ?? new Date();+ }++ const clickId = nanoid(16);+ const clickedAt = new Date(finalLeadEventDate.getTime() - 5 * 60 * 1000);+ const leadEventName = type === "lead" ? args.leadEventName : "Sign up";+ let saleEvents: z.infer<typeof saleEventSchemaTBWithTimestamp>[] = [];++ // Record click event+ const clickEvent = recordClickZodSchema.parse({+ timestamp: clickedAt.toISOString(),+ identity_hash: targetCustomer.externalId || targetCustomer.id,+ click_id: clickId,+ link_id: targetLink.id,+ url: targetLink.url,+ ip: "127.0.0.1",+ continent: targetCustomer.country+ ? COUNTRIES_TO_CONTINENTS[targetCustomer.country.toUpperCase()] || ""+ : "",+ });++ // Record lead event+ const leadEvent = leadEventSchemaTBWithTimestamp.parse({+ ...clickEvent,+ event_id: nanoid(16),+ event_name: leadEventName ?? "Sign up",+ customer_id: targetCustomer.id,+ timestamp: finalLeadEventDate.toISOString(),+ });++ // Record sale events+ if (type === "sale") {+ const {+ invoiceId,+ saleAmount,+ saleEventDate,+ productId,+ importStripeInvoices,+ } = args;++ if (importStripeInvoices) {+ saleEvents = stripeCustomerInvoices.map((invoice) =>+ saleEventSchemaTBWithTimestamp.parse({+ ...clickEvent,+ event_id: nanoid(16),+ invoice_id: invoice.id,+ event_name: "Invoice paid",+ amount: invoice.amount,+ customer_id: targetCustomer.id,+ payment_processor: "stripe",+ currency: "usd",+ timestamp: invoice.createdAt.toISOString(),+ metadata: JSON.stringify(invoice.metadata),+ }),+ );+ } else if (saleAmount) {+ saleEvents = [+ saleEventSchemaTBWithTimestamp.parse({+ ...clickEvent,+ event_id: nanoid(16),+ invoice_id: invoiceId ?? "",+ event_name: "Purchase",+ amount: saleAmount,+ customer_id: targetCustomer.id,+ payment_processor: "custom",+ currency: "usd",+ timestamp: new Date(saleEventDate ?? Date.now()).toISOString(),+ metadata: productId ? JSON.stringify({ productId }) : undefined,+ }),+ ];+ }+ }++ await Promise.all([+ recordClickZod(clickEvent),+ recordLeadWithTimestamp(leadEvent),+ saleEvents.length > 0 ? recordSaleWithTimestamp(saleEvents) : undefined,+ ]);++ return {+ clickEvent: {+ id: clickEvent.click_id,+ timestamp: clickEvent.timestamp,+ },+ leadEvent: {+ id: leadEvent.event_id,+ timestamp: leadEvent.timestamp,+ },+ saleEvents: saleEvents.map((saleEvent) => {+ const stripeInvoice = stripeCustomerInvoices.find(+ (invoice) => invoice.id === saleEvent.invoice_id,+ );++ const metadata = saleEvent.metadata+ ? JSON.parse(saleEvent.metadata)+ : undefined;++ return {+ id: saleEvent.event_id,+ timestamp: saleEvent.timestamp,+ amount: saleEvent.amount,+ currency: saleEvent.currency,+ invoiceId: saleEvent.invoice_id,+ productId: metadata?.productId,+ ...(stripeInvoice?.refunded && {+ status: "refunded" as const,+ }),+ };+ }),+ };+}++async function executeSideEffects(args: ExecuteSideEffectsArgs) {+ const {+ type,+ targetLink,+ targetCustomer,+ clickEvent,+ leadEvent,+ saleEvents,+ isFirstConversion,+ partnerId,+ programId,+ workspace,+ } = args;++ // Just to make TypeScript happy+ if (type === "custom") {+ throw new Error("Error");+ }++ const { totalSales, totalSaleAmount } = saleEvents.reduce(+ (acc, saleEvent) => {+ acc.totalSales++;+ acc.totalSaleAmount += saleEvent.amount;++ return acc;+ },+ {+ totalSales: 0,+ totalSaleAmount: 0,+ },+ );++ let lastLeadAt: Date | undefined = undefined;+ let lastConversionAt: Date | undefined = undefined;++ if (leadEvent) {+ lastLeadAt = new Date(leadEvent.timestamp);+ }++ const earliestSaleAt =+ saleEvents.length > 0+ ? new Date(+ Math.min(...saleEvents.map((e) => new Date(e.timestamp).getTime())),+ )+ : undefined;++ if (saleEvents.length > 0) {+ lastConversionAt = earliestSaleAt;+ }++ await prisma.$transaction([+ prisma.link.update({+ where: {+ id: targetLink.id,+ },+ data: {+ clicks: {+ increment: 1,+ },+ leads: {+ increment: 1,+ },+ lastLeadAt: updateLinkStatsForImporter({+ currentTimestamp: targetLink.lastLeadAt,+ newTimestamp: lastLeadAt || new Date(),+ }),+ ...(isFirstConversion && {+ conversions: {+ increment: 1,+ },+ lastConversionAt: updateLinkStatsForImporter({+ currentTimestamp: targetLink.lastConversionAt,+ newTimestamp: lastConversionAt || new Date(),+ }),+ }),+ sales: {+ increment: totalSales,+ },+ saleAmount: {+ increment: totalSaleAmount,+ },+ },+ }),++ prisma.customer.update({+ where: {+ id: targetCustomer.id,+ },+ data: {+ linkId: targetLink.id,+ programId: targetLink.programId,+ partnerId: targetLink.partnerId,+ clickId: clickEvent.id!,+ clickedAt: new Date(clickEvent.timestamp),+ sales: {+ increment: totalSales,+ },+ saleAmount: {+ increment: totalSaleAmount,+ },+ ...(type === CommissionType.sale &&+ !targetCustomer.firstSaleAt &&+ earliestSaleAt && {+ firstSaleAt: earliestSaleAt,+ }),+ },+ }),+ ]);++ await Promise.allSettled([+ syncPartnerLinksStats({+ partnerId,+ programId,+ eventType: type,+ }),++ executeWorkflows({+ trigger: "partnerMetricsUpdated",+ reason: "commission",+ identity: {+ workspaceId: workspace.id,+ programId,+ partnerId,+ },+ metrics: {+ current: {+ leads: type === CommissionType.lead ? 1 : 0,+ saleAmount: totalSaleAmount,+ conversions: isFirstConversion ? 1 : 0,+ },+ },+ }),+ ]);+}diff --git a/apps/web/lib/constants/misc.ts b/apps/web/lib/constants/misc.tsindex 452a117869..d11edddcf9 100644--- a/apps/web/lib/constants/misc.ts+++ b/apps/web/lib/constants/misc.ts@@ -4,3 +4,6 @@ export const SORTABLE_LINKS_LIMIT = 10_000;export const MEGA_WORKSPACE_LINKS_LIMIT = 1_000_000;export const MIN_PAYOUT_AMOUNT_FOR_REMINDERS = 10_00;export const SLACK_SUPPORT_INVITE_MAX_EMAILS = 5;++export const VITEST_POLL_INTERVAL_MS = 5000; // 5 seconds+export const VITEST_TEST_TIMEOUT_MS = 90_000; // 90 secondsdiff --git a/apps/web/lib/openapi/commissions/create-commission.ts b/apps/web/lib/openapi/commissions/create-commission.tsnew file mode 100644index 0000000000..9c6c9edf0c--- /dev/null+++ b/apps/web/lib/openapi/commissions/create-commission.ts@@ -0,0 +1,35 @@+import {+ createCommissionResponseSchema,+ createManualCommissionBodySchema,+} from "@/lib/zod/schemas/commissions";+import { ZodOpenApiOperationObject } from "zod-openapi";+import { openApiErrorResponses } from "../responses";++export const createCommission: ZodOpenApiOperationObject = {+ operationId: "createCommission",+ "x-speakeasy-name-override": "create",+ summary: "Create commission",+ description:+ "Create one or more commissions (custom, lead or sale) for a partner. Commission creation is processed asynchronously. Use the List Commissions endpoint or webhooks to be notified when the commission is created.",+ requestBody: {+ content: {+ "application/json": {+ schema: createManualCommissionBodySchema,+ },+ },+ },+ responses: {+ "202": {+ description:+ "The request was accepted and commission creation was queued.",+ content: {+ "application/json": {+ schema: createCommissionResponseSchema,+ },+ },+ },+ ...openApiErrorResponses,+ },+ tags: ["Commissions"],+ security: [{ token: [] }],+};diff --git a/apps/web/lib/openapi/commissions/index.ts b/apps/web/lib/openapi/commissions/index.tsindex ac45385631..489a49d75e 100644--- a/apps/web/lib/openapi/commissions/index.ts+++ b/apps/web/lib/openapi/commissions/index.ts@@ -1,10 +1,12 @@import { ZodOpenApiPathsObject } from "zod-openapi";import { bulkUpdateCommissions } from "./bulk-update-commissions";+import { createCommission } from "./create-commission";import { listCommissions } from "./list-commissions";import { updateCommission } from "./update-commission";export const commissionsPaths: ZodOpenApiPathsObject = {"/commissions": {+ post: createCommission,get: listCommissions,},"/commissions/{id}": {diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex 68e9414274..19be79372f 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -1,7 +1,7 @@import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";import { CommissionStatus, CommissionType } from "@dub/prisma/client";import * as z from "zod/v4";-import { CustomerSchema } from "./customers";+import { createCustomerBodySchema, CustomerSchema } from "./customers";import { LinkSchema } from "./links";import {getCursorPaginationQuerySchema,@@ -193,30 +193,6 @@ export const getCommissionsCountQuerySchema = getCommissionsQuerySchematype: z.string().optional(),});-export const createCommissionSchema = z.object({- workspaceId: z.string(),- partnerId: z.string(),- commissionType: z.enum(CommissionType),- useExistingEvents: z.boolean(),-- // Custom- date: parseDateSchema.nullish(),- amount: z.number().min(0).nullish(),- description: z.string().max(190).nullish(),-- // Lead- customerId: z.string().nullish(),- linkId: z.string().nullish(),- leadEventDate: parseDateSchema.nullish(),- leadEventName: z.string().nullish(),-- // Sale- saleEventDate: parseDateSchema.nullish(),- saleAmount: centsSchema.pipe(z.number().min(0)).nullish(),- invoiceId: z.string().nullish(),- productId: z.string().nullish(),-});-export const commissionPatchStatusSchema = z.enum(["pending","refunded",@@ -462,4 +438,142 @@ export const createPartnerCommissionSchema = z.object({referer: z.string().nullable(),}).optional(),+ triggerAggregateDueCommissions: z+ .boolean()+ .default(false)+ .optional()+ .describe(+ "Whether to trigger the triggerAggregateDueCommissionsCronJob or not.",+ ),+});++export const createManualCommissionBodySchema = z+ .discriminatedUnion("type", [+ // Custom commission+ z.object({+ type: z.literal("custom"),+ partnerId: z+ .string()+ .describe("The ID of the partner to create the commission for."),+ amount: centsSchema+ .pipe(z.number().min(1))+ .describe("The commission amount in cents."),+ date: parseDateSchema+ .nullish()+ .describe("If not provided, the current date will be used."),+ description: z+ .string()+ .max(190)+ .nullish()+ .describe("The description of the commission."),+ }),++ // Lead commission+ z.object({+ type: z.literal("lead"),+ partnerId: z+ .string()+ .describe("The ID of the partner to create the commission for."),+ customerId: z+ .string()+ .nullish()+ .describe(+ "The customer ID to associate the commission with. Useful if the customer was already created in a prior operation and you want to associate the commission with it.",+ ),+ customer: createCustomerBodySchema+ .nullish()+ .describe(+ "The full customer object to associate the commission with. Useful for creating the customer on demand.",+ ),+ linkId: z+ .string()+ .nullish()+ .describe(+ "The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",+ ),+ leadEventDate: parseDateSchema+ .nullish()+ .describe(+ "The date and time of the lead event. If not provided, defaults to the current date and time.",+ ),+ leadEventName: z+ .string()+ .nullish()+ .default("Sign up")+ .describe(+ "The name of the lead event. If not provided, defaults to 'Sign up'.",+ ),+ }),++ // Sale commission+ z.object({+ type: z.literal("sale"),+ partnerId: z+ .string()+ .describe("The ID of the partner to create the commission for."),+ customerId: z+ .string()+ .nullish()+ .describe(+ "The customer ID to associate the commission with. Useful if the customer was already created in a prior operation and you want to associate the commission with it.",+ ),+ customer: createCustomerBodySchema+ .nullish()+ .describe(+ "The full customer object to associate the commission with. Useful for creating the customer on demand.",+ ),+ linkId: z+ .string()+ .nullish()+ .describe(+ "The partner link ID to associate the commission with. If not provided, default to the link with the most revenue.",+ ),+ importStripeInvoices: z+ .boolean()+ .nullish()+ .default(false)+ .describe(+ "When `true`, import all unimported paid Stripe invoices for the customer and create a commission for each. When `false`, create a single manual sale event using `saleAmount`.",+ ),+ saleAmount: centsSchema+ .pipe(z.number().min(0))+ .nullish()+ .describe(+ "Required when `importStripeInvoices` is `false`. The sale amount in cents for the manual sale event. Ignored when importing from Stripe.",+ ),+ saleEventDate: parseDateSchema+ .nullish()+ .describe(+ "Only used when `importStripeInvoices` is `false`. The date of the manual sale event. Defaults to the current date and time if not provided.",+ ),+ invoiceId: z+ .string()+ .nullish()+ .describe(+ "Only used when `importStripeInvoices` is `false`. An optional invoice ID to attach to the generated sale event and commission entry for deduplication.",+ ),+ productId: z+ .string()+ .nullish()+ .describe(+ "Only used when `importStripeInvoices` is `false`. An optional product ID stored on the sale event metadata – will also impact commission earnings calculation (if a `Sale` `Product ID` modifier is set).",+ ),+ }),+ ])+ .superRefine((data, ctx) => {+ if (data.type !== "sale") return;++ if (!data.importStripeInvoices && data.saleAmount == null) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ "`saleAmount` is required when `importStripeInvoices` is false.",+ path: ["saleAmount"],+ });+ }+ });++export const createCommissionResponseSchema = z.object({+ success: z.boolean(),+ message: z.string(),});diff --git a/apps/web/tests/commissions/create-commission.test.ts b/apps/web/tests/commissions/create-commission.test.tsnew file mode 100644index 0000000000..eb5632b63a--- /dev/null+++ b/apps/web/tests/commissions/create-commission.test.ts@@ -0,0 +1,208 @@+import { CommissionResponse } from "@/lib/types";+import { describe, expect, test } from "vitest";+import { randomCustomer, randomId } from "../utils/helpers";+import { IntegrationHarness } from "../utils/integration";+import {+ E2E_CUSTOMER_ID,+ E2E_LEAD_REWARD,+ E2E_PARTNER,+} from "../utils/resource";+import { verifyCommission } from "../utils/verify-commission";++const expectedQueuedResponse = {+ success: true,+ message: "Your commissions are being created and will appear shortly.",+};++const validationCases = [+ {+ name: "missing type field",+ body: { partnerId: E2E_PARTNER.id, amount: 500 },+ expectedStatus: 422,+ expectedMessage: "invalid_union: type: Invalid input",+ },+ {+ name: "invalid type value",+ body: { type: "invalid", partnerId: E2E_PARTNER.id },+ expectedStatus: 422,+ expectedMessage: "invalid_union: type: Invalid input",+ },+ {+ name: "custom commission with amount 0",+ body: { type: "custom", partnerId: E2E_PARTNER.id, amount: 0 },+ expectedStatus: 422,+ expectedMessage: "too_small: amount: Too small: expected number to be >=1",+ },+ {+ name: "sale commission missing saleAmount",+ body: {+ type: "sale",+ partnerId: E2E_PARTNER.id,+ customerId: E2E_CUSTOMER_ID,+ importStripeInvoices: false,+ },+ expectedStatus: 422,+ expectedMessage:+ "custom: saleAmount: `saleAmount` is required when `importStripeInvoices` is false.",+ },+];++validationCases.forEach(({ name, body, expectedStatus, expectedMessage }) => {+ test(`POST /commissions - validation error: ${name}`, async (ctx) => {+ const h = new IntegrationHarness(ctx);+ const { http } = await h.init();+ const response = await http.post<any>({ path: "/commissions", body });+ expect(response.status).toEqual(expectedStatus);+ expect(response.data.error.code).toEqual("unprocessable_entity");+ expect(response.data.error.message).toEqual(expectedMessage);+ });+});++describe.concurrent("POST /commissions", async () => {+ const h = new IntegrationHarness();+ const { http } = await h.init();++ test("create custom commission with required fields", async () => {+ const description = randomId();+ const { status, data } = await http.post<any>({+ path: "/commissions",+ body: {+ type: "custom",+ partnerId: E2E_PARTNER.id,+ amount: 500,+ description,+ },+ });++ expect(status).toEqual(202);+ expect(data).toStrictEqual(expectedQueuedResponse);++ await new Promise((resolve) => setTimeout(resolve, 2000));++ const { data: commissions } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ partnerId: E2E_PARTNER.id,+ type: "custom",+ sortBy: "createdAt",+ sortOrder: "desc",+ pageSize: "1",+ },+ });++ const commissionFound = commissions.find(+ (c) => c.description === description,+ );+ expect(commissionFound).toBeDefined();+ expect(commissionFound!.earnings).toEqual(500);+ expect(commissionFound!.type).toEqual("custom");+ });++ test("create lead commission", async () => {+ const customer = randomCustomer();++ const { status, data } = await http.post<any>({+ path: "/commissions",+ body: {+ type: "lead",+ partnerId: E2E_PARTNER.id,+ customer: {+ externalId: customer.externalId,+ email: customer.email,+ name: customer.name,+ country: "US",+ },+ },+ });++ expect(status).toEqual(202);+ expect(data).toStrictEqual(expectedQueuedResponse);++ await verifyCommission({+ http,+ customerExternalId: customer.externalId,+ expectedEarnings: E2E_LEAD_REWARD.modifiers[1].amountInCents,+ });+ });++ test("create sale commission with a new customer", async () => {+ const invoiceId = `INV_${randomId()}`;+ const customer = randomCustomer();++ const { status, data } = await http.post<any>({+ path: "/commissions",+ body: {+ type: "sale",+ partnerId: E2E_PARTNER.id,+ saleAmount: 1000,+ invoiceId,+ customer: {+ externalId: customer.externalId,+ email: customer.email,+ name: customer.name,+ country: "US",+ },+ },+ });++ expect(status).toEqual(202);+ expect(data).toStrictEqual(expectedQueuedResponse);++ await verifyCommission({+ http,+ invoiceId,+ expectedSaleAmount: 1000,+ expectedEarnings: 5000, // Earn $50 per sale for 3 months+ });+ });++ test("error when customer is not found", async () => {+ const { status, data } = await http.post<any>({+ path: "/commissions",+ body: {+ type: "sale",+ partnerId: E2E_PARTNER.id,+ customerId: "cus_nonexistent",+ saleAmount: 1000,+ },+ });+ expect(status).toEqual(404);+ expect(data.error.code).toEqual("not_found");+ expect(data.error.message).toContain("not found");+ });++ test("error when invoiceId already exists", async () => {+ const { data: existingCommissions } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ type: "sale",+ sortBy: "createdAt",+ sortOrder: "desc",+ pageSize: "50",+ },+ });++ const commissionWithInvoice = existingCommissions.find(+ (c) => c.invoiceId != null,+ );++ expect(commissionWithInvoice).toBeDefined();++ const { status, data } = await http.post<any>({+ path: "/commissions",+ body: {+ type: "sale",+ partnerId: E2E_PARTNER.id,+ saleAmount: 1000,+ invoiceId: commissionWithInvoice!.invoiceId,+ customerId: E2E_CUSTOMER_ID,+ },+ });++ expect(status).toEqual(409);+ expect(data.error.code).toEqual("conflict");+ expect(data.error.message).toContain(+ "There is already a commission for the invoice",+ );+ });+});diff --git a/apps/web/tests/utils/verify-commission.ts b/apps/web/tests/utils/verify-commission.tsindex ed5f10c045..b5984797e3 100644--- a/apps/web/tests/utils/verify-commission.ts+++ b/apps/web/tests/utils/verify-commission.ts@@ -1,3 +1,7 @@+import {+ VITEST_POLL_INTERVAL_MS,+ VITEST_TEST_TIMEOUT_MS,+} from "@/lib/constants/misc";import { CommissionResponse, Customer } from "@/lib/types";import { expect } from "vitest";import { HttpClient } from "./http";@@ -6,18 +10,15 @@ interface VerifyCommissionProps {http: HttpClient;customerExternalId?: string;invoiceId?: string;- expectedAmount?: number;+ expectedSaleAmount?: number;expectedEarnings: number;}-const POLL_INTERVAL_MS = 5000; // 5 seconds-const TIMEOUT_MS = 60000; // 60 seconds-export const verifyCommission = async ({http,customerExternalId,invoiceId,- expectedAmount,+ expectedSaleAmount,expectedEarnings,}: VerifyCommissionProps) => {let customerId: string | undefined;@@ -46,7 +47,7 @@ export const verifyCommission = async ({// Poll for commission every 5 seconds, timeout after 60 secondsconst startTime = Date.now();- while (Date.now() - startTime < TIMEOUT_MS) {+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {const { status, data: commissions } = await http.get<CommissionResponse[]>({path: "/commissions",query,@@ -64,8 +65,8 @@ export const verifyCommission = async ({expect(commission.customer?.id).toEqual(customerId);}- if (expectedAmount !== undefined) {- expect(commission.amount).toEqual(expectedAmount);+ if (expectedSaleAmount !== undefined) {+ expect(commission.amount).toEqual(expectedSaleAmount);}expect(commission.earnings).toEqual(expectedEarnings);@@ -74,12 +75,14 @@ export const verifyCommission = async ({}// Wait before next poll- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ await new Promise((resolve) =>+ setTimeout(resolve, VITEST_POLL_INTERVAL_MS),+ );}// Timeout reached - fail the testthrow new Error(- `Commission not found within ${TIMEOUT_MS / 1000} seconds. ` ++ `Commission not found within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +`Query: ${JSON.stringify(query)}`,);};diff --git a/apps/web/tests/utils/verify-fraud-event.ts b/apps/web/tests/utils/verify-fraud-event.tsindex 0661a607b4..6a1d4c315e 100644--- a/apps/web/tests/utils/verify-fraud-event.ts+++ b/apps/web/tests/utils/verify-fraud-event.ts@@ -5,8 +5,10 @@ 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+import {+ VITEST_POLL_INTERVAL_MS,+ VITEST_TEST_TIMEOUT_MS,+} from "@/lib/constants/misc";export const verifyFraudEvent = async ({http,@@ -35,7 +37,7 @@ export const verifyFraudEvent = async ({| z.infer<(typeof fraudEventSchemas)[keyof typeof fraudEventSchemas]>| undefined;- while (Date.now() - startTime < TIMEOUT_MS) {+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {const { status, data } = await http.get<z.infer<(typeof fraudEventSchemas)[keyof typeof fraudEventSchemas]>[]>({@@ -52,12 +54,14 @@ export const verifyFraudEvent = async ({}// Wait before next poll- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ await new Promise((resolve) =>+ setTimeout(resolve, VITEST_POLL_INTERVAL_MS),+ );}if (!fraudEvent) {throw new Error(- `Fraud event not found within ${TIMEOUT_MS / 1000} seconds. ` ++ `Fraud event not found within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +`Query: ${JSON.stringify({ customerId: customers[0].id, type: ruleType })}`,);}diff --git a/apps/web/tests/workflows/utils/verify-bounty-submission.ts b/apps/web/tests/workflows/utils/verify-bounty-submission.tsindex 32bcdfc4c6..674de44012 100644--- a/apps/web/tests/workflows/utils/verify-bounty-submission.ts+++ b/apps/web/tests/workflows/utils/verify-bounty-submission.ts@@ -1,3 +1,7 @@+import {+ VITEST_POLL_INTERVAL_MS,+ VITEST_TEST_TIMEOUT_MS,+} from "@/lib/constants/misc";import { expect } from "vitest";import { HttpClient } from "../../utils/http";@@ -10,9 +14,6 @@ interface VerifyBountySubmissionProps {query?: Record<string, string>;}-const POLL_INTERVAL_MS = 5000; // 5 seconds-const TIMEOUT_MS = 60000; // 60 seconds-export const verifyBountySubmission = async ({http,bountyId,@@ -25,7 +26,7 @@ export const verifyBountySubmission = async ({let lastSubmission: any = null;- while (Date.now() - startTime < TIMEOUT_MS) {+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {const { data: submissions } = await http.get<any[]>({path: `/bounties/${bountyId}/submissions`,query: { ...extraQuery, partnerId },@@ -55,7 +56,9 @@ export const verifyBountySubmission = async ({return submission;}- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ await new Promise((resolve) =>+ setTimeout(resolve, VITEST_POLL_INTERVAL_MS),+ );}const lastState = lastSubmission@@ -63,7 +66,7 @@ export const verifyBountySubmission = async ({: "No submission found";throw new Error(- `Bounty submission did not reach status "${expectedStatus}" within ${TIMEOUT_MS / 1000} seconds. ` ++ `Bounty submission did not reach status "${expectedStatus}" within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +`bountyId: ${bountyId}, partnerId: ${partnerId}. ${lastState}`,);};diff --git a/apps/web/tests/workflows/utils/verify-campaign-sent.ts b/apps/web/tests/workflows/utils/verify-campaign-sent.tsindex 7a5a31f526..aa8a433748 100644--- a/apps/web/tests/workflows/utils/verify-campaign-sent.ts+++ b/apps/web/tests/workflows/utils/verify-campaign-sent.ts@@ -1,3 +1,7 @@+import {+ VITEST_POLL_INTERVAL_MS,+ VITEST_TEST_TIMEOUT_MS,+} from "@/lib/constants/misc";import { expect } from "vitest";import { HttpClient } from "../../utils/http";@@ -7,9 +11,6 @@ interface VerifyCampaignSentProps {partnerId: string;}-const POLL_INTERVAL_MS = 5000; // 5 seconds-const TIMEOUT_MS = 60000; // 60 seconds-export const verifyCampaignSent = async ({http,campaignId,@@ -17,7 +18,7 @@ export const verifyCampaignSent = async ({}: VerifyCampaignSentProps) => {const startTime = Date.now();- while (Date.now() - startTime < TIMEOUT_MS) {+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {const { data: emails } = await http.get<any[]>({path: "/e2e/notification-emails",query: { campaignId, partnerId },@@ -32,11 +33,13 @@ export const verifyCampaignSent = async ({return emailSent;}- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ await new Promise((resolve) =>+ setTimeout(resolve, VITEST_POLL_INTERVAL_MS),+ );}throw new Error(- `Campaign email not found within ${TIMEOUT_MS / 1000} seconds. ` ++ `Campaign email not found within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +`campaignId: ${campaignId}, partnerId: ${partnerId}`,);};diff --git a/apps/web/tests/workflows/utils/verify-partner-group-move.ts b/apps/web/tests/workflows/utils/verify-partner-group-move.tsindex 29cfcd03ef..2a9bd2a6aa 100644--- a/apps/web/tests/workflows/utils/verify-partner-group-move.ts+++ b/apps/web/tests/workflows/utils/verify-partner-group-move.ts@@ -1,3 +1,7 @@+import {+ VITEST_POLL_INTERVAL_MS,+ VITEST_TEST_TIMEOUT_MS,+} from "@/lib/constants/misc";import { EnrolledPartnerProps } from "@/lib/types";import { expect } from "vitest";import { HttpClient } from "../../utils/http";@@ -9,9 +13,6 @@ interface VerifyPartnerGroupMoveProps {query?: Record<string, string>;}-const POLL_INTERVAL_MS = 5000; // 5 seconds-const TIMEOUT_MS = 60000; // 60 seconds-export const verifyPartnerGroupMove = async ({http,partnerId,@@ -21,7 +22,7 @@ export const verifyPartnerGroupMove = async ({const startTime = Date.now();let lastGroupId: string | null = null;- while (Date.now() - startTime < TIMEOUT_MS) {+ while (Date.now() - startTime < VITEST_TEST_TIMEOUT_MS) {const { data: partner } = await http.get<EnrolledPartnerProps>({path: `/partners/${partnerId}`,query,@@ -34,11 +35,13 @@ export const verifyPartnerGroupMove = async ({return partner;}- await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));+ await new Promise((resolve) =>+ setTimeout(resolve, VITEST_POLL_INTERVAL_MS),+ );}throw new Error(- `Partner group move not found within ${TIMEOUT_MS / 1000} seconds. ` ++ `Partner group move not found within ${VITEST_TEST_TIMEOUT_MS / 1000} seconds. ` +`partnerId: ${partnerId}, expectedGroupId: ${expectedGroupId}. ` +`Last seen groupId: ${lastGroupId}`,);diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.tsindex 4281c4a9cf..6d46eb2d91 100644--- a/apps/web/vitest.config.ts+++ b/apps/web/vitest.config.ts@@ -1,6 +1,7 @@import { loadEnv } from "vite";import tsconfigPaths from "vite-tsconfig-paths";import { defineConfig } from "vitest/config";+import { VITEST_TEST_TIMEOUT_MS } from "./lib/constants/misc";export default defineConfig({plugins: [tsconfigPaths()],@@ -8,7 +9,7 @@ export default defineConfig({dir: "./tests",reporters: ["verbose"],globals: true,- testTimeout: 60000,+ testTimeout: VITEST_TEST_TIMEOUT_MS,env: loadEnv("", process.cwd(), ""),setupFiles: ["./tests/setupTests.ts"],},diff --git a/packages/prisma/schema/commission.prisma b/packages/prisma/schema/commission.prismaindex 64e5d321ad..061b2a106c 100644--- a/packages/prisma/schema/commission.prisma+++ b/packages/prisma/schema/commission.prisma@@ -54,7 +54,7 @@ model Commission {@@index([programId, partnerId]) // for programEnrollment relation (used in cron/payouts/aggregate-due-commissions)@@index([programId, status, createdAt, amount, earnings]) // for program/commissions (scoped by programId)@@index([createdAt, status, programId, earnings]) // for admin/commissions- @@index([partnerId, customerId])+ @@index([partnerId, customerId, type, createdAt]) // for finding the firstCommission in create-partner-commission workflow@@index(payoutId)@@index(customerId)@@index(linkId)