The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
final changes
Steven Teyd72440b3128a
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 9933ae5015..8ac7480ec1 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@@ -3,6 +3,7 @@ import { handleMoneyKeyDown } from "@/lib/form-utils";import { mutatePrefix } from "@/lib/swr/mutate";import useRewards from "@/lib/swr/use-rewards";import useWorkspace from "@/lib/swr/use-workspace";+import { CustomerActivityResponse } from "@/lib/types";import { createCommissionSchema } from "@/lib/zod/schemas/commissions";import { CustomerSelector } from "@/ui/customers/customer-selector";import { PartnerLinkSelector } from "@/ui/partners/partner-link-selector";@@ -17,17 +18,22 @@ import { X } from "@/ui/shared/icons";import {AnimatedSizeContainer,Button,+ LoadingSpinner,Sheet,SmartDateTimePicker,Switch,+ Table,ToggleGroup,+ useTable,} from "@dub/ui";-import { cn } from "@dub/utils";+import { cn, fetcher, formatDateTime } from "@dub/utils";import { CommissionType } from "@prisma/client";import { useAction } from "next-safe-action/hooks";+import Link from "next/link";import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";import { Controller, useForm } from "react-hook-form";import { toast } from "sonner";+import useSWR from "swr";import { z } from "zod";interface CreateCommissionSheetProps {@@ -41,7 +47,7 @@ function CreateCommissionSheetContent({setIsOpen,partnerId: initialPartnerId,}: CreateCommissionSheetProps) {- const { id: workspaceId, defaultProgramId } = useWorkspace();+ const { id: workspaceId, defaultProgramId, slug } = useWorkspace();const [hasInvoiceId, setHasInvoiceId] = useState(false);const [hasProductId, setHasProductId] = useState(false);const { rewards, loading: rewardsLoading } = useRewards();@@ -53,7 +59,11 @@ function CreateCommissionSheetContent({const [commissionType, setCommissionType] =useState<CommissionType>("custom");- const [openAccordions, setOpenAccordions] = useState<string[]>([+ type AccordionValue =+ | "partner-and-type"+ | "customer-and-commission"+ | "commission";+ const [openAccordions, setOpenAccordions] = useState<AccordionValue[]>(["partner-and-type",]);@@ -92,6 +102,15 @@ function CreateCommissionSheetContent({"description",]);+ // Fetch customer activity data when customer is selected and we're using existing events+ const { data: customerActivity, isLoading: isCustomerActivityLoading } =+ useSWR<CustomerActivityResponse>(+ customerId && useExistingEvents && workspaceId+ ? `/api/customers/${customerId}/activity?workspaceId=${workspaceId}`+ : null,+ fetcher,+ );+useEffect(() => {if (commissionType === "custom") {setValue("linkId", null);@@ -105,14 +124,10 @@ function CreateCommissionSheetContent({}, [hasCustomLeadEventDate, setValue]);useEffect(() => {- const baseValues = ["partner-and-type"];-if (commissionType === "custom") {- setOpenAccordions([...baseValues, "commission"]);- } else if (commissionType === "sale") {- setOpenAccordions([...baseValues, "customer", "sale"]);- } else if (commissionType === "lead") {- setOpenAccordions([...baseValues, "customer"]);+ setOpenAccordions(["partner-and-type", "commission"]);+ } else {+ setOpenAccordions(["partner-and-type", "customer-and-commission"]);}}, [commissionType]);@@ -145,6 +160,7 @@ function CreateCommissionSheetContent({await executeAsync({...data,+ commissionType,partnerId,workspaceId,date,@@ -160,6 +176,84 @@ function CreateCommissionSheetContent({return rewards?.map((reward) => reward.event);}, [rewards]);+ // Filter events based on commission type+ const filteredEvents = useMemo(() => {+ if (!customerActivity?.events) return [];++ return customerActivity.events.filter((event) => {+ if (commissionType === "sale") return event.event === "sale";+ if (commissionType === "lead") return event.event === "lead";+ return false;+ });+ }, [customerActivity?.events, commissionType]);++ // Table configuration for existing events+ const eventsTable = useTable({+ data: filteredEvents || [],+ columns: [+ {+ header: "Event",+ minSize: 160,+ size: 200,+ maxSize: 250,+ cell: ({ row }) => {+ const eventType = commissionType === "sale" ? "sales" : "leads";+ const link = row.original.link;+ const eventUrl =+ link?.domain && link?.key+ ? `/${slug}/events?event=${eventType}&interval=all&domain=${link.domain}&key=${link.key}`+ : null;++ const eventContent = (+ <div className="flex flex-col">+ <span className="text-sm font-medium text-neutral-700">+ {row.original.eventName ||+ (row.original.event === "sale" ? "Sale" : "Lead")}+ </span>+ <span className="text-xs text-neutral-500">+ {formatDateTime(row.original.timestamp)}+ </span>+ </div>+ );++ return eventUrl ? (+ <Link+ href={eventUrl}+ target="_blank"+ className="-mx-2 -my-1 block cursor-pointer rounded-md px-2 py-1 decoration-dotted underline-offset-2 hover:underline"+ >+ {eventContent}+ </Link>+ ) : (+ eventContent+ );+ },+ },+ ...(commissionType === "sale"+ ? [+ {+ header: "Amount",+ minSize: 100,+ size: 100,+ maxSize: 100,+ cell: ({ row }) => (+ <span className="text-sm text-neutral-700">+ {row.original.sale?.amount+ ? `$${(row.original.sale.amount / 100).toFixed(2)}`+ : "-"}+ </span>+ ),+ },+ ]+ : []),+ ],+ className: "[&_tr:last-child>td]:border-b-transparent",+ scrollWrapperClassName: "min-h-[40px] max-h-[200px]",+ resourceName: (p) => `event${p ? "s" : ""}`,+ loading: isCustomerActivityLoading,+ error: undefined,+ } as any);+const shouldDisableSubmit = useMemo(() => {if (!partnerId) {return true;@@ -169,16 +263,25 @@ function CreateCommissionSheetContent({return !amount;}- if (commissionType === "sale") {- return !linkId || !customerId || !saleAmount;+ if (!linkId || !customerId) {+ return true;}- if (commissionType === "lead") {- return !linkId || !customerId;+ if (useExistingEvents && !filteredEvents.length) {+ return true;}return false;- }, [commissionType, partnerId, linkId, customerId, saleAmount, amount]);+ }, [+ commissionType,+ partnerId,+ linkId,+ customerId,+ saleAmount,+ amount,+ useExistingEvents,+ filteredEvents,+ ]);return (<form onSubmit={handleSubmit(onSubmit)} className="flex h-full flex-col">@@ -202,7 +305,9 @@ function CreateCommissionSheetContent({<ProgramSheetAccordiontype="multiple"value={openAccordions}- onValueChange={setOpenAccordions}+ onValueChange={(value) =>+ setOpenAccordions(value as AccordionValue[])+ }className="space-y-6"><ProgramSheetAccordionItem value="partner-and-type">@@ -414,7 +519,7 @@ function CreateCommissionSheetContent({)}{(commissionType === "sale" || commissionType === "lead") && (- <ProgramSheetAccordionItem value="customer">+ <ProgramSheetAccordionItem value="customer-and-commission"><ProgramSheetAccordionTrigger>Customer and commission details</ProgramSheetAccordionTrigger>@@ -465,6 +570,23 @@ function CreateCommissionSheetContent({</div>)}+ {/* Show existing events table when using existing events */}+ {customerId && useExistingEvents && (+ <div>+ {isCustomerActivityLoading ? (+ <div className="flex h-32 items-center justify-center rounded-md border border-neutral-200">+ <LoadingSpinner />+ </div>+ ) : filteredEvents.length > 0 ? (+ <Table {...eventsTable} />+ ) : (+ <div className="flex h-20 items-center justify-center rounded-md border border-neutral-200 text-sm text-neutral-500">+ No {commissionType} events found for this customer+ </div>+ )}+ </div>+ )}+{customerId &&!useExistingEvents &&(commissionType === "lead" ? (diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.tsindex edb52dc79a..864e6e5e14 100644--- a/apps/web/lib/actions/partners/create-manual-commission.ts+++ b/apps/web/lib/actions/partners/create-manual-commission.ts@@ -1,22 +1,21 @@"use server";import { isFirstConversion } from "@/lib/analytics/is-first-conversion";-import { EventType } from "@/lib/analytics/types";-import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";import { createId } from "@/lib/api/create-id";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 } from "@/lib/partners/create-partner-commission";-import { getLeadEvent, tb } from "@/lib/tinybird";-import { recordClick } from "@/lib/tinybird/record-click";+import { getCustomerEventsTB } from "@/lib/tinybird/get-customer-events-tb";+import {+ recordClickZod,+ recordClickZodSchema,+} from "@/lib/tinybird/record-click-zod";import { recordLeadWithTimestamp } from "@/lib/tinybird/record-lead";import { recordSaleWithTimestamp } from "@/lib/tinybird/record-sale";-import { ClickEventTB, LeadEventTB } from "@/lib/types";-import { eventsFilterTB } from "@/lib/zod/schemas/analytics";-import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";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 } from "@dub/utils";import { COUNTRIES_TO_CONTINENTS } from "@dub/utils/src";@@ -25,6 +24,14 @@ import { waitUntil } from "@vercel/functions";import { z } from "zod";import { authActionClient } from "../safe-action";+const leadEventSchemaTBWithTimestamp = leadEventSchemaTB.extend({+ timestamp: z.string(),+});++const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({+ timestamp: z.string(),+});+export const createManualCommissionAction = authActionClient.schema(createCommissionSchema).action(async ({ parsedInput, ctx }) => {@@ -32,23 +39,31 @@ export const createManualCommissionAction = authActionClientconst {partnerId,+ commissionType,+ useExistingEvents,+ // custom commission attributesdate,amount,- linkId,- invoiceId,- productId,+ description,+ // lead attributescustomerId,- saleAmount,- saleEventDate,+ linkId,leadEventDate,leadEventName,- description,- useExistingEvents,+ // sale attributes+ saleEventDate,+ saleAmount,+ invoiceId,+ productId,} = parsedInput;+ // for useExistingEvents, we need to keep track of some stats so we can update later+ let totalSales = 0;+ let totalSaleAmount = 0;+const programId = getDefaultProgramIdOrThrow(workspace);- let [{ partner, links }, customer] = await Promise.all([+ const [{ partner, links }, customer] = await Promise.all([getProgramEnrollmentOrThrow({programId,partnerId,@@ -80,13 +95,10 @@ export const createManualCommissionAction = authActionClientreturn;}- // Create a lead or sale commission- if (!customerId || !customer) {- throw new Error("Customer not found.");- }-- if (customer.projectId !== workspace.id) {- throw new Error(`Customer ${customerId} not found.`);+ if (!customerId || !customer || customer.projectId !== workspace.id) {+ throw new Error(+ `Customer${customerId ? ` with customerId ${customerId}` : ""} not found.`,+ );}const link = links.find((l) => l.id === linkId);@@ -117,24 +129,167 @@ export const createManualCommissionAction = authActionClient}}- let clickEvent: ClickEventTB | null = null;- let leadEvent: LeadEventTB | null = null;- let shouldUpdateCustomer = false;+ const tbEventsToRecord: Promise<any>[] = []; // a list of promises of events to record in Tinybird+ const commissionsToTransferEventIds: string[] = []; // eventIds for the commissions to transfer to the new customer-partner pair – we need to nullify them later+ const commissionToCreate: (() => Promise<any>)[] = []; // a list of functions that return promises of commissions to create- // Create a new customer if program wants to move the customer to a different partner- const shouldCreateNewCustomer = !links.find(- (link) => link.id === customer?.linkId,- );+ // If we're using existing events, we need to duplicate them under the new customer.id+ if (useExistingEvents) {+ if (!customer.linkId) {+ throw new Error(+ `No linkId found for existing customer ${customer.id}.`,+ );+ }++ if (customer.linkId === link.id) {+ throw new Error(+ `Customer ${customer.id} is already attributed to link ${link.id}.`,+ );+ }- if (shouldCreateNewCustomer) {- customer = await prisma.$transaction(async (tx) => {+ // fetch existing customer events and duplicate them under the new customer.id+ const existingCustomerEvents = await getCustomerEventsTB({+ customerId: customer.id,+ linkIds: [customer.linkId],+ }).then((res) => res.data);++ if (existingCustomerEvents.length === 0) {+ throw new Error(+ `No existing events found for customer ${customer.id}.`,+ );+ }++ const existingClickEvent = existingCustomerEvents.find(+ (event) => event.event === "click",+ );+ console.log("Found existing click event: ", existingClickEvent);+ const existingLeadEvent = existingCustomerEvents.find(+ (event) => event.event === "lead",+ );+ console.log("Found existing lead event: ", existingLeadEvent);+ const existingSaleEvents = existingCustomerEvents.filter(+ (event) => event.event === "sale",+ );+ console.log("Found existing sale events: ", existingSaleEvents);++ const clickEventData = recordClickZodSchema.parse({+ ...existingClickEvent,+ click_id: nanoid(16), // create new clickId+ link_id: link.id, // set to new link.id,+ });++ if (existingClickEvent) {+ tbEventsToRecord.push(recordClickZod(clickEventData));+ }++ const duplicateCustomerId = createId({ prefix: "cus_" });++ if (existingLeadEvent) {+ const leadEventData = leadEventSchemaTBWithTimestamp.parse({+ ...clickEventData,+ ...existingLeadEvent,+ event_id: nanoid(16), // create new event_id+ timestamp: new Date(existingLeadEvent.timestamp).toISOString(), // set to existing lead event's timestamp+ link_id: link.id, // set to new link.id+ customer_id: duplicateCustomerId, // set to new duplicateCustomerId+ });+ tbEventsToRecord.push(recordLeadWithTimestamp(leadEventData));++ // Store the original lead eventId for nullification+ commissionsToTransferEventIds.push(existingLeadEvent.event_id);++ if (commissionType === "lead") {+ // add the new lead event to the list of commissions to create+ commissionToCreate.push(() =>+ createPartnerCommission({+ event: "lead",+ programId,+ partnerId,+ linkId: link.id,+ customerId: duplicateCustomerId,+ eventId: leadEventData.event_id,+ quantity: 1,+ createdAt: new Date(leadEventData.timestamp),+ user,+ context: {+ customer: { country: customer.country },+ },+ }),+ );+ }+ }++ const recordSaleEvents =+ commissionType === "sale" && existingSaleEvents.length > 0;++ if (existingSaleEvents.length > 5) {+ throw new Error(+ `You can only backfill up to 5 sale events. Found ${existingSaleEvents.length} existing sale events.`,+ );+ }++ if (recordSaleEvents) {+ const saleEventsData = existingSaleEvents.map((existingSaleEvent) =>+ saleEventSchemaTBWithTimestamp.parse({+ ...clickEventData,+ ...existingSaleEvent,+ event_id: nanoid(16), // create new event_id+ timestamp: new Date(existingSaleEvent.timestamp).toISOString(), // set to existing sale event's timestamp+ link_id: link.id, // set to new link.id+ customer_id: duplicateCustomerId, // set to new duplicateCustomerId+ amount: existingSaleEvent.saleAmount, // change format returned by Tinybird+ }),+ );+ tbEventsToRecord.push(recordSaleWithTimestamp(saleEventsData));++ // Store the original sale eventIds for nullification+ commissionsToTransferEventIds.push(+ ...existingSaleEvents.map(+ (existingSaleEvent) => existingSaleEvent.event_id,+ ),+ );++ if (commissionType === "sale") {+ // add the new sale events to the list of commissions to create+ commissionToCreate.push(+ ...saleEventsData.map(+ (saleEventData) => () =>+ createPartnerCommission({+ event: "sale",+ programId,+ partnerId,+ linkId: link.id,+ customerId: duplicateCustomerId,+ eventId: saleEventData.event_id,+ quantity: 1,+ amount: saleEventData.amount,+ currency: saleEventData.currency,+ invoiceId: saleEventData.invoice_id,+ createdAt: new Date(saleEventData.timestamp),+ user,+ context: {+ customer: { country: customer.country },+ sale: { productId },+ },+ }),+ ),+ );+ }+ totalSales = existingSaleEvents.length;+ totalSaleAmount = existingSaleEvents.reduce(+ (acc, saleEvent) => acc + saleEvent.saleAmount,+ 0,+ );+ }++ const duplicatedCustomer = await prisma.$transaction(async (tx) => {await tx.customer.update({where: {- id: customer!.id,+ id: customer.id,},data: {- name: `${customer!.name} (old)`,- externalId: customer!.id, // TODO: We need to make this null+ name: customer.name ? `${customer.name} (old)` : undefined,+ externalId: `dummy_${nanoid(32)}`, // generate random externalIdstripeCustomerId: null,linkId: null,clickId: null,@@ -144,233 +299,133 @@ export const createManualCommissionAction = authActionClientreturn await tx.customer.create({data: {...customer,- id: createId({ prefix: "cus_" }),+ id: duplicateCustomerId,linkId: link.id,- projectId: workspace.id,+ clickId: clickEventData.click_id,+ clickedAt: new Date(clickEventData.timestamp),+ country: clickEventData.country,+ ...(recordSaleEvents && {+ sales: totalSales,+ saleAmount: totalSaleAmount,+ }),},});});- }-- // if there is an existing lead event + no custom lead details were provided- // we can use that leadEvent's existing details- if (useExistingEvents) {- const existingLeadEvent = await getLeadEvent({- customerId,- });- if (existingLeadEvent && existingLeadEvent.data.length > 0) {- leadEvent = leadEventSchemaTB.parse(existingLeadEvent.data[0]);- }+ console.log(+ `Duplicated customer ${customer.id} to ${duplicatedCustomer.id}: `,+ duplicatedCustomer,+ );- if (!leadEvent) {- throw new Error("Existing lead event for the customer is not found.");- }+ // Else, we create new events} else {- // else, if there's no existing lead event and there is also no custom leadEventName/Date- // we need to create a dummy click + lead event (using the customer's country if available)- const dummyRequest = new Request(link.url, {- headers: new Headers({- "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",- "x-forwarded-for": "127.0.0.1",- ...(customer.country- ? {- "x-vercel-ip-country": customer.country.toUpperCase(),- "x-vercel-ip-continent":- COUNTRIES_TO_CONTINENTS[customer.country.toUpperCase()],- }- : {- "x-vercel-ip-country": "US",- "x-vercel-ip-country-region": "CA",- "x-vercel-ip-continent": "NA",- }),- }),- });-const finalLeadEventDate = leadEventDate ?? saleEventDate ?? new Date();+ const clickId = nanoid(16);+ const clickTimestamp = new Date(+ finalLeadEventDate.getTime() - 5 * 60 * 1000,+ );- const clickData = await recordClick({- req: dummyRequest,- linkId,- clickId: nanoid(16),+ const generatedClickEvent = recordClickZodSchema.parse({+ timestamp: clickTimestamp.toISOString(),+ identity_hash: customer.externalId || customer.id,+ click_id: clickId,+ link_id: link.id,url: link.url,- domain: link.domain,- key: link.key,- workspaceId: workspace.id,- skipRatelimit: true,- timestamp: new Date(- new Date(finalLeadEventDate).getTime() - 5 * 60 * 1000,- ).toISOString(),+ ip: "127.0.0.1",+ continent: customer.country+ ? COUNTRIES_TO_CONTINENTS[customer.country.toUpperCase()] || "NA"+ : "NA",});- clickEvent = clickEventSchemaTB.parse({- ...clickData,- bot: 0,- qr: 0,- });- const leadEventId = nanoid(16);- leadEvent = leadEventSchemaTB.parse({- ...clickEvent,- event_id: leadEventId,+ // Record click event+ tbEventsToRecord.push(recordClickZod(generatedClickEvent));++ const leadEventData = leadEventSchemaTBWithTimestamp.parse({+ ...generatedClickEvent,+ event_id: nanoid(16),event_name: leadEventName || "Sign up",customer_id: customer.id,+ timestamp: finalLeadEventDate.toISOString(),});+ tbEventsToRecord.push(recordLeadWithTimestamp(leadEventData));- shouldUpdateCustomer = !customer.linkId && clickData ? true : false;-- await Promise.allSettled([- recordLeadWithTimestamp({- ...leadEvent,- timestamp: new Date(finalLeadEventDate).toISOString(),- }),-- createPartnerCommission({- event: "lead",- programId,- partnerId,- linkId,- eventId: leadEventId,- customerId: customer.id,- amount: 0,- quantity: 1,- createdAt: finalLeadEventDate,- user,- context: {- customer: {- country: customer.country,+ if (commissionType === "lead") {+ commissionToCreate.push(() =>+ createPartnerCommission({+ event: "lead",+ programId,+ partnerId,+ linkId: link.id,+ customerId: customer.id,+ eventId: leadEventData.event_id,+ quantity: 1,+ createdAt: new Date(leadEventData.timestamp),+ user,+ context: {+ customer: { country: customer.country },},- },- }),-- executeWorkflows({- trigger: WorkflowTrigger.leadRecorded,- programId,- partnerId,- }),- ]);- }-- if (saleAmount && leadEvent) {- const saleEventId = nanoid(16);- const saleDate = new Date(saleEventDate ?? Date.now());+ }),+ );+ }- await Promise.allSettled([- recordSaleWithTimestamp({- ...leadEvent,- event_id: saleEventId,+ // Prepare sale event if requested+ if (saleAmount) {+ const saleEventData = saleEventSchemaTBWithTimestamp.parse({+ ...generatedClickEvent,+ event_id: nanoid(16),event_name: "Purchase",amount: saleAmount,customer_id: customer.id,payment_processor: "custom",currency: "usd",- timestamp: saleDate.toISOString(),+ timestamp: new Date(saleEventDate ?? Date.now()).toISOString(),metadata: productId ? JSON.stringify({ productId }) : undefined,- }),-- createPartnerCommission({- event: "sale",- programId,- partnerId,- linkId,- eventId: saleEventId,- customerId: customer.id,- amount: saleAmount,- quantity: 1,- invoiceId,- currency: "usd",- createdAt: saleDate,- user,- context: {- customer: {- country: customer.country,- },- sale: {- productId,- },- },- }),-- executeWorkflows({- trigger: WorkflowTrigger.saleRecorded,- programId,- partnerId,- }),- ]);+ });++ tbEventsToRecord.push(recordSaleWithTimestamp(saleEventData));+ if (commissionType === "sale") {+ commissionToCreate.push(() =>+ createPartnerCommission({+ event: "sale",+ 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),+ user,+ context: {+ customer: { country: customer.country },+ sale: { productId },+ },+ }),+ );+ }+ }}+ const res = await Promise.allSettled(tbEventsToRecord);+ console.log("recorded events in Tinybird: ", res);+waitUntil((async () => {- // Duplicate the customer events- // Because we're moving the customer to a new partner, we need to duplicate the events- if (useExistingEvents && shouldCreateNewCustomer) {- for (const eventType of ["leads", "sales"]) {- const { startDate, endDate } = getStartEndDates({- interval: "all",- });-- const pipe = tb.buildPipe({- pipe: "v2_events",- parameters: eventsFilterTB,- data: z.any(),- });-- const response = await pipe({- workspaceId: workspace.id,- eventType: eventType as EventType,- sortBy: "timestamp",- offset: 0,- limit: 100,- start: startDate.toISOString().replace("T", " ").replace("Z", ""),- end: endDate.toISOString().replace("T", " ").replace("Z", ""),- });-- const events = response.data;-- console.log(`Found ${events.length} events for ${eventType}`);-- if (eventType === "leads") {- await Promise.all(- events.map((event) =>- recordLeadWithTimestamp({- ...event,- customer_id: customer.id,- link_id: link.id,- device_model: "Unknown",- device_vendor: "Unknown",- browser_version: "Unknown",- os_version: "Unknown",- engine_version: "Unknown",- cpu_architecture: "Unknown",- bot: 0,- }),- ),- );- } else if (eventType === "sales") {- await Promise.all(- events.map((event) =>- recordSaleWithTimestamp({- ...event,- customer_id: customer.id,- link_id: link.id,- device_model: "Unknown",- device_vendor: "Unknown",- browser_version: "Unknown",- os_version: "Unknown",- engine_version: "Unknown",- cpu_architecture: "Unknown",- bot: 0,- }),- ),- );- }- }- }-- Promise.allSettled([- // Update link stats+ const finalCommissionsToTransferEventIds =+ commissionsToTransferEventIds.filter(+ (eventId) => typeof eventId === "string",+ );+ console.log(+ "Final commissions to transfer event ids: ",+ finalCommissionsToTransferEventIds,+ );+ const updatedRes = await Promise.all([+ // update link statsprisma.link.update({where: {- id: linkId,+ id: link.id,},data: {...(isFirstConversion({@@ -384,40 +439,43 @@ export const createManualCommissionAction = authActionClientincrement: 1,},}),- ...(saleAmount && {- sales: {- increment: 1,- },- saleAmount: {- increment: saleAmount,- },- }),+ sales: {+ increment: saleAmount ? 1 : totalSales,+ },+ saleAmount: {+ increment: saleAmount ?? totalSaleAmount,+ },},}),-- // Update customer details / stats- (shouldUpdateCustomer || saleAmount) &&- prisma.customer.update({+ finalCommissionsToTransferEventIds.length > 0 &&+ prisma.commission.updateMany({where: {- id: customer.id,+ eventId: {+ in: finalCommissionsToTransferEventIds,+ },},data: {- ...(shouldUpdateCustomer && {- linkId,- clickId: clickEvent?.click_id,- clickedAt: clickEvent?.timestamp,- }),- ...(saleAmount && {- sales: {- increment: 1,- },- saleAmount: {- increment: saleAmount,- },- }),+ eventId: null,+ invoiceId: null,},}),]);+ console.log({ commissionsToTransferEventIds, updatedRes });++ // create partner commissions+ await Promise.allSettled(commissionToCreate.map((fn) => fn()));++ // execute workflows+ if (["lead", "sale"].includes(commissionType)) {+ await executeWorkflows({+ trigger:+ commissionType === "lead"+ ? WorkflowTrigger.leadRecorded+ : WorkflowTrigger.saleRecorded,+ programId,+ partnerId,+ });+ }})(),);});diff --git a/apps/web/lib/analytics/get-customer-events.ts b/apps/web/lib/analytics/get-customer-events.tsindex 8f1ad591a0..2367d543b6 100644--- a/apps/web/lib/analytics/get-customer-events.ts+++ b/apps/web/lib/analytics/get-customer-events.ts@@ -1,9 +1,8 @@-import { tb } from "@/lib/tinybird";import { prisma } from "@dub/prisma";import { Link } from "@dub/prisma/client";import { transformLink } from "../api/links";import { decodeLinkIfCaseSensitive } from "../api/links/case-sensitivity";-import z from "../zod";+import { getCustomerEventsTB } from "../tinybird/get-customer-events-tb";import {clickEventResponseSchema,clickEventSchema,@@ -18,15 +17,9 @@ export const getCustomerEvents = async ({customerId: string;linkIds?: string[];}) => {- const pipe = tb.buildPipe({- pipe: "v2_customer_events",- parameters: z.any(), // TODO- data: z.any(), // TODO- });-- const response = await pipe({+ const response = await getCustomerEventsTB({customerId,- ...(linkIds ? { linkIds } : {}),+ linkIds,});const linksMap = await getLinksMap(response.data.map((d) => d.link_id));diff --git a/apps/web/lib/partners/create-partner-commission.ts b/apps/web/lib/partners/create-partner-commission.tsindex c1f04909ed..57ed637257 100644--- a/apps/web/lib/partners/create-partner-commission.ts+++ b/apps/web/lib/partners/create-partner-commission.ts@@ -224,7 +224,7 @@ export const createPartnerCommission = async ({});console.log(- `Created a ${event} commission ${commission.id} (${currencyFormatter(commission.earnings)}) for ${partnerId}: ${JSON.stringify(commission)}`,+ `Created a ${event} commission ${commission.id} (${currencyFormatter(commission.earnings / 100, { currency: commission.currency })}) for ${partnerId}: ${JSON.stringify(commission)}`,);waitUntil(diff --git a/apps/web/lib/tinybird/get-customer-events-tb.ts b/apps/web/lib/tinybird/get-customer-events-tb.tsnew file mode 100644index 0000000000..0a5dd89f85--- /dev/null+++ b/apps/web/lib/tinybird/get-customer-events-tb.ts@@ -0,0 +1,21 @@+import { z } from "zod";+import { tb } from "./client";++const pipe = tb.buildPipe({+ pipe: "v2_customer_events",+ parameters: z.any(), // TODO+ data: z.any(), // TODO+});++export const getCustomerEventsTB = async ({+ customerId,+ linkIds,+}: {+ customerId: string;+ linkIds?: string[];+}) => {+ return await pipe({+ customerId,+ ...(linkIds ? { linkIds } : {}),+ });+};diff --git a/apps/web/lib/tinybird/record-click-zod.ts b/apps/web/lib/tinybird/record-click-zod.tsnew file mode 100644index 0000000000..c1ce7f1f7d--- /dev/null+++ b/apps/web/lib/tinybird/record-click-zod.ts@@ -0,0 +1,40 @@+import { z } from "zod";+import { tb } from "./client";++export const recordClickZodSchema = z.object({+ timestamp: z.string().default(""),+ identity_hash: z.string().default(""),+ click_id: z.string().default(""),+ link_id: z.string().default(""),+ url: z.string().default(""),+ ip: z.string().default(""),+ continent: z.string().default(""),+ country: z.string().default("Unknown"),+ region: z.string().default("Unknown"),+ city: z.string().default("Unknown"),+ latitude: z.string().default("Unknown"),+ longitude: z.string().default("Unknown"),+ vercel_region: z.string().default(""),+ device: z.string().default("Desktop"),+ device_vendor: z.string().default("Unknown"),+ device_model: z.string().default("Unknown"),+ browser: z.string().default("Unknown"),+ browser_version: z.string().default("Unknown"),+ engine: z.string().default("Unknown"),+ engine_version: z.string().default("Unknown"),+ os: z.string().default("Unknown"),+ os_version: z.string().default("Unknown"),+ cpu_architecture: z.string().default("Unknown"),+ ua: z.string().default("Unknown"),+ bot: z.number().default(0),+ qr: z.number().default(0),+ referer: z.string().default("(direct)"),+ referer_url: z.string().default("(direct)"),+ trigger: z.string().default("link"),+});++export const recordClickZod = tb.buildIngestEndpoint({+ datasource: "dub_click_events",+ event: recordClickZodSchema,+ wait: true,+});diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 10f262ea05..f11f54225a 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -96,6 +96,7 @@ import {} from "./zod/schemas/rewards";import {saleEventResponseSchema,+ saleEventSchemaTB,trackSaleResponseSchema,} from "./zod/schemas/sales";import { tokenSchema } from "./zod/schemas/token";@@ -532,6 +533,8 @@ export type ClickEventTB = z.infer<typeof clickEventSchemaTB>;export type LeadEventTB = z.infer<typeof leadEventSchemaTB>;+export type SaleEventTB = z.infer<typeof saleEventSchemaTB>;+export type GroupProps = z.infer<typeof GroupSchema> & {additionalLinks: PartnerGroupAdditionalLink[] | null;};diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex bb546996b9..0f0417ef2c 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -131,6 +131,8 @@ export const getCommissionsCountQuerySchema = getCommissionsQuerySchema.omit({export const createCommissionSchema = z.object({workspaceId: z.string(),partnerId: z.string(),+ commissionType: z.nativeEnum(CommissionType),+ useExistingEvents: z.boolean(),// Customdate: parseDateSchema.nullish(),@@ -148,8 +150,6 @@ export const createCommissionSchema = z.object({saleAmount: z.number().min(0).nullish(),invoiceId: z.string().nullish(),productId: z.string().nullish(),-- useExistingEvents: z.boolean()});export const updateCommissionSchema = z.object({