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.

5.8 KB
Raw Blame
import { DubApiError } from "@/lib/api/errors";
import { getDubAdminRole, withWorkspace } from "@/lib/auth";
import { getFeatureFlags } from "@/lib/edge-config";
import { stripe } from "@/lib/stripe";
import { isEligibleForTrial } from "@/lib/stripe/is-eligible-for-trial";
import { booleanQuerySchema } from "@/lib/zod/schemas/misc";
import { APP_DOMAIN, DUB_TRIAL_PERIOD_DAYS } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";

const upgradePlanSchema = z.object({
  plan: z.enum(["pro", "business", "advanced"]),
  period: z.enum(["monthly", "yearly"]),
  tier: z.number().min(1).max(3).optional().default(1),
  baseUrl: z.string().refine((url) => url.startsWith(APP_DOMAIN), {
    message: "Invalid baseUrl.",
  }),
  onboarding: booleanQuerySchema.nullish(),
});

// POST /api/workspaces/[idOrSlug]/billing/upgrade
export const POST = withWorkspace(
  async ({ req, workspace, session }) => {
    let { plan, period, tier, baseUrl, onboarding } = upgradePlanSchema.parse(
      await req.json(),
    );

    if (workspace.disabledAt) {
      plan = "advanced";
      period = "yearly";
    }

    const lookupKey =
      tier > 1 ? `${plan}${tier}_${period}` : `${plan}_${period}`;

    const prices = await stripe.prices.list({
      lookup_keys: [lookupKey],
    });

    if (prices.data.length === 0) {
      throw new DubApiError({
        code: "not_found",
        message: `Price not found for lookup key: ${lookupKey}`,
      });
    }

    const existingSubscription = workspace.stripeId
      ? await stripe.subscriptions
          .list({
            customer: workspace.stripeId,
            limit: 1,
          })
          .then((res) => res.data[0])
      : null;

    if (process.env.VERCEL === "1" && process.env.VERCEL_ENV === "preview") {
      const adminRole = await getDubAdminRole(session.user.id);
      if (!adminRole) {
        throw new DubApiError({
          code: "unauthorized",
          message: "Unauthorized: Not an admin.",
        });
      }
    }

    if (workspace.stripeId && existingSubscription) {
      if (existingSubscription.status === "trialing") {
        await stripe.subscriptions.update(existingSubscription.id, {
          items: [
            {
              id: existingSubscription.items.data[0].id,
              price: prices.data[0].id,
            },
          ],
          proration_behavior: "none", // no invoice is created and no charge is issued
        });

        const successUrl = new URL(baseUrl);
        successUrl.searchParams.set("upgraded", "true");
        successUrl.searchParams.set("plan", plan);
        successUrl.searchParams.set("period", period);
        return NextResponse.json({ url: successUrl.toString() });
      }

      // Active subscriptions: use the billing portal's plan-change confirmation flow.
      const currentItem = existingSubscription.items.data[0];
      const targetPriceId = prices.data[0].id;
      const alreadyOnTargetPlan =
        currentItem.price.id === targetPriceId &&
        (currentItem.quantity ?? 1) === 1;

      if (alreadyOnTargetPlan) {
        throw new DubApiError({
          code: "bad_request",
          message:
            "You're already on this plan. Refresh the page or choose a different plan.",
        });
      }

      const flags = await getFeatureFlags({ workspaceId: workspace.id });

      try {
        const { url } = await stripe.billingPortal.sessions.create({
          customer: workspace.stripeId,
          ...(flags.noProrationUpgrade
            ? { configuration: "bpc_1TyLVFAlJJEpqkPVbJdDVr4m" }
            : {}),
          return_url: baseUrl,
          flow_data: {
            type: "subscription_update_confirm",
            subscription_update_confirm: {
              subscription: existingSubscription.id,
              items: [
                {
                  id: currentItem.id,
                  quantity: 1,
                  price: targetPriceId,
                },
              ],
            },
          },
        });
        return NextResponse.json({ url });
      } catch (error) {
        if (
          error instanceof Error &&
          error.message.includes("no changes to confirm")
        ) {
          throw new DubApiError({
            code: "bad_request",
            message:
              "You're already on this plan. Refresh the page or choose a different plan.",
          });
        }
        throw error;
      }
    } else {
      const stripeSession = await stripe.checkout.sessions.create({
        ...(workspace.stripeId
          ? {
              customer: workspace.stripeId,
              // need to pass this or Stripe will throw an error: https://git.new/kX4fi6B
              customer_update: {
                name: "auto",
                address: "auto",
              },
            }
          : {
              customer_email: session.user.email,
            }),
        billing_address_collection: "required",
        success_url: onboarding
          ? `${APP_DOMAIN}/onboarding/success?workspace=${workspace.slug}`
          : `${APP_DOMAIN}/${workspace.slug}?upgraded=true&plan=${plan}&period=${period}`,
        cancel_url: baseUrl,
        line_items: [{ price: prices.data[0].id, quantity: 1 }],
        allow_promotion_codes: true,
        automatic_tax: {
          enabled: true,
        },
        tax_id_collection: {
          enabled: true,
        },
        mode: "subscription",
        ...(isEligibleForTrial({ workspace, session })
          ? {
              subscription_data: {
                trial_period_days: DUB_TRIAL_PERIOD_DAYS,
              },
            }
          : {}),
        client_reference_id: workspace.id,
        metadata: {
          dubCustomerId: session.user.id,
        },
      });

      return NextResponse.json({ id: stripeSession.id });
    }
  },
  {
    requiredPermissions: ["billing.write"],
  },
);