feat: active user billing (#27867)

* factory and statergie

* chore: use correct method of DI

* feat: add onchagne

* add logic to HWM stat

* add webhook resolver methods to each statergy

* move seat tracking + webhooks over to own statergy

* Move to factory base approach

* move logic to correct class

* rename create -> createByTeamId

* fix: remove debug `true ||` overrides from IS_STRIPE_ENABLED and IS_TEAM_BILLING_ENABLED

Remove accidentally committed debug overrides that short-circuited
IS_STRIPE_ENABLED and IS_TEAM_BILLING_ENABLED to always be true,
bypassing Stripe credential checks. This would break self-hosted
instances without Stripe configured.

Identified by cubic (https://cubic.dev)

Co-Authored-By: unknown <>

* feat: active user billing

* add tests

* UI side for users on active billing

* use correct period of stripe sub

* feat: claude feedback

* fix: skip Stripe sync for canceled/expired subscriptions to prevent repeated API calls

Co-Authored-By: unknown <>

* feat: feedback

* feat: only render when active users mode is set

* fix type error

* fix: constants + feature flags

* fix: default to null in tests

* chore: use seats in test

* fix: use node:crypto protocol for Node.js builtin imports

Co-Authored-By: [email protected] <[email protected]>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-02-12 13:57:32 +00:00
1 parent bf348ee209
commit d52e2d9fad
28 files changed
+2327 -79

No files matched your search

@@ -35,6 +35,7 @@ const initialData: AppFlags = {
"booking-audit": false,
"monthly-proration": false,
"hwm-seating": false,
"active-user-billing": false,
"sidebar-tips": false,
};
@@ -9,7 +9,8 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader } from "@calcom/ui/co
import { showToast } from "@calcom/ui/components/toast";
import { usePathname } from "next/navigation";
import { useSession } from "next-auth/react";
import { useState } from "react";
import { useMemo, useState } from "react";
import { ActiveUserBreakdown } from "~/settings/billing/components/ActiveUserBreakdown";
import BillingCredits from "~/settings/billing/components/BillingCredits";
import { InvoicesTable } from "~/settings/billing/components/InvoicesTable";
@@ -51,25 +52,21 @@ const BillingView = () => {
const [showSkipTrialDialog, setShowSkipTrialDialog] = useState(false);
const utils = trpc.useUtils();
// Determine the billing context and extract appropriate team/org ID
const getTeamIdFromContext = () => {
const teamIdNumber = useMemo(() => {
if (!pathname) return null;
// Team billing: /settings/teams/{id}/billing
if (pathname.includes("/teams/") && pathname.includes("/billing")) {
const teamIdMatch = pathname.match(/\/teams\/(\d+)\/billing/);
return teamIdMatch ? teamIdMatch[1] : null;
return teamIdMatch ? parseInt(teamIdMatch[1], 10) : null;
}
// Organization billing: /settings/organizations/billing
if (pathname.includes("/organizations/billing")) {
const orgId = session.data?.user?.org?.id;
return typeof orgId === "number" ? orgId.toString() : null;
return typeof orgId === "number" ? orgId : null;
}
};
const teamId = getTeamIdFromContext();
const teamIdNumber = teamId ? parseInt(teamId, 10) : null;
return null;
}, [pathname, session.data?.user?.org?.id]);
const { data: subscriptionStatus, isLoading: isLoadingStatus } =
trpc.viewer.teams.getSubscriptionStatus.useQuery(
@@ -91,8 +88,8 @@ const BillingView = () => {
},
});
const billingHref = teamId
? `/api/integrations/stripepayment/portal?teamId=${teamId}&returnTo=${WEBAPP_URL}${returnTo}`
const billingHref = teamIdNumber
? `/api/integrations/stripepayment/portal?teamId=${teamIdNumber}&returnTo=${WEBAPP_URL}${returnTo}`
: `/api/integrations/stripepayment/portal?returnTo=${WEBAPP_URL}${returnTo}`;
const onContactSupportClick = async () => {
@@ -146,6 +143,9 @@ const BillingView = () => {
</div>
</div>
<BillingCredits />
{teamIdNumber && subscriptionStatus?.billingMode === "ACTIVE_USERS" && (
<ActiveUserBreakdown teamId={teamIdNumber} />
)}
<InvoicesTable />
<Dialog open={showSkipTrialDialog} onOpenChange={setShowSkipTrialDialog}>
@@ -0,0 +1,256 @@
"use client";
import { useEffect, useState } from "react";
import dayjs from "@calcom/dayjs";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Badge } from "@coss/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { PanelCard } from "@calcom/ui/components/card";
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetPanel,
SheetTitle,
SheetClose,
} from "@coss/ui/components/sheet";
import { Skeleton } from "@coss/ui/components/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@coss/ui/components/table";
import { ActiveUserBreakdownSkeleton } from "./ActiveUserBreakdownSkeleton";
const PAGE_SIZE = 10;
export function ActiveUserBreakdown({ teamId }: { teamId: number }) {
const { data, isLoading } = trpc.viewer.teams.getActiveUserBreakdown.useQuery(
{ teamId },
{ enabled: !!teamId }
);
if (isLoading) return <ActiveUserBreakdownSkeleton />;
if (!data) return null;
return <ActiveUserBreakdownContent data={data} teamId={teamId} />;
}
type BreakdownData = {
activeUsers: Array<{ id: number; email: string; name: string | null; activeAs: "host" | "attendee" }>;
totalMembers: number;
activeHosts: number;
activeAttendees: number;
periodStart: string;
periodEnd: string;
pricePerSeat: number | null;
};
type SelectedUser = {
id: number;
email: string;
name: string | null;
activeAs: "host" | "attendee";
};
function ActiveUserBreakdownContent({ data, teamId }: { data: BreakdownData; teamId: number }) {
const { t } = useLocale();
const [currentPage, setCurrentPage] = useState(0);
const [selectedUser, setSelectedUser] = useState<SelectedUser | null>(null);
const { activeUsers, totalMembers, activeHosts, activeAttendees, periodStart, periodEnd } = data;
useEffect(() => {
setCurrentPage(0);
}, [activeUsers]);
const totalPages = Math.ceil(activeUsers.length / PAGE_SIZE);
const paginatedUsers = activeUsers.slice(currentPage * PAGE_SIZE, (currentPage + 1) * PAGE_SIZE);
const formattedStart = dayjs.utc(periodStart).format("MMM D, YYYY");
const formattedEnd = dayjs.utc(periodEnd).format("MMM D, YYYY");
return (
<>
<PanelCard
title={t("active_users_billing")}
subtitle={t("active_users_billing_description", {
start: formattedStart,
end: formattedEnd,
})}
className="mt-5">
<div className="px-5 py-3">
<p className="text-subtle text-sm font-medium">
{t("active_users_summary", {
hosts: activeHosts,
attendees: activeAttendees,
active: activeHosts + activeAttendees,
total: totalMembers,
})}
</p>
</div>
{activeUsers.length === 0 ? (
<div className="text-subtle p-6 text-center text-sm">{t("no_active_users")}</div>
) : (
<>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("name")}</TableHead>
<TableHead>{t("email")}</TableHead>
<TableHead>{t("status")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{paginatedUsers.map((user) => (
<TableRow
key={user.id}
className="cursor-pointer"
onClick={() => setSelectedUser(user)}>
<TableCell>{user.name || "-"}</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
{user.activeAs === "host" ? (
<Badge variant="success">{t("active_as_host")}</Badge>
) : (
<Badge variant="info">{t("active_as_attendee")}</Badge>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
{totalPages > 1 && (
<div className="border-muted flex items-center justify-end gap-2 border-t px-4 py-3">
<Button
color="secondary"
size="sm"
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 0}
StartIcon="arrow-left">
{t("previous")}
</Button>
<Button
color="secondary"
size="sm"
onClick={() => setCurrentPage(currentPage + 1)}
disabled={currentPage >= totalPages - 1}
EndIcon="arrow-right">
{t("next")}
</Button>
</div>
)}
</>
)}
</PanelCard>
<Sheet open={!!selectedUser} onOpenChange={(open) => !open && setSelectedUser(null)}>
<SheetContent side="right" inset>
<SheetHeader>
<SheetTitle>{selectedUser?.name || selectedUser?.email}</SheetTitle>
<SheetDescription>
<span className="flex items-center gap-2">
{selectedUser?.email}
{selectedUser?.activeAs === "host" ? (
<Badge variant="success">{t("active_as_host")}</Badge>
) : (
<Badge variant="info">{t("active_as_attendee")}</Badge>
)}
</span>
</SheetDescription>
</SheetHeader>
<SheetPanel>
{selectedUser && (
<UserBookingsSheet
teamId={teamId}
userId={selectedUser.id}
activeAs={selectedUser.activeAs}
/>
)}
</SheetPanel>
<SheetFooter>
<SheetClose render={<Button color="secondary">{t("close")}</Button>} />
</SheetFooter>
</SheetContent>
</Sheet>
</>
);
}
function UserBookingsSheet({
teamId,
userId,
activeAs,
}: {
teamId: number;
userId: number;
activeAs: "host" | "attendee";
}) {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.teams.getActiveUserBookings.useQuery(
{ teamId, userId, activeAs },
{ enabled: true }
);
if (isLoading) {
return (
<div className="flex flex-col gap-3">
<Skeleton className="h-8 w-24" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-full" />
</div>
);
}
const bookings = data?.bookings ?? [];
return (
<div className="flex flex-col gap-4">
<div className="flex items-baseline gap-2">
<span className="text-2xl font-bold">{bookings.length}</span>
<span className="text-muted-foreground text-sm">
{bookings.length === 1 ? t("booking") : t("bookings")}
</span>
</div>
{bookings.length === 0 ? (
<p className="text-muted-foreground text-sm">{t("no_bookings")}</p>
) : (
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("booking")}</TableHead>
<TableHead>{t("date")}</TableHead>
<TableHead>{activeAs === "host" ? t("attendees") : t("host")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{bookings.map((booking) => (
<TableRow key={booking.id}>
<TableCell className="font-medium">{booking.title}</TableCell>
<TableCell className="text-muted-foreground">
{dayjs.utc(booking.startTime).format("MMM D, YYYY h:mm A")}
</TableCell>
<TableCell className="text-muted-foreground">{booking.otherParty || "-"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
);
}
@@ -0,0 +1,29 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { PanelCard } from "@calcom/ui/components/card";
import { SkeletonText } from "@calcom/ui/components/skeleton";
export function ActiveUserBreakdownSkeleton() {
const { t } = useLocale();
return (
<PanelCard title={t("active_users_billing")} className="mt-5">
<div className="p-4">
<SkeletonText className="mb-4 h-4 w-64" />
<div className="mb-3 flex gap-4 border-b pb-3">
<SkeletonText className="h-4 w-32" />
<SkeletonText className="h-4 w-40" />
<SkeletonText className="h-4 w-20" />
</div>
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="flex gap-4 py-3">
<SkeletonText className="h-4 w-32" />
<SkeletonText className="h-4 w-40" />
<SkeletonText className="h-4 w-20" />
</div>
))}
</div>
</PanelCard>
);
}
@@ -2173,6 +2173,13 @@
"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",
"active_users_billing": "Active users",
"active_users_billing_description": "Billing period: {{start}} - {{end}}",
"active_as_host": "Host",
"active_as_attendee": "Attendee",
"inactive_member": "Inactive",
"active_users_summary": "{{hosts}} hosts + {{attendees}} attendees = {{active}} active of {{total}} members",
"no_active_users": "No active users in this billing 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",