diff --git a/apps/billing-web/e2e/fixtures/scenario.ts b/apps/billing-web/e2e/fixtures/scenario.ts
index 14919ab666e..1e6957439d0 100644
--- a/apps/billing-web/e2e/fixtures/scenario.ts
+++ b/apps/billing-web/e2e/fixtures/scenario.ts
@@ -204,3 +204,64 @@ export function defaultScenario(): CloudScenario {
operations: {}
}
}
+
+const CREATOR_YEARLY = {
+ slug: 'creator_yearly',
+ tier: 'CREATOR',
+ duration: 'ANNUAL',
+ price_cents: 26_880,
+ credits_cents: 82_800,
+ max_seats: 1,
+ availability: { available: true },
+ seat_summary: {
+ seat_count: 1,
+ total_cost_cents: 26_880,
+ total_credits_cents: 82_800
+ }
+} as const
+
+/**
+ * The default Creator Monthly subscriber switching to Creator Yearly, quoted
+ * as the real Cloud quotes it: the reset to yearly charges in full today,
+ * carries no proration instant, and reports the yearly renewal date, the
+ * plan's list price and the pre-discount subtotal.
+ */
+export function switchToYearly(scenario: CloudScenario): void {
+ const monthly = scenario.plans.plans[0]
+ scenario.plans = {
+ ...scenario.plans,
+ plans: [...scenario.plans.plans, CREATOR_YEARLY]
+ }
+ scenario.preview = {
+ ...scenario.preview,
+ transition_type: 'duration_change',
+ is_immediate: true,
+ effective_at: new Date().toISOString(),
+ renewal_at: '2027-09-30T00:00:00.000Z',
+ cost_today_cents: 26_880,
+ amount_due_cents: 26_880,
+ subtotal_cents: 26_880,
+ cost_next_period_cents: 26_880,
+ renewal_amount_cents: 26_880,
+ credits_today_cents: 82_800,
+ credits_next_period_cents: 82_800,
+ current_plan: {
+ slug: monthly.slug,
+ tier: monthly.tier,
+ duration: monthly.duration,
+ price_cents: monthly.price_cents,
+ credits_cents: monthly.credits_cents,
+ seat_summary: monthly.seat_summary,
+ period_end: '2026-10-30T00:00:00.000Z'
+ },
+ new_plan: {
+ slug: CREATOR_YEARLY.slug,
+ tier: CREATOR_YEARLY.tier,
+ duration: CREATOR_YEARLY.duration,
+ price_cents: CREATOR_YEARLY.price_cents,
+ list_price_cents: 33_600,
+ credits_cents: CREATOR_YEARLY.credits_cents,
+ seat_summary: CREATOR_YEARLY.seat_summary
+ }
+ }
+}
diff --git a/apps/billing-web/e2e/full-page-endings.spec.ts b/apps/billing-web/e2e/full-page-endings.spec.ts
index c73c16b65f6..97c3d1059fa 100644
--- a/apps/billing-web/e2e/full-page-endings.spec.ts
+++ b/apps/billing-web/e2e/full-page-endings.spec.ts
@@ -64,6 +64,7 @@ test('a Pay that goes through names the plan and the workspace, and Close goes b
page.getByText('Your plan for Personal has been successfully updated.')
).toBeVisible()
await expect(page.getByTestId('checkout-ending-plan')).toContainText('Pro')
+ await expect(page.getByTestId('checkout-ending-paid-today')).toBeHidden()
await expect(code(page)).toBeHidden()
await expect(page.getByText('You can close this tab now.')).toBeVisible()
await expect(page.getByText(/Closing in/)).toBeHidden()
@@ -109,6 +110,126 @@ test('a reload after its own Pay went through renders Already completed on every
expect(subscribeRequests(cloud)).toHaveLength(1)
})
+const RECEIPT_PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+
+test('77-4068: a Pay that goes through counts the credits the server says it added', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ cloud.scenario.operations.op_subscribe = {
+ ...succeededOperation('op_subscribe'),
+ amount_charged_cents: 5000,
+ credits_added: 10_000,
+ plan: RECEIPT_PLAN
+ }
+ await signIn(CHECKOUT)
+ await payButton(page).click()
+
+ await expect(heading(page, "You're all set")).toBeVisible()
+ await expect(page.getByTestId('checkout-ending-plan')).toContainText(
+ '10,000 credits added'
+ )
+})
+
+const paidToday = (page: Page) => page.getByTestId('checkout-ending-paid-today')
+
+test('758-15763: a Pay under a promo code keeps the plan rate on Success and lists the code, then what was paid today', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ cloud.scenario.preview = {
+ ...cloud.scenario.preview,
+ amount_due_cents: 4000,
+ promotion_code: 'LAUNCH20',
+ discounts: [
+ {
+ kind: 'promotion',
+ code: 'LAUNCH20',
+ name: 'Launch 20%',
+ amount_off_cents: 1000,
+ duration: 'once'
+ }
+ ]
+ }
+ await signIn(CHECKOUT)
+ await payButton(page).click()
+
+ await expect(heading(page, "You're all set")).toBeVisible()
+ const card = page.getByTestId('checkout-ending-plan')
+ await expect(card).toContainText('$50.00')
+ await expect(paidToday(page)).toHaveText(
+ /Launch 20%\s*−\$10\.00\s*First month\s*Paid today\s*\$40\.00/
+ )
+})
+
+test('765-15713: a prorated upgrade reads Paid today and why, without itemizing the proration', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ const preview = cloud.scenario.preview
+ cloud.scenario.preview = {
+ ...preview,
+ transition_type: 'upgrade',
+ proration_at: '2026-07-10T09:30:00.000Z',
+ amount_due_cents: 3250,
+ cost_today_cents: 3250,
+ credits_today_cents: 3250,
+ credits_next_period_cents: 10_000,
+ renewal_amount_cents: 10_000,
+ current_plan: {
+ ...preview.new_plan,
+ slug: 'creator_monthly',
+ tier: 'CREATOR',
+ price_cents: 3500
+ }
+ }
+ await signIn(CHECKOUT)
+ await payButton(page).click()
+
+ await expect(heading(page, "You're all set")).toBeVisible()
+ await expect(paidToday(page)).toHaveText(
+ /^\s*Paid today\s*\$32\.50\s*Prorated for the rest of this billing period\s*$/
+ )
+})
+
+test('390-4947 / 328-4444: a charge whose credits are still landing reads Payment received, then Already completed names the plan once they land', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ cloud.scenario.operations.op_subscribe = {
+ ...succeededOperation('op_subscribe'),
+ amount_charged_cents: 5000,
+ plan: RECEIPT_PLAN
+ }
+ await signIn(CHECKOUT)
+ await payButton(page).click()
+
+ await expect(heading(page, 'Payment received')).toBeVisible()
+ const receipt = page.getByTestId('checkout-ending-receipt')
+ await expect(receipt).toContainText('Payment$50.00')
+ await expect(receipt).toContainText('Credits addedAdding…')
+ await expect(receipt).toContainText('PlanPro')
+ await expect(code(page)).toHaveText('op_subscribe')
+
+ cloud.scenario.operations.op_subscribe = {
+ ...cloud.scenario.operations.op_subscribe,
+ credits_added: 10_000
+ }
+ settleOnServer(cloud)
+ await page.reload()
+
+ await expect(heading(page, 'Already completed')).toBeVisible()
+ await expect(page.getByTestId('checkout-ending-plan')).toContainText(
+ 'Pro$50.00 USD / mo10,000 credits added'
+ )
+ await expect(code(page)).toBeHidden()
+ expect(subscribeRequests(cloud)).toHaveLength(1)
+})
+
test('a later checkout in the same tab for a plan still for sale opens the form, not the old payment', async ({
page,
signIn
diff --git a/apps/billing-web/e2e/full-page-summary.spec.ts b/apps/billing-web/e2e/full-page-summary.spec.ts
index e28d5a4fe24..357d12eb6cc 100644
--- a/apps/billing-web/e2e/full-page-summary.spec.ts
+++ b/apps/billing-web/e2e/full-page-summary.spec.ts
@@ -1,5 +1,6 @@
import type { Page } from '@playwright/test'
+import { switchToYearly } from './fixtures/scenario'
import { installFakeStripe } from './fixtures/stripe'
import { entryPath, expect, test as base } from './fixtures/test'
@@ -179,3 +180,88 @@ test('a held discount and an entered code read as rows, with no Subtotal the quo
await expect(summary).not.toContainText('−$9.99')
await expect(summary).not.toContainText('Subtotal')
})
+
+const YEARLY_CHECKOUT = entryPath('checkout', { plan: 'creator_yearly' })
+
+test('a monthly to yearly switch reads its renewal date and struck-through list price from the quote', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ switchToYearly(cloud.scenario)
+ await signIn(YEARLY_CHECKOUT)
+
+ await expectSummary(page, [
+ 'Switch to Creator Yearly · Personal',
+ '$268.80 USD',
+ 'Creator Yearly$268.80',
+ '$268.80 $336 /yr, billed yearly',
+ 'Renews at $268.80 on September 30, 2027',
+ "This month's credits stay valid until October 30, 2026"
+ ])
+ const summary = page.getByRole('region', { name: 'Order summary' })
+ await expect(summary.locator('s')).toHaveText('$336')
+ await expect(summary).not.toContainText('Subtotal')
+})
+
+test('a promo code on a yearly switch is bounded to the first year', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ switchToYearly(cloud.scenario)
+ cloud.scenario.preview = {
+ ...cloud.scenario.preview,
+ amount_due_cents: 21_504,
+ promotion_code: 'COMFY20',
+ discounts: [
+ {
+ kind: 'promotion',
+ code: 'COMFY20',
+ amount_off_cents: 5376,
+ duration: 'once'
+ }
+ ]
+ }
+ await signIn(YEARLY_CHECKOUT)
+
+ await expectSummary(page, [
+ 'Promo code−$53.76',
+ 'First year',
+ 'Total due today$215.04'
+ ])
+})
+
+test('744-15697: an account balance the server applied is the last deduction, and keeps the prorated row it explains', async ({
+ page,
+ cloud,
+ signIn
+}) => {
+ const preview = cloud.scenario.preview
+ cloud.scenario.preview = {
+ ...preview,
+ transition_type: 'upgrade',
+ proration_at: '2026-07-10T09:30:00.000Z',
+ amount_due_cents: 2750,
+ cost_today_cents: 3250,
+ balance_applied_cents: 500,
+ credits_today_cents: 3250,
+ credits_next_period_cents: 10_000,
+ renewal_amount_cents: 10_000,
+ renewal_at: RENEWAL_AT,
+ current_plan: {
+ ...preview.new_plan,
+ slug: 'creator_monthly',
+ tier: 'CREATOR',
+ price_cents: 3500
+ }
+ }
+ await signIn(CHECKOUT)
+
+ await expectSummary(page, [
+ 'Pro Plan - Prorated$32.50',
+ 'Account balance−$5.00',
+ 'Credit already on your account',
+ 'Total due today$27.50'
+ ])
+})
diff --git a/apps/billing-web/src/checkout/checkoutPage.test.ts b/apps/billing-web/src/checkout/checkoutPage.test.ts
index 8bd6d4cfdad..7d7dcb5bf50 100644
--- a/apps/billing-web/src/checkout/checkoutPage.test.ts
+++ b/apps/billing-web/src/checkout/checkoutPage.test.ts
@@ -1,4 +1,5 @@
import type {
+ BillingOperationReceipt,
BillingOperationState,
PendingBillingOperation
} from '@comfyorg/account-core/billing'
@@ -17,6 +18,7 @@ import type {
} from '@/checkout/checkoutPage'
import {
RESOLVING,
+ awaitingServer,
challengeToReopen,
isChallengeReopenable,
isLocked,
@@ -24,6 +26,7 @@ import {
railAcceptsPay,
railView,
reduceCheckoutPage,
+ settledPlanSource,
submitPhaseOf,
waitingOn
} from '@/checkout/checkoutPage'
@@ -1156,6 +1159,11 @@ describe("reduceCheckoutPage over this tab's own operation", () => {
operation: awaited(succeededOperation()),
attribution: 'returned'
}
+ const RECEIPT_PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+ const withReceipt = (receipt: BillingOperationReceipt) => ({
+ ...succeededOperation(),
+ receipt
+ })
it.for<{
name: string
@@ -1214,12 +1222,131 @@ describe("reduceCheckoutPage over this tab's own operation", () => {
operation: succeededOperation(),
attribution: 'started'
}
+ },
+ {
+ name: 'Already completed takes the plan the catalog lists for its receipt',
+ events: [
+ reconciled(withReceipt({ plan: RECEIPT_PLAN })),
+ notAllowed,
+ { type: 'settledPlanRead', plan: PRO }
+ ],
+ expected: {
+ kind: 'terminal',
+ operation: withReceipt({ plan: RECEIPT_PLAN }),
+ attribution: 'settled',
+ plan: PRO
+ }
+ },
+ {
+ name: 'a success whose credits were landing takes the read that reports them',
+ events: [
+ reconciled(awaited(withReceipt({ amountChargedCents: 3250 }))),
+ reconciled(
+ awaited(withReceipt({ amountChargedCents: 3250, creditsAdded: 6858 }))
+ )
+ ],
+ expected: {
+ ...RETURNED,
+ operation: awaited(
+ withReceipt({ amountChargedCents: 3250, creditsAdded: 6858 })
+ )
+ }
+ },
+ {
+ name: 'a success keeps its operation over a read of a different one',
+ events: [
+ reconciled(awaited(succeededOperation())),
+ reconciled(succeededOperation('op_other'))
+ ],
+ expected: RETURNED
}
])('$name', ({ events, expected }) => {
expect(replay(events)).toEqual(expected)
})
})
+describe('settled payments the page reads on its own', () => {
+ const PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+ const settled = (receipt?: BillingOperationReceipt) => ({
+ ...succeededOperation('op_1'),
+ ...(receipt === undefined ? {} : { receipt })
+ })
+
+ it.for<{ name: string; page: CheckoutPage; awaiting: boolean }>([
+ {
+ name: 'an outcome parked for a human',
+ page: { kind: 'unconfirmed', operationId: 'op_1' },
+ awaiting: true
+ },
+ {
+ name: 'a success whose credits are still landing',
+ page: {
+ kind: 'terminal',
+ operation: settled({ amountChargedCents: 5000 }),
+ attribution: 'settled'
+ },
+ awaiting: true
+ },
+ {
+ name: 'a success whose credits landed',
+ page: {
+ kind: 'terminal',
+ operation: settled({ amountChargedCents: 5000, creditsAdded: 10 }),
+ attribution: 'settled'
+ },
+ awaiting: false
+ },
+ {
+ name: 'a success with no receipt',
+ page: { kind: 'terminal', attribution: 'started' },
+ awaiting: false
+ }
+ ])('re-reads $name: $awaiting', ({ page, awaiting }) => {
+ expect(awaitingServer(page)).toBe(awaiting)
+ })
+
+ it.for<{
+ name: string
+ page: CheckoutPage
+ source: ReturnType
+ }>([
+ {
+ name: 'the plan a settled receipt names',
+ page: {
+ kind: 'terminal',
+ operation: settled({ plan: PLAN }),
+ attribution: 'settled'
+ },
+ source: { key: 'receipt:pro_monthly', receiptSlug: 'pro_monthly' }
+ },
+ {
+ name: "the status's plan for a returned payment with no receipt plan",
+ page: {
+ kind: 'terminal',
+ operation: settled(),
+ attribution: 'returned'
+ },
+ source: { key: 'status' }
+ },
+ {
+ name: 'nothing for a settled payment with no receipt plan',
+ page: { kind: 'terminal', operation: settled(), attribution: 'settled' },
+ source: undefined
+ },
+ {
+ name: "nothing for this page's own Pay, which its quote names",
+ page: {
+ kind: 'terminal',
+ operation: settled({ plan: PLAN }),
+ attribution: 'started'
+ },
+ source: undefined
+ }
+ ])('reads $name', ({ page, source }) => {
+ expect(settledPlanSource(page)).toEqual(source)
+ })
+})
+
describe('waitingOn', () => {
it.for<{ name: string; operation: PendingBillingOperation; on: WaitingOn }>([
{
diff --git a/apps/billing-web/src/checkout/checkoutPage.ts b/apps/billing-web/src/checkout/checkoutPage.ts
index d1144571b7e..5bad67ddc30 100644
--- a/apps/billing-web/src/checkout/checkoutPage.ts
+++ b/apps/billing-web/src/checkout/checkoutPage.ts
@@ -6,6 +6,7 @@ import type {
PendingBillingOperation,
TerminalBillingOperation
} from '@comfyorg/account-core/billing'
+import { isGrantLanding } from '@comfyorg/account-core/billing'
type ElementStatus = 'loading' | 'ready' | 'failed'
@@ -106,7 +107,11 @@ type Capture = {
*/
type Attribution = 'started' | 'returned' | 'followed' | 'settled'
-/** The plan a returned payment bought, as the server's status and catalog list it. */
+/**
+ * The plan a settled payment bought, as the server's catalog lists it: the
+ * one its receipt names, or for a returned payment without one, the plan the
+ * status now reports.
+ */
export type SettledPlan = Pick<
BillingPlansData['plans'][number],
'tier' | 'duration' | 'price_cents'
@@ -191,7 +196,7 @@ export type CheckoutPageEvent =
| { readonly type: 'planUnavailable'; readonly reason: PlanUnavailableReason }
/** The quote answered `allowed: false`; its free-text reason is never read. */
| { readonly type: 'notAllowed' }
- /** The server's status and catalog named the plan a returned payment bought. */
+ /** The server's catalog named the plan a settled payment bought. */
| { readonly type: 'settledPlanRead'; readonly plan: SettledPlan }
/** Try again on a checkout that could not load. */
| { readonly type: 'retried' }
@@ -394,7 +399,7 @@ export function reduceCheckoutPage(
return page.kind === 'resolving' ? stoppedOn(page, event) : page
switch (event.type) {
case 'settledPlanRead':
- return page.kind === 'terminal' && page.attribution === 'returned'
+ return page.kind === 'terminal' && page.attribution !== 'started'
? { ...page, plan: event.plan }
: page
case 'requoteFailed':
@@ -660,6 +665,40 @@ export function waitingOn(operation: PendingBillingOperation): WaitingOn {
return settling ? 'settling' : 'verifying'
}
+/**
+ * A screen that promised to update but whose operation the lifecycle no
+ * longer polls: an outcome parked for a human, or a success whose credits
+ * the server has not recorded yet. The page re-reads it itself.
+ */
+export function awaitingServer(page: CheckoutPage): boolean {
+ if (page.kind === 'unconfirmed') return true
+ return (
+ page.kind === 'terminal' &&
+ page.operation !== undefined &&
+ isGrantLanding(page.operation)
+ )
+}
+
+/**
+ * Where a settled page reads the plan its payment bought, keyed so a caller
+ * reads it once: the slug its receipt names, or for this tab's own payment
+ * returned without one, the status. A page that priced the payment itself
+ * names the plan from its quote and needs neither.
+ */
+export function settledPlanSource(
+ page: CheckoutPage
+): { readonly key: string; readonly receiptSlug?: string } | undefined {
+ if (page.kind !== 'terminal' || page.attribution === 'started')
+ return undefined
+ const receiptSlug =
+ page.operation?.phase === 'succeeded'
+ ? page.operation.receipt?.plan?.slug
+ : undefined
+ if (receiptSlug !== undefined)
+ return { key: `receipt:${receiptSlug}`, receiptSlug }
+ return page.attribution === 'returned' ? { key: 'status' } : undefined
+}
+
/** The server parked the operation for a human and cannot say whether money moved. */
const outcomeUnknown = (operation: BillingOperationState) =>
operation.phase === 'reconciliation_needed'
@@ -715,12 +754,18 @@ function followed(
return page
}
-/** A terminal reached before its operation arrived takes the operation's id. */
+/**
+ * A terminal reached before its operation arrived takes the operation, and a
+ * later read of the same operation replaces it, since the server may since
+ * have recorded the credits it added.
+ */
function withSettled(
page: Extract,
operation: BillingOperationState
): CheckoutPage {
- return operation.phase === 'succeeded' && page.operation === undefined
+ const takes =
+ page.operation === undefined || page.operation.id === operation.id
+ return operation.phase === 'succeeded' && takes
? { ...page, operation }
: page
}
diff --git a/apps/billing-web/src/checkout/endingScreen.test.ts b/apps/billing-web/src/checkout/endingScreen.test.ts
index 67a742b0238..8570b356549 100644
--- a/apps/billing-web/src/checkout/endingScreen.test.ts
+++ b/apps/billing-web/src/checkout/endingScreen.test.ts
@@ -1,3 +1,5 @@
+import type { BillingOperationReceipt } from '@comfyorg/account-core/billing'
+
import type { CheckoutPage } from '@/checkout/checkoutPage'
import { RESOLVING } from '@/checkout/checkoutPage'
import type { EndingScreen } from '@/checkout/endingScreen'
@@ -127,3 +129,84 @@ describe('endingOf', () => {
expect(endingOf(page)).toEqual(screen)
})
})
+
+describe('endingOf with the receipt the server reported', () => {
+ const PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+ const settledWith = (receipt: BillingOperationReceipt) => ({
+ ...succeededOperation('op_paid'),
+ receipt
+ })
+
+ it.for<{
+ name: string
+ page: CheckoutPage
+ screen: EndingScreen
+ }>([
+ {
+ name: "this page's own Pay, with the credits it added",
+ page: {
+ kind: 'terminal',
+ operation: settledWith({
+ amountChargedCents: 3250,
+ creditsAdded: 6858,
+ plan: PLAN
+ }),
+ attribution: 'started'
+ },
+ screen: {
+ kind: 'success',
+ receipt: { amountChargedCents: 3250, creditsAdded: 6858, plan: PLAN }
+ }
+ },
+ {
+ name: 'a payment already through, with its plan and credits',
+ page: {
+ kind: 'terminal',
+ operation: settledWith({ creditsAdded: 6858, plan: PLAN }),
+ attribution: 'settled'
+ },
+ screen: {
+ kind: 'already_completed',
+ code: 'op_paid',
+ receipt: { creditsAdded: 6858, plan: PLAN }
+ }
+ },
+ {
+ name: 'a payment the page watched settle, with its plan',
+ page: {
+ kind: 'terminal',
+ operation: settledWith({ plan: PLAN }),
+ attribution: 'followed'
+ },
+ screen: { kind: 'completed', code: 'op_paid', receipt: { plan: PLAN } }
+ },
+ {
+ name: "this page's own charge whose credits are still landing",
+ page: {
+ kind: 'terminal',
+ operation: settledWith({ amountChargedCents: 3250, plan: PLAN }),
+ attribution: 'started'
+ },
+ screen: {
+ kind: 'received',
+ code: 'op_paid',
+ receipt: { amountChargedCents: 3250, plan: PLAN }
+ }
+ },
+ {
+ name: 'a charge already through whose credits are still landing',
+ page: {
+ kind: 'terminal',
+ operation: settledWith({ amountChargedCents: 1500 }),
+ attribution: 'settled'
+ },
+ screen: {
+ kind: 'received',
+ code: 'op_paid',
+ receipt: { amountChargedCents: 1500 }
+ }
+ }
+ ])('$name', ({ page, screen }) => {
+ expect(endingOf(page)).toEqual(screen)
+ })
+})
diff --git a/apps/billing-web/src/checkout/endingScreen.ts b/apps/billing-web/src/checkout/endingScreen.ts
index b88dd377bd3..7ea9d3e3cc9 100644
--- a/apps/billing-web/src/checkout/endingScreen.ts
+++ b/apps/billing-web/src/checkout/endingScreen.ts
@@ -1,4 +1,8 @@
-import type { CapabilityDenialReason } from '@comfyorg/account-core/billing'
+import type {
+ BillingOperationReceipt,
+ CapabilityDenialReason
+} from '@comfyorg/account-core/billing'
+import { isGrantLanding } from '@comfyorg/account-core/billing'
import type {
CheckoutPage,
@@ -39,16 +43,31 @@ const REFUSAL_COPY: Readonly> = {
/**
* The full-page screen a checkout ends on, and the code support can act on.
- * `success` is the only one that may name a plan: this page's own Pay sent
- * it. `completed` is money this page watched settle without sending it;
- * `already_completed` was through before the page could offer a form.
+ * `success` names the plan its quote priced: this page's own Pay sent it.
+ * `completed` is money this page watched settle without sending it;
+ * `already_completed` was through before the page could offer a form. Those
+ * two name a plan only from the `receipt` the server reported for the
+ * operation. `received` with a receipt is a charge the server confirmed
+ * whose credits are still landing.
*/
export type EndingScreen =
- | { readonly kind: 'success' }
- | { readonly kind: 'completed'; readonly code?: string }
- | { readonly kind: 'already_completed'; readonly code?: string }
+ | { readonly kind: 'success'; readonly receipt?: BillingOperationReceipt }
+ | {
+ readonly kind: 'completed'
+ readonly code?: string
+ readonly receipt?: BillingOperationReceipt
+ }
+ | {
+ readonly kind: 'already_completed'
+ readonly code?: string
+ readonly receipt?: BillingOperationReceipt
+ }
| { readonly kind: 'in_progress'; readonly code: string }
- | { readonly kind: 'received'; readonly code: string }
+ | {
+ readonly kind: 'received'
+ readonly code: string
+ readonly receipt?: BillingOperationReceipt
+ }
| { readonly kind: 'unconfirmed'; readonly code: string }
| {
readonly kind: 'refused'
@@ -129,10 +148,83 @@ const TERMINAL_KIND = {
function terminalEnding(
page: Extract
): EndingScreen {
+ const { operation } = page
+ const receipt =
+ operation?.phase === 'succeeded' && operation.receipt !== undefined
+ ? { receipt: operation.receipt }
+ : {}
+ if (operation !== undefined && isGrantLanding(operation))
+ return { kind: 'received', code: operation.id, ...receipt }
if (page.attribution === 'started' || page.attribution === 'returned')
- return { kind: 'success' }
+ return { kind: 'success', ...receipt }
const kind = TERMINAL_KIND[page.attribution]
- return page.operation === undefined
+ return operation === undefined
? { kind }
- : { kind, code: page.operation.id }
+ : { kind, code: operation.id, ...receipt }
+}
+
+/**
+ * A line of a receipt, in the grammar where tense is status: `adding` is the
+ * grant the server has not recorded yet; every other row is confirmed.
+ */
+export type ReceiptRow =
+ | { readonly kind: 'payment' | 'amount_paid'; readonly cents: number }
+ | { readonly kind: 'adding' | 'plan' }
+ | { readonly kind: 'added'; readonly credits: number }
+
+/**
+ * What an ending shows of the server's receipt. A done ending whose receipt
+ * names a plan shows the plan card; one that names none (a top-up) lists only
+ * what was added and paid, never a balance that may be stale by now, in place
+ * of the reference code. Payment received lists a confirmed charge with its
+ * credits still adding, above the code.
+ */
+export interface EndingReceipt {
+ readonly namesPlan: boolean
+ readonly rows: readonly ReceiptRow[]
+ /** The rows say what the payment did, so the reference code gives way. */
+ readonly rowsReplaceCode: boolean
+}
+
+function settledRows(receipt: BillingOperationReceipt): ReceiptRow[] {
+ return [
+ ...(receipt.creditsAdded === undefined
+ ? []
+ : [{ kind: 'added', credits: receipt.creditsAdded } as const]),
+ ...(receipt.amountChargedCents === undefined
+ ? []
+ : [{ kind: 'amount_paid', cents: receipt.amountChargedCents } as const])
+ ]
+}
+
+function landingRows(receipt: BillingOperationReceipt): ReceiptRow[] {
+ if (receipt.amountChargedCents === undefined) return []
+ return [
+ { kind: 'payment', cents: receipt.amountChargedCents },
+ { kind: 'adding' },
+ ...(receipt.plan === undefined ? [] : [{ kind: 'plan' } as const])
+ ]
+}
+
+export function endingReceipt(screen: EndingScreen): EndingReceipt {
+ switch (screen.kind) {
+ case 'success':
+ return { namesPlan: true, rows: [], rowsReplaceCode: false }
+ case 'completed':
+ case 'already_completed': {
+ const receipt = screen.receipt
+ if (receipt?.plan !== undefined)
+ return { namesPlan: true, rows: [], rowsReplaceCode: false }
+ const rows = receipt === undefined ? [] : settledRows(receipt)
+ return { namesPlan: false, rows, rowsReplaceCode: rows.length > 0 }
+ }
+ case 'received':
+ return {
+ namesPlan: false,
+ rows: screen.receipt === undefined ? [] : landingRows(screen.receipt),
+ rowsReplaceCode: false
+ }
+ default:
+ return { namesPlan: false, rows: [], rowsReplaceCode: false }
+ }
}
diff --git a/apps/billing-web/src/checkout/successBreakdown.test.ts b/apps/billing-web/src/checkout/successBreakdown.test.ts
new file mode 100644
index 00000000000..45e149260bb
--- /dev/null
+++ b/apps/billing-web/src/checkout/successBreakdown.test.ts
@@ -0,0 +1,235 @@
+import type { SubscriptionPreview } from '@comfyorg/account-core/billing'
+
+import type { CheckoutPage } from '@/checkout/checkoutPage'
+import type { SuccessBreakdown } from '@/checkout/successBreakdown'
+import { successBreakdown } from '@/checkout/successBreakdown'
+import { createBillingI18n } from '@/i18n'
+import { previewOf, succeededOperation } from '@/test/fakeBillingClient'
+
+const { t } = createBillingI18n().global
+
+const context = {
+ workspace: 'Comfy Studios',
+ tierName: (tier: SubscriptionPreview['new_plan']['tier']) =>
+ t(`hosted.tier.${tier}`),
+ t,
+ locale: 'en'
+}
+
+const PRO_MONTHLY = {
+ slug: 'pro_monthly',
+ tier: 'PRO',
+ duration: 'MONTHLY',
+ price_cents: 10_000,
+ credits_cents: 0,
+ seat_summary: {
+ seat_count: 1,
+ total_cost_cents: 10_000,
+ total_credits_cents: 0
+ }
+} as const satisfies SubscriptionPreview['new_plan']
+
+function quoteOf(overrides: Partial): SubscriptionPreview {
+ return previewOf({
+ currency: 'usd',
+ new_plan: PRO_MONTHLY,
+ amount_due_cents: 10_000,
+ cost_today_cents: 10_000,
+ ...overrides
+ })
+}
+
+const ownPay: CheckoutPage = { kind: 'terminal', attribution: 'started' }
+
+function settled(
+ attribution: 'started' | 'returned' | 'settled',
+ amountChargedCents?: number
+): CheckoutPage {
+ const operation = {
+ ...succeededOperation('op_paid'),
+ receipt: { amountChargedCents, creditsAdded: 21_100 }
+ }
+ return {
+ kind: 'terminal',
+ attribution,
+ operation,
+ plan: { tier: 'PRO', duration: 'MONTHLY', price_cents: 10_000n }
+ }
+}
+
+describe('successBreakdown', () => {
+ it.for<{
+ name: string
+ page: CheckoutPage
+ quote?: SubscriptionPreview
+ breakdown: SuccessBreakdown | undefined
+ }>([
+ {
+ name: 'in-page Pay with a promo code entered at checkout',
+ page: ownPay,
+ quote: quoteOf({
+ amount_due_cents: 8_000,
+ promotion_code: 'SAVE20',
+ discounts: [
+ {
+ kind: 'promotion',
+ code: 'SAVE20',
+ name: 'Save 20%',
+ amount_off_cents: 2_000,
+ duration: 'once'
+ }
+ ]
+ }),
+ breakdown: {
+ deductions: [
+ { label: 'Save 20%', amount: '−$20.00', subline: 'First month' }
+ ],
+ paidToday: { label: 'Paid today', amount: '$80.00', sublines: [] }
+ }
+ },
+ {
+ name: 'in-page Pay under a discount the subscription already holds',
+ page: ownPay,
+ quote: quoteOf({
+ amount_due_cents: 7_500,
+ discounts: [
+ {
+ kind: 'promotion',
+ code: 'LOYAL',
+ name: 'Loyalty',
+ amount_off_cents: 2_500,
+ duration: 'repeating',
+ duration_in_months: 3
+ }
+ ]
+ }),
+ breakdown: {
+ deductions: [
+ { label: 'Loyalty', amount: '−$25.00', subline: 'For 3 months' }
+ ],
+ paidToday: { label: 'Paid today', amount: '$75.00', sublines: [] }
+ }
+ },
+ {
+ name: 'in-page Pay partly covered by the account balance',
+ page: ownPay,
+ quote: quoteOf({ amount_due_cents: 9_000, balance_applied_cents: 1_000 }),
+ breakdown: {
+ deductions: [
+ {
+ label: 'Account balance',
+ amount: '−$10.00',
+ subline: 'Credit already on your account'
+ }
+ ],
+ paidToday: { label: 'Paid today', amount: '$90.00', sublines: [] }
+ }
+ },
+ {
+ name: 'a prorated upgrade: no itemized rows, only the paid amount and why',
+ page: ownPay,
+ quote: quoteOf({
+ transition_type: 'upgrade',
+ proration_at: '2026-07-10T09:30:00.000Z',
+ current_plan: {
+ ...PRO_MONTHLY,
+ slug: 'standard_monthly',
+ tier: 'STANDARD'
+ },
+ amount_due_cents: 4_321,
+ cost_today_cents: 4_321,
+ balance_applied_cents: 0
+ }),
+ breakdown: {
+ deductions: [],
+ paidToday: {
+ label: 'Paid today',
+ amount: '$43.21',
+ sublines: ['Prorated for the rest of this billing period']
+ }
+ }
+ },
+ {
+ name: 'paid today matches the plan rate: the card stays as is',
+ page: ownPay,
+ quote: quoteOf({}),
+ breakdown: undefined
+ },
+ {
+ name: 'a plan-level discounted rate charged in full',
+ page: ownPay,
+ quote: quoteOf({
+ new_plan: { ...PRO_MONTHLY, list_price_cents: 12_000 },
+ discounts: [{ kind: 'plan', code: 'ANNUAL', amount_off_cents: 2_000 }]
+ }),
+ breakdown: undefined
+ },
+ {
+ name: 'a scheduled change that charges nothing today',
+ page: ownPay,
+ quote: quoteOf({
+ is_immediate: false,
+ transition_type: 'downgrade',
+ amount_due_cents: 0,
+ cost_today_cents: 0
+ }),
+ breakdown: undefined
+ },
+ {
+ name: 'in-page Pay whose finished op reported the charge',
+ page: settled('started', 7_900),
+ quote: quoteOf({
+ amount_due_cents: 8_000,
+ promotion_code: 'SAVE20',
+ discounts: [
+ {
+ kind: 'promotion',
+ code: 'SAVE20',
+ name: 'Save 20%',
+ amount_off_cents: 2_000
+ }
+ ]
+ }),
+ breakdown: {
+ deductions: [{ label: 'Save 20%', amount: '−$20.00' }],
+ paidToday: { label: 'Paid today', amount: '$79.00', sublines: [] }
+ }
+ },
+ {
+ name: 'a provider return reads only the op status: Paid today alone',
+ page: settled('returned', 8_000),
+ quote: quoteOf({
+ amount_due_cents: 8_000,
+ promotion_code: 'SAVE20',
+ discounts: [
+ {
+ kind: 'promotion',
+ code: 'SAVE20',
+ amount_off_cents: 2_000
+ }
+ ]
+ }),
+ breakdown: {
+ deductions: [],
+ paidToday: { label: 'Paid today', amount: '$80.00', sublines: [] }
+ }
+ },
+ {
+ name: 'a provider return charged the plan rate',
+ page: settled('returned', 10_000),
+ breakdown: undefined
+ },
+ {
+ name: 'a provider return whose op does not report the charge',
+ page: settled('returned'),
+ breakdown: undefined
+ },
+ {
+ name: 'a payment this page did not send is not a Success',
+ page: settled('settled', 8_000),
+ breakdown: undefined
+ }
+ ])('$name', ({ page, quote, breakdown }) => {
+ expect(successBreakdown(page, quote, context)).toEqual(breakdown)
+ })
+})
diff --git a/apps/billing-web/src/checkout/successBreakdown.ts b/apps/billing-web/src/checkout/successBreakdown.ts
new file mode 100644
index 00000000000..4000d7b1ae8
--- /dev/null
+++ b/apps/billing-web/src/checkout/successBreakdown.ts
@@ -0,0 +1,137 @@
+import type { SubscriptionPreview } from '@comfyorg/account-core/billing'
+import { formatQuoteMoney } from '@comfyorg/account-ui/billing/checkout'
+
+import type { CheckoutPage } from '@/checkout/checkoutPage'
+import { endingOf } from '@/checkout/endingScreen'
+import type {
+ DiscountRow,
+ LedgerContext,
+ SummaryLedger
+} from '@/checkout/summaryLedger'
+import { buildSummaryLedger } from '@/checkout/summaryLedger'
+
+/**
+ * Why a Success card's charge differs from the plan rate it shows: one row
+ * per reason the server reported, then what it charged today.
+ */
+export interface SuccessBreakdown {
+ readonly deductions: readonly DiscountRow[]
+ readonly paidToday: SummaryLedger['items'][number]
+}
+
+/**
+ * What the page knows about the charge. This page's own Pay still holds the
+ * quote it paid, so its reasons are the quote's; a return from a payment
+ * provider knows only what the operation status reports.
+ */
+type ChargeSource =
+ | {
+ readonly kind: 'quoted'
+ readonly quote: SubscriptionPreview
+ readonly paidCents: number
+ }
+ | {
+ readonly kind: 'op_status'
+ readonly rateCents: number
+ readonly paidCents: number
+ }
+
+type Terminal = Extract
+
+function chargedCents({ operation }: Terminal): number | undefined {
+ return operation?.phase === 'succeeded'
+ ? operation.receipt?.amountChargedCents
+ : undefined
+}
+
+function quotedSource(
+ quote: SubscriptionPreview | undefined,
+ charged: number | undefined
+): ChargeSource | undefined {
+ if (quote === undefined) return undefined
+ return {
+ kind: 'quoted',
+ quote,
+ paidCents: charged ?? quote.amount_due_cents ?? quote.cost_today_cents
+ }
+}
+
+function opStatusSource(
+ plan: Terminal['plan'],
+ charged: number | undefined
+): ChargeSource | undefined {
+ if (plan === undefined || charged === undefined) return undefined
+ return {
+ kind: 'op_status',
+ rateCents: Number(plan.price_cents),
+ paidCents: charged
+ }
+}
+
+function chargeSourceOf(
+ page: CheckoutPage,
+ quote: SubscriptionPreview | undefined
+): ChargeSource | undefined {
+ if (page.kind !== 'terminal' || endingOf(page)?.kind !== 'success')
+ return undefined
+ const charged = chargedCents(page)
+ return page.attribution === 'started'
+ ? quotedSource(quote, charged)
+ : opStatusSource(page.plan, charged)
+}
+
+const R = 'checkout.fullPage.ending.receipt'
+
+/**
+ * The rows under a Success card's plan rate, or none while today's charge
+ * equals that rate. "Differs" compares the two server amounts; no reason's
+ * amount is derived from the gap. A plan-level rate is already the card's
+ * price, and a scheduled change charges nothing today, so neither gets rows.
+ * Proration is not itemized, only named under the amount paid.
+ */
+export function successBreakdown(
+ page: CheckoutPage,
+ quote: SubscriptionPreview | undefined,
+ context: LedgerContext
+): SuccessBreakdown | undefined {
+ const source = chargeSourceOf(page, quote)
+ if (source === undefined) return undefined
+ const { t, locale } = context
+
+ if (source.kind === 'op_status')
+ return source.paidCents === source.rateCents
+ ? undefined
+ : {
+ deductions: [],
+ paidToday: {
+ label: t(`${R}.paidToday`, {}),
+ amount: formatQuoteMoney(source.paidCents, 'usd', locale),
+ sublines: []
+ }
+ }
+
+ const { quote: paid, paidCents } = source
+ if (paidCents === paid.new_plan.price_cents) return undefined
+ const ledger = buildSummaryLedger(paid, context)
+ const paidToday = {
+ label: t(`${R}.paidToday`, {}),
+ amount: formatQuoteMoney(paidCents, paid.currency ?? 'usd', locale)
+ }
+ switch (ledger.family) {
+ case 'scheduled':
+ return undefined
+ case 'prorated_change':
+ return {
+ deductions: [],
+ paidToday: { ...paidToday, sublines: [t(`${R}.prorated`, {})] }
+ }
+ default:
+ return {
+ deductions:
+ ledger.balance === undefined
+ ? ledger.discounts
+ : [...ledger.discounts, ledger.balance],
+ paidToday: { ...paidToday, sublines: [] }
+ }
+ }
+}
diff --git a/apps/billing-web/src/checkout/summaryLedger.test.ts b/apps/billing-web/src/checkout/summaryLedger.test.ts
index 8373591de18..6482d065f9b 100644
--- a/apps/billing-web/src/checkout/summaryLedger.test.ts
+++ b/apps/billing-web/src/checkout/summaryLedger.test.ts
@@ -723,6 +723,183 @@ describe('buildSummaryLedger discounts', () => {
})
})
+describe('buildSummaryLedger server-reported fields', () => {
+ it.for<{
+ name: string
+ discount: Partial
+ duration: Plan['duration']
+ subline?: string
+ }>([
+ {
+ name: 'a once coupon on a yearly plan',
+ discount: { duration: 'once' },
+ duration: 'ANNUAL',
+ subline: 'First year'
+ },
+ {
+ name: 'a once coupon on a monthly plan',
+ discount: { duration: 'once' },
+ duration: 'MONTHLY',
+ subline: 'First month'
+ },
+ {
+ name: 'a repeating coupon',
+ discount: { duration: 'repeating', duration_in_months: 3 },
+ duration: 'MONTHLY',
+ subline: 'For 3 months'
+ },
+ {
+ name: 'a one-month repeating coupon',
+ discount: { duration: 'repeating', duration_in_months: 1 },
+ duration: 'MONTHLY',
+ subline: 'For 1 month'
+ },
+ {
+ name: 'a repeating coupon whose term the quote leaves out',
+ discount: { duration: 'repeating' },
+ duration: 'MONTHLY'
+ },
+ {
+ name: 'a forever coupon, the bare basis',
+ discount: { duration: 'forever' },
+ duration: 'ANNUAL'
+ },
+ {
+ name: 'a coupon whose term the server does not know',
+ discount: {},
+ duration: 'ANNUAL'
+ }
+ ])(
+ 'bounds a discount row by its term: $name',
+ ({ discount, duration, subline }) => {
+ const { discounts } = ledgerOf({
+ transition_type: 'new_subscription',
+ amount_due_cents: 604_800,
+ cost_today_cents: 756_000,
+ new_plan: planOf('TEAM', duration, 756_000),
+ promotion_code: 'COMFY20',
+ discounts: [{ ...entered('COMFY20', 151_200), ...discount }]
+ })
+
+ expect(discounts).toEqual([
+ {
+ label: 'Promo code',
+ amount: '−$1,512.00',
+ ...(subline === undefined ? {} : { subline })
+ }
+ ])
+ }
+ )
+
+ it.for<{
+ name: string
+ duration: Plan['duration']
+ rate: SummaryLedger['items'][number]['comparedRate']
+ }>([
+ {
+ name: 'yearly',
+ duration: 'ANNUAL',
+ rate: {
+ keypath: 'checkout.fullPage.summary.item.comparedYearly',
+ amount: '$7,560',
+ listAmount: '$8,400'
+ }
+ },
+ {
+ name: 'monthly',
+ duration: 'MONTHLY',
+ rate: {
+ keypath: 'checkout.fullPage.summary.item.comparedMonthly',
+ amount: '$7,560',
+ listAmount: '$8,400'
+ }
+ }
+ ])(
+ 'strikes through the list price a discounted $name rate replaces',
+ ({ duration, rate }) => {
+ const [item] = ledgerOf({
+ transition_type: 'new_subscription',
+ amount_due_cents: 756_000,
+ cost_today_cents: 756_000,
+ credits_today_cents: 0,
+ credits_next_period_cents: 0,
+ new_plan: planOf('TEAM', duration, 756_000, {
+ list_price_cents: 840_000
+ })
+ }).items
+
+ expect(item).toEqual({
+ label: 'Team Plan',
+ amount: '$7,560.00',
+ comparedRate: rate,
+ sublines: []
+ })
+ }
+ )
+
+ it('keeps the plain rate when the list price is the price', () => {
+ const [item] = ledgerOf({
+ transition_type: 'new_subscription',
+ amount_due_cents: 756_000,
+ cost_today_cents: 756_000,
+ credits_today_cents: 0,
+ credits_next_period_cents: 0,
+ new_plan: planOf('TEAM', 'ANNUAL', 756_000, {
+ list_price_cents: 756_000
+ })
+ }).items
+
+ expect(item).toEqual({
+ label: 'Team Plan',
+ amount: '$7,560.00',
+ sublines: ['Billed yearly']
+ })
+ })
+
+ const PRORATED_OVER_BALANCE: Partial = {
+ transition_type: 'upgrade',
+ proration_at: PRICED_AT,
+ amount_due_cents: 2750,
+ cost_today_cents: 3250,
+ balance_applied_cents: 500,
+ subtotal_cents: 3250,
+ renewal_at: JULY_28,
+ current_plan: planOf('CREATOR', 'MONTHLY', 3500),
+ new_plan: planOf('PRO', 'MONTHLY', 10_000)
+ }
+
+ it('lists the account balance the server applied, and keeps the row it explains', () => {
+ const ledger = ledgerOf(PRORATED_OVER_BALANCE)
+
+ expect(ledger.items.map(({ label, amount }) => [label, amount])).toEqual([
+ ['Pro Plan - Prorated', '$32.50']
+ ])
+ expect(ledger.balance).toEqual({
+ label: 'Account balance',
+ amount: '−$5.00',
+ subline: 'Credit already on your account'
+ })
+ expect(ledger.total).toBe('$27.50')
+ })
+
+ it('shows no balance row when the server applied none', () => {
+ expect(ledgerOf({ amount_due_cents: 2800 })).not.toHaveProperty('balance')
+ })
+
+ it('shows no Subtotal under a single money row, even with a discount and a reported subtotal', () => {
+ const ledger = ledgerOf({
+ ...PRORATED_OVER_BALANCE,
+ balance_applied_cents: undefined,
+ amount_due_cents: 2250,
+ promotion_code: 'COMFY10',
+ discounts: [entered('COMFY10', 1000)]
+ })
+
+ expect(ledger.discounts).toHaveLength(1)
+ expect(ledger).not.toHaveProperty('subtotal')
+ })
+})
+
describe('formatHeadlineMoney', () => {
it.for([
{ cents: 70_000, text: '$700' },
diff --git a/apps/billing-web/src/checkout/summaryLedger.ts b/apps/billing-web/src/checkout/summaryLedger.ts
index a0ae4d2fbcb..dd71d7f13eb 100644
--- a/apps/billing-web/src/checkout/summaryLedger.ts
+++ b/apps/billing-web/src/checkout/summaryLedger.ts
@@ -10,20 +10,33 @@ import { longDate, monthDay } from '@/checkout/longDate'
*/
type SummaryFamily = 'charge_now' | 'prorated_change' | 'scheduled' | 'top_up'
+/**
+ * A discounted plan rate beside the list price it replaces, both as the
+ * server priced them. The list price is the one amount the summary strikes
+ * through.
+ */
+interface ComparedRate {
+ readonly keypath: string
+ readonly amount: string
+ readonly listAmount: string
+}
+
/** A ledger line: a label and its sublines on the left, dollars on the right. */
interface LedgerRow {
readonly label: string
readonly amount: string
+ readonly comparedRate?: ComparedRate
readonly sublines: readonly string[]
}
/**
- * A discount the quote applied: what it is on the left, what it removed from
- * today's charge on the right. The code that produced it lives on a chip.
+ * A deduction from today's charge: what it is on the left, what it removed on
+ * the right. A discount's code lives on a chip; its subline bounds its term.
*/
-interface DiscountRow {
+export interface DiscountRow {
readonly label: string
readonly amount?: string
+ readonly subline?: string
}
/** Which code produced a discount. Only the customer's own code comes off. */
@@ -50,6 +63,10 @@ export interface SummaryLedger {
readonly items: readonly LedgerRow[]
/** Every promotion the quote applied, held or entered, in the server's order. */
readonly discounts: readonly DiscountRow[]
+ /** The server's pre-discount total, only when a discount follows two or more money rows. */
+ readonly subtotal?: string
+ /** Credit already on the account that the server applied to today's charge. */
+ readonly balance?: DiscountRow
readonly chips: readonly PromoChip[]
/** Codes apply to a charge made today, so only those families take one. */
readonly acceptsPromo: boolean
@@ -57,11 +74,18 @@ export interface SummaryLedger {
readonly trailing: readonly string[]
}
-type DiscountSlots = Pick
+type DiscountSlots = Pick<
+ SummaryLedger,
+ 'discounts' | 'subtotal' | 'balance' | 'chips' | 'acceptsPromo'
+>
type FamilyLedger = Omit
-type Translate = (key: string, named: Record) => string
+type Translate = (
+ key: string,
+ named: Record,
+ plural?: number
+) => string
type Duration = SubscriptionPreview['new_plan']['duration']
type Plan = SubscriptionPreview['new_plan']
@@ -80,6 +104,8 @@ const BY_DURATION = {
cadence: `${S}.cadence.monthly`,
rate: `${S}.rate.monthly`,
itemRate: `${S}.item.rateMonthly`,
+ comparedRate: `${S}.item.comparedMonthly`,
+ onceTerm: `${S}.discount.firstMonth`,
perPeriod: `${S}.credits.perMonth`,
refillAfter: `${S}.credits.refillMonthlyAfter`,
refillsTo: `${S}.item.refillsMonthly`,
@@ -89,6 +115,8 @@ const BY_DURATION = {
cadence: `${S}.cadence.yearly`,
rate: `${S}.rate.yearly`,
itemRate: `${S}.item.rateYearly`,
+ comparedRate: `${S}.item.comparedYearly`,
+ onceTerm: `${S}.discount.firstYear`,
perPeriod: `${S}.credits.perYear`,
refillAfter: `${S}.credits.refillYearlyAfter`,
refillsTo: `${S}.item.refillsYearly`,
@@ -205,17 +233,19 @@ function refillsToLine(r: QuoteReading): string {
/**
* A money row renders only when the total reconciles with it: today's
- * charge equals the row, or a discount row itemizes the difference. A $0
- * first period or a credit on file the quote does not itemize would leave
- * the row contradicting the total, so it comes off and the total stands on
- * its own.
+ * charge equals the row, or a discount or balance row itemizes the
+ * difference. A $0 first period or a credit the quote does not itemize would
+ * leave the row contradicting the total, so it comes off and the total
+ * stands on its own.
*/
function moneyItems(
r: QuoteReading,
cents: number,
row: Omit
): LedgerRow[] {
- return cents === r.dueCents || r.promotions.length > 0
+ const itemized =
+ r.promotions.length > 0 || r.quote.balance_applied_cents !== undefined
+ return cents === r.dueCents || itemized
? [{ ...row, amount: r.money(cents) }]
: []
}
@@ -367,25 +397,45 @@ function zeroDueLine(r: QuoteReading): string[] {
]
}
+/**
+ * The rate a plan discount (the yearly or team-commitment price) brought
+ * down from its list price, both as the server rated them.
+ */
+function comparedRateOf(r: QuoteReading): ComparedRate | undefined {
+ const listCents = r.next.list_price_cents
+ if (listCents === undefined || listCents <= r.next.price_cents)
+ return undefined
+ return {
+ keypath: r.byNew.comparedRate,
+ amount: r.headlineMoney(r.next.price_cents),
+ listAmount: r.headlineMoney(listCents)
+ }
+}
+
+function cadenceLineOf(r: QuoteReading): string {
+ return r.next.duration === 'MONTHLY'
+ ? r.t(`${S}.item.billedMonthly`, {
+ amount: r.headlineMoney(r.next.seat_summary.total_cost_cents)
+ })
+ : r.t(`${S}.item.billedYearly`, {})
+}
+
function chargeNowLedger(r: QuoteReading): FamilyLedger {
- const cadenceLine =
- r.next.duration === 'MONTHLY'
- ? r.t(`${S}.item.billedMonthly`, {
- amount: r.headlineMoney(r.next.seat_summary.total_cost_cents)
- })
- : r.t(`${S}.item.billedYearly`, {})
+ const comparedRate = comparedRateOf(r)
+ const refills =
+ r.cadenceChanges || !grantIsAllowance(r) ? [refillsToLine(r)] : []
return {
...r.shared,
family: 'charge_now',
headline: { amount: r.headlineMoney(r.dueCents), currency: r.currency },
credits: chargeNowCredits(r),
- items: moneyItems(r, r.quote.cost_today_cents, {
- label: r.plan,
- sublines:
- r.cadenceChanges || !grantIsAllowance(r)
- ? [cadenceLine, refillsToLine(r)]
- : [cadenceLine]
- }),
+ items: moneyItems(
+ r,
+ r.quote.cost_today_cents,
+ comparedRate === undefined
+ ? { label: r.plan, sublines: [cadenceLineOf(r), ...refills] }
+ : { label: r.plan, comparedRate, sublines: refills }
+ ),
trailing: chargeNowTrailing(r)
}
}
@@ -404,7 +454,7 @@ export function buildSummaryLedger(
): SummaryLedger {
const reading = readQuote(quote, context)
const ledger = familyLedger(reading)
- return { ...ledger, ...discountSlots(reading) }
+ return { ...ledger, ...discountSlots(reading, ledger.items.length) }
}
function familyLedger(r: QuoteReading): FamilyLedger {
@@ -425,32 +475,75 @@ export function acceptsPromoCode(quote: SubscriptionPreview): boolean {
type Discount = NonNullable[number]
+const deduction = (r: QuoteReading, cents: number) =>
+ r.t(`${S}.discount.amount`, { amount: r.money(cents) })
+
+/**
+ * How long a coupon keeps applying, stated as bounds only: `once` covers the
+ * first period, `repeating` its months, and `forever` needs no subline.
+ */
+function discountTerm(r: QuoteReading, discount: Discount): string | undefined {
+ if (discount.duration === 'once') return r.t(r.byNew.onceTerm, {})
+ const months = discount.duration_in_months
+ if (discount.duration !== 'repeating' || months === undefined)
+ return undefined
+ return r.t(`${S}.discount.forMonths`, { count: months }, months)
+}
+
function discountRow(r: QuoteReading, discount: Discount): DiscountRow {
+ const subline = discountTerm(r, discount)
return {
label: discount.name ?? r.t(`${S}.discount.fallbackLabel`, {}),
...(discount.amount_off_cents === undefined
? {}
- : {
- amount: r.t(`${S}.discount.amount`, {
- amount: r.money(discount.amount_off_cents)
- })
- })
+ : { amount: deduction(r, discount.amount_off_cents) }),
+ ...(subline === undefined ? {} : { subline })
}
}
+function balanceRow(r: QuoteReading): DiscountRow | undefined {
+ const cents = r.quote.balance_applied_cents
+ if (cents === undefined) return undefined
+ return {
+ label: r.t(`${S}.balance.label`, {}),
+ amount: deduction(r, cents),
+ subline: r.t(`${S}.balance.subline`, {})
+ }
+}
+
+/**
+ * Subtotal names the base a discount came off, so it shows only where a
+ * discount follows two or more money rows; above a single row it would
+ * repeat that row.
+ */
+function subtotalOf(
+ r: QuoteReading,
+ moneyRows: number,
+ discountRows: number
+): string | undefined {
+ const cents = r.quote.subtotal_cents
+ if (cents === undefined || moneyRows < 2 || discountRows === 0)
+ return undefined
+ return r.money(cents)
+}
+
/**
* Every promotion gets a row, in the order the server listed them and at the
* amount it reported. The `promotion` discount matching the quote's
* `promotion_code` is the customer's entered code, the only chip that comes
* off; any other is one the account already holds.
*/
-function discountSlots(r: QuoteReading): DiscountSlots {
+function discountSlots(r: QuoteReading, moneyRows: number): DiscountSlots {
const enteredCode = r.quote.promotion_code?.toUpperCase()
const held = r.promotions.filter(
(discount) => discount.code.toUpperCase() !== enteredCode
)
+ const subtotal = subtotalOf(r, moneyRows, r.promotions.length)
+ const balance = balanceRow(r)
return {
discounts: r.promotions.map((discount) => discountRow(r, discount)),
+ ...(subtotal === undefined ? {} : { subtotal }),
+ ...(balance === undefined ? {} : { balance }),
chips: [
...held.map(({ code }) => ({ code, removable: false })),
...(r.quote.promotion_code === undefined
diff --git a/apps/billing-web/src/components/fullPage/CheckoutEnding.test.ts b/apps/billing-web/src/components/fullPage/CheckoutEnding.test.ts
index 05c35a0d1e8..aa5b5afccf9 100644
--- a/apps/billing-web/src/components/fullPage/CheckoutEnding.test.ts
+++ b/apps/billing-web/src/components/fullPage/CheckoutEnding.test.ts
@@ -5,7 +5,7 @@ import type { CapabilityDenialReason } from '@comfyorg/account-core/billing'
import type { EndingScreen } from '@/checkout/endingScreen'
import { endingOf } from '@/checkout/endingScreen'
-import type { EndingPlan } from '@/components/fullPage/CheckoutEnding.vue'
+import type { EndingPlan } from '@/components/fullPage/EndingPlanCard.vue'
import CheckoutEnding from '@/components/fullPage/CheckoutEnding.vue'
import { createBillingI18n } from '@/i18n'
@@ -235,6 +235,150 @@ describe('CheckoutEnding', () => {
expect(screen.getByTestId('checkout-ending-plan')).toHaveTextContent(
'Pro$50.00 USD / mo'
)
+ expect(screen.queryByText(/credits added/)).not.toBeInTheDocument()
+ })
+
+ it('77-4068: Success counts the credits the server says it added', () => {
+ renderEnding({ kind: 'success', receipt: { creditsAdded: 6858 } })
+
+ expect(screen.getByTestId('checkout-ending-plan')).toHaveTextContent(
+ 'Pro$50.00 USD / mo6,858 credits added'
+ )
+ })
+
+ it('758-15763: Success keeps the rate and lists each reason, then Paid today', () => {
+ render(CheckoutEnding, {
+ props: {
+ screen: { kind: 'success' },
+ workspace: 'Acme Team',
+ plan: PLAN,
+ breakdown: {
+ deductions: [
+ { label: 'Launch', amount: '−$10.00', subline: 'First month' },
+ { label: 'Account balance', amount: '−$5.00' }
+ ],
+ paidToday: { label: 'Paid today', amount: '$35.00', sublines: [] }
+ }
+ },
+ global: { plugins: [createBillingI18n()] }
+ })
+
+ expect(screen.getByTestId('checkout-ending-plan')).toHaveTextContent(
+ 'Pro$50.00 USD / moLaunch−$10.00First monthAccount balance−$5.00Paid today$35.00'
+ )
+ })
+
+ it('shows no Paid today when the charge matched the plan rate', () => {
+ renderEnding({ kind: 'success' })
+
+ expect(
+ screen.queryByTestId('checkout-ending-paid-today')
+ ).not.toBeInTheDocument()
+ })
+
+ describe('the receipt the server reported', () => {
+ const RECEIPT_PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+
+ it.for([
+ {
+ kind: 'already_completed',
+ code: 'op_old',
+ receipt: { plan: RECEIPT_PLAN, creditsAdded: 6858 }
+ },
+ {
+ kind: 'completed',
+ code: 'op_seen',
+ receipt: { plan: RECEIPT_PLAN, creditsAdded: 6858 }
+ }
+ ])(
+ '328-4444: $kind names the plan its receipt names, in place of the reference',
+ (ending) => {
+ renderEnding(ending)
+
+ expect(screen.getByTestId('checkout-ending-plan')).toHaveTextContent(
+ 'Pro$50.00 USD / mo6,858 credits added'
+ )
+ expect(
+ screen.queryByTestId('checkout-ending-code')
+ ).not.toBeInTheDocument()
+ }
+ )
+
+ it('keeps the reference when the catalog cannot list the plan a receipt names', () => {
+ render(CheckoutEnding, {
+ props: {
+ screen: {
+ kind: 'already_completed',
+ code: 'op_old',
+ receipt: { plan: RECEIPT_PLAN }
+ },
+ workspace: 'Acme Team'
+ },
+ global: { plugins: [createBillingI18n()] }
+ })
+
+ expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent(
+ 'op_old'
+ )
+ expect(
+ screen.queryByTestId('checkout-ending-plan')
+ ).not.toBeInTheDocument()
+ })
+
+ it('410-5225: a top-up already completed reads Added and Amount paid, and no balance', () => {
+ renderEnding({
+ kind: 'already_completed',
+ code: 'op_topup',
+ receipt: { creditsAdded: 3000, amountChargedCents: 1500 }
+ })
+
+ expect(screen.getByTestId('checkout-ending-receipt')).toHaveTextContent(
+ 'Added+3,000Amount paid$15.00'
+ )
+ expect(screen.queryByText(/balance/i)).not.toBeInTheDocument()
+ expect(
+ screen.queryByTestId('checkout-ending-plan')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByTestId('checkout-ending-code')
+ ).not.toBeInTheDocument()
+ })
+
+ it('390-4947: Payment received confirms the payment and shows the credits still adding', () => {
+ renderEnding({
+ kind: 'received',
+ code: 'op_r',
+ receipt: { amountChargedCents: 3500, plan: RECEIPT_PLAN }
+ })
+
+ expect(screen.getByTestId('checkout-ending-receipt')).toHaveTextContent(
+ 'Payment$35.00Credits addedAdding…PlanPro'
+ )
+ expect(screen.getByTestId('checkout-ending-code')).toHaveTextContent(
+ 'op_r'
+ )
+ })
+
+ it('390-4947: a top-up still adding its credits names no plan', () => {
+ renderEnding({
+ kind: 'received',
+ code: 'op_r',
+ receipt: { amountChargedCents: 2500 }
+ })
+
+ expect(screen.getByTestId('checkout-ending-receipt')).toHaveTextContent(
+ 'Payment$25.00Credits addedAdding…'
+ )
+ expect(screen.queryByText('Plan')).not.toBeInTheDocument()
+ })
+
+ it('keeps Payment received card-less while the charge is not confirmed', () => {
+ renderEnding({ kind: 'received', code: 'op_r' })
+
+ expect(
+ screen.queryByTestId('checkout-ending-receipt')
+ ).not.toBeInTheDocument()
+ })
})
it.for<{ ending: EndingScreen; action: Action; event: string }>([
diff --git a/apps/billing-web/src/components/fullPage/CheckoutEnding.vue b/apps/billing-web/src/components/fullPage/CheckoutEnding.vue
index 22801d95d60..db82f860c75 100644
--- a/apps/billing-web/src/components/fullPage/CheckoutEnding.vue
+++ b/apps/billing-web/src/components/fullPage/CheckoutEnding.vue
@@ -2,23 +2,26 @@
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
+import { formatQuoteMoney } from '@comfyorg/account-ui/billing/checkout'
import { buttonVariants } from '@comfyorg/design-system/button.variants'
import { cn } from '@comfyorg/tailwind-utils'
-import type { EndingKind, EndingScreen } from '@/checkout/endingScreen'
+import type {
+ EndingKind,
+ EndingScreen,
+ ReceiptRow
+} from '@/checkout/endingScreen'
+import { endingReceipt } from '@/checkout/endingScreen'
import { longDate } from '@/checkout/longDate'
import { supportLinkWithCode } from '@/checkout/payVerdict'
+import type { SuccessBreakdown } from '@/checkout/successBreakdown'
import { namedPlan } from '@/checkout/summaryLedger'
import EndingCodeCard from '@/components/fullPage/EndingCodeCard.vue'
+import type { EndingPlan } from '@/components/fullPage/EndingPlanCard.vue'
+import EndingPlanCard from '@/components/fullPage/EndingPlanCard.vue'
import SuccessCloseFooter from '@/components/fullPage/SuccessCloseFooter.vue'
import { useHostedCopy } from '@/composables/useHostedCopy'
-export interface EndingPlan {
- readonly name: string
- readonly price: string
- readonly period: string
-}
-
type Tone = 'done' | 'waiting' | 'refused'
/**
@@ -57,11 +60,13 @@ const {
screen,
workspace,
plan,
+ breakdown,
closesItself = false
} = defineProps<{
screen: EndingScreen
workspace: string
plan?: EndingPlan
+ breakdown?: SuccessBreakdown
closesItself?: boolean
}>()
@@ -92,6 +97,47 @@ const bodyParams = computed(() =>
: { workspace }
)
const code = computed(() => ('code' in screen ? screen.code : undefined))
+const receipt = computed(() => endingReceipt(screen))
+/** A plan card stands in for the reference; without the plan's listing the code stays. */
+const planCard = computed(() => (receipt.value.namesPlan ? plan : undefined))
+const showsCode = computed(
+ () =>
+ code.value !== undefined &&
+ planCard.value === undefined &&
+ !receipt.value.rowsReplaceCode
+)
+const creditsAdded = computed(() =>
+ 'receipt' in screen ? screen.receipt?.creditsAdded : undefined
+)
+
+const R = 'checkout.fullPage.ending.receipt'
+const credits = (count: number) =>
+ new Intl.NumberFormat(locale.value).format(count)
+const money = (cents: number) => formatQuoteMoney(cents, 'usd', locale.value)
+
+/** Each row the receipt shows, as label and value; a plan row needs the plan's name. */
+const receiptRows = computed(() =>
+ receipt.value.rows.flatMap((row) => {
+ const value = rowValue(row)
+ return value === undefined
+ ? []
+ : [{ kind: row.kind, label: t(`${R}.${row.kind}`), value }]
+ })
+)
+
+function rowValue(row: ReceiptRow): string | undefined {
+ switch (row.kind) {
+ case 'payment':
+ case 'amount_paid':
+ return money(row.cents)
+ case 'adding':
+ return t(`${R}.addingValue`)
+ case 'added':
+ return t(`${R}.creditCount`, { count: credits(row.credits) })
+ case 'plan':
+ return plan?.name
+ }
+}
const supportLink = computed(() => supportLinkWithCode(code.value))
const primary = computed(() => ending.value.primary)
@@ -134,22 +180,32 @@ function act() {
-
+
+
-
- {{ plan.name }}
-
-
- {{ plan.price }}
- {{ plan.period }}
-
-
+
+
- {{ row.label }}
+ -
+ {{ row.value }}
+
+
+
diff --git a/apps/billing-web/src/components/fullPage/CheckoutSummaryColumn.test.ts b/apps/billing-web/src/components/fullPage/CheckoutSummaryColumn.test.ts
index fad9ede3df2..032b2cd155c 100644
--- a/apps/billing-web/src/components/fullPage/CheckoutSummaryColumn.test.ts
+++ b/apps/billing-web/src/components/fullPage/CheckoutSummaryColumn.test.ts
@@ -194,3 +194,115 @@ describe('CheckoutSummaryColumn discount rows', () => {
expect(warn).not.toHaveBeenCalled()
})
})
+
+describe('CheckoutSummaryColumn server-reported rows', () => {
+ function inPageOrder(nodes: Element[]): string[] {
+ return nodes
+ .sort((a, b) =>
+ a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
+ )
+ .map((node) => (node.tagName === 'HR' ? '---' : node.textContent.trim()))
+ }
+
+ it('strikes through only the list price of a discounted rate', () => {
+ renderColumn({
+ ...UPGRADE,
+ items: [
+ {
+ label: 'Team Plan',
+ amount: '$7,560.00',
+ comparedRate: {
+ keypath: 'checkout.fullPage.summary.item.comparedYearly',
+ amount: '$7,560',
+ listAmount: '$8,400'
+ },
+ sublines: []
+ }
+ ]
+ })
+
+ expect(screen.getByText('$8,400').tagName).toBe('S')
+ expect(
+ screen.getByText(
+ (_, element) =>
+ element?.tagName === 'SPAN' &&
+ element.textContent.trim() === '$7,560 $8,400 /yr, billed yearly'
+ )
+ ).toBeInTheDocument()
+ expect(screen.getByText('$7,560.00').tagName).not.toBe('S')
+ })
+
+ it('bounds a discount by its term under its label', () => {
+ renderColumn({
+ ...UPGRADE,
+ items: [UPGRADE.items[0]],
+ discounts: [
+ { label: 'Promo code', amount: '−$1,512.00', subline: 'First year' }
+ ]
+ })
+
+ expect(
+ inPageOrder([
+ screen.getByText('First year'),
+ screen.getByText('Promo code'),
+ screen.getByText('Total due today')
+ ])
+ ).toEqual(['Promo code', 'First year', 'Total due today'])
+ })
+
+ it('divides a Subtotal off the money rows, then lists the discount and last the account balance', () => {
+ renderColumn({
+ ...UPGRADE,
+ subtotal: '$32.50',
+ discounts: [{ label: 'Promo code', amount: '−$10.00' }],
+ balance: {
+ label: 'Account balance',
+ amount: '−$5.00',
+ subline: 'Credit already on your account'
+ },
+ total: '$17.50'
+ })
+
+ const labels = [
+ 'Unused time from Creator plan',
+ 'Subtotal',
+ 'Promo code',
+ '−$10.00',
+ 'Account balance',
+ '−$5.00',
+ 'Credit already on your account',
+ 'Total due today'
+ ]
+ const outline = inPageOrder([
+ ...screen.getAllByRole('separator'),
+ ...labels.map((text) => screen.getByText(text))
+ ])
+ expect(outline).toEqual([
+ '---',
+ 'Unused time from Creator plan',
+ '---',
+ 'Subtotal',
+ 'Promo code',
+ '−$10.00',
+ 'Account balance',
+ '−$5.00',
+ 'Credit already on your account',
+ '---',
+ 'Total due today'
+ ])
+ expect(
+ screen.getByText(
+ (_, element) =>
+ element?.tagName === 'DIV' &&
+ element.textContent.replace(/\s/g, '') === 'Subtotal$32.50'
+ )
+ ).toBeInTheDocument()
+ })
+
+ it('lists no Subtotal and no balance row when the ledger has neither', () => {
+ renderColumn(UPGRADE)
+
+ expect(screen.queryByText('Subtotal')).not.toBeInTheDocument()
+ expect(screen.queryByText('Account balance')).not.toBeInTheDocument()
+ })
+})
diff --git a/apps/billing-web/src/components/fullPage/EndingPlanCard.vue b/apps/billing-web/src/components/fullPage/EndingPlanCard.vue
new file mode 100644
index 00000000000..926a5d5eb56
--- /dev/null
+++ b/apps/billing-web/src/components/fullPage/EndingPlanCard.vue
@@ -0,0 +1,66 @@
+
+
+
+
+
+ {{ plan.name }}
+
+
+ {{ plan.price }}
+ {{ plan.period }}
+
+
+
+
+ {{
+ t('checkout.fullPage.ending.receipt.creditsAddedLine', {
+ count: credits(creditsAdded)
+ })
+ }}
+
+
+
+
+
+
+
+
diff --git a/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue b/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue
index 0b44edab30f..b421aa37a9e 100644
--- a/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue
+++ b/apps/billing-web/src/components/fullPage/summary/CheckoutLedger.vue
@@ -2,6 +2,7 @@
import { useI18n } from 'vue-i18n'
import type { SummaryLedger } from '@/checkout/summaryLedger'
+import LedgerRows from '@/components/fullPage/summary/LedgerRows.vue'
const { ledger } = defineProps<{ ledger: SummaryLedger }>()
@@ -32,44 +33,7 @@ const { t } = useI18n()
-
-
-
-
+
diff --git a/apps/billing-web/src/components/fullPage/summary/LedgerDeduction.vue b/apps/billing-web/src/components/fullPage/summary/LedgerDeduction.vue
new file mode 100644
index 00000000000..b3870b4957b
--- /dev/null
+++ b/apps/billing-web/src/components/fullPage/summary/LedgerDeduction.vue
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+ {{ row.label }}
+
+
+ {{ row.amount }}
+
+
+
+ {{ row.subline }}
+
+
+
diff --git a/apps/billing-web/src/components/fullPage/summary/LedgerItem.vue b/apps/billing-web/src/components/fullPage/summary/LedgerItem.vue
new file mode 100644
index 00000000000..20c205294e7
--- /dev/null
+++ b/apps/billing-web/src/components/fullPage/summary/LedgerItem.vue
@@ -0,0 +1,36 @@
+
+
+
+
+
+
+ {{ row.label }}
+
+
+ {{ row.amount }}
+
+
+
+ {{ row.comparedRate.amount }}
+
+ {{ row.comparedRate.listAmount }}
+
+
+
+ {{ subline }}
+
+
+
diff --git a/apps/billing-web/src/components/fullPage/summary/LedgerRows.vue b/apps/billing-web/src/components/fullPage/summary/LedgerRows.vue
new file mode 100644
index 00000000000..98ef2dbc6bb
--- /dev/null
+++ b/apps/billing-web/src/components/fullPage/summary/LedgerRows.vue
@@ -0,0 +1,66 @@
+
+
+
+
+
+
+
+
+
+ {{ t('checkout.fullPage.summary.subtotal') }}
+ {{ ledger.subtotal }}
+
+
+
+
+
diff --git a/apps/billing-web/src/composables/useFullPageCheckout.ts b/apps/billing-web/src/composables/useFullPageCheckout.ts
index 873bc052373..69e9e204462 100644
--- a/apps/billing-web/src/composables/useFullPageCheckout.ts
+++ b/apps/billing-web/src/composables/useFullPageCheckout.ts
@@ -31,11 +31,13 @@ import type {
import {
RESOLVING,
UNREADABLE_LINK,
+ awaitingServer,
challengeToReopen,
isParked,
needsConsent,
railAcceptsPay,
- reduceCheckoutPage
+ reduceCheckoutPage,
+ settledPlanSource
} from '@/checkout/checkoutPage'
import { planCreditsSettingsUrl, pricingTableUrl } from '@/checkout/cloudLinks'
import { createOperationChannel } from '@/checkout/operationChannel'
@@ -458,25 +460,31 @@ export function useFullPageCheckout() {
}
/**
- * "We couldn't confirm your payment" promises to update on its own, but the
- * lifecycle stops polling an operation the server parked for a human. The
- * page re-reads it on the parked cadence until it settles either way.
+ * "We couldn't confirm your payment" and "Payment received" promise to
+ * update on their own, but the lifecycle stops polling an operation the
+ * server parked for a human or already settled. The page re-reads it on the
+ * parked cadence until the verdict, or the credits, arrive.
*/
- const recheckUnconfirmed = useIntervalFn(
+ const recheck = useIntervalFn(
() => void reconcile(),
OPERATION_POLL_TIMING.parkedMs,
{ immediate: false }
)
watch(
- () => page.value.kind === 'unconfirmed',
- (unconfirmed) =>
- unconfirmed ? recheckUnconfirmed.resume() : recheckUnconfirmed.pause()
+ () => awaitingServer(page.value),
+ (awaiting) => (awaiting ? recheck.resume() : recheck.pause())
)
- /** A returned payment names the plan the server now lists, never the fresh quote. */
- async function readSettledPlan() {
- const [read, catalog] = await Promise.all([status.read(), plans.read()])
- const slug = read.status === 'ok' ? read.value.status.plan_slug : undefined
+ /**
+ * A settled payment this page did not price names the plan the catalog
+ * lists for its receipt, or for a returned one without a receipt plan, the
+ * plan the status now reports; never the fresh quote.
+ */
+ async function readSettledPlan(receiptSlug: string | undefined) {
+ const [slug, catalog] = await Promise.all([
+ receiptSlug ?? statusPlanSlug(),
+ plans.read()
+ ])
const listed =
slug !== undefined && catalog.status === 'ok'
? catalog.value.data.plans.find((plan) => plan.slug === slug)
@@ -489,6 +497,11 @@ export function useFullPageCheckout() {
})
}
+ async function statusPlanSlug() {
+ const read = await status.read()
+ return read.status === 'ok' ? read.value.status.plan_slug : undefined
+ }
+
/** A finished checkout has no code left to re-apply. */
watch(
() => page.value.kind === 'terminal',
@@ -498,10 +511,10 @@ export function useFullPageCheckout() {
)
watch(
- () =>
- page.value.kind === 'terminal' && page.value.attribution === 'returned',
- (returned) => {
- if (returned) void readSettledPlan()
+ () => settledPlanSource(page.value)?.key,
+ () => {
+ const source = settledPlanSource(page.value)
+ if (source !== undefined) void readSettledPlan(source.receiptSlug)
}
)
diff --git a/apps/billing-web/src/locales/en/main.json b/apps/billing-web/src/locales/en/main.json
index 21bd36fe129..ad72aaa6cf1 100644
--- a/apps/billing-web/src/locales/en/main.json
+++ b/apps/billing-web/src/locales/en/main.json
@@ -271,6 +271,18 @@
"closeTab": "You can close this tab now.",
"closingIn": "Closing in {seconds}…",
"closeLine": "You can close this page. We'll email your invoice once this goes through and this page will automatically update.",
+ "receipt": {
+ "payment": "Payment",
+ "adding": "Credits added",
+ "plan": "Plan",
+ "added": "Added",
+ "amount_paid": "Amount paid",
+ "addingValue": "Adding…",
+ "creditCount": "+{count}",
+ "creditsAddedLine": "{count} credits added",
+ "paidToday": "Paid today",
+ "prorated": "Prorated for the rest of this billing period"
+ },
"actions": {
"close": "Close",
"retry": "Try again",
@@ -336,6 +348,11 @@
},
"summary": {
"label": "Order summary",
+ "subtotal": "Subtotal",
+ "balance": {
+ "label": "Account balance",
+ "subline": "Credit already on your account"
+ },
"verb": {
"subscribe": "Subscribe to {plan}",
"upgrade": "Upgrade to {plan}",
@@ -371,11 +388,16 @@
"refillsMonthly": "Credits refill to {credits} each month",
"refillsYearly": "Credits refill to {credits} each year",
"startsMonthly": "Starts {date}, billed monthly",
- "startsYearly": "Starts {date}, billed yearly"
+ "startsYearly": "Starts {date}, billed yearly",
+ "comparedMonthly": "{amount} {listAmount} /mo, billed monthly",
+ "comparedYearly": "{amount} {listAmount} /yr, billed yearly"
},
"discount": {
"fallbackLabel": "Promo code",
- "amount": "−{amount}"
+ "amount": "−{amount}",
+ "firstMonth": "First month",
+ "firstYear": "First year",
+ "forMonths": "For {count} month | For {count} months"
},
"promo": {
"add": "Add promo code",
diff --git a/apps/billing-web/src/views/FullPageCheckoutView.test.ts b/apps/billing-web/src/views/FullPageCheckoutView.test.ts
index d1616caba68..84be320f07a 100644
--- a/apps/billing-web/src/views/FullPageCheckoutView.test.ts
+++ b/apps/billing-web/src/views/FullPageCheckoutView.test.ts
@@ -4,6 +4,7 @@ import { nextTick, ref } from 'vue'
import type { VNode } from 'vue'
import type {
+ BillingOperationReceipt,
BillingOperationState,
BillingResult,
PendingBillingOperation,
@@ -1930,6 +1931,76 @@ describe("FullPageCheckoutView over this tab's own payment", () => {
)
expect(fake.subscribe).not.toHaveBeenCalled()
})
+
+ const RECEIPT_PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+ const withReceipt = (
+ operation: BillingOperationState,
+ receipt: BillingOperationReceipt
+ ): BillingOperationState => ({ ...operation, phase: 'succeeded', receipt })
+
+ it('328-4444: Already completed names the plan and credits its receipt reports, from the catalog', async () => {
+ await renderCheckout({
+ plans: ON_PRO.plans,
+ recover: {
+ status: 'ok',
+ value: withReceipt(succeededOperation('op_done'), {
+ plan: RECEIPT_PLAN,
+ creditsAdded: 10_000
+ })
+ },
+ preview: { status: 'ok', value: previewOf({ allowed: false }) }
+ })
+
+ expect(
+ await screen.findByRole('heading', { name: 'Already completed' })
+ ).toBeInTheDocument()
+ const plan = await screen.findByTestId('checkout-ending-plan')
+ expect(plan).toHaveTextContent('Pro$50.00 USD / mo10,000 credits added')
+ expect(screen.queryByTestId('checkout-ending-code')).not.toBeInTheDocument()
+ })
+
+ it('390-4947: shows Payment received while its credits land, and Success once a re-read reports them', async () => {
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] })
+ const landing = withReceipt(awaited(succeededOperation('op_mine')), {
+ amountChargedCents: 5000,
+ plan: RECEIPT_PLAN
+ })
+ const fake = await renderCheckout({
+ ...ON_PRO,
+ recover: { status: 'ok', value: landing },
+ preview: { status: 'ok', value: previewOf({ allowed: false }) }
+ })
+
+ expect(
+ await screen.findByRole('heading', { name: 'Payment received' })
+ ).toBeInTheDocument()
+ await waitFor(() =>
+ expect(screen.getByTestId('checkout-ending-receipt')).toHaveTextContent(
+ 'Payment$50.00Credits addedAdding…PlanPro'
+ )
+ )
+
+ const landed = withReceipt(landing, {
+ amountChargedCents: 5000,
+ creditsAdded: 10_000,
+ plan: RECEIPT_PLAN
+ })
+ fake.recover.mockImplementation(async () => ({
+ status: 'ok',
+ value: landed
+ }))
+ vi.advanceTimersByTime(OPERATION_POLL_TIMING.parkedMs)
+
+ expect(
+ await screen.findByRole('heading', { name: "You're all set" })
+ ).toBeInTheDocument()
+ expect(await screen.findByTestId('checkout-ending-plan')).toHaveTextContent(
+ '10,000 credits added'
+ )
+ const reads = fake.recover.mock.calls.length
+ vi.advanceTimersByTime(OPERATION_POLL_TIMING.parkedMs * 3)
+ expect(fake.recover).toHaveBeenCalledTimes(reads)
+ })
})
const challengedOperation = (
diff --git a/apps/billing-web/src/views/FullPageCheckoutView.vue b/apps/billing-web/src/views/FullPageCheckoutView.vue
index 6a27bd3295c..61cb0c49c92 100644
--- a/apps/billing-web/src/views/FullPageCheckoutView.vue
+++ b/apps/billing-web/src/views/FullPageCheckoutView.vue
@@ -14,10 +14,12 @@ import {
submitPhaseOf
} from '@/checkout/checkoutPage'
import { endingOf } from '@/checkout/endingScreen'
-import type { EndingPlan } from '@/components/fullPage/CheckoutEnding.vue'
+import type { EndingPlan } from '@/components/fullPage/EndingPlanCard.vue'
import CheckoutEnding from '@/components/fullPage/CheckoutEnding.vue'
import type { CheckoutCharge } from '@/components/fullPage/CheckoutPaymentColumn.vue'
import CheckoutPaymentColumn from '@/components/fullPage/CheckoutPaymentColumn.vue'
+import { successBreakdown } from '@/checkout/successBreakdown'
+import type { LedgerContext } from '@/checkout/summaryLedger'
import { buildSummaryLedger } from '@/checkout/summaryLedger'
import CheckoutSummaryColumn from '@/components/fullPage/CheckoutSummaryColumn.vue'
import { keepSubscriptionCopy } from '@/checkout/keepSubscription'
@@ -80,15 +82,17 @@ const quote = computed(() =>
: undefined
)
+const ledgerContext = computed
(() => ({
+ workspace: session.value?.workspace.name,
+ tierName: (tier) => coded('tier', tier),
+ t,
+ locale: locale.value
+}))
+
const ledger = computed(() => {
const quoted = quote.value
if (!quoted) return undefined
- return buildSummaryLedger(quoted, {
- workspace: session.value?.workspace.name,
- tierName: (tier) => coded('tier', tier),
- t,
- locale: locale.value
- })
+ return buildSummaryLedger(quoted, ledgerContext.value)
})
const charge = computed(() => {
@@ -113,18 +117,22 @@ const keepSubscription = computed(() => {
const ending = computed(() => endingOf(page.value))
+const breakdown = computed(() =>
+ successBreakdown(page.value, preview.value, ledgerContext.value)
+)
+
const locked = computed(() => isLocked(page.value))
/** The server cannot cancel a pending payment yet; the click has nowhere honest to go. */
function cancelPayment() {}
/**
- * The plan this page's own Pay bought: as its quote priced it, or, once a
- * reload or a provider's page took that quote away, as the server now lists it.
+ * The plan a settled payment bought: as this page's own quote priced it, or,
+ * for any payment it did not price here, as the server's catalog lists it.
*/
const boughtPlan = computed(() => {
const current = page.value
- if (current.kind === 'terminal' && current.attribution === 'returned')
+ if (current.kind === 'terminal' && current.attribution !== 'started')
return current.plan && { ...current.plan, currency: 'usd' }
const quoted = preview.value
return quoted && { ...quoted.new_plan, currency: quoted.currency ?? 'usd' }
@@ -166,6 +174,7 @@ function viewPlans() {
session?.workspace.name ?? t('checkout.fullPage.ending.thisWorkspace')
"
:plan="endingPlan"
+ :breakdown
:closes-itself="openedByScript"
@close="close"
@retry="retryLoad"
diff --git a/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts b/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts
index f09bac0f6b1..8b7c5873dae 100644
--- a/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts
+++ b/packages/account-core/src/core/billing/contracts/previewSubscribe.contract.test.ts
@@ -61,7 +61,9 @@ const MONEY_FIELDS = [
'cost_today_cents',
'credits_next_period_cents',
'credits_today_cents',
- 'renewal_amount_cents'
+ 'renewal_amount_cents',
+ 'subtotal_cents',
+ 'balance_applied_cents'
] as const satisfies readonly (keyof PreviewResponseBody)[]
const INT64_MIN = -9223372036854775808n
diff --git a/packages/account-core/src/core/billing/index.ts b/packages/account-core/src/core/billing/index.ts
index 2db4fb52a8c..29aa90a4271 100644
--- a/packages/account-core/src/core/billing/index.ts
+++ b/packages/account-core/src/core/billing/index.ts
@@ -110,6 +110,7 @@ export type {
BillingOpStatus,
BillingOperationEvent,
BillingOperationIdentity,
+ BillingOperationReceipt,
BillingOperationKind,
BillingOperationPhase,
BillingOperationServerPhase,
@@ -120,10 +121,12 @@ export type {
EmbeddedChallenge,
FailedBillingOperation,
HostedBillingDestination,
- PendingBillingOperation
+ PendingBillingOperation,
+ SucceededBillingOperation
} from './operationState.js'
export {
isBlockedOnCustomerPhase,
+ isGrantLanding,
isTerminal,
reduceBillingOperation,
validateActionUrl
diff --git a/packages/account-core/src/core/billing/operationLifecycle.test.ts b/packages/account-core/src/core/billing/operationLifecycle.test.ts
index a2c5326abdd..8c5452aa1c8 100644
--- a/packages/account-core/src/core/billing/operationLifecycle.test.ts
+++ b/packages/account-core/src/core/billing/operationLifecycle.test.ts
@@ -1115,6 +1115,95 @@ describe('createBillingOperationLifecycle', () => {
)
})
+ const RECEIPT_PLAN = { slug: 'pro_monthly', duration: 'MONTHLY' } as const
+
+ it('keeps the receipt a succeeded operation reports', async () => {
+ const { lifecycle } = harness({
+ answers: [
+ httpOk(
+ opStatus({
+ status: 'succeeded',
+ amount_charged_cents: 3250,
+ credits_added: 6858,
+ plan: RECEIPT_PLAN
+ })
+ )
+ ]
+ })
+ await lifecycle.begin('subscription', issued())
+ await flush()
+
+ expect(lifecycle.get('op-1')).toMatchObject({
+ phase: 'succeeded',
+ receipt: {
+ amountChargedCents: 3250,
+ creditsAdded: 6858,
+ plan: RECEIPT_PLAN
+ }
+ })
+ })
+
+ it('leaves the receipt off a success that reported none', async () => {
+ const { lifecycle } = harness({
+ answers: [httpOk(opStatus({ status: 'succeeded' }))]
+ })
+ await lifecycle.begin('subscription', issued())
+ await flush()
+
+ expect(lifecycle.get('op-1')).not.toHaveProperty('receipt')
+ })
+
+ it('re-reads a success whose credits are still landing, when asked for settled operations', async () => {
+ const charged = {
+ status: 'succeeded' as const,
+ amount_charged_cents: 3250
+ }
+ const { lifecycle } = harness({
+ retainSettled: true,
+ answers: [
+ httpOk(opStatus(charged)),
+ httpOk(opStatus({ ...charged, credits_added: 6858 }))
+ ]
+ })
+ await lifecycle.begin('subscription', issued())
+ await flush()
+ expect(lifecycle.get('op-1')).toMatchObject({
+ receipt: { amountChargedCents: 3250 }
+ })
+
+ await expect(
+ lifecycle.recover({ includeSettled: true })
+ ).resolves.toMatchObject({
+ status: 'ok',
+ value: {
+ phase: 'succeeded',
+ receipt: { amountChargedCents: 3250, creditsAdded: 6858 }
+ }
+ })
+ })
+
+ it('keeps a success whose credits already landed as it was', async () => {
+ const landed = {
+ status: 'succeeded' as const,
+ amount_charged_cents: 3250,
+ credits_added: 6858
+ }
+ const { lifecycle } = harness({
+ retainSettled: true,
+ answers: [
+ httpOk(opStatus(landed)),
+ httpOk(opStatus({ ...landed, credits_added: 1 }))
+ ]
+ })
+ await lifecycle.begin('subscription', issued())
+ await flush()
+ const settled = lifecycle.get('op-1')
+
+ await lifecycle.recover({ includeSettled: true })
+
+ expect(lifecycle.get('op-1')).toBe(settled)
+ })
+
it('re-reads an operation that needed reconciliation, following it forward to success', async () => {
const storage = memoryStorage()
const { lifecycle, calls } = harness({
diff --git a/packages/account-core/src/core/billing/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts
index f43f1405c98..27323ac6b12 100644
--- a/packages/account-core/src/core/billing/operationLifecycle.ts
+++ b/packages/account-core/src/core/billing/operationLifecycle.ts
@@ -16,7 +16,6 @@
* wiring onto the scope source, the scope tracker, and the generated
* contract is new.
*/
-import { zBillingOpStatusResponse } from '@comfyorg/ingest-types/zod'
import { BILLING_OPERATION_TELEMETRY_EVENT } from '../../telemetry.js'
import type {
@@ -56,6 +55,8 @@ import type {
PendingBillingOperation
} from './operationState.js'
import {
+ BillingOpStatusSchema,
+ isGrantLanding,
isTerminal,
reduceBillingOperation,
validateActionUrl
@@ -64,6 +65,11 @@ import { selectBillingPresentation } from './presentation.js'
import { readValidatedBillingResponse } from './sharedRead.js'
import type { BillingStatusData, BillingStatusReader } from './status.js'
+/** Settled, but a later read may still change what the operation reports. */
+function isStillSettling(state: BillingOperationState): boolean {
+ return state.phase === 'reconciliation_needed' || isGrantLanding(state)
+}
+
export function operationRoute(operationId: string): string {
return `/billing/ops/${encodeURIComponent(operationId)}`
}
@@ -444,7 +450,7 @@ export function createBillingOperationLifecycle(
return readValidatedBillingResponse(
transport,
{ method: 'GET', route: operationRoute(operationId) },
- (body) => zBillingOpStatusResponse.safeParse(body)
+ (body) => BillingOpStatusSchema.safeParse(body)
)
}
@@ -515,8 +521,9 @@ export function createBillingOperationLifecycle(
/**
* An id is observed afresh once this tab has stopped learning anything new
* about it: its poll budget ran out or it left the scope. One the server
- * parked for reconciliation is observed afresh only for a caller reading
- * settled operations, since the reconciliation may since have settled it.
+ * parked for reconciliation, or a success whose credits were still landing,
+ * is observed afresh only for a caller reading settled operations, since
+ * the server may since have settled it or recorded the grant.
*/
function adopt(input: AdoptInput, includeSettled = false): OperationRecord {
const existing = operations.get(input.id)
@@ -524,7 +531,7 @@ export function createBillingOperationLifecycle(
existing !== undefined &&
existing.state.phase !== 'timed_out' &&
existing.state.phase !== 'superseded' &&
- !(includeSettled && existing.state.phase === 'reconciliation_needed')
+ !(includeSettled && isStillSettling(existing.state))
) {
return existing
}
diff --git a/packages/account-core/src/core/billing/operationState.ts b/packages/account-core/src/core/billing/operationState.ts
index cd5d2e3e1ac..02e2ceeb900 100644
--- a/packages/account-core/src/core/billing/operationState.ts
+++ b/packages/account-core/src/core/billing/operationState.ts
@@ -11,12 +11,18 @@
* so no server or payment-provider text can reach a consumer through this
* state.
*/
-import type { zBillingOpStatusResponse } from '@comfyorg/ingest-types/zod'
+import { zBillingOpStatusResponse } from '@comfyorg/ingest-types/zod'
import type { z } from 'zod'
import type { BillingScope } from './billingScope.js'
+import { wireCents } from './wireCents.js'
-export type BillingOpStatus = z.infer
+export const BillingOpStatusSchema = zBillingOpStatusResponse.extend({
+ amount_charged_cents: wireCents.optional(),
+ credits_added: wireCents.optional()
+})
+
+export type BillingOpStatus = z.infer
export type BillingOperationKind = 'subscription' | 'topup' | 'cancel'
@@ -113,9 +119,26 @@ export type FailedBillingOperation = BillingOperationIdentity & {
readonly retryable: boolean
}
+/**
+ * What the server reports a succeeded operation did, for display only. Each
+ * fact is absent while the server cannot say it: a charge billed outside a
+ * Stripe invoice, a grant not recorded yet, or an operation that is not a
+ * plan change.
+ */
+export interface BillingOperationReceipt {
+ readonly amountChargedCents?: number
+ readonly creditsAdded?: number
+ readonly plan?: NonNullable
+}
+
+export type SucceededBillingOperation = BillingOperationIdentity & {
+ readonly phase: 'succeeded'
+ readonly receipt?: BillingOperationReceipt
+}
+
export type BillingOperationState =
| PendingBillingOperation
- | (BillingOperationIdentity & { readonly phase: 'succeeded' })
+ | SucceededBillingOperation
| FailedBillingOperation
/** This tab's poll budget ran out; the server may still settle the operation. */
| (BillingOperationIdentity & { readonly phase: 'timed_out' })
@@ -236,7 +259,7 @@ function terminalFromStatus(
state: PendingBillingOperation,
status: BillingOpStatus
): BillingOperationState | undefined {
- if (status.status === 'succeeded') return withPhase(state, 'succeeded')
+ if (status.status === 'succeeded') return succeeded(state, status)
if (status.status === 'failed') {
return {
...identityOf(state),
@@ -257,6 +280,44 @@ function terminalFromStatus(
return undefined
}
+function receiptOf(
+ status: BillingOpStatus
+): BillingOperationReceipt | undefined {
+ const receipt: BillingOperationReceipt = {
+ ...(status.amount_charged_cents === undefined
+ ? {}
+ : { amountChargedCents: status.amount_charged_cents }),
+ ...(status.credits_added === undefined
+ ? {}
+ : { creditsAdded: status.credits_added }),
+ ...(status.plan === undefined ? {} : { plan: status.plan })
+ }
+ return Object.keys(receipt).length === 0 ? undefined : receipt
+}
+
+function succeeded(
+ state: BillingOperationState,
+ status: BillingOpStatus
+): SucceededBillingOperation {
+ const receipt = receiptOf(status)
+ return {
+ ...withPhase(state, 'succeeded'),
+ ...(receipt === undefined ? {} : { receipt })
+ }
+}
+
+/**
+ * The charge went through and the server has not recorded its credits yet;
+ * reading the operation again fills them in.
+ */
+export function isGrantLanding(state: BillingOperationState): boolean {
+ return (
+ state.phase === 'succeeded' &&
+ state.receipt?.amountChargedCents !== undefined &&
+ state.receipt.creditsAdded === undefined
+ )
+}
+
/**
* A link echoed while this tab's completed challenge is still processing
* points at that same challenge; surfacing it would ask the customer to
diff --git a/packages/account-core/src/core/billing/subscriptionCommands.test.ts b/packages/account-core/src/core/billing/subscriptionCommands.test.ts
index 271138cdc2e..932294f8d4c 100644
--- a/packages/account-core/src/core/billing/subscriptionCommands.test.ts
+++ b/packages/account-core/src/core/billing/subscriptionCommands.test.ts
@@ -697,6 +697,50 @@ describe('createBillingCommands', () => {
})
})
+ it('hands back the server-reported subtotal, list price, discount term and applied balance as numbers', async () => {
+ const itemized = http(200, {
+ ...QUOTE_BODY,
+ subtotal_cents: 2000,
+ balance_applied_cents: 300,
+ new_plan: { ...PREVIEW_PLAN, list_price_cents: 2500 },
+ discounts: [
+ {
+ amount_off_cents: 500,
+ code: 'LAUNCH',
+ kind: 'promotion',
+ duration: 'repeating',
+ duration_in_months: 3
+ }
+ ]
+ })
+ const h = harness({
+ status: FREE,
+ script: { [POST_PREVIEW]: [itemized] }
+ })
+
+ const result = await h.commands.previewSubscribe({
+ planSlug: 'pro-monthly'
+ })
+
+ expect(result).toEqual({
+ status: 'ok',
+ value: expect.objectContaining({
+ subtotal_cents: 2000,
+ balance_applied_cents: 300,
+ new_plan: expect.objectContaining({ list_price_cents: 2500 }),
+ discounts: [
+ {
+ amount_off_cents: 500,
+ code: 'LAUNCH',
+ kind: 'promotion',
+ duration: 'repeating',
+ duration_in_months: 3
+ }
+ ]
+ })
+ })
+ })
+
it('omits the optional fields the caller left out, issuing no operation', async () => {
const h = harness({ status: FREE, script: { [POST_PREVIEW]: [quote] } })
@@ -784,12 +828,15 @@ describe('createBillingCommands', () => {
'cost_today_cents',
'credits_next_period_cents',
'credits_today_cents',
- 'renewal_amount_cents'
+ 'renewal_amount_cents',
+ 'subtotal_cents',
+ 'balance_applied_cents'
] as const satisfies readonly (keyof SubscriptionPreview)[]
const PLAN_CENT_FIELDS = [
'credits_cents',
- 'price_cents'
+ 'price_cents',
+ 'list_price_cents'
] as const satisfies readonly (keyof SubscriptionPreview['new_plan'])[]
const SEAT_CENT_FIELDS = [
@@ -800,7 +847,8 @@ describe('createBillingCommands', () => {
type PreviewDiscount = NonNullable[number]
const DISCOUNT_CENT_FIELDS = [
- 'amount_off_cents'
+ 'amount_off_cents',
+ 'duration_in_months'
] as const satisfies readonly (keyof PreviewDiscount)[]
// Compile-time pins: an amount a regen adds fails the package typecheck
@@ -818,7 +866,7 @@ describe('createBillingCommands', () => {
>
>()
expectTypeOf<(typeof DISCOUNT_CENT_FIELDS)[number]>().toEqualTypeOf<
- Extract
+ Extract
>()
const rejectsQuote = async (patch: object) => {
diff --git a/packages/account-core/src/core/billing/subscriptionCommands.ts b/packages/account-core/src/core/billing/subscriptionCommands.ts
index 70fd4c48b08..e742dd20ac3 100644
--- a/packages/account-core/src/core/billing/subscriptionCommands.ts
+++ b/packages/account-core/src/core/billing/subscriptionCommands.ts
@@ -40,6 +40,7 @@ import type {
import { validateActionUrl } from './operationState.js'
import { readValidatedBillingResponse } from './sharedRead.js'
import type { BillingStatusReader } from './status.js'
+import { wireCents } from './wireCents.js'
export const SUBSCRIBE_ROUTE = '/billing/subscribe'
export const RESUBSCRIBE_ROUTE = '/billing/subscription/resubscribe'
@@ -111,37 +112,34 @@ export type PaymentPortalResult =
| { readonly status: 'ok'; readonly value: { readonly url: string } }
| BillingFailure
-/**
- * The generated schema coerces every int64 to a `bigint`, which no caller can
- * add to a price or hand to a currency formatter — and the generated *type*
- * for the same field is a `number`. Money on this route is bounded to cents
- * well inside the JavaScript-safe range, so the cents are read as numbers, the
- * way `capabilities` reads `revision` — as whole units of currency that
- * survive arithmetic, since these amounts are displayed as prices and
- * confirmed as charges.
- */
-const cents = z.number().int().safe()
-
const PlanInfoSchema = zPreviewPlanInfo.extend({
- credits_cents: cents,
- price_cents: cents,
+ credits_cents: wireCents,
+ price_cents: wireCents,
+ list_price_cents: wireCents.optional(),
seat_summary: zPreviewPlanInfo.shape.seat_summary.extend({
- total_cost_cents: cents,
- total_credits_cents: cents
+ total_cost_cents: wireCents,
+ total_credits_cents: wireCents
})
})
const PreviewSchema = zPreviewSubscribeResponse.extend({
- amount_due_cents: cents.optional(),
- cost_next_period_cents: cents,
- cost_today_cents: cents,
- credits_next_period_cents: cents,
- credits_today_cents: cents,
- renewal_amount_cents: cents.optional(),
+ amount_due_cents: wireCents.optional(),
+ cost_next_period_cents: wireCents,
+ cost_today_cents: wireCents,
+ credits_next_period_cents: wireCents,
+ credits_today_cents: wireCents,
+ renewal_amount_cents: wireCents.optional(),
+ subtotal_cents: wireCents.optional(),
+ balance_applied_cents: wireCents.optional(),
current_plan: PlanInfoSchema.optional(),
new_plan: PlanInfoSchema,
discounts: z
- .array(zSubscriptionDiscount.extend({ amount_off_cents: cents.optional() }))
+ .array(
+ zSubscriptionDiscount.extend({
+ amount_off_cents: wireCents.optional(),
+ duration_in_months: wireCents.optional()
+ })
+ )
.optional()
})
diff --git a/packages/account-core/src/core/billing/wireCents.ts b/packages/account-core/src/core/billing/wireCents.ts
new file mode 100644
index 00000000000..ba2d0e19afc
--- /dev/null
+++ b/packages/account-core/src/core/billing/wireCents.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod'
+
+/**
+ * The generated schemas coerce every int64 to a `bigint`, which no caller can
+ * add to a price or hand to a currency formatter, while the generated *type*
+ * for the same field is a `number`. Billing amounts and credit counts sit well
+ * inside the JavaScript-safe range, so they are read as safe integers.
+ */
+export const wireCents = z.number().int().safe()
diff --git a/packages/ingest-types/src/index.ts b/packages/ingest-types/src/index.ts
index 439d8673aa1..a842cc05503 100644
--- a/packages/ingest-types/src/index.ts
+++ b/packages/ingest-types/src/index.ts
@@ -122,6 +122,7 @@ export type {
BillingCompanyDetailsUpdateRequest,
BillingEvent,
BillingEventsResponse,
+ BillingOpReceiptPlan,
BillingOpStatusResponse,
BillingPlansResponse,
BillingStatus,
@@ -230,6 +231,12 @@ export type {
CreateTopupData,
CreateTopupError,
CreateTopupErrors,
+ CreateTopupQuoteData,
+ CreateTopupQuoteError,
+ CreateTopupQuoteErrors,
+ CreateTopupQuoteRequest,
+ CreateTopupQuoteResponse,
+ CreateTopupQuoteResponses,
CreateTopupRequest,
CreateTopupResponse,
CreateTopupResponse2,
@@ -1075,6 +1082,7 @@ export type {
TeamCreditStops,
TeamCreditStopSummary,
ToolCallSummary,
+ TopupQuoteResponse,
UpdateAssetData,
UpdateAssetError,
UpdateAssetErrors,
diff --git a/packages/ingest-types/src/types.gen.ts b/packages/ingest-types/src/types.gen.ts
index 9d0cc0837ed..8f83cbbc3e7 100644
--- a/packages/ingest-types/src/types.gen.ts
+++ b/packages/ingest-types/src/types.gen.ts
@@ -504,6 +504,29 @@ export type UpdateHubProfileRequest = {
website_urls?: Array
}
+/**
+ * What a credit top-up of the requested amount would grant.
+ */
+export type TopupQuoteResponse = {
+ /**
+ * The quoted amount, in cents.
+ */
+ amount_cents: number
+ /**
+ * Display credits at 211 per dollar, rounded half up. The top-up
+ * itself grants `amount_cents` of balance.
+ *
+ */
+ credits: number
+ /**
+ * Approximately 12 months from now (the default top-up window); the
+ * actual grant may start an hour or two earlier, and a price-level
+ * validity setting can change it.
+ *
+ */
+ expires_at: string
+}
+
/**
* One persisted tool call attached to an assistant message's content.tool_calls (services/agent/internal/persist.ToolCallSummary), so a chat reload can render the tool-call history a turn produced. Display data only — raw arguments/results are never projected here. Only terminal rows (status ok/error) are ever surfaced; a row a dead turn left in pending/running has no wire-status mapping and is dropped rather than shown as a perpetual-progress chip.
*/
@@ -821,6 +844,19 @@ export type SubscriptionDiscount = {
*/
amount_off_cents?: number
code: string
+ /**
+ * How long the underlying coupon keeps applying. May be absent when
+ * the coupon's term is not known, e.g. a plan coupon Stripe does not
+ * echo back.
+ *
+ */
+ duration?: 'once' | 'repeating' | 'forever'
+ /**
+ * The coupon's total term in months when duration is repeating.
+ * Omitted for discounts carried over from the current subscription.
+ *
+ */
+ duration_in_months?: number
kind: 'plan' | 'promotion'
/**
* Customer-facing display name of the underlying coupon. `code` can
@@ -1536,6 +1572,16 @@ export type PreviewSubscribeResponse = {
*/
allowed: boolean
amount_due_cents?: number
+ /**
+ * Credit from the customer's existing account balance applied to
+ * today's charge (the invoice's starting balance, capped at the
+ * total). Present only on Stripe-rated quotes that invoice today in
+ * embedded checkout, when a credit balance is applied; otherwise
+ * absent. Display only: amount_due_cents already reflects it
+ * (an absent amount_due_cents means 0).
+ *
+ */
+ balance_applied_cents?: number
/**
* Amount that will be charged at next billing period in cents
*/
@@ -1615,6 +1661,17 @@ export type PreviewSubscribeResponse = {
*
*/
requires_reactivation_confirmation?: boolean
+ /**
+ * Stripe's subtotal for today's invoice: before invoice-level
+ * discounts and any customer credit balance, and before tax only for
+ * tax-exclusive prices. On an immediate plan change it is net of the
+ * unused-time credit, so it can be zero or negative. Present only on
+ * Stripe-rated quotes that invoice today and itemize every applied
+ * discount in discounts. The charge is always
+ * cost_today_cents / amount_due_cents.
+ *
+ */
+ subtotal_cents?: number
/**
* Type of subscription transition
*/
@@ -1652,6 +1709,14 @@ export type PreviewPlanInfo = {
*/
credits_cents: number
duration: SubscriptionDuration
+ /**
+ * The plan's price for one billing period before invoice-level
+ * discounts, as rated by Stripe. Present only on new_plan of
+ * Stripe-rated quotes that itemize every applied discount in
+ * discounts.
+ *
+ */
+ list_price_cents?: number
/**
* Current billing period end (only for current_plan)
*/
@@ -3754,6 +3819,16 @@ export type CreateTopupRequest = {
idempotency_key?: string
}
+/**
+ * Request body for previewing a credit top-up.
+ */
+export type CreateTopupQuoteRequest = {
+ /**
+ * Amount to quote, in cents.
+ */
+ amount_cents: number
+}
+
/**
* A hosted Stripe Checkout session for a credit top-up.
*/
@@ -4113,6 +4188,16 @@ export type BillingOpStatusResponse = {
*
*/
action_url?: string
+ /**
+ * Display only. What the operation's Stripe invoice collected, in
+ * cents, tax included. Present only for a succeeded operation billed
+ * through a Stripe invoice, and absent whenever that amount could not
+ * be read. Top-ups paid on a hosted checkout page or through
+ * Metronome get neither this nor credits_added. Returned only to
+ * workspace billing managers, like the other payment details.
+ *
+ */
+ amount_charged_cents?: number
/**
* State derived from the PaymentIntent attached to this operation's
* exact stored Stripe invoice. Absent when the operation has no
@@ -4129,6 +4214,15 @@ export type BillingOpStatusResponse = {
* When the operation completed (success or failure)
*/
completed_at?: string
+ /**
+ * Display only. Credits (not cents) actually granted for the
+ * operation's Stripe invoice — for a plan change, the prorated
+ * difference. Present only for a succeeded operation whose grant has
+ * been recorded. Visible to any workspace member who can read the
+ * operation.
+ *
+ */
+ credits_added?: number
/**
* Coarse classification of why the correlated PaymentIntent's last
* payment attempt failed, derived at read time from the provider's
@@ -4182,6 +4276,7 @@ export type BillingOpStatusResponse = {
*
*/
phase?: 'awaiting_payment_method' | 'awaiting_invoice_payment' | 'in_progress'
+ plan?: BillingOpReceiptPlan
/**
* Typed next action for a failed operation. Absent for pending and succeeded operations.
*/
@@ -4206,6 +4301,18 @@ export type BillingOpStatusResponse = {
status: 'pending' | 'succeeded' | 'failed' | 'reconciliation_needed'
}
+/**
+ * Display only. The plan the operation targets; for a scheduled change,
+ * the plan it switches to at period end. Present only for succeeded
+ * plan changes, initial subscriptions and resubscribes. Visible to any
+ * workspace member who can read the operation.
+ *
+ */
+export type BillingOpReceiptPlan = {
+ duration: SubscriptionDuration
+ slug: string
+}
+
/**
* Paginated list of billing events for a workspace.
*/
@@ -8216,6 +8323,49 @@ export type CreateTopupCheckoutResponses = {
export type CreateTopupCheckoutResponse2 =
CreateTopupCheckoutResponses[keyof CreateTopupCheckoutResponses]
+export type CreateTopupQuoteData = {
+ body: CreateTopupQuoteRequest
+ path?: never
+ query?: never
+ url: '/api/billing/topup/quote'
+}
+
+export type CreateTopupQuoteErrors = {
+ /**
+ * Refused: `INVALID_REQUEST`, `INVALID_AMOUNT`,
+ * `LEGACY_STRIPE_CHECKOUT_REQUIRED` (use Stripe Checkout),
+ * `BILLING_PLAN_ENDED` (sales-managed plan has ended), or
+ * `BILLING_DISABLED`.
+ *
+ */
+ 400: ErrorResponse
+ /**
+ * Unauthorized
+ */
+ 401: ErrorResponse
+ /**
+ * A refused request that changes data. For a web session, `code` is `csrf_invalid` (no `X-CSRF-Token`, or not the session's), `workspace_access_denied` (the selected workspace is unknown, deleted, or the user is not a member; the three look the same), `origin_not_allowed` or `cross_site_request`; see the `WebSessionAuth` scheme. `FORBIDDEN` is the route's own authorization check failing, such as an unverified email. A credential this route does not take gets AuthTypeNotAllowedError instead, and so does the session while `web_session_enabled` is off for the user, unless the operation says it takes the session whatever the flag.
+ */
+ 403: ForbiddenError
+ /**
+ * Internal server error
+ */
+ 500: ErrorResponse
+}
+
+export type CreateTopupQuoteError =
+ CreateTopupQuoteErrors[keyof CreateTopupQuoteErrors]
+
+export type CreateTopupQuoteResponses = {
+ /**
+ * Top-up quote
+ */
+ 200: TopupQuoteResponse
+}
+
+export type CreateTopupQuoteResponse =
+ CreateTopupQuoteResponses[keyof CreateTopupQuoteResponses]
+
export type GetBillingUsageTimeSeriesData = {
body?: never
path?: never
@@ -8523,10 +8673,6 @@ export type GetFeaturesResponses = {
* Maximum upload size in bytes
*/
max_upload_size?: number
- /**
- * Whether new free-tier subscriptions are enabled for this caller. Current servers always emit a boolean; clients should tolerate absence when talking to older servers that predate this declared field.
- */
- new_free_tier_subscriptions?: boolean
/**
* Stripe publishable key (pk_...) for the environment's Stripe account. Public by design (the secret key is never exposed here). Absent when STRIPE_PUBLISHABLE_KEY is not configured on the server, so a client can tell "not configured" from "configured as empty".
*/
diff --git a/packages/ingest-types/src/zod.gen.ts b/packages/ingest-types/src/zod.gen.ts
index ea50d379f8a..1dceb247f7b 100644
--- a/packages/ingest-types/src/zod.gen.ts
+++ b/packages/ingest-types/src/zod.gen.ts
@@ -334,6 +334,29 @@ export const zUpdateHubProfileRequest = z.object({
website_urls: z.array(z.string()).optional()
})
+/**
+ * What a credit top-up of the requested amount would grant.
+ */
+export const zTopupQuoteResponse = z.object({
+ amount_cents: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ }),
+ credits: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ }),
+ expires_at: z.string().datetime()
+})
+
/**
* One persisted tool call attached to an assistant message's content.tool_calls (services/agent/internal/persist.ToolCallSummary), so a chat reload can render the tool-call history a turn produced. Display data only — raw arguments/results are never projected here. Only terminal rows (status ok/error) are ever surfaced; a row a dead turn left in pending/running has no wire-status mapping and is dropped rather than shown as a perpetual-progress chip.
*/
@@ -527,6 +550,16 @@ export const zSubscriptionDiscount = z.object({
})
.optional(),
code: z.string(),
+ duration: z.enum(['once', 'repeating', 'forever']).optional(),
+ duration_in_months: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+ .optional(),
kind: z.enum(['plan', 'promotion']),
name: z.string().optional()
})
@@ -975,6 +1008,15 @@ export const zPreviewPlanInfo = z.object({
message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
}),
duration: zSubscriptionDuration,
+ list_price_cents: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+ .optional(),
period_end: z.string().datetime().optional(),
period_start: z.string().datetime().optional(),
price_cents: z.coerce
@@ -1004,6 +1046,15 @@ export const zPreviewSubscribeResponse = z.object({
message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
})
.optional(),
+ balance_applied_cents: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+ .optional(),
cost_next_period_cents: z.coerce
.bigint()
.min(BigInt('-9223372036854775808'), {
@@ -1059,6 +1110,15 @@ export const zPreviewSubscribeResponse = z.object({
.optional(),
renewal_at: z.string().datetime().optional(),
requires_reactivation_confirmation: z.boolean().optional(),
+ subtotal_cents: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+ .optional(),
transition_type: z.enum([
'new_subscription',
'upgrade',
@@ -2302,6 +2362,20 @@ export const zCreateTopupRequest = z.object({
idempotency_key: z.string().optional()
})
+/**
+ * Request body for previewing a credit top-up.
+ */
+export const zCreateTopupQuoteRequest = z.object({
+ amount_cents: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+})
+
/**
* A hosted Stripe Checkout session for a credit top-up.
*/
@@ -2462,11 +2536,32 @@ export const zBillingPlansResponse = z.object({
team_credit_stops: zTeamCreditStops.optional()
})
+/**
+ * Display only. The plan the operation targets; for a scheduled change,
+ * the plan it switches to at period end. Present only for succeeded
+ * plan changes, initial subscriptions and resubscribes. Visible to any
+ * workspace member who can read the operation.
+ *
+ */
+export const zBillingOpReceiptPlan = z.object({
+ duration: zSubscriptionDuration,
+ slug: z.string()
+})
+
/**
* Status of an asynchronous billing operation.
*/
export const zBillingOpStatusResponse = z.object({
action_url: z.string().optional(),
+ amount_charged_cents: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+ .optional(),
authentication_state: z
.enum([
'requires_action',
@@ -2477,6 +2572,15 @@ export const zBillingOpStatusResponse = z.object({
])
.optional(),
completed_at: z.string().datetime().optional(),
+ credits_added: z.coerce
+ .bigint()
+ .min(BigInt('-9223372036854775808'), {
+ message: 'Invalid value: Expected int64 to be >= -9223372036854775808'
+ })
+ .max(BigInt('9223372036854775807'), {
+ message: 'Invalid value: Expected int64 to be <= 9223372036854775807'
+ })
+ .optional(),
decline_reason: z
.enum([
'card_declined',
@@ -2500,6 +2604,7 @@ export const zBillingOpStatusResponse = z.object({
'in_progress'
])
.optional(),
+ plan: zBillingOpReceiptPlan.optional(),
recovery_action: z
.enum([
'retry',
@@ -3568,6 +3673,13 @@ export const zCreateTopupCheckoutBody = zCreateTopupCheckoutRequest
*/
export const zCreateTopupCheckoutResponse2 = zCreateTopupCheckoutResponse
+export const zCreateTopupQuoteBody = zCreateTopupQuoteRequest
+
+/**
+ * Top-up quote
+ */
+export const zCreateTopupQuoteResponse = zTopupQuoteResponse
+
export const zGetBillingUsageTimeSeriesQuery = z.object({
group_by: z
.enum(['model', 'endpoint', 'product'])
@@ -3631,7 +3743,6 @@ export const zGetFeaturesResponse = z.object({
})
.optional(),
max_upload_size: z.number().int().optional(),
- new_free_tier_subscriptions: z.boolean().optional(),
stripe_publishable_key: z.string().optional(),
supports_preview_metadata: z.boolean().optional(),
web_session_probe: z.boolean().optional()