Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: completed the fixes for the new trail
=684914fd6877
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.tsindex 2a88546a58..991c452437 100644--- a/backend/src/ee/routes/v1/license-v2-router.ts+++ b/backend/src/ee/routes/v1/license-v2-router.ts@@ -147,6 +147,7 @@ const BillingV2OverviewSchema = z.object({.nullable(),invoices: BillingV2InvoiceSchema.array(),entitlements: z.record(BillingV2EntitlementSchema),+ trialedProductKeys: z.string().array(),onDemandAmount: z.number()});@@ -455,18 +456,49 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {}),response: {200: z.object({- outcome: z.enum(["trial_started", "collect_payment_method"]),- checkoutUrl: z.string().optional()+ outcome: z.literal("trial_started"),+ cardSetupUrl: z.string().optional()})}},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {+ // A trial has no Stripe customer yet, so the server needs an email. Take it from the authenticated+ // user (this route is JWT-only) rather than trusting a client-supplied value.+ const email = req.auth.authMode === AuthMode.JWT ? (req.auth.user.email ?? undefined) : undefined;return server.services.licenseV2.startTrial({orgId: req.params.organizationId,actor: buildActor(req.permission),productId: req.body.productId,- plan: req.body.plan+ plan: req.body.plan,+ });+ }+ });++ server.route({+ method: "POST",+ url: "/:organizationId/billing/v2/trial/cancel",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ params: z.object({ organizationId: z.string().trim() }),+ body: z.object({+ productId: z.string().trim()+ }),+ response: {+ 200: z.object({+ outcome: z.literal("trial_completed")+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ return server.services.licenseV2.cancelTrial({+ orgId: req.params.organizationId,+ actor: buildActor(req.permission),+ productId: req.body.productId});}});diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.tsindex 4d02c8a4ab..c861170db4 100644--- a/backend/src/ee/services/license-v2/license-v2-service.ts+++ b/backend/src/ee/services/license-v2/license-v2-service.ts@@ -32,6 +32,7 @@ import {TAddBillingV2PaymentMethodDTO,TAddBillingV2ProductDTO,TBillingV2SubscriptionLifecycleDTO,+ TCancelBillingV2TrialDTO,TChangeBillingV2CommitmentDTO,TCreateBillingV2CheckoutSessionDTO,TCreateBillingV2PortalSessionDTO,@@ -65,6 +66,8 @@ type TLicenseV2ServiceFactoryDep = {| "removeSubscriptionItem"| "changeCommitment"| "startTrial"+ | "cancelTrial"+ | "getTrials"| "cancelSubscription"| "resumeSubscription">;@@ -679,6 +682,19 @@ export const licenseV2ServiceFactory = ({0);+ // Products whose one-per-product trial is used up (any outcome — trialing/converted/expired/+ // canceled/completed). The UI gates the trial CTA on this so a canceled trial isn't re-offered.+ // A failed lookup degrades to empty: the server still blocks a repeat trial with a 409 on start.+ let trialedProductKeys: string[] = [];+ if (!isSelfHostedLicense) {+ try {+ const trials = await licenseClient.getTrials(orgId);+ trialedProductKeys = [...new Set(trials.trials.map((trial) => trial.product_key))];+ } catch (error) {+ logger.error(error, `billing-v2: failed to read trial history [orgId=${orgId}]`);+ }+ }+// Header billing summary. Monthly-recurring and annual-committed are two independent clocks and are// never summed. The next charge is the soonest line to close: derive its amount/product(s)/cadence// from the lines whose currentPeriodEnd matches nextChargeAt (usage-based lines make the total an@@ -720,6 +736,7 @@ export const licenseV2ServiceFactory = ({billingDetails,invoices,entitlements,+ trialedProductKeys,onDemandAmount};@@ -888,13 +905,30 @@ export const licenseV2ServiceFactory = ({return { subscriptionId };};- // Start a plan-scoped self-serve trial. trial_started attaches directly; collect_payment_method- // returns a setup-mode checkout URL to add a card (the trial then auto-starts via webhook).- const startTrial = async ({ orgId, actor, productId, plan }: TStartBillingV2TrialDTO) => {+ // Start a plan-scoped self-serve trial. The trial is granted immediately (no upfront charge);+ // cardSetupUrl, when present, is a best-effort card-setup checkout the client redirects to.+ const startTrial = async ({ orgId, actor, productId, plan, email }: TStartBillingV2TrialDTO) => {+ await ensureManageBilling(orgId, actor);+ // The trial has no Stripe customer yet, so the server creates one from the org's own name + the+ // authenticated user's email; neither is client-supplied.+ const organization = await orgDAL.findById(orgId);+ const result = await licenseClient.startTrial(orgId, {+ productKey: productId,+ planKey: plan,+ email,+ name: organization?.name+ });+ await licenseClient.invalidateEntitlements(orgId);+ return { outcome: result.outcome, cardSetupUrl: result.cardSetupUrl };+ };++ // Cancel an in-progress trial: the product drops to free and the trial never converts. A 404 from+ // the server (no active trial) propagates so the UI can surface it.+ const cancelTrial = async ({ orgId, actor, productId }: TCancelBillingV2TrialDTO) => {await ensureManageBilling(orgId, actor);- const result = await licenseClient.startTrial(orgId, { productKey: productId, planKey: plan });+ const result = await licenseClient.cancelTrial(orgId, { productKey: productId });await licenseClient.invalidateEntitlements(orgId);- return { outcome: result.outcome, checkoutUrl: result.checkoutUrl };+ return { outcome: result.outcome };};// Remove a single product from a multi-product subscription, the operation the Stripe Customer@@ -933,6 +967,7 @@ export const licenseV2ServiceFactory = ({removeProduct,changeCommitment,startTrial,+ cancelTrial,cancelSubscription,resumeSubscription};diff --git a/backend/src/ee/services/license-v2/license-v2-types.ts b/backend/src/ee/services/license-v2/license-v2-types.tsindex 251ecbb3dd..95cd20f53c 100644--- a/backend/src/ee/services/license-v2/license-v2-types.ts+++ b/backend/src/ee/services/license-v2/license-v2-types.ts@@ -162,6 +162,8 @@ export type BillingV2Overview = {} | null;invoices: BillingV2Invoice[];entitlements: Record<string, BillingV2Entitlement>;+ // Product keys whose one-per-product trial is used up (any outcome); the UI gates the trial CTA on it.+ trialedProductKeys: string[];// Total monthly on-demand overage across all products (dollars), for the summary's on-demand note.onDemandAmount: number;};@@ -267,6 +269,14 @@ export type TStartBillingV2TrialDTO = {actor: OrgServiceActor;productId: string;plan: string;+ // Billing email for the trial; a trial has no Stripe customer yet, so the server needs it up front.+ email?: string;+};++export type TCancelBillingV2TrialDTO = {+ orgId: string;+ actor: OrgServiceActor;+ productId: string;};export type TBillingV2SubscriptionLifecycleDTO = {diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.tsindex ddf642bbfc..f1b132daca 100644--- a/backend/src/services/license-client/license-client-backends.ts+++ b/backend/src/services/license-client/license-client-backends.ts@@ -14,6 +14,7 @@ import {subscriptionResponseSchema,TAddSubscriptionItemsPayload,TBillingProfileResponse,+ TCancelTrialPayload,TCatalogResponse,TChangeCommitmentPayload,TCheckoutResult,@@ -23,13 +24,17 @@ import {TEntitlementOrg,TEntitlementsResponse,TLicenseClientBackend,+ trialCancelResultSchema,trialResultSchema,+ trialsResponseSchema,TSessionResponse,TStartTrialPayload,TSubscriptionPreview,TSubscriptionPreviewPayload,TSubscriptionResponse,- TTrialResult+ TTrialCancelResult,+ TTrialResult,+ TTrialsResponse} from "./license-client-types";// Token-scoped paths for the self-hosted (license-key) backend: the key identifies the license, so@@ -276,18 +281,54 @@ export const licenseServerBackend = (},// Start a plan-scoped self-serve trial. The wire request/response use snake_case; map to camelCase.+ // The trial is granted immediately; cardSetupUrl (when present) is a best-effort card-setup checkout.startTrial: async (orgId: string, payload: TStartTrialPayload): Promise<TTrialResult> => {const url = new URL(orgScoped(orgId, "/billing/trial"), serverUrl);const res = await fetch(url, {method: "POST",headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },- body: JSON.stringify({ product_key: payload.productKey, plan_key: payload.planKey }),+ body: JSON.stringify({+ product_key: payload.productKey,+ plan_key: payload.planKey,+ email: payload.email,+ name: payload.name+ }),redirect: "manual"});await throwIfResponseError(res);const body: unknown = await res.json();const parsed = trialResultSchema.parse(body);- return { outcome: parsed.outcome, checkoutUrl: parsed.checkout_url };+ return { outcome: parsed.outcome, cardSetupUrl: parsed.card_setup_url };+ },++ // Cancel an in-progress trial for a product. 404 (no active trial) surfaces as a thrown error.+ cancelTrial: async (orgId: string, payload: TCancelTrialPayload): Promise<TTrialCancelResult> => {+ const url = new URL(orgScoped(orgId, "/billing/trial/cancel"), serverUrl);+ const res = await fetch(url, {+ method: "POST",+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },+ body: JSON.stringify({ product_key: payload.productKey }),+ redirect: "manual"+ });+ await throwIfResponseError(res);+ const body: unknown = await res.json();+ return trialCancelResultSchema.parse(body);+ },++ // The org's trial history. 404 (org has no license yet) degrades to an empty history.+ fetchTrials: async (orgId: string): Promise<TTrialsResponse> => {+ const url = new URL(orgScoped(orgId, "/billing/trials"), serverUrl);+ const res = await fetch(url, {+ method: "GET",+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}` },+ redirect: "manual"+ });+ if (res.status === 404) {+ return { trials: [] };+ }+ await throwIfResponseError(res);+ const body: unknown = await res.json();+ return trialsResponseSchema.parse(body);},cancelSubscription: async (orgId: string): Promise<TCheckoutResult> => {@@ -400,6 +441,8 @@ export const licenseServerSelfHostedBackend = (removeSubscriptionItem: notSupportedOnSelfHosted("removeSubscriptionItem"),changeCommitment: notSupportedOnSelfHosted("changeCommitment"),startTrial: notSupportedOnSelfHosted("startTrial"),+ cancelTrial: notSupportedOnSelfHosted("cancelTrial"),+ fetchTrials: notSupportedOnSelfHosted("fetchTrials"),cancelSubscription: notSupportedOnSelfHosted("cancelSubscription"),resumeSubscription: notSupportedOnSelfHosted("resumeSubscription")});diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.tsindex 1f9ebc2b38..58e06d643f 100644--- a/backend/src/services/license-client/license-client-types.ts+++ b/backend/src/services/license-client/license-client-types.ts@@ -369,19 +369,50 @@ export type TChangeCommitmentPayload = {export type TStartTrialPayload = {productKey: string;planKey: string;+ // A trial starts with no Stripe customer yet, so the server needs an email + org name to create one.+ email?: string;+ name?: string;};-// trial_started: attached directly (card on file). collect_payment_method: caller must complete the-// setup-mode Checkout at checkoutUrl to add a card; the trial then auto-starts via webhook.+// The trial is always granted immediately (our-side, no Stripe subscription, no upfront charge), so+// outcome is always "trial_started". cardSetupUrl is a best-effort setup-mode Checkout to add a card;+// omitted when there's no customer / the portal isn't configured / the session couldn't open. The+// card never gates the trial — at trial end a worker converts (card on file) or expires to free.const trialResultSchema = z.object({- outcome: z.enum(["trial_started", "collect_payment_method"]),- checkout_url: z.string().optional()+ outcome: z.literal("trial_started"),+ card_setup_url: z.string().optional()}).passthrough();-export type TTrialResult = { outcome: "trial_started" | "collect_payment_method"; checkoutUrl?: string };+export type TTrialResult = { outcome: "trial_started"; cardSetupUrl?: string };export { trialResultSchema };+export type TCancelTrialPayload = {+ productKey: string;+};++// Revokes the trialing entitlement immediately (product → free) and marks the trial completed so it+// never converts. Idempotent-ish: the server 404s when there's no active trial to cancel.+const trialCancelResultSchema = z.object({ outcome: z.literal("trial_completed") }).passthrough();+export type TTrialCancelResult = { outcome: "trial_completed" };+export { trialCancelResultSchema };++// The org's trial history: any product listed here has used up its one-per-product trial (regardless+// of how it ended), so the client can gate the trial CTA instead of discovering it via a 409 on start.+const trialHistoryItemSchema = z+ .object({+ product_key: z.string(),+ plan_key: z.string().nullish(),+ // trialing | converted | expired | canceled | completed+ outcome: z.string(),+ started_at: z.number().nullish(),+ trial_ends_at: z.number().nullish()+ })+ .passthrough();+const trialsResponseSchema = z.object({ trials: z.array(trialHistoryItemSchema).default([]) }).passthrough();+export type TTrialsResponse = z.infer<typeof trialsResponseSchema>;+export { trialsResponseSchema };+export type TLicenseClientBackend = {fetchEntitlements: (org: TEntitlementOrg) => Promise<TEntitlementsResponse>;// Ask the license server to recompute/bust its cached entitlements after a license change.@@ -399,6 +430,10 @@ export type TLicenseClientBackend = {changeCommitment: (orgId: string, payload: TChangeCommitmentPayload) => Promise<TCheckoutResult>;// Start a plan-scoped self-serve trial.startTrial: (orgId: string, payload: TStartTrialPayload) => Promise<TTrialResult>;+ // Cancel an in-progress trial for a product (product → free; the trial never converts).+ cancelTrial: (orgId: string, payload: TCancelTrialPayload) => Promise<TTrialCancelResult>;+ // The org's trial history, used to tell which products have already used their one-time trial.+ fetchTrials: (orgId: string) => Promise<TTrialsResponse>;cancelSubscription: (orgId: string) => Promise<TCheckoutResult>;resumeSubscription: (orgId: string) => Promise<TCheckoutResult>;};diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.tsindex cb5cc39ba0..0b6ac9d1be 100644--- a/backend/src/services/license-client/license-client.ts+++ b/backend/src/services/license-client/license-client.ts@@ -7,6 +7,7 @@ import { licenseServerBackend, licenseServerSelfHostedBackend } from "./license-import { entitlementResolverFactory } from "./license-client-cache";import {TAddSubscriptionItemsPayload,+ TCancelTrialPayload,TChangeCommitmentPayload,TCreateCheckoutPayload,TCreatePortalPayload,@@ -182,6 +183,21 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFactreturn backend.startTrial(orgId, payload);};+ const cancelTrial = async (orgId: string, payload: TCancelTrialPayload) => {+ if (!backend) {+ throw new Error("license client backend is not configured");+ }+ return backend.cancelTrial(orgId, payload);+ };++ // The org's trial history; returns an empty history when no backend is configured (self-hosted).+ const getTrials = async (orgId: string) => {+ if (!backend) {+ return { trials: [] };+ }+ return backend.fetchTrials(orgId);+ };+const cancelSubscription = async (orgId: string) => {if (!backend) {throw new Error("license client backend is not configured");@@ -212,6 +228,8 @@ export const licenseClientFactory = ({ envConfig, keyStore }: TLicenseClientFactremoveSubscriptionItem,changeCommitment,startTrial,+ cancelTrial,+ getTrials,cancelSubscription,resumeSubscription};diff --git a/backend/src/services/license-client/usage/usage-event-queue.ts b/backend/src/services/license-client/usage/usage-event-queue.tsindex 4c32a18d0f..ae7a143d89 100644--- a/backend/src/services/license-client/usage/usage-event-queue.ts+++ b/backend/src/services/license-client/usage/usage-event-queue.ts@@ -73,6 +73,9 @@ export const usageEventQueueFactory = ({}]);+ logger.info(+ `usage-event-queue: reported usage event [orgId=${orgId}] [dimensionKey=${dimensionKey}] [value=${value}]`+ );await keyStore.setItemWithExpiry(lastReportedKey, KeyStoreTtls.LicenseUsageLastReportedInSeconds, String(value));};diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsxindex 8f3518af0a..679205c251 100644--- a/frontend/src/hooks/api/billingV2/index.tsx+++ b/frontend/src/hooks/api/billingV2/index.tsx@@ -2,6 +2,7 @@ export {useAddBillingV2PaymentMethod,useAddBillingV2Product,useCancelBillingV2Subscription,+ useCancelBillingV2Trial,useChangeBillingV2Commitment,useCreateBillingV2CheckoutSession,useCreateBillingV2PortalSession,diff --git a/frontend/src/hooks/api/billingV2/mutations.tsx b/frontend/src/hooks/api/billingV2/mutations.tsxindex 01b6547c0f..916ee785a5 100644--- a/frontend/src/hooks/api/billingV2/mutations.tsx+++ b/frontend/src/hooks/api/billingV2/mutations.tsx@@ -7,10 +7,12 @@ import {BillingV2CheckoutResult,BillingV2MutationResult,BillingV2Preview,+ BillingV2TrialCancelResult,BillingV2TrialResult,TAddBillingV2PaymentMethodDTO,TAddBillingV2ProductDTO,TBillingV2LifecycleDTO,+ TCancelBillingV2TrialDTO,TChangeBillingV2CommitmentDTO,TCreateBillingV2CheckoutSessionDTO,TCreateBillingV2PortalSessionDTO,@@ -136,7 +138,8 @@ export const useChangeBillingV2Commitment = () => {});};-// Start a plan-scoped self-serve trial. collect_payment_method returns a Stripe setup checkout URL.+// Start a plan-scoped self-serve trial. The trial is granted immediately; cardSetupUrl (when present)+// is a best-effort Stripe setup checkout the caller redirects to for adding a card.export const useStartBillingV2Trial = () => {const queryClient = useQueryClient();return useMutation({@@ -154,6 +157,24 @@ export const useStartBillingV2Trial = () => {});};+// Cancel an in-progress trial for a product (product drops to free; the trial never converts).+export const useCancelBillingV2Trial = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ orgId, productId }: TCancelBillingV2TrialDTO) => {+ const { data } = await apiRequest.post<BillingV2TrialCancelResult>(+ `/api/v1/organizations/${orgId}/billing/v2/trial/cancel`,+ { productId }+ );++ return data;+ },+ onSuccess: (_data, { orgId }) => {+ queryClient.invalidateQueries({ queryKey: billingV2Keys.overview(orgId) });+ }+ });+};+export const useRemoveBillingV2Product = () => {const queryClient = useQueryClient();return useMutation({diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.tsindex 4b45e79ecd..299a4109e7 100644--- a/frontend/src/hooks/api/billingV2/types.ts+++ b/frontend/src/hooks/api/billingV2/types.ts@@ -157,6 +157,8 @@ export type BillingV2Overview = {} | null;invoices: BillingV2Invoice[];entitlements: Record<string, BillingV2Entitlement>;+ // Product keys whose one-per-product trial is used up (any outcome); gates the trial CTA.+ trialedProductKeys: string[];};export type BillingV2CheckoutResult = {@@ -253,11 +255,21 @@ export type TStartBillingV2TrialDTO = {plan: string;};-// trial_started: attached directly. collect_payment_method: complete the setup Checkout at checkoutUrl-// to add a card (the trial then auto-starts via webhook).+export type TCancelBillingV2TrialDTO = {+ orgId: string;+ productId: string;+};++// The trial is granted immediately (outcome is always trial_started). cardSetupUrl, when present, is a+// best-effort setup-mode Checkout to add a card; the client redirects to it, else shows a card-required+// banner. The card never gates the trial.export type BillingV2TrialResult = {- outcome: "trial_started" | "collect_payment_method";- checkoutUrl?: string;+ outcome: "trial_started";+ cardSetupUrl?: string;+};++export type BillingV2TrialCancelResult = {+ outcome: "trial_completed";};export type TBillingV2LifecycleDTO = {diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsxindex c3d4913970..815ca68a9b 100644--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx@@ -180,6 +180,7 @@ export const BillingV2Page = () => {billingEmail={billingEmail}returnPath={window.location.pathname}renewsOn={overview?.entitlements[flow.prodId]?.renewsOn ?? null}+ trialUsed={overview?.trialedProductKeys.includes(flow.prodId) ?? false}onClose={close}onRemove={setRemoveProdId}onContact={() => {diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-data.tsindex 3e6921ae12..a6032ea180 100644--- a/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-data.ts@@ -122,42 +122,15 @@ export const dimBarSegments = (return { committedPct: usagePct(dim.used, dim.limit) ?? 0, onDemandPct: 0 };};-// Headline price breakdown for a product card, e.g. "55 seats committed × $20",-// "1 CA committed × $435 + 100 certificates committed × $3", "140 active contributors × $7", or-// "Flat · up to 10 resources". Annual committed dims read as "{committed} {units} committed × $rate";-// monthly priced dims as "{used} {units} × $rate"; a capped flat dim as "up to {limit} {units}".-export const productBreakdown = (entitlement?: BillingV2Entitlement): string | null => {+// Annual committed total for a product (dollars/yr): committed quantity × pinned annual rate, summed+// across its annually-committed dimensions. This is the prepaid yearly figure, shown separately from+// any monthly on-demand overage (the two are never summed into one headline).+export const productAnnualCommitted = (entitlement?: BillingV2Entitlement): number => {const dims = entitlement?.dimensions ?? [];- if (dims.length === 0) {- return null;- }-- const pricedTerms: string[] = [];- const flatTerms: string[] = [];- dims.forEach((dim) => {+ return dims.reduce((sum, dim) => {if (dimAnnualCommitted(dim) && dim.committedRate) {- const committed = dim.committed ?? 0;- pricedTerms.push(- `${committed.toLocaleString()} ${pluralizeUnit(dim.noun)} committed × ${fmtMoney(dim.committedRate)}`- );- return;- }- const rate = dimMonthlyRate(dim);- if (rate > 0) {- const qty = dim.metered ? Math.max(0, dim.used - (dim.freeBand ?? 0)) : dim.used;- pricedTerms.push(`${qty.toLocaleString()} ${pluralizeUnit(dim.noun)} × ${fmtMoney(rate)}`);- return;+ return sum + (dim.committed ?? 0) * dim.committedRate;}- if (dim.limit !== null) {- flatTerms.push(`up to ${dim.limit.toLocaleString()} ${pluralizeUnit(dim.noun)}`);- }- });-- if (pricedTerms.length > 0) {- return [...pricedTerms, ...flatTerms].join(" + ");- }- if (flatTerms.length > 0) {- return `Flat · ${flatTerms.join(" + ")}`;- }- return null;+ return sum;+ }, 0);};diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsxindex 9db0d03346..88b8a0685a 100644--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx@@ -46,7 +46,7 @@ import {BillingV2Overview} from "@app/hooks/api";-import { byDisplayOrder, cadencePeriod, fmtMoney, productBreakdown } from "../billing-v2-data";+import { byDisplayOrder, fmtMoney, productAnnualCommitted } from "../billing-v2-data";import { ActiveBadge, CadenceBadge, DimensionMeter, ProductIcon } from "./shared";export type BillingV2Mode = "self-serve" | "managed";@@ -232,7 +232,7 @@ const StatusBadge = ({ subState }: { subState: BillingV2RenderState }) => {};const HeaderColumn = ({ label, children }: { label: string; children: ReactNode }) => (- <div className="flex flex-1 flex-col gap-3 px-6 py-5 first:pl-0">+ <div className="flex flex-1 flex-col gap-3 px-6 py-5"><div className="text-xs font-medium tracking-wide text-muted uppercase">{label}</div>{children}</div>@@ -407,12 +407,15 @@ const ProductRow = ({ prod, entitlement, readOnly, onManage, onContact }: Produc);}- // Active product: cadence badge, renewal (or trial) line, headline recurring + on-demand, price- // breakdown, and one usage bar per dimension.+ // Active product: cadence badge, renewal (or trial) line, and the price as two independent clocks+ // (never summed) — the annual prepaid commitment and the monthly charge — plus one bar per dimension.const dims = entitlement?.dimensions ?? [];- const amount = entitlement?.amount ?? 0;const onDemand = entitlement?.onDemandAmount ?? 0;- const breakdown = productBreakdown(entitlement);+ 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);return (@@ -438,18 +441,28 @@ const ProductRow = ({ prod, entitlement, readOnly, onManage, onContact }: Produc</div></div><div className="flex shrink-0 flex-col items-end gap-0.5">- <div className="flex items-baseline gap-1">- <span className="text-sm font-semibold text-foreground tabular-nums">- {fmtMoney(amount)}- </span>- <span className="text-xs text-muted">/ {cadencePeriod(entitlement?.cadence)}</span>- </div>- {breakdown && <span className="text-xs text-muted">{breakdown}</span>}+ {annualCommitted > 0 && (+ <div className="flex items-baseline gap-1">+ <span className="text-sm font-semibold text-foreground tabular-nums">+ {fmtMoney(annualCommitted)}+ </span>+ <span className="text-xs text-muted">/ yr </span>+ </div>+ )}+ {monthlyRecurring > 0 && (+ <div className="flex items-baseline gap-1">+ <span className="text-sm font-semibold text-foreground tabular-nums">+ {fmtMoney(monthlyRecurring)}+ </span>+ <span className="text-xs text-muted">/ mo</span>+ </div>+ )}{onDemand > 0 && (<span className="text-xs font-medium text-warning">+ {fmtMoney(onDemand)} / mo on-demand</span>)}+ {!hasPrice && <span className="text-sm text-muted">Included</span>}</div>{action && <div className="flex shrink-0 items-center gap-1.5">{action}</div>}</div>diff --git a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsxindex eb7f5aaffc..b3e169e641 100644--- a/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx+++ b/frontend/src/pages/organization/BillingV2Page/components/ProductSheet.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { ArrowRight, Check, PlusIcon, Sparkles } from "lucide-react";+import { ArrowRight, CalendarX2Icon, Check, PlusIcon, Sparkles } from "lucide-react";import { createNotification } from "@app/components/notifications";import {@@ -34,6 +34,7 @@ import {BillingV2Dim,BillingV2Entitlement,BillingV2Plan,+ useCancelBillingV2Trial,useStartBillingV2Trial} from "@app/hooks/api";@@ -147,6 +148,8 @@ type PlanCardProps = {cadence: BillingV2Cadence;isCurrent: boolean;entitled: boolean;+ // This product's one-per-product trial is already used up (any outcome), so no trial CTA.+ trialUsed: boolean;canChangeCommitment: boolean;onActivate: (planTier: string) => void;onStartTrial: (planTier: string) => void;@@ -159,6 +162,7 @@ const PlanCard = ({cadence,isCurrent,entitled,+ trialUsed,canChangeCommitment,onActivate,onStartTrial,@@ -166,7 +170,9 @@ const PlanCard = ({onContact}: PlanCardProps) => {const isCustom = plan.salesLed && !plan.base && plan.dims.length === 0;- const offersTrial = plan.selfServe && plan.trialable && !entitled;+ // A trial is offered only when the plan supports it, the org isn't already on the product, and it+ // hasn't used its one-time trial for this product yet.+ const offersTrial = plan.selfServe && plan.trialable && !entitled && !trialUsed;let cta = null;if (plan.salesLed && !isCurrent) {@@ -328,6 +334,8 @@ type ProductSheetProps = {billingEmail?: string;returnPath: string;renewsOn: string | null;+ // This product's one-per-product trial is already used up (backend-computed from trial history).+ trialUsed: boolean;onClose: () => void;onRemove: (prodId: string) => void;onContact: (prod: BillingV2CatalogProduct) => void;@@ -343,6 +351,7 @@ export const ProductSheet = ({billingEmail,returnPath,renewsOn,+ trialUsed,onClose,onRemove,onContact@@ -352,14 +361,19 @@ export const ProductSheet = ({const [activatePlan, setActivatePlan] = useState<string | null>(null);// The plan tier awaiting trial confirmation (drives the confirm dialog).const [trialConfirmTier, setTrialConfirmTier] = useState<string | null>(null);+ // Whether the cancel-trial confirm dialog is open.+ const [showCancelTrial, setShowCancelTrial] = useState(false);const startTrial = useStartBillingV2Trial();+ const cancelTrial = useCancelBillingV2Trial();if (!prod) {return null;}const entitled = Boolean(entitlement?.entitled);+ // A trialing product is canceled (trial → free), not removed like a paid product line.+ const isTrialing = Boolean(entitlement?.isTrialing);const selfServePlan = prod.plans.find((plan) => plan.selfServe && !plan.salesLed);// The active product's plan-card price renders in its billing cadence; a new one defaults to monthly.const displayCadence: BillingV2Cadence = entitlement?.cadence === "annual" ? "annual" : "monthly";@@ -387,14 +401,15 @@ export const ProductSheet = ({productId: prod.id,plan: trialConfirmTier});- // No card on file: finish the Stripe setup checkout, which auto-starts the trial via webhook.- if (result.outcome === "collect_payment_method" && result.checkoutUrl) {- window.location.href = result.checkoutUrl;+ // The trial is already active. Redirect to the card-setup checkout when the server returns one so+ // it can convert at trial end; otherwise nudge the user to add a card before then.+ if (result.cardSetupUrl) {+ window.location.href = result.cardSetupUrl;return;}createNotification({type: "success",- text: `Your ${prod.name} trial has started. It may take a moment to update here.`+ text: `Your ${prod.name} trial has started. Add a card before it ends to keep the product.`});onClose();} catch {@@ -403,6 +418,20 @@ export const ProductSheet = ({}};+ const handleCancelTrial = async () => {+ try {+ await cancelTrial.mutateAsync({ orgId, productId: prod.id });+ createNotification({+ type: "success",+ text: `Your ${prod.name} trial has been canceled.`+ });+ onClose();+ } catch {+ createNotification({ type: "error", text: `Failed to cancel the ${prod.name} trial.` });+ setShowCancelTrial(false);+ }+ };+const activatePlanObj = activatePlan? plans.find((plan) => plan.tier === activatePlan): (selfServePlan ?? undefined);@@ -470,6 +499,7 @@ export const ProductSheet = ({plan={plan}cadence={displayCadence}entitled={entitled}+ trialUsed={trialUsed}isCurrent={entitled && plan.tier === currentTier}canChangeCommitment={canChangeCommitment}onActivate={openActivate}@@ -491,13 +521,23 @@ export const ProductSheet = ({<SheetFooter className="flex-row items-center justify-between border-t">{entitled ? (<>- <Button- variant="ghost"- className="text-danger"- onClick={() => onRemove(prod.id)}- >- Remove product- </Button>+ {isTrialing ? (+ <Button+ variant="ghost"+ className="text-danger"+ onClick={() => setShowCancelTrial(true)}+ >+ Cancel trial+ </Button>+ ) : (+ <Button+ variant="ghost"+ className="text-danger"+ onClick={() => onRemove(prod.id)}+ >+ Remove product+ </Button>+ )}<Button variant="outline" onClick={onClose}>Close</Button>@@ -562,6 +602,42 @@ export const ProductSheet = ({</AlertDialogFooter></AlertDialogContent></AlertDialog>++ <AlertDialog+ open={showCancelTrial}+ onOpenChange={(open) => {+ if (!open && !cancelTrial.isPending) {+ setShowCancelTrial(false);+ }+ }}+ >+ <AlertDialogContent className="sm:max-w-lg!">+ <AlertDialogHeader>+ <AlertDialogMedia>+ <CalendarX2Icon />+ </AlertDialogMedia>+ <AlertDialogTitle>Cancel your {prod.name} trial?</AlertDialogTitle>+ <AlertDialogDescription>+ {prod.name} drops back to the free tier right away and the trial won't convert to+ a paid plan. You can't restart this trial later.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Keep trial</AlertDialogCancel>+ <AlertDialogAction+ variant="danger"+ isDisabled={cancelTrial.isPending}+ isPending={cancelTrial.isPending}+ onClick={(e) => {+ e.preventDefault();+ handleCancelTrial();+ }}+ >+ Cancel trial+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></>);};