import { Test } from '@nestjs/testing'; import { testConfig } from '../../test/support/test-config.js'; import { APP_CONFIG } from '../config/app-config.js'; import type { User } from '../generated/prisma/client.js'; import { PrismaService } from '../prisma/prisma.service.js'; import { STRIPE_CLIENT } from '../stripe/stripe.constants.js'; import { SubscriptionsService } from './subscriptions.service.js'; const user = { id: 'u1', email: 'ann@example.com', name: 'Ann', stripeCustomerId: null } as User; const stripeSubscription = (overrides: Record = {}) => ({ id: 'sub_1', status: 'active', customer: 'cus_1', metadata: { userId: 'u1' }, cancel_at_period_end: false, items: { data: [{ price: { id: 'price_growth' }, current_period_start: 1_790_000_000, current_period_end: 1_792_592_000 }] }, ...overrides, }); describe('SubscriptionsService', () => { const db = { subscription: { findFirst: vi.fn(), upsert: vi.fn() }, user: { update: vi.fn(), findUnique: vi.fn() }, }; const stripe = { customers: { create: vi.fn() }, checkout: { sessions: { create: vi.fn() } }, billingPortal: { sessions: { create: vi.fn() } }, subscriptions: { retrieve: vi.fn() }, }; let service: SubscriptionsService; beforeEach(async () => { vi.clearAllMocks(); db.subscription.findFirst.mockResolvedValue(null); stripe.customers.create.mockResolvedValue({ id: 'cus_new' }); stripe.checkout.sessions.create.mockResolvedValue({ url: 'https://checkout.stripe.test/s' }); const moduleRef = await Test.createTestingModule({ providers: [ SubscriptionsService, { provide: PrismaService, useValue: { db } }, { provide: STRIPE_CLIENT, useValue: stripe }, { provide: APP_CONFIG, useValue: testConfig() }, ], }).compile(); service = moduleRef.get(SubscriptionsService); }); describe('createCheckout', () => { it('creates the Stripe customer once and opens a branded subscription checkout', async () => { expect(await service.createCheckout(user, 'starter')).toEqual({ url: 'https://checkout.stripe.test/s' }); expect(stripe.customers.create).toHaveBeenCalledWith( { email: 'ann@example.com', name: 'Ann', metadata: { userId: 'u1' } }, { idempotencyKey: 'customer-u1' }, ); expect(db.user.update).toHaveBeenCalledWith({ where: { id: 'u1' }, data: { stripeCustomerId: 'cus_new' } }); expect(stripe.checkout.sessions.create).toHaveBeenCalledWith( expect.objectContaining({ mode: 'subscription', adaptive_pricing: { enabled: false }, customer: 'cus_new', client_reference_id: 'u1', line_items: [{ price: 'price_starter', quantity: 1 }], subscription_data: { metadata: { userId: 'u1' } }, success_url: 'https://app.test/studio?checkout=success', cancel_url: 'https://app.test/studio?checkout=cancelled', branding_settings: expect.objectContaining({ display_name: 'Prevision', logo: { type: 'url', url: 'https://cdn.test/prevision-logo.png' } }), }), ); }); it('reuses an existing Stripe customer', async () => { await service.createCheckout({ ...user, stripeCustomerId: 'cus_1' }, 'growth'); expect(stripe.customers.create).not.toHaveBeenCalled(); expect(stripe.checkout.sessions.create).toHaveBeenCalledWith(expect.objectContaining({ customer: 'cus_1' })); }); it('refuses a second plan', async () => { db.subscription.findFirst.mockResolvedValue({ id: 's1' }); await expect(service.createCheckout(user, 'growth')).rejects.toMatchObject({ status: 409, code: 'ALREADY_SUBSCRIBED' }); }); }); describe('createPortal', () => { it('opens the billing portal for a customer', async () => { stripe.billingPortal.sessions.create.mockResolvedValue({ url: 'https://billing.stripe.test/p' }); expect(await service.createPortal({ ...user, stripeCustomerId: 'cus_1' })).toEqual({ url: 'https://billing.stripe.test/p' }); expect(stripe.billingPortal.sessions.create).toHaveBeenCalledWith({ customer: 'cus_1', return_url: 'https://app.test/studio', configuration: 'bpc_test', }); }); it('refuses accounts that never subscribed', async () => { await expect(service.createPortal(user)).rejects.toMatchObject({ status: 404, code: 'NO_SUBSCRIPTION' }); }); }); describe('syncFromStripe', () => { it('upserts the subscription with its plan and billing period', async () => { stripe.subscriptions.retrieve.mockResolvedValue(stripeSubscription()); await service.syncFromStripe('sub_1'); const data = { userId: 'u1', stripePriceId: 'price_growth', plan: 'growth', status: 'active', currentPeriodStart: new Date(1_790_000_000 * 1000), currentPeriodEnd: new Date(1_792_592_000 * 1000), cancelAtPeriodEnd: false, }; expect(db.subscription.upsert).toHaveBeenCalledWith({ where: { stripeSubscriptionId: 'sub_1' }, create: { stripeSubscriptionId: 'sub_1', ...data }, update: data, }); }); it('finds the account by Stripe customer when metadata is missing', async () => { stripe.subscriptions.retrieve.mockResolvedValue(stripeSubscription({ metadata: {} })); db.user.findUnique.mockResolvedValue({ id: 'u9' }); await service.syncFromStripe('sub_1'); expect(db.user.findUnique).toHaveBeenCalledWith({ where: { stripeCustomerId: 'cus_1' }, select: { id: true } }); expect(db.subscription.upsert).toHaveBeenCalledWith(expect.objectContaining({ update: expect.objectContaining({ userId: 'u9' }) })); }); it.each([ ['an unknown price', { items: { data: [{ price: { id: 'price_other' }, current_period_start: 1, current_period_end: 2 }] } }], ['an unknown status', { status: 'brand_new_status' }], ])('skips a subscription with %s', async (_, overrides) => { stripe.subscriptions.retrieve.mockResolvedValue(stripeSubscription(overrides)); await service.syncFromStripe('sub_1'); expect(db.subscription.upsert).not.toHaveBeenCalled(); }); }); });