feat: add skip trial feature for teams/orgs billing page (#26584)
* feat: add skip trial feature for teams/orgs billing page Co-Authored-By: [email protected] <[email protected]> * feat: add translation strings for skip trial feature and fix lint-staged config Co-Authored-By: [email protected] <[email protected]> * fix: use IS_TEAM_BILLING_ENABLED instead of IS_SELF_HOSTED Co-Authored-By: [email protected] <[email protected]> * fix: use correct DialogHeader props in billing-view.tsx Co-Authored-By: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * add pbac to skip team handler --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
7 files changed
+281
-8
No files matched your search
@@ -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 (
|
||||
<>
|
||||
<div className="bg-cal-muted border-muted mt-5 rounded-xl border p-1">
|
||||
@@ -89,6 +123,21 @@ const BillingView = () => {
|
||||
{t("billing_portal")}
|
||||
</Button>
|
||||
</div>
|
||||
{isTrialing && (
|
||||
<div className="bg-default border-muted mt-1 flex rounded-[10px] border px-5 py-4">
|
||||
<div className="flex w-full flex-col gap-1">
|
||||
<h3 className="text-emphasis text-sm font-semibold leading-none">{t("skip_trial")}</h3>
|
||||
<p className="text-subtle text-sm font-medium leading-tight">{t("skip_trial_description")}</p>
|
||||
</div>
|
||||
<Button
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={() => setShowSkipTrialDialog(true)}
|
||||
loading={isLoadingStatus}>
|
||||
{t("skip_trial")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between px-4 py-5">
|
||||
<p className="text-subtle text-sm font-medium leading-tight">{t("need_help")}</p>
|
||||
<Button color="secondary" size="sm" onClick={onContactSupportClick}>
|
||||
@@ -97,6 +146,21 @@ const BillingView = () => {
|
||||
</div>
|
||||
</div>
|
||||
<BillingCredits />
|
||||
|
||||
<Dialog open={showSkipTrialDialog} onOpenChange={setShowSkipTrialDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader title={t("skip_trial_confirmation_title")} />
|
||||
<p className="text-subtle text-sm">{t("skip_trial_confirmation_description")}</p>
|
||||
<DialogFooter>
|
||||
<Button color="minimal" onClick={() => setShowSkipTrialDialog(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
<Button color="primary" onClick={handleSkipTrial} loading={skipTrialMutation.isPending}>
|
||||
{t("skip_trial")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
}),
|
||||
});
|
||||
@@ -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<TrpcSessionUser>;
|
||||
};
|
||||
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;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZGetSubscriptionStatusInputSchema = z.object({
|
||||
teamId: z.number(),
|
||||
});
|
||||
|
||||
export type TGetSubscriptionStatusInputSchema = z.infer<typeof ZGetSubscriptionStatusInputSchema>;
|
||||
@@ -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<TrpcSessionUser>;
|
||||
};
|
||||
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;
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ZSkipTrialForTeamInputSchema = z.object({
|
||||
teamId: z.number(),
|
||||
});
|
||||
|
||||
export type TSkipTrialForTeamInputSchema = z.infer<typeof ZSkipTrialForTeamInputSchema>;
|
||||
Reference in new issue
Block a user