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.

1.8 KB
Raw Blame
import { trackSale } from "@/lib/api/conversions/track-sale";
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { trackSaleRequestSchema } from "@/lib/zod/schemas/sales";
import { NextResponse } from "next/server";
import * as z from "zod/v4";

// POST /api/track/sale – Track a sale conversion event
export const POST = withWorkspace(
  async ({ req, workspace }) => {
    const body = await parseRequestBody(req);

    let {
      customerExternalId: newExternalId,
      externalId: oldExternalId, // deprecated
      customerId: oldCustomerId, // deprecated
      customerName,
      customerEmail,
      customerAvatar,
      clickId,
      amount,
      currency,
      eventName,
      paymentProcessor,
      invoiceId,
      leadEventName,
      metadata,
    } = trackSaleRequestSchema
      .extend({
        // add backwards compatibility
        customerExternalId: z.string().nullish(),
        externalId: z.string().nullish(),
        customerId: z.string().nullish(),
      })
      .parse(body);

    const customerExternalId = newExternalId || oldExternalId || oldCustomerId;

    if (!customerExternalId) {
      throw new DubApiError({
        code: "bad_request",
        message: "customerExternalId is required",
      });
    }

    const response = await trackSale({
      customerExternalId,
      customerName,
      customerEmail,
      customerAvatar,
      clickId,
      amount,
      currency,
      eventName,
      paymentProcessor,
      invoiceId,
      leadEventName,
      metadata,
      workspace,
    });

    return NextResponse.json(response);
  },
  {
    requiredPlan: ["business", "advanced", "enterprise"],
    requiredRoles: ["owner", "member"],
  },
);