The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
fetch events for customer
Kiran K224d4697ee7c
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 81b5bfb2af..641aab8285 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@@ -38,17 +38,28 @@ interface CreateCommissionSheetProps {type FormData = z.infer<typeof createCommissionSchema>;-function CreateCommissionSheetContent(props: CreateCommissionSheetProps) {- const { setIsOpen, partnerId: initialPartnerId } = props;+interface CustomerEvent {+ type: string;+ date?: string;+ amount?: number;+}+function CreateCommissionSheetContent({+ setIsOpen,+ partnerId: initialPartnerId,+}: CreateCommissionSheetProps) {const { id: workspaceId, defaultProgramId } = useWorkspace();const [hasInvoiceId, setHasInvoiceId] = useState(false);const [hasProductId, setHasProductId] = useState(false);const { rewards, loading: rewardsLoading } = useRewards();+const [hasCustomLeadEventDate, setHasCustomLeadEventDate] = useState(false);const [hasCustomLeadEventName, setHasCustomLeadEventName] = useState(false);const [useExistingEvents, setUseExistingEvents] = useState(true);+ const [existingEvents, setExistingEvents] = useState<CustomerEvent[]>([]);+ const [existingEventsLoading, setExistingEventsLoading] = useState(false);+const [commissionType, setCommissionType] =useState<CommissionType>("custom");@@ -122,7 +133,6 @@ function CreateCommissionSheetContent(props: CreateCommissionSheetProps) {await mutatePrefix(`/api/commissions?workspaceId=${workspaceId}`);},onError({ error }) {- console.log(error);toast.error(error.serverError);},});@@ -179,42 +189,45 @@ function CreateCommissionSheetContent(props: CreateCommissionSheetProps) {}, [commissionType, partnerId, linkId, customerId, saleAmount, amount]);// fetch existing events for given customer (filtered by commissionType)- const [existingEvents, setExistingEventss] = useState<- { type: string; date?: string; amount?: number }[]- >([]);- const [existingEventsLoading, setExistingEventssLoading] = useState(false);-useEffect(() => {- if (!customerId || !commissionType) {- setExistingEventss([]);- setExistingEventssLoading(false);+ if (+ !customerId ||+ !commissionType ||+ !workspaceId ||+ commissionType === "custom"+ ) {+ setExistingEvents([]);+ setExistingEventsLoading(false);return;}- // Simulate API fetch with delay- const fetchData = async () => {- setExistingEventssLoading(true);+ const fetchEvents = async () => {+ setExistingEventsLoading(true);+try {- await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulate network delay+ const searchParams = new URLSearchParams({+ workspaceId,+ customerId,+ event: `${commissionType}s`,+ });- // Mock data - replace with actual API call- const mockEvents = [- { type: "Lead", date: "2024-01-15", amount: 50 },- { type: "Sale", date: "2024-01-20", amount: 250 },- ];+ const response = await fetch(`/api/events?${searchParams.toString()}`, {+ method: "GET",+ });- setExistingEventss(mockEvents);+ setExistingEvents(await response.json());} catch (error) {- console.error("Failed to fetch existing events:", error);- setExistingEventss([]);+ setExistingEvents([]);} finally {- setExistingEventssLoading(false);+ setExistingEventsLoading(false);}};- fetchData();+ fetchEvents();}, [customerId, commissionType]);+ console.log({ existingEvents });+return (<form onSubmit={handleSubmit(onSubmit)} className="flex h-full flex-col"><div className="sticky top-0 z-10 border-b border-neutral-200 bg-white">diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.tsindex e98ac18926..166d8512b2 100644--- a/apps/web/lib/actions/partners/create-manual-commission.ts+++ b/apps/web/lib/actions/partners/create-manual-commission.ts@@ -20,6 +20,10 @@ import { WorkflowTrigger } from "@prisma/client";import { waitUntil } from "@vercel/functions";import { authActionClient } from "../safe-action";+// TODO: if eventIds is provided + existing customer partnerId is different from provided partnerId+// create a new customer+// duplicate the event IDs+export const createManualCommissionAction = authActionClient.schema(createCommissionSchema).action(async ({ parsedInput, ctx }) => {@@ -38,6 +42,7 @@ export const createManualCommissionAction = authActionClientleadEventDate,leadEventName,description,+ eventIds,} = parsedInput;const programId = getDefaultProgramIdOrThrow(workspace);@@ -128,7 +133,7 @@ export const createManualCommissionAction = authActionClientexistingLeadEvent.data.length > 0) {leadEvent = leadEventSchemaTB.parse(existingLeadEvent.data[0]);- } else {+ } else if (!eventIds || eventIds.length === 0) {// 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, {@@ -210,6 +215,14 @@ export const createManualCommissionAction = authActionClientpartnerId,}),]);+ } else {+ // if eventIds are provided, we need to duplicate the events+ const duplicateEvents = eventIds.map((eventId) => {+ return {+ ...leadEvent,+ event_id: eventId,+ };+ });}if (saleAmount && leadEvent) {diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex 2cd029d19e..a21f0b6f46 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -148,6 +148,8 @@ export const createCommissionSchema = z.object({saleAmount: z.number().min(0).nullish(),invoiceId: z.string().nullish(),productId: z.string().nullish(),++ eventIds: z.array(z.string()).nullish(),});export const updateCommissionSchema = z.object({