Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add seat modal
Marc Seitzdf276707df58
diff --git a/components/billing/add-seat-modal.tsx b/components/billing/add-seat-modal.tsxnew file mode 100644index 00000000..15466516--- /dev/null+++ b/components/billing/add-seat-modal.tsx@@ -0,0 +1,190 @@+import { useRouter } from "next/router";++import { useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import { getPriceIdFromPlan } from "@/ee/stripe/functions/get-price-id-from-plan";+import { getQuantityFromPriceId } from "@/ee/stripe/functions/get-quantity-from-plan";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";++import { useAnalytics } from "@/lib/analytics";+import { usePlan } from "@/lib/swr/use-billing";+import useLimits from "@/lib/swr/use-limits";++export function AddSeatModal({+ open,+ setOpen,+ children,+}: {+ open: boolean;+ setOpen: React.Dispatch<React.SetStateAction<boolean>>;+ children?: React.ReactNode;+}) {+ const router = useRouter();+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const analytics = useAnalytics();+ const { plan: userPlan, planName, isAnnualPlan } = usePlan();+ const { limits } = useLimits();++ const [quantity, setQuantity] = useState<number>(1);+ const [loading, setLoading] = useState<boolean>(false);++ // Get the minimum quantity for the current plan+ const priceId = getPriceIdFromPlan(+ planName,+ isAnnualPlan ? "yearly" : "monthly",+ );+ const minQuantity = getQuantityFromPriceId(priceId);++ // Set initial quantity to 1 (adding one seat)+ useEffect(() => {+ if (open) {+ setQuantity(1);+ }+ }, [open]);++ // Calculate the total number of seats after the update+ const totalSeatsAfterUpdate = limits ? limits.users + quantity : quantity;++ const handleDecrement = () => {+ if (quantity > 1) {+ setQuantity(quantity - 1);+ }+ };++ const handleIncrement = () => {+ setQuantity(quantity + 1);+ };++ const handleSubmit = async () => {+ setLoading(true);++ try {+ const response = await fetch(`/api/teams/${teamId}/billing/manage`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ priceId,+ quantity: totalSeatsAfterUpdate,+ addSeat: true,+ // return_url: `${process.env.NEXTAUTH_URL}/settings/people?success=true`,+ }),+ });++ if (!response.ok) {+ const error = await response.json();+ toast.error(error);+ setLoading(false);+ return;+ }++ const url = await response.json();++ analytics.capture("Add Seat Clicked", {+ quantity: quantity,+ totalSeats: totalSeatsAfterUpdate,+ teamId,+ plan: userPlan,+ });++ router.push(url);+ } catch (error) {+ toast.error("An error occurred while processing your request.");+ setLoading(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>{children}</DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader className="text-start">+ <DialogTitle>Add more seats</DialogTitle>+ <DialogDescription>{planName}</DialogDescription>+ </DialogHeader>+ <div className="py-6">+ <div className="flex items-center justify-center space-x-4">+ <Button+ variant="outline"+ size="icon"+ onClick={handleDecrement}+ disabled={quantity <= 1}+ className="h-10 w-10 rounded-full"+ >+ <span className="text-xl">−</span>+ </Button>++ <div className="w-24">+ <Input+ type="number"+ value={quantity}+ onChange={(e) => {+ const value = parseInt(e.target.value);+ if (!isNaN(value) && value >= 1) {+ setQuantity(value);+ }+ }}+ className="text-center text-lg"+ min={1}+ />+ </div>++ <Button+ variant="outline"+ size="icon"+ onClick={handleIncrement}+ className="h-10 w-10 rounded-full"+ >+ <span className="text-xl">+</span>+ </Button>+ </div>++ {limits && (+ <p className="mt-4 text-center text-sm text-muted-foreground">+ Current limit: {limits.users}{" "}+ {limits.users === 1 ? "user" : "users"}+ </p>+ )}++ <p className="mt-2 text-center text-sm">+ Adding <span className="font-semibold">{quantity}</span>{" "}+ {quantity === 1 ? "seat" : "seats"}+ </p>++ <p className="mt-2 text-center text-sm font-medium">+ Total after update: {totalSeatsAfterUpdate}{" "}+ {totalSeatsAfterUpdate === 1 ? "user" : "users"}+ </p>++ {minQuantity > 1 && (+ <p className="mt-2 text-center text-sm text-muted-foreground">+ Minimum quantity for {planName}: {minQuantity} users+ </p>+ )}+ </div>++ <DialogFooter>+ <Button onClick={handleSubmit} className="w-full" disabled={loading}>+ {loading ? "Redirecting..." : "Proceed to checkout"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/ee/stripe/constants.ts b/ee/stripe/constants.tsindex 51a2e548..a3ed7261 100644--- a/ee/stripe/constants.ts+++ b/ee/stripe/constants.ts@@ -5,6 +5,15 @@ export enum PlanEnum {DataRoomsPlus = "Data Rooms Plus",}+export const PLAN_NAME_MAP: Record<string, string> = {+ free: "Free",+ starter: "Starter",+ pro: "Pro",+ business: "Business",+ datarooms: "Data Rooms",+ "datarooms-plus": "Data Rooms Plus",+};+export type PeriodType = "monthly" | "yearly";export interface Feature {@@ -26,8 +35,8 @@ export interface PlanFeatures {export const PLAN_PRICING = {Pro: {extraUserPrice: {- monthly: "€19/month per additional user",- yearly: "€14/month per additional user",+ monthly: "€29/month per additional user",+ yearly: "€24/month per additional user",},},Business: {@@ -44,7 +53,7 @@ export const PLAN_PRICING = {},"Data Rooms Plus": {extraUserPrice: {- monthly: "€79/month per additional user",+ monthly: "€69/month per additional user",yearly: "€49/month per additional user",},},diff --git a/lib/swr/use-billing.ts b/lib/swr/use-billing.tsindex 35724c5c..a8e7a1e4 100644--- a/lib/swr/use-billing.ts+++ b/lib/swr/use-billing.ts@@ -1,4 +1,5 @@import { useTeam } from "@/context/team-context";+import { PLAN_NAME_MAP } from "@/ee/stripe/constants";import useSWR from "swr";import { fetcher } from "@/lib/utils";@@ -84,6 +85,7 @@ export function usePlan() {return {plan: parsedPlan.plan ?? "free",+ planName: PLAN_NAME_MAP[parsedPlan.plan ?? "free"],trial: parsedPlan.trial,isTrial: !!parsedPlan.trial,isOldAccount: parsedPlan.old,diff --git a/pages/api/teams/[teamId]/billing/manage.ts b/pages/api/teams/[teamId]/billing/manage.tsindex ab2edf86..80df7d8b 100644--- a/pages/api/teams/[teamId]/billing/manage.ts+++ b/pages/api/teams/[teamId]/billing/manage.ts@@ -36,10 +36,20 @@ export default async function handle(const userEmail = (session.user as CustomUser).email;const { teamId } = req.query as { teamId: string };- const { priceId, upgradePlan, proAnnualBanner } = req.body as {+ const {+ priceId,+ upgradePlan,+ quantity,+ addSeat,+ proAnnualBanner,+ return_url,+ } = req.body as {priceId: string;upgradePlan: boolean;+ quantity?: number;+ addSeat?: boolean;proAnnualBanner?: boolean;+ return_url?: string;};try {const team = await prisma.team.findUnique({@@ -80,7 +90,7 @@ export default async function handle(const { url } = await stripe.billingPortal.sessions.create({customer: team.stripeId,return_url: `${process.env.NEXTAUTH_URL}/settings/billing?cancel=true`,- ...(upgradePlan &&+ ...((upgradePlan || addSeat) &&subscriptionItemId && {flow_data: {type: "subscription_update_confirm",@@ -89,7 +99,9 @@ export default async function handle(items: [{id: subscriptionItemId,- quantity: isOldAccount(team.plan) ? 1 : minQuantity,+ quantity: isOldAccount(team.plan)+ ? 1+ : (quantity ?? minQuantity),price: priceId,},],@@ -97,7 +109,9 @@ export default async function handle(after_completion: {type: "redirect",redirect: {- return_url: `${process.env.NEXTAUTH_URL}/settings/billing?success=true`,+ return_url:+ return_url ??+ `${process.env.NEXTAUTH_URL}/settings/billing?success=true`,},},},diff --git a/pages/settings/people.tsx b/pages/settings/people.tsxindex 58ec17d2..4e912012 100644--- a/pages/settings/people.tsx+++ b/pages/settings/people.tsx@@ -5,10 +5,12 @@ import { useState } from "react";import { useTeam } from "@/context/team-context";import { PlanEnum } from "@/ee/stripe/constants";+import { getPriceIdFromPlan } from "@/ee/stripe/functions/get-price-id-from-plan";import { useSession } from "next-auth/react";import { toast } from "sonner";import { mutate } from "swr";+import { AddSeatModal } from "@/components/billing/add-seat-modal";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import AppLayout from "@/components/layouts/app";import { SettingsHeader } from "@/components/settings/settings-header";@@ -36,12 +38,13 @@ import { CustomUser } from "@/lib/types";export default function Billing() {const [isTeamMemberInviteModalOpen, setTeamMemberInviteModalOpen] =useState<boolean>(false);+ const [isAddSeatModalOpen, setAddSeatModalOpen] = useState<boolean>(false);const [leavingUserId, setLeavingUserId] = useState<string>("");const { data: session } = useSession();const { team, loading } = useGetTeam()!;const teamInfo = useTeam();- const { plan: userPlan } = usePlan();+ const { plan: userPlan, planName } = usePlan();const { limits } = useLimits();const { teams } = useTeams();const analytics = useAnalytics();@@ -51,6 +54,7 @@ export default function Billing() {const router = useRouter();const numUsers = (team && team.users.length) ?? 1;+ const numInvitations = (invitations && invitations.length) ?? 0;const getUserDocumentCount = (userId: string) => {const documents = team?.documents.filter(@@ -225,8 +229,17 @@ export default function Billing() {Teammates that have access to this project.</p></div>- {userPlan !== "free" &&- (limits === null || (limits && limits.users >= numUsers)) ? (+ {userPlan === "free" ? (+ <UpgradePlanModal+ clickedPlan={PlanEnum.Pro}+ trigger={"invite_team_members"}+ >+ <Button className="whitespace-nowrap px-1 text-xs sm:px-4 sm:text-sm">+ Upgrade to invite members+ </Button>+ </UpgradePlanModal>+ ) : limits === null ||+ (limits && limits.users > numUsers + numInvitations) ? (<AddTeamMembersopen={isTeamMemberInviteModalOpen}setOpen={setTeamMemberInviteModalOpen}@@ -234,14 +247,14 @@ export default function Billing() {<Button>Invite</Button></AddTeamMembers>) : (- <UpgradePlanModal- clickedPlan={PlanEnum.Pro}- trigger={"invite_team_members"}+ <AddSeatModal+ open={isAddSeatModalOpen}+ setOpen={setAddSeatModalOpen}><Button className="whitespace-nowrap px-1 text-xs sm:px-4 sm:text-sm">- Upgrade to invite members+ Add a seat to invite member</Button>- </UpgradePlanModal>+ </AddSeatModal>)}</div></div>