Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

22.8 KB
Raw Blame
import Link from "next/link";
import { useRouter } from "next/router";

import { useEffect, useMemo, useState } from "react";
import React from "react";

import { useTeam } from "@/context/team-context";
import { Feature, PlanEnum, getPlanFeatures } from "@/ee/stripe/constants";
import { getPriceIdFromPlan } from "@/ee/stripe/functions/get-price-id-from-plan";
import { PLANS } from "@/ee/stripe/utils";
import {
  CheckIcon,
  CircleHelpIcon,
  Sparkles,
  Users2Icon,
  XIcon,
} from "lucide-react";

import { useAnalytics } from "@/lib/analytics";
import { usePlan } from "@/lib/swr/use-billing";
import { capitalize, cn } from "@/lib/utils";

import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";
import { Switch } from "@/components/ui/switch";
import {
  BadgeTooltip,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

// Start Data Room Trial Button Component
const StartDataRoomTrialButton = ({ teamId }: { teamId?: string }) => {
  const router = useRouter();

  const handleStartTrial = () => {
    router.push("/welcome?type=dataroom-trial");
  };

  return (
    <span
      onClick={handleStartTrial}
      className="cursor-pointer underline underline-offset-4 hover:text-foreground"
    >
      Start free Data Rooms Plus trial
    </span>
  );
};

// Feature rendering component
const FeatureItem = ({ feature }: { feature: Feature }) => {
  const baseClasses = `flex items-center ${feature.isHighlighted ? "bg-orange-50 -mx-3 px-3 py-2 -my-1 font-bold rounded-md dark:bg-orange-900/20" : ""}`;

  if (feature.isUsers) {
    return (
      <div className={cn("justify-between gap-x-8", baseClasses)}>
        <div className="flex items-center gap-x-3">
          {feature.isNotIncluded ? (
            <XIcon className="h-5 w-5 flex-shrink-0 text-gray-500" />
          ) : (
            <CheckIcon className="h-5 w-5 flex-shrink-0 text-[#fb7a00]" />
          )}
          <span>{feature.text}</span>
        </div>
        {feature.tooltip && (
          <TooltipProvider>
            <Tooltip delayDuration={0}>
              <TooltipTrigger asChild>
                <div className="cursor-help">
                  <Users2Icon className="h-4 w-4 text-gray-500" />
                </div>
              </TooltipTrigger>
              <TooltipContent>
                <p>{feature.tooltip}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        )}
      </div>
    );
  }

  return (
    <div className={cn("text-sm", baseClasses)}>
      {feature.isNotIncluded ? (
        <XIcon className="mr-3 h-5 w-5 flex-shrink-0 text-gray-500" />
      ) : (
        <CheckIcon className="mr-3 h-5 w-5 flex-shrink-0 text-[#fb7a00]" />
      )}
      <div className="flex items-center gap-2">
        <span>{feature.text}</span>
        {feature.tooltip && (
          <BadgeTooltip content={feature.tooltip}>
            <CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
          </BadgeTooltip>
        )}
      </div>
    </div>
  );
};

// Segmented control component for Base/Plus/Premium selection
const PlanSelector = ({
  value,
  onChange,
}: {
  value: "base" | "plus" | "premium";
  onChange: (value: "base" | "plus" | "premium") => void;
}) => {
  return (
    <div className="mt-1 flex w-full rounded-lg border border-gray-200 p-1">
      <button
        className={cn(
          "flex-1 rounded-md px-3 py-1 text-sm transition-colors",
          value === "base"
            ? "bg-gray-300 text-foreground dark:bg-gray-600 dark:text-white"
            : "text-gray-600 hover:text-gray-900 dark:text-muted-foreground dark:hover:text-white",
        )}
        onClick={() => onChange("base")}
      >
        Base
      </button>
      <button
        className={cn(
          "flex-1 rounded-md px-3 py-1 text-sm transition-colors",
          value === "plus"
            ? "bg-gray-800 text-white dark:bg-gray-200 dark:text-gray-900"
            : "text-gray-600 hover:text-gray-900 dark:text-muted-foreground dark:hover:text-white",
        )}
        onClick={() => onChange("plus")}
      >
        Plus
      </button>
      <button
        className={cn(
          "flex-1 rounded-md px-3 py-1 text-sm transition-colors",
          value === "premium"
            ? "bg-gray-900 text-white dark:bg-gray-100 dark:text-gray-900"
            : "text-gray-600 hover:text-gray-900 dark:text-muted-foreground dark:hover:text-white",
        )}
        onClick={() => onChange("premium")}
      >
        Premium
      </button>
    </div>
  );
};

export function UpgradePlanModalWithDiscount({
  clickedPlan,
  trigger,
  open,
  setOpen,
  highlightItem,
  children,
}: {
  clickedPlan: PlanEnum;
  trigger?: string;
  open?: boolean;
  setOpen?: React.Dispatch<React.SetStateAction<boolean>>;
  highlightItem?: string[];
  children?: React.ReactNode;
}) {
  const router = useRouter();
  const [period, setPeriod] = useState<"yearly" | "monthly">("yearly");
  const [selectedPlan, setSelectedPlan] = useState<string | null>(null);
  const teamInfo = useTeam();
  const teamId = teamInfo?.currentTeam?.id;
  const {
    plan: teamPlan,
    isCustomer,
    isOldAccount,
    isTrial,
    isFree,
  } = usePlan();
  const analytics = useAnalytics();
  const [dataRoomsPlanSelection, setDataRoomsPlanSelection] = useState<
    "base" | "plus" | "premium"
  >("base");

  // Get next higher plan for current user
  const getNextHigherPlan = () => {
    if (isFree) return PlanEnum.Pro;
    if (teamPlan === "pro") return PlanEnum.Business;
    if (teamPlan === "business") return PlanEnum.DataRooms;
    if (teamPlan === "datarooms") return PlanEnum.DataRoomsPlus;
    if (teamPlan === "datarooms-plus") return PlanEnum.DataRoomsPremium;
    return null;
  };

  const nextHigherPlan = getNextHigherPlan();

  const plansToShow = useMemo(() => {
    switch (clickedPlan) {
      case PlanEnum.Pro:
        return [PlanEnum.Pro, PlanEnum.Business];
      case PlanEnum.Business:
        return [PlanEnum.Business, PlanEnum.DataRooms];
      case PlanEnum.DataRooms:
        return [PlanEnum.DataRooms, PlanEnum.DataRoomsPlus];
      case PlanEnum.DataRoomsPlus:
        return [PlanEnum.DataRoomsPlus, PlanEnum.DataRoomsPremium];
      case PlanEnum.DataRoomsPremium:
        return [PlanEnum.DataRoomsPlus, PlanEnum.DataRoomsPremium];
      default:
        return [PlanEnum.Pro, PlanEnum.Business];
    }
  }, [clickedPlan]);

  // Track analytics event when modal is opened
  useEffect(() => {
    if (open) {
      analytics.capture("Upgrade Button Clicked", {
        trigger: trigger,
        teamId,
      });
    } else {
      setDataRoomsPlanSelection("base");
    }
  }, [open, trigger]);

  const handleUpgradeClick = () => {
    analytics.capture("Upgrade Button Clicked", {
      trigger: trigger,
      teamId,
    });
  };

  // If button is present, clone it and add onClick handler
  const buttonChild = React.isValidElement<{
    onClick?: React.MouseEventHandler<HTMLButtonElement>;
  }>(children)
    ? React.cloneElement(children, { onClick: handleUpgradeClick })
    : children;

  // Calculate 30% discounted yearly price
  const getDiscountedYearlyPrice = (yearlyPrice: number) => {
    return Math.round(yearlyPrice * 0.7); // Round to whole number
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>{buttonChild}</DialogTrigger>
      <DialogContent
        mobileFullScreen
        className="max-h-[90vh] min-h-fit overflow-y-auto bg-white p-0 text-foreground dark:bg-gray-900"
        style={{
          width: "95vw",
          maxWidth: "1200px",
        }}
      >
        <div className="pt-10 sm:pt-0">
          <div className="flex flex-col lg:flex-row">
            {/* Left Sidebar - Discount Information */}
            <div className="flex h-full w-full flex-col border-b border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-900 lg:w-64 lg:border-b-0 lg:border-r">
              <div className="mb-2">
                <h2 className="text-sm font-bold uppercase text-[#fb7a00]">
                  SWITCH TO YEARLY
                </h2>
              </div>
              <p className="mb-6 text-2xl font-semibold text-gray-900 dark:text-white">
                Save <span className="font-bold text-[#fb7a00]">30%</span> on
                yearly plans
              </p>

              {/* Decorative elements - Holiday section - Centered vertically */}
              <div className="relative flex flex-1 flex-col items-center justify-center">
                <div className="mb-3 h-16 w-16 text-[#fb7a00] opacity-30">
                  <Sparkles className="h-full w-full" />
                </div>
                <div className="flex w-full items-center gap-2">
                  <div className="h-px flex-1 bg-[#fb7a00]"></div>
                  <p className="text-sm font-semibold text-[#fb7a00]">
                    NEW YEAR&apos;S
                  </p>
                  <div className="h-px flex-1 bg-[#fb7a00]"></div>
                </div>
                <p className="mt-2 text-xs text-gray-600 dark:text-gray-400">
                  New Year&apos;s offer
                </p>
                {/* <div className="absolute bottom-0 h-12 w-12 text-[#fb7a00] opacity-20">
                <Sparkles className="h-full w-full" />
              </div> */}
              </div>

              <p className="mt-6 text-center text-xs text-gray-500 dark:text-gray-400">
                Ends Jan 15 2026
              </p>
            </div>

            {/* Right Content - Plans */}
            <div className="flex-1 p-6">
              {/* Monthly/Yearly Toggle */}
              <div className="mb-6 flex items-center justify-center">
                <span className="mr-2 text-sm">
                  Monthly{" "}
                  {period === "monthly" && (
                    <span className="text-[#fb7a00]"></span>
                  )}
                </span>
                <Switch
                  checked={period === "yearly"}
                  onCheckedChange={() =>
                    setPeriod(period === "monthly" ? "yearly" : "monthly")
                  }
                />
                <span className="ml-2 text-sm">Annually</span>
              </div>

              <div className="isolate grid grid-cols-1 gap-4 overflow-hidden rounded-xl p-4 md:grid-cols-2">
                {plansToShow.map((planOption) => {
                  const isDataRoomsUpgrade = plansToShow.includes(
                    PlanEnum.DataRooms,
                  );

                  // Determine which plan to show based on selection for Data Rooms
                  let effectivePlan = planOption;
                  let displayPlanName = planOption;

                  if (planOption === PlanEnum.DataRooms && isDataRoomsUpgrade) {
                    if (dataRoomsPlanSelection === "plus") {
                      effectivePlan = PlanEnum.DataRoomsPlus;
                      displayPlanName = PlanEnum.DataRoomsPlus;
                    } else if (dataRoomsPlanSelection === "premium") {
                      effectivePlan = PlanEnum.DataRoomsPremium;
                      displayPlanName = PlanEnum.DataRoomsPremium;
                    }
                  }

                  const planFeatures = getPlanFeatures(effectivePlan, {
                    period,
                  });

                  const planData = PLANS.find(
                    (p) => p.name === displayPlanName,
                  );
                  const monthlyPrice = planData?.price.monthly.amount || 0;
                  const yearlyPrice = planData?.price.yearly.amount || 0;
                  const discountedYearlyPrice =
                    getDiscountedYearlyPrice(yearlyPrice);

                  // Determine if this plan should have orange styling
                  const isOrangePlan = isFree
                    ? displayPlanName === PlanEnum.Business ||
                      displayPlanName === PlanEnum.DataRoomsPlus
                    : displayPlanName === nextHigherPlan;

                  return (
                    <div
                      key={displayPlanName}
                      className={`relative flex flex-col rounded-lg border ${
                        isOrangePlan
                          ? "border-[#fb7a00]"
                          : "border-gray-200 dark:border-gray-700"
                      } bg-white p-6 shadow-sm dark:bg-gray-900`}
                    >
                      <div className="mb-4 border-b border-gray-200 pb-2 dark:border-gray-700">
                        <div className="flex items-center justify-between">
                          <h3 className="text-balance text-xl font-medium text-gray-900 dark:text-white">
                            {displayPlanName}
                          </h3>
                        </div>
                        {period === "yearly" &&
                          (() => {
                            const monthlyForYear = monthlyPrice * 12;
                            const yearlyWithDiscount = Math.round(
                              yearlyPrice * 12 * 0.7,
                            );
                            const savings = monthlyForYear - yearlyWithDiscount;
                            return savings > 0 ? (
                              <span className="absolute right-2 top-2 rounded bg-[#fb7a00]/10 px-2 py-1 text-xs font-medium text-[#fb7a00]">
                                Save €{savings}/year
                              </span>
                            ) : null;
                          })()}
                        {period === "monthly" && isOrangePlan && (
                          <span className="absolute right-2 top-2 rounded bg-[#fb7a00] px-2 py-1 text-xs text-white">
                            {displayPlanName === PlanEnum.Business &&
                              "Most popular"}
                            {displayPlanName === PlanEnum.DataRoomsPlus &&
                              "Best deal"}
                          </span>
                        )}
                      </div>

                      <div className="mb-2">
                        {period === "yearly" ? (
                          // Yearly: Show discounted price with crossed out original
                          <>
                            <div className="flex items-baseline gap-2">
                              <span className="text-balance text-4xl font-medium tabular-nums text-gray-900 dark:text-white">
                                €{discountedYearlyPrice}
                              </span>
                              <span className="text-xl text-gray-500 line-through">
                                €{yearlyPrice}
                              </span>
                            </div>
                            <span className="text-gray-500 dark:text-white/75">
                              /month, billed annually
                            </span>
                          </>
                        ) : (
                          // Monthly: Show regular monthly price (no discount)
                          <>
                            <div className="flex items-baseline gap-2">
                              <span className="text-balance text-4xl font-medium tabular-nums text-gray-900 dark:text-white">
                                €{monthlyPrice}
                              </span>
                            </div>
                            <span className="text-gray-500 dark:text-white/75">
                              /month
                            </span>
                          </>
                        )}
                      </div>

                      {planOption === PlanEnum.DataRooms &&
                        isDataRoomsUpgrade &&
                        !plansToShow.includes(PlanEnum.DataRoomsPlus) && (
                          <PlanSelector
                            value={dataRoomsPlanSelection}
                            onChange={setDataRoomsPlanSelection}
                          />
                        )}

                      <p className="mt-4 text-sm text-gray-600 dark:text-white">
                        {planFeatures.featureIntro}
                      </p>

                      <ul className="mb-6 mt-2 space-y-2 text-sm leading-6 text-gray-600 dark:text-gray-300">
                        {planFeatures.features.map((feature, i) => (
                          <li key={i}>
                            <FeatureItem
                              feature={{
                                ...feature,
                                isHighlighted: highlightItem?.includes(
                                  feature.id,
                                ),
                              }}
                            />
                          </li>
                        ))}
                      </ul>

                      <div className="mt-auto">
                        <Button
                          variant={isOrangePlan ? "default" : "outline"}
                          className={`w-full py-2 text-sm ${
                            isOrangePlan
                              ? "bg-[#fb7a00]/90 text-white hover:bg-[#fb7a00]"
                              : "bg-gray-800 text-white hover:bg-gray-900 hover:text-white dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"
                          }`}
                          loading={selectedPlan === planOption}
                          disabled={selectedPlan !== null}
                          onClick={() => {
                            const priceId = getPriceIdFromPlan({
                              planName: displayPlanName,
                              period,
                              isOld: isOldAccount,
                            });

                            setSelectedPlan(planOption);
                            // Apply 30% coupon only for yearly plans
                            // Uses same logic as retention flow: getCouponFromPlan() in API routes
                            const applyDiscount = period === "yearly";
                            if (isCustomer && teamPlan !== "free") {
                              // For existing customers: Apply coupon directly to subscription (same as retention flow)
                              fetch(`/api/teams/${teamId}/billing/manage`, {
                                method: "POST",
                                headers: {
                                  "Content-Type": "application/json",
                                },
                                body: JSON.stringify({
                                  priceId,
                                  upgradePlan: true,
                                  applyYearlyDiscount: applyDiscount, // Only true for yearly plans
                                }),
                              })
                                .then(async (res) => {
                                  if (!res.ok) {
                                    const errorData = await res
                                      .json()
                                      .catch(() => null);
                                    const errorMessage =
                                      errorData?.error ||
                                      errorData?.message ||
                                      res.statusText ||
                                      "Failed to upgrade plan";
                                    throw new Error(errorMessage);
                                  }
                                  const url = await res.json();
                                  router.push(url);
                                })
                                .catch((err) => {
                                  alert(err.message || err);
                                  setSelectedPlan(null);
                                });
                            } else {
                              // For new customers: Add coupon to Stripe checkout session
                              fetch(
                                `/api/teams/${teamId}/billing/upgrade?priceId=${priceId}${applyDiscount ? "&applyYearlyDiscount=true" : ""}`,
                                {
                                  method: "POST",
                                  headers: {
                                    "Content-Type": "application/json",
                                  },
                                },
                              )
                                .then(async (res) => {
                                  if (!res.ok) {
                                    const errorData = await res
                                      .json()
                                      .catch(() => null);
                                    const errorMessage =
                                      errorData?.error ||
                                      errorData?.message ||
                                      res.statusText ||
                                      "Failed to start checkout";
                                    throw new Error(errorMessage);
                                  }
                                  const data = await res.json();
                                  if (!data.url) {
                                    throw new Error(
                                      "Failed to start checkout",
                                    );
                                  }
                                  window.location.href = data.url;
                                })
                                .catch((err) => {
                                  alert(err.message || err);
                                  setSelectedPlan(null);
                                });
                            }
                          }}
                        >
                          {selectedPlan === planOption
                            ? "Redirecting to Stripe..."
                            : `Upgrade to ${displayPlanName} ${capitalize(period)}`}
                        </Button>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="mt-6 flex flex-col items-center text-center text-sm text-muted-foreground">
                All plans include unlimited visitors and page by page document
                analytics.
                <div className="flex items-center gap-2">
                  <Link
                    href="/settings/upgrade-holiday-offer"
                    className="underline underline-offset-4 hover:text-foreground"
                  >
                    See all plans
                  </Link>
                  {((teamPlan === "free" && !isTrial) ||
                    (teamPlan === "pro" && !isTrial)) && (
                    <>
                      <span>|</span>
                      <StartDataRoomTrialButton teamId={teamId} />
                    </>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}