Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(billing): meter-tile product cards with inline usage details (#8492)

Andrew Huangcec3f07a45b2
diff --git a/frontend/src/components/license/UpgradeGate/index.ts b/frontend/src/components/license/UpgradeGate/index.ts
index 8f5fe8e1c5..df205081a1 100644
--- a/frontend/src/components/license/UpgradeGate/index.ts
+++ b/frontend/src/components/license/UpgradeGate/index.ts
@@ -63,6 +63,7 @@ export {
SecretRotationsUpgradeIntent,
SecretsBrokeringUpgradeIntent,
SecretScanningUpgradeIntent,
+ SecretsManagementUpgradeIntent,
UpgradeFeature
} from "./upgrade-intents";
export { UpgradeGate } from "./UpgradeGate";
diff --git a/frontend/src/components/license/UpgradeGate/upgrade-intents.ts b/frontend/src/components/license/UpgradeGate/upgrade-intents.ts
index 70fe3d88a0..5e3ed97f4f 100644
--- a/frontend/src/components/license/UpgradeGate/upgrade-intents.ts
+++ b/frontend/src/components/license/UpgradeGate/upgrade-intents.ts
@@ -11,6 +11,7 @@ export const BillingPlan = {
} as const;
export const UpgradeFeature = {
+ SecretsManagement: "secrets-management",
DynamicSecrets: "dynamic-secrets",
SecretRotations: "secret-rotations",
HoneyTokens: "honey-tokens",
@@ -54,6 +55,16 @@ export type UpgradeIntent = {
quota?: { used: number; limit: number };
};
+export const SecretsManagementUpgradeIntent = {
+ featureKey: UpgradeFeature.SecretsManagement,
+ productKey: BillingProduct.SecretsManagement,
+ planKey: BillingPlan.Pro,
+ upgradeLabel: "Unlock Secrets Management",
+ title: "Open Secrets Management",
+ description:
+ "Secrets Management is included with the Pro plan. Review the plans or start a free trial to continue."
+} satisfies UpgradeIntent;
+
export const DynamicSecretsUpgradeIntent = {
featureKey: UpgradeFeature.DynamicSecrets,
productKey: BillingProduct.SecretsManagement,
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index bed38b5cd4..40b29fdba7 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -42,7 +42,7 @@ const ORG_PAGE_SIZE = 10;
// from the "commit and save" nudge) instead of the default plans view.
type BillingV2Flow =
| { type: "sheet"; prodId: string; view?: "commitment" }
- | { type: "breakdown"; prodId: string };
+ | { type: "breakdown"; prodId: string; dimensionKey?: string };
export const BillingV2Page = () => {
const { t } = useTranslation();
@@ -203,8 +203,8 @@ export const BillingV2Page = () => {
setFlow({ type: "sheet", prodId: productId, view: "commitment" });
};
- const onViewBreakdown = (productId: string) => {
- setFlow({ type: "breakdown", prodId: productId });
+ const onViewBreakdown = (productId: string, dimensionKey?: string) => {
+ setFlow({ type: "breakdown", prodId: productId, dimensionKey });
};
const hasActiveSubscription = overview?.subState === "active";
@@ -318,6 +318,8 @@ export const BillingV2Page = () => {
setBreakdownScope("organization");
setSelectedOrgId(nextId);
}}
+ breakdownOrgId={selectedOrgId}
+ breakdownScope={showOrgFilter ? breakdownScope : "organization"}
onSearchOrgs={setOrgSearch}
showOrgFilter={showOrgFilter}
onUpdatePayment={onUpdatePayment}
@@ -364,6 +366,7 @@ export const BillingV2Page = () => {
scope={showOrgFilter ? breakdownScope : "organization"}
prod={catalogById(catalog, flow.prodId)!}
entitlement={overview?.entitlements[flow.prodId]}
+ initialDimensionKey={flow.dimensionKey}
onClose={close}
/>
)}
diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
index 1e50a3b68d..0f5aa55465 100644
--- a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
@@ -30,6 +30,12 @@ export const billingV2ErrorCode = (error: unknown): string | undefined =>
export const fmtMoney = (n: number, maximumFractionDigits = 0): string =>
`$${Number(n).toLocaleString("en-US", { maximumFractionDigits })}`;
+// Whole dollars stay whole ("$408"); any fractional amount always shows cents ("$22.20", "$0.60").
+export const fmtMoneyCents = (n: number): string =>
+ Number.isInteger(n)
+ ? fmtMoney(n)
+ : `$${Number(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
+
// Pluralize a singular dimension noun (the catalog's "noun" field) for display beside a count, since
// a limit meter always reads as a plural quantity ("0 / 100 certificates"). Conservative: a noun that
// already ends in "s" is left alone so a value the server sends plural isn't doubled.
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx b/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx
index ee2f1df81f..aabe8a09cc 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx
@@ -2,7 +2,6 @@ import {
CircleAlert,
CreditCard,
ExternalLink,
- Info,
type LucideIcon,
TriangleAlert
} from "lucide-react";
@@ -63,8 +62,8 @@ const PAYMENT_ALERT: Record<
}
};
-// Top-of-page notice: a managed org shows the "managed by your account team" note; a self-serve org in
-// dunning (past-due / suspended) shows a payment-recovery prompt. A renewal payment alert replaces the
+// Top-of-page notice: a self-serve org in dunning (past-due / suspended) shows a payment-recovery
+// prompt. A managed org has no banner; the billing summary carries its account-team note. A renewal payment alert replaces the
// generic dunning prompt so a past-due org never sees two payment banners. Nothing otherwise.
export const Banner = ({
mode,
@@ -75,16 +74,7 @@ export const Banner = ({
onManageSubscription
}: BannerProps) => {
if (mode === "managed") {
- return (
- <Alert variant="info">
- <Info />
- <AlertTitle>Your plan is managed by your account team</AlertTitle>
- <AlertDescription>
- Products and limits on this organization are set by contract. Contact your account manager
- to make changes.
- </AlertDescription>
- </Alert>
- );
+ return null;
}
if (paymentAlert) {
diff --git a/frontend/src/pages/organization/BillingV2Page/components/BillingSheets.tsx b/frontend/src/pages/organization/BillingV2Page/components/BillingSheets.tsx
new file mode 100644
index 0000000000..f463341f6d
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/BillingSheets.tsx
@@ -0,0 +1,214 @@
+import { ReactNode } from "react";
+import { ExternalLink } from "lucide-react";
+
+import {
+ Badge,
+ Button,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import { BillingV2Overview } from "@app/hooks/api";
+
+import { fmtMoneyCents, formatAddressLines, taxTypeLabel } from "../billing-v2-format";
+import { CardEmpty } from "./shared";
+
+type BillingSheetProps = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ title: string;
+ description: string;
+ action?: ReactNode;
+ children: ReactNode;
+};
+
+const BillingSheet = ({
+ isOpen,
+ onOpenChange,
+ title,
+ description,
+ action,
+ children
+}: BillingSheetProps) => (
+ <Sheet open={isOpen} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{title}</SheetTitle>
+ <SheetDescription>{description}</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-5 overflow-y-auto p-4">{children}</div>
+ {action && <SheetFooter>{action}</SheetFooter>}
+ </SheetContent>
+ </Sheet>
+);
+
+const DetailField = ({ label, children }: { label: string; children: ReactNode }) => (
+ <div>
+ <div className="mb-1 text-xs text-label">{label}</div>
+ <div className="text-sm text-foreground">{children}</div>
+ </div>
+);
+
+type SheetProps = {
+ overview: BillingV2Overview;
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+};
+
+export const PaymentSheet = ({
+ overview,
+ isOpen,
+ onOpenChange,
+ canManage,
+ onUpdate
+}: SheetProps & { canManage: boolean; onUpdate: () => void }) => (
+ <BillingSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ title="Payment Method"
+ description="The card charged for your subscription and usage."
+ action={
+ canManage && (
+ <Button variant="outline" onClick={onUpdate}>
+ {overview.payment ? "Update Payment Method" : "Add Payment Method"}
+ </Button>
+ )
+ }
+ >
+ {overview.payment ? (
+ <>
+ <DetailField label="Card">
+ {overview.payment.brand.toUpperCase()} ending in {overview.payment.last4}
+ </DetailField>
+ <DetailField label="Expires">
+ {String(overview.payment.expMonth).padStart(2, "0")} /{" "}
+ {String(overview.payment.expYear).slice(-2)}
+ </DetailField>
+ </>
+ ) : (
+ <CardEmpty title="No payment method" description="You haven't added a payment method yet." />
+ )}
+ </BillingSheet>
+);
+
+export const DetailsSheet = ({
+ overview,
+ isOpen,
+ onOpenChange,
+ canManage,
+ onEdit
+}: SheetProps & { canManage: boolean; onEdit: () => void }) => {
+ const details = overview.billingDetails;
+ const addressLines = formatAddressLines(details?.address ?? null);
+ const emptyDash = <span className="text-muted">—</span>;
+
+ return (
+ <BillingSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ title="Billing Details"
+ description="The name, email, and address shown on your invoices."
+ action={
+ canManage && (
+ <Button variant="outline" onClick={onEdit}>
+ Edit Billing Details
+ </Button>
+ )
+ }
+ >
+ {details ? (
+ <>
+ <DetailField label="Billing Name">{details.name || emptyDash}</DetailField>
+ <DetailField label="Billing Email">{details.email || emptyDash}</DetailField>
+ {addressLines.length > 0 && (
+ <DetailField label="Billing Address">
+ {addressLines.map((line) => (
+ <div key={line}>{line}</div>
+ ))}
+ </DetailField>
+ )}
+ {details.taxIds.length > 0 && (
+ <DetailField label="Tax ID">
+ {details.taxIds.map((taxId) => (
+ <div key={`${taxId.type}-${taxId.value}`}>
+ {taxId.value} <span className="text-muted">({taxTypeLabel(taxId.type)})</span>
+ </div>
+ ))}
+ </DetailField>
+ )}
+ </>
+ ) : (
+ <CardEmpty
+ title="No billing details"
+ description="Your billing name, email, and address will appear here once added."
+ />
+ )}
+ </BillingSheet>
+ );
+};
+
+export const InvoicesSheet = ({ overview, isOpen, onOpenChange }: SheetProps) => (
+ <BillingSheet
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ title="Invoices"
+ description="Every invoice issued for this organization."
+ >
+ {overview.invoices.length === 0 ? (
+ <CardEmpty
+ title="No invoices yet"
+ description="Your first invoice appears after your next billing date."
+ />
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Date</TableHead>
+ <TableHead>Amount</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {overview.invoices.map((inv) => (
+ <TableRow key={inv.id}>
+ <TableCell>{inv.date}</TableCell>
+ <TableCell className="tabular-nums">{fmtMoneyCents(inv.amount)}</TableCell>
+ <TableCell>
+ {inv.paid ? (
+ <Badge variant="success">Paid</Badge>
+ ) : (
+ <Badge variant="danger">Unpaid</Badge>
+ )}
+ </TableCell>
+ <TableCell className="text-right">
+ {inv.pdfUrl ? (
+ <a
+ className="inline-flex items-center gap-1.5 text-xs text-muted hover:underline"
+ href={inv.pdfUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <ExternalLink className="size-3.5" />
+ PDF
+ </a>
+ ) : (
+ <span className="text-muted">—</span>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </BillingSheet>
+);
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index 5e0b7c66dc..5fba15853c 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -1,20 +1,18 @@
import { TriangleAlert } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@app/components/v3";
-import { cn } from "@app/components/v3/utils";
-import { isInfisicalCloud } from "@app/helpers/platform";
-import { BillingV2CatalogProduct, BillingV2Organization, BillingV2Overview } from "@app/hooks/api";
+import {
+ BillingV2BreakdownScopeKind,
+ BillingV2CatalogProduct,
+ BillingV2Organization,
+ BillingV2Overview
+} from "@app/hooks/api";
import { BillingV2RenderState } from "../billing-v2-view-types";
-import { BillingHeaderCard } from "./cards/BillingHeaderCard";
-import { DetailsCard } from "./cards/DetailsCard";
-import { InvoicesCard } from "./cards/InvoicesCard";
-import { PaymentCard } from "./cards/PaymentCard";
-import { ProductsCard } from "./cards/ProductsCard";
import { ErrorPanel } from "./states/ErrorPanel";
-import { BillingSectionSkeleton, StatTilesSkeleton } from "./states/OverviewSkeleton";
import { Banner } from "./Banner";
import { RootOrgFilter } from "./RootOrgFilter";
+import { TabbedOverview, TabbedOverviewSkeleton } from "./TabbedOverview";
import { TrialBanners } from "./TrialBanners";
export type OverviewProps = {
@@ -24,13 +22,15 @@ export type OverviewProps = {
onManageSubscription: () => void;
onUpgrade: (productId: string) => void;
onSetCommitment: (productId: string) => void;
- onViewBreakdown: (productId: string) => void;
+ onViewBreakdown: (productId: string, dimensionKey?: string) => void;
rootOrgs: BillingV2Organization[];
rootOrgCount: number;
isRootOrgsLoading: boolean;
isReloading: boolean;
selectedOrgId: string;
onSelectOrg: (orgId: string) => void;
+ breakdownOrgId: string;
+ breakdownScope: BillingV2BreakdownScopeKind;
onSearchOrgs: (search: string) => void;
showOrgFilter: boolean;
onUpdatePayment: () => void;
@@ -59,6 +59,8 @@ export const Overview = ({
isReloading,
selectedOrgId,
onSelectOrg,
+ breakdownOrgId,
+ breakdownScope,
onSearchOrgs,
showOrgFilter,
onUpdatePayment,
@@ -83,42 +85,7 @@ export const Overview = ({
) : null;
if (subState === "loading" || isReloading) {
- const isManagedShell = overview ? overview.mode === "managed" : !isInfisicalCloud();
- const hasHeaderTiles = overview ? overview.subState !== "no-subscription" : true;
- const keepsBillingHistory = Boolean(
- overview && (overview.payment || overview.billingDetails || overview.invoices.length > 0)
- );
- const hasBillingSection = overview
- ? overview.isCloud && (overview.subState !== "no-subscription" || keepsBillingHistory)
- : isInfisicalCloud();
-
- return (
- <div className="flex flex-col gap-4">
- {isManagedShell && (
- <Banner
- mode="managed"
- subState={subState}
- canManage={false}
- onUpdatePayment={onUpdatePayment}
- onManageSubscription={onManageSubscription}
- />
- )}
- {hasHeaderTiles && <StatTilesSkeleton />}
- <ProductsCard
- key="products"
- overview={overview}
- catalog={catalog}
- readOnly
- orgFilter={orgFilter}
- isReloading
- onManage={onUpgrade}
- onSetCommitment={onSetCommitment}
- onViewBreakdown={onViewBreakdown}
- onContact={onContact}
- />
- {hasBillingSection && <BillingSectionSkeleton />}
- </div>
- );
+ return <TabbedOverviewSkeleton orgFilter={orgFilter} />;
}
if (subState === "error" || !overview) {
@@ -131,107 +98,25 @@ export const Overview = ({
);
}
- const { mode, checkoutFrozen, selfServe } = overview;
+ const { mode, checkoutFrozen } = overview;
const isManaged = mode === "managed";
// Managed plans and read-only billing roles cannot mutate the subscription. A frozen checkout
// (server DISABLE_CHECKOUT) disables every mutation path too, so treat it as read-only for the
// products area and show a notice — the customer never reaches a control that would 503.
const productsReadOnly = isManaged || !canManageBilling || checkoutFrozen;
- const frozenNotice =
- checkoutFrozen && !isManaged ? (
- <Alert variant="warning">
- <TriangleAlert />
- <AlertTitle>Billing changes are temporarily paused</AlertTitle>
- <AlertDescription>
- Purchases and plan changes are unavailable right now. Your current subscription is
- unaffected; please check back shortly.
- </AlertDescription>
- </Alert>
- ) : null;
-
- // An enterprise-managed org (billing_method enterprise_*) sees the surface but self-serve is off; the
- // per-product controls render disabled and this points them to sales. Distinct from checkoutFrozen.
- const enterpriseNotice =
- !selfServe && !isManaged ? (
- <Alert variant="info">
- <TriangleAlert />
- <AlertTitle>Managed Billing</AlertTitle>
- <AlertDescription>
- Contact your Infisical account manager to adjust products, commitments, or your
- subscription.
- </AlertDescription>
- </Alert>
- ) : null;
-
- const showPayment = overview.isCloud && !isManaged;
-
- const hasBillingHistory =
- Boolean(overview.payment) || Boolean(overview.billingDetails) || overview.invoices.length > 0;
-
- const billingSection = !isManaged && (
- <>
- <div className="@container">
- <div className={cn("grid gap-4", showPayment && "@3xl:grid-cols-[2fr_3fr]")}>
- {showPayment && (
- <PaymentCard
- overview={overview}
- canManage={canManageBilling}
- onUpdate={onUpdatePayment}
- />
- )}
- <DetailsCard overview={overview} canManage={canManageBilling} onEdit={onEditDetails} />
- </div>
- </div>
- {showPayment && <InvoicesCard invoices={overview.invoices} />}
- </>
- );
-
- if (subState === "no-subscription") {
- return (
- <div className="flex flex-col gap-4">
- {frozenNotice}
- {enterpriseNotice}
- <Banner
- mode={mode}
- subState={subState}
- canManage={canManageBilling}
- paymentAlert={overview.paymentAlert}
- onUpdatePayment={onUpdatePayment}
- onManageSubscription={onManageSubscription}
- />
- <TrialBanners
- overview={overview}
- catalog={catalog}
- readOnly={productsReadOnly}
- onManage={onUpgrade}
- onUpdatePayment={onUpdatePayment}
- onContact={onContact}
- onCompleteTrialPayment={onCompleteTrialPayment}
- isCompletingTrialPayment={isCompletingTrialPayment}
- hasTrialApproval={hasTrialApproval}
- onOpenTrialApproval={onOpenTrialApproval}
- />
- <ProductsCard
- key="products"
- overview={overview}
- catalog={catalog}
- readOnly={productsReadOnly}
- orgFilter={orgFilter}
- onManage={onUpgrade}
- onSetCommitment={onSetCommitment}
- onViewBreakdown={onViewBreakdown}
- onContact={onContact}
- />
- {hasBillingHistory && billingSection}
- </div>
- );
- }
-
return (
<div className="flex flex-col gap-4">
- {frozenNotice}
- {enterpriseNotice}
+ {checkoutFrozen && !isManaged && (
+ <Alert variant="warning">
+ <TriangleAlert />
+ <AlertTitle>Billing changes are temporarily paused</AlertTitle>
+ <AlertDescription>
+ Purchases and plan changes are unavailable right now. Your current subscription is
+ unaffected; please check back shortly.
+ </AlertDescription>
+ </Alert>
+ )}
<Banner
mode={mode}
subState={subState}
@@ -252,19 +137,21 @@ export const Overview = ({
hasTrialApproval={hasTrialApproval}
onOpenTrialApproval={onOpenTrialApproval}
/>
- <BillingHeaderCard overview={overview} catalog={catalog} />
- <ProductsCard
- key="products"
+ <TabbedOverview
overview={overview}
catalog={catalog}
readOnly={productsReadOnly}
+ canManageBilling={canManageBilling}
orgFilter={orgFilter}
+ breakdownOrgId={breakdownOrgId}
+ breakdownScope={breakdownScope}
onManage={onUpgrade}
onSetCommitment={onSetCommitment}
onViewBreakdown={onViewBreakdown}
+ onUpdatePayment={onUpdatePayment}
+ onEditDetails={onEditDetails}
onContact={onContact}
/>
- {billingSection}
</div>
);
};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsx
new file mode 100644
index 0000000000..e8062a1cae
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductOverviewCard.tsx
@@ -0,0 +1,868 @@
+import { CSSProperties, ReactNode, useEffect, useRef, useState } from "react";
+import { ChevronDownIcon, ChevronRightIcon, ChevronUpIcon, EllipsisIcon } from "lucide-react";
+
+import {
+ Badge,
+ Button,
+ Card,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ IconButton,
+ Popover,
+ PopoverAnchor,
+ PopoverContent,
+ Skeleton
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import {
+ BillingV2BreakdownScopeKind,
+ BillingV2CatalogProduct,
+ BillingV2Entitlement,
+ BillingV2EntitlementDim,
+ useGetBillingV2UsageBreakdown
+} from "@app/hooks/api";
+
+import {
+ byDisplayOrder,
+ cadenceLabel,
+ commitSavingsNudge,
+ dimBarSegments,
+ dimCommitted,
+ dimHasCeiling,
+ dimMonthlyRate,
+ dimOnDemandQuantity,
+ fmtMoney,
+ fmtMoneyCents,
+ pluralizeUnit,
+ productAnnualCommitted,
+ tierLabel,
+ unitForCount
+} from "../billing-v2-format";
+import { ProductIcon } from "./shared";
+import { breakdownableDimensions } from "./UsageBreakdownSheet";
+
+const productTint = "color-mix(in srgb, var(--product-color-resolved) 85%, transparent)";
+
+const priceParts = (ent: BillingV2Entitlement): { amount: string; period: string }[] => {
+ const annual = productAnnualCommitted(ent);
+ const monthly = ent.cadence === "annual" ? 0 : (ent.amount ?? 0);
+ return [
+ ...(annual > 0 ? [{ amount: fmtMoney(annual), period: "/ yr" }] : []),
+ ...(monthly > 0 ? [{ amount: fmtMoney(monthly), period: "/ mo" }] : [])
+ ];
+};
+
+const trialLine = (ent: BillingV2Entitlement) => {
+ if (ent.trialPaymentDueAt) {
+ return `Payment needed · access until ${ent.trialPaymentDueAt}`;
+ }
+ if (ent.isTrialing) {
+ return ent.trialEndsAt ? `Trial ends ${ent.trialEndsAt}` : "Trial";
+ }
+ return null;
+};
+
+const dimRates = (dim: BillingV2EntitlementDim) => {
+ const rates: string[] = [];
+ if (dimCommitted(dim) && dim.committedRate !== undefined) {
+ rates.push(`${fmtMoneyCents(dim.committedRate)} / yr committed`);
+ }
+ const monthly = dimMonthlyRate(dim);
+ if (monthly > 0) {
+ rates.push(`${fmtMoneyCents(monthly)} / mo${dimCommitted(dim) ? " on-demand" : ""}`);
+ }
+ return rates.join(" · ");
+};
+
+const MeterTile = ({
+ dim,
+ className,
+ isDimmed,
+ isSelected,
+ onSelect
+}: {
+ dim: BillingV2EntitlementDim;
+ className?: string;
+ isDimmed?: boolean;
+ isSelected?: boolean;
+ onSelect?: () => void;
+}) => {
+ const allowance = dimCommitted(dim) ? dim.committed : dim.limit;
+ const overage = dimOnDemandQuantity(dim);
+ const hasBar = dimHasCeiling(dim);
+ const monthlyRate = dimMonthlyRate(dim);
+ const { committedPct, onDemandPct } = dimBarSegments(dim);
+
+ let subtext: ReactNode = null;
+ if (overage > 0) {
+ subtext = <span className="text-warning">+{overage.toLocaleString()} on-demand</span>;
+ } else if (allowance === null && monthlyRate > 0) {
+ subtext = `${fmtMoneyCents(monthlyRate)} each / mo`;
+ } else if (allowance === null) {
+ subtext = "(No limit)";
+ }
+
+ const content = (
+ <>
+ <span className="truncate text-xs text-accent">{dim.label}</span>
+ <span className="flex min-w-0 items-baseline gap-1 tabular-nums">
+ <span className={cn("text-base leading-5 font-medium", overage > 0 && "text-warning")}>
+ {dim.used.toLocaleString()}
+ </span>
+ {allowance !== null && (
+ <span className="text-xs text-muted">/ {allowance.toLocaleString()}</span>
+ )}
+ {subtext && <span className="ml-1.5 truncate text-xs text-muted">{subtext}</span>}
+ </span>
+ {hasBar && (
+ <span className="flex h-1 w-full gap-0.5 overflow-hidden rounded-xs bg-border">
+ <span
+ className={cn("h-full rounded-xs", onDemandPct > 0 && "rounded-r-none")}
+ style={{ width: `${committedPct}%`, background: productTint }}
+ />
+ {onDemandPct > 0 && (
+ <span
+ className="h-full rounded-xs rounded-l-none bg-warning/85"
+ style={{ width: `${onDemandPct}%` }}
+ />
+ )}
+ </span>
+ )}
+ </>
+ );
+
+ const tileClass = cn(
+ "flex h-20 min-w-0 flex-col justify-center gap-1.5 rounded-md bg-container px-3 text-left transition-opacity",
+ isDimmed && "opacity-40 hover:opacity-100 focus-visible:opacity-100",
+ className
+ );
+
+ if (!onSelect) {
+ return <div className={tileClass}>{content}</div>;
+ }
+ return (
+ <button
+ type="button"
+ aria-pressed={isSelected}
+ aria-label={`Show ${dim.label} usage`}
+ className={cn(
+ tileClass,
+ "cursor-pointer outline-0 hover:bg-container-hover focus-visible:ring-2 focus-visible:ring-ring"
+ )}
+ onClick={onSelect}
+ >
+ {content}
+ </button>
+ );
+};
+
+const TILE_BREAKPOINTS = [
+ {
+ columns: 1,
+ grid: ["grid-cols-1"],
+ clampedGrid: "grid-cols-[minmax(0,1fr)_5rem]",
+ hide: "hidden",
+ show: "flex"
+ },
+ {
+ columns: 2,
+ grid: ["@sm:grid-cols-1", "@sm:grid-cols-2"],
+ clampedGrid: "@sm:grid-cols-[repeat(2,minmax(0,1fr))_5rem]",
+ hide: "@sm:hidden",
+ show: "@sm:flex"
+ },
+ {
+ columns: 3,
+ grid: ["@lg:grid-cols-1", "@lg:grid-cols-2", "@lg:grid-cols-3"],
+ clampedGrid: "@lg:grid-cols-[repeat(3,minmax(0,1fr))_5rem]",
+ hide: "@lg:hidden",
+ show: "@lg:flex"
+ },
+ {
+ columns: 4,
+ grid: ["@2xl:grid-cols-1", "@2xl:grid-cols-2", "@2xl:grid-cols-3", "@2xl:grid-cols-4"],
+ clampedGrid: "@2xl:grid-cols-[repeat(4,minmax(0,1fr))_5rem]",
+ hide: "@2xl:hidden",
+ show: "@2xl:flex"
+ }
+];
+
+const visibilityClasses = (isVisibleAt: (columns: number) => boolean) => {
+ let wasVisible = true;
+ return TILE_BREAKPOINTS.map(({ columns, hide, show }) => {
+ const isVisible = isVisibleAt(columns);
+ if (isVisible === wasVisible) return "";
+ wasVisible = isVisible;
+ return isVisible ? show : hide;
+ });
+};
+
+const UsageDistribution = ({
+ orgId,
+ scope,
+ dim,
+ onViewBreakdown
+}: {
+ orgId: string;
+ scope: BillingV2BreakdownScopeKind;
+ dim: BillingV2EntitlementDim;
+ onViewBreakdown: () => void;
+}) => {
+ const {
+ data: breakdown,
+ isPending,
+ isError
+ } = useGetBillingV2UsageBreakdown(orgId, dim.key, scope);
+
+ const header = (
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span className="text-sm font-medium">{dim.label} by organization</span>
+ {breakdown && breakdown.scopedCount > 0 && (
+ <span className="text-xs text-muted">
+ {breakdown.scopedCount.toLocaleString()}{" "}
+ {unitForCount(breakdown.unit, breakdown.scopedCount)} across {breakdown.scopes.length}{" "}
+ {breakdown.scopes.length === 1 ? "organization" : "organizations"}
+ </span>
+ )}
+ </div>
+ <Button variant="link" size="xs" onClick={onViewBreakdown}>
+ Full Breakdown
+ <ChevronRightIcon />
+ </Button>
+ </div>
+ );
+
+ let body: ReactNode;
+ if (isPending) {
+ body = (
+ <div className="flex flex-col gap-2.5">
+ <Skeleton className="h-2 w-full rounded-xs" />
+ <Skeleton className="h-4 w-3/4" />
+ <Skeleton className="h-4 w-2/3" />
+ </div>
+ );
+ } else if (isError || !breakdown) {
+ body = <span className="text-xs text-muted">Usage by organization is unavailable.</span>;
+ } else if (breakdown.scopedCount === 0) {
+ body = (
+ <span className="text-xs text-muted">
+ No {pluralizeUnit(breakdown.unit)} have been created yet.
+ </span>
+ );
+ } else {
+ const total = breakdown.scopedCount;
+ const topScopes = [...breakdown.scopes].sort((a, b) => b.count - a.count).slice(0, 5);
+ const subOrgShades = ["bg-sub-org/85", "bg-sub-org/60", "bg-sub-org/40", "bg-sub-org/25"];
+ let subOrgIndex = 0;
+ const shaded = topScopes.map((entry) => {
+ const shade = entry.isRoot
+ ? "bg-org/85"
+ : subOrgShades[Math.min(subOrgIndex, subOrgShades.length - 1)];
+ if (!entry.isRoot) subOrgIndex += 1;
+ return { entry, shade };
+ });
+ const projects = breakdown.hasProjectDetail
+ ? breakdown.scopes
+ .flatMap((entry) => entry.projects.map((project) => ({ ...project, org: entry.name })))
+ .sort((a, b) => b.count - a.count)
+ : [];
+
+ body = (
+ <>
+ <div className="flex h-2 w-full gap-0.5 overflow-hidden rounded-xs bg-border">
+ {shaded.map(({ entry, shade }) => (
+ <span
+ key={entry.orgId}
+ className={cn("h-full", shade)}
+ style={{ width: `${(entry.count / total) * 100}%` }}
+ />
+ ))}
+ </div>
+ <div className="flex flex-col gap-2.5">
+ {shaded.map(({ entry, shade }) => (
+ <div key={entry.orgId} className="flex items-center gap-4 text-xs">
+ <span className="flex min-w-0 flex-1 items-center gap-2 @2xl:w-56 @2xl:flex-none">
+ <span className={cn("size-2 shrink-0 rounded-xs", shade)} />
+ <span className="truncate font-medium">{entry.name}</span>
+ {!entry.isRoot && <span className="shrink-0 text-muted">sub-org</span>}
+ </span>
+ <span className="hidden h-1 flex-1 overflow-hidden rounded-xs bg-border @2xl:block">
+ <span
+ className={cn("block h-full", shade)}
+ style={{ width: `${(entry.count / total) * 100}%` }}
+ />
+ </span>
+ <span className="flex w-20 shrink-0 justify-end gap-2 tabular-nums">
+ <span className="font-medium">{entry.count.toLocaleString()}</span>
+ <span className="w-8 text-right text-muted">
+ {Math.round((entry.count / total) * 100)}%
+ </span>
+ </span>
+ </div>
+ ))}
+ </div>
+ {projects.length > 0 && (
+ <div className="flex flex-col gap-2 rounded-md bg-card p-3 text-xs">
+ <div className="flex items-center justify-between gap-3">
+ <span className="font-medium text-accent">Top projects</span>
+ <Button variant="text" size="xs" onClick={onViewBreakdown}>
+ All {projects.length} {projects.length === 1 ? "Project" : "Projects"}
+ </Button>
+ </div>
+ {projects.slice(0, 5).map((project) => (
+ <div key={project.id} className="flex items-baseline justify-between gap-3">
+ <span className="flex min-w-0 items-baseline gap-2">
+ <span className="truncate">{project.name}</span>
+ <span className="shrink-0 text-muted">{project.org}</span>
+ </span>
+ <span className="font-medium tabular-nums">{project.count.toLocaleString()}</span>
+ </div>
+ ))}
+ </div>
+ )}
+ </>
+ );
+ }
+
+ return (
+ <div className="flex min-w-0 flex-col gap-3.5 rounded-md bg-container p-4">
+ {header}
+ {body}
+ </div>
+ );
+};
+
+const PlanDetails = ({
+ prod,
+ ent,
+ planName,
+ isManaged,
+ canChangePlan,
+ onManage,
+ onSetCommitment
+}: {
+ prod: BillingV2CatalogProduct;
+ ent: BillingV2Entitlement;
+ planName: string;
+ isManaged: boolean;
+ canChangePlan: boolean;
+ onManage: () => void;
+ onSetCommitment: () => void;
+}) => {
+ const dims = ent.dimensions ?? [];
+ const committedDims = dims.filter(dimCommitted);
+ const onDemandDims = dims.filter((dim) => dimOnDemandQuantity(dim) > 0);
+ const pricedDims = isManaged ? [] : dims.filter((dim) => dimRates(dim));
+ const nudge = canChangePlan ? commitSavingsNudge(ent) : null;
+ const cadence = cadenceLabel(ent.cadence ?? null);
+ const trial = trialLine(ent);
+ const trialPlanName = ent.trialPlan
+ ? (ent.trialPlanName ??
+ prod.plans.find((plan) => plan.tier === ent.trialPlan)?.name ??
+ tierLabel(ent.trialPlan))
+ : null;
+
+ const rows: { key: string; label: string; value: ReactNode; action?: ReactNode }[] = [
+ {
+ key: "plan",
+ label: "Plan",
+ value: [planName, cadence].filter(Boolean).join(" · "),
+ action: canChangePlan && (
+ <Button variant="link" size="xs" onClick={onManage}>
+ Compare Plans
+ </Button>
+ )
+ }
+ ];
+ if (trial) {
+ rows.push({
+ key: "trial",
+ label: "Trial",
+ value: <span className={ent.trialPaymentDueAt ? "text-warning" : undefined}>{trial}</span>
+ });
+ }
+ if (ent.renewsOn) {
+ rows.push({ key: "renews", label: "Renews", value: ent.renewsOn });
+ }
+ committedDims.forEach((dim, index) => {
+ rows.push({
+ key: `commitment-${dim.key}`,
+ label: index === 0 ? "Commitment" : "",
+ value: `${(dim.committed ?? 0).toLocaleString()} ${unitForCount(dim.noun, dim.committed ?? 0)}${
+ !isManaged && dim.committedRate
+ ? ` · ${fmtMoney((dim.committed ?? 0) * dim.committedRate)} / yr`
+ : ""
+ }`,
+ action: index === 0 && canChangePlan && (
+ <Button variant="link" size="xs" onClick={onSetCommitment}>
+ Adjust
+ </Button>
+ )
+ });
+ });
+ if (!isManaged && onDemandDims.length > 0) {
+ onDemandDims.forEach((dim, index) => {
+ const quantity = dimOnDemandQuantity(dim);
+ const rate = dimMonthlyRate(dim);
+ rows.push({
+ key: `on-demand-${dim.key}`,
+ label: index === 0 ? "On-demand" : "",
+ value: (
+ <span className="text-warning">
+ {rate > 0
+ ? `${quantity.toLocaleString()} × ${fmtMoneyCents(rate)} = ${fmtMoneyCents(quantity * rate)} / mo`
+ : `${quantity.toLocaleString()} ${unitForCount(dim.noun, quantity)}`}
+ </span>
+ )
+ });
+ });
+ }
+ pricedDims.forEach((dim) => {
+ rows.push({
+ key: `rate-${dim.key}`,
+ label: dim.label,
+ value: <span className="text-muted">{dimRates(dim)}</span>
+ });
+ });
+ if (prod.includes && prod.includes.length > 0) {
+ rows.push({ key: "includes", label: "Includes", value: prod.includes.join(" · ") });
+ }
+
+ return (
+ <div className="flex min-w-0 flex-col gap-3.5 rounded-md bg-container p-4">
+ <span className="text-sm font-medium">Plan and billing</span>
+ <div className="grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-3 gap-y-1.5 text-xs @xl:grid-cols-[7.5rem_minmax(0,1fr)_auto] @xl:gap-y-2.5">
+ {rows.map((row) => (
+ <div key={row.key} className="contents">
+ <span className="col-span-2 truncate text-accent @xl:col-span-1">{row.label}</span>
+ <span className="min-w-0">{row.value}</span>
+ <span className="justify-self-end">{row.action}</span>
+ </div>
+ ))}
+ </div>
+ {trialPlanName && (
+ <div className="flex flex-col gap-0.5 rounded-md bg-info/5 px-3 py-2.5 text-xs">
+ <span className="font-medium text-info">Trialing {trialPlanName}</span>
+ <span className={ent.trialPlanPaymentDueAt ? "text-warning" : "text-muted"}>
+ {ent.trialPlanPaymentDueAt
+ ? `Access until ${ent.trialPlanPaymentDueAt} · confirm payment to upgrade.`
+ : `${ent.trialPlanEndsAt ? `Ends ${ent.trialPlanEndsAt} · ` : ""}Upgrades automatically when the trial ends.`}
+ </span>
+ </div>
+ )}
+ {nudge && (
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-md bg-warning/5 px-3 py-2.5 text-xs">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span className="font-medium text-warning">
+ Save ~{nudge.savingsPct}% with annual billing
+ </span>
+ <span className="text-muted">
+ {nudge.qty.toLocaleString()} {nudge.label} for {fmtMoney(nudge.annualCommitted)} / yr
+ instead of ~{fmtMoney(nudge.monthlyAnnualized)} / yr billed monthly.
+ </span>
+ </div>
+ <Button variant="outline" size="xs" onClick={onSetCommitment}>
+ Annual Options
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+};
+
+const ProductMenu = ({
+ prod,
+ currentTier,
+ canChangePlan,
+ hasBreakdown,
+ hasNudge,
+ onManage,
+ onSetCommitment,
+ onViewBreakdown
+}: {
+ prod: BillingV2CatalogProduct;
+ currentTier?: string;
+ canChangePlan: boolean;
+ hasBreakdown: boolean;
+ hasNudge: boolean;
+ onManage: (productId: string) => void;
+ onSetCommitment?: () => void;
+ onViewBreakdown?: () => void;
+}) => {
+ const [showPlans, setShowPlans] = useState(false);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const openPlansOnCloseRef = useRef(false);
+ const plans = prod.plans
+ .filter((plan) => !plan.deprecated || plan.tier === currentTier)
+ .sort(byDisplayOrder);
+ const showViewPlans = !canChangePlan && plans.length > 0;
+ if (!canChangePlan && !hasBreakdown && !showViewPlans) return null;
+
+ return (
+ <Popover open={showPlans} onOpenChange={setShowPlans}>
+ <DropdownMenu>
+ <PopoverAnchor asChild>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ ref={triggerRef}
+ aria-label={`${prod.name} actions`}
+ size="xs"
+ variant="ghost-muted"
+ >
+ <EllipsisIcon />
+ </IconButton>
+ </DropdownMenuTrigger>
+ </PopoverAnchor>
+ <DropdownMenuContent
+ align="end"
+ sideOffset={2}
+ onCloseAutoFocus={(event) => {
+ if (openPlansOnCloseRef.current) {
+ event.preventDefault();
+ openPlansOnCloseRef.current = false;
+ setShowPlans(true);
+ }
+ }}
+ >
+ {canChangePlan && (
+ <DropdownMenuItem onClick={() => onManage(prod.id)}>Manage Plan</DropdownMenuItem>
+ )}
+ {canChangePlan && hasNudge && onSetCommitment && (
+ <DropdownMenuItem onClick={onSetCommitment}>Switch to Annual</DropdownMenuItem>
+ )}
+ {canChangePlan && hasBreakdown && <DropdownMenuSeparator />}
+ {hasBreakdown && onViewBreakdown && (
+ <DropdownMenuItem onClick={onViewBreakdown}>View Usage Breakdown</DropdownMenuItem>
+ )}
+ {showViewPlans && (
+ <DropdownMenuItem
+ onSelect={() => {
+ openPlansOnCloseRef.current = true;
+ }}
+ >
+ View Plans
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <PopoverContent
+ align="end"
+ aria-label={`${prod.name} plans`}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (document.activeElement === document.body) triggerRef.current?.focus();
+ }}
+ >
+ <div className="flex flex-col gap-3">
+ <span className="text-sm font-medium">{prod.name} plans</span>
+ {plans.map((plan) => (
+ <div key={plan.tier} className="flex items-center justify-between gap-3">
+ <span className="text-sm">{plan.name}</span>
+ {plan.tier === currentTier && <Badge variant="neutral">Current</Badge>}
+ </div>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+type ProductOverviewCardProps = {
+ prod: BillingV2CatalogProduct;
+ ent: BillingV2Entitlement;
+ readOnly: boolean;
+ selfServe: boolean;
+ isManaged: boolean;
+ breakdownOrgId: string;
+ breakdownScope: BillingV2BreakdownScopeKind;
+ isExpanded: boolean;
+ isDimmed: boolean;
+ selectedDimensionKey?: string;
+ onExpand: (dimensionKey?: string) => void;
+ onCollapse: () => void;
+ onManage: (productId: string) => void;
+ onSetCommitment: (productId: string) => void;
+ onViewBreakdown: (productId: string, dimensionKey?: string) => void;
+};
+
+export const ProductOverviewCard = ({
+ prod,
+ ent,
+ readOnly,
+ selfServe,
+ isManaged,
+ breakdownOrgId,
+ breakdownScope,
+ isExpanded,
+ isDimmed,
+ selectedDimensionKey,
+ onExpand,
+ onCollapse,
+ onManage,
+ onSetCommitment,
+ onViewBreakdown
+}: ProductOverviewCardProps) => {
+ const canChangePlan = !readOnly && selfServe;
+ const dims = ent.dimensions ?? [];
+ const breakdownDims = breakdownableDimensions(ent);
+ const breakdownKeys = new Set(breakdownDims.map((dim) => dim.key));
+ const selectedDim =
+ breakdownDims.find((dim) => dim.key === selectedDimensionKey) ?? breakdownDims[0];
+ const hasNudge = canChangePlan && Boolean(commitSavingsNudge(ent));
+ const onDemand = ent.onDemandAmount ?? 0;
+ const planName = ent.planTier
+ ? (prod.plans.find((plan) => plan.tier === ent.planTier)?.name ?? tierLabel(ent.planTier))
+ : "Included";
+ const prices = priceParts(ent);
+ const trial = trialLine(ent);
+ const detailsId = `billing-product-details-${prod.id}`;
+ const headerRef = useRef<HTMLDivElement>(null);
+ const isClampedAt = (columns: number) => !isExpanded && dims.length > columns;
+ const tileGridClasses = TILE_BREAKPOINTS.map(({ columns, grid, clampedGrid }) =>
+ isClampedAt(columns) ? clampedGrid : grid[Math.min(dims.length, columns) - 1]
+ );
+
+ useEffect(() => {
+ if (!isExpanded) return;
+ const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+ headerRef.current
+ ?.closest("[data-slot=card]")
+ ?.scrollIntoView({ behavior: reduceMotion ? "auto" : "smooth", block: "start" });
+ }, [isExpanded]);
+
+ return (
+ <Card
+ className={cn(
+ "product-color @container h-full scroll-mt-6 transition-opacity",
+ isExpanded && "lg:col-span-2",
+ isDimmed && "opacity-50 focus-within:opacity-100 hover:opacity-100"
+ )}
+ style={{ "--product-color": prod.color } as CSSProperties}
+ >
+ <div ref={headerRef} className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-3">
+ <ProductIcon product={prod} size={36} />
+ <div className="flex min-w-0 flex-col gap-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <CardTitle>{prod.name}</CardTitle>
+ {ent.planTier && <Badge variant="neutral">{planName}</Badge>}
+ {ent.status === "grace" && <Badge variant="warning">Grace</Badge>}
+ {ent.status !== "grace" && ent.isTrialing && <Badge variant="info">Trial</Badge>}
+ {prod.addon && <Badge variant="neutral">Add-on</Badge>}
+ </div>
+ <div className="flex flex-wrap items-baseline gap-x-1.5 text-xs tabular-nums">
+ {!isManaged && (
+ <>
+ {prices.length === 0 && !trial && <span className="text-muted">Included</span>}
+ {prices.map((price, index) => (
+ <span key={price.period} className="flex items-baseline gap-x-1.5">
+ {index > 0 && <span className="text-muted">+</span>}
+ <span className="font-medium text-foreground">{price.amount}</span>
+ <span className="text-muted">{price.period}</span>
+ </span>
+ ))}
+ {onDemand > 0 && (
+ <span className="text-warning">+{fmtMoneyCents(onDemand)} on-demand</span>
+ )}
+ </>
+ )}
+ {isManaged && <span className="text-muted">Set by your license</span>}
+ {trial && (
+ <span className={ent.trialPaymentDueAt ? "text-warning" : "text-muted"}>
+ {!isManaged && (prices.length > 0 || onDemand > 0) && "· "}
+ {trial}
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ <ProductMenu
+ prod={prod}
+ currentTier={ent.planTier}
+ canChangePlan={canChangePlan}
+ hasBreakdown={breakdownDims.length > 0}
+ hasNudge={hasNudge}
+ onManage={onManage}
+ onSetCommitment={() => onSetCommitment(prod.id)}
+ onViewBreakdown={() => onViewBreakdown(prod.id, selectedDim?.key)}
+ />
+ </div>
+
+ {dims.length > 0 ? (
+ <div className={cn("grid gap-2", tileGridClasses)}>
+ {dims.map((dim, index) => (
+ <MeterTile
+ key={dim.key}
+ dim={dim}
+ className={cn(
+ visibilityClasses((columns) => !isClampedAt(columns) || index < columns)
+ )}
+ isSelected={isExpanded && selectedDim?.key === dim.key}
+ isDimmed={isExpanded && Boolean(selectedDim) && selectedDim?.key !== dim.key}
+ onSelect={breakdownKeys.has(dim.key) ? () => onExpand(dim.key) : undefined}
+ />
+ ))}
+ {isClampedAt(1) && (
+ <button
+ type="button"
+ className={cn(
+ "flex h-20 min-w-0 cursor-pointer flex-col justify-center gap-1.5 rounded-md bg-container px-3 text-left outline-0 hover:bg-container-hover focus-visible:ring-2 focus-visible:ring-ring",
+ visibilityClasses(isClampedAt)
+ )}
+ onClick={() => onExpand()}
+ >
+ <span className="truncate text-xs text-accent">Others</span>
+ {TILE_BREAKPOINTS.filter(({ columns }) => isClampedAt(columns)).map(({ columns }) => (
+ <span
+ key={columns}
+ className={cn(
+ "text-base leading-5 font-medium tabular-nums",
+ visibilityClasses((visibleColumns) => visibleColumns === columns)
+ )}
+ >
+ +{dims.length - columns}
+ </span>
+ ))}
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="flex h-20 items-center justify-center rounded-md bg-container px-3 text-center text-xs text-muted">
+ No usage-based limits on this plan
+ </div>
+ )}
+
+ {isExpanded && (
+ <div
+ id={detailsId}
+ className={cn(
+ "grid grid-cols-1 gap-2",
+ selectedDim && "@3xl:grid-cols-[minmax(0,1fr)_minmax(0,32rem)]"
+ )}
+ >
+ {selectedDim && (
+ <UsageDistribution
+ orgId={breakdownOrgId}
+ scope={breakdownScope}
+ dim={selectedDim}
+ onViewBreakdown={() => onViewBreakdown(prod.id, selectedDim.key)}
+ />
+ )}
+ <PlanDetails
+ prod={prod}
+ ent={ent}
+ planName={planName}
+ isManaged={isManaged}
+ canChangePlan={canChangePlan}
+ onManage={() => onManage(prod.id)}
+ onSetCommitment={() => onSetCommitment(prod.id)}
+ />
+ </div>
+ )}
+
+ <div className="mt-auto flex justify-center">
+ <Button
+ variant="ghost"
+ size="xs"
+ aria-expanded={isExpanded}
+ aria-controls={isExpanded ? detailsId : undefined}
+ onClick={() => (isExpanded ? onCollapse() : onExpand())}
+ >
+ {isExpanded ? <ChevronUpIcon /> : <ChevronDownIcon />}
+ {isExpanded ? "Hide Details" : "Details"}
+ </Button>
+ </div>
+ </Card>
+ );
+};
+
+export const InactiveProductCard = ({
+ prod,
+ isDimmed,
+ readOnly,
+ isManaged,
+ selfServe,
+ onManage,
+ onContact
+}: {
+ prod: BillingV2CatalogProduct;
+ isDimmed: boolean;
+ readOnly: boolean;
+ isManaged: boolean;
+ selfServe: boolean;
+ onManage: (productId: string) => void;
+ onContact: (prod: BillingV2CatalogProduct) => void;
+}) => {
+ const trialPlan = prod.plans.find((plan) => plan.selfServe && plan.trialable);
+ const hasSelfServePlan = prod.plans.some((plan) => plan.selfServe);
+ const hasSalesLedPlan = prod.plans.some((plan) => plan.salesLed);
+ const canActivate = !readOnly && selfServe && !prod.deprecated && hasSelfServePlan;
+ const canContactSales =
+ !readOnly &&
+ !isManaged &&
+ !prod.deprecated &&
+ hasSalesLedPlan &&
+ (!selfServe || !hasSelfServePlan);
+
+ let note = "This product hasn't been activated for your organization.";
+ if (isManaged) {
+ note = "Not included in your license. Contact your account manager to enable it.";
+ } else if (!selfServe && !canContactSales) {
+ note = "Contact your account manager to enable this product.";
+ }
+
+ return (
+ <Card
+ className={cn(
+ "product-color h-full gap-3 transition-opacity",
+ isDimmed && "opacity-50 focus-within:opacity-100 hover:opacity-100"
+ )}
+ style={{ "--product-color": prod.color } as CSSProperties}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-2.5">
+ <ProductIcon product={prod} size={28} />
+ <div className="flex min-w-0 flex-wrap items-center gap-1.5">
+ <CardTitle>{prod.name}</CardTitle>
+ {prod.addon && <Badge variant="neutral">Add-on</Badge>}
+ </div>
+ </div>
+ {!canActivate && (
+ <ProductMenu
+ prod={prod}
+ canChangePlan={false}
+ hasBreakdown={false}
+ hasNudge={false}
+ onManage={onManage}
+ />
+ )}
+ </div>
+ <span className="flex-1 text-xs text-muted">
+ {canActivate || canContactSales ? (prod.tagline ?? note) : note}
+ </span>
+ {canActivate && (
+ <Button
+ variant="product"
+ size="xs"
+ className="self-start"
+ style={{ "--product-color": prod.color } as CSSProperties}
+ onClick={() => onManage(prod.id)}
+ >
+ {trialPlan && trialPlan.trialDays > 0
+ ? `Try Free for ${trialPlan.trialDays} Days`
+ : "View Plans"}
+ </Button>
+ )}
+ {canContactSales && (
+ <Button variant="outline" size="xs" className="self-start" onClick={() => onContact(prod)}>
+ Contact Sales
+ </Button>
+ )}
+ </Card>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
index 0716ff6e36..529af7e5a4 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx
@@ -50,6 +50,7 @@ import {
dimCommitManageable,
dimCommitted,
fmtMoney,
+ fmtMoneyCents,
isMeteredCadence,
unitForCount,
unitPrice
@@ -97,7 +98,7 @@ const dimPriceLine = (
variant === "headline"
? `/ ${dim.noun} / ${perMonth ? "month" : cadenceWord(cadence)}`
: `per ${dim.noun} / ${perMonth ? "mo" : cadenceWordShort(cadence)}`;
- const line: PriceLine = { amount: fmtMoney(amount, 2), unit, metered };
+ const line: PriceLine = { amount: fmtMoneyCents(amount), unit, metered };
if (metered && dim.included > 0) {
line.prefix = `First ${dim.included.toLocaleString()} ${unitForCount(dim.noun, dim.included)} included, then`;
}
@@ -137,7 +138,7 @@ const PlanPricing = ({ plan, cadence }: { plan: BillingV2Plan; cadence: BillingV
const annual = cad === "annual";
let headline: PriceLine | null = plan.base
? {
- amount: fmtMoney(annual ? unitPrice(plan.base, cad) / 12 : unitPrice(plan.base, cad)),
+ amount: fmtMoneyCents(annual ? unitPrice(plan.base, cad) / 12 : unitPrice(plan.base, cad)),
unit: annual ? "/ month" : `/ ${cadenceWord(cad)}`
}
: null;
diff --git a/frontend/src/pages/organization/BillingV2Page/components/TabbedOverview.tsx b/frontend/src/pages/organization/BillingV2Page/components/TabbedOverview.tsx
new file mode 100644
index 0000000000..eea9651288
--- /dev/null
+++ b/frontend/src/pages/organization/BillingV2Page/components/TabbedOverview.tsx
@@ -0,0 +1,494 @@
+import { ReactNode, useState } from "react";
+import { ChevronRightIcon, InfoIcon, RefreshCw } from "lucide-react";
+
+import {
+ CertificateManagementUpgradeIntent,
+ PamUpgradeIntent,
+ SecretsManagementUpgradeIntent,
+ UpgradeIntent,
+ useUpgradeGate
+} from "@app/components/license/UpgradeGate";
+import { createNotification } from "@app/components/notifications";
+import {
+ Badge,
+ Card,
+ CardContent,
+ IconButton,
+ Separator,
+ Skeleton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { cn } from "@app/components/v3/utils";
+import { useOrganization } from "@app/context";
+import {
+ BillingV2BreakdownScopeKind,
+ BillingV2CatalogProduct,
+ BillingV2Overview,
+ useRefreshBillingV2Entitlements
+} from "@app/hooks/api";
+
+import {
+ byDisplayOrder,
+ cadenceLabel,
+ fmtMoneyCents,
+ nextChargeProductLabel
+} from "../billing-v2-format";
+import { DetailsSheet, InvoicesSheet, PaymentSheet } from "./BillingSheets";
+import { InactiveProductCard, ProductOverviewCard } from "./ProductOverviewCard";
+import { CardEmpty } from "./shared";
+
+const PRODUCT_UPGRADE_INTENTS: Record<string, UpgradeIntent> = {
+ [CertificateManagementUpgradeIntent.productKey]: CertificateManagementUpgradeIntent,
+ [PamUpgradeIntent.productKey]: PamUpgradeIntent,
+ [SecretsManagementUpgradeIntent.productKey]: SecretsManagementUpgradeIntent
+};
+
+const SectionHeading = ({ title }: { title: string }) => (
+ <div className="mt-4 flex items-center gap-3">
+ <h2 className="shrink-0 text-sm">{title}</h2>
+ <Separator className="flex-1" />
+ </div>
+);
+
+type TabbedOverviewProps = {
+ overview: BillingV2Overview;
+ catalog: BillingV2CatalogProduct[];
+ readOnly: boolean;
+ canManageBilling: boolean;
+ orgFilter?: ReactNode;
+ breakdownOrgId: string;
+ breakdownScope: BillingV2BreakdownScopeKind;
+ onManage: (productId: string) => void;
+ onSetCommitment: (productId: string) => void;
+ onViewBreakdown: (productId: string, dimensionKey?: string) => void;
+ onUpdatePayment: () => void;
+ onEditDetails: () => void;
+ onContact: (prod: BillingV2CatalogProduct) => void;
+};
+
+const ACCOUNT_STATUS = {
+ "past-due": { label: "Past Due", variant: "warning" },
+ suspended: { label: "Suspended", variant: "danger" }
+} as const;
+
+const SKELETON_PRODUCTS = ["product-a", "product-b", "product-c", "product-d"];
+
+export const TabbedOverviewSkeleton = ({ orgFilter }: { orgFilter?: ReactNode }) => (
+ <div className="flex flex-col gap-6">
+ {orgFilter && <div className="flex justify-end">{orgFilter}</div>}
+ <div className="flex flex-col gap-4">
+ <Card>
+ <div className="flex items-center justify-between">
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-3 w-20" />
+ <Skeleton className="h-5 w-40" />
+ </div>
+ <Skeleton className="h-4 w-28" />
+ </div>
+ </Card>
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ {SKELETON_PRODUCTS.map((key) => (
+ <Card key={key}>
+ <div className="flex items-center gap-3">
+ <Skeleton className="size-9 rounded-md" />
+ <div className="flex flex-col gap-1.5">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-3 w-24" />
+ </div>
+ </div>
+ <Skeleton className="h-20 w-full rounded-md" />
+ </Card>
+ ))}
+ </div>
+ </div>
+ </div>
+);
+
+const SummaryBlock = ({
+ label,
+ onClick,
+ children
+}: {
+ label: string;
+ onClick: () => void;
+ children: ReactNode;
+}) => (
+ <button
+ type="button"
+ className="flex min-w-36 cursor-pointer flex-col gap-1 rounded-md bg-container px-3 py-2.5 text-left outline-0 transition-colors hover:bg-container-hover focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={onClick}
+ >
+ <span className="text-xs text-accent">{label}</span>
+ <span className="flex min-w-0 items-center justify-between gap-2 text-sm">
+ <span className="flex min-w-0 items-baseline gap-1.5 truncate">{children}</span>
+ <ChevronRightIcon className="size-3.5 shrink-0 text-muted" />
+ </span>
+ </button>
+);
+
+export const TabbedOverview = ({
+ overview,
+ catalog,
+ readOnly,
+ canManageBilling,
+ orgFilter,
+ breakdownOrgId,
+ breakdownScope,
+ onManage,
+ onSetCommitment,
+ onViewBreakdown,
+ onUpdatePayment,
+ onEditDetails,
+ onContact
+}: TabbedOverviewProps) => {
+ const { currentOrg } = useOrganization();
+ const refreshEntitlements = useRefreshBillingV2Entitlements();
+ const [expanded, setExpanded] = useState<{ productId: string; dimensionKey?: string } | null>(
+ null
+ );
+ const { openUpgradeGate, upgradeGate } = useUpgradeGate();
+ const [openSheet, setOpenSheet] = useState<"payment" | "invoices" | "details" | null>(null);
+ const { billing, entitlements } = overview;
+ const isManaged = overview.mode === "managed";
+ const isSubscribed = overview.subState !== "no-subscription";
+ const hasBillingHistory =
+ Boolean(overview.payment) || Boolean(overview.billingDetails) || overview.invoices.length > 0;
+ const showPayment = overview.isCloud && !isManaged;
+ const showInvoices = showPayment && (isSubscribed || overview.invoices.length > 0);
+ const showBillingInfo = !isManaged && (isSubscribed || hasBillingHistory);
+ const visible = [...catalog]
+ .filter((prod) => !prod.deprecated || entitlements[prod.id]?.entitled)
+ .sort(byDisplayOrder);
+ const isActiveProduct = (productId: string) =>
+ Boolean(entitlements[productId]?.entitled) && entitlements[productId]?.status !== "churned";
+ const activeProducts = visible.filter((prod) => isActiveProduct(prod.id));
+ const inactiveProducts = visible.filter((prod) => !isActiveProduct(prod.id));
+ const expandedProduct =
+ expanded &&
+ visible.some((prod) => prod.id === expanded.productId) &&
+ isActiveProduct(expanded.productId)
+ ? expanded
+ : null;
+ const accountStatus =
+ overview.subState in ACCOUNT_STATUS
+ ? ACCOUNT_STATUS[overview.subState as keyof typeof ACCOUNT_STATUS]
+ : null;
+ const { nextCharge } = billing;
+ const trials = visible
+ .filter((prod) => {
+ const ent = entitlements[prod.id];
+ return (
+ isActiveProduct(prod.id) && ent?.isTrialing && ent.trialEndsAt && !ent.trialPaymentDueAt
+ );
+ })
+ .map((prod) => ({ name: prod.name, endsAt: entitlements[prod.id]?.trialEndsAt ?? "" }))
+ .sort((a, b) => Date.parse(a.endsAt) - Date.parse(b.endsAt));
+ let trialNote: string | null = null;
+ if (trials.length === 1) {
+ trialNote = `${trials[0].name} trial ends ${trials[0].endsAt}`;
+ } else if (trials.length > 1) {
+ trialNote = `${trials.length} trials · first ends ${trials[0].endsAt}`;
+ }
+ let accountTeamNote: { label: string; detail: string } | null = null;
+ if (isManaged) {
+ accountTeamNote = {
+ label: "Managed by your account team",
+ detail:
+ "Products and limits on this organization are set by contract. Contact your account manager to make changes."
+ };
+ } else if (!overview.selfServe) {
+ accountTeamNote = {
+ label: "Managed Billing",
+ detail:
+ "Contact your Infisical account manager to adjust products, commitments, or your subscription."
+ };
+ }
+
+ const handleRefresh = () => {
+ refreshEntitlements.mutate(
+ { orgId: currentOrg.id },
+ {
+ onSuccess: () => {
+ createNotification({ type: "success", text: "Entitlements refreshed." });
+ }
+ }
+ );
+ };
+
+ let summaryLeft: ReactNode;
+ if (isManaged) {
+ summaryLeft = (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-accent">Billing Method</span>
+ <span className="flex items-baseline gap-2">
+ <span className="text-lg leading-6 font-medium">Contract</span>
+ <span className="text-xs text-muted">Set by your license</span>
+ </span>
+ </div>
+ );
+ } else if (!isSubscribed && !trialNote) {
+ summaryLeft = (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-accent">Subscription</span>
+ <span className="flex items-baseline gap-2">
+ <span className="text-lg leading-6 font-medium">None</span>
+ <span className="text-xs text-muted">
+ {visible.some(
+ (prod) =>
+ !entitlements[prod.id]?.entitled || entitlements[prod.id]?.status === "churned"
+ )
+ ? "Activate a product to start one"
+ : "No products to activate"}
+ </span>
+ </span>
+ </div>
+ );
+ } else {
+ const chargeDetail = nextCharge
+ ? [nextChargeProductLabel(catalog, nextCharge.productKeys), cadenceLabel(nextCharge.cadence)]
+ .filter(Boolean)
+ .join(" · ")
+ : "";
+ summaryLeft = (
+ <div className="flex flex-col gap-1">
+ <span className="flex items-center gap-2 text-xs text-accent">
+ Next Charge
+ {accountStatus && <Badge variant={accountStatus.variant}>{accountStatus.label}</Badge>}
+ </span>
+ <span className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-lg leading-6 font-medium tabular-nums">
+ {nextCharge ? fmtMoneyCents(nextCharge.amount) : "Nothing due"}
+ </span>
+ {nextCharge && <span className="text-xs text-muted">· {nextCharge.at}</span>}
+ {nextCharge && (chargeDetail || overview.onDemandAmount > 0) && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton size="2xs" variant="ghost-muted" aria-label="Next charge details">
+ <InfoIcon />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span className="flex flex-col gap-0.5">
+ {chargeDetail && <span>{chargeDetail}</span>}
+ {nextCharge.hasUsage && <span>Estimate includes usage to date</span>}
+ {overview.onDemandAmount > 0 && (
+ <span className="text-warning">
+ +{fmtMoneyCents(overview.onDemandAmount)} on-demand this period
+ </span>
+ )}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </span>
+ {trialNote && <span className="text-xs text-muted">{trialNote}</span>}
+ </div>
+ );
+ }
+
+ let summaryRight: ReactNode = null;
+ if (isManaged) {
+ summaryRight = (
+ <span className="text-xs text-muted">
+ {billing.activeProductCount.toLocaleString()} active{" "}
+ {billing.activeProductCount === 1 ? "product" : "products"}
+ </span>
+ );
+ }
+ const latestInvoice = overview.invoices[0];
+
+ return (
+ <div className="flex flex-col gap-4">
+ {upgradeGate}
+ {orgFilter && <div className="flex justify-end">{orgFilter}</div>}
+ <Card aria-label="Billing summary">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ {summaryLeft}
+ <div className="flex flex-wrap items-center gap-3">
+ {accountTeamNote && (
+ <span className="flex items-center gap-1 text-xs text-muted">
+ {accountTeamNote.label}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ size="2xs"
+ variant="ghost-muted"
+ aria-label={`About ${accountTeamNote.label.toLowerCase()}`}
+ >
+ <InfoIcon />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>{accountTeamNote.detail}</TooltipContent>
+ </Tooltip>
+ </span>
+ )}
+ {summaryRight}
+ {showPayment && showBillingInfo && (
+ <SummaryBlock label="Card on File" onClick={() => setOpenSheet("payment")}>
+ {overview.payment ? (
+ `${overview.payment.brand.toUpperCase()} ···· ${overview.payment.last4}`
+ ) : (
+ <span className="text-muted">Not added</span>
+ )}
+ </SummaryBlock>
+ )}
+ {showInvoices && (
+ <SummaryBlock label="Invoices" onClick={() => setOpenSheet("invoices")}>
+ {latestInvoice ? (
+ <>
+ <span className="tabular-nums">{fmtMoneyCents(latestInvoice.amount)}</span>
+ <span
+ className={cn(
+ "truncate text-xs",
+ latestInvoice.paid ? "text-muted" : "text-danger"
+ )}
+ >
+ {latestInvoice.paid ? latestInvoice.date : "Unpaid"}
+ </span>
+ </>
+ ) : (
+ <span className="text-muted">None yet</span>
+ )}
+ </SummaryBlock>
+ )}
+ {showBillingInfo && (
+ <SummaryBlock label="Billing Details" onClick={() => setOpenSheet("details")}>
+ {overview.billingDetails?.name || overview.billingDetails?.email || (
+ <span className="text-muted">Not added</span>
+ )}
+ </SummaryBlock>
+ )}
+ {!readOnly && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <IconButton
+ aria-label="Refresh entitlements"
+ variant="ghost-muted"
+ size="xs"
+ isDisabled={refreshEntitlements.isPending}
+ onClick={handleRefresh}
+ >
+ <RefreshCw />
+ </IconButton>
+ </TooltipTrigger>
+ <TooltipContent>Plan changes may take a few minutes to take effect.</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ </Card>
+
+ {visible.length === 0 ? (
+ <Card>
+ <CardContent>
+ <CardEmpty
+ title="No products available"
+ description="Products will appear here once they're available."
+ />
+ </CardContent>
+ </Card>
+ ) : (
+ <>
+ {activeProducts.length > 0 && (
+ <section className="flex flex-col gap-4">
+ {inactiveProducts.length > 0 && <SectionHeading title="Your Products" />}
+ <div className="grid grid-cols-1 items-stretch gap-4 lg:grid-cols-2">
+ {activeProducts.map((prod) => {
+ const isExpanded = expandedProduct?.productId === prod.id;
+ return (
+ <ProductOverviewCard
+ key={prod.id}
+ prod={prod}
+ ent={entitlements[prod.id]!}
+ readOnly={readOnly}
+ selfServe={overview.selfServe}
+ isManaged={isManaged}
+ breakdownOrgId={breakdownOrgId}
+ breakdownScope={breakdownScope}
+ isExpanded={isExpanded}
+ isDimmed={Boolean(expandedProduct) && !isExpanded}
+ selectedDimensionKey={isExpanded ? expandedProduct?.dimensionKey : undefined}
+ onExpand={(dimensionKey) =>
+ setExpanded({
+ productId: prod.id,
+ dimensionKey:
+ dimensionKey ?? (isExpanded ? expandedProduct?.dimensionKey : undefined)
+ })
+ }
+ onCollapse={() => setExpanded(null)}
+ onManage={onManage}
+ onSetCommitment={onSetCommitment}
+ onViewBreakdown={onViewBreakdown}
+ />
+ );
+ })}
+ </div>
+ </section>
+ )}
+ {inactiveProducts.length > 0 && (
+ <section className="flex flex-col gap-4">
+ {activeProducts.length > 0 && (
+ <SectionHeading title={isManaged ? "Not in Your License" : "Available Products"} />
+ )}
+ <div className="grid grid-cols-1 items-stretch gap-4 md:grid-cols-2 xl:grid-cols-3">
+ {inactiveProducts.map((prod) => (
+ <InactiveProductCard
+ key={prod.id}
+ isDimmed={Boolean(expandedProduct)}
+ prod={prod}
+ readOnly={readOnly}
+ isManaged={isManaged}
+ selfServe={overview.selfServe}
+ onManage={(productId) => {
+ const intent = PRODUCT_UPGRADE_INTENTS[productId];
+ const hasTrial = prod.plans.some(
+ (plan) => plan.selfServe && plan.trialable && plan.trialDays > 0
+ );
+ if (!intent || !hasTrial) {
+ onManage(productId);
+ return;
+ }
+ openUpgradeGate({
+ intent: { ...intent, upgradeLabel: `Try ${prod.name}` },
+ paywallKey: "billing-product-card"
+ });
+ }}
+ onContact={onContact}
+ />
+ ))}
+ </div>
+ </section>
+ )}
+ </>
+ )}
+
+ {showPayment && showBillingInfo && (
+ <PaymentSheet
+ overview={overview}
+ isOpen={openSheet === "payment"}
+ onOpenChange={(isOpen) => setOpenSheet(isOpen ? "payment" : null)}
+ canManage={canManageBilling}
+ onUpdate={onUpdatePayment}
+ />
+ )}
+ {showInvoices && (
+ <InvoicesSheet
+ overview={overview}
+ isOpen={openSheet === "invoices"}
+ onOpenChange={(isOpen) => setOpenSheet(isOpen ? "invoices" : null)}
+ />
+ )}
+ {showBillingInfo && (
+ <DetailsSheet
+ overview={overview}
+ isOpen={openSheet === "details"}
+ onOpenChange={(isOpen) => setOpenSheet(isOpen ? "details" : null)}
+ canManage={canManageBilling}
+ onEdit={onEditDetails}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
index 371892e330..e8c1024519 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/UsageBreakdownSheet.tsx
@@ -482,6 +482,7 @@ type UsageBreakdownSheetProps = {
scope: BillingV2BreakdownScopeKind;
prod: BillingV2CatalogProduct;
entitlement?: BillingV2Entitlement;
+ initialDimensionKey?: string;
onClose: () => void;
};
@@ -490,10 +491,11 @@ export const UsageBreakdownSheet = ({
scope,
prod,
entitlement,
+ initialDimensionKey,
onClose
}: UsageBreakdownSheetProps) => {
const dimensions = breakdownableDimensions(entitlement);
- const [activeKey, setActiveKey] = useState(dimensions[0]?.key ?? "");
+ const [activeKey, setActiveKey] = useState(initialDimensionKey ?? dimensions[0]?.key ?? "");
const activeDim = dimensions.find((dim) => dim.key === activeKey) ?? dimensions[0];
const dimensionKey = activeDim?.key ?? null;
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx
deleted file mode 100644
index 30e8c6ab8a..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/BillingHeaderCard.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-import { ReactNode } from "react";
-import { Calendar, CreditCard, Info, ShieldAlert, ShieldCheck } from "lucide-react";
-
-import { Badge, Card, CardAction, CardContent, CardHeader, CardTitle } from "@app/components/v3";
-import { cn } from "@app/components/v3/utils";
-import { BillingV2CatalogProduct, BillingV2Overview } from "@app/hooks/api";
-
-import { cadenceLabel, fmtMoney, nextChargeProductLabel } from "../../billing-v2-format";
-import { BillingV2RenderState } from "../../billing-v2-view-types";
-import { ActiveBadge } from "../shared";
-
-const StatusBadge = ({ subState }: { subState: BillingV2RenderState }) => {
- if (subState === "trialing") {
- return <Badge variant="info">Trial</Badge>;
- }
- if (subState === "past-due") {
- return <Badge variant="warning">Past due</Badge>;
- }
- if (subState === "suspended") {
- return <Badge variant="danger">Suspended</Badge>;
- }
- return <ActiveBadge />;
-};
-
-type StatTone = "success" | "info" | "warning" | "danger" | "org";
-
-const STAT_TONE: Record<StatTone, string> = {
- success: "border-success/15 bg-success/10 text-success",
- info: "border-info/15 bg-info/10 text-info",
- org: "border-org/15 bg-org/10 text-org",
- warning: "border-warning/15 bg-warning/10 text-warning",
- danger: "border-danger/15 bg-danger/10 text-danger"
-};
-
-const STATUS_VISUAL: Record<BillingV2RenderState, { tone: StatTone; icon: ReactNode }> = {
- active: { tone: "success", icon: <ShieldCheck /> },
- trialing: { tone: "info", icon: <ShieldCheck /> },
- "past-due": { tone: "warning", icon: <ShieldAlert /> },
- suspended: { tone: "danger", icon: <ShieldAlert /> },
- "no-subscription": { tone: "info", icon: <ShieldCheck /> },
- loading: { tone: "info", icon: <ShieldCheck /> },
- error: { tone: "danger", icon: <ShieldAlert /> }
-};
-
-type StatTileProps = {
- title: string;
- tone: StatTone;
- icon: ReactNode;
- value: ReactNode;
- footer: ReactNode;
-};
-
-const StatTile = ({ title, tone, icon, value, footer }: StatTileProps) => (
- <Card className="flex-1 gap-2 p-4">
- <CardHeader>
- <CardTitle className="text-xs font-normal text-muted capitalize">{title}</CardTitle>
- <CardAction>
- <div
- className={cn(
- "flex size-7 items-center justify-center rounded-md border [&>svg]:size-4",
- STAT_TONE[tone]
- )}
- >
- {icon}
- </div>
- </CardAction>
- </CardHeader>
- <CardContent className="flex flex-col gap-1.5">
- <div className="text-lg font-semibold text-foreground">{value}</div>
- <div className="flex min-h-5 items-center">{footer}</div>
- </CardContent>
- </Card>
-);
-
-type BillingHeaderCardProps = {
- overview: BillingV2Overview;
- catalog: BillingV2CatalogProduct[];
-};
-
-// Header stat tiles: Account (standing), Next charge, and What you pay (two independent recurring
-// clocks, never summed), with an info note on the per-product cadence model below.
-export const BillingHeaderCard = ({ overview, catalog }: BillingHeaderCardProps) => {
- const { billing } = overview;
- const { nextCharge } = billing;
- const status = STATUS_VISUAL[overview.subState];
- const productLabel = nextCharge ? nextChargeProductLabel(catalog, nextCharge.productKeys) : "";
- const nextChargeCadence = nextCharge ? cadenceLabel(nextCharge.cadence) : "";
- const nextChargeSubline = [productLabel, nextChargeCadence].filter(Boolean).join(" · ");
- const hasRecurring = billing.monthlyRecurring > 0 || billing.annualCommitted > 0;
-
- return (
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-4 lg:flex-row">
- <StatTile
- title="Account"
- tone={status.tone}
- icon={status.icon}
- value={<StatusBadge subState={overview.subState} />}
- footer={
- <span className="text-xs text-muted">
- {billing.activeProductCount} active{" "}
- {billing.activeProductCount === 1 ? "product" : "products"}
- </span>
- }
- />
-
- <StatTile
- title="Next charge"
- tone="org"
- icon={<Calendar />}
- value={
- nextCharge ? (
- <>
- {fmtMoney(nextCharge.amount)}{" "}
- <span className="text-sm font-normal text-muted">on {nextCharge.at}</span>
- </>
- ) : (
- "—"
- )
- }
- footer={
- <span className="text-xs text-muted">
- {nextCharge ? (
- <>
- {nextChargeSubline}
- {nextCharge.hasUsage && " · plus usage"}
- </>
- ) : (
- "No upcoming charge"
- )}
- </span>
- }
- />
-
- <StatTile
- title="What you pay"
- tone="org"
- icon={<CreditCard />}
- value={
- hasRecurring ? (
- <div className="flex items-center justify-between gap-0.5">
- {billing.monthlyRecurring > 0 && (
- <div>
- {fmtMoney(billing.monthlyRecurring)}{" "}
- <span className="text-sm font-normal text-muted">/ mo recurring</span>
- </div>
- )}
- {billing.annualCommitted > 0 && (
- <div>
- {fmtMoney(billing.annualCommitted)}{" "}
- <span className="text-sm font-normal text-muted">/ yr committed</span>
- </div>
- )}
- </div>
- ) : (
- "Free"
- )
- }
- footer={
- hasRecurring ? (
- <div className="flex w-full items-center justify-between gap-1.5">
- {billing.monthlyRecurring > 0 && <Badge variant="info">Monthly</Badge>}
- {billing.annualCommitted > 0 && <Badge variant="warning">Annual</Badge>}
- </div>
- ) : null
- }
- />
- </div>
-
- <div className="flex items-start gap-2 px-1 text-xs text-muted">
- <Info className="mt-[2px] size-3 shrink-0 text-muted" />
- <span>
- Each product bills on its own cadence. Monthly plans charge on their renewal day; annual
- plans are committed upfront, with usage above the commitment billed monthly on-demand.
- </span>
- </div>
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/DetailsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/DetailsCard.tsx
deleted file mode 100644
index ffdf3b2a95..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/DetailsCard.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { ReactNode } from "react";
-import { Building2 } from "lucide-react";
-
-import { Button, Card, CardAction, CardContent, CardHeader, CardTitle } from "@app/components/v3";
-import { cn } from "@app/components/v3/utils";
-import { BillingV2Overview } from "@app/hooks/api";
-
-import { formatAddressLines, taxTypeLabel } from "../../billing-v2-format";
-import { CardEmpty } from "../shared";
-
-type DetailsCardProps = {
- overview: BillingV2Overview;
- canManage: boolean;
- onEdit: () => void;
-};
-
-const DetailField = ({ label, children }: { label: string; children: ReactNode }) => (
- <div>
- <div className="mb-1 text-xs text-label">{label}</div>
- <div className="text-sm text-foreground">{children}</div>
- </div>
-);
-
-export const DetailsCard = ({ overview, canManage, onEdit }: DetailsCardProps) => {
- const addressLines = formatAddressLines(overview.billingDetails?.address ?? null);
- const taxIds = overview.billingDetails?.taxIds ?? [];
- const hasAddress = addressLines.length > 0;
- const hasTaxIds = taxIds.length > 0;
- const emptyDash = <span className="text-muted">—</span>;
- const name = overview.billingDetails?.name || emptyDash;
- const email = overview.billingDetails?.email || emptyDash;
- // Responsive (keyed off the card's own width via @container, not the viewport, since the sidebar
- // changes how much room the card has): stack to one column when narrow, then two, then three.
- // The third column is the tax ID, so it only appears when one is present.
- const gridCols = hasTaxIds
- ? "grid-cols-1 @lg:grid-cols-2 @3xl:grid-cols-3"
- : "grid-cols-1 @lg:grid-cols-2";
-
- const nameEmailFields = (
- <>
- <DetailField label="Billing Name">{name}</DetailField>
- <DetailField label="Billing Email">{email}</DetailField>
- </>
- );
-
- const taxIdField = hasTaxIds ? (
- <DetailField label="Tax ID">
- {taxIds.map((taxId) => (
- <div key={`${taxId.type}-${taxId.value}`}>
- {taxId.value} <span className="text-muted">({taxTypeLabel(taxId.type)})</span>
- </div>
- ))}
- </DetailField>
- ) : null;
-
- return (
- // h-full so it matches the payment card's height when they share a row.
- <Card className="h-full">
- <CardHeader>
- <CardTitle>
- <Building2 className="size-4 text-accent" />
- Billing Details
- </CardTitle>
- {canManage && (
- <CardAction>
- <Button variant="outline" size="sm" onClick={onEdit}>
- Edit
- </Button>
- </CardAction>
- )}
- </CardHeader>
- <CardContent className="@container">
- {overview.billingDetails ? (
- <div className={cn("grid gap-x-8 gap-y-5", gridCols)}>
- {hasAddress ? (
- <>
- <div className="flex flex-col gap-4">{nameEmailFields}</div>
- <DetailField label="Billing Address">
- {addressLines.map((line) => (
- <div key={line}>{line}</div>
- ))}
- </DetailField>
- {taxIdField}
- </>
- ) : (
- <>
- {nameEmailFields}
- {taxIdField}
- </>
- )}
- </div>
- ) : (
- <CardEmpty
- title="No billing details"
- description="Your billing name, email, and address will appear here once added."
- />
- )}
- </CardContent>
- </Card>
- );
-};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/InvoicesCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/InvoicesCard.tsx
deleted file mode 100644
index fe4df7476d..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/InvoicesCard.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { ExternalLink, ReceiptText } from "lucide-react";
-
-import {
- Badge,
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow
-} from "@app/components/v3";
-import { BillingV2Invoice } from "@app/hooks/api";
-
-import { fmtMoney } from "../../billing-v2-format";
-import { CardEmpty } from "../shared";
-
-export const InvoicesCard = ({ invoices }: { invoices: BillingV2Invoice[] }) => (
- <Card>
- <CardHeader>
- <CardTitle>
- <ReceiptText className="size-4 text-accent" />
- Invoices
- </CardTitle>
- </CardHeader>
- <CardContent>
- {invoices.length === 0 ? (
- <CardEmpty
- title="No invoices yet"
- description="Your first invoice appears after your next billing date."
- />
- ) : (
- <Table>
- <TableHeader>
- <TableRow>
- <TableHead>Date</TableHead>
- <TableHead>Amount</TableHead>
- <TableHead>Status</TableHead>
- <TableHead />
- </TableRow>
- </TableHeader>
- <TableBody>
- {invoices.map((inv) => (
- <TableRow key={inv.id}>
- <TableCell>{inv.date}</TableCell>
- <TableCell className="tabular-nums">{fmtMoney(inv.amount, 2)}</TableCell>
- <TableCell>
- {inv.paid ? (
- <Badge variant="success">Paid</Badge>
- ) : (
- <Badge variant="danger">Unpaid</Badge>
- )}
- </TableCell>
- <TableCell className="text-right">
- {inv.pdfUrl ? (
- <a
- className="inline-flex items-center gap-1.5 text-xs text-muted hover:underline"
- href={inv.pdfUrl}
- target="_blank"
- rel="noopener noreferrer"
- >
- <ExternalLink className="size-3.5" />
- PDF
- </a>
- ) : (
- <span className="text-muted">—</span>
- )}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- )}
- </CardContent>
- </Card>
-);
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/PaymentCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/PaymentCard.tsx
deleted file mode 100644
index 7eba1f488d..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/PaymentCard.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import { CreditCard } from "lucide-react";
-
-import { Button, Card, CardAction, CardContent, CardHeader, CardTitle } from "@app/components/v3";
-import { BillingV2Overview } from "@app/hooks/api";
-
-import { CardEmpty } from "../shared";
-
-type PaymentCardProps = {
- overview: BillingV2Overview;
- canManage: boolean;
- onUpdate: () => void;
-};
-
-export const PaymentCard = ({ overview, canManage, onUpdate }: PaymentCardProps) => (
- // h-full so it matches the details card's height when they share a row.
- <Card className="h-full">
- <CardHeader>
- <CardTitle>
- <CreditCard className="size-4 text-accent" />
- Payment Method
- </CardTitle>
- {canManage && (
- <CardAction>
- <Button variant="outline" size="sm" onClick={onUpdate}>
- Update
- </Button>
- </CardAction>
- )}
- </CardHeader>
- <CardContent>
- {overview.payment ? (
- <div className="flex items-center gap-3.5">
- <div>
- <div className="text-sm font-medium text-foreground">
- {overview.payment.brand.toUpperCase()} ending in {overview.payment.last4}
- </div>
- <div className="mt-0.5 text-xs text-muted">
- Expires {String(overview.payment.expMonth).padStart(2, "0")} /{" "}
- {String(overview.payment.expYear).slice(-2)}
- </div>
- </div>
- </div>
- ) : (
- <CardEmpty
- title="No payment method"
- description="You haven't added a payment method yet."
- />
- )}
- </CardContent>
- </Card>
-);
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductCardSkeleton.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductCardSkeleton.tsx
deleted file mode 100644
index 7ceff01204..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductCardSkeleton.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import { Skeleton } from "@app/components/v3";
-import { cn } from "@app/components/v3/utils";
-import { BillingV2Entitlement } from "@app/hooks/api";
-
-import { commitSavingsNudge, dimHasCeiling, productAnnualCommitted } from "../../billing-v2-format";
-import { breakdownableDimensions } from "../UsageBreakdownSheet";
-
-type MeterRow = { key: string; hasBar: boolean };
-
-export type ProductCardShape = {
- meters: MeterRow[];
- figures: number;
- hasOnDemandNote: boolean;
- hasAction: boolean;
- hasTrialStrip: boolean;
- hasBreakdownStrip: boolean;
- hasCommitStrip: boolean;
-};
-
-type ShapeContext = { readOnly?: boolean; selfServe: boolean };
-
-export const productCardShape = (
- entitlement: BillingV2Entitlement | undefined,
- { readOnly, selfServe }: ShapeContext
-): ProductCardShape => {
- const annualCommitted = productAnnualCommitted(entitlement);
- const monthlyRecurring = entitlement?.cadence === "annual" ? 0 : (entitlement?.amount ?? 0);
-
- return {
- meters: (entitlement?.dimensions ?? []).map((dim) => ({
- key: dim.key,
- hasBar: dimHasCeiling(dim)
- })),
- figures: [annualCommitted > 0, monthlyRecurring > 0].filter(Boolean).length,
- hasOnDemandNote: (entitlement?.onDemandAmount ?? 0) > 0,
- hasAction: !readOnly && selfServe,
- hasTrialStrip: Boolean(entitlement?.trialPlan),
- hasBreakdownStrip: breakdownableDimensions(entitlement).length > 0,
- hasCommitStrip: Boolean(!readOnly && selfServe && commitSavingsNudge(entitlement))
- };
-};
-
-export const UNKNOWN_PRODUCT_SHAPE: ProductCardShape = {
- meters: [
- { key: "first", hasBar: true },
- { key: "second", hasBar: true }
- ],
- figures: 0,
- hasOnDemandNote: false,
- hasAction: false,
- hasTrialStrip: false,
- hasBreakdownStrip: true,
- hasCommitStrip: false
-};
-
-const FIGURES = ["figure-a", "figure-b"];
-
-export const ActiveProductCardSkeleton = ({ shape }: { shape: ProductCardShape }) => {
- const priceLines = shape.figures + (shape.hasOnDemandNote ? 1 : 0);
- const figureBox = priceLines > 1 ? "h-6" : "h-7";
-
- return (
- <div className="flex flex-col gap-3 rounded-lg border border-border bg-container p-4">
- <div className="flex items-center gap-3">
- <Skeleton className="size-10 shrink-0 rounded-lg" />
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <div className="flex h-5.5 items-center">
- <Skeleton className="h-3.5 w-44" />
- </div>
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-32" />
- </div>
- </div>
- <div className="flex shrink-0 flex-col items-end gap-0.5">
- {priceLines === 0 ? (
- <div className="flex h-5 items-center">
- <Skeleton className="h-3.5 w-14" />
- </div>
- ) : (
- <>
- {FIGURES.slice(0, shape.figures).map((figure) => (
- <div key={figure} className={cn("flex items-center", figureBox)}>
- <Skeleton className="h-4 w-24" />
- </div>
- ))}
- {shape.hasOnDemandNote && (
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-28" />
- </div>
- )}
- </>
- )}
- </div>
- {shape.hasAction && <Skeleton className="h-8 w-20 shrink-0 rounded-md" />}
- </div>
-
- {shape.hasTrialStrip && (
- <div className="-mx-4 flex flex-col gap-1.5 border-y border-border bg-warning/5 px-4 py-2.5">
- <div className="flex h-4 items-center justify-between gap-3">
- <Skeleton className="h-3 w-40" />
- <Skeleton className="h-3 w-20" />
- </div>
- <div className="flex h-4 items-center">
- <Skeleton className="h-2.5 w-56" />
- </div>
- </div>
- )}
-
- {shape.meters.length > 0 && (
- <div className="flex flex-col gap-3.5">
- {shape.meters.map((meter) => (
- <div key={meter.key} className="flex flex-col gap-1.5">
- <div className="flex h-4 items-center justify-between gap-2.5">
- <Skeleton className="h-3 w-24" />
- <Skeleton className="h-3 w-28" />
- </div>
- {meter.hasBar && <Skeleton className="h-[5px] w-full rounded-xs" />}
- </div>
- ))}
- </div>
- )}
-
- {shape.hasBreakdownStrip && (
- <div
- className={cn(
- "-mx-4 -mb-4 flex items-center justify-between gap-3 border-t border-border px-4 py-2.5",
- shape.hasCommitStrip && "mb-0"
- )}
- >
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-44" />
- </div>
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-24" />
- </div>
- </div>
- )}
-
- {shape.hasCommitStrip && (
- <div
- className={cn(
- "-mx-4 -mb-4 flex items-center justify-between gap-3 border-t border-border bg-warning/5 px-4 py-2.5",
- shape.hasBreakdownStrip ? "-mt-3" : "mt-1"
- )}
- >
- <div className="flex min-w-0 items-center gap-2.5">
- <Skeleton className="size-6 shrink-0 rounded-md" />
- <Skeleton className="h-3 w-56" />
- </div>
- <Skeleton className="h-8 w-28 shrink-0 rounded-md" />
- </div>
- )}
- </div>
- );
-};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
deleted file mode 100644
index 00f477cdf3..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
+++ /dev/null
@@ -1,473 +0,0 @@
-import { CSSProperties, ReactNode } from "react";
-import { ChevronRight, Clock, DollarSign, Package, RefreshCw } from "lucide-react";
-
-import { createNotification } from "@app/components/notifications";
-import {
- Badge,
- Button,
- Card,
- CardAction,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
- Tooltip,
- TooltipContent,
- TooltipTrigger
-} from "@app/components/v3";
-import { cn } from "@app/components/v3/utils";
-import { useOrganization } from "@app/context";
-import {
- BillingV2CatalogProduct,
- BillingV2Entitlement,
- BillingV2Overview,
- useRefreshBillingV2Entitlements
-} from "@app/hooks/api";
-
-import {
- byDisplayOrder,
- commitSavingsNudge,
- dimHasCeiling,
- fmtMoney,
- productAnnualCommitted,
- tierLabel
-} from "../../billing-v2-format";
-import { ActiveBadge, CardEmpty, DimensionMeter, ProductIcon } from "../shared";
-import { breakdownableDimensions } from "../UsageBreakdownSheet";
-import {
- ActiveProductCardSkeleton,
- productCardShape,
- UNKNOWN_PRODUCT_SHAPE
-} from "./ProductCardSkeleton";
-
-type ActiveProductCardProps = {
- prod: BillingV2CatalogProduct;
- entitlement?: BillingV2Entitlement;
- readOnly?: boolean;
- selfServe: boolean;
- onManage: (id: string) => void;
- onSetCommitment: (id: string) => void;
- onViewBreakdown: (id: string) => void;
-};
-
-// Full-width card for an active product: identity and status, price, Manage action, usage meters.
-const ActiveProductCard = ({
- prod,
- entitlement,
- readOnly,
- selfServe,
- onManage,
- onSetCommitment,
- onViewBreakdown
-}: ActiveProductCardProps) => {
- // "Commit annually and save" nudge: shown when the org holds this product monthly but hasn't set the
- // available commitment. Clicking opens the set-commitment flow. Hidden for enterprise-managed orgs.
- const commitNudge = readOnly || !selfServe ? null : commitSavingsNudge(entitlement);
-
- // Two independent price clocks (never summed): the recurring charge plus any on-demand overage.
- const dims = entitlement?.dimensions ?? [];
- const onDemand = entitlement?.onDemandAmount ?? 0;
- const annualCommitted = productAnnualCommitted(entitlement);
- // Monthly recurring applies to non-annual products (item.amount is their monthly charge); an annual
- // product carries no monthly recurring, only optional usage-driven on-demand overage.
- const monthlyRecurring = entitlement?.cadence === "annual" ? 0 : (entitlement?.amount ?? 0);
- const hasPrice = annualCommitted > 0 || monthlyRecurring > 0 || onDemand > 0;
- const isTrialing = Boolean(entitlement?.isTrialing);
- const trialedPlan = entitlement?.trialPlan
- ? prod.plans.find((plan) => plan.tier === entitlement.trialPlan)
- : undefined;
- const trialPlanName = entitlement?.trialPlan
- ? (entitlement.trialPlanName ?? trialedPlan?.name ?? tierLabel(entitlement.trialPlan))
- : null;
- const trialDaysLeft = entitlement?.trialPlanDaysLeft;
- // Past trialEndsAt but still usable: the conversion charge is waiting on the customer's bank.
- const trialPaymentDueAt = entitlement?.trialPaymentDueAt;
- const trialPlanPaymentDueAt = entitlement?.trialPlanPaymentDueAt;
-
- // The headline figure steps down a size when a second amount line shares the block.
- const priceLines = [annualCommitted > 0, monthlyRecurring > 0, onDemand > 0].filter(
- Boolean
- ).length;
- const figureClass = cn(
- "font-semibold text-foreground tabular-nums",
- priceLines > 1 ? "text-base" : "text-lg"
- );
-
- // Bar-bearing dims first so the block reads bars, then bare cost lines, then the shared legend.
- const sortedDims = [...dims].sort((a, b) => Number(dimHasCeiling(b)) - Number(dimHasCeiling(a)));
-
- const hasBreakdown = breakdownableDimensions(entitlement).length > 0;
-
- // Cadence and renewal (or trial) as one muted subline under the product name.
- let subline: ReactNode = null;
- if (trialPaymentDueAt) {
- subline = (
- <span className="text-warning">Payment needed · access until {trialPaymentDueAt}</span>
- );
- } else if (isTrialing) {
- subline = entitlement?.trialEndsAt ? (
- <span>Trial ends {entitlement.trialEndsAt}</span>
- ) : (
- entitlement?.renewsOn && <span>Renews {entitlement.renewsOn}</span>
- );
- } else {
- subline = (
- <span>
- {entitlement?.cadence === "annual" ? "Yearly" : "Monthly"}
- {entitlement?.renewsOn ? ` · renews ${entitlement.renewsOn}` : ""}
- </span>
- );
- }
-
- return (
- <div className="flex flex-col gap-3 rounded-lg border border-border bg-container p-4">
- <div className="flex items-center gap-3">
- <ProductIcon product={prod} size={40} />
- <div className="flex min-w-0 flex-1 flex-col gap-0.5">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-[15px] font-semibold text-foreground">{prod.name}</span>
- {entitlement?.planTier && (
- <Badge variant="info">{tierLabel(entitlement.planTier)}</Badge>
- )}
- {prod.addon && <Badge variant="neutral">Add-on</Badge>}
- {isTrialing ? <Badge variant="info">Trial</Badge> : <ActiveBadge />}
- </div>
- <div className="truncate text-xs text-muted">{subline}</div>
- </div>
- <div className="flex shrink-0 flex-col items-end gap-0.5">
- {annualCommitted > 0 && (
- <div className="flex items-baseline gap-1">
- <span className={figureClass}>{fmtMoney(annualCommitted)}</span>
- <span className="text-xs text-accent">/ yr committed</span>
- </div>
- )}
- {monthlyRecurring > 0 && (
- <div className="flex items-baseline gap-1">
- <span className={figureClass}>{fmtMoney(monthlyRecurring)}</span>
- <span className="text-xs text-accent">/ mo</span>
- </div>
- )}
- {onDemand > 0 && (
- <span className="text-xs text-accent">
- <span className="font-medium text-warning/90">+{fmtMoney(onDemand)}</span> / mo
- on-demand
- </span>
- )}
- {!hasPrice && <span className="text-sm text-muted">Included</span>}
- </div>
- {!readOnly && selfServe && (
- <Button
- variant="outline"
- size="sm"
- className="shrink-0"
- onClick={() => onManage(prod.id)}
- >
- Manage
- </Button>
- )}
- </div>
- {trialPlanName && (
- <div className="-mx-4 flex flex-col gap-1.5 border-y border-border bg-warning/5 px-4 py-2.5">
- <div className="flex items-center justify-between gap-3">
- <span className="flex items-center gap-2 text-xs text-foreground">
- <Clock className="size-3.5 shrink-0 text-warning" />
- Trialing {trialPlanName}
- </span>
- {trialPlanPaymentDueAt && (
- <span className="shrink-0 text-xs font-medium text-warning">Payment needed</span>
- )}
- {!trialPlanPaymentDueAt && trialDaysLeft !== null && trialDaysLeft !== undefined && (
- <span className="shrink-0 text-xs font-medium text-warning tabular-nums">
- {trialDaysLeft === 0
- ? "Ends today"
- : `${trialDaysLeft} day${trialDaysLeft === 1 ? "" : "s"} left`}
- </span>
- )}
- </div>
- <span className="text-[11px] text-muted">
- {trialPlanPaymentDueAt ? (
- <>
- Access until {trialPlanPaymentDueAt} · confirm payment to upgrade to {trialPlanName}
- </>
- ) : (
- <>
- {entitlement?.trialPlanEndsAt ? `Trial ends ${entitlement.trialPlanEndsAt} · ` : ""}
- upgrades to {trialPlanName} automatically when it ends
- </>
- )}
- </span>
- </div>
- )}
- {sortedDims.length > 0 && (
- <div className="flex flex-col gap-3.5">
- {sortedDims.map((dim) => (
- <DimensionMeter key={dim.key} dim={dim} color={prod.color} />
- ))}
- </div>
- )}
- {hasBreakdown && (
- <button
- type="button"
- onClick={() => onViewBreakdown(prod.id)}
- className={cn(
- "group -mx-4 -mb-4 flex cursor-pointer items-center justify-between gap-3 border-t border-border px-4 py-2.5 text-left transition-colors hover:bg-container-hover",
- commitNudge && "mb-0"
- )}
- >
- <span className="text-xs text-muted">Usage across your organization</span>
- <span className="flex shrink-0 items-center gap-1 text-xs text-accent transition-colors group-hover:text-foreground">
- View breakdown
- <ChevronRight className="size-3.5" />
- </span>
- </button>
- )}
- {commitNudge && (
- // Full-bleed strip at the card's bottom edge nudging the monthly subscriber to commit annually.
- <div
- className={cn(
- "-mx-4 -mb-4 flex items-center justify-between gap-3 border-t border-border bg-warning/5 px-4 py-2.5",
- // Sitting under the breakdown strip, -mt-3 cancels the card's gap-3 so the two full-bleed
- // strips meet on one divider and read as a single footer instead of two floating bars.
- hasBreakdown ? "-mt-3" : "mt-1"
- )}
- >
- <span className="flex items-center gap-2.5 text-xs text-muted">
- <span className="flex size-6 shrink-0 items-center justify-center rounded-md border border-warning/40 text-warning">
- <DollarSign className="size-3.5" />
- </span>
- <span>
- Commit annually and save{" "}
- <span className="font-medium text-foreground">~{commitNudge.savingsPct}%</span> —
- would be{" "}
- <span className="font-medium text-foreground">
- {fmtMoney(commitNudge.annualCommitted)} / yr
- </span>
- </span>
- </span>
- <Button
- variant="outline"
- size="sm"
- className="shrink-0"
- onClick={() => onSetCommitment(prod.id)}
- >
- Switch to annual
- </Button>
- </div>
- )}
- </div>
- );
-};
-
-type AvailableProductTileProps = {
- prod: BillingV2CatalogProduct;
- readOnly?: boolean;
- onManage: (id: string) => void;
- onContact: (prod: BillingV2CatalogProduct) => void;
-};
-
-// Compact tile for a product the org doesn't hold yet: tagline plus an activate / trial / contact action.
-const AvailableProductTile = ({
- prod,
- readOnly,
- onManage,
- onContact
-}: AvailableProductTileProps) => {
- const selfServe = prod.plans.some((plan) => plan.selfServe);
- const salesLed = prod.plans.some((plan) => plan.salesLed);
- const trialPlan = prod.plans.find((plan) => plan.selfServe && plan.trialable);
-
- let action = null;
- if (!readOnly) {
- if (selfServe) {
- action = (
- <Button
- variant="product"
- size="sm"
- style={{ "--product-color": prod.color } as CSSProperties}
- onClick={() => onManage(prod.id)}
- >
- {trialPlan
- ? `Try free${trialPlan.trialDays > 0 ? ` for ${trialPlan.trialDays} days` : ""}`
- : "Activate"}
- </Button>
- );
- } else if (salesLed) {
- action = (
- <Button variant="outline" size="sm" onClick={() => onContact(prod)}>
- Contact sales
- </Button>
- );
- }
- }
-
- return (
- <div className="flex flex-col gap-3 rounded-lg border border-border bg-container p-4">
- <div className="flex flex-wrap items-center gap-2.5">
- <ProductIcon product={prod} />
- <span className="text-sm font-semibold text-foreground">{prod.name}</span>
- {prod.addon && <Badge variant="neutral">Add-on</Badge>}
- </div>
- {prod.tagline && <p className="text-sm text-muted">{prod.tagline}</p>}
- {action && <div className="mt-auto pt-1">{action}</div>}
- </div>
- );
-};
-
-const UNKNOWN_PRODUCTS = ["product-a", "product-b"];
-
-type ProductsCardProps = {
- overview?: BillingV2Overview;
- catalog: BillingV2CatalogProduct[];
- readOnly?: boolean;
- orgFilter?: ReactNode;
- isReloading?: boolean;
- onManage: (id: string) => void;
- onSetCommitment: (id: string) => void;
- onViewBreakdown: (id: string) => void;
- onContact: (prod: BillingV2CatalogProduct) => void;
-};
-
-export const ProductsCard = ({
- overview,
- catalog,
- readOnly,
- orgFilter,
- isReloading,
- onManage,
- onSetCommitment,
- onViewBreakdown,
- onContact
-}: ProductsCardProps) => {
- const entitlements = overview?.entitlements ?? {};
- // A deprecated product stays visible to existing subscribers but is closed to new ones, so hide it
- // from anyone who isn't already entitled to it (plan-level deprecation still shows the product).
- const visible = [...catalog]
- .filter((prod) => !prod.deprecated || entitlements[prod.id]?.entitled)
- .sort(byDisplayOrder);
- const active = visible.filter((prod) => entitlements[prod.id]?.entitled);
- const available = visible.filter((prod) => !entitlements[prod.id]?.entitled);
-
- const { currentOrg } = useOrganization();
- const refreshEntitlements = useRefreshBillingV2Entitlements();
-
- // Pull the latest entitlements from the license server (busting the server cache) and refetch the
- // overview so the freshly-resolved products land in the UI.
- const handleRefresh = () => {
- refreshEntitlements.mutate(
- { orgId: currentOrg.id },
- {
- onSuccess: () => {
- createNotification({ type: "success", text: "Entitlements refreshed." });
- }
- }
- );
- };
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>
- <Package className="size-4 text-accent" />
- Products
- </CardTitle>
- <CardDescription>Active products</CardDescription>
- {(orgFilter || !readOnly) && (
- <CardAction>
- <div className="flex items-center gap-2">
- {orgFilter}
- {!readOnly && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- isDisabled={refreshEntitlements.isPending}
- onClick={handleRefresh}
- >
- <RefreshCw />
- Refresh
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- Plan changes may take a few minutes to take effect.
- </TooltipContent>
- </Tooltip>
- )}
- </div>
- </CardAction>
- )}
- </CardHeader>
- <CardContent>
- {!overview && (
- <div className="flex flex-col gap-4">
- {UNKNOWN_PRODUCTS.map((product) => (
- <ActiveProductCardSkeleton key={product} shape={UNKNOWN_PRODUCT_SHAPE} />
- ))}
- </div>
- )}
- {overview && visible.length === 0 && (
- <CardEmpty
- title="No products available"
- description="Products will appear here once they're available."
- />
- )}
- {overview && visible.length > 0 && (
- <>
- {active.length === 0 && (
- <CardEmpty
- title="No active products"
- description="Activate your first product to get started."
- />
- )}
- <div className="flex flex-col gap-4">
- {active.map((prod) =>
- isReloading ? (
- <ActiveProductCardSkeleton
- key={prod.id}
- shape={productCardShape(entitlements[prod.id], {
- readOnly,
- selfServe: overview.selfServe
- })}
- />
- ) : (
- <ActiveProductCard
- key={prod.id}
- prod={prod}
- entitlement={entitlements[prod.id]}
- readOnly={readOnly}
- selfServe={overview.selfServe}
- onManage={onManage}
- onSetCommitment={onSetCommitment}
- onViewBreakdown={onViewBreakdown}
- />
- )
- )}
- {available.length > 0 && (
- <>
- <div className="flex items-center gap-3 pt-2">
- <span className="text-sm font-medium text-muted">Available products</span>
- <div className="h-px flex-1 bg-border" />
- </div>
- {/* Container-keyed columns: the collapsible sidebar changes the room, not the viewport. */}
- <div className="@container">
- <div className="grid gap-4 @2xl:grid-cols-2 @4xl:grid-cols-3">
- {available.map((prod) => (
- <AvailableProductTile
- key={prod.id}
- prod={prod}
- readOnly={readOnly}
- onManage={onManage}
- onContact={onContact}
- />
- ))}
- </div>
- </div>
- </>
- )}
- </div>
- </>
- )}
- </CardContent>
- </Card>
- );
-};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
index b1a96cacb7..f89bf9010b 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
@@ -33,6 +33,7 @@ import {
dimMonthlyRate,
dimOnDemandQuantity,
fmtMoney,
+ fmtMoneyCents,
unitForCount
} from "../billing-v2-format";
@@ -159,13 +160,13 @@ export const DimensionRateLegend = ({
{dim.committedRate !== undefined && (
<span className="flex items-center gap-1.5">
<span className="size-2 rounded-full" style={{ background: committedTint }} />
- Committed {`${fmtMoney(dim.committedRate)} / ${dim.noun} /yr`}
+ Committed {`${fmtMoneyCents(dim.committedRate)} / ${dim.noun} /yr`}
</span>
)}
{dim.onDemandRate !== undefined && (
<span className="flex items-center gap-1.5">
<span className="size-2 rounded-full bg-warning/85" />
- On-demand {`${fmtMoney(dim.onDemandRate)} / ${dim.noun} /mo`}
+ On-demand {`${fmtMoneyCents(dim.onDemandRate)} / ${dim.noun} /mo`}
</span>
)}
</Fragment>
diff --git a/frontend/src/pages/organization/BillingV2Page/components/states/OverviewSkeleton.tsx b/frontend/src/pages/organization/BillingV2Page/components/states/OverviewSkeleton.tsx
deleted file mode 100644
index 4bc1587056..0000000000
--- a/frontend/src/pages/organization/BillingV2Page/components/states/OverviewSkeleton.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { Card, CardAction, CardContent, CardHeader, CardTitle, Skeleton } from "@app/components/v3";
-
-const TILES = ["account", "next-charge", "what-you-pay"];
-const DETAIL_ROWS = ["row-a", "row-b", "row-c"];
-
-export const StatTilesSkeleton = () => (
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-4 lg:flex-row">
- {TILES.map((tile) => (
- <Card key={tile} className="flex-1 gap-2 p-4">
- <CardHeader>
- <CardTitle>
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-16" />
- </div>
- </CardTitle>
- <CardAction>
- <Skeleton className="size-7 rounded-md" />
- </CardAction>
- </CardHeader>
- <CardContent className="flex flex-col gap-1.5">
- <div className="flex h-7 items-center">
- <Skeleton className="h-4 w-2/3" />
- </div>
- <div className="flex min-h-5 items-center">
- <Skeleton className="h-3 w-24" />
- </div>
- </CardContent>
- </Card>
- ))}
- </div>
- <div className="flex items-start gap-2 px-1">
- <Skeleton className="mt-[2px] size-3 shrink-0 rounded-full" />
- <div className="flex flex-1 flex-col gap-1.5">
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-full" />
- </div>
- <div className="flex h-4 items-center">
- <Skeleton className="h-3 w-2/5" />
- </div>
- </div>
- </div>
- </div>
-);
-
-const CardSkeleton = ({ rows, hasAction = true }: { rows: string[]; hasAction?: boolean }) => (
- <Card className="h-full">
- <CardHeader>
- <CardTitle>
- <div className="flex h-5 items-center">
- <Skeleton className="h-3.5 w-32" />
- </div>
- </CardTitle>
- {hasAction && (
- <CardAction>
- <Skeleton className="h-8 w-24 rounded-md" />
- </CardAction>
- )}
- </CardHeader>
- <CardContent className="flex flex-col gap-3">
- {rows.map((row) => (
- <div key={row} className="flex h-5 items-center justify-between gap-4">
- <Skeleton className="h-3 w-40" />
- <Skeleton className="h-3 w-20" />
- </div>
- ))}
- </CardContent>
- </Card>
-);
-
-export const BillingSectionSkeleton = () => (
- <>
- <div className="@container">
- <div className="grid gap-4 @3xl:grid-cols-[2fr_3fr]">
- <CardSkeleton rows={DETAIL_ROWS.slice(0, 2)} />
- <CardSkeleton rows={DETAIL_ROWS} />
- </div>
- </div>
- <CardSkeleton rows={DETAIL_ROWS} hasAction={false} />
- </>
-);