File size: 6,224 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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<string, unknown> = {}) => ({
  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();
    });
  });
});