Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

fetch customer stripe invoices

Steven Tey050723fa0464
diff --git a/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts b/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts
new file mode 100644
index 0000000000..7547339103
--- /dev/null
+++ b/apps/web/app/(ee)/api/customers/[id]/stripe-invoices/route.ts
@@ -0,0 +1,50 @@
+import { getCustomerOrThrow } from "@/lib/api/customers/get-customer-or-throw";
+import { DubApiError } from "@/lib/api/errors";
+import { withWorkspace } from "@/lib/auth";
+import { stripeAppClient } from "@/lib/stripe";
+import { StripeCustomerInvoiceSchema } from "@/lib/zod/schemas/customers";
+import { NextResponse } from "next/server";
+
+const stripe = stripeAppClient({
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
+});
+
+export const GET = withWorkspace(async ({ workspace, params }) => {
+ const { id: customerId } = params;
+
+ if (!workspace.stripeConnectId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Your workspace isn't connected to Stripe yet. Please install the Stripe integration under /settings/integrations/stripe to proceed.",
+ });
+ }
+
+ const customer = await getCustomerOrThrow({
+ workspaceId: workspace.id,
+ id: customerId,
+ });
+
+ if (!customer.stripeCustomerId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Customer doesn't have a Stripe customer ID. Please add a Stripe customer ID to the customer before proceeding.",
+ });
+ }
+
+ const { data } = await stripe.invoices.list(
+ {
+ customer: customer.stripeCustomerId,
+ status: "paid",
+ },
+ {
+ stripeAccount: workspace.stripeConnectId,
+ },
+ );
+
+ const stripeCustomerInvoices =
+ StripeCustomerInvoiceSchema.array().parse(data);
+
+ return NextResponse.json(stripeCustomerInvoices);
+});
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.tsx
index eecb9af7ea..202d8dccc0 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,7 +3,6 @@ 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";
@@ -23,19 +22,10 @@ import {
Sheet,
SmartDateTimePicker,
Switch,
- Table,
ToggleGroup,
- useTable,
} from "@dub/ui";
-import {
- cn,
- currencyFormatter,
- fetcher,
- formatDateTime,
- pluralize,
-} from "@dub/utils";
+import { cn, currencyFormatter, formatDate } from "@dub/utils";
import { useAction } from "next-safe-action/hooks";
-import Link from "next/link";
import { useParams } from "next/navigation";
import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
@@ -49,6 +39,33 @@ interface CreateCommissionSheetProps {
type FormData = z.infer<typeof createCommissionSchema>;
+// API returns created as ISO string after JSON serialization
+type StripeInvoiceFromApi = {
+ id: string;
+ amount_paid: number;
+ created: string;
+};
+
+async function fetcherStripeInvoices(url: string): Promise<{
+ invoices: StripeInvoiceFromApi[];
+ noStripeCustomerId?: boolean;
+ message?: string;
+}> {
+ const res = await fetch(url);
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ if (res.status === 400 && body?.error?.message) {
+ return {
+ invoices: [],
+ noStripeCustomerId: true,
+ message: body.error.message,
+ };
+ }
+ throw new Error(body?.error?.message ?? "Failed to load invoices");
+ }
+ return { invoices: Array.isArray(body) ? body : [] };
+}
+
function CreateCommissionSheetContent({
setIsOpen,
}: CreateCommissionSheetProps) {
@@ -56,6 +73,7 @@ function CreateCommissionSheetContent({
const [hasInvoiceId, setHasInvoiceId] = useState(false);
const [hasProductId, setHasProductId] = useState(false);
const [hasDate, setHasDate] = useState(false);
+ const [hasSaleEventDate, setHasSaleEventDate] = useState(false);
const [hasCustomLeadEventDate, setHasCustomLeadEventDate] = useState(false);
const [hasCustomLeadEventName, setHasCustomLeadEventName] = useState(false);
@@ -136,14 +154,36 @@ function CreateCommissionSheetContent({
},
];
- // 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,
- );
+ const eventSourceOptions = [
+ {
+ value: "new",
+ label: "Create new event",
+ description:
+ "Create a new sale event for the partner (e.g. for one-time purchases)",
+ },
+ {
+ value: "existing",
+ label: "Import from Stripe",
+ description:
+ "Fetch the customer's paid invoices from Stripe (e.g. for recurring subscriptions)",
+ },
+ ];
+
+ // Fetch Stripe invoices when customer is selected and we're using existing events
+ const {
+ data: stripeInvoicesData,
+ isLoading: isStripeInvoicesLoading,
+ error: stripeInvoicesError,
+ } = useSWR(
+ customerId && useExistingEvents && commissionType === "sale" && workspaceId
+ ? `/api/customers/${customerId}/stripe-invoices?workspaceId=${workspaceId}`
+ : null,
+ fetcherStripeInvoices,
+ );
+
+ const stripeInvoices = stripeInvoicesData?.invoices ?? [];
+ const noStripeCustomerId = stripeInvoicesData?.noStripeCustomerId ?? false;
+ const noStripeCustomerMessage = stripeInvoicesData?.message;
useEffect(() => {
if (commissionType === "custom") {
@@ -163,6 +203,12 @@ function CreateCommissionSheetContent({
}
}, [hasDate, setValue]);
+ useEffect(() => {
+ if (!hasSaleEventDate) {
+ setValue("saleEventDate", null);
+ }
+ }, [hasSaleEventDate, setValue]);
+
useEffect(() => {
if (commissionType === "custom") {
setOpenAccordions(["partner-and-type", "commission"]);
@@ -212,99 +258,39 @@ function CreateCommissionSheetContent({
});
};
- // 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
- ? currencyFormatter(row.original.sale.amount)
- : "-"}
- </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(() => {
+ const submitDisabledMessage = useMemo(() => {
if (!partnerId) {
- return true;
+ return "You need to select a partner first before you can create a commission.";
}
if (commissionType === "custom") {
- return !amount;
+ return !amount
+ ? "You need to enter an amount for the commission."
+ : undefined;
}
if (!linkId || !customerId) {
- return true;
+ return "You need to select a customer and a link first before you can create a commission.";
}
- if (useExistingEvents && !filteredEvents.length) {
- return true;
+ if (commissionType === "sale") {
+ if (useExistingEvents) {
+ if (isStripeInvoicesLoading) {
+ return "Loading Stripe invoices...";
+ }
+
+ if (noStripeCustomerId) {
+ return "This customer doesn't have a Stripe customer ID. Add one in the customer profile before proceeding.";
+ }
+
+ if (stripeInvoices.length === 0) {
+ return "No paid Stripe invoices found for this customer.";
+ }
+ } else {
+ if (!saleAmount) {
+ return "You need to enter a sale amount for the commission.";
+ }
+ }
}
return false;
@@ -313,10 +299,12 @@ function CreateCommissionSheetContent({
partnerId,
linkId,
customerId,
- saleAmount,
- amount,
+ amount, // custom commission amount
+ saleAmount, // sale commission amount
useExistingEvents,
- filteredEvents,
+ noStripeCustomerId,
+ stripeInvoices.length,
+ isStripeInvoicesLoading,
]);
return (
@@ -600,46 +588,102 @@ function CreateCommissionSheetContent({
className="mt-2 flex w-full items-center gap-1 rounded-lg border border-neutral-200 bg-neutral-50 p-1"
optionClassName="h-8 flex items-center justify-center rounded-md flex-1 text-sm normal-case"
indicatorClassName="bg-white"
- options={[
- {
- value: "new",
- label: "Create new event",
- },
- {
- value: "existing",
- label: `Use existing ${pluralize("event", filteredEvents.length)}`,
- },
- ]}
+ options={eventSourceOptions}
selected={useExistingEvents ? "existing" : "new"}
selectAction={(value: string) =>
setUseExistingEvents(value === "existing")
}
/>
- {useExistingEvents && (
- <p className="mt-2 text-xs text-neutral-500">
- Existing events will be transferred to the new
- partner.
- </p>
- )}
+ <p className="mt-2 text-xs text-neutral-500">
+ {
+ eventSourceOptions.find(
+ (option) =>
+ option.value ===
+ (useExistingEvents ? "existing" : "new"),
+ )?.description
+ }
+ </p>
</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>
- )}
+ {/* Stripe invoices for sale + use existing */}
+ {customerId &&
+ useExistingEvents &&
+ commissionType === "sale" && (
+ <div className="space-y-3">
+ {isStripeInvoicesLoading ? (
+ <div className="flex h-40 items-center justify-center rounded-lg border border-neutral-200 bg-neutral-50/50">
+ <LoadingSpinner />
+ </div>
+ ) : noStripeCustomerId ? (
+ <div className="rounded-lg border border-amber-200 bg-amber-50/80 p-4">
+ <p className="text-sm font-medium text-amber-800">
+ No Stripe customer ID
+ </p>
+ <p className="mt-1 text-xs text-amber-700">
+ {noStripeCustomerMessage ??
+ "This customer doesn't have a Stripe customer ID. Add one in the customer profile to use paid Stripe invoices here."}
+ </p>
+ <a
+ href={`/${slug}/program/customers/${customerId}`}
+ target="_blank"
+ className="mt-2 inline-block text-xs font-medium text-amber-800 underline hover:no-underline"
+ >
+ Open customer profile →
+ </a>
+ </div>
+ ) : stripeInvoicesError ? (
+ <div className="rounded-lg border border-red-200 bg-red-50/80 p-4 text-sm text-red-800">
+ Failed to load invoices. Try again.
+ </div>
+ ) : stripeInvoices.length === 0 ? (
+ <div className="flex h-24 flex-col items-center justify-center rounded-lg border border-neutral-200 bg-neutral-50/30 text-center">
+ <p className="text-sm font-medium text-neutral-600">
+ No paid invoices found
+ </p>
+ <p className="mt-0.5 text-xs text-neutral-500">
+ This customer has no paid invoices in Stripe.
+ </p>
+ </div>
+ ) : (
+ <div className="overflow-hidden rounded-lg border border-neutral-200 bg-white shadow-sm">
+ <div className="border-b border-neutral-100 bg-neutral-50/80 px-3 py-2">
+ <p className="text-xs font-medium text-neutral-500">
+ Paid invoices ({stripeInvoices.length})
+ </p>
+ </div>
+ <div className="max-h-96 overflow-y-auto p-1.5">
+ {stripeInvoices.map((inv) => {
+ const createdDate = new Date(inv.created);
+ return (
+ <div
+ key={inv.id}
+ className="flex items-center justify-between gap-3 rounded-md px-3 py-2.5"
+ >
+ <div className="min-w-0 flex-1">
+ <a
+ href={`https://dashboard.stripe.com/invoices/${inv.id}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="cursor-alias font-mono text-sm font-medium text-neutral-800 decoration-dotted underline-offset-2 hover:underline"
+ >
+ {inv.id}
+ </a>
+ <p className="mt-0.5 text-xs text-neutral-500">
+ {formatDate(createdDate)}
+ </p>
+ </div>
+ <span className="shrink-0 text-sm font-medium text-neutral-700">
+ {currencyFormatter(inv.amount_paid)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
{customerId &&
!useExistingEvents &&
@@ -789,16 +833,33 @@ function CreateCommissionSheetContent({
</div>
<div>
- <SmartDateTimePicker
- value={saleEventDate}
- onChange={(date) => {
- setValue("saleEventDate", date, {
- shouldDirty: true,
- });
- }}
- label="Sale date"
- placeholder='E.g. "2024-03-01", "Last Thursday", "2 hours ago"'
- />
+ <div className="flex items-center gap-4">
+ <Switch
+ fn={setHasSaleEventDate}
+ checked={hasSaleEventDate}
+ trackDimensions="w-8 h-4"
+ thumbDimensions="w-3 h-3"
+ thumbTranslate="translate-x-4"
+ />
+ <h3 className="text-sm font-medium text-neutral-700">
+ Add sale date
+ </h3>
+ </div>
+
+ {hasSaleEventDate && (
+ <div className="mt-4">
+ <SmartDateTimePicker
+ value={saleEventDate}
+ onChange={(date) => {
+ setValue("saleEventDate", date, {
+ shouldDirty: true,
+ });
+ }}
+ label="Sale date"
+ placeholder='E.g. "2024-03-01", "Last Thursday", "2 hours ago"'
+ />
+ </div>
+ )}
</div>
<div>
@@ -924,10 +985,10 @@ function CreateCommissionSheetContent({
<Button
type="submit"
variant="primary"
- text="Create commission"
+ text={`Create commission${stripeInvoices.length > 0 ? "s" : ""}`}
className="w-fit"
loading={isPending}
- disabled={shouldDisableSubmit}
+ disabledTooltip={submitDisabledMessage}
/>
</div>
</div>
diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.ts
index 53e820be22..2b5ca0884e 100644
--- a/apps/web/lib/actions/partners/create-manual-commission.ts
+++ b/apps/web/lib/actions/partners/create-manual-commission.ts
@@ -1,18 +1,15 @@
"use server";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
-import { createId } from "@/lib/api/create-id";
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 { qstash } from "@/lib/cron";
import {
createPartnerCommission,
CreatePartnerCommissionProps,
} from "@/lib/partners/create-partner-commission";
-import { getCustomerEventsTB } from "@/lib/tinybird/get-customer-events-tb";
import {
recordClickZod,
recordClickZodSchema,
@@ -23,12 +20,13 @@ 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 { APP_DOMAIN_WITH_NGROK, nanoid, prettyPrint } from "@dub/utils";
+import { nanoid } 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(),
@@ -51,17 +49,18 @@ export const createManualCommissionAction = authActionClient
const {
partnerId,
commissionType,
- useExistingEvents,
// custom commission attributes
date,
amount,
description,
- // lead attributes
+ // customer attributes (for lead and sale commissions)
customerId,
linkId,
+ // lead attributes
leadEventDate,
leadEventName,
// sale attributes
+ useExistingEvents,
saleEventDate,
saleAmount,
invoiceId,
@@ -94,7 +93,7 @@ export const createManualCommissionAction = authActionClient
]);
// Create a custom commission
- if (!linkId) {
+ if (commissionType === "custom") {
await createPartnerCommission({
event: "custom",
partnerId,
@@ -111,7 +110,7 @@ export const createManualCommissionAction = authActionClient
return;
}
- if (!customerId || !customer || customer.projectId !== workspace.id) {
+ if (!customer || customer.projectId !== workspace.id) {
throw new Error(
`Customer${customerId ? ` with customerId ${customerId}` : ""} not found.`,
);
@@ -146,219 +145,109 @@ export const createManualCommissionAction = authActionClient
}
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 commissionsToCreate: CreatePartnerCommissionProps[] = [];
// Track event timestamps for updating link stats
let leadEventTimestamp: Date | null = null;
let saleEventTimestamp: Date | null = null;
- // If we're using existing events, we need to duplicate them under the new customer.id
+ // If we're using existing events (Stripe invoice for sale, or duplicate events for lead)
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}.`,
+ // Sale from selected Stripe invoice: create new events using invoice data
+ if (commissionType === "sale" && invoiceId && saleAmount != null) {
+ const finalLeadEventDate = saleEventDate ?? new Date();
+ const clickId = nanoid(16);
+ const clickTimestamp = new Date(
+ finalLeadEventDate.getTime() - 5 * 60 * 1000,
);
- }
-
- // 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 newClickAttributes = {
- click_id: nanoid(16), // create new clickId
- link_id: link.id, // set to new link.id,
- };
- const clickEventData = recordClickZodSchema.parse({
- ...existingClickEvent,
- ...newClickAttributes,
- });
-
- console.log("Click event to record: ", clickEventData);
- if (existingClickEvent) {
- tbEventsToRecord.push(recordClickZod(clickEventData));
- }
+ const generatedClickEvent = recordClickZodSchema.parse({
+ timestamp: clickTimestamp.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()] || ""
+ : "",
+ });
- const duplicateCustomerId = createId({ prefix: "cus_" });
+ tbEventsToRecord.push(recordClickZod(generatedClickEvent));
- if (existingLeadEvent) {
const leadEventData = leadEventSchemaTBWithTimestamp.parse({
- ...clickEventData,
- ...existingLeadEvent,
- ...newClickAttributes, // make sure new click attributes are not overridden by existing click attributes
- event_id: nanoid(16), // create new event_id
- link_id: link.id, // set to new link.id
- customer_id: duplicateCustomerId, // set to new duplicateCustomerId
+ ...generatedClickEvent,
+ event_id: nanoid(16),
+ event_name: leadEventName || "Sign up",
+ customer_id: customer.id,
+ timestamp: finalLeadEventDate.toISOString(),
});
- console.log("Lead event to record: ", leadEventData);
- 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
- commissionsToCreate.push({
- event: "lead" as const,
- programId,
- partnerId,
- linkId: link.id,
- customerId: duplicateCustomerId,
- eventId: leadEventData.event_id,
- quantity: 1,
- createdAt: new Date(leadEventData.timestamp + "Z"), // add the "Z" to the timestamp to make it UTC
- user,
- context: {
- customer: { country: customer.country },
- },
- });
- // Track the lead event timestamp for link stats update
- leadEventTimestamp = new Date(leadEventData.timestamp + "Z");
- }
- }
-
- const recordSaleEvents =
- commissionType === "sale" && existingSaleEvents.length > 0;
-
- if (recordSaleEvents) {
- if (existingSaleEvents.length > 5) {
- throw new Error(
- `You can only backfill up to 5 sale events. Found ${existingSaleEvents.length} existing sale events.`,
- );
- }
- const saleEventsData = existingSaleEvents.map((existingSaleEvent) =>
- saleEventSchemaTBWithTimestamp.parse({
- ...clickEventData,
- ...existingSaleEvent,
- ...newClickAttributes, // make sure new click attributes are not overridden
- event_id: nanoid(16), // create new event_id
- link_id: link.id, // set to new link.id
- customer_id: duplicateCustomerId, // set to new duplicateCustomerId
- amount: existingSaleEvent.saleAmount, // change format returned by Tinybird
- }),
- );
- console.log("Sale events to record: ", saleEventsData);
- tbEventsToRecord.push(recordSaleWithTimestamp(saleEventsData));
+ tbEventsToRecord.push(recordLeadWithTimestamp(leadEventData));
- // Store the original sale eventIds for nullification
- commissionsToTransferEventIds.push(
- ...existingSaleEvents.map(
- (existingSaleEvent) => existingSaleEvent.event_id,
- ),
- );
+ const saleEventData = saleEventSchemaTBWithTimestamp.parse({
+ ...generatedClickEvent,
+ event_id: nanoid(16),
+ invoice_id: invoiceId,
+ event_name: "Purchase",
+ amount: saleAmount,
+ customer_id: customer.id,
+ payment_processor: "stripe",
+ currency: "usd",
+ timestamp: new Date(saleEventDate ?? Date.now()).toISOString(),
+ metadata: productId ? JSON.stringify({ productId }) : undefined,
+ });
- if (commissionType === "sale") {
- // add the new sale events to the list of commissions to create
- commissionsToCreate.push(
- ...saleEventsData.map((saleEventData) => ({
- event: "sale" as const,
- 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 + "Z"), // add the "Z" to the timestamp to make it UTC
- user,
- context: {
- customer: {
- country: customer.country,
- },
- sale: {
- productId,
- },
- },
- })),
- );
- // Track the latest sale event timestamp for link stats update
- const latestSaleTimestamp = Math.max(
- ...saleEventsData.map((data) =>
- new Date(data.timestamp + "Z").getTime(),
- ),
- );
- saleEventTimestamp = new Date(latestSaleTimestamp);
- }
- totalSales = existingSaleEvents.length;
- totalSaleAmount = existingSaleEvents.reduce(
- (acc, saleEvent) => acc + saleEvent.saleAmount,
- 0,
- );
- }
+ tbEventsToRecord.push(recordSaleWithTimestamp(saleEventData));
- const duplicatedCustomer = await prisma.$transaction(async (tx) => {
- await tx.customer.update({
- where: {
- id: customer.id,
- },
- data: {
- name: customer.name ? `${customer.name} (old)` : undefined,
- externalId: `dummy_${nanoid(32)}`, // generate random externalId
- stripeCustomerId: null,
- linkId: null,
- programId: null,
- partnerId: null,
- clickId: null,
+ 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),
+ user,
+ context: {
+ customer: { country: customer.country },
+ sale: { productId },
},
});
- return await tx.customer.create({
+ saleEventTimestamp = new Date(saleEventData.timestamp);
+ totalSales = 1;
+ totalSaleAmount = saleAmount;
+
+ await prisma.customer.update({
+ where: { id: customer.id },
data: {
- ...customer,
- id: duplicateCustomerId,
linkId: link.id,
programId: link.programId,
partnerId: link.partnerId,
- clickId: clickEventData.click_id,
- clickedAt: new Date(clickEventData.timestamp),
- country:
- clickEventData.country === "Unknown"
- ? null
- : clickEventData.country,
- ...(recordSaleEvents && {
- sales: totalSales,
- saleAmount: totalSaleAmount,
- }),
+ clickId,
+ clickedAt: new Date(clickTimestamp),
+ sales: { increment: 1 },
+ saleAmount: { increment: saleAmount },
+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
},
});
- });
-
- console.log(
- `Duplicated customer ${customer.id} to ${duplicatedCustomer.id}: `,
- duplicatedCustomer,
- );
-
- // Else, we create new events
+ } else if (commissionType === "lead") {
+ if (!customer.linkId) {
+ throw new Error(
+ `No linkId found for existing customer ${customer.id}.`,
+ );
+ }
+ // TODO: duplicate existing lead events under new link
+ } else {
+ throw new Error(
+ "Select a Stripe invoice when using existing invoices for a sale commission.",
+ );
+ }
} else {
const finalLeadEventDate = leadEventDate ?? saleEventDate ?? new Date();
const clickId = nanoid(16);
@@ -488,89 +377,57 @@ export const createManualCommissionAction = authActionClient
waitUntil(
(async () => {
- const finalCommissionsToTransferEventIds =
- commissionsToTransferEventIds.filter(
- (eventId) => typeof eventId === "string",
- );
+ console.log("Commissions to create: ", commissionsToCreate);
- console.log(
- "Final commissions to transfer event ids: ",
- finalCommissionsToTransferEventIds,
+ // create partner commissions
+ await Promise.allSettled(
+ commissionsToCreate.map((commission) =>
+ createPartnerCommission(commission),
+ ),
);
const firstConversionFlag =
commissionType === "sale" &&
isFirstConversion({
customer,
- linkId,
+ linkId: link.id,
});
- const updatedRes = await Promise.all([
- // update link stats
- prisma.link.update({
- where: {
- id: link.id,
+ await prisma.link.update({
+ where: {
+ id: link.id,
+ },
+ data: {
+ // we'll always create click + lead events, so need to increment the stats
+ clicks: {
+ increment: 1,
},
- data: {
- // we'll always create click + lead events, so need to increment the stats
- clicks: {
- increment: 1,
- },
- leads: {
+ leads: {
+ increment: 1,
+ },
+ lastLeadAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastLeadAt,
+ newTimestamp: leadEventTimestamp || new Date(),
+ }),
+ ...(firstConversionFlag && {
+ conversions: {
increment: 1,
},
- lastLeadAt: updateLinkStatsForImporter({
- currentTimestamp: link.lastLeadAt,
- newTimestamp: leadEventTimestamp || new Date(),
+ lastConversionAt: updateLinkStatsForImporter({
+ currentTimestamp: link.lastConversionAt,
+ newTimestamp: saleEventTimestamp || new Date(),
}),
- ...(firstConversionFlag && {
- conversions: {
- increment: 1,
- },
- lastConversionAt: updateLinkStatsForImporter({
- currentTimestamp: link.lastConversionAt,
- newTimestamp: saleEventTimestamp || new Date(),
- }),
- }),
- ...(commissionType === "sale" && {
- sales: {
- increment: saleAmount ? 1 : totalSales,
- },
- saleAmount: {
- increment: saleAmount ?? totalSaleAmount,
- },
- }),
- },
- }),
-
- // update the commissions
- finalCommissionsToTransferEventIds.length > 0 &&
- prisma.commission.updateMany({
- where: {
- eventId: {
- in: finalCommissionsToTransferEventIds,
- },
+ }),
+ ...(commissionType === "sale" && {
+ sales: {
+ increment: saleAmount ? 1 : totalSales,
},
- data: {
- eventId: null,
- invoiceId: null,
+ saleAmount: {
+ increment: saleAmount ?? totalSaleAmount,
},
}),
- ]);
-
- console.log(
- `Updated link${finalCommissionsToTransferEventIds.length > 0 ? " and nullified old commissions" : ""}:`,
- updatedRes,
- );
-
- console.log("Commissions to create: ", commissionsToCreate);
-
- // create partner commissions
- await Promise.allSettled(
- commissionsToCreate.map((commission) =>
- createPartnerCommission(commission),
- ),
- );
+ },
+ });
// execute workflows
if (["lead", "sale"].includes(commissionType)) {
@@ -604,15 +461,3 @@ export const createManualCommissionAction = authActionClient
})(),
);
});
-
-async function triggerAggregateDueCommissionsCronJob(programId: string) {
- const qstashResponse = await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/aggregate-due-commissions`,
- body: {
- programId,
- },
- });
- console.log(
- `Triggered aggregate due commissions cron job for program ${programId}: ${prettyPrint(qstashResponse)}`,
- );
-}
diff --git a/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts b/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
new file mode 100644
index 0000000000..22e56a5d84
--- /dev/null
+++ b/apps/web/lib/actions/partners/trigger-aggregate-due-commissions.ts
@@ -0,0 +1,14 @@
+import { qstash } from "@/lib/cron";
+import { APP_DOMAIN_WITH_NGROK, prettyPrint } from "@dub/utils";
+
+export async function triggerAggregateDueCommissionsCronJob(programId: string) {
+ const qstashResponse = await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/aggregate-due-commissions`,
+ body: {
+ programId,
+ },
+ });
+ console.log(
+ `Triggered aggregate due commissions cron job for program ${programId}: ${prettyPrint(qstashResponse)}`,
+ );
+}
diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.ts
index e6e5cc34e0..cbd2082ee8 100644
--- a/apps/web/lib/zod/schemas/customers.ts
+++ b/apps/web/lib/zod/schemas/customers.ts
@@ -194,3 +194,9 @@ export const StripeCustomerSchema = z.object({
subscriptions: z.number(),
dubCustomerId: z.string().nullable(),
});
+
+export const StripeCustomerInvoiceSchema = z.object({
+ id: z.string(),
+ amount_paid: z.number(),
+ created: z.number().transform((v) => new Date(v * 1000)),
+});