Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -3150,6 +3150,12 @@
"addNewPaymentMethod": "Add new payment method",
"alipay": "Alipay"
},
"declined": {
"title": "Payment declined",
"body": "Your card couldn't be charged. Try another card, or contact your bank if this looks wrong.",
"reasonLabel": "What your bank said",
"updatePaymentMethod": "Update payment method"
},
"success": {
"allSet": "You're all set",
"inviteEmailsPlaceholder": "Enter emails separated by commas",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { render, screen } from '@testing-library/vue'
import userEvent from '@testing-library/user-event'
import { describe, expect, it } from 'vitest'
import { createI18n } from 'vue-i18n'

import enMessages from '@/locales/en/main.json'

import SubscriptionDeclinedWorkspace from './SubscriptionDeclinedWorkspace.vue'

const i18n = createI18n({
legacy: false,
locale: 'en',
messages: { en: enMessages }
})

function renderDeclined(declineReason: string | null = null) {
return render(SubscriptionDeclinedWorkspace, {
props: { declineReason },
global: { plugins: [i18n] }
})
}

describe('SubscriptionDeclinedWorkspace', () => {
it('shows the Stripe reason when the API provides one', () => {
renderDeclined('Insufficient funds')

expect(screen.getByText('What your bank said')).toBeInTheDocument()
expect(screen.getByText('Insufficient funds')).toBeInTheDocument()
})

it('omits the reason block entirely when there is none', () => {
renderDeclined(null)

expect(screen.queryByText('What your bank said')).toBeNull()
expect(screen.getByText('Payment declined')).toBeInTheDocument()
})

it('offers a retry rather than ending the flow', async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — The name promises a flow-level guarantee, but the test only asserts that the child emits updatePayment and back — nothing covers where the parent's handleDeclinedBack actually lands, which is exactly where the retry dead-ends on the preview step. Asserting the resulting checkoutStep in a useSubscriptionCheckout or dialog-level test would catch that.

Raised by 1 of 8 reviewers (claude-opus-5-thinking-max edge-case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right level, wrong file — added the flow-level assertions to the composable suite in f3600d4: in-flow back lands on the preserved preview, recovered back lands on pricing. The component test keeps asserting only what the child owns (its emits).

const { emitted } = renderDeclined('Card declined')

await userEvent.click(
screen.getByRole('button', { name: 'Update payment method' })
)
expect(emitted().updatePayment).toBeTruthy()

await userEvent.click(screen.getByRole('button', { name: 'Back' }))
expect(emitted().back).toBeTruthy()
})
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<template>
<div
class="mx-auto flex h-full max-w-[400px] flex-col items-stretch justify-between text-sm motion-safe:animate-in motion-safe:duration-300 motion-safe:fade-in motion-safe:slide-in-from-bottom-2"
>
<div class="flex flex-col items-center gap-4 pt-8">
<i class="pi pi-exclamation-circle text-5xl text-warning-background" />
<h2
class="m-0 text-center text-xl font-semibold text-base-foreground lg:text-2xl"
>
{{ $t('subscription.declined.title') }}
</h2>
<p class="m-0 text-center text-sm text-muted-foreground">
{{ $t('subscription.declined.body') }}
</p>

<!-- Shown only when the API gives a reason: an empty box reads as a
second failure rather than an explanation. -->
<div
v-if="declineReason"
class="mt-4 flex w-full flex-col gap-1 rounded-xl bg-secondary-background p-4"
>
<span class="text-sm text-muted-foreground">
{{ $t('subscription.declined.reasonLabel') }}
</span>
<span class="text-sm text-base-foreground">{{ declineReason }}</span>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — checkoutDeclineReason comes from the operation's errorMessage, which handleFailure fills with the first-party billingFailureDetail(...) i18n string (falling back to "We couldn't update your subscription. Please try again."), never the processor's text — so labeling it "Stripe reasoning:" attributes our own copy to Stripe. Since that value is never empty for a failed subscription op, the v-if always renders and usually just restates the body text, meaning the null case the unit test covers cannot occur in production.

Raised by 1 of 8 reviewers (claude-opus-5-thinking-max adversarial).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Label fixed in f3600d4: "What your bank said" (the copy the Outcome Screens design uses) — the box carries our mapped rendering of the bank's decline code, so attributing it to Stripe was wrong on both ends. The always-renders point stands for the generic fallback until #16571's failure classification lands; with it, the verdict-class codes are the ones that reach this screen with a reason.

</div>
</div>

<div class="flex flex-col gap-2 pt-8 pb-4">
<Button
variant="inverted"
size="lg"
class="w-full rounded-lg"
@click="$emit('updatePayment')"
>
{{ $t('subscription.declined.updatePaymentMethod') }}
</Button>
<Button
variant="muted-textonly"
size="lg"
class="w-full rounded-lg"
@click="$emit('back')"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question → answered: you asked whether to keep this secondary Back or rely on the X plus a reopen. I'd keep it.

The X isn't equivalent here. With the declined step suppressing the dialog header, closing is the only other route, and on reopen the customer doesn't land back where they were — #15923's initializer reads subscriptionActionOperation, the failed operation no longer matches (the selector takes pending and reconciliation_needed only), so they land on 'pricing' and start over. That directly contradicts the design note you quoted — "Declined is not terminal: back returns to the confirm step with everything intact for a retry." The X gives them terminal-with-extra-steps.

So the deviation is the design being honored rather than departed from. Worth saying that in the Figma thread rather than dropping the button.

(One caveat: "everything intact" only holds on the in-flow path — see my comment on handleDeclinedBack. Once that's guarded, this reasoning is clean.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed and keeping it — and your re-entry analysis is now doubly load-bearing, since Back's destination depends on exactly that distinction (see the routing fix above).

>
{{ $t('g.back') }}
</Button>
</div>
</div>
</template>

<script setup lang="ts">
import Button from '@/components/ui/button/Button.vue'

const { declineReason = null } = defineProps<{
/** Stripe's stated reason, when the API provides one. */
declineReason?: string | null
}>()

defineEmits<{
/** Collect a different payment method. */
updatePayment: []
/** Return to the confirm step with the quote and selection intact. */
back: []
}>()
</script>
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,26 @@
// panel stays fixed; below xl the whole dialog scrolls as before.
isEmbeddedPaymentStep &&
'xl:h-[min(740px,90vh)] xl:gap-0 xl:overflow-hidden xl:rounded-2xl xl:p-0',
(isEmbeddedSuccessStep || isEmbeddedConfirmStep || isVerifyingStep) &&
(isEmbeddedSuccessStep ||
isEmbeddedConfirmStep ||
isVerifyingStep ||
isDeclinedStep) &&
'h-[min(740px,85vh)] overflow-hidden rounded-2xl bg-base-background xl:h-[min(740px,90vh)] xl:w-[512px]',
(isEmbeddedPaymentStep ||
isEmbeddedSuccessStep ||
isEmbeddedConfirmStep ||
isVerifyingStep) &&
isVerifyingStep ||
isDeclinedStep) &&
'motion-safe:xl:transition-[width] motion-safe:xl:duration-300 motion-safe:xl:ease-in-out',
// The w-fit shell hugs min-content on phones; give the embedded
// steps a real width floor below xl.
(isEmbeddedPaymentStep ||
isEmbeddedSuccessStep ||
isEmbeddedConfirmStep ||
isVerifyingStep) &&
isVerifyingStep ||
isDeclinedStep) &&
'max-xl:w-[min(430px,92vw)]',
isEmbeddedPaymentStep && 'max-xl:h-[85vh]'
isEmbeddedPaymentStep && 'max-xl:h-[min(740px,85vh)]'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: This changes the embedded payment step's mobile height (max-xl:h-[85vh] → max-xl:h-[min(740px,85vh)]), which is a different step from the one this PR adds and isn't mentioned in the description.

It caps the payment step at 740px on tall phones where 85vh previously exceeded that. Plausibly a deliberate alignment with the other embedded steps — they all use min(740px,...) — but I'd rather not infer it.

Is it intentional? If yes, could you add a line to the description so it isn't read as a stray edit during a bisect later. If it's incidental, dropping it keeps this PR to the declined step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deliberate, and you're right it belonged in the description — added. It caps the payment step at 740px on tall phones to match the min(740px,…) treatment every other embedded step already uses; without it the payment step was the one screen that could grow past its siblings.

)
"
>
Expand Down Expand Up @@ -64,7 +69,8 @@
!isEmbeddedPaymentStep &&
!isEmbeddedSuccessStep &&
!isEmbeddedConfirmStep &&
!isVerifyingStep
!isVerifyingStep &&
!isDeclinedStep

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — This adds the declined step to the "Choose a Plan" header guard, but the v-if="reason === 'out_of_credits'" block just below it has no step gating, so a dialog opened from an out-of-credits prompt stacks "Insufficient credits" above "Payment declined" inside a fixed-height overflow-hidden panel. The verifying and success steps already have the same omission, so gating that block on the step is a better fix than adding another negation here.

Raised by 1 of 8 reviewers (claude-opus-5-thinking-max edge-case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took the better fix as suggested: the out-of-credits block is now positively gated on the plan-facing steps (pricing/preview), which also covers the pre-existing verifying/success stacking.

"
class="flex flex-col items-center gap-3"
>
Expand All @@ -73,7 +79,13 @@
</h2>
</div>

<div v-if="reason === 'out_of_credits'" class="text-center">
<div
v-if="
reason === 'out_of_credits' &&
(checkoutStep === 'pricing' || checkoutStep === 'preview')
"
class="text-center"
>
<h2 class="m-0 text-xl text-muted-foreground lg:text-2xl">
{{ $t('credits.topUp.insufficientTitle') }}
</h2>
Expand Down Expand Up @@ -226,6 +238,13 @@
@cancel-payment="handleCancelPendingPayment"
/>

<SubscriptionDeclinedWorkspace
v-if="checkoutStep === 'declined'"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium — The declined screen is shown for any operation in the terminal failed status, which the billing store also uses for checkout_superseded (deliberately not surfaced, since its replacement is proceeding normally) and for backend/network/system failures. Those cases now get a full-screen "Payment declined" that blames the customer's bank and offers a payment-method fix that cannot address the real error; gate the transition on a provider-decline category, or use generic failure copy.

Raised by 3 of 8 reviewers (claude-opus-5-thinking-max adversarial, gpt-5.6-sol-max adversarial, gpt-5.6-sol-max edge-case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly guarded already, fully addressed one PR up. Superseded operations can't reach this screen: supersession only happens when a new attempt has replaced the active operation, and both routing sites guard on the active operation id, so the superseded op is no longer the one being watched. Backend/system failures do land here on this branch with the generic mapped copy; the classification that splits them arrives in #16571 (stacked on this), where processing-class failures get their own outcome screen with Try again and no payment-method CTA. The residual default — unknown code → declined — is deliberate: an unrecognized failure on a charge is most likely the charge.

:decline-reason="checkoutDeclineReason"
@update-payment="handleDeclinedUpdatePayment"
@back="handleDeclinedBack"
/>

<!-- Success Step - "You're all set" -->
<SubscriptionSuccessWorkspace
v-if="checkoutStep === 'success' && (selectedTierKey || isTeamCheckout)"
Expand All @@ -252,6 +271,7 @@ import { useSubscriptionCheckout } from '@/platform/workspace/composables/useSub
import SubscriptionAddPaymentPreviewWorkspace from './SubscriptionAddPaymentPreviewWorkspace.vue'
import SubscriptionSuccessWorkspace from './SubscriptionSuccessWorkspace.vue'
import SubscriptionTransitionPreviewWorkspace from './SubscriptionTransitionPreviewWorkspace.vue'
import SubscriptionDeclinedWorkspace from './SubscriptionDeclinedWorkspace.vue'
import SubscriptionVerifyingWorkspace from './SubscriptionVerifyingWorkspace.vue'
import UnifiedPricingTable from './UnifiedPricingTable.vue'

Expand Down Expand Up @@ -284,6 +304,8 @@ const collectingNewPaymentMethod = ref(false)

const {
checkoutStep,
checkoutDeclineReason,
handleDeclinedBack,
isCancelingPayment,
cancelUnavailable,
cancelUnreachable,
Expand Down Expand Up @@ -375,6 +397,14 @@ function selectSavedPaymentMethod(id: string | null) {
}

const isVerifyingStep = computed(() => checkoutStep.value === 'verifying')
const isDeclinedStep = computed(() => checkoutStep.value === 'declined')

// The decline CTA returns to confirm and opens method collection, which is
// dialog state rather than checkout state.
function handleDeclinedUpdatePayment() {
handleDeclinedBack()
selectSavedPaymentMethod(null)
}

onMounted(() => {
if (!initialCheckout) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ const {
mockStartOperation,
mockRetryPaymentAuthentication,
mockGetOperation,
mockClearOperation,
mockCancelOperation,
mockSubscriptionActionOperation,
mockListSavedPaymentMethods,
Expand Down Expand Up @@ -194,6 +195,7 @@ const {
mockStartOperation: vi.fn(),
mockRetryPaymentAuthentication: vi.fn(),
mockGetOperation: vi.fn(),
mockClearOperation: vi.fn(),
mockCancelOperation: vi.fn(),
mockSubscriptionActionOperation: {
value: undefined as MockSubscriptionActionOperation | undefined
Expand Down Expand Up @@ -354,6 +356,7 @@ vi.mock('@/platform/workspace/stores/billingOperationStore', () => ({
retryPaymentAuthentication: mockRetryPaymentAuthentication,
getOperation: mockGetOperation,
cancelOperation: mockCancelOperation,
clearOperation: mockClearOperation,
get subscriptionActionOperation() {
return mockSubscriptionActionOperation.value
}
Expand Down Expand Up @@ -2640,12 +2643,32 @@ describe('useSubscriptionCheckout', () => {
return checkout
}

it('returns to plan selection when the recovered charge fails', async () => {
it('reaches the declined step instead of returning to pricing', async () => {
const checkout = await reentryOn('failed', {
errorMessage: 'Insufficient funds'
})

expect(checkout.checkoutStep.value).toBe('declined')
})

it('backs out of an in-flow decline to the preserved preview', async () => {
const checkout = await setupWithApprovedPreview()

checkout.checkoutStep.value = 'declined'
checkout.handleDeclinedBack()

expect(checkout.checkoutStep.value).toBe('preview')
})

it('backs out of a recovered decline to plan selection, not a blank preview', async () => {
const checkout = await reentryOn('failed', {
errorMessage: 'Insufficient funds'
})

checkout.handleDeclinedBack()

expect(checkout.checkoutStep.value).toBe('pricing')
expect(checkout.checkoutDeclineReason.value).toBeNull()
})

it('closes on success when there is no plan selection to show', async () => {
Expand Down
24 changes: 19 additions & 5 deletions src/platform/workspace/composables/useSubscriptionCheckout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import {
} from '@/platform/workspace/utils/pendingSubscriptionCheckout'
import { trackWorkspaceCheckoutStarted } from '@/platform/workspace/utils/workspaceCheckoutTelemetry'

type CheckoutStep = 'pricing' | 'preview' | 'verifying' | 'success'
type CheckoutStep = 'pricing' | 'preview' | 'verifying' | 'success' | 'declined'
export type CheckoutTierKey = Exclude<TierKey, 'free' | 'founder'>

export type SubscriptionCheckoutSelection =
Expand Down Expand Up @@ -164,6 +164,7 @@ export function useSubscriptionCheckout(
? 'verifying'
: 'pricing'
)
const checkoutDeclineReason = ref<string | null>(null)
const isCancelingPayment = ref(false)
const cancelUnavailable = ref(false)
const cancelUnreachable = ref(false)
Expand Down Expand Up @@ -928,6 +929,18 @@ export function useSubscriptionCheckout(
emit('close', true)
}

// Declined is not terminal: back returns to the confirm step with the quote
// and selection intact so the same charge can be retried. A decline reached
// on re-entry has no preserved quote to land on — plan selection is the only
// step that can host it.
function handleDeclinedBack() {
checkoutDeclineReason.value = null
const opId = activeCheckoutOperation.value?.opId
if (opId) billingOperationStore.clearOperation(opId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low — clearOperation(opId) removes the record but leaves activeCheckoutOperationId pointing at the deleted id, unlike the sibling cleanup paths resetToPricing() and handleCancelPendingPayment(), which both null it right after removing the operation. Because activeCheckoutOperation only falls back to billingOperationStore.subscriptionActionOperation when that ref is null, the dialog stays blind to any other subscription operation (e.g. a reconciliation_needed op) until a new subscribe overwrites the id.

Raised by 3 of 8 reviewers (claude-opus-5-thinking-max adversarial, claude-opus-5-thinking-max edge-case, kimi-k3-max edge-case).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f3600d4 — handleDeclinedBack nulls activeCheckoutOperationId right after clearOperation, matching resetToPricing and handleCancelPendingPayment.

activeCheckoutOperationId.value = null
checkoutStep.value = previewData.value ? 'preview' : 'pricing'
}

async function handleSubscription(
confirmReactivation = false,
confirmationToken?: string,
Expand Down Expand Up @@ -1435,10 +1448,9 @@ export function useSubscriptionCheckout(
return
}
if (status === 'failed') {
// The declined outcome step arrives one PR up; until it does, the
// store's failure toast carries the verdict and the dialog returns
// to plan selection.
checkoutStep.value = 'pricing'
checkoutDeclineReason.value =
activeCheckoutOperation.value?.errorMessage ?? null
checkoutStep.value = 'declined'
return
}
if (status === undefined) {
Expand Down Expand Up @@ -1642,6 +1654,8 @@ export function useSubscriptionCheckout(

return {
checkoutStep,
checkoutDeclineReason,
handleDeclinedBack,
isLoadingPreview,
loadingTier,
isSubscribing,
Expand Down
Loading