From 34fa947a7e34663a20ae1c0c614af27d3a8ae659 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 17:38:50 -0400 Subject: [PATCH 1/4] chore(ingest-types): regenerate from cloud@0dbfffb Picks up the checkout quote subtotal, list price, discount term and applied balance (cloud #11148, #11223), the read-only top-up quote (cloud #11188) and the succeeded operation receipt fields (cloud #11199). account-core reads the new int64 amounts as safe integers, like the existing cents, instead of the generated bigint. Drops new_free_tier_subscriptions, which was hand-added to the generated files and is not in the cloud spec; both consumers declare it themselves. --- .../previewSubscribe.contract.test.ts | 4 +- .../src/core/billing/operationLifecycle.ts | 4 +- .../src/core/billing/operationState.ts | 10 +- .../core/billing/subscriptionCommands.test.ts | 56 ++++++- .../src/core/billing/subscriptionCommands.ts | 42 +++-- .../src/core/billing/wireCents.ts | 9 + packages/ingest-types/src/index.ts | 8 + packages/ingest-types/src/types.gen.ts | 154 +++++++++++++++++- packages/ingest-types/src/zod.gen.ts | 113 ++++++++++++- 9 files changed, 364 insertions(+), 36 deletions(-) create mode 100644 packages/account-core/src/core/billing/wireCents.ts 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/operationLifecycle.ts b/packages/account-core/src/core/billing/operationLifecycle.ts index f43f1405c98..7af9a290f01 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,7 @@ import type { PendingBillingOperation } from './operationState.js' import { + BillingOpStatusSchema, isTerminal, reduceBillingOperation, validateActionUrl @@ -444,7 +444,7 @@ export function createBillingOperationLifecycle( return readValidatedBillingResponse( transport, { method: 'GET', route: operationRoute(operationId) }, - (body) => zBillingOpStatusResponse.safeParse(body) + (body) => BillingOpStatusSchema.safeParse(body) ) } diff --git a/packages/account-core/src/core/billing/operationState.ts b/packages/account-core/src/core/billing/operationState.ts index cd5d2e3e1ac..54e5de227e7 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' 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() From 0e0816b14b05cafeae864c93c44e33072396d8a8 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 17:44:17 -0400 Subject: [PATCH 2/4] feat(account-core): keep the receipt a succeeded billing operation reports A succeeded operation now carries the amount charged, credits added and plan the op status reports, each absent while the server cannot say it. A success whose credits are still landing is read again for a caller recovering settled operations, the way a parked reconciliation already is. --- .../account-core/src/core/billing/index.ts | 5 +- .../core/billing/operationLifecycle.test.ts | 89 +++++++++++++++++++ .../src/core/billing/operationLifecycle.ts | 13 ++- .../src/core/billing/operationState.ts | 59 +++++++++++- 4 files changed, 160 insertions(+), 6 deletions(-) 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 7af9a290f01..27323ac6b12 100644 --- a/packages/account-core/src/core/billing/operationLifecycle.ts +++ b/packages/account-core/src/core/billing/operationLifecycle.ts @@ -56,6 +56,7 @@ import type { } 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)}` } @@ -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 54e5de227e7..02e2ceeb900 100644 --- a/packages/account-core/src/core/billing/operationState.ts +++ b/packages/account-core/src/core/billing/operationState.ts @@ -119,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' }) @@ -242,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), @@ -263,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 From e1f325abad316e2471c78dda0567ae92a557c931 Mon Sep 17 00:00:00 2001 From: dante01yoon Date: Wed, 30 Sep 2026 17:57:54 -0400 Subject: [PATCH 3/4] feat(billing-web): render server-reported subtotal, list price, discount term, balance and receipts Summary: a discounted plan rate shows its list price struck through, a discount row states its term (first period, N months), the account balance the server applied is the last deduction and keeps the row it explains, and Subtotal shows only where a discount follows two or more money rows. Endings: Success counts the credits the operation reports, Already completed and You're all set name the plan its receipt names from the catalog, a top-up lists Added and Amount paid, and a charge whose credits are still landing reads Payment received until a re-read reports them. The e2e fixtures gain a monthly-to-yearly quote carrying renewal_at, list price and subtotal the way the real backend quotes it. --- apps/billing-web/e2e/fixtures/scenario.ts | 61 ++++++ .../billing-web/e2e/full-page-endings.spec.ts | 57 ++++++ .../billing-web/e2e/full-page-summary.spec.ts | 86 +++++++++ .../src/checkout/checkoutPage.test.ts | 127 +++++++++++++ apps/billing-web/src/checkout/checkoutPage.ts | 55 +++++- .../src/checkout/endingScreen.test.ts | 83 ++++++++ apps/billing-web/src/checkout/endingScreen.ts | 114 +++++++++-- .../src/checkout/summaryLedger.test.ts | 177 ++++++++++++++++++ .../billing-web/src/checkout/summaryLedger.ts | 151 ++++++++++++--- .../fullPage/CheckoutEnding.test.ts | 114 +++++++++++ .../components/fullPage/CheckoutEnding.vue | 85 ++++++++- .../fullPage/CheckoutSummaryColumn.test.ts | 112 +++++++++++ .../fullPage/summary/CheckoutLedger.vue | 40 +--- .../fullPage/summary/LedgerDeduction.vue | 21 +++ .../fullPage/summary/LedgerItem.vue | 36 ++++ .../fullPage/summary/LedgerRows.vue | 66 +++++++ .../src/composables/useFullPageCheckout.ts | 45 +++-- apps/billing-web/src/locales/en/main.json | 24 ++- .../src/views/FullPageCheckoutView.test.ts | 71 +++++++ .../src/views/FullPageCheckoutView.vue | 6 +- 20 files changed, 1421 insertions(+), 110 deletions(-) create mode 100644 apps/billing-web/src/components/fullPage/summary/LedgerDeduction.vue create mode 100644 apps/billing-web/src/components/fullPage/summary/LedgerItem.vue create mode 100644 apps/billing-web/src/components/fullPage/summary/LedgerRows.vue 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..e4f04367f96 100644 --- a/apps/billing-web/e2e/full-page-endings.spec.ts +++ b/apps/billing-web/e2e/full-page-endings.spec.ts @@ -109,6 +109,63 @@ 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' + ) +}) + +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/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..be5a747dde1 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 { 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..9592953112c 100644 --- a/apps/billing-web/src/components/fullPage/CheckoutEnding.test.ts +++ b/apps/billing-web/src/components/fullPage/CheckoutEnding.test.ts @@ -235,6 +235,120 @@ 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' + ) + }) + + 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..fdc9442f3e6 100644 --- a/apps/billing-web/src/components/fullPage/CheckoutEnding.vue +++ b/apps/billing-web/src/components/fullPage/CheckoutEnding.vue @@ -2,10 +2,16 @@ 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 { namedPlan } from '@/checkout/summaryLedger' @@ -92,6 +98,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) @@ -135,21 +182,47 @@ function act() {

- {{ plan.name }} + {{ planCard.name }}

- {{ plan.price }} - {{ plan.period }} + {{ planCard.price }} + {{ planCard.period }} +

+

+