From 030f5bbf6c5f304ffeab6aa24778069b60efbb58 Mon Sep 17 00:00:00 2001 From: Creeland Date: Mon, 16 Nov 2026 16:01:37 -0600 Subject: [PATCH] feat(epic-web): leave invoices paid after the cutover to Course Builder Both this app and the Course Builder app fulfil a paid one-off Epic Web invoice, and both Stripe endpoints stay live through the migration, so each invoice would be fulfilled twice. Invoices are created by hand and carry no app marker. Ownership is split by when the invoice was paid, against one cutoff both apps read from EPIC_WEB_INVOICE_CUTOVER_AT (ISO-8601 UTC, trailing Z). With the variable set, an invoice paid at or after it is ignored here (owned-by-course-builder). Unset keeps today's behaviour. A malformed value, or a paid invoice with no paid_at, fails the run instead of picking a side. Inert until the variable is set. Co-Authored-By: Claude Fable 5.2 --- .../functions/stripe/invoice-paid.test.ts | 213 ++++++++++++++++++ .../inngest/functions/stripe/invoice-paid.ts | 33 +++ .../src/lib/invoice-fulfilment.test.ts | 147 ++++++++++++ apps/epic-web/src/lib/invoice-fulfilment.ts | 117 ++++++++++ 4 files changed, 510 insertions(+) create mode 100644 apps/epic-web/src/inngest/functions/stripe/invoice-paid.test.ts diff --git a/apps/epic-web/src/inngest/functions/stripe/invoice-paid.test.ts b/apps/epic-web/src/inngest/functions/stripe/invoice-paid.test.ts new file mode 100644 index 000000000..41cd7fd3e --- /dev/null +++ b/apps/epic-web/src/inngest/functions/stripe/invoice-paid.test.ts @@ -0,0 +1,213 @@ +/** + * The ownership rule in the handler: an invoice Course Builder owns is + * ignored right after it is loaded, before the catalog is read or anything + * is written; unset, the handler fulfils as before. + */ +const mockRetrieve = jest.fn() +const mockFindFirstMerchantProduct = jest.fn() +const mockFindFirstPurchase = jest.fn() +const mockFindUniqueOrThrowUser = jest.fn() +const mockSanityFetch = jest.fn() +const mockSdk = { + findOrCreateUser: jest.fn(), + findOrCreateMerchantCustomer: jest.fn(), + createMerchantChargeAndPurchase: jest.fn(), +} + +jest.mock( + 'inngest/inngest.server', + () => ({ + inngest: { + createFunction: ( + _config: unknown, + _trigger: unknown, + handler: unknown, + ) => ({ + handler, + }), + }, + }), + // jest resolves node_modules before src, so this app-local path would hit + // the `inngest` package; a virtual mock answers the handler's import. + {virtual: true}, +) + +jest.mock('pages/api/skill/[...skillRecordings]', () => ({ + paymentOptions: { + providers: { + stripe: { + paymentClient: { + invoices: {retrieve: (...args: unknown[]) => mockRetrieve(...args)}, + }, + }, + }, + }, +})) +jest.mock('@skillrecordings/database', () => ({ + prisma: { + merchantProduct: { + findFirst: (...args: unknown[]) => mockFindFirstMerchantProduct(...args), + }, + purchase: { + findFirst: (...args: unknown[]) => mockFindFirstPurchase(...args), + }, + user: { + findUniqueOrThrow: (...args: unknown[]) => + mockFindUniqueOrThrowUser(...args), + }, + }, + getSdk: () => mockSdk, +})) +jest.mock('@skillrecordings/skill-lesson/utils/sanity-client', () => ({ + sanityClient: {fetch: (...args: unknown[]) => mockSanityFetch(...args)}, +})) + +import {NonRetriableError} from 'inngest' +import {stripeInvoicePaid} from './invoice-paid' + +const handler = (stripeInvoicePaid as unknown as {handler: Function}).handler + +const CUTOVER = '2026-12-08T15:05:00Z' +const cutoverSeconds = Date.parse(CUTOVER) / 1000 + +function stripeInvoice(paidAt: number | null) { + return { + id: 'in_team_order', + status: 'paid', + subscription: null, + billing_reason: 'manual', + customer: 'cus_team_buyer', + customer_email: 'buyer@example.com', + customer_name: 'Buyer', + charge: 'ch_team_order', + amount_paid: 68000, + currency: 'usd', + status_transitions: {finalized_at: cutoverSeconds - 7200, paid_at: paidAt}, + lines: { + data: [ + { + quantity: 3, + subscription: null, + price: {product: 'prod_epic_web', recurring: null}, + }, + ], + has_more: false, + }, + } +} + +function run() { + const steps: string[] = [] + const step = { + run: async (name: string, fn: () => unknown) => { + steps.push(name) + return fn() + }, + sendEvent: jest.fn(async () => undefined), + } + const event = { + data: {type: 'invoice.paid', data: {object: {id: 'in_team_order'}}}, + } + return {steps, step, result: handler({event, step})} +} + +const env = process.env +beforeEach(() => { + jest.clearAllMocks() + process.env = {...env} + delete process.env.EPIC_WEB_INVOICE_CUTOVER_AT + jest.spyOn(console, 'info').mockImplementation(() => undefined) + jest.spyOn(console, 'error').mockImplementation(() => undefined) + mockFindFirstMerchantProduct.mockResolvedValue({ + id: 'mp_epic_web', + productId: 'product_epic_web', + merchantAccountId: 'kcd_account', + }) + mockSanityFetch.mockResolvedValue(true) + mockFindFirstPurchase.mockResolvedValue(null) + mockSdk.findOrCreateUser.mockResolvedValue({ + user: {id: 'user_buyer', email: 'buyer@example.com'}, + }) + mockSdk.findOrCreateMerchantCustomer.mockResolvedValue({id: 'mcus_1'}) + mockSdk.createMerchantChargeAndPurchase.mockResolvedValue({ + id: 'purchase_1', + userId: 'user_buyer', + productId: 'product_epic_web', + bulkCouponId: 'coupon_1', + }) + mockFindUniqueOrThrowUser.mockResolvedValue({id: 'user_buyer'}) +}) +afterAll(() => { + process.env = env +}) + +const nothingReadOrWritten = () => { + expect(mockFindFirstMerchantProduct).not.toHaveBeenCalled() + expect(mockSanityFetch).not.toHaveBeenCalled() + expect(mockFindFirstPurchase).not.toHaveBeenCalled() + expect(mockSdk.findOrCreateUser).not.toHaveBeenCalled() + expect(mockSdk.findOrCreateMerchantCustomer).not.toHaveBeenCalled() + expect(mockSdk.createMerchantChargeAndPurchase).not.toHaveBeenCalled() +} + +test('variable set, paid at or after the cutoff: ignored before any read or write', async () => { + process.env.EPIC_WEB_INVOICE_CUTOVER_AT = CUTOVER + mockRetrieve.mockResolvedValue(stripeInvoice(cutoverSeconds + 30)) + const {steps, step, result} = run() + await expect(result).resolves.toEqual({ + kind: 'ignore', + invoiceId: 'in_team_order', + reason: 'owned-by-course-builder', + paidAt: '2026-12-08T15:05:30.000Z', + cutoverAt: '2026-12-08T15:05:00.000Z', + }) + expect(steps).toEqual(['load invoice', 'decide owner']) + nothingReadOrWritten() + expect(step.sendEvent).not.toHaveBeenCalled() +}) + +test('variable set, paid before the cutoff: fulfilled as before', async () => { + process.env.EPIC_WEB_INVOICE_CUTOVER_AT = CUTOVER + mockRetrieve.mockResolvedValue(stripeInvoice(cutoverSeconds - 30)) + const {steps, step, result} = run() + await expect(result).resolves.toMatchObject({ + invoiceId: 'in_team_order', + purchaseId: 'purchase_1', + created: true, + }) + expect(steps.slice(0, 3)).toEqual([ + 'load invoice', + 'decide owner', + 'plan fulfilment', + ]) + expect(mockSdk.createMerchantChargeAndPurchase).toHaveBeenCalledTimes(1) + expect(step.sendEvent).toHaveBeenCalledTimes(1) +}) + +test('variable unset: fulfilled, whenever it was paid (inert by default)', async () => { + mockRetrieve.mockResolvedValue(stripeInvoice(cutoverSeconds + 999_999)) + const {result} = run() + await expect(result).resolves.toMatchObject({created: true}) + expect(mockSdk.createMerchantChargeAndPurchase).toHaveBeenCalledTimes(1) +}) + +test('unparseable variable: the run fails, nothing read or written', async () => { + process.env.EPIC_WEB_INVOICE_CUTOVER_AT = '2026-12-08 15:05' + mockRetrieve.mockResolvedValue(stripeInvoice(cutoverSeconds + 30)) + const {result} = run() + await expect(result).rejects.toThrow( + /EPIC_WEB_INVOICE_CUTOVER_AT must be an ISO-8601 UTC timestamp/, + ) + // retriable: a corrected variable is picked up by Inngest's retries + await expect(result).rejects.not.toBeInstanceOf(NonRetriableError) + nothingReadOrWritten() +}) + +test('paid invoice without paid_at: fails without retry, nothing read or written', async () => { + process.env.EPIC_WEB_INVOICE_CUTOVER_AT = CUTOVER + mockRetrieve.mockResolvedValue(stripeInvoice(null)) + const {result} = run() + await expect(result).rejects.toBeInstanceOf(NonRetriableError) + await expect(result).rejects.toThrow(/has no status_transitions.paid_at/) + nothingReadOrWritten() +}) diff --git a/apps/epic-web/src/inngest/functions/stripe/invoice-paid.ts b/apps/epic-web/src/inngest/functions/stripe/invoice-paid.ts index cfb5b3dc4..90634c8d8 100644 --- a/apps/epic-web/src/inngest/functions/stripe/invoice-paid.ts +++ b/apps/epic-web/src/inngest/functions/stripe/invoice-paid.ts @@ -10,7 +10,10 @@ import {NonRetriableError} from 'inngest' import groq from 'groq' import {paymentOptions} from 'pages/api/skill/[...skillRecordings]' import { + decideInvoiceOwnership, fulfilInvoice, + INVOICE_CUTOVER_ENV, + InvoiceOwnershipError, PaidInvoiceSchema, planInvoiceFulfilment, } from 'lib/invoice-fulfilment' @@ -25,6 +28,10 @@ const stripe = paymentOptions.providers.stripe?.paymentClient * Stripe sends both invoice.paid and invoice.payment_succeeded for the same * payment, so runs are keyed on the invoice id, and fulfilInvoice checks for * an existing purchase before writing anything. + * + * While Course Builder also receives these events, an invoice paid at or + * after EPIC_WEB_INVOICE_CUTOVER_AT is Course Builder's and is ignored here + * (see decideInvoiceOwnership). Unset, every invoice is fulfilled here. */ export const stripeInvoicePaid = inngest.createFunction( { @@ -48,6 +55,32 @@ export const stripeInvoicePaid = inngest.createFunction( ) }) + // Decided once per run (a step result is memoized), so a variable + // changed mid-run cannot flip the answer after a purchase is written. + const ownership = await step.run('decide owner', async () => { + try { + return decideInvoiceOwnership(invoice, process.env[INVOICE_CUTOVER_ENV]) + } catch (error) { + if (error instanceof InvoiceOwnershipError) { + console.error(error.message) + // A paid invoice without paid_at won't change on retry (the + // invoice above is memoized); a bad variable might be fixed, so + // that one is left to Inngest's retries and then fails visibly. + if (error.code === 'paid-at-missing') { + throw new NonRetriableError(error.message) + } + } + throw error + } + }) + + if (ownership.kind === 'ignore') { + console.info( + `invoice ${ownership.invoiceId} ignored: ${ownership.reason} (paid ${ownership.paidAt}, cutover ${ownership.cutoverAt})`, + ) + return ownership + } + const plan = await step.run('plan fulfilment', async () => { return planInvoiceFulfilment(invoice, { findEpicWebMerchantProduct: async (stripeProductId) => { diff --git a/apps/epic-web/src/lib/invoice-fulfilment.test.ts b/apps/epic-web/src/lib/invoice-fulfilment.test.ts index 12b50a44d..1aa4734cf 100644 --- a/apps/epic-web/src/lib/invoice-fulfilment.test.ts +++ b/apps/epic-web/src/lib/invoice-fulfilment.test.ts @@ -1,5 +1,8 @@ import { + decideInvoiceOwnership, fulfilInvoice, + PaidInvoiceSchema, + parseInvoiceCutover, type FulfilDeps, type FulfilledPurchase, type PaidInvoice, @@ -251,3 +254,147 @@ describe('invoice fulfilment', () => { expect(plan).toMatchObject({kind: 'refuse'}) }) }) + +describe('decideInvoiceOwnership', () => { + const CUTOVER = '2026-12-08T15:05:00Z' + const cutoverSeconds = Date.parse(CUTOVER) / 1000 + const paidAt = (paid_at: number | null | undefined) => + invoice({status_transitions: {paid_at}}) + + test('variable unset: legacy fulfils, paid_at not even needed', () => { + expect( + decideInvoiceOwnership(paidAt(cutoverSeconds + 60), undefined), + ).toEqual({ + kind: 'ours', + }) + expect(decideInvoiceOwnership(invoice(), undefined)).toEqual({kind: 'ours'}) + }) + + test('paid before the cutoff: legacy fulfils', () => { + expect(decideInvoiceOwnership(paidAt(cutoverSeconds - 1), CUTOVER)).toEqual( + { + kind: 'ours', + }, + ) + }) + + test('paid exactly at the cutoff: Course Builder owns it', () => { + expect(decideInvoiceOwnership(paidAt(cutoverSeconds), CUTOVER)).toEqual({ + kind: 'ignore', + invoiceId: 'in_team_order', + reason: 'owned-by-course-builder', + paidAt: '2026-12-08T15:05:00.000Z', + cutoverAt: '2026-12-08T15:05:00.000Z', + }) + }) + + test('paid after the cutoff: Course Builder owns it', () => { + expect( + decideInvoiceOwnership(paidAt(cutoverSeconds + 3600), CUTOVER), + ).toMatchObject({kind: 'ignore', reason: 'owned-by-course-builder'}) + }) + + test('a cutoff with milliseconds compares against whole-second paid_at', () => { + const at = '2026-12-08T15:05:00.500Z' + expect(decideInvoiceOwnership(paidAt(cutoverSeconds), at)).toEqual({ + kind: 'ours', + }) + expect( + decideInvoiceOwnership(paidAt(cutoverSeconds + 1), at), + ).toMatchObject({kind: 'ignore'}) + }) + + test.each([ + ['seconds', '2026-12-08T10:05:00Z', '2026-12-08T10:05:00.000Z'], + ['minutes only', '2026-12-08T10:05Z', '2026-12-08T10:05:00.000Z'], + ['milliseconds', '2026-12-08T10:05:00.250Z', '2026-12-08T10:05:00.250Z'], + [ + 'surrounding whitespace', + ' 2026-12-08T10:05:00Z ', + '2026-12-08T10:05:00.000Z', + ], + ])('accepts %s (same set as Course Builder)', (_label, raw, iso) => { + expect(parseInvoiceCutover(raw)?.toISOString()).toBe(iso) + }) + + test('unset is null (legacy owns every invoice)', () => { + expect(parseInvoiceCutover(undefined)).toBeNull() + }) + + // Course Builder's reject list, plus the forms a laxer parser would take + // (numeric zero offsets, 4-digit fractions, lowercase t/z, rollover): each + // must be an error in both apps. + test.each([ + '', + ' ', + '2026-12-08', + '2026-12-08 10:05:00', + '2026-12-08T10:05:00+01:00', + '2026-12-08T10:05:00', + '2026-02-30T10:00:00Z', + '2026-12-08T24:00:00Z', + 'tomorrow', + '1765188300', + '2026-12-08T10:05:00+00:00', + '2026-12-08T10:05:00+0000', + '2026-12-08T10:05:00.1234Z', + '2026-13-45T25:00:00Z', + '2026-12-08t10:05:00z', + ])('fails loudly on %j instead of picking a side', (raw) => { + expect(() => parseInvoiceCutover(raw)).toThrow( + expect.objectContaining({ + name: 'InvoiceOwnershipError', + code: 'invalid-cutover', + message: expect.stringMatching(/EPIC_WEB_INVOICE_CUTOVER_AT/), + }), + ) + expect(() => decideInvoiceOwnership(paidAt(cutoverSeconds), raw)).toThrow( + expect.objectContaining({code: 'invalid-cutover'}), + ) + }) + + test.each([ + ['missing status_transitions', undefined], + ['null status_transitions', null], + ['null paid_at', {paid_at: null}], + ['missing paid_at', {}], + ])( + 'a paid invoice with %s is an error, not a guess', + (_label, transitions) => { + expect(() => + decideInvoiceOwnership( + invoice({status_transitions: transitions as any}), + CUTOVER, + ), + ).toThrow( + expect.objectContaining({ + name: 'InvoiceOwnershipError', + code: 'paid-at-missing', + }), + ) + }, + ) + + test('an unpaid invoice is left to the planner (which ignores it)', () => { + expect(decideInvoiceOwnership(invoice({status: 'open'}), CUTOVER)).toEqual({ + kind: 'ours', + }) + }) + + test('the schema keeps status_transitions.paid_at from a re-fetched invoice', () => { + const parsed = PaidInvoiceSchema.parse({ + ...invoice(), + status_transitions: { + finalized_at: 1796740000, + paid_at: cutoverSeconds, + voided_at: null, + }, + }) + expect(parsed.status_transitions?.paid_at).toBe(cutoverSeconds) + // an invoice object without the field still parses (older fixtures) + const {status_transitions: _omit, ...withoutTransitions} = invoice() + expect(PaidInvoiceSchema.parse(withoutTransitions).status_transitions).toBe( + undefined, + ) + }) +}) diff --git a/apps/epic-web/src/lib/invoice-fulfilment.ts b/apps/epic-web/src/lib/invoice-fulfilment.ts index 7cc219ce3..5dcc5b1ea 100644 --- a/apps/epic-web/src/lib/invoice-fulfilment.ts +++ b/apps/epic-web/src/lib/invoice-fulfilment.ts @@ -26,6 +26,12 @@ export const PaidInvoiceSchema = z.object({ .optional(), amount_paid: z.number(), currency: z.string(), + // paid_at (Unix seconds) is set once, when the invoice is paid, and + // decides which app owns it (decideInvoiceOwnership). + status_transitions: z + .object({paid_at: z.number().nullable().optional()}) + .nullable() + .optional(), lines: z.object({ data: z.array( z.object({ @@ -46,6 +52,117 @@ export const PaidInvoiceSchema = z.object({ export type PaidInvoice = z.infer +/** + * During the move to Course Builder both apps receive every invoice event, + * and invoices are made by hand in the Stripe dashboard, so nothing on the + * invoice says which app it belongs to. Ownership is split by when it was + * paid, against one cutoff both apps carry in this variable (ISO-8601, + * UTC): paid before the cutoff, legacy fulfils it; at or after it, Course + * Builder does. Unset, legacy fulfils every invoice, as it always has. + */ +export const INVOICE_CUTOVER_ENV = 'EPIC_WEB_INVOICE_CUTOVER_AT' + +/** + * The only accepted form: `YYYY-MM-DDTHH:MM[:SS[.mmm]]Z`. It is the same + * set Course Builder's parser accepts, so one value can never be valid in + * one app and an error in the other: no numeric offsets (not even + * `+00:00`), no date-only, no epoch numbers. + */ +const ISO_UTC = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?Z$/ + +/** + * A misconfiguration that must stop fulfilment loudly rather than let this + * app silently pick a side. + */ +export class InvoiceOwnershipError extends Error { + constructor( + readonly code: 'invalid-cutover' | 'paid-at-missing', + message: string, + ) { + super(message) + this.name = 'InvoiceOwnershipError' + } +} + +/** + * The cutoff, or null when the variable is unset. Anything else that is not + * in the accepted form (an empty string included) throws, and so does an + * impossible date such as 2026-02-30 or 24:00, which Date.parse would + * otherwise roll over: a typo must not quietly hand every invoice to one + * app. + */ +export function parseInvoiceCutover(value: string | undefined): Date | null { + if (value === undefined) return null + const trimmed = value.trim() + const match = ISO_UTC.exec(trimmed) + const ms = Date.parse(trimmed) + const date = new Date(ms) + const exact = + !!match && + !Number.isNaN(ms) && + date.getUTCFullYear() === Number(match[1]) && + date.getUTCMonth() + 1 === Number(match[2]) && + date.getUTCDate() === Number(match[3]) && + date.getUTCHours() === Number(match[4]) && + date.getUTCMinutes() === Number(match[5]) && + date.getUTCSeconds() === Number(match[6] ?? 0) + if (!exact) { + throw new InvoiceOwnershipError( + 'invalid-cutover', + `${INVOICE_CUTOVER_ENV} must be an ISO-8601 UTC timestamp like 2026-12-08T10:05:00Z, got ${JSON.stringify( + value, + )}; refusing to decide invoice ownership`, + ) + } + return date +} + +export type InvoiceOwnership = + | {kind: 'ours'} + | { + kind: 'ignore' + invoiceId: string + reason: 'owned-by-course-builder' + paidAt: string + cutoverAt: string + } + +/** + * Whether this (legacy) app fulfils the invoice. Decided on the re-fetched + * invoice, before anything is written: + * - variable unset: ours (today's behaviour); + * - invoice not paid: ours to look at (planInvoiceFulfilment ignores it); + * - paid_at at or after the cutoff: owned by Course Builder, ignored; + * - paid_at before the cutoff: ours. + * A paid invoice without paid_at is not guessed about: it throws. + */ +export function decideInvoiceOwnership( + invoice: PaidInvoice, + cutoverValue: string | undefined, +): InvoiceOwnership { + const cutover = parseInvoiceCutover(cutoverValue) + if (!cutover) return {kind: 'ours'} + if (invoice.status !== 'paid') return {kind: 'ours'} + const paidAt = invoice.status_transitions?.paid_at + if (typeof paidAt !== 'number' || !Number.isFinite(paidAt)) { + throw new InvoiceOwnershipError( + 'paid-at-missing', + `invoice ${invoice.id} is paid but has no status_transitions.paid_at; cannot tell whether it belongs to legacy or Course Builder`, + ) + } + if (paidAt * 1000 >= cutover.getTime()) { + return { + kind: 'ignore', + invoiceId: invoice.id, + reason: 'owned-by-course-builder', + paidAt: new Date(paidAt * 1000).toISOString(), + cutoverAt: cutover.toISOString(), + } + } + return {kind: 'ours'} +} + export type EpicWebMerchantProduct = { id: string productId: string