Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: update currency
Marc Seitz203de72eb7dd
diff --git a/components/billing/add-seat-modal.tsx b/components/billing/add-seat-modal.tsxindex 38dab98b..1fa46f47 100644--- a/components/billing/add-seat-modal.tsx+++ b/components/billing/add-seat-modal.tsx@@ -181,7 +181,7 @@ export function AddSeatModal({{minQuantity > 1 && (<p className="mt-2 text-center text-sm text-muted-foreground">- Minimum quantity for {planName}: {minQuantity} users+ Your {planName} plan includes {minQuantity} seats</p>)}</div>@@ -191,7 +191,7 @@ export function AddSeatModal({{loading ? "Redirecting..." : "Proceed to checkout"}</Button><Link- href="/settings/upgrade"+ href="/settings/billing/upgrade"className="block w-full text-center text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground"onClick={() => setOpen(false)}>diff --git a/components/billing/plan-price.tsx b/components/billing/plan-price.tsxnew file mode 100644index 00000000..8c5d0f80--- /dev/null+++ b/components/billing/plan-price.tsx@@ -0,0 +1,115 @@+import {+ type Currency,+ CURRENCY_LABEL,+ CURRENCY_SYMBOL,+} from "@/ee/stripe/currency";++import { cn } from "@/lib/utils";++export type { Currency };++type Period = "monthly" | "yearly";++// Renders a plan's monthly price in the selected currency. Falls back to the+// EUR amount when no USD price is configured for the plan.+export const PlanPrice = ({+ amount,+ amountUsd,+ period,+ currency,+}: {+ amount: number;+ amountUsd?: number;+ period: Period;+ currency: Currency;+}) => {+ const useUsd = currency === "usd" && amountUsd != null;+ const value = useUsd ? amountUsd : amount;+ const symbol = useUsd ? CURRENCY_SYMBOL.usd : CURRENCY_SYMBOL.eur;++ return (+ <div className="mb-2 text-balance text-4xl font-medium tabular-nums text-gray-900 dark:text-white">+ {symbol}+ {value}+ <span className="text-base font-normal text-gray-500 dark:text-white/75">+ /month{period === "yearly" && ", billed annually"}+ </span>+ </div>+ );+};++type SegmentedOption<T extends string> = { value: T; label: string };++// Rounded-pill segmented switch shared by the currency and billing-period+// toggles so they stay visually consistent.+function SegmentedToggle<T extends string>({+ options,+ value,+ onChange,+}: {+ options: readonly SegmentedOption<T>[];+ value: T;+ onChange: (value: T) => void;+}) {+ return (+ <div className="inline-flex items-center rounded-full bg-gray-100 p-0.5 dark:bg-gray-800">+ {options.map((option) => {+ const isSelected = option.value === value;+ return (+ <button+ key={option.value}+ type="button"+ aria-pressed={isSelected}+ onClick={() => onChange(option.value)}+ className={cn(+ "rounded-full px-3 py-1 text-sm font-medium transition-colors",+ isSelected+ ? "bg-white text-gray-900 shadow-sm dark:bg-gray-100 dark:text-gray-900"+ : "text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white",+ )}+ >+ {option.label}+ </button>+ );+ })}+ </div>+ );+}++const CURRENCY_OPTIONS: readonly SegmentedOption<Currency>[] = [+ { value: "usd", label: CURRENCY_LABEL.usd },+ { value: "eur", label: CURRENCY_LABEL.eur },+];++export const CurrencyToggle = ({+ value,+ onChange,+}: {+ value: Currency;+ onChange: (currency: Currency) => void;+}) => (+ <SegmentedToggle<Currency>+ options={CURRENCY_OPTIONS}+ value={value}+ onChange={onChange}+ />+);++const PERIOD_OPTIONS: readonly SegmentedOption<Period>[] = [+ { value: "monthly", label: "Monthly" },+ { value: "yearly", label: "Annually" },+];++export const PeriodToggle = ({+ value,+ onChange,+}: {+ value: Period;+ onChange: (period: Period) => void;+}) => (+ <SegmentedToggle<Period>+ options={PERIOD_OPTIONS}+ value={value}+ onChange={onChange}+ />+);diff --git a/components/billing/unlimited-plan-modal.tsx b/components/billing/unlimited-plan-modal.tsxindex c805cd59..73e439d8 100644--- a/components/billing/unlimited-plan-modal.tsx+++ b/components/billing/unlimited-plan-modal.tsx@@ -1,11 +1,9 @@import Link from "next/link";-import { useRouter } from "next/router";import { useState } from "react";import React from "react";import { useTeam } from "@/context/team-context";-import { getStripe } from "@/ee/stripe/client";import { PlanEnum, getPlanFeatures } from "@/ee/stripe/constants";import { getPriceIdFromPlan } from "@/ee/stripe/functions/get-price-id-from-plan";import { PLANS } from "@/ee/stripe/utils";@@ -34,7 +32,6 @@ export function UnlimitedPlanModal({open?: boolean;setOpen?: React.Dispatch<React.SetStateAction<boolean>>;}) {- const router = useRouter();const [internalOpen, setInternalOpen] = useState(false);const [internalPeriod, setInternalPeriod] = useState<"yearly" | "monthly">(externalPeriod ?? "yearly",@@ -71,7 +68,7 @@ export function UnlimitedPlanModal({}).then(async (res) => {const url = await res.json();- router.push(url);+ window.location.href = url;}).catch((err) => {alert(err);@@ -84,9 +81,9 @@ export function UnlimitedPlanModal({}).then(async (res) => {const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (data.url) {+ window.location.href = data.url;+ }}).catch((err) => {alert(err);diff --git a/components/billing/upgrade-plan-container.tsx b/components/billing/upgrade-plan-container.tsxindex 01e9b306..39f82373 100644--- a/components/billing/upgrade-plan-container.tsx+++ b/components/billing/upgrade-plan-container.tsx@@ -5,28 +5,15 @@ import { useState } from "react";import { useTeam } from "@/context/team-context";import { CancellationModal } from "@/ee/features/billing/cancellation/components";import { PlanEnum } from "@/ee/stripe/constants";-import {- BanIcon,- CirclePauseIcon,- CreditCardIcon,- MoreVertical,- ReceiptTextIcon,-} from "lucide-react";+import { MoreVertical, SquareXIcon } from "lucide-react";import { toast } from "sonner";import { mutate } from "swr";import { useAnalytics } from "@/lib/analytics";import { usePlan } from "@/lib/swr/use-billing";+import Stripe from "@/components/shared/icons/stripe";import { Button } from "@/components/ui/button";-import {- Card,- CardContent,- CardDescription,- CardFooter,- CardHeader,- CardTitle,-} from "@/components/ui/card";import {DropdownMenu,DropdownMenuContent,@@ -50,16 +37,16 @@ export default function UpgradePlanContainer() {isDataroomsUnlimited,isPaused,isCancelled,- isCustomer,startsAt,endsAt,pauseStartsAt,- pauseEndsAt,discount,- mutate: mutatePlan,} = usePlan({ withDiscount: true });const analytics = useAnalytics();+ const goToUpgrade = () => router.push("/settings/billing/upgrade");+ const goToInvoices = () => router.push("/settings/billing/invoices");+const manageSubscription = async ({type,}: {@@ -73,6 +60,7 @@ export default function UpgradePlanContainer() {if (!currentTeamId) return;setLoading(true);+ const toastId = toast.loading("Redirecting to Stripe...");try {fetch(`/api/teams/${currentTeamId}/billing/manage`, {@@ -87,6 +75,9 @@ export default function UpgradePlanContainer() {router.push(url);}).catch((err) => {+ toast.error("Failed to open Stripe. Please try again.", {+ id: toastId,+ });throw err;}).finally(() => {@@ -94,7 +85,6 @@ export default function UpgradePlanContainer() {});} catch (error) {console.error(error);- } finally {setLoading(false);}};@@ -195,133 +185,146 @@ export default function UpgradePlanContainer() {return discountText;};+ const planTitle = isDataroomsUnlimited+ ? "Unlimited"+ : isDataroomsPremium+ ? "Premium"+ : isDataroomsPlus+ ? "Datarooms+"+ : plan.charAt(0).toUpperCase() + plan.slice(1);++ const BillingPortalItem = () => (+ <DropdownMenuItem+ onClick={() => manageSubscription({ type: "manage" })}+ disabled={loading}+ >+ <Stripe className="h-4 w-4 rounded-[3px]" />+ Open billing portal+ </DropdownMenuItem>+ );+const ButtonList = () => {if (isFree) {return (- <div className="flex items-center gap-3">- <UpgradeButton- text=""- customText="Upgrade"- clickedPlan={PlanEnum.Business}- trigger="upgrade_plan"- useModal={false}- onClick={() => router.push("/settings/upgrade")}- />- </div>+ <UpgradeButton+ text=""+ customText="Upgrade"+ clickedPlan={PlanEnum.Business}+ trigger="upgrade_plan"+ useModal={false}+ onClick={goToUpgrade}+ />);- } else if (isCancelled) {+ }++ if (isCancelled) {return (- <Button onClick={handleReactivateSubscription} loading={unpauseLoading}>- Reactivate subscription- </Button>+ <>+ <Button onClick={handleReactivateSubscription} loading={unpauseLoading}>+ Reactivate subscription+ </Button>+ <Button variant="outline" onClick={goToInvoices}>+ View invoices+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm" className="h-9 w-9 p-0">+ <MoreVertical className="h-4 w-4" />+ <span className="sr-only">More options</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <BillingPortalItem />+ </DropdownMenuContent>+ </DropdownMenu>+ </>);- } else {+ }++ if (isPaused) {return (- <div className="flex items-center gap-3">- {isPaused ? (- <>- <Button- onClick={handleUnpauseSubscription}- loading={unpauseLoading}- >- Unpause subscription+ <>+ <Button onClick={handleUnpauseSubscription} loading={unpauseLoading}>+ Unpause subscription+ </Button>+ <Button variant="outline" onClick={goToInvoices}>+ View invoices+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm" className="h-9 w-9 p-0">+ <MoreVertical className="h-4 w-4" />+ <span className="sr-only">More options</span></Button>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="outline" size="sm" className="h-9 w-9 p-0">- <MoreVertical className="h-4 w-4" />- <span className="sr-only">More options</span>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() => manageSubscription({ type: "cancellation" })}- className="text-red-500"- >- <BanIcon className="h-4 w-4" />- Cancel subscription- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </>- ) : (- <>- <Button- variant="outline"- onClick={() => setCancellationModalOpen(true)}+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <BillingPortalItem />+ <DropdownMenuItem+ onClick={() => manageSubscription({ type: "cancellation" })}+ disabled={loading}>+ <SquareXIcon className="h-4 w-4" />Cancel subscription- </Button>- <Button- variant="outline"- onClick={() =>- manageSubscription({ type: "subscription_update" })- }- loading={loading}- >- Change plan- </Button>-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="outline" size="sm" className="h-9 w-9 p-0">- <MoreVertical className="h-4 w-4" />- <span className="sr-only">More options</span>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() => manageSubscription({ type: "manage" })}- >- <CreditCardIcon className="h-4 w-4" />- Change billing information- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </>- )}- </div>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </>);}++ return (+ <>+ <Button onClick={goToUpgrade}>Manage plan</Button>+ <Button variant="outline" onClick={goToInvoices}>+ View invoices+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" size="sm" className="h-9 w-9 p-0">+ <MoreVertical className="h-4 w-4" />+ <span className="sr-only">More options</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <BillingPortalItem />+ <DropdownMenuItem onClick={() => setCancellationModalOpen(true)}>+ <SquareXIcon className="h-4 w-4" />+ Cancel subscription+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </>+ );};return (<>- <div className="rounded-lg">- <Card className="bg-transparent">- <CardHeader>- <CardTitle>- {isDataroomsUnlimited- ? "Unlimited"- : isDataroomsPremium- ? "Premium"- : isDataroomsPlus- ? "Datarooms+"- : plan.charAt(0).toUpperCase() + plan.slice(1)}{" "}- Plan- </CardTitle>+ <div className="rounded-lg border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">+ <div className="flex flex-col items-start justify-between gap-3 p-5 sm:flex-row sm:items-center sm:p-6">+ <div className="space-y-1">+ <h2 className="text-base font-semibold text-gray-900 dark:text-gray-100">+ {planTitle} Plan+ </h2>{!isCancelled && startsAt && endsAt && isBillingCycleCurrent() && (- <CardDescription>+ <p className="text-sm text-gray-500 dark:text-gray-400"><span className="font-medium text-foreground">Current billing cycle:{" "}</span>- <span className="text-foreground">- {new Date(startsAt).toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- })}- {" - "}- {new Date(endsAt).toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- })}- </span>- </CardDescription>+ {new Date(startsAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ {" - "}+ {new Date(endsAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ </p>)}{isPaused && pauseStartsAt && (- <CardDescription>+ <p className="text-sm text-gray-500 dark:text-gray-400"><span className="font-medium text-foreground">Subscription{" "}{new Date(pauseStartsAt) > new Date()@@ -329,42 +332,35 @@ export default function UpgradePlanContainer() {: "paused on"}:{" "}</span>- <span className="text-foreground">- {new Date(pauseStartsAt).toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- })}- </span>- </CardDescription>+ {new Date(pauseStartsAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ </p>)}{isCancelled && endsAt && (- <CardDescription>+ <p className="text-sm text-gray-500 dark:text-gray-400"><span className="font-medium text-foreground">Subscription cancels on:{" "}</span>- <span className="text-foreground">- {new Date(endsAt).toLocaleDateString("en-US", {- month: "short",- day: "numeric",- year: "numeric",- })}- </span>- </CardDescription>+ {new Date(endsAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ </p>)}{discount && discount.valid && getDiscountText() && (- <CardDescription>- <div className="inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20 dark:bg-green-400/10 dark:text-green-400 dark:ring-green-400/30">- 🎉 {getDiscountText()} applied- </div>- </CardDescription>+ <div className="inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20 dark:bg-green-400/10 dark:text-green-400 dark:ring-green-400/30">+ 🎉 {getDiscountText()} applied+ </div>)}- </CardHeader>- <CardContent></CardContent>- <CardFooter className="flex items-center justify-end rounded-b-lg border-t px-6 py-3">- <div className="shrink-0">{ButtonList()}</div>- </CardFooter>- </Card>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {ButtonList()}+ </div>+ </div></div><CancellationModaldiff --git a/components/billing/upgrade-plan-modal-old.tsx b/components/billing/upgrade-plan-modal-old.tsxindex 46997bc9..27bf2160 100644--- a/components/billing/upgrade-plan-modal-old.tsx+++ b/components/billing/upgrade-plan-modal-old.tsx@@ -4,7 +4,6 @@ import { useEffect, useMemo, useState } from "react";import React from "react";import { useTeam } from "@/context/team-context";-import { getStripe } from "@/ee/stripe/client";import { PLANS } from "@/ee/stripe/utils";import { CheckIcon } from "lucide-react";@@ -41,7 +40,7 @@ export function UpgradePlanModal({const [period, setPeriod] = useState<"yearly" | "monthly">("yearly");const [clicked, setClicked] = useState<boolean>(false);const teamInfo = useTeam();- const { plan: teamPlan, trial, isCustomer, isOldAccount } = usePlan();+ const { plan: teamPlan, trial, isCustomer } = usePlan();const analytics = useAnalytics();const isTrial = !!trial;@@ -263,9 +262,9 @@ export function UpgradePlanModal({).then(async (res) => {const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (data.url) {+ window.location.href = data.url;+ }}).catch((err) => {alert(err);diff --git a/components/billing/upgrade-plan-modal-with-discount.tsx b/components/billing/upgrade-plan-modal-with-discount.tsxindex fa33db19..e5c011f6 100644--- a/components/billing/upgrade-plan-modal-with-discount.tsx+++ b/components/billing/upgrade-plan-modal-with-discount.tsx@@ -5,7 +5,6 @@ import { useEffect, useMemo, useState } from "react";import React from "react";import { useTeam } from "@/context/team-context";-import { getStripe } from "@/ee/stripe/client";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";@@ -522,9 +521,12 @@ export function UpgradePlanModalWithDiscount({throw new Error(errorMessage);}const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (!data.url) {+ throw new Error(+ "Failed to start checkout",+ );+ }+ window.location.href = data.url;}).catch((err) => {alert(err.message || err);diff --git a/components/billing/upgrade-plan-modal.tsx b/components/billing/upgrade-plan-modal.tsxindex de841a74..4f5ed5b5 100644--- a/components/billing/upgrade-plan-modal.tsx+++ b/components/billing/upgrade-plan-modal.tsx@@ -5,7 +5,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import React from "react";import { useTeam } from "@/context/team-context";-import { getStripe } from "@/ee/stripe/client";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";@@ -13,12 +12,19 @@ import { CheckIcon, CircleHelpIcon, UserPlusIcon, XIcon } from "lucide-react";import { useAnalytics } from "@/lib/analytics";import { usePlan } from "@/lib/swr/use-billing";+import { useGeoCurrency } from "@/lib/swr/use-geo-currency";+import { useSubscriptionCurrency } from "@/lib/swr/use-subscription-currency";import { capitalize, cn } from "@/lib/utils";+import {+ type Currency,+ CurrencyToggle,+ PeriodToggle,+ PlanPrice,+} from "@/components/billing/plan-price";import { UnlimitedPlanModal } from "@/components/billing/unlimited-plan-modal";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogTrigger } from "@/components/ui/dialog";-import { Switch } from "@/components/ui/switch";import {BadgeTooltip,Tooltip,@@ -193,6 +199,17 @@ export function UpgradePlanModal({}) {const router = useRouter();const [period, setPeriod] = useState<"yearly" | "monthly">("yearly");+ const geoCurrency = useGeoCurrency();+ const { currency: subscriptionCurrency } = useSubscriptionCurrency();+ const [currencyOverride, setCurrencyOverride] = useState<Currency | null>(+ null,+ );+ // Existing customers are locked to the currency they already pay in (Stripe+ // subscriptions cannot mix currencies). Otherwise default to the visitor's+ // geo currency, with a manual toggle taking precedence.+ const currency: Currency =+ subscriptionCurrency ?? currencyOverride ?? geoCurrency ?? "eur";+ const isCurrencyLocked = subscriptionCurrency != null;const [selectedPlan, setSelectedPlan] = useState<string | null>(null);const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;@@ -306,6 +323,7 @@ export function UpgradePlanModal({<DialogTrigger asChild>{buttonChild}</DialogTrigger><DialogContentmobileFullScreen+ onOpenAutoFocus={(e) => e.preventDefault()}className="max-h-[90vh] min-h-fit overflow-hidden bg-gray-50 p-0 text-foreground dark:bg-gray-900"style={{width: "90vw",@@ -315,18 +333,21 @@ export function UpgradePlanModal({<div className="flex max-h-[95vh] flex-col max-sm:h-full max-sm:max-h-none">{/* Fixed header — billing period toggle stays visible while the cards scroll */}<div className="flex-none bg-gray-50 px-4 pb-5 pt-10 dark:bg-gray-900 sm:px-6 sm:pb-5 sm:pt-6">- <div className="flex items-center justify-center">- <span className="mr-2 text-sm">Monthly</span>- <Switch- checked={period === "yearly"}- onCheckedChange={() =>- setPeriod(period === "monthly" ? "yearly" : "monthly")- }- />- <span className="ml-2 text-sm">- Annually{" "}- <span className="text-[#fb7a00]">(Save up to 35%)</span>- </span>+ <div className="relative flex flex-col items-center gap-3 sm:block">+ {!isCurrencyLocked && (+ <div className="sm:absolute sm:left-0 sm:top-1/2 sm:-translate-y-1/2">+ <CurrencyToggle+ value={currency}+ onChange={setCurrencyOverride}+ />+ </div>+ )}+ <div className="flex items-center justify-center gap-2">+ <PeriodToggle value={period} onChange={setPeriod} />+ <span className="text-sm text-[#fb7a00]">+ (Save up to 35%)+ </span>+ </div></div></div>@@ -428,6 +449,7 @@ export function UpgradePlanModal({const planFeatures = getPlanFeatures(effectivePlan, {period,+ currency,highlightFeatures: highlightForSelector,});@@ -546,19 +568,20 @@ export function UpgradePlanModal({)}</div>- <div className="mb-2">- <span className="text-balance text-4xl font-medium tabular-nums text-gray-900 dark:text-white">- €- {- PLANS.find((p) => p.name === displayPlanName)?.price[- period- ].amount- }- </span>- <span className="text-gray-500 dark:text-white/75">- /month{period === "yearly" && ", billed annually"}- </span>- </div>+ <PlanPrice+ amount={+ PLANS.find((p) => p.name === displayPlanName)?.price[+ period+ ].amount ?? 0+ }+ amountUsd={+ PLANS.find((p) => p.name === displayPlanName)?.price[+ period+ ].amountUsd+ }+ period={period}+ currency={currency}+ />{planOption === PlanEnum.DataRooms &&isDataRoomsUpgrade &&@@ -740,7 +763,7 @@ export function UpgradePlanModal({fetch(`/api/teams/${teamId}/billing/upgrade?priceId=${priceId- }`,+ }¤cy=${currency}`,{method: "POST",headers: {@@ -750,9 +773,9 @@ export function UpgradePlanModal({).then(async (res) => {const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (data.url) {+ window.location.href = data.url;+ }}).catch((err) => {alert(err);@@ -784,7 +807,7 @@ export function UpgradePlanModal({</span>{" "}and page by page document analytics.{" "}<Link- href={`/settings/upgrade${+ href={`/settings/billing/upgrade${clickedPlan === PlanEnum.Pro? "?view=documents": clickedPlan === PlanEnum.Businessdiff --git a/components/billing/yearly-upgrade-banner.tsx b/components/billing/yearly-upgrade-banner.tsxindex 86a0591f..3f1908ff 100644--- a/components/billing/yearly-upgrade-banner.tsx+++ b/components/billing/yearly-upgrade-banner.tsx@@ -148,7 +148,7 @@ export default function YearlyUpgradeBanner({})()}<p- onClick={() => router.push("/settings/upgrade")}+ onClick={() => router.push("/settings/billing/upgrade")}className="mt-4 cursor-pointer text-center text-xs text-gray-500 underline hover:text-gray-600 dark:text-gray-400 dark:hover:text-gray-300">Compare all plansdiff --git a/components/document-upload.tsx b/components/document-upload.tsxindex f13682eb..9c14f177 100644--- a/components/document-upload.tsx+++ b/components/document-upload.tsx@@ -84,7 +84,7 @@ export default function DocumentUpload({description: "Upgrade to a paid plan to increase the limit",action: {label: "Upgrade",- onClick: () => router.push("/settings/upgrade"),+ onClick: () => router.push("/settings/billing/upgrade"),},duration: 10000,});@@ -128,7 +128,7 @@ export default function DocumentUpload({description: "Upgrade to a paid plan to increase the limit",action: {label: "Upgrade",- onClick: () => router.push("/settings/upgrade"),+ onClick: () => router.push("/settings/billing/upgrade"),},duration: 10000,});@@ -142,7 +142,7 @@ export default function DocumentUpload({description: `Upgrade to a paid plan to upload ${file.type} files`,action: {label: "Upgrade",- onClick: () => router.push("/settings/upgrade"),+ onClick: () => router.push("/settings/billing/upgrade"),},duration: 10000,});diff --git a/components/emails/custom-domain-setup.tsx b/components/emails/custom-domain-setup.tsxindex 8e6260d7..39710be1 100644--- a/components/emails/custom-domain-setup.tsx+++ b/components/emails/custom-domain-setup.tsx@@ -100,7 +100,7 @@ export default function CustomDomainSetup({) : (<ButtonclassName="rounded bg-black text-center text-xs font-semibold text-white no-underline"- href={`https://app.papermark.com/settings/upgrade`}+ href={`https://app.papermark.com/settings/billing/upgrade`}style={{ padding: "12px 20px" }}>Upgrade to use custom domains@@ -124,7 +124,7 @@ export default function CustomDomainSetup({<>Want to learn more about our plans?{" "}<Link- href="https://app.papermark.com/settings/upgrade"+ href="https://app.papermark.com/settings/billing/upgrade"className="font-medium text-blue-600 no-underline">View pricingdiff --git a/components/layouts/mobile-dataroom-more-menu.tsx b/components/layouts/mobile-dataroom-more-menu.tsxindex 95b5a932..e7f0fb7d 100644--- a/components/layouts/mobile-dataroom-more-menu.tsx+++ b/components/layouts/mobile-dataroom-more-menu.tsx@@ -338,7 +338,7 @@ export function MobileDataroomMoreMenu({{isTrial && (<div className="mt-4"><Link- href="/settings/upgrade?view=datarooms"+ href="/settings/billing/upgrade?view=datarooms"onClick={onClose}className="flex w-full items-center justify-center rounded-lg bg-foreground px-4 py-3 text-sm font-medium text-background transition-colors hover:bg-foreground/90">diff --git a/components/layouts/mobile-more-menu.tsx b/components/layouts/mobile-more-menu.tsxindex cfff0d76..a44cb200 100644--- a/components/layouts/mobile-more-menu.tsx+++ b/components/layouts/mobile-more-menu.tsx@@ -253,7 +253,7 @@ export function MobileMoreMenu({ open, onClose }: MobileMoreMenuProps) {{isTrial && (<div className="mt-4"><Link- href="/settings/upgrade?view=business-datarooms"+ href="/settings/billing/upgrade?view=business-datarooms"onClick={onClose}className="flex w-full items-center justify-center rounded-lg bg-foreground px-4 py-3 text-sm font-medium text-background transition-colors hover:bg-foreground/90">diff --git a/components/shared/icons/stripe.tsx b/components/shared/icons/stripe.tsxnew file mode 100644index 00000000..ff0cf22c--- /dev/null+++ b/components/shared/icons/stripe.tsx@@ -0,0 +1,27 @@+export default function Stripe({ className }: { className?: string }) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 512 512"+ fill="none"+ className={className}+ >+ <g clipPath="url(#stripe_clip)">+ <rect width="512" height="512" fill="#000000" />+ <path+ fillRule="evenodd"+ clipRule="evenodd"+ d="M120 392L392 334.317V120L120 178.357V392Z"+ fill="white"+ />+ </g>+ <defs>+ <clipPath id="stripe_clip">+ <rect width="512" height="512" rx="64" fill="white" />+ </clipPath>+ </defs>+ </svg>+ );+}diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsxindex 092cb4fa..2afe6cfb 100644--- a/components/sidebar/app-sidebar.tsx+++ b/components/sidebar/app-sidebar.tsx@@ -309,7 +309,7 @@ export function AppSidebarContent() {{linksLimit || documentsLimit ? (<p className="mt-2 px-2 text-xs text-muted-foreground"><Link- href="/settings/upgrade"+ href="/settings/billing/upgrade"className="font-medium text-foreground underline-offset-2 hover:underline">Change plandiff --git a/lib/api/rbac/guard.ts b/lib/api/rbac/guard.tsindex 68ead8a3..3351431c 100644--- a/lib/api/rbac/guard.ts+++ b/lib/api/rbac/guard.ts@@ -1,4 +1,5 @@import { NextApiResponse } from "next";+import { NextResponse } from "next/server";import prisma from "@/lib/prisma";@@ -9,6 +10,39 @@ import {} from "./entitlements";import { isDataroomScopedRole } from "./permissions";+/**+ * App-router variant of the team-level scope check. Billing routes are+ * team-level actions, so a dataroom-scoped member is denied outright. Returns a+ * 403 `NextResponse` when denied, or `null` when access is allowed.+ */+export async function denyDataroomScopedMember({+ userId,+ teamId,+ role,+}: {+ userId: string;+ teamId: string;+ role?: string;+}): Promise<NextResponse | null> {+ let resolvedRole = role;+ if (resolvedRole === undefined) {+ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });+ resolvedRole = membership?.role;+ }++ if (!resolvedRole || !isDataroomScopedRole(resolvedRole)) {+ return null;+ }++ return NextResponse.json(+ { error: "You do not have permission to perform this action." },+ { status: 403 },+ );+}+/*** Lightweight inline guard for team routes that have NOT yet been migrated to* the `withTeam` session wrapper. It enforces two invariants for thediff --git a/lib/swr/use-geo-currency.ts b/lib/swr/use-geo-currency.tsnew file mode 100644index 00000000..80c49394--- /dev/null+++ b/lib/swr/use-geo-currency.ts@@ -0,0 +1,21 @@+import useSWR from "swr";++import type { Currency } from "@/ee/stripe/currency";++import { fetcher } from "@/lib/utils";++// Resolves the visitor's default billing currency from their IP geolocation+// (EUR for European countries, USD otherwise). Returns `undefined` while+// loading so callers can fall back to a sensible default.+export function useGeoCurrency(): Currency | undefined {+ const { data } = useSWR<{ country: string | null; currency: Currency }>(+ "/api/geo/currency",+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateIfStale: false,+ dedupingInterval: 60 * 60 * 1000,+ },+ );+ return data?.currency;+}diff --git a/lib/swr/use-subscription-currency.ts b/lib/swr/use-subscription-currency.tsnew file mode 100644index 00000000..131eef95--- /dev/null+++ b/lib/swr/use-subscription-currency.ts@@ -0,0 +1,29 @@+import { useTeam } from "@/context/team-context";+import type { Currency } from "@/ee/stripe/currency";+import useSWR from "swr";++import { fetcher } from "@/lib/utils";++// Resolves the currency the team is already being billed in. Returns `null`+// when the team has no active subscription (so the upgrade UI can fall back to+// geo/manual selection), and `undefined` while loading. Existing customers are+// locked to this currency because Stripe subscriptions cannot mix currencies.+export function useSubscriptionCurrency(): {+ currency: Currency | null | undefined;+ loading: boolean;+} {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data, isLoading } = useSWR<{ currency: Currency | null }>(+ teamId ? `/api/teams/${teamId}/billing/currency` : null,+ fetcher,+ {+ revalidateOnFocus: false,+ revalidateIfStale: false,+ dedupingInterval: 60 * 60 * 1000,+ },+ );++ return { currency: data?.currency, loading: isLoading };+}diff --git a/lib/swr/use-teams.ts b/lib/swr/use-teams.tsindex 20e17e8c..4b95b0f1 100644--- a/lib/swr/use-teams.ts+++ b/lib/swr/use-teams.ts@@ -1,5 +1,3 @@-import { useRouter } from "next/router";-import { useSession } from "next-auth/react";import useSWR from "swr";@@ -7,11 +5,10 @@ import { Team } from "@/lib/types";import { fetcher } from "@/lib/utils";export function useTeams() {- const router = useRouter();const { data: session } = useSession();const { data: teams, isValidating } = useSWR<Team[]>(- router.isReady && session ? "/api/teams" : null,+ session ? "/api/teams" : null,fetcher,{dedupingInterval: 20000,@@ -22,7 +19,7 @@ export function useTeams() {return {teams,- loading: !teams && router.isReady && !!session,+ loading: !teams && !!session,isValidating,};}diff --git a/next.config.mjs b/next.config.mjsindex d1afefe5..9bd5a002 100644--- a/next.config.mjs+++ b/next.config.mjs@@ -162,6 +162,13 @@ const nextConfig = {destination: "/settings/general",permanent: false,},+ {+ // The plan picker moved to /settings/billing/upgrade (App Router).+ // Keep the old path working for bookmarks and previously sent emails.+ source: "/settings/upgrade",+ destination: "/settings/billing/upgrade",+ permanent: false,+ },{source: "/:path*",destination: "https://presentation.atelierbatalla.com/:path*",@@ -337,7 +344,9 @@ const nextConfig = {// oidc-provider uses Koa which has dynamic requires that webpack can't// statically analyze. Keep them out of the bundle; they'll be loaded at// runtime from node_modules.- serverComponentsExternalPackages: ["oidc-provider", "koa"],+ // jsonpath (a dub dependency) reads its grammar file from disk at module+ // load, which breaks when webpack bundles it into app-router routes.+ serverComponentsExternalPackages: ["oidc-provider", "koa", "jsonpath"],},webpack: (config, { isServer }) => {// oidc-provider depends on Koa which uses dynamic requires webpack can'tdiff --git a/package-lock.json b/package-lock.jsonindex 385d86e8..bc67382f 100644--- a/package-lock.json+++ b/package-lock.json@@ -58,7 +58,7 @@"@radix-ui/react-tooltip": "^1.2.8","@radix-ui/react-use-controllable-state": "^1.2.2","@sindresorhus/slugify": "^3.0.0",- "@stripe/stripe-js": "^4.10.0",+ "@stripe/stripe-js": "^9.8.0","@tailwindcss/typography": "^0.5.19","@tanstack/react-table": "^8.21.3","@teamhanko/passkeys-next-auth-provider": "^0.3.1",@@ -145,7 +145,7 @@"shiki": "^3.23.0","sonner": "^2.0.7","streamdown": "^2.5.0",- "stripe": "^16.12.0",+ "stripe": "^22.3.0","swr": "^2.4.1","tailwind-merge": "^2.6.1","tailwind-scrollbar-hide": "^2.0.0",@@ -8586,7 +8586,9 @@"license": "MIT"},"node_modules/@stripe/stripe-js": {- "version": "4.10.0",+ "version": "9.8.0",+ "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-9.8.0.tgz",+ "integrity": "sha512-DHJpol/98VKyojNSYmpkB5vOMnlf87hPe0wPxyaYTNiTMk5QjKMXDfSZLwGctYIXAgAWDFeRABc8lFAj0BELyw==","license": "MIT","engines": {"node": ">=12.16"@@ -23361,14 +23363,20 @@}},"node_modules/stripe": {- "version": "16.12.0",+ "version": "22.3.0",+ "resolved": "https://registry.npmjs.org/stripe/-/stripe-22.3.0.tgz",+ "integrity": "sha512-ypO6xjVrMWs9SmIMeHr8naCx3dAQ0clxMdUTxn7Ejd7hmY9meBGfE+N4pVHkf9sUNebAHp6uJo6mV3GxDIc2cA==","license": "MIT",- "dependencies": {- "@types/node": ">=8.1.0",- "qs": "^6.11.0"- },"engines": {- "node": ">=12.*"+ "node": ">=18"+ },+ "peerDependencies": {+ "@types/node": ">=18"+ },+ "peerDependenciesMeta": {+ "@types/node": {+ "optional": true+ }}},"node_modules/strnum": {diff --git a/package.json b/package.jsonindex 92441604..1a20de6e 100644--- a/package.json+++ b/package.json@@ -70,7 +70,7 @@"@radix-ui/react-tooltip": "^1.2.8","@radix-ui/react-use-controllable-state": "^1.2.2","@sindresorhus/slugify": "^3.0.0",- "@stripe/stripe-js": "^4.10.0",+ "@stripe/stripe-js": "^9.8.0","@tailwindcss/typography": "^0.5.19","@tanstack/react-table": "^8.21.3","@teamhanko/passkeys-next-auth-provider": "^0.3.1",@@ -157,7 +157,7 @@"shiki": "^3.23.0","sonner": "^2.0.7","streamdown": "^2.5.0",- "stripe": "^16.12.0",+ "stripe": "^22.3.0","swr": "^2.4.1","tailwind-merge": "^2.6.1","tailwind-scrollbar-hide": "^2.0.0",diff --git a/pages/api/stripe/webhook-old.ts b/pages/api/stripe/webhook-old.tsdeleted file mode 100644index f29aa47f..00000000--- a/pages/api/stripe/webhook-old.ts+++ /dev/null@@ -1,87 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { stripeInstance } from "@/ee/stripe";-import { checkoutSessionCompleted } from "@/ee/stripe/webhooks/checkout-session-completed";-import { customerSubscriptionDeleted } from "@/ee/stripe/webhooks/customer-subscription-deleted";-import { customerSubsciptionUpdated } from "@/ee/stripe/webhooks/customer-subscription-updated";-import { invoiceUpcoming } from "@/ee/stripe/webhooks/invoice-upcoming";-import { Readable } from "node:stream";-import type Stripe from "stripe";--import { log } from "@/lib/utils";--// Stripe requires the raw body to construct the event.-export const config = {- api: {- bodyParser: false,- },-};--async function buffer(readable: Readable) {- const chunks: Buffer[] = [];- for await (const chunk of readable) {- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);- }- return Buffer.concat(chunks);-}--const relevantEvents = new Set([- "checkout.session.completed",- "customer.subscription.updated",- "customer.subscription.deleted",-]);--export default async function webhookHandler(- req: NextApiRequest,- res: NextApiResponse,-) {- // POST /api/stripe/webhook-old – listen to Stripe webhooks- if (req.method === "POST") {- const buf = await buffer(req);- const sig = req.headers["stripe-signature"];- const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET_OLD;- let event: Stripe.Event;- try {- if (!sig || !webhookSecret) return;- const stripe = stripeInstance(true);- event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);- } catch (err: any) {- return res.status(400).send(`Webhook Error: ${err.message}`);- }-- // Ignore unsupported events- if (!relevantEvents.has(event.type)) {- return res.status(400).send(`Unhandled event type: ${event.type}`);- }-- try {- switch (event.type) {- case "checkout.session.completed":- await checkoutSessionCompleted(event, true);- break;- case "customer.subscription.updated":- await customerSubsciptionUpdated(event, res, true);- break;- case "customer.subscription.deleted":- await customerSubscriptionDeleted(event, res);- break;- case "invoice.upcoming":- await invoiceUpcoming(event, res, true);- break;- }- } catch (error) {- await log({- message: `Stripe webhook failed. Error: ${error}`,- type: "error",- });- return res- .status(400)- .send("Webhook error: Webhook handler failed. View logs.");- }-- return res.status(200).json({ received: true });- } else {- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsdeleted file mode 100644index d681fa7a..00000000--- a/pages/api/stripe/webhook.ts+++ /dev/null@@ -1,95 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { processPaymentFailure } from "@/ee/features/security";-import { stripeInstance } from "@/ee/stripe";-import { checkoutSessionCompleted } from "@/ee/stripe/webhooks/checkout-session-completed";-import { customerSubscriptionDeleted } from "@/ee/stripe/webhooks/customer-subscription-deleted";-import { customerSubsciptionUpdated } from "@/ee/stripe/webhooks/customer-subscription-updated";-import { invoiceUpcoming } from "@/ee/stripe/webhooks/invoice-upcoming";-import { Readable } from "node:stream";-import type Stripe from "stripe";--import { log } from "@/lib/utils";--// Stripe requires the raw body to construct the event.-// add supportsResponseStreaming to enable waitUntil-export const config = {- supportsResponseStreaming: true,- api: {- bodyParser: false,- },-};--async function buffer(readable: Readable) {- const chunks: Buffer[] = [];- for await (const chunk of readable) {- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);- }- return Buffer.concat(chunks);-}--const relevantEvents = new Set([- "checkout.session.completed",- "customer.subscription.updated",- "customer.subscription.deleted",- "payment_intent.payment_failed",- "invoice.upcoming",-]);--export default async function webhookHandler(- req: NextApiRequest,- res: NextApiResponse,-) {- // POST /api/stripe/webhook – listen to Stripe webhooks- if (req.method === "POST") {- const buf = await buffer(req);- const sig = req.headers["stripe-signature"];- const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;- let event: Stripe.Event;- try {- if (!sig || !webhookSecret) return;- const stripe = stripeInstance();- event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);- } catch (err: any) {- return res.status(400).send(`Webhook Error: ${err.message}`);- }-- // Ignore unsupported events- if (!relevantEvents.has(event.type)) {- return res.status(400).send(`Unhandled event type: ${event.type}`);- }-- try {- switch (event.type) {- case "checkout.session.completed":- await checkoutSessionCompleted(event);- break;- case "customer.subscription.updated":- await customerSubsciptionUpdated(event, res);- break;- case "customer.subscription.deleted":- await customerSubscriptionDeleted(event, res);- break;- case "payment_intent.payment_failed":- await processPaymentFailure(event);- break;- case "invoice.upcoming":- await invoiceUpcoming(event, res);- break;- }- } catch (error) {- await log({- message: `Stripe webhook failed. Error: ${error}`,- type: "error",- });- return res- .status(400)- .send("Webhook error: Webhook handler failed. View logs.");- }-- return res.status(200).json({ received: true });- } else {- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}diff --git a/pages/api/teams/[teamId]/billing/cancel.ts b/pages/api/teams/[teamId]/billing/cancel.tsdeleted file mode 100644index 02b4482b..00000000--- a/pages/api/teams/[teamId]/billing/cancel.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { handleRoute } from "@/ee/features/billing/cancellation/api/cancel-route";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- return handleRoute(req, res);-}diff --git a/pages/api/teams/[teamId]/billing/cancellation-feedback.ts b/pages/api/teams/[teamId]/billing/cancellation-feedback.tsdeleted file mode 100644index 0deaeffc..00000000--- a/pages/api/teams/[teamId]/billing/cancellation-feedback.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { handleRoute } from "@/ee/features/billing/cancellation/api/cancellation-feedback-route";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- return handleRoute(req, res);-}diff --git a/pages/api/teams/[teamId]/billing/invoices.ts b/pages/api/teams/[teamId]/billing/invoices.tsdeleted file mode 100644index 51a63724..00000000--- a/pages/api/teams/[teamId]/billing/invoices.ts+++ /dev/null@@ -1,90 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { stripeInstance } from "@/ee/stripe";-import { authOptions } from "@/pages/api/auth/[...nextauth]";-import { getServerSession } from "next-auth/next";--import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";-import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";--function isOldAccount(plan: string) {- return plan.includes("+old");-}--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method !== "GET") {- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const userId = (session.user as CustomUser).id;- const { teamId } = req.query as { teamId: string };-- // Billing is a team-level action: dataroom-scoped members cannot view invoices.- if (await enforceDataroomMemberScope({ userId, teamId, res })) {- return;- }-- try {- // Get team with stripeId- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- select: {- stripeId: true,- plan: true,- },- });-- if (!team) {- return res.status(404).json({ error: "Team not found" });- }-- if (!team.stripeId) {- return res.status(200).json({ invoices: [] });- }-- // Fetch invoices from Stripe- const stripe = stripeInstance(isOldAccount(team.plan));- const invoices = await stripe.invoices.list({- customer: team.stripeId,- limit: 100,- });-- // Transform invoices to a simpler format- const transformedInvoices = invoices.data.map((invoice) => ({- id: invoice.id,- number: invoice.number,- status: invoice.status,- amount: invoice.amount_paid,- currency: invoice.currency,- created: invoice.created,- invoicePdf: invoice.invoice_pdf,- hostedInvoiceUrl: invoice.hosted_invoice_url,- periodStart: invoice.period_start,- periodEnd: invoice.period_end,- description: invoice.lines.data[0]?.description || "Subscription",- }));-- return res.status(200).json({ invoices: transformedInvoices });- } catch (error) {- console.error("Error fetching invoices:", error);- return res.status(500).json({ error: "Failed to fetch invoices" });- }-}-diff --git a/pages/api/teams/[teamId]/billing/manage.ts b/pages/api/teams/[teamId]/billing/manage.tsdeleted file mode 100644index 19a57b48..00000000--- a/pages/api/teams/[teamId]/billing/manage.ts+++ /dev/null@@ -1,221 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { stripeInstance } from "@/ee/stripe";-import { getCouponFromPlan } from "@/ee/stripe/functions/get-coupon-from-plan";-import { getQuantityFromPriceId } from "@/ee/stripe/functions/get-quantity-from-plan";-import getSubscriptionItem from "@/ee/stripe/functions/get-subscription-item";-import { getPlanFromPriceId, isOldAccount } from "@/ee/stripe/utils";-import { waitUntil } from "@vercel/functions";-import { getServerSession } from "next-auth/next";--import { identifyUser, trackAnalytics } from "@/lib/analytics";-import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";-import { errorhandler } from "@/lib/errorHandler";-import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";--import { authOptions } from "../../../auth/[...nextauth]";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "POST") {- // POST /api/teams/:teamId/billing/manage – manage a user's subscription- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }-- const userId = (session.user as CustomUser).id;- const userEmail = (session.user as CustomUser).email;-- const { teamId } = req.query as { teamId: string };-- // Billing management is a team-level action: dataroom-scoped members are- // denied (they cannot upgrade plans or otherwise manage billing).- if (await enforceDataroomMemberScope({ userId, teamId, res })) {- return;- }-- const {- priceId,- upgradePlan,- quantity,- addSeat,- proAnnualBanner,- return_url,- applyYearlyDiscount,- type = "manage",- } = req.body as {- priceId: string;- upgradePlan: boolean;- quantity?: number;- addSeat?: boolean;- proAnnualBanner?: boolean;- return_url?: string;- applyYearlyDiscount?: boolean;- type?:- | "manage"- | "invoices"- | "subscription_update"- | "payment_method_update"- | "cancellation";- };- try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- select: {- stripeId: true,- subscriptionId: true,- plan: true,- },- });-- if (!team) {- return res.status(400).json({ error: "Team does not exists" });- }- if (!team.stripeId) {- return res.status(400).json({ error: "No Stripe customer ID" });- }-- if (!team.subscriptionId) {- return res.status(400).json({ error: "No subscription ID" });- }-- const {- id: subscriptionItemId,- currentPeriodStart,- currentPeriodEnd,- } = await getSubscriptionItem(- team.subscriptionId,- isOldAccount(team.plan),- );-- const minQuantity = getQuantityFromPriceId(priceId);- const plan = getPlanFromPriceId(priceId, isOldAccount(team.plan));- const isUnlimitedPlan = plan?.slug === "datarooms-unlimited";-- const stripe = stripeInstance(isOldAccount(team.plan));-- // Apply 30% discount for yearly plans before redirecting to billing portal- // Same logic as retention flow: apply coupon directly to subscription- if (applyYearlyDiscount && upgradePlan) {- const plan = getPlanFromPriceId(priceId, isOldAccount(team.plan));- if (plan) {- // Use the same logic as retention flow: getCouponFromPlan(team.plan, isAnnualPlan)- // team.plan format is "pro", "business", "pro+old", "business+old", etc.- const planString = `${plan.slug}${isOldAccount(team.plan) ? "+old" : ""}`;- const couponId = getCouponFromPlan(planString, true);-- // Verify coupon exists before applying (coupons might only exist in production, not test mode)- try {- await stripe.coupons.retrieve(couponId);- // Apply discount directly to subscription (same as retention flow)- await stripe.subscriptions.update(team.subscriptionId, {- discounts: [{ coupon: couponId }],- });- } catch (error: any) {- // If coupon doesn't exist (common in test mode), log and skip- if (error.code === "resource_missing") {- console.warn(- `[Manage] Coupon "${couponId}" not found in ${process.env.NEXT_PUBLIC_VERCEL_ENV || "test"} mode. ` +- `Skipping discount application. This is expected if the coupon only exists in production.`,- );- } else {- // Re-throw other errors- throw error;- }- }- }- }-- const { url } = await stripe.billingPortal.sessions.create({- customer: team.stripeId,- return_url: `${process.env.NEXTAUTH_URL}/settings/billing?cancel=true`,- ...(type === "manage" &&- (upgradePlan || addSeat) &&- subscriptionItemId && {- flow_data: {- type: "subscription_update_confirm",- subscription_update_confirm: {- subscription: team.subscriptionId,- items: [- {- id: subscriptionItemId,- quantity: isUnlimitedPlan- ? 1- : isOldAccount(team.plan)- ? 1- : (quantity ?? minQuantity),- price: priceId,- },- ],- },- after_completion: {- type: "redirect",- redirect: {- return_url:- return_url ??- `${process.env.NEXTAUTH_URL}/settings/billing?success=true`,- },- },- },- }),- ...(type === "subscription_update" && {- flow_data: {- type: "subscription_update",- subscription_update: {- subscription: team.subscriptionId,- },- },- }),- ...(type === "cancellation" && {- flow_data: {- type: "subscription_cancel",- subscription_cancel: {- subscription: team.subscriptionId,- },- after_completion: {- type: "redirect",- redirect: {- return_url:- return_url ??- `${process.env.NEXTAUTH_URL}/settings/billing?cancellation=true`,- },- },- },- }),- });-- waitUntil(identifyUser(userEmail ?? userId));- waitUntil(- trackAnalytics({- event: "Stripe Billing Portal Clicked",- teamId,- action: proAnnualBanner ? "pro-annual-banner" : undefined,- }),- );-- return res.status(200).json(url);- } catch (error) {- errorhandler(error, res);- }- } else {- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}diff --git a/pages/api/teams/[teamId]/billing/pause.ts b/pages/api/teams/[teamId]/billing/pause.tsdeleted file mode 100644index 2062819c..00000000--- a/pages/api/teams/[teamId]/billing/pause.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { handleRoute } from "@/ee/features/billing/cancellation/api/pause-route";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- return handleRoute(req, res);-}diff --git a/pages/api/teams/[teamId]/billing/plan.ts b/pages/api/teams/[teamId]/billing/plan.tsdeleted file mode 100644index f2643fe2..00000000--- a/pages/api/teams/[teamId]/billing/plan.ts+++ /dev/null@@ -1,118 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { isTeamPaused } from "@/ee/features/billing/cancellation/lib/is-team-paused";-import getSubscriptionItem, {- SubscriptionDiscount,-} from "@/ee/stripe/functions/get-subscription-item";-import { isOldAccount } from "@/ee/stripe/utils";-import { getServerSession } from "next-auth/next";--import { errorhandler } from "@/lib/errorHandler";-import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";--import { authOptions } from "../../../auth/[...nextauth]";--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "GET") {- // GET /api/teams/:teamId/billing/plan- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const { teamId } = req.query as { teamId: string };- const userId = (session.user as CustomUser).id;- const withDiscount = req.query.withDiscount === "true";-- try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- select: {- plan: true,- stripeId: true,- subscriptionId: true,- startsAt: true,- endsAt: true,- pausedAt: true,- pauseStartsAt: true,- pauseEndsAt: true,- cancelledAt: true,- trialEndsAt: true,- },- });-- if (!team) {- return res.status(404).json({ error: "Team not found" });- }-- const isCustomer = !!team.stripeId;-- // calculate the plan cycle either yearly or monthly based on the startsAt and endsAt dates- let subscriptionCycle = "monthly";- if (team?.startsAt && team?.endsAt) {- const durationInDays = Math.round(- (team.endsAt.getTime() - team.startsAt.getTime()) /- (1000 * 60 * 60 * 24),- );- // If duration is more than 31 days, consider it yearly- subscriptionCycle = durationInDays > 31 ? "yearly" : "monthly";- }-- // Fetch discount information if team has an active subscription- let discount: SubscriptionDiscount | null = null;- if (- withDiscount &&- team?.subscriptionId &&- team.plan &&- team.plan !== "free" &&- team.pauseStartsAt === null- ) {- try {- const subscriptionData = await getSubscriptionItem(- team.subscriptionId,- isOldAccount(team.plan),- );- discount = subscriptionData.discount;- } catch (error) {- // If we can't fetch discount info, just log and continue without it- console.error("Failed to fetch discount information:", error);- }- }-- // Calculate if team is currently paused- const isPaused = isTeamPaused(team);-- return res.status(200).json({- plan: team.plan,- startsAt: team.startsAt,- endsAt: team.endsAt,- isCustomer,- subscriptionCycle,- pausedAt: team.pausedAt,- pauseStartsAt: team.pauseStartsAt,- pauseEndsAt: team.pauseEndsAt,- isPaused,- cancelledAt: team.cancelledAt,- trialEndsAt: team.trialEndsAt,- discount,- });- } catch (error) {- errorhandler(error, res);- }- } else {- // We only allow GET and POST requests- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}diff --git a/pages/api/teams/[teamId]/billing/reactivate.ts b/pages/api/teams/[teamId]/billing/reactivate.tsdeleted file mode 100644index 4e7afed7..00000000--- a/pages/api/teams/[teamId]/billing/reactivate.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { handleRoute } from "@/ee/features/billing/cancellation/api/reactivate-route";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- return handleRoute(req, res);-}diff --git a/pages/api/teams/[teamId]/billing/retention-offer.ts b/pages/api/teams/[teamId]/billing/retention-offer.tsdeleted file mode 100644index 92982139..00000000--- a/pages/api/teams/[teamId]/billing/retention-offer.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { handleRoute } from "@/ee/features/billing/cancellation/api/retention-route";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- return handleRoute(req, res);-}diff --git a/pages/api/teams/[teamId]/billing/unpause.ts b/pages/api/teams/[teamId]/billing/unpause.tsdeleted file mode 100644index bd825aea..00000000--- a/pages/api/teams/[teamId]/billing/unpause.ts+++ /dev/null@@ -1,15 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { handleRoute } from "@/ee/features/billing/cancellation/api/unpause-route";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- return handleRoute(req, res);-}diff --git a/pages/api/teams/[teamId]/billing/upgrade.ts b/pages/api/teams/[teamId]/billing/upgrade.tsdeleted file mode 100644index 9355b94e..00000000--- a/pages/api/teams/[teamId]/billing/upgrade.ts+++ /dev/null@@ -1,193 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { checkRateLimit, rateLimiters } from "@/ee/features/security";-import { stripeInstance } from "@/ee/stripe";-import { getCouponFromPlan } from "@/ee/stripe/functions/get-coupon-from-plan";-import { getPlanFromPriceId, isOldAccount } from "@/ee/stripe/utils";-import { waitUntil } from "@vercel/functions";-import { getServerSession } from "next-auth/next";--import { identifyUser, trackAnalytics } from "@/lib/analytics";-import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";-import { getDubDiscountForExternalUserId } from "@/lib/dub";-import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";-import { getIpAddress } from "@/lib/utils/ip";--import { authOptions } from "../../../auth/[...nextauth]";--export const config = {- // in order to enable `waitUntil` function- supportsResponseStreaming: true,-};--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "POST") {- // Apply rate limiting- const clientIP = getIpAddress(req.headers);- const rateLimitResult = await checkRateLimit(- rateLimiters.billing,- clientIP,- );-- if (!rateLimitResult.success) {- return res.status(429).json({- error: "Too many billing requests. Please try again later.",- remaining: rateLimitResult.remaining,- });- }-- // POST /api/teams/:teamId/billing/upgrade- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }-- const { teamId, priceId, applyYearlyDiscount } = req.query as {- teamId: string;- priceId: string;- applyYearlyDiscount?: string;- };-- const { id: userId, email: userEmail } = session.user as CustomUser;-- // Billing is a team-level action: dataroom-scoped members cannot upgrade.- if (await enforceDataroomMemberScope({ userId, teamId, res })) {- return;- }-- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId,- },- },- },- select: { stripeId: true, plan: true },- });-- if (!team) {- res.status(404).end("Unauthorized");- return;- }-- const oldAccount = isOldAccount(team.plan);- const plan = getPlanFromPriceId(priceId, oldAccount);-- if (!plan) {- res.status(400).json({ error: "Invalid price ID" });- return;- }-- const minimumQuantity = plan.minQuantity;-- let stripeSession;- let couponId: string | undefined;-- // Apply 30% coupon for yearly plans if requested (same as retention flow)- // Since the upgrade modal is yearly-only, if applyYearlyDiscount is true, always apply- if (applyYearlyDiscount === "true") {- // Use the same logic as retention flow: getCouponFromPlan(team.plan, isAnnualPlan)- // team.plan format is "pro", "business", "pro+old", "business+old", etc.- const planString = oldAccount ? `${plan.slug}+old` : plan.slug;- couponId = getCouponFromPlan(planString, true);-- // Verify coupon exists in Stripe (coupons might only exist in production, not test mode)- const stripe = stripeInstance(oldAccount);- try {- await stripe.coupons.retrieve(couponId);- } catch (error: any) {- // If coupon doesn't exist (common in test mode), continue without discount- if (error.code === "resource_missing") {- console.warn(- `[Upgrade] Coupon "${couponId}" not found in ${process.env.NEXT_PUBLIC_VERCEL_ENV || "test"} mode. ` +- `Continuing without discount. This is expected if the coupon only exists in production.`,- );- couponId = undefined;- } else {- // Re-throw other errors- throw error;- }- }- }-- const isUnlimitedPlan = plan.slug === "datarooms-unlimited";-- const lineItem = {- price: priceId,- quantity: isUnlimitedPlan ? 1 : oldAccount ? 1 : minimumQuantity,- ...(!oldAccount &&- !isUnlimitedPlan && {- adjustable_quantity: {- enabled: true,- minimum: minimumQuantity,- maximum: 99,- },- }),- };-- const dubDiscount = await getDubDiscountForExternalUserId(userId);-- const stripe = stripeInstance(oldAccount);- const baseSessionConfig = {- billing_address_collection: "required" as const,- success_url: `${process.env.NEXTAUTH_URL}/settings/billing?success=true`,- cancel_url: `${process.env.NEXTAUTH_URL}/settings/billing?cancel=true`,- line_items: [lineItem],- automatic_tax: {- enabled: true,- },- tax_id_collection: {- enabled: true,- },- mode: "subscription" as const,- client_reference_id: teamId,- ...(couponId && {- discounts: [{ coupon: couponId }],- }),- };-- if (team.stripeId) {- // if the team already has a stripeId (i.e. is a customer) let's use as a customer- stripeSession = await stripe.checkout.sessions.create({- ...baseSessionConfig,- customer: team.stripeId,- customer_update: { name: "auto" },- ...(!couponId && { allow_promotion_codes: true }),- });- } else {- // else initialize a new customer- stripeSession = await stripe.checkout.sessions.create({- ...baseSessionConfig,- customer_email: userEmail ?? undefined,- ...(dubDiscount ?? (!couponId && { allow_promotion_codes: true })),- metadata: {- dubCustomerId: userId,- },- });- }-- waitUntil(- Promise.all([- identifyUser(userEmail ?? userId),- trackAnalytics({- event: "Stripe Checkout Clicked",- teamId,- priceId: priceId,- }),- ]),- );-- return res.status(200).json(stripeSession);- } else {- // We only allow POST requests- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}diff --git a/pages/settings/billing.tsx b/pages/settings/billing.tsxindex 9e5a44a9..41742f23 100644--- a/pages/settings/billing.tsx+++ b/pages/settings/billing.tsx@@ -13,7 +13,6 @@ import UpgradePlanContainer from "@/components/billing/upgrade-plan-container";import { GTMComponent } from "@/components/gtm-component";import AppLayout from "@/components/layouts/app";import { SettingsHeader } from "@/components/settings/settings-header";-import { TabMenu } from "@/components/tab-menu";export default function Billing() {const router = useRouter();@@ -56,23 +55,6 @@ export default function Billing() {<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10"><SettingsHeader />- <TabMenu- navigation={[- {- label: "Subscription",- href: "/settings/billing",- value: "subscription",- currentValue: "subscription",- },- {- label: "Invoices",- href: "/settings/billing/invoices",- value: "invoices",- currentValue: "subscription",- },- ]}- />-<UpgradePlanContainer /></main></AppLayout>diff --git a/pages/settings/billing/invoices.tsx b/pages/settings/billing/invoices.tsxindex 38d3a96e..b8b842d6 100644--- a/pages/settings/billing/invoices.tsx+++ b/pages/settings/billing/invoices.tsx@@ -1,12 +1,12 @@+import Link from "next/link";import { useRouter } from "next/router";-import { Download, FileText, Loader2 } from "lucide-react";+import { ArrowLeft, Download, FileText, Loader2 } from "lucide-react";import { useInvoices } from "@/lib/swr/use-invoices";import AppLayout from "@/components/layouts/app";import { SettingsHeader } from "@/components/settings/settings-header";-import { TabMenu } from "@/components/tab-menu";import { Button } from "@/components/ui/button";import {Table,@@ -53,31 +53,23 @@ export default function Invoices() {<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10"><SettingsHeader />- <TabMenu- navigation={[- {- label: "Subscription",- href: "/settings/billing",- value: "subscription",- currentValue: "invoices",- },- {- label: "Invoices",- href: "/settings/billing/invoices",- value: "invoices",- currentValue: "invoices",- },- ]}- />-<div className="space-y-4">- <div className="space-y-1">- <h3 className="text-2xl font-semibold tracking-tight text-foreground">- Invoices- </h3>- <p className="text-sm text-muted-foreground">- A history of all your invoices- </p>+ <div className="space-y-2">+ <Link+ href="/settings/billing"+ className="inline-flex items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-foreground"+ >+ <ArrowLeft className="h-4 w-4" />+ Back to subscription+ </Link>+ <div className="space-y-1">+ <h3 className="text-2xl font-semibold tracking-tight text-foreground">+ Invoices+ </h3>+ <p className="text-sm text-muted-foreground">+ A history of all your invoices+ </p>+ </div></div><div className="rounded-lg border bg-white">diff --git a/pages/settings/upgrade-holiday-offer.tsx b/pages/settings/upgrade-holiday-offer.tsxindex f0024880..389e5af7 100644--- a/pages/settings/upgrade-holiday-offer.tsx+++ b/pages/settings/upgrade-holiday-offer.tsx@@ -4,7 +4,6 @@ import { useEffect, useState } from "react";import React from "react";import { useTeam } from "@/context/team-context";-import { getStripe } from "@/ee/stripe/client";import { Feature, PlanEnum, getPlanFeatures } from "@/ee/stripe/constants";import { PLANS } from "@/ee/stripe/utils";import { CheckIcon, Users2Icon, XIcon } from "lucide-react";@@ -374,9 +373,12 @@ export default function UpgradeHolidayOfferPage() {}const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (!data.url) {+ throw new Error(+ "Something went wrong. Please try again.",+ );+ }+ window.location.href = data.url;}).catch((err) => {alert(err);@@ -565,9 +567,12 @@ export default function UpgradeHolidayOfferPage() {}const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (!data.url) {+ throw new Error(+ "Something went wrong. Please try again.",+ );+ }+ window.location.href = data.url;}).catch((err) => {alert(err);@@ -756,9 +761,12 @@ export default function UpgradeHolidayOfferPage() {}const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });+ if (!data.url) {+ throw new Error(+ "Something went wrong. Please try again.",+ );+ }+ window.location.href = data.url;}).catch((err) => {alert(err);diff --git a/pages/settings/upgrade.tsx b/pages/settings/upgrade.tsxdeleted file mode 100644index e609bb05..00000000--- a/pages/settings/upgrade.tsx+++ /dev/null@@ -1,726 +0,0 @@-import { useRouter } from "next/router";--import { useEffect, useMemo, useState } from "react";-import React from "react";--import { UnlimitedPlanModal } from "@/components/billing/unlimited-plan-modal";-import { useTeam } from "@/context/team-context";-import { getStripe } from "@/ee/stripe/client";-import { Feature, PlanEnum, getPlanFeatures } from "@/ee/stripe/constants";-import { PLANS } from "@/ee/stripe/utils";-import { CheckIcon, InfinityIcon, Users2Icon, XIcon } from "lucide-react";-import { toast } from "sonner";--import { useAnalytics } from "@/lib/analytics";-import { usePlan } from "@/lib/swr/use-billing";-import { capitalize } from "@/lib/utils";--import { Button } from "@/components/ui/button";-import { Switch } from "@/components/ui/switch";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@/components/ui/tooltip";--// Feature rendering component-const FeatureItem = ({- feature,- period,-}: {- feature: Feature;- period: "monthly" | "yearly";-}) => {- const baseClasses = `flex items-center ${feature.isHighlighted ? "bg-orange-50 -mx-6 px-6 py-2 rounded-md dark:bg-orange-900/20" : ""}`;-- if (feature.isUsers) {- return (- <div className={`justify-between gap-x-8 ${baseClasses}`}>- <div className="flex items-center gap-x-3">- {feature.isNotIncluded ? (- <XIcon className="h-6 w-5 flex-none text-gray-500" />- ) : (- <CheckIcon className="h-6 w-5 flex-none 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>- );- }-- if (feature.isCustomDomain) {- return (- <span className={`gap-x-3 ${baseClasses}`}>- {feature.isNotIncluded ? (- <XIcon className="h-6 w-5 flex-none text-gray-500" />- ) : (- <CheckIcon className="h-6 w-5 flex-none text-[#fb7a00]" />- )}- <span>{feature.text}</span>- </span>- );- }-- return (- <div className={`gap-x-3 ${baseClasses}`}>- {feature.isNotIncluded ? (- <XIcon className="h-6 w-5 flex-none text-gray-500" />- ) : (- <CheckIcon className="h-6 w-5 flex-none text-[#fb7a00]" />- )}- <span>{feature.text}</span>- </div>- );-};--// Toggle component for Document Sharing vs Data Rooms-const PlanTypeSelector = ({- value,- onChange,- showBusinessDatarooms,-}: {- value: "documents" | "datarooms" | "business-datarooms";- onChange: (value: "documents" | "datarooms") => void;- showBusinessDatarooms?: boolean;-}) => {- const isDocuments = value === "documents";- const isDatarooms = value === "datarooms";- const isBusinessDatarooms = value === "business-datarooms";-- return (- <div className="mb-8 flex w-full max-w-md items-center justify-center rounded-lg border border-gray-200 p-1">- <button- className={`flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors ${- isDocuments- ? "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("documents")}- >- Document Sharing- </button>- <button- className={`flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors ${- isDatarooms- ? "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("datarooms")}- >- Data Rooms- </button>- </div>- );-};---export default function UpgradePage() {- const router = useRouter();- const [period, setPeriod] = useState<"yearly" | "monthly">("yearly");- const [selectedPlan, setSelectedPlan] = useState<string | null>(null);- const teamInfo = useTeam();- const { plan: teamPlan, trial, isTrial, isCustomer, isOldAccount } =- usePlan();-- const canStartDataRoomTrial =- !isTrial && (teamPlan === "free" || teamPlan === "pro");-- const handleStartDataRoomTrial = () => {- analytics.capture("Data Room Trial Button Clicked", {- source: "upgrade_page",- teamId: teamInfo?.currentTeam?.id,- });- router.push("/welcome?type=dataroom-trial");- };- const analytics = useAnalytics();-- // Determine initial view based on query params or default to datarooms- const getInitialView = () => {- if (router.query.view === "documents") return "documents";- if (router.query.view === "business-datarooms") return "business-datarooms";- return "datarooms";- };- const [planType, setPlanType] = useState<"documents" | "datarooms" | "business-datarooms">(getInitialView());-- // Update planType when query param changes- useEffect(() => {- if (router.query.view === "documents") {- setPlanType("documents");- } else if (router.query.view === "business-datarooms") {- setPlanType("business-datarooms");- } else if (router.query.view === "datarooms" || !router.query.view) {- setPlanType("datarooms");- }- }, [router.query.view]);-- // Document sharing plans (first 3)- const documentSharingPlans = [- PlanEnum.Pro,- PlanEnum.Business,- PlanEnum.DataRooms,- ];-- return (- <div className="min-h-screen bg-gray-50 p-8 dark:bg-gray-900">- <div className="relative mb-8 flex flex-col items-center gap-3 sm:block">- <h1 className="text-center text-3xl font-bold">- Select best plan for your business- </h1>- {canStartDataRoomTrial && (- <Button- size="sm"- className="bg-[#fb7a00] text-white hover:bg-[#fb7a00]/90 sm:absolute sm:right-0 sm:top-1/2 sm:-translate-y-1/2"- onClick={handleStartDataRoomTrial}- >- Start 7-day trial- </Button>- )}- </div>-- <div className="mb-8 flex items-center justify-center">- <span className="mr-2 text-sm">Monthly</span>- <Switch- checked={period === "yearly"}- onCheckedChange={() =>- setPeriod(period === "monthly" ? "yearly" : "monthly")- }- />- <span className="ml-2 text-sm">- Annually <span className="text-[#fb7a00]">(Save up to 35%)</span>- </span>- </div>-- {/* Plan Type Selector */}- <div className="mb-2 flex justify-center">- <PlanTypeSelector- value={planType}- onChange={(value) => setPlanType(value)}- />- </div>-- {planType !== "documents" && (- <div className="mb-8 text-center">- <UnlimitedPlanModal period={period}>- <p className="cursor-pointer text-sm text-muted-foreground transition-colors hover:text-foreground">- Deals with everything unlimited?{" "}- <span className="font-light underline underline-offset-4">- Get unlimited members, storage, and data rooms in one plan.- </span>- </p>- </UnlimitedPlanModal>- </div>- )}-- {/* Document Sharing Plans (3 in a row) */}- {planType === "documents" && (- <div className="grid grid-cols-1 gap-2 md:grid-cols-3 mb-8">- {documentSharingPlans.map((planOption) => {- const planFeatures = getPlanFeatures(planOption, { period });-- return (- <div- key={planOption}- className={`relative flex flex-col rounded-lg border ${- planOption === PlanEnum.DataRooms || planOption === PlanEnum.DataRoomsPlus- ? "border-[#fb7a00]"- : planOption === PlanEnum.DataRoomsPremium- ? "border-gray-900 dark:border-gray-200"- : "border-gray-400"- } 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">- <h3 className="text-balance text-xl font-medium text-foreground text-gray-900 dark:text-white">- {planOption}{" "}- {planOption === PlanEnum.Pro && (- <span className="text-xs font-normal text-muted-foreground">- All plans include unlimited visitors- </span>- )}- </h3>- {(planOption === PlanEnum.DataRooms ||- planOption === PlanEnum.DataRoomsPlus) && (- <span- className="absolute -top-3 right-4 rounded bg-[#fb7a00] px-2 py-1 text-xs text-white"- >- {planOption === PlanEnum.DataRoomsPlus- ? "Best deal"- : "Most popular"}- </span>- )}- </div>-- <div className="mb-2 text-balance text-4xl font-medium tabular-nums text-foreground">- €- {PLANS.find((p) => p.name === planOption)!.price[period].amount}- <span className="text-base font-normal dark:text-white/75">- /month{period === "yearly" && ", billed annually"}- </span>- </div>- <p className="mt-4 text-sm text-gray-600 dark:text-white">- {planFeatures.featureIntro}- </p>-- <ul- role="list"- className="mb-4 mt-4 space-y-3 text-sm leading-6 text-gray-600 dark:text-gray-300"- >- {planFeatures.features.map((feature, i) => (- <li key={i}>- <FeatureItem feature={feature} period={period} />- </li>- ))}- </ul>- <div className="mt-auto">- <Button- variant="default"- className={`w-full py-2 text-sm ${- planOption === PlanEnum.DataRooms || planOption === PlanEnum.DataRoomsPlus- ? "bg-[#fb7a00]/90 text-white hover:bg-[#fb7a00]"- : planOption === PlanEnum.DataRoomsPremium- ? "bg-gray-900 text-white hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"- : "bg-gray-800 text-white hover:bg-gray-900 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"- }`}- loading={selectedPlan === planOption}- disabled={selectedPlan !== null}- onClick={() => {- setSelectedPlan(planOption);- if (isCustomer && teamPlan !== "free") {- fetch(- `/api/teams/${teamInfo?.currentTeam?.id}/billing/manage`,- {- method: "POST",- },- )- .then(async (res) => {- if (res.status === 429) {- toast.error(- "Rate limit exceeded. Please try again later.",- );- setSelectedPlan(null);- return;- }-- const url = await res.json();- router.push(url);- })- .catch((err) => {- alert(err);- setSelectedPlan(null);- });- } else {- fetch(- `/api/teams/${- teamInfo?.currentTeam?.id- }/billing/upgrade?priceId=${- PLANS.find((p) => p.name === planOption)!.price[- period- ].priceIds[- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "production"- : "test"- ][isOldAccount ? "old" : "new"]- }`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- },- )- .then(async (res) => {- if (res.status === 429) {- toast.error(- "Rate limit exceeded. Please try again later.",- );- setSelectedPlan(null);- return;- }-- const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });- })- .catch((err) => {- alert(err);- setSelectedPlan(null);- });- }- }}- >- {selectedPlan === planOption- ? "Redirecting to Stripe..."- : `Upgrade to ${planOption} ${capitalize(period)}`}- </Button>- </div>- </div>- );- })}- </div>- )}-- {/* Business + Data Rooms Plans (4 in a row) */}- {planType === "business-datarooms" && (- <div className="grid grid-cols-1 gap-2 md:grid-cols-4">- {[- PlanEnum.Business,- PlanEnum.DataRooms,- PlanEnum.DataRoomsPlus,- PlanEnum.DataRoomsPremium,- ].map((planOption) => {- const planFeatures = getPlanFeatures(planOption, { period });-- return (- <div- key={planOption}- className={`relative flex flex-col rounded-lg border ${- planOption === PlanEnum.DataRooms- ? "border-[#fb7a00]"- : planOption === PlanEnum.DataRoomsPlus || planOption === PlanEnum.DataRoomsPremium- ? "border-gray-900 dark:border-gray-200"- : "border-gray-400"- } 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">- <h3 className="text-balance text-xl font-medium text-foreground text-gray-900 dark:text-white">- {planOption}- </h3>- {planOption === PlanEnum.DataRooms && (- <span- className="absolute -top-3 right-4 rounded bg-[#fb7a00] px-2 py-1 text-xs text-white"- >- Most popular- </span>- )}- {planOption === PlanEnum.DataRoomsPremium && (- <span- className="absolute -top-3 right-4 rounded bg-gray-900 px-2 py-1 text-xs text-white dark:bg-white dark:text-gray-900"- >- Best offer- </span>- )}- </div>-- <div className="mb-2 text-balance text-4xl font-medium tabular-nums text-foreground">- €- {PLANS.find((p) => p.name === planOption)!.price[period]- .amount}- <span className="text-base font-normal dark:text-white/75">- /month{period === "yearly" && ", billed annually"}- </span>- </div>- <p className="mt-4 text-sm text-gray-600 dark:text-white">- {planFeatures.featureIntro}- </p>-- <ul- role="list"- className="mb-4 mt-4 space-y-3 text-sm leading-6 text-gray-600 dark:text-gray-300"- >- {planFeatures.features.map((feature, i) => (- <li key={i}>- <FeatureItem feature={feature} period={period} />- </li>- ))}- </ul>- <div className="mt-auto">- <Button- variant="default"- className={`w-full py-2 text-sm ${- planOption === PlanEnum.DataRooms- ? "bg-[#fb7a00]/90 text-white hover:bg-[#fb7a00]"- : planOption === PlanEnum.DataRoomsPlus || planOption === PlanEnum.DataRoomsPremium- ? "bg-gray-900 text-white hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"- : "bg-gray-800 text-white hover:bg-gray-900 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"- }`}- loading={selectedPlan === planOption}- disabled={selectedPlan !== null}- onClick={() => {- setSelectedPlan(planOption);- if (isCustomer && teamPlan !== "free") {- fetch(- `/api/teams/${teamInfo?.currentTeam?.id}/billing/manage`,- {- method: "POST",- },- )- .then(async (res) => {- if (res.status === 429) {- toast.error(- "Rate limit exceeded. Please try again later.",- );- setSelectedPlan(null);- return;- }-- const url = await res.json();- router.push(url);- })- .catch((err) => {- alert(err);- setSelectedPlan(null);- });- } else {- fetch(- `/api/teams/${- teamInfo?.currentTeam?.id- }/billing/upgrade?priceId=${- PLANS.find((p) => p.name === planOption)!.price[- period- ].priceIds[- process.env.NEXT_PUBLIC_VERCEL_ENV ===- "production"- ? "production"- : "test"- ][isOldAccount ? "old" : "new"]- }`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- },- )- .then(async (res) => {- if (res.status === 429) {- toast.error(- "Rate limit exceeded. Please try again later.",- );- setSelectedPlan(null);- return;- }-- const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });- })- .catch((err) => {- alert(err);- setSelectedPlan(null);- });- }- }}- >- {selectedPlan === planOption- ? "Redirecting to Stripe..."- : `Upgrade to ${planOption} ${capitalize(period)}`}- </Button>- </div>- </div>- );- })}- </div>- )}-- {/* Data Rooms Plans (3 in a row) */}- {planType === "datarooms" && (- <>- <div className="grid grid-cols-1 gap-2 md:grid-cols-3">- {[- PlanEnum.DataRooms,- PlanEnum.DataRoomsPlus,- PlanEnum.DataRoomsPremium,- ].map((planOption) => {- const planFeatures = getPlanFeatures(planOption, { period });-- return (- <div- key={planOption}- className={`relative flex flex-col rounded-lg border ${- planOption === PlanEnum.DataRooms- ? "border-[#fb7a00]"- : planOption === PlanEnum.DataRoomsPlus || planOption === PlanEnum.DataRoomsPremium- ? "border-gray-900 dark:border-gray-200"- : "border-gray-400"- } 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">- <h3 className="text-balance text-xl font-medium text-foreground text-gray-900 dark:text-white">- {planOption}- </h3>- {planOption === PlanEnum.DataRooms && (- <span className="absolute -top-3 right-4 rounded bg-[#fb7a00] px-2 py-1 text-xs text-white">- Most popular- </span>- )}- {planOption === PlanEnum.DataRoomsPremium && (- <span className="absolute -top-3 right-4 rounded bg-gray-900 px-2 py-1 text-xs text-white dark:bg-white dark:text-gray-900">- Best offer- </span>- )}- </div>-- <div className="mb-2 text-balance text-4xl font-medium tabular-nums text-foreground">- €- {PLANS.find((p) => p.name === planOption)!.price[period]- .amount}- <span className="text-base font-normal dark:text-white/75">- /month{period === "yearly" && ", billed annually"}- </span>- </div>- <p className="mt-4 text-sm text-gray-600 dark:text-white">- {planFeatures.featureIntro}- </p>-- <ul- role="list"- className="mb-4 mt-4 space-y-3 text-sm leading-6 text-gray-600 dark:text-gray-300"- >- {planFeatures.features.map((feature, i) => (- <li key={i}>- <FeatureItem feature={feature} period={period} />- </li>- ))}- </ul>- <div className="mt-auto">- <Button- className={`w-full py-2 text-sm ${- planOption === PlanEnum.DataRooms- ? "bg-[#fb7a00]/90 text-white hover:bg-[#fb7a00]"- : planOption === PlanEnum.DataRoomsPlus || planOption === PlanEnum.DataRoomsPremium- ? "bg-gray-900 text-white hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"- : "bg-gray-800 text-white hover:bg-gray-900 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200"- }`}- loading={selectedPlan === planOption}- disabled={selectedPlan !== null}- onClick={() => {- setSelectedPlan(planOption);- if (isCustomer && teamPlan !== "free") {- fetch(- `/api/teams/${teamInfo?.currentTeam?.id}/billing/manage`,- {- method: "POST",- },- )- .then(async (res) => {- if (res.status === 429) {- toast.error(- "Rate limit exceeded. Please try again later.",- );- setSelectedPlan(null);- return;- }-- const url = await res.json();- router.push(url);- })- .catch((err) => {- alert(err);- setSelectedPlan(null);- });- } else {- fetch(- `/api/teams/${- teamInfo?.currentTeam?.id- }/billing/upgrade?priceId=${- PLANS.find((p) => p.name === planOption)!.price[- period- ].priceIds[- process.env.NEXT_PUBLIC_VERCEL_ENV ===- "production"- ? "production"- : "test"- ][isOldAccount ? "old" : "new"]- }`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- },- )- .then(async (res) => {- if (res.status === 429) {- toast.error(- "Rate limit exceeded. Please try again later.",- );- setSelectedPlan(null);- return;- }-- const data = await res.json();- const { id: sessionId } = data;- const stripe = await getStripe(isOldAccount);- stripe?.redirectToCheckout({ sessionId });- })- .catch((err) => {- alert(err);- setSelectedPlan(null);- });- }- }}- >- {selectedPlan === planOption- ? "Redirecting to Stripe..."- : `Upgrade to ${planOption} ${capitalize(period)}`}- </Button>- </div>- </div>- );- })}- </div>-- {/* Unlimited Plan Banner */}- <UnlimitedPlanModal period={period}>- <div className="mt-6 cursor-pointer rounded-xl border-2 border-gray-900 bg-white px-6 py-10 shadow-sm transition-colors hover:bg-gray-50 dark:border-gray-200 dark:bg-gray-900 dark:hover:bg-gray-800 md:px-8 md:py-20">- <div className="flex flex-col items-start gap-6 md:flex-row md:items-center md:justify-between">- <div className="flex items-center gap-4 md:gap-5">- <div className="flex h-12 w-12 flex-none items-center justify-center rounded-full border-2 border-gray-900 bg-transparent dark:border-gray-200">- <InfinityIcon className="h-6 w-6 text-gray-900 dark:text-gray-200" />- </div>- <div>- <h3 className="text-lg font-semibold text-gray-900 dark:text-white md:text-xl">- Data Rooms Unlimited- </h3>- <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">- Unlimited members, documents, storage, data rooms with no seat limits.- </p>- </div>- </div>- <div className="flex w-full flex-col items-start gap-4 md:w-auto md:flex-row md:items-center md:gap-8">- <div className="md:text-right">- <span className="text-3xl font-semibold tabular-nums text-gray-900 dark:text-white md:text-4xl">- €{PLANS.find((p) => p.name === PlanEnum.DataRoomsUnlimited)!.price[period].amount}- </span>- <span className="text-sm text-gray-500 dark:text-gray-400">- /month{period === "yearly" && ", billed annually"}- </span>- </div>- <Button size="lg" className="w-full bg-gray-900 text-white hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200 md:w-auto">- Get Unlimited- </Button>- </div>- </div>- </div>- </UnlimitedPlanModal>- </>- )}-- <div className="mt-8 flex flex-col items-center">- <a- href="https://cal.com/marcseitz/papermark"- target="_blank"- className="text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"- >- Looking for Papermark Enterprise?- </a>- </div>- </div>- );-}