From aaf5958b7d6a37401187dd1c6b75e66547d9e400 Mon Sep 17 00:00:00 2001 From: sean-brydon <55134778+sean-brydon@users.noreply.github.com> Date: Tue, 13 Jan 2026 10:34:52 +0000 Subject: [PATCH] feat: adds admin billing section (#26747) * feat: adds admin billing section * use loading prop * add log on resend error * add error log in billing portal --- .../(admin-layout)/admin/billing/page.tsx | 25 ++++++ .../SettingsLayoutAppDirClient.tsx | 18 ++-- .../modules/settings/admin/billing-view.tsx | 7 ++ .../modules/settings/admin/license-view.tsx | 85 +++++++++++++++++++ apps/web/public/static/locales/en/common.json | 17 ++++ .../server/routers/viewer/admin/_router.ts | 32 ++++--- .../viewer/admin/billingPortalLink.handler.ts | 74 ++++++++++++++++ .../viewer/admin/billingPortalLink.schema.ts | 5 ++ .../resendPurchaseCompleteEmail.handler.ts | 63 ++++++++++++++ .../resendPurchaseCompleteEmail.schema.ts | 7 ++ 10 files changed, 315 insertions(+), 18 deletions(-) create mode 100644 apps/web/app/(use-page-wrapper)/settings/(admin-layout)/admin/billing/page.tsx create mode 100644 apps/web/modules/settings/admin/billing-view.tsx create mode 100644 apps/web/modules/settings/admin/license-view.tsx create mode 100644 packages/trpc/server/routers/viewer/admin/billingPortalLink.handler.ts create mode 100644 packages/trpc/server/routers/viewer/admin/billingPortalLink.schema.ts create mode 100644 packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.handler.ts create mode 100644 packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.schema.ts diff --git a/apps/web/app/(use-page-wrapper)/settings/(admin-layout)/admin/billing/page.tsx b/apps/web/app/(use-page-wrapper)/settings/(admin-layout)/admin/billing/page.tsx new file mode 100644 index 0000000000..f8590cec25 --- /dev/null +++ b/apps/web/app/(use-page-wrapper)/settings/(admin-layout)/admin/billing/page.tsx @@ -0,0 +1,25 @@ +import { _generateMetadata, getTranslate } from "app/_utils"; + +import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader"; + +import AdminBillingView from "~/settings/admin/billing-view"; + +export const generateMetadata = async () => + await _generateMetadata( + (t) => t("admin_billing_title"), + (t) => t("admin_billing_description"), + undefined, + undefined, + "/settings/admin/billing" + ); + +const Page = async () => { + const t = await getTranslate(); + return ( + + + + ); +}; + +export default Page; diff --git a/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/SettingsLayoutAppDirClient.tsx b/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/SettingsLayoutAppDirClient.tsx index 1dded19804..a4fd91b02e 100644 --- a/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/SettingsLayoutAppDirClient.tsx +++ b/apps/web/app/(use-page-wrapper)/settings/(settings-layout)/SettingsLayoutAppDirClient.tsx @@ -220,6 +220,11 @@ const getTabs = (orgBranding: OrganizationBranding | null) => { href: "/auth/setup?step=1", trackingMetadata: { section: "admin", page: "license" }, }, + { + name: "admin_billing", + href: "/settings/admin/billing", + trackingMetadata: { section: "admin", page: "billing" }, + }, { name: "impersonation", href: "/settings/admin/impersonation", @@ -673,12 +678,13 @@ const SettingsSidebarContainer = ({ const searchParams = useCompatSearchParams(); const orgBranding = useOrgBranding(); const { t } = useLocale(); - const [otherTeamMenuState, setOtherTeamMenuState] = useState< - { - teamId: number | undefined; - teamMenuOpen: boolean; - }[] - >(); + const [otherTeamMenuState, setOtherTeamMenuState] = + useState< + { + teamId: number | undefined; + teamMenuOpen: boolean; + }[] + >(); const session = useSession(); const organizationId = session.data?.user?.org?.id; diff --git a/apps/web/modules/settings/admin/billing-view.tsx b/apps/web/modules/settings/admin/billing-view.tsx new file mode 100644 index 0000000000..9aa8a9f3cc --- /dev/null +++ b/apps/web/modules/settings/admin/billing-view.tsx @@ -0,0 +1,7 @@ +"use client"; + +import LicenseView from "./license-view"; + +export default function AdminBillingView() { + return ; +} diff --git a/apps/web/modules/settings/admin/license-view.tsx b/apps/web/modules/settings/admin/license-view.tsx new file mode 100644 index 0000000000..3b37456d52 --- /dev/null +++ b/apps/web/modules/settings/admin/license-view.tsx @@ -0,0 +1,85 @@ +"use client"; + +import { useState } from "react"; + +import { IS_CALCOM } from "@calcom/lib/constants"; +import { useLocale } from "@calcom/lib/hooks/useLocale"; +import { trpc } from "@calcom/trpc/react"; +import { Button } from "@calcom/ui/components/button"; +import { PanelCard } from "@calcom/ui/components/card"; +import { TextField } from "@calcom/ui/components/form"; +import { showToast } from "@calcom/ui/components/toast"; + +export default function LicenseView() { + const { t } = useLocale(); + const [billingEmail, setBillingEmail] = useState(""); + + const resendEmailMutation = trpc.viewer.admin.resendPurchaseCompleteEmail.useMutation({ + onSuccess: () => { + showToast(t("admin_license_resend_success"), "success"); + }, + onError: (error) => { + showToast(error.message || t("admin_license_resend_error"), "error"); + }, + }); + + const billingPortalMutation = trpc.viewer.admin.billingPortalLink.useMutation({ + onSuccess: (data) => { + if (!data?.url) { + showToast(t("admin_license_portal_missing_url"), "error"); + return; + } + + window.open(data.url, "_blank", "noopener,noreferrer"); + }, + onError: (error) => { + showToast(error.message || t("admin_license_portal_error"), "error"); + }, + }); + + const showResendSection = IS_CALCOM; + + return ( +
+ {showResendSection && ( + +
+
+ setBillingEmail(event.target.value)} + /> + +
+
+
+ )} + + +
+ +
+
+
+ ); +} diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json index 0d11fc875b..378f98fc4d 100644 --- a/apps/web/public/static/locales/en/common.json +++ b/apps/web/public/static/locales/en/common.json @@ -2150,6 +2150,23 @@ "admin_orgs_edit_description": "Here you can edit an organization.", "admin_oAuth_description": "Add new OAuth clients", "admin_lockedSMS_description": "Lock or unlock SMS sending for users", + "admin_license_description": "Manage license billing for this deployment", + "admin_billing": "Billing", + "admin_billing_title": "Admin billing", + "admin_billing_description": "Manage billing emails and Stripe portal access for licenses.", + "admin_license_resend_title": "Resend purchase confirmation", + "admin_license_resend_description": "Send the purchase confirmation email to a billing address.", + "admin_license_billing_email_label": "Billing email", + "admin_license_billing_email_placeholder": "customer@example.com", + "admin_license_resend_button": "Resend email", + "admin_license_resend_success": "Purchase confirmation email sent.", + "admin_license_resend_error": "Failed to resend purchase confirmation email.", + "admin_license_portal_title": "Billing portal", + "admin_license_portal_description": "Open the Stripe billing portal for this license.", + "admin_license_portal_button": "Open billing portal", + "admin_license_portal_missing_url": "Billing portal link was not returned.", + "admin_license_portal_error": "Failed to fetch billing portal link.", + "admin_license_self_hosted_only": "License billing tools are available for self-hosted deployments only.", "no_available_apps": "There are no available apps", "no_available_apps_description": "Please ensure there are apps in your deployment under 'packages/app-store'", "no_apps": "There are no apps enabled in this instance of Cal.com", diff --git a/packages/trpc/server/routers/viewer/admin/_router.ts b/packages/trpc/server/routers/viewer/admin/_router.ts index c7024dc144..2d42b77a24 100644 --- a/packages/trpc/server/routers/viewer/admin/_router.ts +++ b/packages/trpc/server/routers/viewer/admin/_router.ts @@ -1,11 +1,13 @@ import { authedAdminProcedure } from "../../../procedures/authedProcedure"; import { router } from "../../../trpc"; import { ZAdminAssignFeatureToTeamSchema } from "./assignFeatureToTeam.schema"; +import { ZBillingPortalLinkSchema } from "./billingPortalLink.schema"; import { ZCreateSelfHostedLicenseSchema } from "./createSelfHostedLicenseKey.schema"; import { ZAdminGetTeamsForFeatureSchema } from "./getTeamsForFeature.schema"; import { ZListMembersSchema } from "./listPaginated.schema"; import { ZAdminLockUserAccountSchema } from "./lockUserAccount.schema"; import { ZAdminRemoveTwoFactor } from "./removeTwoFactor.schema"; +import { ZResendPurchaseCompleteEmailSchema } from "./resendPurchaseCompleteEmail.schema"; import { ZAdminPasswordResetSchema } from "./sendPasswordReset.schema"; import { ZSetSMSLockState } from "./setSMSLockState.schema"; import { toggleFeatureFlag } from "./toggleFeatureFlag.procedure"; @@ -56,6 +58,16 @@ export const adminRouter = router({ const { default: handler } = await import("./createSelfHostedLicenseKey.handler"); return handler(opts); }), + resendPurchaseCompleteEmail: authedAdminProcedure + .input(ZResendPurchaseCompleteEmailSchema) + .mutation(async (opts) => { + const { default: handler } = await import("./resendPurchaseCompleteEmail.handler"); + return handler(opts); + }), + billingPortalLink: authedAdminProcedure.input(ZBillingPortalLinkSchema).mutation(async (opts) => { + const { default: handler } = await import("./billingPortalLink.handler"); + return handler(opts); + }), verifyWorkflows: authedAdminProcedure.input(ZAdminVerifyWorkflowsSchema).mutation(async (opts) => { const { default: handler } = await import("./verifyWorkflows.handler"); return handler(opts); @@ -64,18 +76,14 @@ export const adminRouter = router({ const { default: handler } = await import("./whitelistUserWorkflows.handler"); return handler(opts); }), - getTeamsForFeature: authedAdminProcedure - .input(ZAdminGetTeamsForFeatureSchema) - .query(async (opts) => { - const { default: handler } = await import("./getTeamsForFeature.handler"); - return handler(opts); - }), - assignFeatureToTeam: authedAdminProcedure - .input(ZAdminAssignFeatureToTeamSchema) - .mutation(async (opts) => { - const { default: handler } = await import("./assignFeatureToTeam.handler"); - return handler(opts); - }), + getTeamsForFeature: authedAdminProcedure.input(ZAdminGetTeamsForFeatureSchema).query(async (opts) => { + const { default: handler } = await import("./getTeamsForFeature.handler"); + return handler(opts); + }), + assignFeatureToTeam: authedAdminProcedure.input(ZAdminAssignFeatureToTeamSchema).mutation(async (opts) => { + const { default: handler } = await import("./assignFeatureToTeam.handler"); + return handler(opts); + }), unassignFeatureFromTeam: authedAdminProcedure .input(ZAdminUnassignFeatureFromTeamSchema) .mutation(async (opts) => { diff --git a/packages/trpc/server/routers/viewer/admin/billingPortalLink.handler.ts b/packages/trpc/server/routers/viewer/admin/billingPortalLink.handler.ts new file mode 100644 index 0000000000..0975f1d065 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/billingPortalLink.handler.ts @@ -0,0 +1,74 @@ +import { z } from "zod"; + +import { createSignature, generateNonce } from "@calcom/features/ee/common/server/private-api-utils"; +import { + getDeploymentKey, + getDeploymentSignatureToken, +} from "@calcom/features/ee/deployment/lib/getDeploymentKey"; +import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository"; +import { CALCOM_PRIVATE_API_ROUTE } from "@calcom/lib/constants"; +import logger from "@calcom/lib/logger"; +import { prisma } from "@calcom/prisma"; + +import type { TrpcSessionUser } from "../../../types"; +import type { TBillingPortalLinkSchema } from "./billingPortalLink.schema"; + +type GetOptions = { + ctx: { + user: NonNullable; + }; + input: TBillingPortalLinkSchema; +}; + +const billingPortalLinkHandler = async ({ input }: GetOptions) => { + if (!CALCOM_PRIVATE_API_ROUTE) { + throw new Error("Private API route does not exist in .env"); + } + + const deploymentRepo = new DeploymentRepository(prisma); + const [licenseKey, signatureToken] = await Promise.all([ + getDeploymentKey(deploymentRepo), + getDeploymentSignatureToken(deploymentRepo), + ]); + + if (!licenseKey) { + throw new Error("License key is missing"); + } + + if (!signatureToken) { + throw new Error("Signature token is missing"); + } + + const nonce = generateNonce(); + const signature = createSignature(input, nonce, signatureToken); + + const response = await fetch(`${CALCOM_PRIVATE_API_ROUTE}/v1/license/billing-portal-link`, { + method: "POST", + headers: { + "Content-Type": "application/json", + nonce, + signature, + "x-cal-license-key": licenseKey, + }, + body: JSON.stringify(input), + signal: AbortSignal.timeout(2000), + }); + + const data = await response.json(); + + if (!response.ok) { + logger.warn("Failed to fetch billing portal link", { + message: data?.message, + status: response.status, + }); + throw new Error(data?.message || "Failed to fetch billing portal link"); + } + + const schema = z.object({ + url: z.string(), + }); + + return schema.parse(data); +}; + +export default billingPortalLinkHandler; diff --git a/packages/trpc/server/routers/viewer/admin/billingPortalLink.schema.ts b/packages/trpc/server/routers/viewer/admin/billingPortalLink.schema.ts new file mode 100644 index 0000000000..64bd60e71f --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/billingPortalLink.schema.ts @@ -0,0 +1,5 @@ +import { z } from "zod"; + +export const ZBillingPortalLinkSchema = z.object({}); + +export type TBillingPortalLinkSchema = z.infer; diff --git a/packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.handler.ts b/packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.handler.ts new file mode 100644 index 0000000000..2a51ff2987 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.handler.ts @@ -0,0 +1,63 @@ +import { z } from "zod"; + +import { createSignature, generateNonce } from "@calcom/features/ee/common/server/private-api-utils"; +import { getDeploymentSignatureToken } from "@calcom/features/ee/deployment/lib/getDeploymentKey"; +import { DeploymentRepository } from "@calcom/features/ee/deployment/repositories/DeploymentRepository"; +import { CALCOM_PRIVATE_API_ROUTE } from "@calcom/lib/constants"; +import logger from "@calcom/lib/logger"; +import { prisma } from "@calcom/prisma"; + +import type { TrpcSessionUser } from "../../../types"; +import type { TResendPurchaseCompleteEmailSchema } from "./resendPurchaseCompleteEmail.schema"; + +type GetOptions = { + ctx: { + user: NonNullable; + }; + input: TResendPurchaseCompleteEmailSchema; +}; + +const resendPurchaseCompleteEmailHandler = async ({ input }: GetOptions) => { + if (!CALCOM_PRIVATE_API_ROUTE) { + throw new Error("Private API route does not exist in .env"); + } + + const deploymentRepo = new DeploymentRepository(prisma); + const signatureToken = await getDeploymentSignatureToken(deploymentRepo); + + if (!signatureToken) { + throw new Error("Signature token is missing"); + } + + const nonce = generateNonce(); + const signature = createSignature(input, nonce, signatureToken); + + const response = await fetch(`${CALCOM_PRIVATE_API_ROUTE}/v1/license/purchase-complete-email/resend`, { + method: "POST", + headers: { + "Content-Type": "application/json", + nonce, + signature, + }, + body: JSON.stringify(input), + signal: AbortSignal.timeout(2000), + }); + + const data = await response.json(); + + if (!response.ok) { + logger.warn("Failed to resend purchase complete email", { + message: data?.message, + status: response.status, + }); + throw new Error(data?.message || "Failed to resend purchase complete email"); + } + + const schema = z.object({ + success: z.boolean(), + }); + + return schema.parse(data); +}; + +export default resendPurchaseCompleteEmailHandler; diff --git a/packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.schema.ts b/packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.schema.ts new file mode 100644 index 0000000000..921b2d9073 --- /dev/null +++ b/packages/trpc/server/routers/viewer/admin/resendPurchaseCompleteEmail.schema.ts @@ -0,0 +1,7 @@ +import { z } from "zod"; + +export const ZResendPurchaseCompleteEmailSchema = z.object({ + billingEmail: z.string().email(), +}); + +export type TResendPurchaseCompleteEmailSchema = z.infer;