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.

4.9 KB
Raw Blame
import { trackLead } from "@/lib/api/conversions/track-lead";
import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";
import { prisma } from "@/lib/prisma";
import { pick, STRIPE_INTEGRATION_ID } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { getConnectedCustomer } from "./utils/get-connected-customer";

// Handle event "customer.subscription.created"
// - non-trial: clear subscriptionCanceledAt (e.g. resubscriptions)
// - trialing: record free trial lead (when enabled)
export async function customerSubscriptionCreated({
  event,
  mode,
  workspace,
}: WebhookHandlerInput<Stripe.CustomerSubscriptionCreatedEvent>): Promise<WebhookHandlerResponse> {
  const createdSubscription = event.data.object;
  const stripeAccountId = workspace.stripeConnectId!;
  const stripeCustomerId = createdSubscription.customer as string;

  // Non-trial subscription created — clear any prior cancellation timestamp
  if (createdSubscription.status !== "trialing") {
    const customer = await prisma.customer.findUnique({
      where: {
        stripeCustomerId,
      },
      select: {
        id: true,
      },
    });

    if (!customer) {
      return {
        response: `Customer with stripeCustomerId ${stripeCustomerId} not found, skipping...`,
      };
    }

    await prisma.customer.update({
      where: {
        id: customer.id,
      },
      data: {
        subscriptionCanceledAt: null,
      },
    });

    return {
      response: `Subscription created (non-trial), cleared subscriptionCanceledAt for customer ${customer.id}`,
    };
  }

  // Free trial subscription created — record free trial lead (when enabled)
  const installedIntegration = await prisma.installedIntegration.findFirst({
    where: {
      projectId: workspace.id,
      integrationId: STRIPE_INTEGRATION_ID,
    },
    orderBy: {
      createdAt: "asc",
    },
  });

  if (!installedIntegration) {
    return {
      response: `Workspace ${workspace.id} has no Stripe integration installed, skipping...`,
    };
  }

  const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(
    installedIntegration.settings || {},
  );

  if (!stripeIntegrationSettings?.freeTrials?.enabled) {
    return {
      response: `Stripe free trial tracking is not enabled for workspace ${workspace.id}, skipping...`,
    };
  }

  // find customer by stripeCustomerId or email
  let customer = await prisma.customer.findUnique({
    where: {
      stripeCustomerId,
    },
    select: {
      id: true,
      clickId: true,
      externalId: true,
      name: true,
      email: true,
    },
  });

  if (!customer) {
    const stripeCustomer = await getConnectedCustomer({
      stripeCustomerId,
      stripeAccountId,
      mode,
    });

    if (stripeCustomer?.email) {
      customer = await prisma.customer.findFirst({
        where: {
          projectId: workspace.id,
          email: stripeCustomer.email,
        },
        select: {
          id: true,
          clickId: true,
          externalId: true,
          name: true,
          email: true,
        },
      });

      if (!customer) {
        // this should never happen, but just in case
        return {
          response: `Customer ${stripeCustomer.id} with email ${stripeCustomer.email} has not been tracked yet, skipping...`,
        };
      }
      // update the customer with the Stripe customer ID (for future reference by invoice.paid)
      waitUntil(
        prisma.customer.update({
          where: {
            id: customer.id,
          },
          data: {
            stripeCustomerId,
          },
        }),
      );
    } else {
      // this should never happen either, but just in case
      return {
        response: `Customer with stripeCustomerId ${stripeCustomerId} ${stripeCustomer ? "does not have an email on Stripe" : "does not exist"}, skipping...`,
      };
    }
  }

  if (!customer.clickId) {
    return {
      response: `Customer ${customer.id} has no clickId, skipping...`,
    };
  }

  if (!customer.externalId) {
    return {
      response: `Customer ${customer.id} has no externalId, skipping...`,
    };
  }

  // if trackQuantity is enabled, use the quantity from the main subscription item
  // (e.g. for a 3-seat free trial, the event quantity will be 3)
  const eventQuantity = stripeIntegrationSettings.freeTrials.trackQuantity
    ? createdSubscription.items.data[0].quantity
    : 1;

  await trackLead({
    clickId: customer.clickId,
    eventName: "Started Trial",
    customerExternalId: customer.externalId,
    customerName: customer.name,
    customerEmail: customer.email,
    eventQuantity,
    workspace: pick(workspace, ["id", "stripeConnectId", "webhookEnabled"]),
  });

  return {
    response: `Customer subscription created for customer ${customer.id} with stripeCustomerId ${stripeCustomerId} and workspace ${workspace.id}`,
  };
}