Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Allow buying seats from billing page and add support for self-hosting (#1905)
Luke Vellab7acb87847c1
diff --git a/.gitignore b/.gitignoreindex 5ac451acd..8b8e2e65c 100644--- a/.gitignore+++ b/.gitignore@@ -37,4 +37,5 @@ tsconfig.tsbuildinfo# Playwrightplaywright-report-test-results\ No newline at end of file+test-results+.kirodiff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 9c8acf29c..5cd94d31d 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -398,8 +398,6 @@"adminRoleDescription": "Full member access plus space management and member permissions","rolePlaceholder": "Select role...","invalidEmailAddress": "Please enter a valid email address",- "billingAcknowledgmentRequired": "You must acknowledge the billing impact",- "billingAcknowledgment": "I understand that adding members will affect my subscription price","makeAdmin": "Make admin","makeMember": "Make member","changingRole": "Changing role...",@@ -483,5 +481,21 @@"mySpaces": "My Spaces","spacesDescription": "Manage the spaces you belong to","noSpaces": "No spaces found",- "noSpacesDescription": "You are not a member of any spaces yet"+ "noSpacesDescription": "You are not a member of any spaces yet",+ "manageSeats": "Manage Seats",+ "manageSeatsDescription": "Adjust the number of seats for your space.",+ "addSeats": "{count, plural, one {Add # Seat} other {Add # Seats}}",+ "removeSeats": "{count, plural, one {Remove # Seat} other {Remove # Seats}}",+ "noChanges": "No Changes",+ "totalSeats": "Total Seats",+ "currentlyUsing": "Currently using {usedSeats} of {currentSeats} seats",+ "decreaseSeats": "Decrease seats",+ "increaseSeats": "Increase seats",+ "manageSubscription": "Manage Subscription",+ "seatUsage": "{usedSeats} of {totalSeats} seats used",+ "noSeatsAvailableAlertTitle": "No Seats Available",+ "noSeatsAvailableAlertBillingDescription": "Increase the number of seats in this space from the <a>billing page</a>.",+ "noSeatsAvailableAlertSelfHostedDescription": "You will need to <a>upgrade</a> to increase the number of seats in this space.",+ "seatsUpdatedAlertTitle": "Seats Updated",+ "seatsUpdatedAlertDescription": "Your seat allocation has been successfully updated. The changes will be reflected in your next billing cycle."}diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/components/manage-seats-button.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/components/manage-seats-button.tsxnew file mode 100644index 000000000..9c7a7e3c4--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/components/manage-seats-button.tsx@@ -0,0 +1,228 @@+"use client";++import { Button } from "@rallly/ui/button";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ useDialog,+} from "@rallly/ui/dialog";+import { Icon } from "@rallly/ui/icon";+import { Input } from "@rallly/ui/input";+import { Label } from "@rallly/ui/label";+import { ArmchairIcon, MinusIcon, PlusIcon } from "lucide-react";+import { useCallback, useState } from "react";+import { Trans } from "@/components/trans";+import { updateSeatsAction } from "@/features/billing/actions";+import { useSafeAction } from "@/lib/safe-action/client";+import { isSelfHosted } from "@/utils/constants";++interface ManageSeatsButtonProps {+ currentSeats: number;+ usedSeats: number;+}++interface SeatCountSelectorProps {+ value: number;+ onChange: (value: number) => void;+ currentSeats: number;+ minSeats: number;+}++function SeatCountSelector({+ value,+ onChange,+ currentSeats,+ minSeats,+}: SeatCountSelectorProps) {+ const handleIncrement = useCallback(() => {+ onChange(value + 1);+ }, [value, onChange]);++ const handleDecrement = useCallback(() => {+ if (value > minSeats) {+ onChange(value - 1);+ }+ }, [value, minSeats, onChange]);++ const handleInputChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const inputValue = e.target.value;++ // Allow empty input for better UX while typing+ if (inputValue === "") {+ return;+ }++ const numValue = Number.parseInt(inputValue, 10);++ // Only update if it's a valid positive integer+ if (!Number.isNaN(numValue) && numValue >= minSeats && numValue <= 999) {+ onChange(numValue);+ }+ },+ [minSeats, onChange],+ );++ const handleInputBlur = useCallback(() => {+ // If the input is empty or invalid on blur, reset to current value+ if (value < minSeats || Number.isNaN(value)) {+ onChange(currentSeats);+ }+ }, [value, minSeats, currentSeats, onChange]);++ const canDecrement = value > minSeats;+ const canIncrement = value < 999; // Reasonable upper limit++ return (+ <div>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="default"+ onClick={handleDecrement}+ disabled={!canDecrement}+ >+ <Icon>+ <MinusIcon />+ </Icon>+ <span className="sr-only">+ <Trans i18nKey="decreaseSeats" defaults="Decrease seats" />+ </span>+ </Button>++ <Input+ type="number"+ value={value}+ onChange={handleInputChange}+ onBlur={handleInputBlur}+ min={minSeats}+ max={999}+ className="w-20 text-center"+ />++ <Button+ type="button"+ onClick={handleIncrement}+ disabled={!canIncrement}+ >+ <Icon>+ <PlusIcon />+ </Icon>+ <span className="sr-only">+ <Trans i18nKey="increaseSeats" defaults="Increase seats" />+ </span>+ </Button>+ </div>+ </div>+ );+}++export function ManageSeatsButton({+ currentSeats,+ usedSeats,+}: ManageSeatsButtonProps) {+ const dialog = useDialog();+ const [newSeatCount, setNewSeatCount] = useState(currentSeats);+ const seatDelta = newSeatCount - currentSeats;+ const isRemoving = seatDelta < 0;+ const isAdding = seatDelta > 0;+ const canRemoveSeats = newSeatCount >= usedSeats;+ const hasChanges = seatDelta !== 0;++ const { execute: updateSeats, isPending } = useSafeAction(updateSeatsAction, {+ onSuccess: ({ data }) => {+ window.location.href = data.portalSessionUrl;+ },+ });++ const handleUpdate = async () => {+ if (isSelfHosted) {+ // Redirect to self-hosted licensing page+ window.location.href = "/licensing";+ } else {+ // Use Stripe billing portal with subscription_update_confirm flow+ updateSeats({ seatDelta });+ }+ };++ return (+ <>+ <Button onClick={dialog.trigger}>+ <Icon>+ <ArmchairIcon />+ </Icon>+ <Trans i18nKey="manageSeats" defaults="Manage Seats" />+ </Button>+ <Dialog {...dialog.dialogProps}>+ <DialogContent size="md">+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="manageSeats" defaults="Manage Seats" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="manageSeatsDescription"+ defaults="Adjust the number of seats for your space."+ />+ </DialogDescription>+ </DialogHeader>+ <div className="flex items-end justify-between gap-4">+ <div>+ <Label className="mb-2">+ <Trans i18nKey="totalSeats" defaults="Total Seats" />+ </Label>++ <p className="mt-1 text-muted-foreground text-sm">+ <Trans+ i18nKey="currentlyUsing"+ defaults="Currently using {usedSeats} of {currentSeats} seats"+ values={{ usedSeats, currentSeats }}+ />+ </p>+ </div>+ <SeatCountSelector+ value={newSeatCount}+ onChange={setNewSeatCount}+ currentSeats={currentSeats}+ minSeats={usedSeats}+ />+ </div>+ <DialogFooter>+ <DialogClose asChild>+ <Button>+ <Trans i18nKey="cancel" defaults="Cancel" />+ </Button>+ </DialogClose>+ <Button+ variant="primary"+ onClick={handleUpdate}+ disabled={!canRemoveSeats || !hasChanges}+ loading={isPending}+ >+ {isAdding ? (+ <Trans+ i18nKey="addSeats"+ defaults="Add {count} Seats"+ values={{ count: seatDelta }}+ />+ ) : isRemoving ? (+ <Trans+ i18nKey="removeSeats"+ defaults="Remove {count} Seats"+ values={{ count: Math.abs(seatDelta) }}+ />+ ) : (+ <Trans i18nKey="noChanges" defaults="No Changes" />+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/components/seats-updated-alert.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/components/seats-updated-alert.tsxnew file mode 100644index 000000000..37396a107--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/components/seats-updated-alert.tsx@@ -0,0 +1,29 @@+"use client";++import { Alert, AlertDescription, AlertTitle } from "@rallly/ui/alert";+import { CheckCircleIcon } from "lucide-react";+import { useSearchParams } from "next/navigation";+import { Trans } from "@/components/trans";++export function SeatsUpdatedAlert() {+ const searchParams = useSearchParams();++ if (!searchParams.has("seats_updated")) {+ return null;+ }++ return (+ <Alert variant="tip">+ <CheckCircleIcon />+ <AlertTitle>+ <Trans i18nKey="seatsUpdatedAlertTitle" defaults="Seats Updated" />+ </AlertTitle>+ <AlertDescription>+ <Trans+ i18nKey="seatsUpdatedAlertDescription"+ defaults="Your seat allocation has been successfully updated. The changes will be reflected in your next billing cycle."+ />+ </AlertDescription>+ </Alert>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/page.tsxindex 80024be12..fe72d02ff 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/page.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/billing/page.tsx@@ -1,8 +1,9 @@import { Button } from "@rallly/ui/button";import { Icon } from "@rallly/ui/icon";-import { DotIcon, SendIcon, ShieldXIcon } from "lucide-react";+import { CreditCardIcon, SendIcon, ShieldXIcon } from "lucide-react";import type { Metadata } from "next";import { notFound } from "next/navigation";+import { SeatsUpdatedAlert } from "@/app/[locale]/(space)/(dashboard)/settings/billing/components/seats-updated-alert";import {PageSection,PageSectionContent,@@ -27,8 +28,11 @@ import {SpaceTierIcon,SpaceTierLabel,} from "@/features/space/components/space-tier";+import { loadMembers } from "@/features/space/data";+import { getTotalSeatsForSpace } from "@/features/space/utils";import { getTranslation } from "@/i18n/server";import { isFeatureEnabled } from "@/lib/feature-flags/server";+import { ManageSeatsButton } from "./components/manage-seats-button";export default async function BillingSettingsPage() {if (!isFeatureEnabled("billing")) {@@ -58,7 +62,13 @@ export default async function BillingSettingsPage() {);}- const subscription = await getSpaceSubscription(space.id);+ const [subscription, members, totalSeats] = await Promise.all([+ getSpaceSubscription(space.id),+ loadMembers(),+ getTotalSeatsForSpace(space.id),+ ]);++ const usedSeats = members.total;return (<PageSectionGroup>@@ -83,48 +93,56 @@ export default async function BillingSettingsPage() {<SpaceTierLabel tier={space.tier} /></div>{subscription ? (- <ul className="flex items-center gap-px text-muted-foreground text-sm">- <li>- <SubscriptionStatus- status={subscription.status}- cancelAtPeriodEnd={subscription.cancelAtPeriodEnd}- periodEnd={subscription.periodEnd}- />- </li>- <li>- <Icon>- <DotIcon />- </Icon>- </li>- <li>- <Trans- i18nKey="seatCount"- defaults="{count, plural, {one, # seat} {other, # seats}}"- values={{ count: subscription?.quantity }}- />- </li>- </ul>+ <p className="text-muted-foreground text-sm">+ <SubscriptionStatus+ status={subscription.status}+ cancelAtPeriodEnd={subscription.cancelAtPeriodEnd}+ periodEnd={subscription.periodEnd}+ />+ </p>) : (<p className="text-muted-foreground text-sm"><Trans i18nKey="priceFree" /></p>)}</div>- <div>- {subscription ? (- <Button asChild>- <a href="/api/stripe/portal">- <Trans i18nKey="manage" />- </a>- </Button>- ) : (- <PayWallButton>- <Trans i18nKey="upgradeToPro" />- </PayWallButton>- )}+ <div className="text-muted-foreground text-sm">+ <Trans+ i18nKey="seatCount"+ defaults="{count, plural, {one, # seat} {other, # seats}}"+ values={{ count: totalSeats }}+ /></div></StackedListItem></StackedList>++ <div>+ {subscription ? (+ <div className="flex justify-between gap-2">+ <Button asChild>+ <a href="/api/stripe/portal">+ <Icon>+ <CreditCardIcon />+ </Icon>+ <Trans+ i18nKey="manageSubscription"+ defaults="Manage Subscription"+ />+ </a>+ </Button>+ <ManageSeatsButton+ currentSeats={totalSeats}+ usedSeats={usedSeats}+ />+ </div>+ ) : (+ <PayWallButton>+ <Trans i18nKey="upgradeToPro" />+ </PayWallButton>+ )}+ </div>++ <SeatsUpdatedAlert /></PageSectionContent></PageSection><PageSection>diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/header.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-button.tsxsimilarity index 86%rename from apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/header.tsxrename to apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-button.tsxindex c5e27621d..a788b7142 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/header.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-button.tsx@@ -11,14 +11,22 @@ import { useSpace } from "@/features/space/client";import { useTranslation } from "@/i18n/client";import { InviteMemberDialog } from "./invite-member-dialog";-export function InviteMemberButton() {+export function InviteMemberButton({+ usedSeats,+ totalSeats,+}: {+ usedSeats: number;+ totalSeats: number;+}) {const { t } = useTranslation();const inviteMemberDialog = useDialog();const space = useSpace();const { showPayWall } = useBilling();+ const availableSeats = Math.max(totalSeats - usedSeats, 0);return (<><Button+ disabled={availableSeats <= 0}onClick={() => {if (space.getMemberAbility().cannot("create", "SpaceMemberInvite")) {toast.error(diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-dialog.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-dialog.tsxindex 19b61b55a..6e1599ad0 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-dialog.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/components/invite-member-dialog.tsx@@ -2,7 +2,6 @@import { zodResolver } from "@hookform/resolvers/zod";import { Button } from "@rallly/ui/button";-import { Checkbox } from "@rallly/ui/checkbox";import type { DialogProps } from "@rallly/ui/dialog";import {Dialog,@@ -39,12 +38,10 @@ import { inviteMemberAction } from "@/features/space/actions";import { SpaceRole } from "@/features/space/components/space-role";import { memberRoleSchema } from "@/features/space/schema";import { useTranslation } from "@/i18n/client";-import { useFeatureFlag } from "@/lib/feature-flags/client";import { useSafeAction } from "@/lib/safe-action/client";function useInviteMemberFormSchema() {const { t } = useTranslation();- const isBillingEnabled = useFeatureFlag("billing");return useMemo(() => {return z.object({@@ -54,27 +51,18 @@ function useInviteMemberFormSchema() {}),}),role: memberRoleSchema,- billingAcknowledgment: isBillingEnabled- ? z.boolean().refine((val) => val === true, {- message: t("billingAcknowledgmentRequired", {- defaultValue: "You must acknowledge the billing impact",- }),- })- : z.boolean().optional().default(true),});- }, [t, isBillingEnabled]);+ }, [t]);}export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {const { t } = useTranslation();- const isBillingEnabled = useFeatureFlag("billing");const formSchema = useInviteMemberFormSchema();const form = useForm<z.infer<typeof formSchema>>({defaultValues: {email: "",role: "member",- billingAcknowledgment: !isBillingEnabled,},resolver: zodResolver(formSchema),});@@ -220,37 +208,11 @@ export function InviteMemberForm({ onSuccess }: { onSuccess?: () => void }) {</FormItem>)}/>- {isBillingEnabled && (- <FormField- control={form.control}- name="billingAcknowledgment"- render={({ field }) => (- <FormItem>- <div className="flex flex-row items-start gap-3 py-2">- <FormControl>- <Checkbox- checked={field.value}- onCheckedChange={field.onChange}- />- </FormControl>- <FormLabel className="font-normal">- {t("billingAcknowledgment", {- defaultValue:- "I understand that adding members will affect my subscription price",- })}- </FormLabel>- </div>- <FormMessage />- </FormItem>- )}- />- )}<FormMessage /></fieldset>- <div className="mt-4">+ <div className="mt-4 flex"><Buttonvariant="primary"- className="w-full"loading={inviteMember.isExecuting}type="submit">diff --git a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsxindex e3a50e0a6..50d39d007 100644--- a/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx+++ b/apps/web/src/app/[locale]/(space)/(dashboard)/settings/members/page.tsx@@ -1,6 +1,8 @@+import { Alert, AlertDescription, AlertTitle } from "@rallly/ui/alert";import { Badge } from "@rallly/ui/badge";+import { InfoIcon } from "lucide-react";import type { Metadata } from "next";-import { InviteMemberButton } from "@/app/[locale]/(space)/(dashboard)/settings/members/components/header";+import Link from "next/link";import {PageSection,PageSectionContent,@@ -9,17 +11,28 @@ import {PageSectionHeader,PageSectionTitle,} from "@/app/components/page-layout";+import { requireSpace } from "@/auth/data";import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";import { StackedList, StackedListItem } from "@/components/stacked-list";import { Trans } from "@/components/trans";+import { IfCloudHosted, IfSelfHosted } from "@/contexts/environment";import { SpaceRole } from "@/features/space/components/space-role";import { loadInvites, loadMembers } from "@/features/space/data";+import { getTotalSeatsForSpace } from "@/features/space/utils";import { getTranslation } from "@/i18n/server";import { InviteDropdownMenu } from "./components/invite-dropdown-menu";+import { InviteMemberButton } from "./components/invite-member-button";import { MemberDropdownMenu } from "./components/member-dropdown-menu";export default async function MembersSettingsPage() {- const [members, invites] = await Promise.all([loadMembers(), loadInvites()]);+ const space = await requireSpace();+ const [members, invites, totalSeats] = await Promise.all([+ loadMembers(),+ loadInvites(),+ getTotalSeatsForSpace(space.id),+ ]);++ const usedSeats = members.total;return (<PageSectionGroup>@@ -112,7 +125,62 @@ export default async function MembersSettingsPage() {))}</StackedList>) : null}- <InviteMemberButton />+ <div className="flex items-center gap-4">+ <InviteMemberButton usedSeats={usedSeats} totalSeats={totalSeats} />+ <p className="font-medium text-sm">+ <Trans+ i18nKey="seatUsage"+ defaults="{usedSeats} of {totalSeats} seats used"+ values={{ usedSeats, totalSeats }}+ />+ </p>+ </div>+ {totalSeats - usedSeats <= 0 ? (+ <Alert variant="info">+ <InfoIcon />+ <AlertTitle>+ <Trans+ i18nKey="noSeatsAvailableAlertTitle"+ defaults="No Seats Available"+ />+ </AlertTitle>+ <AlertDescription>+ <IfCloudHosted>+ <p>+ <Trans+ i18nKey="noSeatsAvailableAlertBillingDescription"+ defaults="Increase the number of seats in this space from the <a>billing page</a>."+ components={{+ a: (+ <Link+ className="underline"+ href="/settings/billing"+ />+ ),+ }}+ />+ </p>+ </IfCloudHosted>+ <IfSelfHosted>+ <p>+ <Trans+ i18nKey="noSeatsAvailableAlertSelfHostedDescription"+ defaults="You will need to <a>upgrade</a> to increase the number of seats in this space."+ components={{+ a: (+ <Link+ className="underline"+ prefetch={false}+ href="https://support.rallly.co/self-hosting/licensing"+ />+ ),+ }}+ />+ </p>+ </IfSelfHosted>+ </AlertDescription>+ </Alert>+ ) : null}</PageSectionContent></PageSection></PageSectionGroup>diff --git a/apps/web/src/components/stacked-list.tsx b/apps/web/src/components/stacked-list.tsxindex 37c232200..f320cd7a9 100644--- a/apps/web/src/components/stacked-list.tsx+++ b/apps/web/src/components/stacked-list.tsx@@ -8,7 +8,7 @@ export function StackedList({className?: string;}) {return (- <ul className={cn("divide-y overflow-hidden rounded-lg border", className)}>+ <ul className={cn("divide-y overflow-hidden rounded-xl border", className)}>{children}</ul>);diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.tsnew file mode 100644index 000000000..6cbf84d1d--- /dev/null+++ b/apps/web/src/features/billing/actions.ts@@ -0,0 +1,88 @@+"use server";++import { z } from "zod";+import { getSpaceSubscription } from "@/features/billing/data";+import { createStripeSubscriptionUpdateConfirmation } from "@/features/billing/utils";+import { getSpaceSeatCount } from "@/features/space/data";+import { AppError } from "@/lib/errors";+import { spaceActionClient } from "@/lib/safe-action/server";++export const updateSeatsAction = spaceActionClient+ .metadata({+ actionName: "billing_update_seats",+ })+ .inputSchema(+ z.object({+ seatDelta: z.number().int(),+ }),+ )+ .action(async ({ ctx, parsedInput }) => {+ // Check if user is the space owner (only owners can manage billing)+ if (ctx.space.ownerId !== ctx.user.id) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Only space owners can manage seat allocation",+ });+ }++ // Get current subscription+ const subscription = await getSpaceSubscription(ctx.space.id);++ if (!subscription || !subscription.active) {+ throw new AppError({+ code: "PAYMENT_REQUIRED",+ message: "No active subscription found for this space",+ });+ }++ // Calculate new seat count+ const currentSeats = subscription.quantity;+ const newSeatCount = currentSeats + parsedInput.seatDelta;++ if (newSeatCount < 1) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Seat count must be at least 1",+ });+ }++ // Check if reducing seats below current usage+ if (parsedInput.seatDelta < 0) {+ const currentSeatUsage = await getSpaceSeatCount(ctx.space.id);+ if (newSeatCount < currentSeatUsage) {+ throw new AppError({+ code: "FORBIDDEN",+ message: `Cannot reduce seats below current usage of ${currentSeatUsage}. Remove members first to free up seats.`,+ });+ }+ }++ // Get the space owner's customer ID+ if (!ctx.user.customerId) {+ throw new AppError({+ code: "PAYMENT_REQUIRED",+ message: "No customer ID found for space owner",+ });+ }++ try {+ const portalSessionUrl = await createStripeSubscriptionUpdateConfirmation(+ {+ customerId: ctx.user.customerId,+ newSeatCount,+ subscriptionId: subscription.id,+ subscriptionItemId: subscription.subscriptionItemId,+ },+ );++ return {+ portalSessionUrl,+ };+ } catch (error) {+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to create billing portal session",+ cause: error,+ });+ }+ });diff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.tsdeleted file mode 100644index f1c5f3212..000000000--- a/apps/web/src/features/billing/mutations.ts+++ /dev/null@@ -1,29 +0,0 @@-import { stripe } from "@rallly/billing";-import { getSpaceSubscription } from "@/features/billing/data";-import { getSpaceSeatCount } from "@/features/space/data";-import { AppError } from "@/lib/errors";--export async function updateSeatCount(spaceId: string, delta: number) {- const seatCount = await getSpaceSeatCount(spaceId);- const subscription = await getSpaceSubscription(spaceId);-- if (subscription?.tier !== "pro") {- throw new AppError({- code: "PAYMENT_REQUIRED",- message: "No active subscription found for this space",- });- }-- try {- await stripe.subscriptionItems.update(subscription.subscriptionItemId, {- quantity: seatCount + delta,- proration_behavior: "create_prorations",- });- } catch (error) {- throw new AppError({- code: "INTERNAL_SERVER_ERROR",- message: "Failed to update subscription item quantity",- cause: error,- });- }-}diff --git a/apps/web/src/features/billing/utils.ts b/apps/web/src/features/billing/utils.tsnew file mode 100644index 000000000..e7349c5ad--- /dev/null+++ b/apps/web/src/features/billing/utils.ts@@ -0,0 +1,94 @@+import { getProPricing, stripe } from "@rallly/billing";+import { absoluteUrl } from "@rallly/utils/absolute-url";+import { AppError } from "@/lib/errors";++async function createQuantityUpdatePortalConfiguration(): Promise<string> {+ try {+ // Get pricing data to configure allowed products and prices+ const pricingData = await getProPricing();++ // Get the product ID from one of the prices (both monthly and yearly should have the same product)+ const monthlyPrice = await stripe.prices.retrieve(pricingData.monthly.id);+ const productId = monthlyPrice.product as string;++ // Create a billing portal configuration that allows both price and quantity changes+ const configuration = await stripe.billingPortal.configurations.create({+ business_profile: {+ headline: "Update your seat allocation",+ },+ features: {+ subscription_update: {+ enabled: true,+ default_allowed_updates: ["price", "quantity"], // Allow both price and quantity changes+ proration_behavior: "create_prorations",+ products: [+ {+ product: productId,+ prices: [pricingData.monthly.id, pricingData.yearly.id], // Allow switching between monthly and yearly+ },+ ],+ },+ subscription_cancel: {+ enabled: false, // Disable cancellation in seat management flow+ },+ payment_method_update: {+ enabled: true,+ },+ invoice_history: {+ enabled: true,+ },+ },+ });++ return configuration.id;+ } catch (error) {+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to create billing portal configuration",+ cause: error,+ });+ }+}++export const createStripeSubscriptionUpdateConfirmation = async ({+ customerId,+ subscriptionId,+ subscriptionItemId,+ newSeatCount,+}: {+ customerId: string;+ subscriptionId: string;+ subscriptionItemId: string;+ newSeatCount: number;+}) => {+ // Create a billing portal configuration that allows quantity updates+ const configurationId = await createQuantityUpdatePortalConfiguration();++ // Create Stripe billing portal session with subscription_update_confirm flow+ // This deep links directly to the confirmation screen for the specific quantity change+ const portalSession = await stripe.billingPortal.sessions.create({+ customer: customerId,+ configuration: configurationId,+ return_url: absoluteUrl("/settings/billing"),+ flow_data: {+ type: "subscription_update_confirm",+ subscription_update_confirm: {+ subscription: subscriptionId,+ items: [+ {+ id: subscriptionItemId,+ quantity: newSeatCount,+ },+ ],+ },+ after_completion: {+ type: "redirect",+ redirect: {+ return_url: absoluteUrl("/settings/billing?seats_updated=true"),+ },+ },+ },+ });++ return portalSession.url;+};diff --git a/apps/web/src/features/licensing/data.ts b/apps/web/src/features/licensing/data.tsindex 1618c436e..9d2cabce6 100644--- a/apps/web/src/features/licensing/data.ts+++ b/apps/web/src/features/licensing/data.ts@@ -1,8 +1,16 @@import { prisma } from "@rallly/database";import { cache } from "react";+export function getInstanceLicense() {+ return prisma.instanceLicense.findFirst({+ orderBy: {+ id: "asc",+ },+ });+}+export const loadInstanceLicense = cache(async () => {- const license = await prisma.instanceLicense.findFirst();+ const license = await getInstanceLicense();if (!license) {return null;diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.tsindex c112147ca..89795e7e5 100644--- a/apps/web/src/features/space/actions.ts+++ b/apps/web/src/features/space/actions.ts@@ -7,13 +7,11 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { waitUntil } from "@vercel/functions";import { revalidatePath } from "next/cache";import { z } from "zod";-import { updateSeatCount } from "@/features/billing/mutations";-import { getMember } from "@/features/space/data";+import { getMember, getSpaceSeatCount } from "@/features/space/data";import { memberRoleSchema } from "@/features/space/schema";-import { toDBRole } from "@/features/space/utils";+import { getTotalSeatsForSpace, toDBRole } from "@/features/space/utils";import { setActiveSpace } from "@/features/user/mutations";import { AppError } from "@/lib/errors";-import { isFeatureEnabled } from "@/lib/feature-flags/server";import {authActionClient,createRateLimitMiddleware,@@ -199,7 +197,7 @@ export const inviteMemberAction = spaceActionClient});if (existingInvite) {- // Update existing invite if role is different+ // Update existing invite if role is different (allow regardless of seats)if (existingInvite.role !== toDBRole(parsedInput.role)) {await prisma.spaceMemberInvite.update({where: { id: existingInvite.id },@@ -220,6 +218,19 @@ export const inviteMemberAction = spaceActionClient};}+ // Check seat availability only for new invites+ const [currentSeatCount, totalSeats] = await Promise.all([+ getSpaceSeatCount(ctx.space.id),+ getTotalSeatsForSpace(ctx.space.id),+ ]);++ if (currentSeatCount >= totalSeats) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "There are not enough available seats to perform this action",+ });+ }+try {await prisma.$transaction(async (tx) => {const invite = await tx.spaceMemberInvite.create({@@ -288,6 +299,20 @@ export const acceptInviteAction = authActionClient}await prisma.$transaction(async (tx) => {+ // Check seat availability before accepting the invite+ const [usedSeats, totalSeats] = await Promise.all([+ tx.spaceMember.count({ where: { spaceId: parsedInput.spaceId } }),+ getTotalSeatsForSpace(parsedInput.spaceId),+ ]);++ if (usedSeats >= totalSeats) {+ throw new AppError({+ code: "FORBIDDEN",+ message:+ "There are not enough available seats to accept this invitation",+ });+ }+await tx.spaceMember.create({data: {spaceId: parsedInput.spaceId,@@ -301,10 +326,6 @@ export const acceptInviteAction = authActionClientid: spaceMemberInvite.id,},});-- if (isFeatureEnabled("billing")) {- await updateSeatCount(spaceMemberInvite.spaceId, 1);- }});try {@@ -350,10 +371,6 @@ export const removeMemberAction = spaceActionClientid: parsedInput.memberId,},});-- if (isFeatureEnabled("billing")) {- await updateSeatCount(member.spaceId, -1);- }});});@@ -670,11 +687,6 @@ export const leaveSpaceFromAccountAction = authActionClientlastSelectedAt: new Date(),},});-- // Update seat count if billing is enabled- if (isFeatureEnabled("billing")) {- await updateSeatCount(parsedInput.spaceId, -1);- }});});@@ -745,10 +757,5 @@ export const leaveSpaceAction = spaceActionClientlastSelectedAt: new Date(),},});-- // Update seat count if billing is enabled- if (isFeatureEnabled("billing")) {- await updateSeatCount(ctx.space.id, -1);- }});});diff --git a/apps/web/src/features/space/utils.ts b/apps/web/src/features/space/utils.tsindex a3634b7f4..ec85d5127 100644--- a/apps/web/src/features/space/utils.ts+++ b/apps/web/src/features/space/utils.ts@@ -1,5 +1,10 @@import type { SpaceMemberRole as PrismaSpaceMemberRole } from "@prisma/client";+import { getSpaceSubscription } from "@/features/billing/data";+import { getInstanceLicense } from "@/features/licensing/data";+import type { LicenseType } from "@/features/licensing/schema";import type { MemberRole } from "@/features/space/schema";+import { AppError } from "@/lib/errors";+import { isSelfHosted } from "@/utils/constants";export const toDBRole = (role: MemberRole): PrismaSpaceMemberRole => {switch (role) {@@ -18,3 +23,80 @@ export const fromDBRole = (role: PrismaSpaceMemberRole): MemberRole => {return "admin";}};++/**+ * Default seat limit for spaces without active subscriptions+ */+const DEFAULT_SEAT_LIMIT = 1;+const MAX_SEAT_LIMIT = 100;++/**+ * Returns the seat limit for self-hosted instances based on license type+ */+export function getSelfHostedSeatLimit(+ licenseType: LicenseType | null,+): number {+ if (!licenseType) {+ return DEFAULT_SEAT_LIMIT;+ }++ switch (licenseType) {+ case "PLUS":+ return 5;+ case "ORGANIZATION":+ return 50;+ case "ENTERPRISE":+ return MAX_SEAT_LIMIT;+ default:+ return DEFAULT_SEAT_LIMIT;+ }+}++/**+ * Gets the total number of seats available for a space+ * Handles both cloud-hosted (Stripe subscription) and self-hosted (license-based) deployments+ */+export async function getTotalSeatsForSpace(spaceId: string): Promise<number> {+ try {+ if (isSelfHosted) {+ // For self-hosted instances, get seat limit from instance license+ const license = await getInstanceLicense();++ if (!license) {+ // No license found, return default limit+ return DEFAULT_SEAT_LIMIT;+ }++ // If license has explicit seats defined, use that+ if (license.seats && license.seats > 0) {+ return Math.min(license.seats, MAX_SEAT_LIMIT);+ }++ // Otherwise, use the license type to determine seat limit+ return getSelfHostedSeatLimit(license.type);+ } else {+ // For cloud-hosted instances, get seat count from Stripe subscription+ const subscription = await getSpaceSubscription(spaceId);++ if (!subscription || !subscription.active) {+ // Return default limit for spaces without active subscriptions+ return DEFAULT_SEAT_LIMIT;+ }++ return subscription.quantity || DEFAULT_SEAT_LIMIT;+ }+ } catch (error) {+ // Log the error for debugging but don't expose internal details+ console.error(`Failed to get total seats for space ${spaceId}:`, error);++ if (error instanceof AppError) {+ throw error;+ }++ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to retrieve seat information",+ cause: error,+ });+ }+}diff --git a/packages/ui/src/alert.tsx b/packages/ui/src/alert.tsxindex 5dbfa731b..5fead028e 100644--- a/packages/ui/src/alert.tsx+++ b/packages/ui/src/alert.tsx@@ -10,6 +10,8 @@ const alertVariants = cva(variants: {variant: {default: "bg-card text-card-foreground",+ primary:+ "border-indigo-200 bg-indigo-50 text-indigo-600 has-[[data-slot=alert-description]]:text-indigo-800/90 [&>svg]:text-indigo-600",destructive:"border-destructive/20 bg-destructive-background text-destructive-foreground has-[[data-slot=alert-description]]:opacity-50",info: "border-blue-200 bg-blue-50 text-blue-900 has-[[data-slot=alert-description]]:text-blue-800/90 [&>svg]:text-blue-600",@@ -58,7 +60,7 @@ function AlertDescription({<divdata-slot="alert-description"className={cn(- "col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",+ "col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-5",className,)}{...props}