Skip to content
Merged
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
106 changes: 106 additions & 0 deletions apps/billing-web/e2e/full-page-promo.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,109 @@ test('a code that lapses before Pay returns to capture with the expired card', a
).toBeEnabled()
await expect(page.getByRole('link', { name: 'Contact support' })).toBeHidden()
})

test('a code applied here survives a reload, still applied at the discounted price', async ({
page,
cloud,
signIn
}) => {
quoteCodes(cloud)
await signIn(CHECKOUT)
await enterCode(page, 'LAUNCH20')
await expect(summary(page)).toContainText('Total due today$40.00')

await page.reload()

await expect(summary(page)).toContainText('Promo code−$10.00')
await expect(summary(page)).toContainText('Total due today$40.00')
await expect(
page.getByRole('button', { name: 'Remove LAUNCH20' })
).toBeVisible()
})

test('a restored code the server now refuses shows the expired card at the full price', async ({
page,
cloud,
signIn
}) => {
let stillValid = true
quoteCodes(cloud, () => stillValid)
await signIn(CHECKOUT)
await enterCode(page, 'LAUNCH20')
await expect(summary(page)).toContainText('Total due today$40.00')
stillValid = false

await page.reload()

const card = page.getByRole('alert')
await expect(card).toContainText('Your promo code expired')
await expect(card).toContainText(
'The LAUNCH20 code expired, so the total was updated.'
)
await expect(summary(page)).toContainText('Total due today$50.00')
await expect(
page.getByRole('button', { name: 'Add promo code' })
).toBeEnabled()
})

test('a copied checkout URL carries no applied code', async ({
page,
context,
cloud,
signIn
}) => {
quoteCodes(cloud)
await signIn(CHECKOUT)
await enterCode(page, 'LAUNCH20')
await expect(summary(page)).toContainText('Total due today$40.00')

const copied = page.url()
expect(copied).not.toMatch(/launch20/i)
const pasted = await context.newPage()
await pasted.goto(copied)

await expect(pasted.getByText(EYEBROW)).toBeVisible()
await expect(summary(pasted)).toContainText('Total due today$50.00')
await expect(
pasted.getByRole('button', { name: 'Add promo code' })
).toBeVisible()
})

test('discount rows follow the server order, the entered code first when it comes first', async ({
page,
cloud,
signIn
}) => {
cloud.reply('POST', '/billing/preview-subscribe', ({ body }) => {
const entered =
typeof body === 'object' && body !== null && 'promotion_code' in body
if (!entered) return { body: cloud.scenario.preview }
return {
body: {
...cloud.scenario.preview,
quote_id: 'quote_launch20',
amount_due_cents: 3000,
promotion_code: 'LAUNCH20',
discounts: [
{ kind: 'promotion', code: 'LAUNCH20', amount_off_cents: 1000 },
{
kind: 'promotion',
code: 'COMFY-EDU',
name: 'Education discount',
amount_off_cents: 1000
}
]
}
}
})
await signIn(CHECKOUT)

await enterCode(page, 'LAUNCH20')

await expect(summary(page)).toContainText(
'Promo code−$10.00Education discount−$10.00'
)
await expect(
page.getByRole('button', { name: 'Remove LAUNCH20' })
).toBeVisible()
})
15 changes: 15 additions & 0 deletions apps/billing-web/src/checkout/promoEntry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,21 @@ describe('reducePromoEntry', () => {
events: [],
expected: editing('LAUNCH20')
},
{
name: 'a code this page applied before a reload comes back applied',
start: initialPromoEntry(undefined, 'LAUNCH20'),
events: [],
expected: applied('LAUNCH20')
},
{
name: 'a code this page applied outranks the link code, typed or unreadable',
start: initialPromoEntry(
{ promotionCode: 'OTHER', unreadablePromotionCode: 'SAVE 20' },
'LAUNCH20'
),
events: [],
expected: applied('LAUNCH20')
},
{
name: 'no URL code starts collapsed',
start: initialPromoEntry(undefined),
Expand Down
10 changes: 7 additions & 3 deletions apps/billing-web/src/checkout/promoEntry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,16 @@ export type PromoPrefill = Pick<
>

/**
* A code carried in on the entry URL opens the field with it typed, never
* applied. One the link could not carry opens refused, as typed.
* A code this page applied before a reload or a provider return comes back
* applied, for the capture read to price again. A code carried in on the
* entry URL opens the field with it typed, never applied. One the link could
* not carry opens refused, as typed.
*/
export function initialPromoEntry(
prefill: PromoPrefill | undefined
prefill: PromoPrefill | undefined,
restored?: string
): PromoEntry {
if (restored !== undefined) return { kind: 'applied', code: restored }
if (prefill?.promotionCode !== undefined)
return { kind: 'editing', draft: prefill.promotionCode }
const unreadable = prefill?.unreadablePromotionCode
Expand Down
128 changes: 128 additions & 0 deletions apps/billing-web/src/checkout/promoMemory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import type { PromoEntry } from '@/checkout/promoEntry'
import {
checkoutIdentity,
codeToRemember,
createPromoMemory
} from '@/checkout/promoMemory'

const PRO = checkoutIdentity(
{ product: 'comfyui', plan: 'pro_monthly' },
'ws-team'
)

afterEach(() => {
sessionStorage.clear()
})

describe('checkoutIdentity', () => {
it.for<{
name: string
other: Parameters<typeof checkoutIdentity>
}>([
{
name: 'another workspace',
other: [{ product: 'comfyui', plan: 'pro_monthly' }, 'ws-other']
},
{
name: 'another plan',
other: [{ product: 'comfyui', plan: 'creator_monthly' }, 'ws-team']
},
{
name: 'another team commitment',
other: [
{ product: 'comfyui', plan: 'pro_monthly', teamCreditStopId: 'stop_2' },
'ws-team'
]
},
{
name: 'an unbound workspace',
other: [{ product: 'comfyui', plan: 'pro_monthly' }, undefined]
}
])('names $name as a different checkout', ({ other }) => {
expect(checkoutIdentity(...other)).not.toBe(PRO)
})
})

describe('codeToRemember', () => {
it.for<{ entry: PromoEntry; code: string | undefined }>([
{ entry: { kind: 'applied', code: 'LAUNCH20' }, code: 'LAUNCH20' },
{ entry: { kind: 'removing', code: 'LAUNCH20' }, code: 'LAUNCH20' },
{ entry: { kind: 'idle' }, code: undefined },
{ entry: { kind: 'editing', draft: 'LAUNCH20' }, code: undefined },
{ entry: { kind: 'applying', draft: 'LAUNCH20' }, code: undefined },
{
entry: { kind: 'rejected', draft: 'LAUNCH20', reason: 'invalid' },
code: undefined
}
])('$entry.kind remembers $code', ({ entry, code }) => {
expect(codeToRemember(entry)).toBe(code)
})
})

describe('createPromoMemory', () => {
it('recalls the code this checkout kept, across a fresh memory', () => {
createPromoMemory(() => PRO).keep('LAUNCH20')

expect(createPromoMemory(() => PRO).recall()).toBe('LAUNCH20')
})

it('forgets the code once it is kept as nothing', () => {
const memory = createPromoMemory(() => PRO)
memory.keep('LAUNCH20')

memory.keep(undefined)

expect(createPromoMemory(() => PRO).recall()).toBeUndefined()
})

it('gives another checkout nothing, and drops the stale code', () => {
createPromoMemory(() => PRO).keep('LAUNCH20')
const other = checkoutIdentity(
{ product: 'comfyui', plan: 'creator_monthly' },
'ws-team'
)

expect(createPromoMemory(() => other).recall()).toBeUndefined()
expect(createPromoMemory(() => PRO).recall()).toBeUndefined()
})

it.for([
'not json',
'{"identity":1,"code":"LAUNCH20"}',
'{"code":"LAUNCH20"}',
'null'
])('reads a malformed record %s as nothing', (raw) => {
sessionStorage.setItem('comfy.billing-web.checkout-promo.v1', raw)

expect(createPromoMemory(() => PRO).recall()).toBeUndefined()
})

it('works as an empty memory where storage throws', () => {
const blocked = () => {
throw new DOMException('blocked', 'SecurityError')
}
const memory = createPromoMemory(() => PRO, blocked)

expect(() => memory.keep('LAUNCH20')).not.toThrow()
expect(memory.recall()).toBeUndefined()
})

it('survives a storage that refuses writes', () => {
const full: Storage = Object.assign(Object.create(sessionStorage), {
getItem: () => null,
setItem: () => {
throw new DOMException('full', 'QuotaExceededError')
},
removeItem: () => {
throw new DOMException('full', 'QuotaExceededError')
}
})
const memory = createPromoMemory(
() => PRO,
() => full
)

expect(() => memory.keep('LAUNCH20')).not.toThrow()
expect(() => memory.keep(undefined)).not.toThrow()
})
})
108 changes: 108 additions & 0 deletions apps/billing-web/src/checkout/promoMemory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**
* The promo code this page applied, kept in the tab's sessionStorage so a
* reload or a return from a provider's site re-applies it. It is never
* written to a URL, so a copied link carries only what the link itself did.
* One record at a time, tagged with the checkout it belongs to: another
* checkout reads nothing and drops it.
*/
import type { BillingEntry } from '@comfyorg/billing-contract'

import type { PromoEntry } from '@/checkout/promoEntry'

const STORAGE_KEY = 'comfy.billing-web.checkout-promo.v1'

/** Who pays, and for what: a code applied to one checkout belongs to it alone. */
export function checkoutIdentity(
entry:
| Pick<BillingEntry, 'product' | 'plan' | 'teamCreditStopId'>
| undefined,
workspaceId: string | undefined
): string {
return JSON.stringify([
workspaceId ?? null,
entry?.product ?? null,
entry?.plan ?? null,
entry?.teamCreditStopId ?? null
])
}

/** A code the server priced for this page, until the customer takes it off. */
export function codeToRemember(entry: PromoEntry): string | undefined {
return entry.kind === 'applied' || entry.kind === 'removing'
? entry.code
: undefined
}

interface Remembered {
readonly identity: string
readonly code: string
}

function isRemembered(value: unknown): value is Remembered {
return (
typeof value === 'object' &&
value !== null &&
'identity' in value &&
'code' in value &&
typeof value.identity === 'string' &&
typeof value.code === 'string'
)
}

function parseRemembered(raw: string | null): Remembered | undefined {
if (raw === null) return undefined
try {
const value: unknown = JSON.parse(raw)
return isRemembered(value) ? value : undefined
} catch {
return undefined
}
}

export interface PromoMemory {
readonly recall: () => string | undefined
/** Nothing forgets the code. */
readonly keep: (code: string | undefined) => void
}

/** A tab without storage, or one that refuses it, remembers nothing and still checks out. */
function withStorage<T>(
storage: () => Storage,
use: (store: Storage) => T,
fallback: T
): T {
try {
return use(storage())
} catch {
return fallback
}
}

export function createPromoMemory(
identity: () => string,
storage: () => Storage = () => globalThis.sessionStorage
): PromoMemory {
const forget = () =>
withStorage(storage, (store) => store.removeItem(STORAGE_KEY), undefined)
return {
recall: () => {
const remembered = withStorage(
storage,
(store) => parseRemembered(store.getItem(STORAGE_KEY)),
undefined
)
if (remembered?.identity === identity()) return remembered.code
if (remembered !== undefined) forget()
return undefined
},
keep: (code) => {
if (code === undefined) return forget()
const record: Remembered = { identity: identity(), code }
withStorage(
storage,
(store) => store.setItem(STORAGE_KEY, JSON.stringify(record)),
undefined
)
}
}
}
Loading
Loading