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.

demo commission

Pedro Ladeira353ec92d9ad6
diff --git a/apps/web/.env.example b/apps/web/.env.example
index e7883eb7b3..c8b378c39e 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -8,7 +8,8 @@ NEXTAUTH_URL=http://localhost:8888 # (only needed for localhost)
# Secret for Vercel cron jobs + sync-embeddings
CRON_SECRET=
-# Shared with the LoopWork demo cron. Mints geo-accurate clicks via POST /api/demo/click
+# Shared with the LoopWork demo. Mints geo-accurate clicks via POST /api/demo/click
+# and backdated commissions via POST /api/demo/commission
DEMO_CLICK_SECRET=
# Encryption key (AES-256-GCM) for encrypting sensitive data in the database
ENCRYPTION_KEY=
diff --git a/apps/web/app/(ee)/api/demo/click/route.ts b/apps/web/app/(ee)/api/demo/click/route.ts
index d35f90f167..63cdfbac2f 100644
--- a/apps/web/app/(ee)/api/demo/click/route.ts
+++ b/apps/web/app/(ee)/api/demo/click/route.ts
@@ -1,15 +1,11 @@
+import { assertDemoLink, verifyDemoSecret } from "@/lib/api/demo/guard";
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
-import { prefixWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import { withAxiom } from "@/lib/axiom/server";
import { getLinkWithPartner } from "@/lib/planetscale/get-link-with-partner";
import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
-import {
- COUNTRY_CODES,
- DEMO_PROGRAM_ID,
- DEMO_WORKSPACE_ID,
- getDomainWithoutWWW,
-} from "@dub/utils";
+import { parseDateSchema } from "@/lib/zod/schemas/utils";
+import { COUNTRY_CODES, getDomainWithoutWWW } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
@@ -25,24 +21,13 @@ const demoClickSchema = z.object({
continent: z.string().nullish(),
referrer: z.string().nullish(),
userAgent: z.string().nullish(),
+ timestamp: parseDateSchema.nullish(),
});
-function verifyDemoClickSecret(req: Request) {
- const secret = process.env.DEMO_CLICK_SECRET;
- const authorization = req.headers.get("authorization");
-
- if (!secret || authorization !== `Bearer ${secret}`) {
- throw new DubApiError({
- code: "unauthorized",
- message: "Invalid or missing DEMO_CLICK_SECRET.",
- });
- }
-}
-
// POST /api/demo/click – mint a geo-accurate click for the LoopWork demo workspace only
export const POST = withAxiom(async (req) => {
try {
- verifyDemoClickSecret(req);
+ verifyDemoSecret(req);
const {
domain,
@@ -53,6 +38,7 @@ export const POST = withAxiom(async (req) => {
continent,
referrer,
userAgent,
+ timestamp,
} = demoClickSchema.parse(await parseRequestBody(req));
const link = await getLinkWithPartner({ domain, key });
@@ -64,21 +50,7 @@ export const POST = withAxiom(async (req) => {
});
}
- if (
- prefixWorkspaceId(link.projectId) !== prefixWorkspaceId(DEMO_WORKSPACE_ID)
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "This endpoint can only record clicks for the demo workspace.",
- });
- }
-
- if (link.programId && link.programId !== DEMO_PROGRAM_ID) {
- throw new DubApiError({
- code: "forbidden",
- message: "This endpoint can only record clicks for the demo program.",
- });
- }
+ assertDemoLink(link);
const clickEvent = await recordFakeClick({
link: {
@@ -98,6 +70,7 @@ export const POST = withAxiom(async (req) => {
},
referrer,
userAgent,
+ ...(timestamp && { timestamp: timestamp.toISOString() }),
});
return NextResponse.json({ clickId: clickEvent.click_id });
diff --git a/apps/web/app/(ee)/api/demo/commission/route.ts b/apps/web/app/(ee)/api/demo/commission/route.ts
new file mode 100644
index 0000000000..62c37bfe5b
--- /dev/null
+++ b/apps/web/app/(ee)/api/demo/commission/route.ts
@@ -0,0 +1,82 @@
+import { createDemoCommission } from "@/lib/api/demo/create-demo-commission";
+import { assertDemoLink, verifyDemoSecret } from "@/lib/api/demo/guard";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withAxiom } from "@/lib/axiom/server";
+import { getLinkWithPartner } from "@/lib/planetscale/get-link-with-partner";
+import { centsSchema, parseDateSchema } from "@/lib/zod/schemas/utils";
+import { COUNTRY_CODES, getDomainWithoutWWW } from "@dub/utils";
+import { NextResponse } from "next/server";
+import * as z from "zod/v4";
+
+const demoCommissionSchema = z
+ .object({
+ domain: z.preprocess(
+ (val) => getDomainWithoutWWW(val as string),
+ z.string({ error: "domain is required." }),
+ ),
+ key: z.string({ error: "key is required." }),
+ date: parseDateSchema,
+ type: z.enum(["lead", "sale"]),
+ country: z.enum(COUNTRY_CODES),
+ region: z.string().nullish(),
+ city: z.string().nullish(),
+ continent: z.string().nullish(),
+ referrer: z.string().nullish(),
+ userAgent: z.string().nullish(),
+ customer: z.object({
+ name: z.string().nullish(),
+ email: z.string().nullish(),
+ externalId: z.string(),
+ country: z.enum(COUNTRY_CODES),
+ }),
+ sale: z
+ .object({
+ amount: centsSchema.pipe(z.number().int().min(0)),
+ invoiceId: z.string().nullish(),
+ eventName: z.string().nullish(),
+ })
+ .nullish(),
+ })
+ .refine((data) => data.type !== "sale" || data.sale?.amount != null, {
+ message: "sale.amount is required when type is sale.",
+ path: ["sale", "amount"],
+ });
+
+// POST /api/demo/commission – backdated click + lead/sale + commission for the LoopWork demo only
+export const POST = withAxiom(async (req) => {
+ try {
+ verifyDemoSecret(req);
+
+ const body = demoCommissionSchema.parse(await parseRequestBody(req));
+ const { domain, key, date, ...rest } = body;
+
+ const link = await getLinkWithPartner({ domain, key });
+
+ if (!link) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Link not found for domain: ${domain} and key: ${key}.`,
+ });
+ }
+
+ assertDemoLink(link);
+
+ if (!date) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Invalid date.",
+ });
+ }
+
+ const result = await createDemoCommission({
+ link,
+ date,
+ ...rest,
+ });
+
+ return NextResponse.json(result);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+});
diff --git a/apps/web/lib/api/demo/create-demo-commission.ts b/apps/web/lib/api/demo/create-demo-commission.ts
new file mode 100644
index 0000000000..44ad1fa88a
--- /dev/null
+++ b/apps/web/lib/api/demo/create-demo-commission.ts
@@ -0,0 +1,301 @@
+import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
+import { createId } from "@/lib/api/create-id";
+import { DubApiError } from "@/lib/api/errors";
+import { updateLinkStatsForImporter } from "@/lib/api/links/update-link-stats-for-importer";
+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";
+import { generateRandomName } from "@/lib/names";
+import { queuePartnerCommissionCreation } from "@/lib/partners/queue-partner-commission-creation";
+import { EdgeLinkProps } from "@/lib/planetscale/types";
+import { prisma } from "@/lib/prisma";
+import { recordLeadWithTimestamp } from "@/lib/tinybird/record-lead";
+import { recordFakeClick } from "@/lib/tinybird/record-fake-click";
+import { recordSaleWithTimestamp } from "@/lib/tinybird/record-sale";
+import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";
+import { saleEventSchemaTB } from "@/lib/zod/schemas/sales";
+import { DEMO_PROGRAM_ID, nanoid } from "@dub/utils";
+import { CommissionType } from "@prisma/client";
+import * as z from "zod/v4";
+
+const leadEventSchemaTBWithTimestamp = leadEventSchemaTB.extend({
+ timestamp: z.string(),
+});
+
+const saleEventSchemaTBWithTimestamp = saleEventSchemaTB.extend({
+ timestamp: z.string(),
+});
+
+export async function createDemoCommission({
+ link,
+ type,
+ date,
+ country,
+ region,
+ city,
+ continent,
+ referrer,
+ userAgent,
+ customer,
+ sale,
+}: {
+ link: Pick<
+ EdgeLinkProps,
+ "id" | "url" | "domain" | "key" | "projectId" | "programId" | "partnerId"
+ >;
+ type: "lead" | "sale";
+ date: Date;
+ country: string;
+ region?: string | null;
+ city?: string | null;
+ continent?: string | null;
+ referrer?: string | null;
+ userAgent?: string | null;
+ customer: {
+ name?: string | null;
+ email?: string | null;
+ externalId: string;
+ country: string;
+ };
+ sale?: {
+ amount: number;
+ invoiceId?: string | null;
+ eventName?: string | null;
+ } | null;
+}) {
+ if (!link.partnerId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Demo commissions require a partner link.",
+ });
+ }
+
+ if (type === "sale" && sale?.amount == null) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "sale.amount is required when type is sale.",
+ });
+ }
+
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: link.projectId,
+ },
+ select: {
+ id: true,
+ stripeConnectId: true,
+ },
+ });
+
+ if (!workspace) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Demo workspace not found.",
+ });
+ }
+
+ const targetLink = await prisma.link.findUnique({
+ where: { id: link.id },
+ });
+
+ if (!targetLink) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Link ${link.id} not found.`,
+ });
+ }
+
+ const invoiceId = sale?.invoiceId ?? null;
+
+ if (type === "sale" && invoiceId) {
+ const existing = await prisma.commission.findUnique({
+ where: {
+ invoiceId_programId: {
+ invoiceId,
+ programId: DEMO_PROGRAM_ID,
+ },
+ },
+ select: { id: true },
+ });
+
+ if (existing) {
+ throw new DubApiError({
+ code: "conflict",
+ message: `There is already a commission for the invoice ${invoiceId}.`,
+ });
+ }
+ }
+
+ const customerId = createId({ prefix: "cus_" });
+ const targetCustomer = await prisma.customer.upsert({
+ where: {
+ projectId_externalId: {
+ projectId: workspace.id,
+ externalId: customer.externalId,
+ },
+ },
+ create: {
+ id: customerId,
+ name: customer.name || customer.email || generateRandomName(),
+ email: customer.email,
+ externalId: customer.externalId,
+ country: customer.country,
+ linkId: targetLink.id,
+ projectId: workspace.id,
+ projectConnectId: workspace.stripeConnectId,
+ createdAt: date,
+ },
+ update: {
+ name: customer.name || customer.email || generateRandomName(),
+ email: customer.email,
+ country: customer.country,
+ },
+ });
+
+ const firstConversion = isFirstConversion({
+ customer: targetCustomer,
+ linkId: targetLink.id,
+ });
+
+ const clickedAt = new Date(date.getTime() - 5 * 60 * 1000);
+
+ const clickEvent = await recordFakeClick({
+ link: {
+ id: targetLink.id,
+ url: targetLink.url,
+ domain: targetLink.domain,
+ key: targetLink.key,
+ projectId: targetLink.projectId,
+ programId: targetLink.programId,
+ partnerId: targetLink.partnerId,
+ },
+ customer: {
+ country,
+ region,
+ city,
+ continent,
+ },
+ referrer,
+ userAgent,
+ timestamp: clickedAt.toISOString(),
+ });
+
+ const eventTimestamp = date.toISOString();
+
+ const leadEvent = leadEventSchemaTBWithTimestamp.parse({
+ ...clickEvent,
+ event_id: nanoid(16),
+ event_name: "Sign up",
+ customer_id: targetCustomer.id,
+ timestamp: eventTimestamp,
+ metadata: "",
+ });
+
+ const saleEvent =
+ type === "sale" && sale
+ ? saleEventSchemaTBWithTimestamp.parse({
+ ...clickEvent,
+ event_id: nanoid(16),
+ event_name: sale.eventName ?? "Purchase",
+ customer_id: targetCustomer.id,
+ payment_processor: "stripe",
+ amount: sale.amount,
+ invoice_id: invoiceId ?? "",
+ currency: "usd",
+ timestamp: eventTimestamp,
+ metadata: "",
+ })
+ : null;
+
+ await Promise.all([
+ recordLeadWithTimestamp(leadEvent),
+ saleEvent ? recordSaleWithTimestamp(saleEvent) : undefined,
+ ]);
+
+ await queuePartnerCommissionCreation({
+ event:
+ type === "sale" ? CommissionType.sale : CommissionType.lead,
+ programId: DEMO_PROGRAM_ID,
+ partnerId: link.partnerId,
+ linkId: targetLink.id,
+ customerId: targetCustomer.id,
+ eventId: saleEvent?.event_id ?? leadEvent.event_id,
+ quantity: 1,
+ createdAt: date,
+ ...(saleEvent && {
+ amount: saleEvent.amount,
+ currency: saleEvent.currency,
+ invoiceId: saleEvent.invoice_id || undefined,
+ isFirstConversion: firstConversion,
+ }),
+ context: {
+ customer: {
+ country: targetCustomer.country,
+ ...(type === "sale" && { signupDate: targetCustomer.createdAt }),
+ },
+ ...(type === "sale" &&
+ saleEvent && {
+ sale: {
+ amount: saleEvent.amount,
+ },
+ }),
+ },
+ triggerAggregateDueCommissions: true,
+ });
+
+ const totalSales = saleEvent ? 1 : 0;
+ const totalSaleAmount = saleEvent?.amount ?? 0;
+ const lastLeadAt = updateLinkStatsForImporter({
+ currentTimestamp: targetLink.lastLeadAt,
+ newTimestamp: date,
+ });
+ const lastConversionAt = saleEvent
+ ? updateLinkStatsForImporter({
+ currentTimestamp: targetLink.lastConversionAt,
+ newTimestamp: date,
+ })
+ : undefined;
+
+ await prisma.$transaction([
+ prisma.link.update({
+ where: { id: targetLink.id },
+ data: {
+ clicks: { increment: 1 },
+ leads: { increment: 1 },
+ lastLeadAt,
+ ...(firstConversion &&
+ saleEvent && {
+ conversions: { increment: 1 },
+ lastConversionAt,
+ }),
+ 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.click_id,
+ clickedAt,
+ sales: { increment: totalSales },
+ saleAmount: { increment: totalSaleAmount },
+ ...(type === "sale" &&
+ !targetCustomer.firstSaleAt && {
+ firstSaleAt: date,
+ }),
+ },
+ }),
+ ]);
+
+ await syncPartnerLinksStats({
+ partnerId: link.partnerId,
+ programId: DEMO_PROGRAM_ID,
+ eventType: type,
+ });
+
+ return {
+ clickId: clickEvent.click_id,
+ customerId: targetCustomer.id,
+ };
+}
diff --git a/apps/web/lib/api/demo/guard.ts b/apps/web/lib/api/demo/guard.ts
new file mode 100644
index 0000000000..43ae0bf60a
--- /dev/null
+++ b/apps/web/lib/api/demo/guard.ts
@@ -0,0 +1,43 @@
+import { DubApiError } from "@/lib/api/errors";
+import { prefixWorkspaceId } from "@/lib/api/workspaces/workspace-id";
+import { EdgeLinkProps } from "@/lib/planetscale/types";
+import { DEMO_PROGRAM_ID, DEMO_WORKSPACE_ID } from "@dub/utils";
+
+export function verifyDemoSecret(req: Request) {
+ const secret = process.env.DEMO_CLICK_SECRET;
+ const authorization = req.headers.get("authorization");
+
+ if (!secret || authorization !== `Bearer ${secret}`) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Invalid or missing DEMO_CLICK_SECRET.",
+ });
+ }
+}
+
+export function assertDemoLink(
+ link: Pick<EdgeLinkProps, "projectId" | "programId"> | null,
+): asserts link is NonNullable<typeof link> {
+ if (!link) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "Link not found.",
+ });
+ }
+
+ if (
+ prefixWorkspaceId(link.projectId) !== prefixWorkspaceId(DEMO_WORKSPACE_ID)
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This endpoint can only record events for the demo workspace.",
+ });
+ }
+
+ if (link.programId && link.programId !== DEMO_PROGRAM_ID) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "This endpoint can only record events for the demo program.",
+ });
+ }
+}
diff --git a/apps/web/lib/tinybird/record-fake-click.ts b/apps/web/lib/tinybird/record-fake-click.ts
index 7461969f92..5a56d2be64 100644
--- a/apps/web/lib/tinybird/record-fake-click.ts
+++ b/apps/web/lib/tinybird/record-fake-click.ts
@@ -53,7 +53,8 @@ export async function recordFakeClick({
const dummyRequest = new Request(link.url, {
headers: new Headers({
"user-agent":
- userAgent || "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
+ toSafeHeaderValue(userAgent) ||
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
"x-forwarded-for": "127.0.0.1",
"x-vercel-ip-country": country,
"x-vercel-ip-country-region": toSafeHeaderValue(customer?.region) || "CA",