Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(billing): new billing setup (#9053)

Michael Fröhlich2c9afcc58b6d
diff --git a/packages/shared/src/interfaces/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.ts
index cf4c4556cc..49ab1a6c06 100644
--- a/packages/shared/src/interfaces/cloudConfigSchema.ts
+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts
@@ -13,7 +13,14 @@ export const CloudConfigSchema = z.object({
customerId: z.string().optional(),
activeSubscriptionId: z.string().optional(),
activeProductId: z.string().optional(),
+ activeUsageProductId: z.string().optional(),
})
+ .transform((data) => ({
+ ...data,
+ isLegacySubscription:
+ data?.activeProductId !== undefined &&
+ data?.activeUsageProductId === undefined,
+ }))
.optional(),
// custom rate limits for an organization
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a4e5963e61..c7d7cbf017 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -712,8 +712,8 @@ importers:
specifier: ^2.0.7
stripe:
- specifier: ^17.4.0
- version: 17.4.0
+ specifier: ^18.5.0
+ version: 18.5.0(@types/[email protected])
superjson:
specifier: 2.2.2
version: 2.2.2
@@ -11724,6 +11724,15 @@ packages:
resolution: {integrity: sha512-sQQGZguPxe7/QYXJKtDpfzT2OAH9F8nyE2SOsVdTU793iiU33/dpaKgWaJEGJm8396Yy/6NvTLblgdHlueGLhA==}
engines: {node: '>=12.*'}
+ resolution: {integrity: sha512-Hp+wFiEQtCB0LlNgcFh5uVyKznpDjzyUZ+CNVEf+I3fhlYvh7rZruIg+jOwzJRCpy0ZTPMjlzm7J2/M2N6d+DA==}
+ engines: {node: '>=12.*'}
+ peerDependencies:
+ '@types/node': '>=12.x.x'
+ peerDependenciesMeta:
+ '@types/node':
+ optional: true
+
resolution: {integrity: sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==}
@@ -26508,6 +26517,12 @@ snapshots:
'@types/node': 24.3.0
qs: 6.13.0
+ dependencies:
+ qs: 6.14.0
+ optionalDependencies:
+ '@types/node': 24.3.0
+
diff --git a/web/package.json b/web/package.json
index 3c7f58d315..d2e2b7549e 100644
--- a/web/package.json
+++ b/web/package.json
@@ -150,7 +150,7 @@
"remark-rehype": "^11.1.1",
"remark-stringify": "^11.0.0",
"sonner": "^2.0.7",
- "stripe": "^17.4.0",
+ "stripe": "^18.5.0",
"superjson": "2.2.2",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
diff --git a/web/src/app/api/billing/stripe-webhook/route.ts b/web/src/app/api/billing/stripe-webhook/route.ts
index d67829f784..1b59965eba 100644
--- a/web/src/app/api/billing/stripe-webhook/route.ts
+++ b/web/src/app/api/billing/stripe-webhook/route.ts
@@ -1,5 +1,5 @@
-import { stripeWebhookApiHandler } from "@/src/ee/features/billing/server/stripeWebhookApiHandler";
+import { stripeWebhookHandler } from "@/src/ee/features/billing/server/stripeWebhookHandler";
export const dynamic = "force-dynamic";
-export const POST = stripeWebhookApiHandler;
+export const POST = stripeWebhookHandler;
diff --git a/web/src/components/LocalIsoDate.tsx b/web/src/components/LocalIsoDate.tsx
index 9393186d75..182dc21807 100644
--- a/web/src/components/LocalIsoDate.tsx
+++ b/web/src/components/LocalIsoDate.tsx
@@ -1,4 +1,37 @@
-type Accuracy = "minute" | "second" | "millisecond";
+type Accuracy = "day" | "hour" | "minute" | "second" | "millisecond";
+
+export const formatLocalIsoDate = (
+ date: Date,
+ useUTC = false,
+ pAccuracy: Accuracy,
+) => {
+ const pad = (num: number) => String(num).padStart(2, "0");
+
+ const year = useUTC ? date.getUTCFullYear() : date.getFullYear();
+ const month = useUTC ? date.getUTCMonth() + 1 : date.getMonth() + 1;
+ const day = useUTC ? date.getUTCDate() : date.getDate();
+ const hours = useUTC ? date.getUTCHours() : date.getHours();
+ const minutes = useUTC ? date.getUTCMinutes() : date.getMinutes();
+ const seconds = useUTC ? date.getUTCSeconds() : date.getSeconds();
+ const ms = useUTC ? date.getUTCMilliseconds() : date.getMilliseconds();
+
+ let formatted = `${year}-${pad(month)}-${pad(day)}`;
+
+ if (["hour", "minute", "second", "millisecond"].includes(pAccuracy)) {
+ formatted += ` ${pad(hours)}`;
+ }
+ if (["minute", "second", "millisecond"].includes(pAccuracy)) {
+ formatted += `:${pad(minutes)}`;
+ }
+ if (["second", "millisecond"].includes(pAccuracy)) {
+ formatted += `:${pad(seconds)}`;
+ }
+ if (pAccuracy === "millisecond") {
+ formatted += `.${String(ms).padStart(3, "0")}`;
+ }
+
+ return formatted;
+};
export const LocalIsoDate = ({
date,
@@ -13,31 +46,8 @@ export const LocalIsoDate = ({
return null;
}
- const formatDate = (date: Date, useUTC = false, pAccuracy: Accuracy) => {
- const pad = (num: number) => String(num).padStart(2, "0");
-
- const year = useUTC ? date.getUTCFullYear() : date.getFullYear();
- const month = useUTC ? date.getUTCMonth() + 1 : date.getMonth() + 1;
- const day = useUTC ? date.getUTCDate() : date.getDate();
- const hours = useUTC ? date.getUTCHours() : date.getHours();
- const minutes = useUTC ? date.getUTCMinutes() : date.getMinutes();
- const seconds = useUTC ? date.getUTCSeconds() : date.getSeconds();
- const ms = useUTC ? date.getUTCMilliseconds() : date.getMilliseconds();
-
- let formatted = `${year}-${pad(month)}-${pad(day)} ${pad(hours)}:${pad(minutes)}`;
-
- if (["second", "millisecond"].includes(pAccuracy)) {
- formatted += `:${pad(seconds)}`;
- }
- if (pAccuracy === "millisecond") {
- formatted += `.${String(ms).padStart(3, "0")}`;
- }
-
- return formatted;
- };
-
- const localDateString = formatDate(date, false, accuracy);
- const utcDateString = formatDate(date, true, "millisecond");
+ const localDateString = formatLocalIsoDate(date, false, accuracy);
+ const utcDateString = formatLocalIsoDate(date, true, "millisecond");
return (
<span title={`UTC: ${utcDateString}`} className={className}>
diff --git a/web/src/components/table/data-table-pagination.tsx b/web/src/components/table/data-table-pagination.tsx
index 3c44025c70..44731d776e 100644
--- a/web/src/components/table/data-table-pagination.tsx
+++ b/web/src/components/table/data-table-pagination.tsx
@@ -23,12 +23,16 @@ interface DataTablePaginationProps<TData> {
table: Table<TData>;
isLoading: boolean;
paginationOptions?: number[];
+ hideTotalCount?: boolean;
+ canJumpPages?: boolean; // if we need a cursor (last_item_id), we can't jump pages
}
export function DataTablePagination<TData>({
table,
isLoading,
paginationOptions = [10, 20, 30, 40, 50],
+ hideTotalCount = false,
+ canJumpPages = true,
}: DataTablePaginationProps<TData>) {
const capture = usePostHogClientCapture();
@@ -109,61 +113,70 @@ export function DataTablePagination<TData>({
{table.getPageCount() !== -1 ? (
<>
Page
- <Input
- type="number"
- min={1}
- max={pageCount}
- value={inputState} // Ensure the value is within bounds
- onChange={(e) => {
- setInputState(e.target.value);
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") {
- e.preventDefault();
- handlePageNavigation(e.currentTarget.value);
- }
- }}
- onBlur={(e) => {
- handlePageNavigation(e.target.value);
- }}
- className="h-8 appearance-none"
- style={{
- width: `${3 + Math.max(1, pageCount.toString().length)}ch`,
- }}
- />
+ {canJumpPages && (
+ <Input
+ type="number"
+ min={1}
+ max={pageCount}
+ value={inputState} // Ensure the value is within bounds
+ onChange={(e) => {
+ setInputState(e.target.value);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handlePageNavigation(e.currentTarget.value);
+ }
+ }}
+ onBlur={(e) => {
+ handlePageNavigation(e.target.value);
+ }}
+ className="h-8 appearance-none"
+ style={{
+ width: `${3 + Math.max(1, pageCount.toString().length)}ch`,
+ }}
+ />
+ )}
+ {!canJumpPages && <span>{currentPage}</span>}
</>
) : (
`Page ${currentPage}`
)}
- {pageCount !== -1 ? (
- <span>of {pageCount}</span>
- ) : (
- <span>
- of{" "}
- {isLoading ? (
- <LoaderCircle className="ml-1 inline-block h-3 w-3 animate-spin text-muted-foreground" />
+ {!hideTotalCount && (
+ <>
+ {pageCount !== -1 ? (
+ <span>of {pageCount}</span>
) : (
- 1
+ <span>
+ of{" "}
+ {isLoading ? (
+ <LoaderCircle className="ml-1 inline-block h-3 w-3 animate-spin text-muted-foreground" />
+ ) : (
+ 1
+ )}
+ </span>
)}
- </span>
+ </>
)}
</div>
<div className="flex items-center space-x-2">
- <Button
- variant="outline"
- className="hidden h-8 w-8 p-0 lg:flex"
- onClick={() => {
- table.setPageIndex(0);
- capture("table:pagination_button_click", {
- type: "firstPage",
- });
- }}
- disabled={!table.getCanPreviousPage()}
- >
- <span className="sr-only">Go to first page</span>
- <ChevronsLeft className="h-4 w-4" />
- </Button>
+ {canJumpPages && (
+ <Button
+ variant="outline"
+ className="hidden h-8 w-8 p-0 lg:flex"
+ onClick={() => {
+ table.setPageIndex(0);
+ capture("table:pagination_button_click", {
+ type: "firstPage",
+ });
+ }}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <span className="sr-only">Go to first page</span>
+ <ChevronsLeft className="h-4 w-4" />
+ </Button>
+ )}
<Button
variant="outline"
className="h-8 w-8 p-0"
@@ -192,20 +205,22 @@ export function DataTablePagination<TData>({
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4" />
</Button>
- <Button
- variant="outline"
- className="hidden h-8 w-8 p-0 lg:flex"
- onClick={() => {
- table.setPageIndex(pageCount - 1);
- capture("table:pagination_button_click", {
- type: "lastPage",
- });
- }}
- disabled={!table.getCanNextPage() || pageCount === -1}
- >
- <span className="sr-only">Go to last page</span>
- <ChevronsRight className="h-4 w-4" />
- </Button>
+ {canJumpPages && (
+ <Button
+ variant="outline"
+ className="hidden h-8 w-8 p-0 lg:flex"
+ onClick={() => {
+ table.setPageIndex(pageCount - 1);
+ capture("table:pagination_button_click", {
+ type: "lastPage",
+ });
+ }}
+ disabled={!table.getCanNextPage() || pageCount === -1}
+ >
+ <span className="sr-only">Go to last page</span>
+ <ChevronsRight className="h-4 w-4" />
+ </Button>
+ )}
</div>
</div>
</div>
diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsx
index b81e86251d..328f769633 100644
--- a/web/src/components/table/data-table.tsx
+++ b/web/src/components/table/data-table.tsx
@@ -56,6 +56,8 @@ interface DataTableProps<TData, TValue> {
onChange: OnChangeFn<PaginationState>;
state: PaginationState;
options?: number[];
+ hideTotalCount?: boolean;
+ canJumpPages?: boolean;
};
rowSelection?: RowSelectionState;
setRowSelection?: OnChangeFn<RowSelectionState>;
@@ -234,6 +236,7 @@ export function DataTable<TData extends object, TValue>({
maxSize: Number.MAX_SAFE_INTEGER,
},
columnResizeMode: "onChange",
+ autoResetPageIndex: false,
});
const handleOnRowClick = useCallback(
@@ -441,6 +444,8 @@ export function DataTable<TData extends object, TValue>({
table={table}
isLoading={data.isLoading}
paginationOptions={pagination.options}
+ hideTotalCount={pagination.hideTotalCount}
+ canJumpPages={pagination.canJumpPages}
/>
</div>
) : null}
diff --git a/web/src/ee/features/billing/README.md b/web/src/ee/features/billing/README.md
index 9834b5029a..406d750032 100644
--- a/web/src/ee/features/billing/README.md
+++ b/web/src/ee/features/billing/README.md
@@ -2,60 +2,112 @@
## Overview
-This page outlines our integration with **Stripe billing**. The integration supports **usage-based billing** for each organization and project within our product.
+Stripe Billing powers subscriptions and usage-based pricing for organizations. We primarily use the new flexible billing model (plan + usage) and still handle legacy, single-item metered subscriptions during migration.
## Key Concepts
- **Organizations**: Entities within the product that can have multiple projects.
- **Projects**: Sub-entities under organizations where usage is tracked.
-- **Observations**: Units of usage, essentially API calls, tracked at the project level and aggregated for billing on the organization level.
+- **Observations**: Units of usage (API calls), tracked at project level and aggregated for billing per organization.
## Implementation Details
+### API Surface (TRPC)
+
+See `web/src/ee/features/billing/server/cloudBillingRouter.ts`.
+
+- `getSubscriptionInfo` — live cancellation/scheduled-change info from Stripe.
+- `createStripeCheckoutSession` — starts checkout for a product from the catalogue.
+- `changeStripeSubscriptionProduct` — switches plan (upgrade now, downgrade at period end).
+- `cancelStripeSubscription` / `reactivateStripeSubscription` — manage cancellation flags.
+- `clearPlanSwitchSchedule` — releases any active/not-started schedule.
+- `getStripeCustomerPortalUrl` — portal for payment methods, tax IDs, invoices (not for plan switches).
+- `getInvoices` — paginated invoice list with subscription/usage/tax breakdown and preview row.
+- `getUsage` — usage for current period from Stripe preview; falls back to ClickHouse aggregate.
+- `getUsageAlerts` / `upsertUsageAlerts` — toggle and configure Stripe usage alerts. (don't work correctly atm)
+
### Checkout and Subscription Management
-1. **Upgrade Process**:
+Implemented in `web/src/ee/features/billing/server/stripeBillingService.ts`.
- - Organizations can upgrade their plan via the **billing settings**.
- - On the **select plans popup**, only product listed in `stripeProducts.ts` are included.
- - A new **Stripe Checkout session** is created via the API.
- - The **organization ID** is passed to Stripe as a reference.
- - The default price in stripe for each product is used.
+1. **Checkout**
+ - Initiated from billing settings; only products from the catalogue are allowed.
+ - For flexible billing, the session includes two items: plan (quantity 1) + usage.
+ - `subscription_data.billing_mode` is set to flexible; metadata carries `orgId` and `cloudRegion`.
-2. **Stripe WebHooks**:
+2. **Plan Changes**
+ - Upgrades: immediate price swap with proration invoiced now; release any schedules first.
+ - Downgrades: create a subscription schedule to switch at current period end; release existing schedules first.
+ - Legacy handling: migrate classic subscriptions to flexible; replace single metered item with plan+usage or vice versa.
- - **Checkout Session Completion**:
- - On completion, the `customerID` and `activeSubscriptionId` are added to the cloud config of the organization's object.
- - Linked based on the stripe client reference (`stripeClientReference.ts`).
- - **Subscription Changes**:
- - On creation, update, or deletion of a subscription, the **active product ID** is updated in the cloud config of the organization which includes the `activeSubscriptionId`.
+3. **Cancellation / Reactivation**
+ - Cancel sets `cancel_at_period_end` (or clears `cancel_at`); reactivate clears cancellation flags.
+ - Both release any active/not-started subscription schedules first.
-3. **Cloud Config**:
- - Contains the **customer ID**, **activeSubscriptionId**, and **active product ID**.
- - All entitlements within the application are based on the **active product ID** and it's mapping to `Plan` in Langfuse (`stripeProducts.ts`).
- - If a `plan` is included in the cloud config (legacy), no new subscription can be created for the organization. Organizations need to be migrated to the new system.
+4. **Cloud Config**
+ - `cloudConfig.stripe`: `customerId`, `activeSubscriptionId`, `activeProductId`, `activeUsageProductId`.
+ - Entitlements derive from `activeProductId` and catalogue mapping.
+ - If `plan` is set (manual override), creating/changing subscriptions is blocked until removed.
### Usage-Based Pricing
-1. **Usage Meter in Stripe**:
+1. **Usage Meter in Stripe**
+ - Usage is tracked at the Stripe customer level via a meter on the usage item.
+ - The worker reports usage periodically for all orgs with a Stripe customer.
+
+2. **Hourly Job**
+ - Runs in the worker (`cloudUsageMeteringQueue`).
+ - Aggregates last-hour observations and posts to Stripe usage.
+ - Governed by BullMQ repeatables and `cron_jobs` table to ensure singleton execution/backfill.
+
+### Webhooks
+
+See `web/src/ee/features/billing/server/stripeWebhookHandler.ts`.
+
+- Validates signature; ensures events are handled only in the correct `cloudRegion`.
+- Ensures subscription metadata (`orgId`, `cloudRegion`) is set (falls back to checkout session lookup if needed).
+- On subscription created/updated: writes `customerId`, `activeSubscriptionId`, `activeProductId`, `activeUsageProductId` to org `cloudConfig`; on deleted: clears active IDs.
+- On `invoice.created`: recreates usage alert to make alerts fire once per billing period.
+- On `billing.alert.triggered`: emails admins/owners and configured recipients.
+- Invalidates org API keys after subscription changes.
+
+## Testing
+
+Lightweight guidance for local/staging testing. Stripe docs are solid references.
+
+1. Create a test clock in the Stripe sandbox
+ - Use the Stripe Dashboard Test Clocks page: [Test Clocks](https://dashboard.stripe.com/test/billing/subscriptions/test-clocks/).
+ - Create up to three users tied to the clock (e.g., "Test User A", "Test User B").
+2. Prepare an organization in your environment (local or staging)
+ - Insert the Stripe customer on the org DB by setting `cloudConfig` to:
+
+```json
+{ "stripe": { "customerId": "cus_T2dbT3t6hyp9RE" } }
+```
+
+- Note: Required because test clocks cannot be used with existing customers; first create them on the clock.
- - A meter with the ID `trace_observations` is used to track usage.
- - This meter tracks observations at the _customer_ level within Stripe.
+3. Local-only notes
+ - Build and run without dev hot-reload to avoid dropped webhook events:
-2. **Hourly Job**:
+```bash
+NODE_OPTIONS="--max-old-space-size=8192" pnpm build && pnpm start
+```
- - An hourly job runs in the **worker container** (`cloudUsageMeteringQueue`).
- - Logs the number of observations within the last hour to Stripe for all organizations which include a customer ID in the cloud config.
- - The job is managed via
- - BullMQ repeatable jobs: trigger run each hour + potential backfill job on startup of worker container
- - `cron_jobs` postgres table to track the last run time of the job and to prevent multiple instances of the job running.
+- Listen to webhooks:
-## Webhook development
+```bash
+stripe listen --forward-to localhost:3000/api/billing/stripe-webhook
+```
-You can test webhooks via the `stripe` CLI. Step by step guide: https://dashboard.stripe.com/test/webhooks/create?endpoint_location=local
+4. Staging notes
+ - Ensure `STRIPE_WEBHOOK_SIGNING_SECRET` and `STRIPE_SECRET_KEY` point to sandbox and have correct permissions.
+5. Exercise scenarios
+ - Use Stripe Workbench → Shell to send meter events; advance the test clock (only forward in time).
+ - Change subscriptions from the UI; advance time; send events; verify invoices/alerts.
+ - Events must be sent with the current date of the test clock.
-1. `stripe login`
-2. `stripe listen --forward-to localhost:3000/api/billing/stripe-webhook`
-3. Add the API key from the Stripe test environment and the webhook signing secret from the CLI to the `.env` file.
+## Current Limitations
-Upgrade/downgrade projects via the Langfuse billing settings.
+- The Stripe Billing Portal cannot be used for plan switches. Plan changes must go through our API. The client shows an alert explaining implications but does not present a dedicated checkout page for switching plans.
+- Stripe is rolling out a v2 of usage-based billing APIs (private beta as of 2025-09). If revisited, consider adopting v2 to reduce maintenance and custom logic.
diff --git a/web/src/ee/features/billing/components/BillingActionButtons.tsx b/web/src/ee/features/billing/components/BillingActionButtons.tsx
new file mode 100644
index 0000000000..0bb2d6e548
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingActionButtons.tsx
@@ -0,0 +1,58 @@
+// Langfuse Cloud only
+
+import { Button } from "@/src/components/ui/button";
+import Link from "next/link";
+
+import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+import { StripeCustomerPortalButton } from "./StripeCustomerPortalButton";
+import { BillingSwitchPlanDialog } from "./BillingSwitchPlanDialog";
+import { useBillingInformation } from "./useBillingInformation";
+import { StripeCancellationButton } from "./StripeCancellationButton";
+
+export const BillingActionButtons = () => {
+ const { organization } = useBillingInformation();
+ const { setOpen } = useSupportDrawer();
+
+ // Do not show checkout or customer portal if manual plan is set in cloud config
+ if (organization?.cloudConfig?.plan) {
+ return (
+ <div className="mt-4 flex flex-row items-center gap-2">
+ <Button variant="secondary" onClick={() => setOpen(true)}>
+ Change plan (via support)
+ </Button>
+ <Button variant="secondary" asChild>
+ <Link href={"https://langfuse.com/pricing"} target="_blank">
+ Compare plans
+ </Link>
+ </Button>
+ </div>
+ );
+ }
+
+ // Show pricing page button
+ return (
+ <div className="mt-4 flex flex-row items-center gap-2">
+ {/* Always show – also for people who are currently on hobby plan */}
+ <BillingSwitchPlanDialog />
+
+ {organization?.cloudConfig?.stripe?.activeSubscriptionId && (
+ <>
+ <StripeCustomerPortalButton
+ orgId={organization.id}
+ title="Update Billing Details"
+ variant="secondary"
+ />
+ <StripeCancellationButton
+ orgId={organization.id}
+ variant="secondary"
+ />
+ </>
+ )}
+ <Button variant="secondary" asChild>
+ <Link href={"https://langfuse.com/pricing"} target="_blank">
+ Compare plans
+ </Link>
+ </Button>
+ </div>
+ );
+};
diff --git a/web/src/ee/features/billing/components/BillingCurrentPlanLabel.tsx b/web/src/ee/features/billing/components/BillingCurrentPlanLabel.tsx
new file mode 100644
index 0000000000..ae6f719328
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingCurrentPlanLabel.tsx
@@ -0,0 +1,22 @@
+// Langfuse Cloud only
+
+import { LocalIsoDate } from "@/src/components/LocalIsoDate";
+
+import { useBillingInformation } from "@/src/ee/features/billing/components/useBillingInformation";
+
+export const BillingCurrentPlanLabel = () => {
+ const { planLabel, cancellation } = useBillingInformation();
+
+ return (
+ <div>
+ <>Current plan: {planLabel} </>
+ {cancellation?.isCancelled && cancellation.date && (
+ <>
+ <span>(will end on </span>
+ <LocalIsoDate date={cancellation.date} accuracy="day" />
+ <span>)</span>
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/ee/features/billing/components/BillingInvoiceTable.tsx b/web/src/ee/features/billing/components/BillingInvoiceTable.tsx
new file mode 100644
index 0000000000..30cd7ca3dd
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingInvoiceTable.tsx
@@ -0,0 +1,289 @@
+import { DataTable } from "@/src/components/table/data-table";
+import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
+import { type LangfuseColumnDef } from "@/src/components/table/types";
+import { Button } from "@/src/components/ui/button";
+import { Badge } from "@/src/components/ui/badge";
+import { api } from "@/src/utils/api";
+import { usdFormatter } from "@/src/utils/numbers";
+import { Download, ExternalLink } from "lucide-react";
+import { formatLocalIsoDate } from "@/src/components/LocalIsoDate";
+import { useEffect, useMemo, useState } from "react";
+
+type InvoiceRow = {
+ id: string;
+ number: string | null;
+ status: string | null;
+ currency: string;
+ created: Date;
+ hostedInvoiceUrl: string | null;
+ invoicePdfUrl: string | null;
+ breakdown?: {
+ subscriptionCents: number;
+ usageCents: number;
+ discountCents: number;
+ taxCents: number;
+ totalCents: number;
+ };
+};
+
+export function BillingInvoiceTable({ orgId }: { orgId: string }) {
+ const [virtualTotal, setVirtualTotal] = useState(9999);
+ const [paginationState, setPaginationState] = useState<{
+ pageIndex: number;
+ pageSize: number;
+ startingAfter?: string;
+ endingBefore?: string;
+ }>({ pageIndex: 0, pageSize: 10 });
+
+ const invoicesQuery = api.cloudBilling.getInvoices.useQuery({
+ orgId,
+ limit: paginationState.pageSize,
+ startingAfter: paginationState.startingAfter,
+ endingBefore: paginationState.endingBefore,
+ });
+
+ const isFirstPage =
+ !paginationState.startingAfter && !paginationState.endingBefore;
+ const hasMore = invoicesQuery.data?.hasMore ?? false;
+
+ const rows = useMemo(() => {
+ const data = invoicesQuery.data?.invoices ?? [];
+ return data.map((i: any) => ({
+ id: i.id,
+ number: i.number,
+ status: i.status ?? null,
+ currency: i.currency,
+ created: i.created,
+ hostedInvoiceUrl: i.hostedInvoiceUrl,
+ invoicePdfUrl: i.invoicePdfUrl,
+ breakdown: i.breakdown,
+ }));
+ }, [invoicesQuery.data]);
+
+ const data = useMemo(() => {
+ if (invoicesQuery.isPending) {
+ return { isLoading: true, isError: false } as const;
+ }
+ if (invoicesQuery.isError) {
+ return {
+ isLoading: false,
+ isError: true,
+ error: invoicesQuery.error.message,
+ } as const;
+ }
+ return { isLoading: false, isError: false, data: rows } as const;
+ }, [
+ rows,
+ invoicesQuery.isPending,
+ invoicesQuery.isError,
+ invoicesQuery.error,
+ ]);
+
+ useEffect(() => {
+ if (isFirstPage) setVirtualTotal(9999);
+ }, [orgId, paginationState.pageSize, isFirstPage]);
+
+ // When we fetch a page that reports hasMore === false, lock in the exact size
+ useEffect(() => {
+ if (!invoicesQuery.isFetching && !hasMore) {
+ const finalCount =
+ paginationState.pageIndex * paginationState.pageSize + rows.length;
+ setVirtualTotal(finalCount); // one-way only; stays stable afterwards
+ }
+ }, [
+ hasMore,
+ invoicesQuery.isFetching,
+ paginationState.pageIndex,
+ paginationState.pageSize,
+ rows.length,
+ ]);
+
+ const columns: LangfuseColumnDef<InvoiceRow>[] = [
+ {
+ accessorKey: "created",
+ id: "created",
+ header: "Date",
+ cell: ({ row }) => {
+ const value = row.getValue("created") as InvoiceRow["created"];
+ return value
+ ? formatLocalIsoDate(new Date(value), false, "day")
+ : undefined;
+ },
+ size: 90,
+ },
+ {
+ accessorKey: "status",
+ id: "status",
+ header: "Status",
+ size: 100,
+ cell: ({ row }) => {
+ const status = (row.getValue("status") as string | null)?.toLowerCase();
+ if (!status) return null;
+ const variant =
+ status === "paid"
+ ? "secondary"
+ : status === "open"
+ ? "outline"
+ : "default";
+ return <Badge variant={variant as any}>{status}</Badge>;
+ },
+ },
+ {
+ accessorKey: "breakdown.subscriptionCents",
+ id: "subscription",
+ header: "Subscription",
+ size: 100,
+ cell: ({ row }) => {
+ const cents = row.original.breakdown?.subscriptionCents ?? 0;
+ return usdFormatter(cents / 100);
+ },
+ },
+ {
+ accessorKey: "breakdown.usageCents",
+ id: "usage",
+ header: "Usage",
+ size: 90,
+ cell: ({ row }) => {
+ const cents = row.original.breakdown?.usageCents ?? 0;
+ return usdFormatter(cents / 100);
+ },
+ },
+ {
+ accessorKey: "breakdown.discountCents",
+ id: "discounts",
+ header: "Discounts",
+ size: 90,
+ cell: ({ row }) => {
+ const cents = row.original.breakdown?.discountCents ?? 0;
+ return usdFormatter(cents / 100);
+ },
+ },
+ {
+ accessorKey: "breakdown.taxCents",
+ id: "tax",
+ header: "Tax",
+ size: 90,
+ cell: ({ row }) => {
+ const cents = row.original.breakdown?.taxCents ?? 0;
+ return usdFormatter(cents / 100);
+ },
+ },
+ {
+ accessorKey: "breakdown.totalCents",
+ id: "total",
+ header: "Total",
+ size: 90,
+ cell: ({ row }) => {
+ const cents = row.original.breakdown?.totalCents ?? 0;
+ return usdFormatter(cents / 100);
+ },
+ },
+ {
+ accessorKey: "actions",
+ id: "actions",
+ header: "Actions",
+ size: 160,
+ cell: ({ row }) => {
+ const { hostedInvoiceUrl, invoicePdfUrl } = row.original;
+ return (
+ <div className="flex gap-2">
+ {hostedInvoiceUrl ? (
+ <a href={hostedInvoiceUrl} target="_blank" rel="noreferrer">
+ <Button size="sm" variant="ghost">
+ <ExternalLink className="mr-1 h-4 w-4" /> View
+ </Button>
+ </a>
+ ) : null}
+ {invoicePdfUrl ? (
+ <a href={invoicePdfUrl} target="_blank" rel="noreferrer">
+ <Button size="sm" variant="ghost">
+ <Download className="mr-1 h-4 w-4" /> PDF
+ </Button>
+ </a>
+ ) : null}
+ </div>
+ );
+ },
+ },
+ ];
+
+ // Helpers to derive cursors from the current page rows (exclude preview) as fallback
+ const firstNonPreviewId = rows.find((r) => r.id !== "preview")?.id;
+ const lastNonPreviewId = [...rows]
+ .reverse()
+ .find((r) => r.id !== "preview")?.id;
+
+ // 3) Guard "Next" when already at the end to avoid useless queries + flicker
+ const onPaginationChange = (updater: any) => {
+ const next =
+ typeof updater === "function" ? updater(paginationState) : updater;
+
+ // forward click but no more pages? ignore
+ if (next.pageIndex > paginationState.pageIndex && !hasMore) {
+ return;
+ }
+
+ // ... your existing handler unchanged below
+ if (next.pageSize !== paginationState.pageSize) {
+ setPaginationState({
+ ...next,
+ startingAfter: undefined,
+ endingBefore: undefined,
+ });
+ return;
+ }
+ if (next.pageIndex === paginationState.pageIndex) return;
+
+ const freshNext =
+ (invoicesQuery.data as any)?.cursors?.next ?? lastNonPreviewId;
+ const freshPrev =
+ (invoicesQuery.data as any)?.cursors?.prev ?? firstNonPreviewId;
+
+ if (next.pageIndex === 0 && paginationState.pageIndex > 0) {
+ setPaginationState({
+ ...next,
+ startingAfter: undefined,
+ endingBefore: undefined,
+ });
+ } else if (next.pageIndex > paginationState.pageIndex) {
+ setPaginationState({
+ ...next,
+ startingAfter: freshNext,
+ endingBefore: undefined,
+ });
+ } else {
+ setPaginationState({
+ ...next,
+ startingAfter: undefined,
+ endingBefore: freshPrev,
+ });
+ }
+ };
+
+ return (
+ <div className="space-y-0">
+ <div className="flex items-center justify-between pt-4">
+ <h3 className="text-large font-medium">Invoice History</h3>
+ </div>
+ <DataTableToolbar columns={columns} />
+ <DataTable
+ tableName={"invoices"}
+ columns={columns}
+ data={data}
+ pagination={{
+ totalCount: virtualTotal,
+ hideTotalCount: true,
+ canJumpPages: false,
+ onChange: onPaginationChange,
+ state: {
+ pageIndex: paginationState.pageIndex,
+ pageSize: paginationState.pageSize,
+ },
+ options: [10, 20, 30, 40, 50],
+ }}
+ />
+ </div>
+ );
+}
+
+export default BillingInvoiceTable;
diff --git a/web/src/ee/features/billing/components/BillingScheduleNotification.tsx b/web/src/ee/features/billing/components/BillingScheduleNotification.tsx
new file mode 100644
index 0000000000..458425a245
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingScheduleNotification.tsx
@@ -0,0 +1,44 @@
+// Langfuse Cloud only
+
+import { InfoIcon } from "lucide-react";
+import { useBillingInformation } from "./useBillingInformation";
+
+export const BillingScheduleNotification = () => {
+ const { planLabel, cancellation, scheduledPlanSwitch } =
+ useBillingInformation();
+
+ if (!scheduledPlanSwitch && !cancellation) {
+ return null;
+ }
+
+ if (cancellation) {
+ return (
+ <div className="mb-4 mt-6 flex overflow-x-auto rounded-lg border border-blue-200 bg-blue-100 py-2 text-sm text-blue-900 contrast-more:border-current dark:border-blue-200/30 dark:bg-blue-900/30 dark:text-blue-200 contrast-more:dark:border-current ltr:pr-4 rtl:pl-4">
+ <div className="flex items-center gap-2 pl-3 leading-7">
+ <InfoIcon className="h-4 w-4" />
+ {`Your organization cancelled the subscription. Features of the ${planLabel} plan will be available until ${cancellation.formatted}.`}
+ </div>
+ </div>
+ );
+ }
+
+ if (scheduledPlanSwitch) {
+ return (
+ <div className="mb-4 mt-6 flex overflow-x-auto rounded-lg border border-blue-200 bg-blue-100 py-2 text-sm text-blue-900 contrast-more:border-current dark:border-blue-200/30 dark:bg-blue-900/30 dark:text-blue-200 contrast-more:dark:border-current ltr:pr-4 rtl:pl-4">
+ <div className="flex gap-2 pl-3">
+ <InfoIcon className="mt-1 h-4 w-4 flex-shrink-0" />
+ <div>
+ <div className="leading-5">{`Your organization is scheduled to switch from ${planLabel} to ${scheduledPlanSwitch.newPlanLabel} on ${scheduledPlanSwitch.formatted}.`}</div>
+ {scheduledPlanSwitch.message && (
+ <div className="mt-2 leading-5 text-blue-800 dark:text-blue-300">
+ {scheduledPlanSwitch.message}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return null;
+};
diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsx
index 1e8b100230..07019e17ec 100644
--- a/web/src/ee/features/billing/components/BillingSettings.tsx
+++ b/web/src/ee/features/billing/components/BillingSettings.tsx
@@ -1,37 +1,17 @@
// Langfuse Cloud only
-import { Button } from "@/src/components/ui/button";
-import { api } from "@/src/utils/api";
-import { MarkerBar } from "@tremor/react";
-import Link from "next/link";
import Header from "@/src/components/layouts/header";
-import { useQueryOrganization } from "@/src/features/organizations/hooks";
-import { Card } from "@/src/components/ui/card";
-import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";
import { useHasEntitlement } from "@/src/features/entitlements/hooks";
-import { type Plan, planLabels } from "@langfuse/shared";
import { useRouter } from "next/router";
import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
-import { MAX_EVENTS_FREE_PLAN } from "@/src/ee/features/billing/constants";
-import {
- Dialog,
- DialogClose,
- DialogContent,
- DialogFooter,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
- DialogBody,
-} from "@/src/components/ui/dialog";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";
-import { toast } from "sonner";
-import { ActionButton } from "@/src/components/ActionButton";
-import { useState } from "react";
-import { useSupportDrawer } from "@/src/features/support-chat/SupportDrawerProvider";
+
import { UsageAlerts } from "./UsageAlerts";
+import { BillingUsageChart } from "./BillingUsageChart";
+import { BillingActionButtons } from "./BillingActionButtons";
+import { BillingScheduleNotification } from "./BillingScheduleNotification";
+import { BillingInvoiceTable } from "./BillingInvoiceTable";
+import { useBillingInformation } from "./useBillingInformation";
export const BillingSettings = () => {
const router = useRouter();
@@ -43,6 +23,7 @@ export const BillingSettings = () => {
const entitled = useHasEntitlement("cloud-billing");
const isUsageAlertEntitled = useHasEntitlement("cloud-usage-alerts");
+ const billingInfo = useBillingInformation();
if (!entitled) return null;
if (!hasAccess)
@@ -55,314 +36,20 @@ export const BillingSettings = () => {
</AlertDescription>
</Alert>
);
+
return (
<div>
+ <BillingScheduleNotification />
+
<Header title="Usage & Billing" />
<div className="space-y-6">
- <OrganizationUsageChart />
+ <BillingUsageChart />
+ <BillingActionButtons />
{isUsageAlertEntitled && orgId && <UsageAlerts orgId={orgId} />}
- </div>
- </div>
- );
-};
-
-const OrganizationUsageChart = () => {
- const organization = useQueryOrganization();
- const usage = api.cloudBilling.getUsage.useQuery(
- {
- orgId: organization?.id as string,
- },
- {
- enabled: organization !== undefined,
- trpc: {
- context: {
- skipBatch: true,
- },
- },
- },
- );
- const hobbyPlanLimit =
- organization?.cloudConfig?.monthlyObservationLimit ?? MAX_EVENTS_FREE_PLAN;
- const plan: Plan = organization?.plan ?? "cloud:hobby";
- const planLabel = planLabels[plan];
- const usageType = usage.data?.usageType
- ? usage.data.usageType.charAt(0).toUpperCase() +
- usage.data.usageType.slice(1)
- : "Events";
-
- return (
- <div>
- <Card className="p-3">
- {usage.data !== undefined ? (
- <>
- <p className="text-sm text-muted-foreground">
- {usage.data.billingPeriod
- ? `${usageType} in current billing period`
- : `${usageType} / last 30d`}
- </p>
- <div className="text-3xl font-bold">
- {numberFormatter(usage.data.usageCount, 0)}
- </div>
- {plan === "cloud:hobby" && (
- <>
- <div className="mt-4 flex justify-between">
- <span className="text-sm">{`${numberFormatter((usage.data.usageCount / hobbyPlanLimit) * 100)}%`}</span>
- <span className="text-sm">
- Plan limit: {compactNumberFormatter(hobbyPlanLimit)}
- </span>
- </div>
- <MarkerBar
- value={Math.min(
- (usage.data.usageCount / hobbyPlanLimit) * 100,
- 100,
- )}
- className="mt-3"
- />
- </>
- )}
- </>
- ) : (
- <span className="text-sm text-muted-foreground">
- Loading (might take a moment) ...
- </span>
+ {orgId && billingInfo.hasActiveSubscription && (
+ <BillingInvoiceTable orgId={orgId} />
)}
- </Card>
- <div className="mt-2 flex flex-col gap-1 text-sm text-muted-foreground">
- <p>Current plan: {planLabel}</p>
- {usage.data?.billingPeriod && (
- <p>
- {`Billing period: ${usage.data.billingPeriod.start.toLocaleDateString()} - ${usage.data.billingPeriod.end.toLocaleDateString()}`}
- </p>
- )}
- {usage.data?.upcomingInvoice && (
- <p>
- {`Next invoice (current usage): ${usage.data.upcomingInvoice.usdAmount} USD`}
- </p>
- )}
- </div>
- <div className="mt-4 flex flex-row items-center gap-2">
- <BillingPortalOrPricingPageButton />
- <Button variant="secondary" asChild>
- <Link href={"https://langfuse.com/pricing"} target="_blank">
- Compare plans
- </Link>
- </Button>
</div>
</div>
);
};
-
-const BillingPortalOrPricingPageButton = () => {
- const organization = useQueryOrganization();
- const router = useRouter();
- const capture = usePostHogClientCapture();
- const { setOpen } = useSupportDrawer();
- const billingPortalUrl = api.cloudBilling.getStripeCustomerPortalUrl.useQuery(
- {
- orgId: organization?.id as string,
- },
- {
- enabled: organization !== undefined,
- refetchOnMount: false,
- refetchOnReconnect: false,
- refetchOnWindowFocus: false,
- },
- );
-
- const [processingPlanId, setProcessingPlanId] = useState<string | null>(null);
-
- const mutCreateCheckoutSession =
- api.cloudBilling.createStripeCheckoutSession.useMutation({
- onSuccess: (url) => {
- router.push(url);
- setProcessingPlanId(null);
- },
- onError: () => {
- setProcessingPlanId(null);
- },
- });
- const mutChangePlan =
- api.cloudBilling.changeStripeSubscriptionProduct.useMutation({
- onSuccess: () => {
- toast.success("Plan changed successfully");
- setProcessingPlanId(null);
- // wait 1 second before reloading
- setTimeout(() => {
- window.location.reload();
- }, 500);
- },
- onError: () => {
- setProcessingPlanId(null);
- },
- });
-
- // Do not show checkout or customer portal if manual plan is set in cloud config
- if (organization?.cloudConfig?.plan) {
- return (
- <Button variant="secondary" onClick={() => setOpen(true)}>
- Change plan (via support)
- </Button>
- );
- }
-
- const switchPlan = (
- <Dialog
- onOpenChange={(open) => {
- if (open) {
- capture("project_settings:pricing_dialog_opened");
- }
- }}
- >
- <DialogTrigger asChild>
- <Button>Change plan</Button>
- </DialogTrigger>
- <DialogContent className="max-w-5xl">
- <DialogHeader className="flex flex-row items-center justify-between">
- <DialogTitle>Plans</DialogTitle>
- <Button variant="secondary" asChild>
- <Link href="https://langfuse.com/pricing" target="_blank">
- Comparison of plans ↗
- </Link>
- </Button>
- </DialogHeader>
- <DialogBody>
- <div className="mb-3 grid grid-cols-1 gap-3 md:grid-cols-3">
- {stripeProducts
- .filter((product) => Boolean(product.checkout))
- .map((product) => (
- <div
- key={product.stripeProductId}
- className="relative flex flex-col rounded-xl border bg-card p-4 shadow-sm transition-all hover:shadow-md"
- >
- <div className="mb-4">
- <h3 className="text-2xl font-bold">
- {product.checkout?.title}
- </h3>
- <div className="mt-4 space-y-1">
- <div className="text-2xl font-bold text-primary">
- {product.checkout?.price}
- </div>
- <div className="text-sm text-muted-foreground">
- + {product.checkout?.usagePrice}
- </div>
- </div>
- </div>
- <div className="mb-4 text-sm text-muted-foreground">
- {product.checkout?.description}
- </div>
- <div className="space-y-2">
- <div className="text-sm font-medium">Main features:</div>
- <ul className="list-inside list-disc space-y-1 text-sm text-muted-foreground">
- {product.checkout?.mainFeatures.map((feature, index) => (
- <li key={index}>{feature}</li>
- ))}
- </ul>
- </div>
- <Link
- href="https://langfuse.com/pricing"
- target="_blank"
- className="mt-auto block py-4 text-sm text-muted-foreground hover:text-foreground"
- >
- Learn more about plan →
- </Link>
- {organization?.cloudConfig?.stripe?.activeProductId ? (
- // Change plan
- <Dialog>
- <DialogTrigger asChild>
- <Button
- disabled={
- organization?.cloudConfig?.stripe
- ?.activeProductId === product.stripeProductId
- }
- className="w-full"
- >
- {organization?.cloudConfig?.stripe
- ?.activeProductId === product.stripeProductId
- ? "Current plan"
- : "Change plan"}
- </Button>
- </DialogTrigger>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>
- Confirm Change:{" "}
- {planLabels[organization?.plan ?? "cloud:hobby"]} →{" "}
- {product.checkout?.title}
- </DialogTitle>
- <DialogDescription className="pt-2">
- This will immediately generate an invoice for any
- usage on your current plan. Your new plan and
- billing period will start today. Are you sure you
- want to continue?
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <DialogClose asChild>
- <Button variant="secondary">Cancel</Button>
- </DialogClose>
- <ActionButton
- onClick={() => {
- if (organization) {
- setProcessingPlanId(product.stripeProductId);
- mutChangePlan.mutate({
- orgId: organization.id,
- stripeProductId: product.stripeProductId,
- });
- }
- }}
- loading={
- processingPlanId === product.stripeProductId
- }
- >
- Confirm
- </ActionButton>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- ) : (
- // Upgrade, no plan yet
- <ActionButton
- onClick={() => {
- if (organization) {
- setProcessingPlanId(product.stripeProductId);
- mutCreateCheckoutSession.mutate({
- orgId: organization.id,
- stripeProductId: product.stripeProductId,
- });
- }
- }}
- disabled={
- organization?.cloudConfig?.stripe?.activeProductId ===
- product.stripeProductId
- }
- className="w-full"
- loading={processingPlanId === product.stripeProductId}
- >
- Select plan
- </ActionButton>
- )}
- </div>
- ))}
- </div>
- </DialogBody>
- </DialogContent>
- </Dialog>
- );
-
- // Show pricing page button
- return (
- <>
- {switchPlan}
- {billingPortalUrl.data && (
- <>
- <Button asChild>
- <Link href={billingPortalUrl.data}>Update Billing Details</Link>
- </Button>
- <Button variant="secondary" asChild>
- <Link href={billingPortalUrl.data}>Cancel Subscription</Link>
- </Button>
- </>
- )}
- </>
- );
-};
diff --git a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
new file mode 100644
index 0000000000..507cebb86b
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
@@ -0,0 +1,266 @@
+// Langfuse Cloud only
+import { useState } from "react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { nanoid } from "nanoid";
+
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+ DialogBody,
+} from "@/src/components/ui/dialog";
+import { toast } from "sonner";
+
+// planLabels used inside StripeSwitchPlanButton
+import {
+ stripeProducts,
+ isUpgrade,
+} from "@/src/ee/features/billing/utils/stripeCatalogue";
+import { ActionButton } from "@/src/components/ActionButton";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { useBillingInformation } from "@/src/ee/features/billing/components/useBillingInformation";
+import { api } from "@/src/utils/api";
+import { StripeCancellationButton } from "./StripeCancellationButton";
+import { StripeSwitchPlanButton } from "./StripeSwitchPlanButton";
+import { StripeKeepPlanButton } from "./StripeKeepPlanButton";
+
+export const BillingSwitchPlanDialog = () => {
+ const [processingPlanId, setProcessingPlanId] = useState<string | null>(null);
+ const [_opId, setOpId] = useState<string | null>(null);
+
+ const router = useRouter();
+ const {
+ organization,
+ cancellation,
+ scheduledPlanSwitch,
+ isLegacySubscription,
+ } = useBillingInformation();
+ const capture = usePostHogClientCapture();
+
+ const mutCreateCheckoutSession =
+ api.cloudBilling.createStripeCheckoutSession.useMutation({
+ onSuccess: (url) => {
+ router.push(url);
+ setProcessingPlanId(null);
+ setOpId(null);
+ },
+ onError: () => {
+ setProcessingPlanId(null);
+ setOpId(null);
+ toast.error("Failed to start checkout session");
+ },
+ });
+
+ return (
+ <Dialog
+ onOpenChange={(open) => {
+ if (open) {
+ capture("project_settings:pricing_dialog_opened");
+ }
+ }}
+ >
+ <DialogTrigger asChild>
+ <Button>Change plan</Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-5xl">
+ <DialogHeader className="flex flex-row items-center justify-between">
+ <DialogTitle>Plans</DialogTitle>
+ <Button variant="secondary" asChild>
+ <Link href="https://langfuse.com/pricing" target="_blank">
+ Comparison of plans ↗
+ </Link>
+ </Button>
+ </DialogHeader>
+ <DialogBody>
+ <div className="mb-3 grid grid-cols-1 gap-3 md:grid-cols-3">
+ {stripeProducts
+ .filter((product) => Boolean(product.checkout))
+ .map((product) => {
+ const currentProductId =
+ organization?.cloudConfig?.stripe?.activeProductId;
+ const isThisUpgrade = currentProductId
+ ? isUpgrade(currentProductId, product.stripeProductId)
+ : true;
+ const isCurrentPlan =
+ currentProductId === product.stripeProductId;
+
+ return (
+ <div
+ key={product.stripeProductId}
+ className="relative flex flex-col rounded-xl border bg-card p-4 shadow-sm transition-all hover:shadow-md"
+ >
+ <div className="mb-4">
+ {/* Labels above plan title */}
+ <div className="mb-1 h-5 text-xs font-medium text-blue-700">
+ {isCurrentPlan && <span>Current Plan</span>}
+ {scheduledPlanSwitch &&
+ scheduledPlanSwitch.newPlanId ===
+ product.stripeProductId && (
+ <span className="ml-1">Starts next period</span>
+ )}
+ {scheduledPlanSwitch &&
+ organization?.cloudConfig?.stripe?.activeProductId ===
+ product.stripeProductId && (
+ <span className="ml-1">(Until next period)</span>
+ )}
+ {!scheduledPlanSwitch &&
+ cancellation?.isCancelled &&
+ organization?.cloudConfig?.stripe?.activeProductId ===
+ product.stripeProductId && (
+ <span className="ml-1">(Until next period)</span>
+ )}
+ </div>
+ <h3 className="text-2xl font-bold">
+ {product.checkout?.title}
+ </h3>
+ <div className="mt-4 space-y-1">
+ <div className="text-2xl font-bold text-primary">
+ {product.checkout?.price}
+ </div>
+ <div className="text-sm text-muted-foreground">
+ + {product.checkout?.usagePrice}
+ </div>
+ </div>
+ </div>
+ <div className="mb-4 text-sm text-muted-foreground">
+ {product.checkout?.description}
+ </div>
+ <div className="space-y-2">
+ <div className="text-sm font-medium">Main features:</div>
+ <ul className="list-inside list-disc space-y-1 text-sm text-muted-foreground">
+ {product.checkout?.mainFeatures.map(
+ (feature, index) => (
+ <li key={index}>{feature}</li>
+ ),
+ )}
+ </ul>
+ </div>
+ <Link
+ href="https://langfuse.com/pricing"
+ target="_blank"
+ className="mt-auto block py-4 text-sm text-muted-foreground hover:text-foreground"
+ >
+ Learn more about plan →
+ </Link>
+ {/* The default behavior the user is on a paid plan.*/}
+ {organization?.cloudConfig?.stripe?.activeProductId ? (
+ // Change plan view
+ <div className="mt-2 space-y-2">
+ {isCurrentPlan && (
+ <>
+ {/* Reactivate button when cancellation is scheduled on current plan */}
+ {cancellation?.isCancelled && (
+ <StripeCancellationButton
+ orgId={organization?.id}
+ variant="default"
+ className="w-full"
+ />
+ )}
+ {!cancellation?.isCancelled &&
+ scheduledPlanSwitch && (
+ <StripeKeepPlanButton
+ orgId={organization?.id}
+ stripeProductId={product.stripeProductId}
+ onProcessing={setProcessingPlanId}
+ processing={
+ processingPlanId === product.stripeProductId
+ }
+ />
+ )}
+ {!cancellation?.isCancelled &&
+ !scheduledPlanSwitch && (
+ <Button className="w-full" disabled>
+ Current plan
+ </Button>
+ )}
+ </>
+ )}
+ {/* A downgrade is scheduled and this is the new plan */}
+ {!isCurrentPlan &&
+ scheduledPlanSwitch &&
+ scheduledPlanSwitch.newPlanId ===
+ product.stripeProductId && (
+ <Button className="w-full" disabled>
+ Scheduled
+ </Button>
+ )}
+
+ {/* A downgrade is scheduled and this is not the new plan and not the current plan*/}
+ {!isCurrentPlan &&
+ scheduledPlanSwitch &&
+ scheduledPlanSwitch.newPlanId !==
+ product.stripeProductId && (
+ <StripeSwitchPlanButton
+ orgId={organization?.id}
+ currentPlan={organization?.plan}
+ newPlanTitle={product.checkout?.title}
+ isLegacySubscription={isLegacySubscription}
+ isUpgrade={isThisUpgrade}
+ stripeProductId={product.stripeProductId}
+ onProcessing={setProcessingPlanId}
+ processing={
+ processingPlanId === product.stripeProductId
+ }
+ />
+ )}
+
+ {/* The default behavior when it is not the current plan and no schedule exists*/}
+ {!isCurrentPlan && !scheduledPlanSwitch && (
+ <StripeSwitchPlanButton
+ orgId={organization?.id}
+ currentPlan={organization?.plan}
+ newPlanTitle={product.checkout?.title}
+ isLegacySubscription={isLegacySubscription}
+ isUpgrade={isThisUpgrade}
+ stripeProductId={product.stripeProductId}
+ onProcessing={setProcessingPlanId}
+ processing={
+ processingPlanId === product.stripeProductId
+ }
+ />
+ )}
+ </div>
+ ) : (
+ // The default behavior when the user is not on a paid plan.
+ <ActionButton
+ onClick={() => {
+ if (organization) {
+ setProcessingPlanId(product.stripeProductId);
+
+ // idempotency key for mutation operations with the stripe api
+ let opId = _opId;
+ if (!opId) {
+ opId = nanoid();
+ setOpId(opId);
+ }
+
+ mutCreateCheckoutSession.mutate({
+ orgId: organization.id,
+ stripeProductId: product.stripeProductId,
+ opId: opId,
+ });
+ }
+ }}
+ disabled={
+ organization?.cloudConfig?.stripe?.activeProductId ===
+ product.stripeProductId
+ }
+ className="w-full"
+ loading={processingPlanId === product.stripeProductId}
+ >
+ Select plan
+ </ActionButton>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/web/src/ee/features/billing/components/BillingUsageChart.tsx b/web/src/ee/features/billing/components/BillingUsageChart.tsx
new file mode 100644
index 0000000000..e7446d40bd
--- /dev/null
+++ b/web/src/ee/features/billing/components/BillingUsageChart.tsx
@@ -0,0 +1,85 @@
+// Langfuse Cloud only
+
+import { api } from "@/src/utils/api";
+import { MarkerBar } from "@tremor/react";
+import { useQueryOrganization } from "@/src/features/organizations/hooks";
+import { Card } from "@/src/components/ui/card";
+import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";
+import { type Plan } from "@langfuse/shared";
+import { MAX_EVENTS_FREE_PLAN } from "@/src/ee/features/billing/constants";
+import { formatLocalIsoDate } from "@/src/components/LocalIsoDate";
+import { BillingCurrentPlanLabel } from "./BillingCurrentPlanLabel";
+
+export const BillingUsageChart = () => {
+ const organization = useQueryOrganization();
+
+ const usage = api.cloudBilling.getUsage.useQuery(
+ {
+ orgId: organization?.id as string,
+ },
+ {
+ enabled: organization !== undefined,
+ trpc: {
+ context: {
+ skipBatch: true,
+ },
+ },
+ },
+ );
+
+ const hobbyPlanLimit =
+ organization?.cloudConfig?.monthlyObservationLimit ?? MAX_EVENTS_FREE_PLAN;
+ const plan: Plan = organization?.plan ?? "cloud:hobby";
+ const usageType = usage.data?.usageType
+ ? usage.data.usageType.charAt(0).toUpperCase() +
+ usage.data.usageType.slice(1)
+ : "Events";
+
+ return (
+ <div>
+ <Card className="p-3">
+ {usage.data !== undefined ? (
+ <>
+ <p className="text-sm text-muted-foreground">
+ {usage.data.billingPeriod
+ ? `${usageType} in current billing period`
+ : `${usageType} / last 30d`}
+ </p>
+ <div className="text-3xl font-bold">
+ {numberFormatter(usage.data.usageCount, 0)}
+ </div>
+ {plan === "cloud:hobby" && (
+ <>
+ <div className="mt-4 flex justify-between">
+ <span className="text-sm">{`${numberFormatter((usage.data.usageCount / hobbyPlanLimit) * 100)}%`}</span>
+ <span className="text-sm">
+ Plan limit: {compactNumberFormatter(hobbyPlanLimit)}
+ </span>
+ </div>
+ <MarkerBar
+ value={Math.min(
+ (usage.data.usageCount / hobbyPlanLimit) * 100,
+ 100,
+ )}
+ className="mt-3"
+ />
+ </>
+ )}
+ </>
+ ) : (
+ <span className="text-sm text-muted-foreground">
+ Loading (might take a moment) ...
+ </span>
+ )}
+ </Card>
+ <div className="mt-2 flex flex-col gap-1 text-sm text-muted-foreground">
+ <BillingCurrentPlanLabel />
+ {usage.data?.billingPeriod && (
+ <p>
+ {`Billing period: ${formatLocalIsoDate(usage.data.billingPeriod.start, false, "day")} - ${formatLocalIsoDate(usage.data.billingPeriod.end, false, "day")}`}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/ee/features/billing/components/StripeCancellationButton.tsx b/web/src/ee/features/billing/components/StripeCancellationButton.tsx
new file mode 100644
index 0000000000..da8357f3a5
--- /dev/null
+++ b/web/src/ee/features/billing/components/StripeCancellationButton.tsx
@@ -0,0 +1,175 @@
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { useBillingInformation } from "./useBillingInformation";
+import { api } from "@/src/utils/api";
+import { useState } from "react";
+import { toast } from "sonner";
+import { nanoid } from "nanoid";
+
+export const StripeCancellationButton = ({
+ orgId,
+ variant,
+ className,
+}: {
+ orgId: string | undefined;
+ variant: "secondary" | "default";
+ className?: string;
+}) => {
+ const { cancellation } = useBillingInformation();
+ const [loading, setLoading] = useState(false);
+ const [_opId, setOpId] = useState<string | null>(null);
+
+ const cancelMutation = api.cloudBilling.cancelStripeSubscription.useMutation({
+ onSuccess: () => {
+ toast.success("Subscription will be cancelled at period end");
+ setLoading(false);
+ setOpId(null);
+ setTimeout(() => window.location.reload(), 500);
+ },
+ onError: () => {
+ setLoading(false);
+ setOpId(null);
+ toast.error("Failed to cancel subscription");
+ },
+ });
+
+ const reactivateMutation =
+ api.cloudBilling.reactivateStripeSubscription.useMutation({
+ onSuccess: () => {
+ toast.success("Subscription reactivated");
+ setLoading(false);
+ setOpId(null);
+ setTimeout(() => window.location.reload(), 500);
+ },
+ onError: () => {
+ setLoading(false);
+ setOpId(null);
+ toast.error("Failed to reactivate subscription");
+ },
+ });
+
+ if (!orgId) return null;
+
+ const onReactivate = async () => {
+ try {
+ setLoading(true);
+ // idempotency key for mutation operations with the stripe api
+ let opId = _opId;
+ if (!opId) {
+ opId = nanoid();
+ setOpId(opId);
+ }
+ await reactivateMutation.mutateAsync({ orgId, opId });
+ } catch (e) {
+ toast.error("Failed to reactivate subscription");
+ }
+ };
+
+ const onCancel = async () => {
+ try {
+ setLoading(true);
+ // idempotency key for mutation operations with the stripe api
+ let opId = _opId;
+ if (!opId) {
+ opId = nanoid();
+ setOpId(opId);
+ }
+ await cancelMutation.mutateAsync({ orgId, opId });
+ } catch (e) {
+ toast.error("Failed to cancel subscription");
+ }
+ };
+
+ // Reactivate with confirm dialog
+ if (cancellation?.isCancelled) {
+ return (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button
+ variant={variant}
+ disabled={loading}
+ title="Reactivate Subscription"
+ className={className}
+ >
+ {loading ? "Working…" : "Reactivate Subscription"}
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="text-lg">
+ Confirm Reactivation: Keep Your Subscription
+ </DialogTitle>
+ </DialogHeader>
+ <DialogBody className="text-sm">
+ <p>
+ Reactivating removes the scheduled cancellation. Your subscription
+ will continue beyond the current billing period and renew until
+ you cancel again.
+ </p>
+ <p>
+ Your features and usage billing remain unchanged. By confirming,
+ you agree to future renewals and charges.
+ </p>
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="secondary">Cancel</Button>
+ </DialogClose>
+ <Button variant="default" onClick={onReactivate} disabled={loading}>
+ {loading ? "Reactivating…" : "Confirm Reactivation"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+ }
+
+ // Cancel with confirm dialog
+ return (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button
+ variant={variant}
+ disabled={loading}
+ title="Cancel Subscription"
+ >
+ Cancel Subscription
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="text-lg">Confirm Cancellation</DialogTitle>
+ </DialogHeader>
+ <DialogBody className="text-sm">
+ <p>
+ Your subscription will not renew. You will retain access until the
+ end of the current billing period
+ </p>
+ <p>
+ Usage during the remainder of the period is still billed under your
+ current plan. By confirming, you schedule the cancellation for
+ period end. You can reactivate before that date if you change your
+ mind.
+ </p>
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="secondary">Keep Subscription</Button>
+ </DialogClose>
+ <Button variant="destructive" onClick={onCancel} disabled={loading}>
+ {loading ? "Cancelling…" : "Confirm Cancellation"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx b/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx
new file mode 100644
index 0000000000..a973ae57df
--- /dev/null
+++ b/web/src/ee/features/billing/components/StripeCustomerPortalButton.tsx
@@ -0,0 +1,85 @@
+import { Button } from "@/src/components/ui/button";
+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
+import { api } from "@/src/utils/api";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+
+export const StripeCustomerPortalButton = ({
+ orgId,
+ title,
+ variant,
+}: {
+ orgId: string | undefined;
+ title: string;
+ variant: "secondary" | "default";
+}) => {
+ const hasAccess = useHasOrganizationAccess({
+ organizationId: orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ });
+
+ const [loading, setLoading] = useState(false);
+
+ useEffect(() => {
+ // Make sure loading is always false when the user enters the page, even when navigation back via browser back button
+ const reset = () => setLoading(false);
+ const onPageShow = () => setLoading(false); // fires on bfcache restore
+ const onVisibility = () => {
+ if (document.visibilityState === "visible") setLoading(false);
+ };
+
+ window.addEventListener("focus", reset);
+ window.addEventListener("pageshow", onPageShow);
+ document.addEventListener("visibilitychange", onVisibility);
+
+ return () => {
+ window.removeEventListener("focus", reset);
+ window.removeEventListener("pageshow", onPageShow);
+ document.removeEventListener("visibilitychange", onVisibility);
+ };
+ }, []);
+
+ const portalQuery = api.cloudBilling.getStripeCustomerPortalUrl.useQuery(
+ { orgId: orgId as string },
+ {
+ enabled: false,
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ refetchOnWindowFocus: false,
+ },
+ );
+
+ const onClick = async () => {
+ if (!orgId) return;
+ try {
+ setLoading(true);
+ const { data, error } = await portalQuery.refetch();
+ if (error) throw error;
+ if (data) {
+ window.location.href = data;
+ } else {
+ toast.error("Could not open billing portal");
+ }
+ } catch (e) {
+ toast.error("Failed to open billing portal");
+ } finally {
+ // do not reset to avoid flickering when opening the portal
+ // setLoading(false);
+ }
+ };
+
+ if (!hasAccess) {
+ return null;
+ }
+
+ return (
+ <Button
+ variant={variant}
+ onClick={onClick}
+ disabled={!orgId || loading}
+ title={title}
+ >
+ {loading ? "Opening…" : title}
+ </Button>
+ );
+};
diff --git a/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx b/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx
new file mode 100644
index 0000000000..62008100ed
--- /dev/null
+++ b/web/src/ee/features/billing/components/StripeKeepPlanButton.tsx
@@ -0,0 +1,95 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { api } from "@/src/utils/api";
+import { toast } from "sonner";
+import { nanoid } from "nanoid";
+
+export const StripeKeepPlanButton = ({
+ orgId,
+ stripeProductId,
+ onProcessing,
+ processing,
+}: {
+ orgId: string | undefined;
+ stripeProductId: string;
+ onProcessing: (id: string | null) => void;
+ processing: boolean;
+}) => {
+ const [_opId, setOpId] = useState<string | null>(null);
+
+ const clearSchedule = api.cloudBilling.clearPlanSwitchSchedule.useMutation({
+ onSuccess: () => {
+ toast.success("Kept current plan");
+ onProcessing(null);
+ setOpId(null);
+ setTimeout(() => window.location.reload(), 500);
+ },
+ onError: () => {
+ onProcessing(null);
+ setOpId(null);
+ toast.error("Failed to keep current plan");
+ },
+ });
+
+ if (!orgId) return null;
+
+ return (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button className="w-full" variant="default">
+ Keep Plan
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="text-lg">
+ Confirm Keeping Current Plan
+ </DialogTitle>
+ </DialogHeader>
+ <DialogBody className="text-sm">
+ <p>
+ You have a scheduled plan change on your current subscription.
+ Keeping your current plan will remove that schedule and you will
+ remain on your existing plan.
+ </p>
+ <p>
+ Your features and pricing will stay as-is; usage continues to be
+ billed under your current plan. Do you want to keep your current
+ plan and cancel the scheduled change?
+ </p>
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="secondary">Go Back</Button>
+ </DialogClose>
+ <Button
+ variant="default"
+ onClick={() => {
+ onProcessing(stripeProductId);
+ // idempotency key for mutation operations with the stripe api
+ let opId = _opId;
+ if (!opId) {
+ opId = nanoid();
+ setOpId(opId);
+ }
+ clearSchedule.mutate({ orgId, opId });
+ }}
+ disabled={processing}
+ >
+ {processing ? "Keeping…" : "Confirm Keep Plan"}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx b/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx
new file mode 100644
index 0000000000..100f72cc20
--- /dev/null
+++ b/web/src/ee/features/billing/components/StripeSwitchPlanButton.tsx
@@ -0,0 +1,146 @@
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import {
+ Dialog,
+ DialogBody,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import { ActionButton } from "@/src/components/ActionButton";
+import { planLabels } from "@langfuse/shared";
+import { api } from "@/src/utils/api";
+import { toast } from "sonner";
+import { nanoid } from "nanoid";
+
+export const StripeSwitchPlanButton = ({
+ className,
+ orgId,
+ currentPlan,
+ newPlanTitle,
+ isLegacySubscription,
+ isUpgrade,
+ stripeProductId,
+ onProcessing,
+ processing,
+}: {
+ orgId: string | undefined;
+ currentPlan: keyof typeof planLabels | undefined;
+ newPlanTitle: string | undefined;
+ isLegacySubscription: boolean;
+ isUpgrade: boolean;
+ stripeProductId: string;
+ onProcessing: (id: string | null) => void;
+ processing: boolean;
+ className?: string;
+}) => {
+ const [_opId, setOpId] = useState<string | null>(null);
+
+ const mutChangePlan =
+ api.cloudBilling.changeStripeSubscriptionProduct.useMutation({
+ onSuccess: () => {
+ toast.success("Plan changed successfully");
+ onProcessing(null);
+ setOpId(null);
+ setTimeout(() => window.location.reload(), 500);
+ },
+ onError: () => {
+ onProcessing(null);
+ setOpId(null);
+ toast.error("Failed to change plan");
+ },
+ });
+
+ if (!orgId) return null;
+
+ return (
+ <Dialog>
+ <DialogTrigger asChild>
+ <Button className="w-full">Change plan</Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle className="text-lg">
+ Confirm Your Change: {planLabels[currentPlan ?? "cloud:hobby"]} →{" "}
+ {newPlanTitle}
+ </DialogTitle>
+ </DialogHeader>
+ <DialogBody className="text-sm">
+ {isLegacySubscription ? (
+ <>
+ <p>
+ We will end your current subscription now and start a new one
+ immediately.
+ </p>
+ <p>
+ You will receive an invoice today that includes (1) the base fee
+ for the new plan for a fresh billing period starting today and
+ (2) your base-fee and usage to date on the previous
+ subscription.
+ </p>
+ <p>
+ By confirming, you accept the immediate invoice and plan
+ activation starting now.
+ </p>
+ </>
+ ) : isUpgrade ? (
+ <>
+ <p>
+ You will be charged a prorated base fee today for the remainder
+ of this billing period. Features update immediately; usage-based
+ charges continue for the rest of the billing period.
+ </p>
+ <p>
+ Example: if your plan is $199/month and you upgrade halfway
+ through the month to a $499/month plan, the prorated charge is
+ roughly $99.5 + $249.5 (plus taxes). Exact amounts depend on
+ timing and tax.
+ </p>
+ <p>
+ By confirming, you accept the prorated charge and immediate plan
+ change.
+ </p>
+ </>
+ ) : (
+ <>
+ <p>
+ No charge is made today. You stay on your current plan until the
+ end of this billing period, then we switch you to the new plan.
+ You can switch back anytime.
+ </p>
+ <p>
+ Usage continues to be billed under your current plan until the
+ switch. By confirming, you schedule the change at period end and
+ understand features will adjust at that time.
+ </p>
+ </>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="secondary">Cancel</Button>
+ </DialogClose>
+ <ActionButton
+ onClick={() => {
+ onProcessing(stripeProductId);
+ // idempotency key for mutation operations with the stripe api
+ let opId = _opId;
+ if (!opId) {
+ opId = nanoid();
+ setOpId(opId);
+ }
+ mutChangePlan.mutate({ orgId, stripeProductId, opId });
+ }}
+ loading={processing}
+ className={className}
+ >
+ Confirm
+ </ActionButton>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/web/src/ee/features/billing/components/useBillingInformation.tsx b/web/src/ee/features/billing/components/useBillingInformation.tsx
new file mode 100644
index 0000000000..7d285bc2c7
--- /dev/null
+++ b/web/src/ee/features/billing/components/useBillingInformation.tsx
@@ -0,0 +1,106 @@
+import { useMemo } from "react";
+
+import { useQueryOrganization } from "@/src/features/organizations/hooks";
+import { formatLocalIsoDate } from "@/src/components/LocalIsoDate";
+import { type Plan, planLabels } from "@langfuse/shared";
+import { stripeProducts } from "@/src/ee/features/billing/utils/stripeCatalogue";
+import { api } from "@/src/utils/api";
+
+export type BillingCancellationInfo = {
+ isCancelled: boolean;
+ date: Date | null;
+ formatted: string | null;
+};
+
+export type BillingScheduledSwitchInfo = {
+ isScheduled: boolean;
+ date: Date | null;
+ formatted: string | null;
+ newPlanLabel: string | null;
+ newPlanId: string | null;
+ scheduleId: string | undefined;
+ message: string | null | undefined;
+};
+
+export type UseBillingInformationResult = {
+ organization: ReturnType<typeof useQueryOrganization>;
+ planLabel: string;
+ cancellation: BillingCancellationInfo | null;
+ scheduledPlanSwitch: BillingScheduledSwitchInfo | null;
+ isLegacySubscription: boolean;
+ hasActiveSubscription: boolean;
+};
+
+export const useBillingInformation = (): UseBillingInformationResult => {
+ const organization = useQueryOrganization();
+ const { data: subscriptionInfo } =
+ api.cloudBilling.getSubscriptionInfo.useQuery(
+ { orgId: organization?.id ?? "" },
+ { enabled: Boolean(organization?.id) },
+ );
+
+ const planLabel = useMemo(() => {
+ if (organization?.plan) {
+ return planLabels[organization.plan as Plan];
+ }
+ return planLabels["cloud:hobby"];
+ }, [organization]);
+
+ const cancellation = useMemo<BillingCancellationInfo | null>(() => {
+ const cancel = subscriptionInfo?.cancellation;
+ if (!cancel) return null;
+ try {
+ const date =
+ typeof cancel.cancelAt === "number" && !Number.isNaN(cancel.cancelAt)
+ ? new Date(cancel.cancelAt * 1000)
+ : null;
+ if (!date || date.getTime() <= Date.now()) return null;
+ const formatted = formatLocalIsoDate(date, false, "day");
+ return { isCancelled: true, date, formatted };
+ } catch {
+ return null;
+ }
+ }, [subscriptionInfo]);
+
+ const scheduledPlanSwitch = useMemo<BillingScheduledSwitchInfo | null>(() => {
+ const sc = subscriptionInfo?.scheduledChange;
+ if (!sc?.switchAt) return null;
+ try {
+ const date =
+ typeof sc.switchAt === "number" && !Number.isNaN(sc.switchAt)
+ ? new Date(sc.switchAt * 1000)
+ : null;
+ if (!date || date.getTime() <= Date.now()) return null;
+ const formatted = formatLocalIsoDate(date, false, "day");
+ const newPlanId = sc.newProductId;
+ const product = newPlanId
+ ? stripeProducts.find((p) => p.stripeProductId === newPlanId)
+ : undefined;
+ const newPlanLabel = product ? planLabels[product.mappedPlan] : null;
+ return {
+ isScheduled: true,
+ date,
+ formatted,
+ newPlanLabel,
+ newPlanId: newPlanId ?? null,
+ scheduleId: sc.scheduleId,
+ message: sc.message ?? null,
+ };
+ } catch {
+ return null;
+ }
+ }, [subscriptionInfo]);
+
+ return {
+ organization,
+ planLabel,
+ cancellation,
+ scheduledPlanSwitch,
+ isLegacySubscription: Boolean(
+ organization?.cloudConfig?.stripe?.isLegacySubscription,
+ ),
+ hasActiveSubscription: Boolean(
+ organization?.cloudConfig?.stripe?.activeSubscriptionId,
+ ),
+ };
+};
diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.ts
index 46557fdcdf..d86a592d22 100644
--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts
+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts
@@ -1,31 +1,49 @@
-import { createStripeClientReference } from "@/src/ee/features/billing/stripeClientReference";
-import { stripeClient } from "@/src/ee/features/billing/utils/stripe";
-import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";
-import { env } from "@/src/env.mjs";
+import * as z from "zod/v4";
+
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+
import { parseDbOrg } from "@langfuse/shared";
import {
createTRPCRouter,
protectedOrganizationProcedure,
} from "@/src/server/api/trpc";
import { TRPCError } from "@trpc/server";
-import * as z from "zod/v4";
import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";
import { auditLog } from "@/src/features/audit-logs/auditLog";
-import {
- getObservationCountOfProjectsSinceCreationDate,
- getScoreCountOfProjectsSinceCreationDate,
- getTraceCountOfProjectsSinceCreationDate,
- logger,
-} from "@langfuse/shared/src/server";
-import { UsageAlertService } from "./usageAlertService";
+import { logger } from "@langfuse/shared/src/server";
+import { createBillingServiceFromContext } from "./stripeBillingService";
export const cloudBillingRouter = createTRPCRouter({
+ getSubscriptionInfo: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ opId: z.string().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+
+ const res = await createBillingServiceFromContext(
+ ctx,
+ ).getSubscriptionInfo(input.orgId);
+ return res;
+ }),
createStripeCheckoutSession: protectedOrganizationProcedure
.input(
z.object({
orgId: z.string(),
stripeProductId: z.string(),
+ opId: z.string().optional(),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -40,124 +58,28 @@ export const cloudBillingRouter = createTRPCRouter({
orgId: input.orgId,
});
- const org = await ctx.prisma.organization.findUnique({
- where: {
- id: input.orgId,
- },
- });
- if (!org) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Organization not found",
- });
- }
-
- const parsedOrg = parseDbOrg(org);
- if (parsedOrg.cloudConfig?.plan)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message:
- "Cannot initialize stripe checkout for orgs that have a manual/legacy plan",
- });
-
- if (!stripeClient)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Stripe client not initialized",
- });
-
- const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
- const stripeActiveSubscriptionId =
- parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
- if (stripeActiveSubscriptionId) {
- // If the org has a customer ID, do not return checkout options, should use the billing portal instead
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Organization already has an active subscription",
- });
- }
-
- if (
- !stripeProducts.some(
- (product) =>
- Boolean(product.checkout) &&
- product.stripeProductId === input.stripeProductId,
- )
- )
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Invalid stripe product id",
- });
-
- const product = await stripeClient.products.retrieve(
+ const stripeBillingService = createBillingServiceFromContext(ctx);
+ const url = await stripeBillingService.createCheckoutSession(
+ input.orgId,
input.stripeProductId,
);
- if (!product.default_price) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Product does not have a default price in Stripe",
- });
- }
-
- const returnUrl = `${env.NEXTAUTH_URL}/organization/${input.orgId}/settings`;
- const session = await stripeClient.checkout.sessions.create({
- customer: stripeCustomerId,
- line_items: [
- {
- price: product.default_price as string,
- },
- ],
- client_reference_id:
- createStripeClientReference(input.orgId) ?? undefined,
- allow_promotion_codes: true,
- tax_id_collection: {
- enabled: true,
- },
- automatic_tax: {
- enabled: true,
- },
- consent_collection: {
- terms_of_service: "required",
- },
- ...(stripeCustomerId
- ? {
- customer_update: {
- name: "auto",
- address: "auto",
- },
- }
- : {}),
- billing_address_collection: "required",
- success_url: returnUrl,
- cancel_url: returnUrl,
- mode: "subscription",
- metadata: {
- orgId: input.orgId,
- cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ?? null,
- },
- });
-
- if (!session.url)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Failed to create checkout session",
- });
- auditLog({
+ void auditLog({
session: ctx.session,
orgId: input.orgId,
- resourceType: "stripeCheckoutSession",
- resourceId: session.id,
- action: "create",
+ resourceType: "organization",
+ resourceId: input.orgId,
+ action: "BillingService.createStripeCheckoutSession",
});
- return session.url;
+ return url;
}),
changeStripeSubscriptionProduct: protectedOrganizationProcedure
.input(
z.object({
orgId: z.string(),
stripeProductId: z.string(),
+ opId: z.string().optional(),
}),
)
.mutation(async ({ input, ctx }) => {
@@ -172,115 +94,88 @@ export const cloudBillingRouter = createTRPCRouter({
orgId: input.orgId,
});
- // check that product is valid
- if (
- !stripeProducts
- .filter((i) => Boolean(i.checkout))
- .map((i) => i.stripeProductId)
- .includes(input.stripeProductId)
- )
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Invalid stripe product id, product not available",
- });
+ const stripeBillingService = createBillingServiceFromContext(ctx);
- const org = await ctx.prisma.organization.findUnique({
- where: {
- id: input.orgId,
- },
+ await stripeBillingService.changePlan(input.orgId, input.stripeProductId);
+ }),
+ cancelStripeSubscription: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ opId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
});
- if (!org) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Organization not found",
- });
- }
-
- const parsedOrg = parseDbOrg(org);
- if (parsedOrg.cloudConfig?.plan)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Cannot change plan for orgs that have a manual/legacy plan",
- });
-
- const stripeSubscriptionId =
- parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
- if (!stripeSubscriptionId)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Organization does not have an active subscription",
- });
+ const stripeBillingService = createBillingServiceFromContext(ctx);
- if (!stripeClient)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Stripe client not initialized",
- });
+ await stripeBillingService.cancel(input.orgId, input.opId);
- const subscription =
- await stripeClient.subscriptions.retrieve(stripeSubscriptionId);
+ return { ok: true } as const;
+ }),
+ reactivateStripeSubscription: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ opId: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
- if (
- ["canceled", "paused", "incomplete", "incomplete_expired"].includes(
- subscription.status,
- )
- )
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message:
- "Subscription is not active, current status: " +
- subscription.status,
- });
+ const stripeBillingService = createBillingServiceFromContext(ctx);
- if (subscription.items.data.length !== 1)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Subscription has multiple items",
- });
+ await stripeBillingService.reactivate(input.orgId, input.opId);
- const item = subscription.items.data[0];
+ return { ok: true } as const;
+ }),
+ clearPlanSwitchSchedule: protectedOrganizationProcedure
+ .input(z.object({ orgId: z.string(), opId: z.string().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
- if (
- !stripeProducts
- .map((i) => i.stripeProductId)
- .includes(item.price.product as string)
- )
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Current subscription product is not a valid product",
- });
+ const stripeBillingService = createBillingServiceFromContext(ctx);
- const newProduct = await stripeClient.products.retrieve(
- input.stripeProductId,
+ await stripeBillingService.clearPlanSwitchSchedule(
+ input.orgId,
+ input.opId,
);
- if (!newProduct.default_price)
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "New product does not have a default price in Stripe",
- });
- await stripeClient.subscriptions.update(stripeSubscriptionId, {
- items: [
- // remove current product from subscription
- {
- id: item.id,
- deleted: true,
- },
- // add new product to subscription
- {
- price: newProduct.default_price as string,
- },
- ],
- // reset billing cycle which causes immediate invoice for existing plan
- billing_cycle_anchor: "now",
- proration_behavior: "none",
- });
+ return { ok: true } as const;
}),
getStripeCustomerPortalUrl: protectedOrganizationProcedure
.input(
z.object({
orgId: z.string(),
+ opId: z.string().optional(),
}),
)
.query(async ({ input, ctx }) => {
@@ -295,45 +190,32 @@ export const cloudBillingRouter = createTRPCRouter({
session: ctx.session,
});
- const org = await ctx.prisma.organization.findUnique({
- where: {
- id: input.orgId,
- },
- });
- if (!org) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Organization not found",
+ try {
+ return await createBillingServiceFromContext(ctx).getCustomerPortalUrl(
+ input.orgId,
+ );
+ } catch (error) {
+ logger.error("cloudBilling.getStripeCustomerPortalUrl:error", {
+ orgId: input.orgId,
+ error,
});
- }
-
- if (!stripeClient)
+ if (error instanceof TRPCError) {
+ throw error;
+ }
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
- message: "Stripe client not initialized",
+ message: `Stripe error: ${error instanceof Error ? error.message : "Unknown Stripe error"}`,
+ cause: error as Error,
});
-
- const parsedOrg = parseDbOrg(org);
- let stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
- let stripeSubscriptionId =
- parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
- if (!stripeCustomerId || !stripeSubscriptionId) {
- // Do not create a new customer if the org is on a plan (assigned manually)
- return null;
}
-
- const billingPortalSession =
- await stripeClient.billingPortal.sessions.create({
- customer: stripeCustomerId,
- return_url: `${env.NEXTAUTH_URL}/organization/${input.orgId}/settings/billing`,
- });
-
- return billingPortalSession.url;
}),
- getUsage: protectedOrganizationProcedure
+ getInvoices: protectedOrganizationProcedure
.input(
z.object({
orgId: z.string(),
+ limit: z.number().int().min(1).max(100).default(10),
+ startingAfter: z.string().optional(),
+ endingBefore: z.string().optional(),
}),
)
.query(async ({ input, ctx }) => {
@@ -348,109 +230,55 @@ export const cloudBillingRouter = createTRPCRouter({
session: ctx.session,
});
- const organization = await ctx.prisma.organization.findUnique({
- where: {
- id: input.orgId,
- },
- include: {
- projects: {
- select: {
- id: true,
- },
+ try {
+ return await createBillingServiceFromContext(ctx).getInvoices(
+ input.orgId,
+ {
+ limit: input.limit,
+ startingAfter: input.startingAfter,
+ endingBefore: input.endingBefore,
},
- },
- });
- if (!organization) {
+ );
+ } catch (error) {
+ logger.error("cloudBilling.getInvoices:error", {
+ orgId: input.orgId,
+ error,
+ });
+ if (error instanceof TRPCError) {
+ throw error;
+ }
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
- message: "Organization not found",
+ message: `Stripe error: ${error instanceof Error ? error.message : "Unknown Stripe error"}`,
+ cause: error as Error,
});
}
- const parsedOrg = parseDbOrg(organization);
-
- // For Stripe subscriptions, we can get usage from the Stripe Metered Billing API
- if (
- stripeClient &&
- parsedOrg.cloudConfig?.stripe?.customerId &&
- parsedOrg.cloudConfig?.stripe?.activeSubscriptionId
- ) {
- const subscription = await stripeClient.subscriptions.retrieve(
- parsedOrg.cloudConfig.stripe.activeSubscriptionId,
- );
- if (subscription) {
- const billingPeriod = {
- start: new Date(subscription.current_period_start * 1000),
- end: new Date(subscription.current_period_end * 1000),
- };
-
- try {
- const stripeInvoice = await stripeClient.invoices.retrieveUpcoming({
- subscription: parsedOrg.cloudConfig.stripe.activeSubscriptionId,
- });
- const upcomingInvoice = {
- usdAmount: stripeInvoice.amount_due / 100,
- date: new Date(stripeInvoice.period_end * 1000),
- };
- const usageInvoiceLines = stripeInvoice.lines.data.filter((line) =>
- Boolean(line.plan?.meter),
- );
- const usage = usageInvoiceLines.reduce((acc, line) => {
- if (line.quantity) {
- return acc + line.quantity;
- }
- return acc;
- }, 0);
- // get meter for usage type (units or observations)
- const meterId = usageInvoiceLines[0]?.plan?.meter;
- const meter = meterId
- ? await stripeClient.billing.meters.retrieve(meterId)
- : undefined;
-
- return {
- usageCount: usage,
- usageType: meter?.display_name.toLowerCase() ?? "units",
- billingPeriod,
- upcomingInvoice,
- };
- } catch (e) {
- logger.error(
- "Failed to get usage from Stripe, using usage from Clickhouse",
- {
- error: e,
- },
- );
- }
- }
- }
-
- // Free plan, usage not tracked on Stripe, get usage from Clickhouse
- const thirtyDaysAgo = new Date();
- thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
- thirtyDaysAgo.setHours(0, 0, 0, 0);
- const projectIds = organization.projects.map((p) => p.id);
+ }),
+ getUsage: protectedOrganizationProcedure
+ .input(
+ z.object({
+ orgId: z.string(),
+ opId: z.string().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "cloud-billing",
+ sessionUser: ctx.session.user,
+ orgId: input.orgId,
+ });
+ throwIfNoOrganizationAccess({
+ organizationId: input.orgId,
+ scope: "langfuseCloudBilling:CRUD",
+ session: ctx.session,
+ });
- const [countTraces, countObservations, countScores] = await Promise.all([
- getTraceCountOfProjectsSinceCreationDate({
- projectIds,
- start: thirtyDaysAgo,
- }),
- getObservationCountOfProjectsSinceCreationDate({
- projectIds,
- start: thirtyDaysAgo,
- }),
- getScoreCountOfProjectsSinceCreationDate({
- projectIds,
- start: thirtyDaysAgo,
- }),
- ]);
+ const stripeBillingService = createBillingServiceFromContext(ctx);
- return {
- usageCount: countTraces + countObservations + countScores,
- usageType: "units",
- };
+ return await stripeBillingService.getUsage(input.orgId);
}),
getUsageAlerts: protectedOrganizationProcedure
- .input(z.object({ orgId: z.string() }))
+ .input(z.object({ orgId: z.string(), opId: z.string().optional() }))
.query(async ({ input, ctx }) => {
throwIfNoEntitlement({
entitlement: "cloud-billing",
@@ -504,146 +332,25 @@ export const cloudBillingRouter = createTRPCRouter({
session: ctx.session,
});
- const org = await ctx.prisma.organization.findUnique({
- where: {
- id: input.orgId,
- },
- });
- if (!org) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Organization not found",
- });
- }
-
- const parsedOrg = parseDbOrg(org);
- const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
- const subscriptionId =
- parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
- const currentAlerts = parsedOrg.cloudConfig?.usageAlerts;
-
- if (!stripeCustomerId || !subscriptionId) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message:
- "Organization must have a Stripe customer with active subscription to configure usage alerts",
- });
- }
-
- if (!stripeClient) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message: "Stripe client not initialized",
- });
- }
-
- let updatedAlerts = input.usageAlerts;
-
- // Get the meterId for the given subscription
- const subscription =
- await stripeClient.subscriptions.retrieve(subscriptionId);
- if (!subscription) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Stripe subscription not found",
- });
- }
- const meterId = subscription.items.data.filter((subItem) =>
- Boolean(subItem.plan.meter),
- )[0]?.plan.meter;
-
try {
- const updatedUsageAlertConfig = {
- enabled: updatedAlerts.enabled,
- type: "STRIPE",
- threshold: updatedAlerts.threshold,
- alertId: currentAlerts?.alertId ?? null, // Keep the existing alert ID if it exists
- meterId: meterId ?? null, // Use the meter ID from the subscription
- notifications: {
- email: updatedAlerts.notifications.email,
- recipients: updatedAlerts.notifications.recipients,
- },
- };
-
- // Disable the usage alert if it got disabled
- if (
- !updatedAlerts.enabled &&
- currentAlerts?.alertId &&
- currentAlerts?.enabled
- ) {
- await UsageAlertService.getInstance({
- stripeClient,
- }).deactivate({ id: currentAlerts?.alertId });
- }
-
- // If there is no existing alert, create a new one
- if (!currentAlerts?.alertId) {
- const alert = await UsageAlertService.getInstance({
- stripeClient,
- }).create({
- orgId: input.orgId,
- customerId: stripeCustomerId,
- meterId,
- amount: updatedAlerts.threshold,
- });
- updatedUsageAlertConfig.alertId = alert.id;
- }
-
- // If there is an existing alert with a different amount or meterId, replace it
- if (
- updatedAlerts.enabled &&
- currentAlerts?.alertId &&
- (currentAlerts?.threshold !== updatedAlerts.threshold ||
- currentAlerts.meterId !== meterId)
- ) {
- const alert = await UsageAlertService.getInstance({
- stripeClient,
- }).recreate({
- orgId: input.orgId,
- customerId: stripeCustomerId,
- meterId,
- existingAlertId: currentAlerts.alertId,
- amount: updatedAlerts.threshold,
- });
- updatedUsageAlertConfig.alertId = alert.id;
- }
-
- // If there is an existing, inactive alert, reactivate it
- if (
- updatedAlerts.enabled &&
- currentAlerts?.alertId &&
- !currentAlerts.enabled
- ) {
- await UsageAlertService.getInstance({
- stripeClient,
- }).activate({ id: currentAlerts.alertId });
- }
-
- // Update organization with new usage alerts configuration
- const newCloudConfig = {
- ...parsedOrg.cloudConfig,
- usageAlerts: updatedUsageAlertConfig,
- };
-
- const updatedOrg = await ctx.prisma.organization.update({
- where: {
- id: input.orgId,
- },
- data: {
- cloudConfig: newCloudConfig,
- },
+ const orgBefore = await ctx.prisma.organization.findUnique({
+ where: { id: input.orgId },
});
-
- await auditLog({
+ const updatedAlerts = await createBillingServiceFromContext(
+ ctx,
+ ).upsertUsageAlerts(input.orgId, input.usageAlerts);
+ const orgAfter = await ctx.prisma.organization.findUnique({
+ where: { id: input.orgId },
+ });
+ void auditLog({
session: ctx.session,
orgId: input.orgId,
resourceType: "organization",
resourceId: input.orgId,
action: "updateUsageAlerts",
- before: org,
- after: updatedOrg,
+ before: orgBefore!,
+ after: orgAfter!,
});
-
return updatedAlerts;
} catch (error) {
logger.error("Failed to update usage alerts", {
diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.ts
new file mode 100644
index 0000000000..b14892f1ba
--- /dev/null
+++ b/web/src/ee/features/billing/server/stripeBillingService.ts
@@ -0,0 +1,1491 @@
+import type Stripe from "stripe";
+import { TRPCError } from "@trpc/server";
+import { type OrgAuthedContext } from "@/src/server/api/trpc";
+
+import { env } from "@/src/env.mjs";
+
+import { parseDbOrg } from "@langfuse/shared";
+import {
+ getTraceCountOfProjectsSinceCreationDate,
+ getObservationCountOfProjectsSinceCreationDate,
+ getScoreCountOfProjectsSinceCreationDate,
+ logger,
+} from "@langfuse/shared/src/server";
+
+import {
+ type Expanded,
+ type ExpandedNullable,
+ isExpanded,
+ isExpandedOrNullable,
+} from "@/src/ee/features/billing/utils/stripeExpand";
+import { stripeClient as defaultStripeClient } from "@/src/ee/features/billing/utils/stripe";
+import { StripeCatalogue } from "@/src/ee/features/billing/utils/stripeCatalogue";
+import { createStripeClientReference } from "@/src/ee/features/billing/utils/stripeClientReference";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+
+import {
+ makeIdempotencyKey,
+ IdempotencyKind,
+} from "@/src/ee/features/billing/utils/stripeIdempotencyKey";
+
+import { UsageAlertService } from "./usageAlertService";
+import { type StripeSubscriptionMetadata } from "@/src/ee/features/billing/utils/stripeSubscriptionMetadata";
+
+type ProductWithDefaultPrice = Expanded<Stripe.Product, "default_price">;
+type SubscriptionWithSchedule = ExpandedNullable<
+ Stripe.Subscription,
+ "schedule"
+>;
+export type BillingSubscriptionInfo = {
+ cancellation: {
+ cancelAt: number;
+ } | null;
+ scheduledChange: {
+ scheduleId: string;
+ switchAt: number;
+ newProductId?: string;
+ message?: string | null;
+ } | null;
+};
+
+class BillingService {
+ constructor(
+ private stripe: Stripe,
+ private ctx: OrgAuthedContext,
+ ) {}
+
+ /** Returns true if a Price is metered (classic `usage_type` or flexible `recurring.meter`). */
+ private isMetered(price: Stripe.Price | undefined): boolean {
+ if (!price) return false;
+ if (price.recurring?.usage_type === "metered") return true;
+ if ((price.recurring as any)?.meter) return true;
+ return false;
+ }
+
+ private async getParsedOrg(orgId: string) {
+ const org = await this.ctx.prisma.organization.findUnique({
+ where: { id: orgId },
+ });
+ if (!org) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Organization not found",
+ });
+ }
+ return {
+ org,
+ parsedOrg: parseDbOrg(org),
+ } as const;
+ }
+
+ private async getParsedOrgWithProjects(orgId: string) {
+ const org = await this.ctx.prisma.organization.findUnique({
+ where: { id: orgId },
+ include: { projects: { select: { id: true } } },
+ });
+ if (!org) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Organization not found",
+ });
+ }
+ return { org, parsedOrg: parseDbOrg(org) };
+ }
+
+ private async retrieveSubscriptionWithSchedule(
+ client: Stripe,
+ subscriptionId: string,
+ ): Promise<SubscriptionWithSchedule> {
+ const subscription = await client.subscriptions.retrieve(subscriptionId, {
+ expand: ["schedule"],
+ });
+
+ const schedule = subscription.schedule;
+
+ if (!isExpandedOrNullable(schedule)) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: `Stripe Error: Could not expand schedule on subscription ${subscriptionId}`,
+ });
+ }
+
+ return { ...subscription, schedule: schedule };
+ }
+
+ private async retrieveProductWithDefaultPrice(
+ client: Stripe,
+ productId: string,
+ ): Promise<ProductWithDefaultPrice> {
+ const product = await client.products.retrieve(productId, {
+ expand: ["default_price"],
+ });
+
+ const defaultPrice = product.default_price;
+
+ if (!isExpanded(defaultPrice)) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: `Stripe Error: Could not expand default_price on product ${productId}`,
+ });
+ }
+
+ return { ...product, default_price: defaultPrice };
+ }
+
+ private async retrieveInvoiceList(
+ stripeCustomerId: string,
+ subscriptionId: string,
+ limit: number,
+ startingAfter?: string,
+ endingBefore?: string,
+ ) {
+ const client = this.stripe;
+
+ const result = await client.invoices.list({
+ customer: stripeCustomerId,
+ subscription: subscriptionId, // one customer may have multiple subscriptions (one per org)
+ limit: limit,
+ starting_after: startingAfter,
+ ending_before: endingBefore,
+ });
+
+ return result;
+ }
+
+ private async createInvoicePreview(
+ client: Stripe,
+ stripeCustomerId: string,
+ subscriptionId: string,
+ ) {
+ const subscription = await client.subscriptions.retrieve(subscriptionId);
+
+ const canCreateInvoicePreview = [
+ "active",
+ "past_due",
+ "trialing",
+ "unpaid",
+ ].includes(subscription.status);
+
+ if (!canCreateInvoicePreview) {
+ return null;
+ }
+
+ return await client.invoices.createPreview({
+ customer: stripeCustomerId,
+ subscription: subscriptionId,
+ });
+ }
+
+ private async releaseExistingSubscriptionScheduleIfAny(
+ subscription: SubscriptionWithSchedule,
+ opId?: string,
+ ) {
+ const client = this.stripe;
+ const schedule = subscription.schedule;
+
+ if (!schedule) {
+ return; // no schedule to release
+ }
+
+ if (!["active", "not_started"].includes(schedule.status)) {
+ logger.info(
+ "stripeBillingService.releaseExistingSubscriptionScheduleIfAny:scheduleNotActive (skipping release)",
+ {
+ scheduleId: schedule.id,
+ status: schedule.status,
+ },
+ );
+ return;
+ }
+ const idempotencyKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.schedule.release"],
+ fields: { scheduleId: schedule.id },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.schedule.release", {
+ scheduleId: schedule.id,
+ status: schedule.status,
+ idempotencyKey,
+ opId,
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user?.email,
+ });
+ await client.subscriptionSchedules.release(
+ schedule.id,
+ {},
+ {
+ idempotencyKey: makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.schedule.release"],
+ fields: { scheduleId: schedule.id },
+ opId,
+ }),
+ },
+ );
+ }
+
+ // ================================================
+ // === Public methods ===
+ // ================================================
+
+ // Returned shape for getSubscriptionInfo
+
+ /**
+ * Fetch live subscription info from Stripe for cancellation and upcoming plan changes.
+ * Does not persist anything to the database.
+ */
+ async getSubscriptionInfo(orgId: string): Promise<BillingSubscriptionInfo> {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+
+ if (!subscriptionId) {
+ // No active subscription → nothing scheduled
+ return { cancellation: null, scheduledChange: null };
+ }
+
+ const subscription = await this.retrieveSubscriptionWithSchedule(
+ client,
+ subscriptionId,
+ );
+
+ // Cancellation info (supports classic and flexible billing)
+ const nowSec = Math.floor(Date.now() / 1000);
+
+ let cancellation: { cancelAt: number } | null = null;
+
+ if (
+ typeof subscription.cancel_at === "number" &&
+ subscription.cancel_at > nowSec
+ ) {
+ cancellation = {
+ cancelAt: subscription.cancel_at,
+ };
+ } else if (subscription.cancel_at_period_end === true) {
+ const end = subscription.items.data[0].current_period_end;
+ if (typeof end === "number" && end > nowSec) {
+ cancellation = {
+ cancelAt: end,
+ };
+ }
+ }
+
+ // Next scheduled change from subscription schedule phases
+ let scheduledChange: {
+ scheduleId: string;
+ switchAt: number;
+ newProductId?: string;
+ message?: string | null;
+ } | null = null;
+
+ const schedule = subscription.schedule;
+ if (schedule && ["active", "not_started"].includes(schedule.status)) {
+ // Retrieve schedule with expanded prices to identify non-metered plan item
+ const fullSchedule = await client.subscriptionSchedules.retrieve(
+ schedule.id,
+ { expand: ["phases.items.price"] },
+ );
+
+ const phases = fullSchedule.phases ?? [];
+ const nextPhase = phases.find((p) => (p.start_date ?? 0) > nowSec);
+
+ if (nextPhase) {
+ // identify the plan (non-metered) item to expose the product id
+ const nonMeteredItem = (nextPhase.items ?? []).find((it) => {
+ if (!isExpanded(it.price)) {
+ logger.warn(
+ "StripeBillingService.getSubscriptionInfo:stripe.subscription.schedule.nextPhase.item.price.notExpanded",
+ {
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user?.email,
+ customerId: parsedOrg.cloudConfig?.stripe?.customerId,
+ subscriptionId:
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId,
+ orgId: parsedOrg.id,
+ scheduleId: fullSchedule.id,
+ priceId: it.price,
+ },
+ );
+ return false;
+ }
+
+ if (it.price?.deleted) {
+ logger.warn(
+ "StripeBillingService.getSubscriptionInfo:stripe.subscription.schedule.nextPhase.item.price.deleted",
+ {
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user?.email,
+ customerId: parsedOrg.cloudConfig?.stripe?.customerId,
+ subscriptionId:
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId,
+ orgId: parsedOrg.id,
+ scheduleId: fullSchedule.id,
+ priceId: it.price,
+ },
+ );
+ return false;
+ }
+
+ return !this.isMetered(it.price);
+ });
+
+ let newProductId: string | undefined = undefined;
+ if (nonMeteredItem) {
+ const price = nonMeteredItem.price as Stripe.Price | undefined;
+ if (price?.product) {
+ newProductId =
+ typeof price.product === "string"
+ ? price.product
+ : price.product.id;
+ }
+ }
+
+ scheduledChange = {
+ scheduleId: fullSchedule.id,
+ switchAt: nextPhase.start_date as number,
+ newProductId,
+ message: fullSchedule.metadata?.message ?? null, // shows up in the users UI
+ };
+ }
+ }
+
+ return { cancellation, scheduledChange };
+ }
+
+ /**
+ * Get a Stripe Billing Portal session URL for an organization.
+ *
+ * Throws when the organization lacks a Stripe customer or active subscription.
+ *
+ * @param orgId Organization id
+ * @returns Hosted portal URL (string)
+ */
+ async getCustomerPortalUrl(orgId: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
+ const stripeSubscriptionId =
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+
+ if (!stripeCustomerId || !stripeSubscriptionId) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "No stripe customer or subscription found",
+ });
+ }
+
+ const billingPortalSession = await client.billingPortal.sessions.create({
+ customer: stripeCustomerId,
+ return_url: `${env.NEXTAUTH_URL}/organization/${orgId}/settings/billing`,
+ });
+
+ return billingPortalSession.url;
+ }
+
+ /**
+ * Create a Stripe Checkout session to start a subscription for the given product.
+ * Validates product against the catalogue and handles legacy vs new plan setup.
+ *
+ * @param orgId Organization id
+ * @param stripeProductId Stripe Product id for the subscription plan
+ * @returns Redirect URL to Stripe Checkout
+ */
+ async createCheckoutSession(orgId: string, stripeProductId: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ if (parsedOrg.cloudConfig?.plan) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "Cannot initialize stripe checkout for orgs that have a manual plan override",
+ });
+ }
+
+ if (!StripeCatalogue.isValidCheckoutProduct(stripeProductId)) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Invalid stripe product id",
+ });
+ }
+
+ const product = await this.retrieveProductWithDefaultPrice(
+ client,
+ stripeProductId,
+ );
+
+ // TODO: Cleanup after all customers are migrated to the new system
+ const lineItems = await (async () => {
+ const isLegacyProduct = this.isMetered(product.default_price);
+
+ if (isLegacyProduct) {
+ return [{ price: product.default_price.id }];
+ }
+
+ const usageProduct = await this.retrieveProductWithDefaultPrice(
+ client,
+ StripeCatalogue.usageProductId(),
+ );
+
+ return [
+ { price: product.default_price.id, quantity: 1 },
+ { price: usageProduct.default_price.id },
+ ];
+ })();
+
+ const returnUrl = `${env.NEXTAUTH_URL}/organization/${orgId}/settings/billing`;
+ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
+ const clientReferenceId = createStripeClientReference(orgId);
+ const subscriptionMetadata: StripeSubscriptionMetadata = {
+ orgId: orgId,
+ cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
+ };
+
+ const sessionConfig: Stripe.Checkout.SessionCreateParams = {
+ customer: stripeCustomerId,
+ line_items: lineItems,
+ client_reference_id: clientReferenceId,
+ allow_promotion_codes: true,
+ tax_id_collection: {
+ enabled: true,
+ },
+ automatic_tax: {
+ enabled: true,
+ },
+ consent_collection: {
+ terms_of_service: "required",
+ },
+ ...(stripeCustomerId
+ ? {
+ customer_update: {
+ name: "auto",
+ address: "auto",
+ },
+ }
+ : {}),
+ billing_address_collection: "required",
+ success_url: returnUrl,
+ cancel_url: returnUrl,
+ mode: "subscription",
+ subscription_data: {
+ // Note: metadata should always be treated as optional since
+ // we cannot rely on it being set (e.g., manual subscription creation in stripe)
+ metadata: subscriptionMetadata,
+ billing_mode: {
+ type: "flexible",
+ },
+ },
+ };
+
+ logger.info("stripeBillingService.checkout.session.create", {
+ customerId: stripeCustomerId,
+ productId: stripeProductId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+
+ const session = await client.checkout.sessions.create(sessionConfig);
+
+ if (!session.url) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to create checkout session",
+ });
+ }
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.createCheckoutSession",
+ before: parsedOrg.cloudConfig,
+ });
+
+ return session.url;
+ }
+
+ /**
+ * Change an organization's active subscription to a new product.
+ *
+ * Behavior:
+ * - Upgrades: immediate price swap with proration invoiced now
+ * - Downgrades: create a subscription schedule to switch at period end
+ * - Legacy: replace single metered item with plan+usage or vice versa
+ *
+ * @param orgId Organization id
+ * @param newProductId Stripe Product id to switch to
+ */
+ async changePlan(orgId: string, newProductId: string, opId?: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ if (parsedOrg.cloudConfig?.plan)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Cannot change plan for orgs that have a manually set plan",
+ });
+
+ const stripeSubscriptionId =
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+
+ if (!stripeSubscriptionId)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Organization does not have an active subscription",
+ });
+
+ const subscription = await this.retrieveSubscriptionWithSchedule(
+ client,
+ stripeSubscriptionId,
+ );
+
+ if (
+ ["canceled", "paused", "incomplete", "incomplete_expired"].includes(
+ subscription.status,
+ )
+ ) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "Subscription is not active, current status: " + subscription.status,
+ });
+ }
+
+ if (!StripeCatalogue.isValidCheckoutProduct(newProductId)) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Invalid stripe product id for new product",
+ });
+ }
+
+ const newProduct = await this.retrieveProductWithDefaultPrice(
+ client,
+ newProductId,
+ );
+
+ // If the users changes the plan, we want to cancel any pending cancellations
+ const cancellationPayload = subscription.cancel_at
+ ? { cancel_at: null }
+ : { cancel_at_period_end: false };
+
+ // [A] Legacy Plan Setup: Switch from / to legacy plans
+ // ------------------------------------------------------------------------------------------------
+ // TODO: Cleanup after all customers are migrated to the new system
+ const isNewProductLegacy =
+ newProduct.default_price.recurring?.usage_type === "metered";
+ const isExistingSubscriptionLegacy =
+ parsedOrg.cloudConfig?.stripe?.isLegacySubscription === true;
+
+ if (isExistingSubscriptionLegacy || isNewProductLegacy) {
+ const usageProduct = await this.retrieveProductWithDefaultPrice(
+ client,
+ StripeCatalogue.usageProductId(),
+ );
+
+ const newLineItems = isNewProductLegacy
+ ? [{ price: newProduct.default_price.id }]
+ : [
+ { price: newProduct.default_price.id, quantity: 1 },
+ { price: usageProduct.default_price.id },
+ ];
+
+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);
+ const legacyUpdateKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.update.product"],
+ fields: {
+ subscriptionId: stripeSubscriptionId,
+ to: newProduct.default_price.id,
+ },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.update.product", {
+ subscriptionId: stripeSubscriptionId,
+ fromProductId: subscription.items.data[0]?.price.product,
+ toProductId: newProduct.default_price.id,
+ isLegacy: true,
+ idempotencyKey: legacyUpdateKey,
+ opId,
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ await client.subscriptions.update(
+ stripeSubscriptionId,
+ {
+ items: [
+ ...subscription.items.data.map((i) => ({
+ id: i.id,
+ deleted: true,
+ })),
+ ...newLineItems,
+ ],
+ billing_cycle_anchor: "now",
+ proration_behavior: "none",
+ ...cancellationPayload,
+ },
+ { idempotencyKey: legacyUpdateKey },
+ );
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.changePlan",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+ return;
+ }
+ // [A] End ----------------------------------------------------------------------------------------
+
+ // Helper to migrate all users who are still on classic over to flexible billing
+ if (subscription.billing_mode?.type === "classic") {
+ const migrateKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.migrate.flexible"],
+ fields: { subscriptionId: stripeSubscriptionId },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.migrate.flexible", {
+ customerId: subscription.customer,
+ subscriptionId: stripeSubscriptionId,
+ idempotencyKey: migrateKey,
+ orgId: parsedOrg.id,
+ opId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ await client.subscriptions.migrate(
+ stripeSubscriptionId,
+ { billing_mode: { type: "flexible" } },
+ { idempotencyKey: migrateKey },
+ );
+ }
+
+ // [B] New Plan Setup: Switch between new plans
+ // ------------------------------------------------------------------------------------------------
+ const subscriptionProductItem = subscription.items.data.find(
+ (i) => i.price.recurring?.usage_type !== "metered",
+ );
+ if (!subscriptionProductItem)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Current subscription does not contain a plan item",
+ });
+
+ const currentSubscriptionProductId =
+ typeof subscriptionProductItem.price.product === "string"
+ ? subscriptionProductItem.price.product
+ : subscriptionProductItem.price.product.id;
+
+ if (!StripeCatalogue.isValidCheckoutProduct(currentSubscriptionProductId)) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Invalid stripe product id for existing subscription product",
+ });
+ }
+
+ const upgrading = StripeCatalogue.isUpgrade(
+ currentSubscriptionProductId,
+ newProductId,
+ );
+
+ // [B.1] Upgrade Path: Switch from lower to higher plan (-> Prorated immediate switch)
+ // -----------------------------------------------------
+ if (upgrading) {
+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);
+
+ const upgradeKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.update.product"],
+ fields: {
+ subscriptionId: stripeSubscriptionId,
+ to: newProduct.default_price.id,
+ },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.update.product", {
+ customerId: subscription.customer,
+ subscriptionId: stripeSubscriptionId,
+ fromProductId: currentSubscriptionProductId,
+ toProductId: newProductId,
+ orgId: parsedOrg.id,
+ isUpgrade: true,
+ idempotencyKey: upgradeKey,
+ opId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ await client.subscriptions.update(
+ stripeSubscriptionId,
+ {
+ items: [
+ {
+ id: subscriptionProductItem.id, // the old item to replace
+ price: newProduct.default_price.id, // price identifies the product
+ quantity: 1,
+ },
+ // usage items stays the same
+ ],
+ proration_behavior: "always_invoice",
+ ...cancellationPayload,
+ },
+ { idempotencyKey: upgradeKey },
+ );
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.changePlan",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+
+ return;
+ }
+
+ // [B.2] Downgrade Path: Switch from higher to lower plan (-> Subscription Schedule)
+ // -----------------------------------------------------
+ const currentPeriodEndSec = subscriptionProductItem.current_period_end;
+
+ const nextPhaseItems = subscription.items.data.map((i) => {
+ const isMetered = this.isMetered(i.price);
+
+ // replace the subscription product item with the new product
+ if (i.id === subscriptionProductItem.id) {
+ return { price: newProduct.default_price.id, quantity: 1 };
+ }
+
+ // keep the existing items
+ return {
+ price: i.price.id,
+ ...(isMetered ? {} : { quantity: i.quantity ?? 1 }),
+ };
+ });
+
+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);
+
+ const createScheduleKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.schedule.create.fromSub"],
+ fields: { subscriptionId: stripeSubscriptionId },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.schedule.create.fromSub", {
+ subscriptionId: stripeSubscriptionId,
+ idempotencyKey: createScheduleKey,
+ opId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ const initialSchedule = await client.subscriptionSchedules.create(
+ {
+ from_subscription: stripeSubscriptionId,
+ },
+ { idempotencyKey: createScheduleKey },
+ ); // not possible to set any items here, if we use from_subscription
+
+ const existingDiscounts = initialSchedule.phases[0]?.discounts || [];
+ const newDiscounts = existingDiscounts.map((discount) => {
+ if (discount.coupon) {
+ return {
+ coupon:
+ typeof discount.coupon === "string"
+ ? discount.coupon
+ : discount.coupon.id,
+ };
+ } else if (discount.promotion_code) {
+ return {
+ promotion_code:
+ typeof discount.promotion_code === "string"
+ ? discount.promotion_code
+ : discount.promotion_code.id,
+ };
+ } else if (discount.discount) {
+ return {
+ discount:
+ typeof discount.discount === "string"
+ ? discount.discount
+ : discount.discount.id,
+ };
+ }
+ return {};
+ });
+
+ const updateScheduleKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.schedule.update"],
+ fields: { scheduleId: initialSchedule.id },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.schedule.update", {
+ scheduleId: initialSchedule.id,
+ customerId: subscription.customer,
+ orgId: parsedOrg.id,
+ subscriptionId: stripeSubscriptionId,
+ fromProductId: currentSubscriptionProductId,
+ toProductId: newProductId,
+ switchAt: currentPeriodEndSec,
+ idempotencyKey: updateScheduleKey,
+ opId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ await client.subscriptionSchedules.update(
+ initialSchedule.id,
+ {
+ end_behavior: "release",
+ phases: [
+ {
+ start_date: initialSchedule.phases[0].start_date,
+ end_date: currentPeriodEndSec,
+ items: initialSchedule.phases[0]!.items as any,
+ proration_behavior: "none",
+ },
+ {
+ start_date: currentPeriodEndSec,
+ end_date: currentPeriodEndSec + 120, // trigger the schedule release 120 seconds after it was applied
+ items: nextPhaseItems,
+ proration_behavior: "none",
+ discounts: newDiscounts,
+ },
+ ],
+ // TODO: Cleanup – discontinue metadata for functional purposes
+ metadata: {
+ subscriptionId: stripeSubscriptionId,
+ reason: "planSwitch.Downgrade",
+ newProductId,
+ usageProductId: StripeCatalogue.usageProductId(),
+ switchAt: currentPeriodEndSec,
+ orgId,
+ },
+ },
+ { idempotencyKey: updateScheduleKey },
+ );
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.changePlan",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+
+ return;
+ // [B] End ----------------------------------------------------------------------------------------
+ }
+
+ /**
+ * Cancel the active subscription at period end. Releases any pending schedules first.
+ *
+ * @param orgId Organization id
+ */
+ async cancel(orgId: string, opId?: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+ if (!subscriptionId)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "No active subscription to cancel",
+ });
+
+ const subscription = await this.retrieveSubscriptionWithSchedule(
+ client,
+ subscriptionId,
+ );
+
+ // If the user cancels the subscription, we want to release the existing schedule
+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);
+
+ const cancelKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.cancelAtPeriodEnd"],
+ fields: { subscriptionId },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.cancelAtPeriodEnd", {
+ subscriptionId,
+ idempotencyKey: cancelKey,
+ opId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ await client.subscriptions.update(
+ subscriptionId,
+ {
+ cancel_at_period_end: true,
+ proration_behavior: "none",
+ },
+ { idempotencyKey: cancelKey },
+ );
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.cancel",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+
+ return {
+ status: "success",
+ };
+ }
+
+ /**
+ * Reactivate a subscription by clearing cancellation flags and releasing pre-existing schedules.
+ *
+ * @param orgId Organization id
+ */
+ async reactivate(orgId: string, opId?: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+ if (!subscriptionId)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "No active subscription to reactivate",
+ });
+
+ const subscription = await this.retrieveSubscriptionWithSchedule(
+ client,
+ subscriptionId,
+ );
+
+ // If the user reactivates the subscription, we want to remove the cancellation
+ const cancellationPayload = subscription.cancel_at
+ ? { cancel_at: null }
+ : { cancel_at_period_end: false };
+
+ // If the user has any pending schedule, we want to release it
+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);
+
+ const reactivateKey = makeIdempotencyKey({
+ kind: IdempotencyKind.enum["subscription.reactivate"],
+ fields: { subscriptionId },
+ opId,
+ });
+ logger.info("stripeBillingService.subscription.reactivate", {
+ subscriptionId,
+ idempotencyKey: reactivateKey,
+ opId,
+ userId: this.ctx.session.user.id,
+ userEmail: this.ctx.session.user.email,
+ });
+ await client.subscriptions.update(
+ subscriptionId,
+ {
+ ...cancellationPayload,
+ },
+ { idempotencyKey: reactivateKey },
+ );
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.reactivate",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+
+ return {
+ status: "success",
+ };
+ }
+
+ /**
+ * Clear any active or not-started subscription schedule for the org's subscription.
+ *
+ * @param orgId Organization id
+ */
+ async clearPlanSwitchSchedule(orgId: string, opId?: string) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+ if (!subscriptionId)
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "No active subscription found",
+ });
+
+ const subscription = await this.retrieveSubscriptionWithSchedule(
+ client,
+ subscriptionId,
+ );
+
+ await this.releaseExistingSubscriptionScheduleIfAny(subscription, opId);
+
+ void auditLog({
+ session: this.ctx.session,
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.clearPlanSwitchSchedule",
+ before: parsedOrg.cloudConfig,
+ after: "webhook",
+ });
+
+ return {
+ status: "success",
+ };
+ }
+
+ /**
+ * List invoices for an organization and return rows enriched with a usage/subscription breakdown.
+ * Includes a preview row for the upcoming invoice as the first entry when no cursors are provided.
+ *
+ * @param orgId Organization id
+ * @param pagination limit + optional Stripe cursors
+ */
+ async getInvoices(
+ orgId: string,
+ pagination: {
+ limit: number;
+ startingAfter?: string;
+ endingBefore?: string;
+ },
+ ) {
+ const client = this.stripe;
+
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+
+ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
+ const stripeSubscriptionId =
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+
+ if (!stripeCustomerId || !stripeSubscriptionId) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "No stripe customer or subscription found",
+ });
+ }
+
+ const list = await this.retrieveInvoiceList(
+ stripeCustomerId,
+ stripeSubscriptionId,
+ pagination.limit,
+ pagination.startingAfter,
+ pagination.endingBefore,
+ );
+
+ const preview = await this.createInvoicePreview(
+ client,
+ stripeCustomerId,
+ stripeSubscriptionId,
+ );
+
+ const priceCache = new Map<string, Stripe.Price>();
+
+ // Anonymous function to get the price from Stripe or the emepheral cache here.
+ // In practice a customer will have at least two prices, and maybe a few more.
+ const getPrice = async (priceId?: string) => {
+ if (!priceId) {
+ return undefined;
+ }
+
+ const cached = priceCache.get(priceId);
+ if (cached) {
+ return cached;
+ }
+
+ const p = await client.prices.retrieve(priceId);
+ priceCache.set(priceId, p);
+ return p;
+ };
+
+ type InvoiceTableRow = {
+ id: string | null | undefined;
+ number: string | null | undefined;
+ status: string | null | undefined;
+ currency: string;
+ created: number;
+ hostedInvoiceUrl: string | null | undefined;
+ invoicePdfUrl: string | null | undefined;
+ breakdown: {
+ subscriptionCents: number;
+ usageCents: number;
+ discountCents: number;
+ taxCents: number;
+ totalCents: number;
+ };
+ };
+ // Anonymous function to map the invoice to a row
+ const mapInvoiceToTableRow = async (
+ invoice: Stripe.Invoice,
+ ): Promise<InvoiceTableRow> => {
+ const lines = invoice.lines?.data ?? [];
+
+ let subscriptionCents = 0;
+ let usageCents = 0;
+
+ for (const l of lines) {
+ const amount = typeof l.amount === "number" ? l.amount : 0;
+
+ const priceId = l.pricing?.price_details?.price;
+ const price = await getPrice(priceId);
+
+ const isMetered = this.isMetered(price);
+ if (isMetered) {
+ usageCents += amount;
+ } else {
+ subscriptionCents += amount;
+ }
+ }
+
+ const discountCents = Array.isArray(
+ (invoice as any).total_discount_amounts,
+ )
+ ? (invoice as any).total_discount_amounts.reduce(
+ (acc: number, d: any) => acc + (d.amount ?? 0),
+ 0,
+ )
+ : 0;
+
+ const taxCents = Array.isArray(invoice.total_taxes)
+ ? invoice.total_taxes.reduce(
+ (acc: number, t: any) => acc + (t.amount ?? 0),
+ 0,
+ )
+ : 0;
+ const totalCents =
+ (typeof invoice.total === "number"
+ ? invoice.total
+ : invoice.amount_due) ?? 0;
+
+ return {
+ id: invoice.id,
+ number: invoice.number,
+ status: invoice.status,
+ currency: invoice.currency?.toUpperCase() ?? "USD",
+ created: invoice.created * 1000,
+ hostedInvoiceUrl: invoice.hosted_invoice_url ?? null,
+ invoicePdfUrl: invoice.invoice_pdf ?? null,
+ breakdown: {
+ subscriptionCents,
+ usageCents,
+ discountCents: 0 - discountCents,
+ taxCents,
+ totalCents,
+ },
+ };
+ };
+
+ const previewRow = preview ? await mapInvoiceToTableRow(preview) : null;
+
+ const invoices = await Promise.all(
+ list.data.map((inv) => mapInvoiceToTableRow(inv)),
+ );
+
+ const isFirstPage = !pagination.startingAfter && !pagination.endingBefore;
+
+ const showPreviewRow = isFirstPage && previewRow;
+
+ if (showPreviewRow) {
+ const shouldTruncate = invoices.length === pagination.limit;
+
+ // remove the last item to account for the preview row
+ const modifiedInvoiceRows = shouldTruncate
+ ? [previewRow, ...invoices.slice(0, Math.max(0, pagination.limit - 1))]
+ : [previewRow, ...invoices];
+
+ return {
+ invoices: modifiedInvoiceRows,
+ hasMore: list.has_more || shouldTruncate, // if we truncated the list there is at least one more element to show
+ cursors: {
+ next:
+ modifiedInvoiceRows.length > 1
+ ? modifiedInvoiceRows[modifiedInvoiceRows.length - 1]!.id
+ : undefined, // last real invoice id
+ prev: invoices.length ? invoices[0]!.id : undefined, // first real invoice id
+ },
+ };
+ }
+
+ return {
+ invoices: invoices,
+ hasMore: list.has_more,
+ cursors: {
+ next:
+ list.has_more && invoices.length
+ ? invoices[invoices.length - 1]!.id
+ : undefined,
+ prev: invoices.length ? invoices[0]!.id : undefined,
+ },
+ };
+ }
+
+ /**
+ * Compute usage for the current billing period.
+ *
+ * Primary source: Stripe invoice preview for the metered usage item.
+ * Fallback: Clickhouse aggregate of traces/observations/scores for the last 30 days.
+ *
+ * @param orgId Organization id
+ */
+ async getUsage(orgId: string) {
+ const client = this.stripe;
+
+ const { org, parsedOrg } = await this.getParsedOrgWithProjects(orgId);
+
+ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
+ const stripeSubscriptionId =
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+
+ // [A] We have a user with an active subscription -> get usage from Stripe
+ // ------------------------------------------------------------------------------------------------
+ if (stripeCustomerId && stripeSubscriptionId) {
+ try {
+ const subscription = await this.retrieveSubscriptionWithSchedule(
+ client,
+ stripeSubscriptionId,
+ );
+
+ const usageItem = subscription.items.data.find((item) =>
+ this.isMetered(item.price),
+ );
+
+ if (!usageItem) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "Metered Cloud Usage Product item not found in subscription",
+ });
+ }
+
+ // 1. Get the total usage off the preview Invoice
+ const previewInvoice = await this.createInvoicePreview(
+ client,
+ stripeCustomerId,
+ stripeSubscriptionId,
+ );
+
+ if (!previewInvoice) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Preview invoice not found",
+ });
+ }
+
+ const usageInvoiceLines = previewInvoice.lines.data.filter(
+ (line: any) => {
+ const isMeteredLineItem =
+ line.pricing?.price_details?.price === usageItem.price.id;
+ return isMeteredLineItem;
+ },
+ );
+ const totalUsage = usageInvoiceLines.reduce((acc, line) => {
+ if (line.quantity) return acc + line.quantity;
+ return acc;
+ }, 0);
+
+ // 2. Get the meter to show the correct billing label
+ const meterId = usageItem.price.recurring?.meter;
+
+ if (!meterId) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Meter ID not found for metered usage item",
+ });
+ }
+
+ const meter = await client.billing.meters.retrieve(meterId);
+
+ if (!meter) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Meter not found for metered usage item",
+ });
+ }
+
+ // 3. Set the billing period
+ const billingPeriod = {
+ start: new Date(usageItem.current_period_start * 1000),
+ end: new Date(usageItem.current_period_end * 1000),
+ };
+
+ return {
+ usageCount: totalUsage,
+ usageType: meter?.display_name.toLowerCase() ?? "units",
+ billingPeriod,
+ };
+ } catch (e) {
+ // Fail softly and fallback to Clickhouse
+ logger.error(
+ "Failed to get usage from Stripe, using usage from Clickhouse",
+ { error: e },
+ );
+ }
+ }
+ // [A] End ----------------------------------------------------------------------------------------
+
+ // [B] We have no active subscription -> get usage from Clickhouse for past 30 days (likely hobby plan or fallback)
+ // ------------------------------------------------------------------------------------------------
+ const thirtyDaysAgo = new Date();
+ thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
+ thirtyDaysAgo.setHours(0, 0, 0, 0);
+
+ const projectIds = org.projects.map((p) => p.id);
+
+ const [countTraces, countObservations, countScores] = await Promise.all([
+ getTraceCountOfProjectsSinceCreationDate({
+ projectIds,
+ start: thirtyDaysAgo,
+ }),
+ getObservationCountOfProjectsSinceCreationDate({
+ projectIds,
+ start: thirtyDaysAgo,
+ }),
+ getScoreCountOfProjectsSinceCreationDate({
+ projectIds,
+ start: thirtyDaysAgo,
+ }),
+ ]);
+
+ return {
+ usageCount: countTraces + countObservations + countScores,
+ usageType: "units",
+ };
+
+ // [B] End ----------------------------------------------------------------------------------------
+ }
+
+ // TODO: Currently not working as expected, need to fix
+ /**
+ * Create/update/deactivate Stripe usage alerts for an organization.
+ *
+ * Preconditions: Org must have a Stripe customer and active subscription.
+ *
+ * @param orgId Organization id
+ * @param payload Usage alert configuration
+ */
+ async upsertUsageAlerts(
+ orgId: string,
+ payload: {
+ enabled: boolean;
+ threshold: number;
+ notifications: { email: boolean; recipients: string[] };
+ },
+ ) {
+ const { parsedOrg } = await this.getParsedOrg(orgId);
+ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;
+ const subscriptionId = parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;
+ const currentAlerts = parsedOrg.cloudConfig?.usageAlerts;
+ if (!stripeCustomerId || !subscriptionId)
+ throw new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message:
+ "Organization must have a Stripe customer with active subscription to configure usage alerts",
+ });
+ const client = this.stripe;
+ let updatedAlerts = payload;
+
+ const subscription = await client.subscriptions.retrieve(subscriptionId);
+ if (!subscription)
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Stripe subscription not found",
+ });
+ const meterId = subscription.items.data.filter((subItem) =>
+ Boolean((subItem as any).plan.meter),
+ )[0]?.plan.meter as string | undefined;
+
+ const updatedUsageAlertConfig: any = {
+ enabled: updatedAlerts.enabled,
+ type: "STRIPE",
+ threshold: updatedAlerts.threshold,
+ alertId: currentAlerts?.alertId ?? null,
+ meterId: meterId ?? null,
+ notifications: {
+ email: updatedAlerts.notifications.email,
+ recipients: updatedAlerts.notifications.recipients,
+ },
+ };
+
+ if (
+ !updatedAlerts.enabled &&
+ currentAlerts?.alertId &&
+ currentAlerts?.enabled
+ ) {
+ await UsageAlertService.getInstance({ stripeClient: client }).deactivate({
+ id: currentAlerts?.alertId,
+ });
+ }
+ if (!currentAlerts?.alertId) {
+ const alert = await UsageAlertService.getInstance({
+ stripeClient: client,
+ }).create({
+ orgId,
+ customerId: stripeCustomerId,
+ meterId,
+ amount: updatedAlerts.threshold,
+ });
+ updatedUsageAlertConfig.alertId = alert.id;
+ }
+ if (
+ updatedAlerts.enabled &&
+ currentAlerts?.alertId &&
+ (currentAlerts?.threshold !== updatedAlerts.threshold ||
+ currentAlerts.meterId !== meterId)
+ ) {
+ const alert = await UsageAlertService.getInstance({
+ stripeClient: client,
+ }).recreate({
+ orgId,
+ customerId: stripeCustomerId,
+ meterId,
+ existingAlertId: currentAlerts.alertId,
+ amount: updatedAlerts.threshold,
+ });
+ updatedUsageAlertConfig.alertId = alert.id;
+ }
+ if (
+ updatedAlerts.enabled &&
+ currentAlerts?.alertId &&
+ !currentAlerts.enabled
+ ) {
+ await UsageAlertService.getInstance({ stripeClient: client }).activate({
+ id: currentAlerts.alertId,
+ });
+ }
+
+ const newCloudConfig = {
+ ...parsedOrg.cloudConfig,
+ usageAlerts: updatedUsageAlertConfig,
+ };
+ await this.ctx.prisma.organization.update({
+ where: { id: orgId },
+ data: { cloudConfig: newCloudConfig },
+ });
+
+ return updatedAlerts;
+ }
+}
+
+/**
+ * Creates a BillingService instance from a TRPC context.
+ * This is the preferred way to create a BillingService in router endpoints.
+ */
+export const createBillingServiceFromContext = (ctx: OrgAuthedContext) => {
+ if (!defaultStripeClient) {
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Stripe client not initialized",
+ });
+ }
+ return new BillingService(defaultStripeClient, ctx);
+};
diff --git a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts b/web/src/ee/features/billing/server/stripeWebhookHandler.ts
similarity index 51%
rename from web/src/ee/features/billing/server/stripeWebhookApiHandler.ts
rename to web/src/ee/features/billing/server/stripeWebhookHandler.ts
index 041bc6688a..1674c87933 100644
--- a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts
+++ b/web/src/ee/features/billing/server/stripeWebhookHandler.ts
@@ -1,7 +1,7 @@
import {
getOrgIdFromStripeClientReference,
isStripeClientReferenceFromCurrentCloudRegion,
-} from "@/src/ee/features/billing/stripeClientReference";
+} from "@/src/ee/features/billing/utils/stripeClientReference";
import { env } from "@/src/env.mjs";
import { type NextRequest, NextResponse } from "next/server";
import { prisma } from "@langfuse/shared/src/db";
@@ -9,20 +9,38 @@ import { stripeClient } from "@/src/ee/features/billing/utils/stripe";
import type Stripe from "stripe";
import {
CloudConfigSchema,
+ InternalServerError,
type Organization,
parseDbOrg,
} from "@langfuse/shared";
import { traceException, redis, logger } from "@langfuse/shared/src/server";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { sendBillingAlertEmail } from "@langfuse/shared/src/server";
import { Role } from "@langfuse/shared";
import { UsageAlertService } from "@/src/ee/features/billing/server/usageAlertService";
+import { type StripeSubscriptionMetadata } from "@/src/ee/features/billing/utils/stripeSubscriptionMetadata";
-/*
- * Sign-up endpoint (email/password users), creates user in database.
- * SSO users are created by the NextAuth adapters.
+/**
+ * Stripe webhook handler for managing subscription events, billing alerts, and invoice notifications.
+ * This endpoint processes various Stripe events to keep the organization's billing state in sync.
+ *
+ * Supported events:
+ * - customer.subscription.created: New subscription setup
+ * - customer.subscription.updated: Plan changes and updates
+ * - customer.subscription.deleted: Subscription cancellations
+ * - invoice.created: Invoice generation and usage alert recreation
+ * - billing.alert.triggered: Usage threshold notifications
+ *
+ * Security:
+ * - Validates Stripe webhook signatures
+ * - Ensures correct cloud region handling
+ * - Maintains subscription metadata integrity
+ *
+ * @param req - Next.js request object containing the Stripe webhook event
+ * @returns NextResponse with appropriate status and message
*/
-export async function stripeWebhookApiHandler(req: NextRequest) {
+export async function stripeWebhookHandler(req: NextRequest) {
if (req.method !== "POST")
return NextResponse.json(
{ message: "Method not allowed" },
@@ -112,6 +130,40 @@ export async function stripeWebhookApiHandler(req: NextRequest) {
return NextResponse.json({ received: true }, { status: 200 });
}
+/**
+ * Retrieves an organization by its Langfuse organization ID.
+ */
+async function getOrgById(orgId: string): Promise<Organization | null> {
+ const org = await prisma.organization.findUnique({
+ where: { id: orgId },
+ });
+ return org;
+}
+
+/**
+ * Retrieves an organization based on its Stripe customer ID.
+ */
+async function getOrgBasedOnCustomerId(
+ customerId: string,
+): Promise<Organization | null> {
+ const org = await prisma.organization.findFirst({
+ where: {
+ cloudConfig: {
+ path: ["stripe", "customerId"],
+ equals: customerId,
+ },
+ },
+ });
+ return org;
+}
+
+/**
+ * Retrieves an organization based on its active Stripe subscription ID.
+ * This is the primary method for finding organizations with existing subscriptions.
+ *
+ * @param subscriptionId - The Stripe subscription ID to look up
+ * @returns The organization with the matching subscription ID, or null if not found
+ */
async function getOrgBasedOnActiveSubscriptionId(
subscriptionId: string,
): Promise<Organization | null> {
@@ -126,6 +178,19 @@ async function getOrgBasedOnActiveSubscriptionId(
return orgBasedOnSubscriptionId;
}
+/**
+ * Fallback method to find an organization using the checkout session attached to a subscription.
+ * Used primarily for new subscriptions where the subscription ID hasn't been saved to the org yet.
+ *
+ * Process:
+ * 1. Retrieves the checkout session linked to the subscription
+ * 2. Extracts the client reference ID (contains org ID)
+ * 3. Validates the cloud region matches
+ * 4. Looks up the organization
+ *
+ * @param subscriptionId - The Stripe subscription ID to look up
+ * @returns The organization associated with the checkout session, or null if not found
+ */
async function getOrgBasedOnCheckoutSessionAttachedToSubscription(
subscriptionId: string,
): Promise<Organization | null> {
@@ -163,67 +228,267 @@ async function getOrgBasedOnCheckoutSessionAttachedToSubscription(
return organization;
}
+/**
+ * Resolve the organization for a given subscription using layered fallbacks:
+ * 1) by active subscription id
+ * 2) by Stripe customer id
+ * 3) by checkout session attached to the subscription
+ * 4) by subscription.metadata.orgId (last, because there might be a mismatch)
+ * Returns parsed org or null if not found (caller should log/return).
+ */
+async function getOrgForSubscriptionWithFallbacks(
+ subscription: Stripe.Subscription,
+) {
+ const subscriptionId = subscription.id;
+
+ // 1) by active subscription id
+ let organization = await getOrgBasedOnActiveSubscriptionId(subscriptionId);
+ if (organization) {
+ return parseDbOrg(organization);
+ }
+
+ // 2) by Stripe customer id
+ const customerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer?.id;
+ if (customerId) {
+ organization = await getOrgBasedOnCustomerId(customerId);
+ if (organization) {
+ return parseDbOrg(organization);
+ }
+ }
+
+ // 3) by checkout session attached to the subscription
+ organization =
+ await getOrgBasedOnCheckoutSessionAttachedToSubscription(subscriptionId);
+ if (organization) {
+ return parseDbOrg(organization);
+ }
+
+ // 4) by metadata.orgId
+ const metadataOrgId = subscription.metadata?.orgId;
+ if (metadataOrgId) {
+ organization = await getOrgById(metadataOrgId);
+ if (organization) {
+ return parseDbOrg(organization);
+ }
+ }
+
+ logger.error(
+ `[Stripe Webhook] getOrgForSubscriptionWithFallbacks: Organization not found for subscription ${subscriptionId}`,
+ );
+ traceException(
+ `[Stripe Webhook] getOrgForSubscriptionWithFallbacks: Organization not found for subscription ${subscriptionId}`,
+ );
+ return null;
+}
+
+/**
+ * Ensures that required metadata (orgId and cloudRegion) is set on a Stripe subscription.
+ * This is crucial for multi-region support and proper organization tracking.
+ *
+ * If metadata is missing:
+ * 1. Attempts to find the organization using subscription ID
+ * 2. Falls back to checkout session lookup if needed
+ * 3. Updates the subscription with the correct metadata
+ *
+ * @param subscription - The Stripe subscription object to check/update
+ * @returns The updated subscription with metadata, or undefined if org not found
+ * @throws {InternalServerError} If cloud region is not set or Stripe client is missing
+ */
+async function ensureMetadataIsSetOnStripeSubscription(
+ subscription: Stripe.Subscription,
+) {
+ if (subscription.metadata?.orgId && subscription.metadata?.cloudRegion) {
+ return;
+ }
+ const currentEnvironment = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+
+ if (!currentEnvironment) {
+ traceException(
+ "[Stripe Webhook] NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is not set but webhook is running",
+ );
+ throw new InternalServerError(
+ "[Stripe Webhook] NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is not set but webhook is running",
+ ); // we throw here because this should really never happen
+ }
+
+ if (!stripeClient) {
+ traceException("[Stripe Webhook] Stripe client not found");
+ throw new InternalServerError("[Stripe Webhook] Stripe client not found"); // we throw here because this should really never happen
+ }
+
+ try {
+ const parsedOrg = await getOrgForSubscriptionWithFallbacks(subscription);
+ if (!parsedOrg) {
+ // Note: all our production environments receive all webhooks from Stripe.
+ // Only one should handle the webhook; it is expected in 2/3 cases the organization is not found.
+ logger.info(
+ `[Stripe Webhook] (${currentEnvironment}) ensureMetadataIsSetOnStripeSubscription: Organization not found for subscription ${subscription.id} in Environment ${currentEnvironment}`,
+ );
+ return;
+ }
+ logger.info(
+ `[Stripe Webhook] (${currentEnvironment}) ensureMetadataIsSetOnStripeSubscription: Organization for subscription ${subscription.id} found in Environment ${currentEnvironment}`,
+ );
+
+ const metadata: StripeSubscriptionMetadata = {
+ orgId: parsedOrg.id,
+ cloudRegion: currentEnvironment,
+ };
+
+ await stripeClient.subscriptions.update(subscription.id, {
+ metadata: metadata,
+ });
+
+ return await stripeClient.subscriptions.retrieve(subscription.id);
+ } catch (err) {
+ // we don't throw here, because there are legit reasons why this might fail. We don't want stripe to keep retrying.
+ logger.error(
+ "[Stripe Webhook] ensureMetadataIsSetOnStripeSubscription error",
+ err,
+ );
+ traceException(
+ "[Stripe Webhook] ensureMetadataIsSetOnStripeSubscription error",
+ );
+ return;
+ }
+}
+
async function handleSubscriptionChanged(
subscription: Stripe.Subscription,
action: "created" | "deleted" | "updated",
) {
- const subscriptionId = subscription.id;
+ const currentEnvironment = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- let organization: Organization | null = null;
+ if (!currentEnvironment) {
+ traceException(
+ `[Stripe Webhook] NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is not set but webhook received event subscription.${action}`,
+ );
+ throw new InternalServerError(
+ `[Stripe Webhook] NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is not set but webhook received event subscription.${action}`, // we throw here because this should really never happen
+ );
+ }
- // For existing subscriptions, we can use the active subscription id to find the org
- // More reliable than the checkout session attached to the subscription for subscriptions that were manually set up
- organization = await getOrgBasedOnActiveSubscriptionId(subscriptionId);
+ const subscriptionMetadata: StripeSubscriptionMetadata = {
+ orgId: subscription.metadata?.orgId,
+ cloudRegion: subscription.metadata?.cloudRegion,
+ };
- // Required fallback for new subscriptions
- if (!organization) {
- organization =
- await getOrgBasedOnCheckoutSessionAttachedToSubscription(subscriptionId);
+ if (!subscriptionMetadata.cloudRegion) {
+ const updatedSubscription =
+ await ensureMetadataIsSetOnStripeSubscription(subscription);
+
+ subscriptionMetadata.orgId = updatedSubscription?.metadata?.orgId;
+ subscriptionMetadata.cloudRegion =
+ updatedSubscription?.metadata?.cloudRegion;
}
- if (!organization) {
+ if (subscriptionMetadata.cloudRegion !== currentEnvironment) {
logger.info(
- "[Stripe Webhook] Organization not found for this subscription",
+ `[Stripe Webhook] (${currentEnvironment}) handleSubscriptionChanged: Skipping subscription.${action} for ${subscription.id} because cloud region mismatch.`,
+ );
+ return;
+ }
+
+ logger.info(
+ `[Stripe Webhook] (${currentEnvironment}) handleSubscriptionChanged: Handle subscription.${action} for ${subscription.id} because cloud region matches.`,
+ );
+
+ const subscriptionId = subscription.id;
+
+ const parsedOrg = await getOrgForSubscriptionWithFallbacks(subscription);
+ if (!parsedOrg) {
+ logger.error(
+ `[Stripe Webhook] (${currentEnvironment}) Organization not found for subscription ${subscriptionId}`,
+ );
+ traceException(
+ `[Stripe Webhook] (${currentEnvironment}) Organization not found for subscription ${subscriptionId}`,
);
return;
}
- const parsedOrg = parseDbOrg(organization);
- // assert that no other stripe customer id is already set on the org
- const customerId = subscription.customer;
- if (!customerId || typeof customerId !== "string") {
- logger.error("[Stripe Webhook] Customer ID not found");
- traceException("[Stripe Webhook] Customer ID not found");
+ if (
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId &&
+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId !== subscriptionId
+ ) {
+ logger.error(
+ `[Stripe Webhook] (${currentEnvironment}) Another active subscription id already set on org`,
+ );
+ traceException(
+ `[Stripe Webhook] (${currentEnvironment}) Another active subscription id already set on org`,
+ );
return;
}
+
+ const stripeCustomerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer?.id;
+
if (
parsedOrg.cloudConfig?.stripe?.customerId &&
- parsedOrg.cloudConfig?.stripe?.customerId !== customerId
+ parsedOrg.cloudConfig?.stripe?.customerId !== stripeCustomerId
) {
- logger.error("[Stripe Webhook] Another customer id already set on org");
- traceException("[Stripe Webhook] Another customer id already set on org");
+ logger.error(
+ `[Stripe Webhook] (${currentEnvironment}) Another customer id already set on org`,
+ );
+ traceException(
+ `[Stripe Webhook] (${currentEnvironment}) Another customer id already set on org`,
+ );
return;
}
+ if (
+ subscription.metadata?.orgId &&
+ subscription.metadata?.orgId !== parsedOrg.id
+ ) {
+ logger.warn(
+ `[Stripe Webhook] (${currentEnvironment}) Organization ID mismatch in subscription metadata for subscription ${subscriptionId} (orgId: ${parsedOrg.id}, metadataOrgId: ${subscription.metadata?.orgId})`,
+ );
+ }
+
// check subscription items
- logger.info("subscription.items.data", { payload: subscription.items.data });
+ const items = subscription.items?.data ?? [];
- if (!subscription.items.data || subscription.items.data.length !== 1) {
+ if (!items || items.length === 0) {
logger.error(
- "[Stripe Webhook] Subscription items not found or more than one",
+ `[Stripe Webhook] (${currentEnvironment}) No subscription items found`,
);
traceException(
- "[Stripe Webhook] Subscription items not found or more than one",
+ `[Stripe Webhook] (${currentEnvironment}) No subscription items found`,
);
return;
}
- const subscriptionItem = subscription.items.data[0];
- const productId = subscriptionItem.price.product;
+ // Note: To support both the old billing and the new billing, we need want to get the product id
+ // of the associated plan (core, pro, team), not the usage product id.
+ // -> New Setup: 2 products exist; Filter for the one with the non-usage price as the active product
+ // -> Old Setup: 1 product exists; Use the first item as the active product
+ const planProductItem =
+ items.length == 1
+ ? items[0]
+ : items.find((it) => {
+ return it.price && it.price.recurring?.usage_type !== "metered";
+ });
+ const productId = planProductItem?.price.product;
+
+ const usageProductItem =
+ items.length == 1
+ ? null // legacy setup; Set to null, so we can distinguish from the new setup
+ : items.find((it) => {
+ return it.price && it.price.recurring?.usage_type === "metered";
+ });
+ const usageProductId = usageProductItem?.price.product;
if (!productId || typeof productId !== "string") {
- logger.error("[Stripe Webhook] Product ID not found");
- traceException("[Stripe Webhook] Product ID not found");
+ logger.error(
+ `[Stripe Webhook] (${currentEnvironment}) Product ID not found`,
+ );
+ traceException(
+ `[Stripe Webhook] (${currentEnvironment}) Product ID not found`,
+ );
return;
}
@@ -233,25 +498,27 @@ async function handleSubscriptionChanged(
parsedOrg.cloudConfig?.stripe?.activeProductId &&
parsedOrg.cloudConfig?.stripe?.activeProductId !== productId
) {
- traceException(
- "[Stripe Webhook] Another active product id already set on (one of the) org with this active subscription id",
- );
logger.error(
- "[Stripe Webhook] Another active product id already set on (one of the) org with this active subscription id",
+ `[Stripe Webhook] (${currentEnvironment}) Another active product id already set on (one of the) org with this active subscription id`,
+ );
+ traceException(
+ `[Stripe Webhook] (${currentEnvironment}) Another active product id already set on (one of the) org with this active subscription id`,
);
+
return;
}
- // update the cloud config with the product ID
+ // update the cloud config with the product ID (do not persist cancellation/schedule info)
if (action === "created" || action === "updated") {
- let updatedCloudConfig = {
+ const updatedCloudConfig = {
...parsedOrg.cloudConfig,
stripe: {
...parsedOrg.cloudConfig?.stripe,
...CloudConfigSchema.shape.stripe.parse({
activeProductId: productId,
+ activeUsageProductId: usageProductId,
activeSubscriptionId: subscriptionId,
- customerId: customerId,
+ customerId: stripeCustomerId,
}),
},
};
@@ -264,24 +531,53 @@ async function handleSubscriptionChanged(
cloudConfig: updatedCloudConfig,
},
});
+
+ void auditLog({
+ session: {
+ user: { id: "stripe-webhook" },
+ orgId: parsedOrg.id,
+ },
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: `BillingService.subscription.${action}`,
+ before: parsedOrg.cloudConfig,
+ after: updatedCloudConfig,
+ });
} else if (action === "deleted") {
+ const updatedCloudConfig = {
+ ...parsedOrg.cloudConfig,
+ stripe: {
+ ...parsedOrg.cloudConfig?.stripe,
+ ...CloudConfigSchema.shape.stripe.parse({
+ customerId: stripeCustomerId,
+ activeProductId: undefined,
+ activeSubscriptionId: undefined,
+ activeUsageProductId: undefined,
+ }),
+ },
+ };
+
await prisma.organization.update({
where: {
id: parsedOrg.id,
},
data: {
- cloudConfig: {
- ...parsedOrg.cloudConfig,
- stripe: {
- ...parsedOrg.cloudConfig?.stripe,
- ...CloudConfigSchema.shape.stripe.parse({
- activeProductId: undefined,
- activeSubscriptionId: undefined,
- customerId: customerId,
- }),
- },
- },
+ cloudConfig: updatedCloudConfig,
+ },
+ });
+
+ void auditLog({
+ session: {
+ user: { id: "stripe-webhook" },
+ orgId: parsedOrg.id,
},
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.subscription.deleted",
+ before: parsedOrg.cloudConfig,
+ after: updatedCloudConfig,
});
}
@@ -533,6 +829,19 @@ async function handleInvoiceCreated(invoice: Stripe.Invoice): Promise<void> {
cloudConfig: parsedOrg.cloudConfig!,
},
});
+
+ void auditLog({
+ session: {
+ user: { id: "stripe-webhook" },
+ orgId: parsedOrg.id,
+ },
+ orgId: parsedOrg.id,
+ resourceType: "organization",
+ resourceId: parsedOrg.id,
+ action: "BillingService.usageAlerts.recreate",
+ before: parsedOrg.cloudConfig,
+ after: parsedOrg.cloudConfig!,
+ });
logger.info(
`[Stripe Webhook] Recreated usage alert for ${parsedOrg.id} after invoice creation`,
{
diff --git a/web/src/ee/features/billing/stripeClientReference.ts b/web/src/ee/features/billing/stripeClientReference.ts
deleted file mode 100644
index 56c3fa017d..0000000000
--- a/web/src/ee/features/billing/stripeClientReference.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { env } from "@/src/env.mjs";
-import { logger } from "@langfuse/shared/src/server";
-
-// used server-side to create a stripe customer reference when creating a checkout session
-export const createStripeClientReference = (orgId: string) => {
- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
- logger.error(
- "Returning null stripeCustomerReference, you cannot run the checkout page outside of Langfuse Cloud",
- );
- return null;
- }
- return `${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}-${orgId}`;
-};
-
-// used server-side to check if the stripe customer reference is valid and parse the orgId when receiving a stripe webhook
-export const isStripeClientReferenceFromCurrentCloudRegion = (
- clientReference: string,
-) =>
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
- clientReference.startsWith(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
-
-export const getOrgIdFromStripeClientReference = (clientReference: string) =>
- clientReference.replace(`${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}-`, "");
diff --git a/web/src/ee/features/billing/utils/stripeProducts.ts b/web/src/ee/features/billing/utils/stripeCatalogue.ts
similarity index 67%
rename from web/src/ee/features/billing/utils/stripeProducts.ts
rename to web/src/ee/features/billing/utils/stripeCatalogue.ts
index b14fc135ca..66b5cc20e5 100644
--- a/web/src/ee/features/billing/utils/stripeProducts.ts
+++ b/web/src/ee/features/billing/utils/stripeCatalogue.ts
@@ -7,6 +7,7 @@ const isTestEnvironment =
type StripeProduct = {
stripeProductId: string;
+ orderKey?: number | undefined; // to check whether a plan is upgraded or downgraded
mappedPlan: Plan;
// include checkout if product can be subscribed to by new users
checkout: {
@@ -18,13 +19,14 @@ type StripeProduct = {
} | null;
};
-// map of planid to plan name
+// Backward-compatible export: same name and shape as before
export const stripeProducts: StripeProduct[] = [
{
stripeProductId: isTestEnvironment
- ? "prod_RoBuRrXjIUBIJ8" // test
+ ? "prod_RoYirvRQ4Kc6po" // sandbox
: "prod_RoYirvRQ4Kc6po", // live
mappedPlan: "cloud:core",
+ orderKey: 29,
checkout: {
title: "Core",
description:
@@ -41,9 +43,10 @@ export const stripeProducts: StripeProduct[] = [
},
{
stripeProductId: isTestEnvironment
- ? "prod_QgDNYKXcBfvUQ3" // test
+ ? "prod_QhK7UMhrkVeF6R" // sandbox
: "prod_QhK7UMhrkVeF6R", // live
mappedPlan: "cloud:pro",
+ orderKey: 199,
checkout: {
title: "Pro",
description:
@@ -61,9 +64,10 @@ export const stripeProducts: StripeProduct[] = [
},
{
stripeProductId: isTestEnvironment
- ? "prod_QgDOxTD64U6KDv" // test
+ ? "prod_QhK9qKGH25BTcS" // sandbox
: "prod_QhK9qKGH25BTcS", // live
mappedPlan: "cloud:team",
+ orderKey: 499,
checkout: {
title: "Pro + Teams Add-on",
description: "Organizational and security controls for larger teams.",
@@ -81,13 +85,46 @@ export const stripeProducts: StripeProduct[] = [
},
{
stripeProductId: isTestEnvironment
- ? "prod_SToP5nTZpC4yO8" // test
+ ? "prod_STnXok7GSSDmyF" // sandbox
: "prod_STnXok7GSSDmyF", // live
mappedPlan: "cloud:enterprise",
checkout: null,
},
];
+export const stripeUsageProduct = {
+ id: isTestEnvironment
+ ? "prod_T2DaIcLiiR78rs" // sandbox
+ : "prod_T4nLLI2vn876J2",
+};
+
export const mapStripeProductIdToPlan = (productId: string): Plan | null =>
stripeProducts.find((product) => product.stripeProductId === productId)
?.mappedPlan ?? null;
+
+export const isUpgrade = (
+ oldProductId: string,
+ newProductId: string,
+): boolean => {
+ const oldProduct = stripeProducts.find(
+ (product) => product.stripeProductId === oldProductId,
+ );
+ const newProduct = stripeProducts.find(
+ (product) => product.stripeProductId === newProductId,
+ );
+ return (oldProduct?.orderKey ?? 0) < (newProduct?.orderKey ?? 0);
+};
+
+export const isValidCheckoutProduct = (id: string) => {
+ return stripeProducts.some(
+ (p) => Boolean(p.checkout) && p.stripeProductId === id,
+ );
+};
+
+export const StripeCatalogue = {
+ products: stripeProducts,
+ usageProductId: () => stripeUsageProduct.id,
+ isValidCheckoutProduct: isValidCheckoutProduct,
+ isUpgrade,
+ mapStripeProductIdToPlan,
+} as const;
diff --git a/web/src/ee/features/billing/utils/stripeClientReference.ts b/web/src/ee/features/billing/utils/stripeClientReference.ts
new file mode 100644
index 0000000000..a2c636d382
--- /dev/null
+++ b/web/src/ee/features/billing/utils/stripeClientReference.ts
@@ -0,0 +1,60 @@
+import { env } from "@/src/env.mjs";
+import { logger } from "@langfuse/shared/src/server";
+import { TRPCError } from "@trpc/server";
+
+/**
+ * Utilities for managing Stripe client references in a multi-region deployment.
+ * Client references are used to link Stripe subscriptions to organizations and ensure
+ * webhooks are processed in the correct cloud region.
+ *
+ * Flow:
+ * 1. createStripeClientReference: Creates reference during checkout (stripeBillingService.ts)
+ * 2. isStripeClientReferenceFromCurrentCloudRegion: Validates region in webhooks
+ * 3. getOrgIdFromStripeClientReference: Extracts org ID for processing
+ *
+ * Format: `${cloudRegion}-${orgId}`
+ * Example: "EU-org_123" or "US-org_456"
+ */
+
+/**
+ * Creates a Stripe client reference by combining cloud region and organization ID.
+ * Used when creating new checkout sessions in stripeBillingService.ts.
+ *
+ * @throws {TRPCError} If not running in a Langfuse Cloud environment
+ */
+export const createStripeClientReference = (orgId: string) => {
+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ logger.error(
+ "Returning null stripeClientReference, you cannot run the checkout page outside of Langfuse Cloud",
+ );
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message:
+ "Cannot create stripe client reference outside of Langfuse Cloud",
+ });
+ }
+ return `${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}-${orgId}`;
+};
+
+/**
+ * Validates if a client reference belongs to the current cloud region.
+ * Used in stripeWebhookHandler.ts to ensure webhooks are processed in the correct region.
+ *
+ * @param clientReference - The client reference from Stripe (format: "REGION-orgId")
+ * @returns true if the reference matches the current cloud region
+ */
+export const isStripeClientReferenceFromCurrentCloudRegion = (
+ clientReference: string,
+) =>
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
+ clientReference.startsWith(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+
+/**
+ * Extracts the organization ID from a client reference.
+ * Used in stripeWebhookHandler.ts after validating the cloud region.
+ *
+ * @param clientReference - The client reference from Stripe (format: "REGION-orgId")
+ * @returns The extracted organization ID
+ */
+export const getOrgIdFromStripeClientReference = (clientReference: string) =>
+ clientReference.replace(`${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}-`, "");
diff --git a/web/src/ee/features/billing/utils/stripeExpand.ts b/web/src/ee/features/billing/utils/stripeExpand.ts
new file mode 100644
index 0000000000..b7173da86f
--- /dev/null
+++ b/web/src/ee/features/billing/utils/stripeExpand.ts
@@ -0,0 +1,40 @@
+/**
+ * Helpers for working with Stripe's `expand` feature using correct TypeScript types.
+ *
+ * Stripe often returns fields as `string | T` via `Expandable<T>`. When you
+ * request expansions (e.g. `{ expand: ["default_price"] }`), the SDK still
+ * types those fields as `string | T`. These utilities assert at runtime that
+ * the expansion occurred and narrow the types accordingly, so downstream code
+ * can rely on fully-expanded objects without repetitive checks.
+ *
+ */
+
+/**
+ * Utility mapped type: take a type `T` and mark keys `K` as expanded.
+ */
+export type Expanded<T, K extends keyof T> = T & {
+ [P in K]-?: Exclude<T[P], string | null | undefined>;
+};
+
+/**
+ * Type guard that narrows a Stripe expandable field from `string | T | null | undefined`
+ * to the fully expanded object `T`. Returns true when the value is non-nullish and
+ * not a string (i.e., Stripe returned the expanded object).
+ */
+export const isExpanded = <T>(v: string | T | null | undefined): v is T =>
+ v != null && typeof v !== "string";
+
+/**
+ * Utility mapped type: take a type `T` and mark keys `K` as expanded and nullable.
+ */
+export type ExpandedNullable<T, K extends keyof T> = {
+ [P in keyof T]: P extends K ? Exclude<T[P], string> : T[P];
+};
+/**
+ * Type guard that narrows a Stripe expandable field from `string | T | null | undefined`
+ * to the fully expanded object `T` or `null | undefined`. Returns true when the value
+ * is non-nullish and not a string (i.e., Stripe returned the expanded object).
+ */
+export const isExpandedOrNullable = <T>(
+ v: string | T | null | undefined,
+): v is T | null | undefined => typeof v !== "string";
diff --git a/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts
new file mode 100644
index 0000000000..c48217669c
--- /dev/null
+++ b/web/src/ee/features/billing/utils/stripeIdempotencyKey.ts
@@ -0,0 +1,74 @@
+import crypto from "crypto";
+import { z } from "zod/v4";
+
+/**
+ * Utilities for generating idempotency keys for Stripe API operations.
+ * Ensures that operations are not accidentally executed multiple times, even across different cloud regions.
+ *
+ * Used primarily in stripeBillingService.ts for subscription operations:
+ * - Plan changes
+ * - Subscription schedule management
+ * - Cancellations and reactivations
+ *
+ * The idempotency key combines:
+ * - Operation type (IdempotencyKind)
+ * - Relevant fields (e.g., subscriptionId)
+ * - Operation ID for uniqueness
+ */
+
+/**
+ * Enumeration of all supported idempotent operations.
+ * Each value represents a specific type of Stripe API operation that needs idempotency protection.
+ */
+export const IdempotencyKind = z.enum([
+ "subscription.schedule.release",
+ "subscription.update.product",
+ "subscription.schedule.create.fromSub",
+ "subscription.schedule.update",
+ "subscription.cancelAtPeriodEnd",
+ "subscription.reactivate",
+ "subscription.migrate.flexible",
+ "subscription.schedule.clear",
+]);
+
+export type IdempotencyKind = z.infer<typeof IdempotencyKind>;
+
+/**
+ * Creates a stable hash of an object by sorting keys before stringification.
+ * Used internally by makeIdempotencyKey to ensure consistent hashing.
+ *
+ * @param obj - Any JSON-serializable object to hash
+ * @returns A 16-character hexadecimal hash string
+ */
+export function stableHash(obj: unknown): string {
+ try {
+ const json = JSON.stringify(obj, Object.keys(obj as any).sort());
+ return crypto.createHash("sha256").update(json).digest("hex").slice(0, 16);
+ } catch {
+ return crypto.randomBytes(8).toString("hex");
+ }
+}
+
+/**
+ * Generates an idempotency key for Stripe API operations.
+ * The key combines operation type, relevant fields, and an operation ID to ensure uniqueness.
+ *
+ * Format: `${kind}:${field1}=${value1}:${field2}=${value2}:op=${opId}`
+ *
+ * @param parts.kind - Type of operation from IdempotencyKind
+ * @param parts.fields - Key-value pairs relevant to the operation
+ * @param parts.opId - Unique operation identifier
+ * @returns Formatted idempotency key or undefined if opId is missing
+ */
+export function makeIdempotencyKey(parts: {
+ kind: IdempotencyKind;
+ fields: Record<string, string | number | undefined>;
+ opId?: string;
+}): string | undefined {
+ if (!parts.opId) return undefined;
+ const left = Object.entries(parts.fields)
+ .filter(([, v]) => v !== undefined)
+ .map(([k, v]) => `${k}=${String(v)}`)
+ .join(":");
+ return `${parts.kind}:${left}:op=${parts.opId}`;
+}
diff --git a/web/src/ee/features/billing/utils/stripeSubscriptionMetadata.ts b/web/src/ee/features/billing/utils/stripeSubscriptionMetadata.ts
new file mode 100644
index 0000000000..2f6ed16613
--- /dev/null
+++ b/web/src/ee/features/billing/utils/stripeSubscriptionMetadata.ts
@@ -0,0 +1,27 @@
+import { z } from "zod";
+
+/**
+ * Schema and type definitions for Stripe subscription metadata.
+ * This metadata is crucial for multi-region deployment and organization tracking.
+ *
+ * Usage flow:
+ * 1. Set during subscription creation in stripeBillingService.ts:
+ * - Added to subscription_data.metadata in createCheckoutSession
+ * - Contains orgId and cloudRegion for new subscriptions
+ *
+ * 2. Validated in stripeWebhookHandler.ts:
+ * - Used to ensure webhooks are processed in correct cloud region
+ * - Automatically added to subscriptions if missing via ensureMetadataIsSetOnStripeSubscription
+ * - Prevents duplicate subscription processing across regions
+ *
+ * @property orgId - Links the subscription to a specific organization
+ * @property cloudRegion - Identifies which cloud region (e.g., EU, US) handles this subscription
+ */
+export const StripeSubscriptionMetadataSchema = z.object({
+ orgId: z.string().optional(),
+ cloudRegion: z.string().optional(),
+});
+
+export type StripeSubscriptionMetadata = z.infer<
+ typeof StripeSubscriptionMetadataSchema
+>;
diff --git a/web/src/features/entitlements/server/getPlan.ts b/web/src/features/entitlements/server/getPlan.ts
index 164bd1511a..0d40abf693 100644
--- a/web/src/features/entitlements/server/getPlan.ts
+++ b/web/src/features/entitlements/server/getPlan.ts
@@ -1,4 +1,4 @@
-import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeProducts";
+import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeCatalogue";
import { env } from "@/src/env.mjs";
import { type Plan } from "@langfuse/shared";
import { type CloudConfigSchema } from "@langfuse/shared";
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 13625d9420..95ca76d2bf 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -580,3 +580,30 @@ const enforceAdminAuth = t.middleware(async (opts) => {
export const adminProcedure = withOtelTracingProcedure
.use(withErrorHandling)
.use(enforceAdminAuth);
+
+// Export context types for easier reuse
+// Base context from createTRPCContext
+export type TRPCContext = Awaited<ReturnType<typeof createTRPCContext>>;
+// After `enforceUserIsAuthed`: session & user are non-null
+export type AuthedSession = NonNullable<TRPCContext["session"]> & {
+ user: NonNullable<NonNullable<TRPCContext["session"]>["user"]>;
+};
+export type AuthedContext = Omit<TRPCContext, "session"> & {
+ session: AuthedSession;
+};
+// After `enforceUserIsAuthedAndProjectMember`: extra fields guaranteed
+export type ProjectAuthedContext = Omit<TRPCContext, "session"> & {
+ session: AuthedSession & {
+ orgId: string;
+ orgRole: Role;
+ projectId: string;
+ projectRole: Role;
+ };
+};
+// After `enforceIsAuthedAndOrgMember`
+export type OrgAuthedContext = Omit<TRPCContext, "session"> & {
+ session: AuthedSession & {
+ orgId: string;
+ orgRole: Role;
+ };
+};