Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Replace billing server action with tRPC mutation (RAL-1026) (#2248)

Luke Vellaf39ee42a9cfd
diff --git a/apps/web/src/app/[locale]/(app)/(space)/settings/billing/components/manage-seats-dialog.tsx b/apps/web/src/app/[locale]/(app)/(space)/settings/billing/components/manage-seats-dialog.tsx
index 6927e408b..858ab21e3 100644
--- a/apps/web/src/app/[locale]/(app)/(space)/settings/billing/components/manage-seats-dialog.tsx
+++ b/apps/web/src/app/[locale]/(app)/(space)/settings/billing/components/manage-seats-dialog.tsx
@@ -16,9 +16,8 @@ import { Input } from "@rallly/ui/input";
import { Label } from "@rallly/ui/label";
import { MinusIcon, PlusIcon } from "lucide-react";
import { useCallback, useState } from "react";
-import { updateSeatsAction } from "@/features/billing/actions";
import { Trans } from "@/i18n/client";
-import { useSafeAction } from "@/lib/safe-action/client";
+import { trpc } from "@/trpc/client";
interface ManageSeatsButtonProps {
currentSeats: number;
@@ -135,10 +134,11 @@ export function ManageSeatsDialog({
const canRemoveSeats = newSeatCount >= usedSeats;
const hasChanges = seatDelta !== 0;
- const { execute: updateSeats, isPending } = useSafeAction(updateSeatsAction);
+ const updateSeats = trpc.billing.updateSeats.useMutation();
const handleUpdate = async () => {
- updateSeats({ seatDelta });
+ const { url } = await updateSeats.mutateAsync({ seatDelta });
+ window.location.href = url;
};
return (
@@ -187,7 +187,7 @@ export function ManageSeatsDialog({
variant="primary"
onClick={handleUpdate}
disabled={!canRemoveSeats || !hasChanges}
- loading={isPending}
+ loading={updateSeats.isPending}
>
{isAdding ? (
<Trans
diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.ts
index c06e06257..6da3096bc 100644
--- a/apps/web/src/app/api/trpc/[trpc]/route.ts
+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts
@@ -1,5 +1,5 @@
import { createWideEvent, logger } from "@rallly/logger";
-
+import * as Sentry from "@sentry/nextjs";
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
import { ipAddress } from "@vercel/functions";
@@ -57,6 +57,10 @@ const handler = async (req: NextRequest) => {
event.errorCode = error.code;
event.errorMessage = error.message;
event.errorType = "TRPCError";
+
+ if (statusCode >= 500) {
+ Sentry.captureException(error);
+ }
},
});
event.statusCode = response.status;
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.ts
deleted file mode 100644
index cb9af40e5..000000000
--- a/apps/web/src/features/billing/actions.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-"use server";
-
-import { redirect } from "next/navigation";
-import * as 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.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",
- });
- }
-
- let portalSessionUrl: string | undefined;
-
- try {
- portalSessionUrl = await createStripeSubscriptionUpdateConfirmation({
- customerId: ctx.user.customerId,
- newSeatCount,
- subscriptionId: subscription.id,
- subscriptionItemId: subscription.subscriptionItemId,
- });
- } catch (error) {
- throw new AppError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Failed to create billing portal session",
- cause: error,
- });
- } finally {
- if (portalSessionUrl) {
- redirect(portalSessionUrl);
- }
- }
- });
diff --git a/apps/web/src/trpc/routers/billing.ts b/apps/web/src/trpc/routers/billing.ts
index 8e7039bda..d429fe7d0 100644
--- a/apps/web/src/trpc/routers/billing.ts
+++ b/apps/web/src/trpc/routers/billing.ts
@@ -1,5 +1,12 @@
+import { TRPCError } from "@trpc/server";
+import * as z from "zod";
+
import { getSpaceSubscription } from "@/features/billing/data";
-import { getActiveSpaceForUser } from "@/features/space/data";
+import { createStripeSubscriptionUpdateConfirmation } from "@/features/billing/utils";
+import {
+ getActiveSpaceForUser,
+ getSpaceSeatCount,
+} from "@/features/space/data";
import { isSelfHosted } from "@/utils/constants";
import { publicProcedure, router, spaceOwnerProcedure } from "../trpc";
@@ -20,4 +27,54 @@ export const billing = router({
getSubscription: spaceOwnerProcedure.query(async ({ ctx }) => {
return await getSpaceSubscription(ctx.space.id);
}),
+ updateSeats: spaceOwnerProcedure
+ .input(z.object({ seatDelta: z.int() }))
+ .mutation(async ({ ctx, input }) => {
+ const subscription = await getSpaceSubscription(ctx.space.id);
+
+ if (!subscription || !subscription.active) {
+ throw new TRPCError({
+ code: "PAYMENT_REQUIRED",
+ message: "No active subscription found for this space",
+ });
+ }
+
+ const currentSeats = subscription.quantity;
+ const newSeatCount = currentSeats + input.seatDelta;
+
+ if (newSeatCount < 1) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Seat count must be at least 1",
+ });
+ }
+
+ if (input.seatDelta < 0) {
+ const currentSeatUsage = await getSpaceSeatCount(ctx.space.id);
+ if (newSeatCount < currentSeatUsage) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Cannot reduce seats below current usage of ${currentSeatUsage}. Remove members first to free up seats.`,
+ });
+ }
+ }
+
+ if (!ctx.user.customerId) {
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: "No customer ID found for space owner",
+ });
+ }
+
+ const portalSessionUrl = await createStripeSubscriptionUpdateConfirmation(
+ {
+ customerId: ctx.user.customerId,
+ newSeatCount,
+ subscriptionId: subscription.id,
+ subscriptionItemId: subscription.subscriptionItemId,
+ },
+ );
+
+ return { url: portalSessionUrl };
+ }),
});