From 383314d3e26d0608eaf6a6bc1cc9a4061cac1c9b Mon Sep 17 00:00:00 2001 From: sean-brydon <55134778+sean-brydon@users.noreply.github.com> Date: Tue, 13 Jan 2026 09:17:42 +0000 Subject: [PATCH] feat: add skip trial feature for teams/orgs billing page (#26584) * feat: add skip trial feature for teams/orgs billing page Co-Authored-By: sean@cal.com * feat: add translation strings for skip trial feature and fix lint-staged config Co-Authored-By: sean@cal.com * fix: use IS_TEAM_BILLING_ENABLED instead of IS_SELF_HOSTED Co-Authored-By: sean@cal.com * fix: use correct DialogHeader props in billing-view.tsx Co-Authored-By: sean@cal.com * restore lint staged config file * invalidate trpc cache * fix: update role filter and error message in skipTrialForTeam handler - Changed role filter to include both OWNER and ADMIN roles to match authorization logic - Updated error message to reflect that both owners and admins can skip the trial Addresses Cubic AI review feedback on PR #26584 Co-Authored-By: unknown <> * fix: optimize skipTrialForTeam to query only specific team by ID Address Cubic AI review feedback: Replace findAllAcceptedTeamMemberships (which fetches all teams) with TeamRepository.findById (which fetches only the specific team needed). Authorization is already validated earlier in the handler, so this redundant query was inefficient. Co-Authored-By: unknown <> * fix static methods * feat: use pbac * fix: remove redundant team query in getSubscriptionStatus handler Co-Authored-By: sean@cal.com * add pbac to skip team handler --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../modules/settings/billing/billing-view.tsx | 70 +++++++++++++- apps/web/public/static/locales/en/common.json | 6 ++ .../server/routers/viewer/teams/_router.tsx | 20 +++- .../teams/getSubscriptionStatus.handler.ts | 83 ++++++++++++++++ .../teams/getSubscriptionStatus.schema.ts | 7 ++ .../viewer/teams/skipTrialForTeam.handler.ts | 96 +++++++++++++++++++ .../viewer/teams/skipTrialForTeam.schema.ts | 7 ++ 7 files changed, 281 insertions(+), 8 deletions(-) create mode 100644 packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.handler.ts create mode 100644 packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.schema.ts create mode 100644 packages/trpc/server/routers/viewer/teams/skipTrialForTeam.handler.ts create mode 100644 packages/trpc/server/routers/viewer/teams/skipTrialForTeam.schema.ts diff --git a/apps/web/modules/settings/billing/billing-view.tsx b/apps/web/modules/settings/billing/billing-view.tsx index 5db170580c..ffa15e2732 100644 --- a/apps/web/modules/settings/billing/billing-view.tsx +++ b/apps/web/modules/settings/billing/billing-view.tsx @@ -1,12 +1,15 @@ "use client"; -import { useSession } from "next-auth/react"; -import { usePathname } from "next/navigation"; - import { WEBAPP_URL } from "@calcom/lib/constants"; import { useLocale } from "@calcom/lib/hooks/useLocale"; +import { trpc } from "@calcom/trpc/react"; import classNames from "@calcom/ui/classNames"; import { Button } from "@calcom/ui/components/button"; +import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/components/dialog"; +import { showToast } from "@calcom/ui/components/toast"; +import { usePathname } from "next/navigation"; +import { useSession } from "next-auth/react"; +import { useState } from "react"; import BillingCredits from "~/settings/billing/components/BillingCredits"; @@ -45,6 +48,8 @@ const BillingView = () => { const session = useSession(); const { t } = useLocale(); const returnTo = pathname; + const [showSkipTrialDialog, setShowSkipTrialDialog] = useState(false); + const utils = trpc.useUtils(); // Determine the billing context and extract appropriate team/org ID const getTeamIdFromContext = () => { @@ -64,6 +69,27 @@ const BillingView = () => { }; const teamId = getTeamIdFromContext(); + const teamIdNumber = teamId ? parseInt(teamId, 10) : null; + + const { data: subscriptionStatus, isLoading: isLoadingStatus } = + trpc.viewer.teams.getSubscriptionStatus.useQuery( + { teamId: teamIdNumber ?? 0 }, + { enabled: !!teamIdNumber } + ); + + const skipTrialMutation = trpc.viewer.teams.skipTrialForTeam.useMutation({ + onSuccess: () => { + showToast(t("trial_skipped_successfully"), "success"); + setShowSkipTrialDialog(false); + // Invalidate the subscription status cache to hide the skip trial button + if (teamIdNumber) { + utils.viewer.teams.getSubscriptionStatus.invalidate({ teamId: teamIdNumber }); + } + }, + onError: (error) => { + showToast(error.message || t("error_skipping_trial"), "error"); + }, + }); const billingHref = teamId ? `/api/integrations/stripepayment/portal?teamId=${teamId}&returnTo=${WEBAPP_URL}${returnTo}` @@ -75,6 +101,14 @@ const BillingView = () => { } }; + const handleSkipTrial = () => { + if (teamIdNumber) { + skipTrialMutation.mutate({ teamId: teamIdNumber }); + } + }; + + const isTrialing = subscriptionStatus?.isTrialing && teamIdNumber; + return ( <>
@@ -89,6 +123,21 @@ const BillingView = () => { {t("billing_portal")}
+ {isTrialing && ( +
+
+

{t("skip_trial")}

+

{t("skip_trial_description")}

+
+ +
+ )}

{t("need_help")}

+ + + + +

{t("skip_trial_confirmation_description")}

+ + + + +
+
); }; diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json index 2e8e699d4f..d0d7f25500 100644 --- a/apps/web/public/static/locales/en/common.json +++ b/apps/web/public/static/locales/en/common.json @@ -1997,6 +1997,12 @@ "billing_freeplan_description": "We work better in teams. Extend your workflows with round-robin and collective events and make advanced routing forms", "billing_freeplan_cta": "Try now", "billing_portal": "Billing portal", + "skip_trial": "Skip trial", + "skip_trial_description": "End your trial period early and start your paid subscription immediately", + "skip_trial_confirmation_title": "Skip trial period?", + "skip_trial_confirmation_description": "Are you sure you want to skip your trial period? Your paid subscription will start immediately and you will be charged according to your plan.", + "trial_skipped_successfully": "Trial period skipped successfully", + "error_skipping_trial": "Failed to skip trial period", "billing_help_cta": "Contact support", "ignore_special_characters_booking_questions": "Ignore special characters in your booking question identifier. Use only letters and numbers", "ignore_special_characters_form_responses": "Ignore special characters in your form field identifier. Use only letters and numbers", diff --git a/packages/trpc/server/routers/viewer/teams/_router.tsx b/packages/trpc/server/routers/viewer/teams/_router.tsx index b52c40e08c..0d034ee1a4 100644 --- a/packages/trpc/server/routers/viewer/teams/_router.tsx +++ b/packages/trpc/server/routers/viewer/teams/_router.tsx @@ -14,6 +14,7 @@ import { ZGetSchema } from "./get.schema"; import { ZGetInternalNotesPresetsInputSchema } from "./getInternalNotesPresets.schema"; import { ZGetMemberAvailabilityInputSchema } from "./getMemberAvailability.schema"; import { ZGetMembershipbyUserInputSchema } from "./getMembershipbyUser.schema"; +import { ZGetSubscriptionStatusInputSchema } from "./getSubscriptionStatus.schema"; import { ZGetUserConnectedAppsInputSchema } from "./getUserConnectedApps.schema"; import { ZHasActiveTeamPlanInputSchema } from "./hasActiveTeamPlan.schema"; import { ZHasEditPermissionForUserSchema } from "./hasEditPermissionForUser.schema"; @@ -22,19 +23,20 @@ import { ZInviteMemberByTokenSchemaInputSchema } from "./inviteMemberByToken.sch import { ZLegacyListMembersInputSchema } from "./legacyListMembers.schema"; import { ZGetListSchema } from "./list.schema"; import { ZListMembersInputSchema } from "./listMembers.schema"; +import { ZGetManagedEventUsersToReassignInputSchema } from "./managedEvents/getManagedEventUsersToReassign.schema"; +import { ZManagedEventManualReassignInputSchema } from "./managedEvents/managedEventManualReassign.schema"; +import { ZManagedEventReassignInputSchema } from "./managedEvents/managedEventReassign.schema"; import { hasTeamPlan } from "./procedures/hasTeamPlan"; import { ZPublishInputSchema } from "./publish.schema"; import { ZRemoveHostsFromEventTypes } from "./removeHostsFromEventTypes.schema"; import { ZRemoveMemberInputSchema } from "./removeMember.schema"; import { ZResendInvitationInputSchema } from "./resendInvitation.schema"; -import { ZGetManagedEventUsersToReassignInputSchema } from "./managedEvents/getManagedEventUsersToReassign.schema"; -import { ZManagedEventManualReassignInputSchema } from "./managedEvents/managedEventManualReassign.schema"; -import { ZManagedEventReassignInputSchema } from "./managedEvents/managedEventReassign.schema"; import { ZGetRoundRobinHostsInputSchema } from "./roundRobin/getRoundRobinHostsToReasign.schema"; import { ZRoundRobinManualReassignInputSchema } from "./roundRobin/roundRobinManualReassign.schema"; import { ZRoundRobinReassignInputSchema } from "./roundRobin/roundRobinReassign.schema"; import { ZSetInviteExpirationInputSchema } from "./setInviteExpiration.schema"; import { ZSkipTeamTrialsInputSchema } from "./skipTeamTrials.schema"; +import { ZSkipTrialForTeamInputSchema } from "./skipTrialForTeam.schema"; import { ZUpdateInputSchema } from "./update.schema"; import { ZUpdateInternalNotesPresetsInputSchema } from "./updateInternalNotesPresets.schema"; import { ZUpdateMembershipInputSchema } from "./updateMembership.schema"; @@ -179,8 +181,8 @@ export const viewerTeamsRouter = router({ .input(ZGetManagedEventUsersToReassignInputSchema) .query(async (opts) => { const { default: handler } = await import("./managedEvents/getManagedEventUsersToReassign.handler"); - return handler(opts); - }), + return handler(opts); + }), checkIfMembershipExists: authedProcedure .input(ZCheckIfMembershipExistsInputSchema) .mutation(async (opts) => { @@ -215,4 +217,12 @@ export const viewerTeamsRouter = router({ const { default: handler } = await import("./skipTeamTrials.handler"); return handler(opts); }), + skipTrialForTeam: authedProcedure.input(ZSkipTrialForTeamInputSchema).mutation(async (opts) => { + const { default: handler } = await import("./skipTrialForTeam.handler"); + return handler(opts); + }), + getSubscriptionStatus: authedProcedure.input(ZGetSubscriptionStatusInputSchema).query(async (opts) => { + const { default: handler } = await import("./getSubscriptionStatus.handler"); + return handler(opts); + }), }); diff --git a/packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.handler.ts b/packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.handler.ts new file mode 100644 index 0000000000..02bd40f8d9 --- /dev/null +++ b/packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.handler.ts @@ -0,0 +1,83 @@ +import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing"; +import { SubscriptionStatus } from "@calcom/ee/billing/repository/billing/IBillingRepository"; +import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository"; +import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service"; +import { TeamService } from "@calcom/features/ee/teams/services/teamService"; +import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants"; +import logger from "@calcom/lib/logger"; +import { MembershipRole } from "@calcom/prisma/enums"; +import { TRPCError } from "@trpc/server"; + +import type { TrpcSessionUser } from "../../../types"; +import type { TGetSubscriptionStatusInputSchema } from "./getSubscriptionStatus.schema"; + +const log = logger.getSubLogger({ prefix: ["getSubscriptionStatus"] }); + +type GetSubscriptionStatusOptions = { + ctx: { + user: NonNullable; + }; + input: TGetSubscriptionStatusInputSchema; +}; + +export const getSubscriptionStatusHandler = async ({ ctx, input }: GetSubscriptionStatusOptions) => { + if (!IS_TEAM_BILLING_ENABLED) { + return { status: null, isTrialing: false }; + } + + const { teamId } = input; + + const membershipRepository = new MembershipRepository(); + const membership = await membershipRepository.findUniqueByUserIdAndTeamId({ + userId: ctx.user.id, + teamId, + }); + + if (!membership || !membership.accepted) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "You are not a member of this team", + }); + } + + const team = await TeamService.fetchTeamOrThrow(teamId); + const permissionService = new PermissionCheckService(); + const hasManageBillingPermission = await permissionService.checkPermission({ + userId: ctx.user.id, + teamId, + permission: team.isOrganization ? "organization.manageBilling" : "team.manageBilling", + fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER], + }); + + if (!hasManageBillingPermission) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Only team owners and admins can view subscription status", + }); + } + + try { + const teamBillingServiceFactory = getTeamBillingServiceFactory(); + const teamBillingService = await teamBillingServiceFactory.findAndInit(teamId); + + const subscriptionStatus = await teamBillingService.getSubscriptionStatus(); + + log.debug(`Subscription status for team ${teamId}: ${subscriptionStatus}`); + + return { + status: subscriptionStatus, + isTrialing: subscriptionStatus === SubscriptionStatus.TRIALING, + }; + } catch (error) { + if (error instanceof TRPCError) { + throw error; + } + log.error("Error getting subscription status", error); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "Failed to get subscription status", + }); + } +}; + +export default getSubscriptionStatusHandler; diff --git a/packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.schema.ts b/packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.schema.ts new file mode 100644 index 0000000000..1226919a31 --- /dev/null +++ b/packages/trpc/server/routers/viewer/teams/getSubscriptionStatus.schema.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; + +export const ZGetSubscriptionStatusInputSchema = z.object({ + teamId: z.number(), +}); + +export type TGetSubscriptionStatusInputSchema = z.infer; diff --git a/packages/trpc/server/routers/viewer/teams/skipTrialForTeam.handler.ts b/packages/trpc/server/routers/viewer/teams/skipTrialForTeam.handler.ts new file mode 100644 index 0000000000..d12725999e --- /dev/null +++ b/packages/trpc/server/routers/viewer/teams/skipTrialForTeam.handler.ts @@ -0,0 +1,96 @@ +import { getTeamBillingServiceFactory } from "@calcom/ee/billing/di/containers/Billing"; +import { SubscriptionStatus } from "@calcom/ee/billing/repository/billing/IBillingRepository"; +import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository"; +import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository"; +import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service"; +import { IS_TEAM_BILLING_ENABLED } from "@calcom/lib/constants"; +import logger from "@calcom/lib/logger"; +import { prisma } from "@calcom/prisma"; +import { MembershipRole } from "@calcom/prisma/enums"; +import { TRPCError } from "@trpc/server"; + +import type { TrpcSessionUser } from "../../../types"; +import type { TSkipTrialForTeamInputSchema } from "./skipTrialForTeam.schema"; + +const log = logger.getSubLogger({ prefix: ["skipTrialForTeam"] }); + +type SkipTrialForTeamOptions = { + ctx: { + user: NonNullable; + }; + input: TSkipTrialForTeamInputSchema; +}; + +export const skipTrialForTeamHandler = async ({ ctx, input }: SkipTrialForTeamOptions) => { + if (!IS_TEAM_BILLING_ENABLED) return { success: true }; + + const { teamId } = input; + + const membershipRepository = new MembershipRepository(); + const membership = await membershipRepository.findUniqueByUserIdAndTeamId({ + userId: ctx.user.id, + teamId, + }); + + if (!membership || !membership.accepted) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "You are not a member of this team", + }); + } + + try { + const teamRepository = new TeamRepository(prisma); + const team = await teamRepository.findById({ id: teamId }); + + if (!team) { + throw new TRPCError({ + code: "NOT_FOUND", + message: "Team not found", + }); + } + + const permissionService = new PermissionCheckService(); + const hasManageBillingPermission = await permissionService.checkPermission({ + userId: ctx.user.id, + teamId, + permission: team.isOrganization ? "organization.manageBilling" : "team.manageBilling", + fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER], + }); + + if (!hasManageBillingPermission) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Only team owners and admins can skip the trial", + }); + } + + const teamBillingServiceFactory = getTeamBillingServiceFactory(); + const teamBillingService = teamBillingServiceFactory.init(team); + + const subscriptionStatus = await teamBillingService.getSubscriptionStatus(); + + if (subscriptionStatus !== SubscriptionStatus.TRIALING) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Team is not currently in trial", + }); + } + + await teamBillingService.endTrial(); + log.info(`Ended trial for team ${teamId}`); + + return { success: true }; + } catch (error) { + if (error instanceof TRPCError) { + throw error; + } + log.error("Error skipping trial for team", error); + throw new TRPCError({ + code: "INTERNAL_SERVER_ERROR", + message: "Failed to skip trial for team", + }); + } +}; + +export default skipTrialForTeamHandler; diff --git a/packages/trpc/server/routers/viewer/teams/skipTrialForTeam.schema.ts b/packages/trpc/server/routers/viewer/teams/skipTrialForTeam.schema.ts new file mode 100644 index 0000000000..a6fa23ff21 --- /dev/null +++ b/packages/trpc/server/routers/viewer/teams/skipTrialForTeam.schema.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; + +export const ZSkipTrialForTeamInputSchema = z.object({ + teamId: z.number(), +}); + +export type TSkipTrialForTeamInputSchema = z.infer;