File size: 4,817 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
import type { INestApplication } from '@nestjs/common';
import { api, createApp, internalToken, resetDatabase, signedStripeEvent, signIn, sql, stripeStub } from './helpers.js';

describe('Subscriptions (e2e)', () => {
  let app: INestApplication;
  let headers: Record<string, string>;
  let userId: string;
  const now = Math.floor(Date.now() / 1000);

  const stripeSubscription = (overrides: Record<string, unknown> = {}) => ({
    id: 'sub_e2e',
    status: 'active',
    customer: 'cus_e2e',
    metadata: { userId },
    cancel_at_period_end: false,
    items: { data: [{ price: { id: 'price_starter' }, current_period_start: now - 60, current_period_end: now + 30 * 86_400 }] },
    ...overrides,
  });

  const deliver = (type: string, object: object) => {
    const { payload, signature } = signedStripeEvent(type, object);
    return api(app).post('/api/webhooks/stripe').set('stripe-signature', signature).set('content-type', 'application/json').send(payload);
  };

  beforeAll(async () => {
    app = await createApp();
  });
  afterAll(() => app.close());
  beforeEach(async () => {
    await resetDatabase();
    vi.clearAllMocks();
    headers = await signIn('user_pay', 'pay@example.com');
    userId = (await api(app).get('/api/me').set(headers)).body.data.user.id;
  });

  it('opens a Stripe checkout for a plan', async () => {
    const response = await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'starter' }).expect(200);
    expect(response.body.data).toEqual({ url: 'https://checkout.stripe.test/session' });
    expect((await sql('SELECT stripe_customer_id FROM users WHERE id = $1', [userId]))[0].stripe_customer_id).toBe('cus_e2e');
    await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'platinum' }).expect(400);
  });

  it('activates the plan from a signed webhook and applies its monthly allowance', async () => {
    stripeStub.subscriptions.retrieve.mockResolvedValue(stripeSubscription());
    await deliver('checkout.session.completed', { id: 'cs_1', subscription: 'sub_e2e' }).expect(200);

    const current = await api(app).get('/api/subscriptions/current').set(headers).expect(200);
    expect(current.body.data).toMatchObject({ plan: 'starter', status: 'active', cancelAtPeriodEnd: false });
    expect((await api(app).get('/api/me').set(headers)).body.data.usage).toMatchObject({ plan: 'starter', limit: 3, used: 0, remaining: 3 });

    const token = await internalToken();
    const create = (jobId: string) => api(app).post('/internal/generations').set('Authorization', `Bearer ${token}`).send({ userId, jobId });
    for (let n = 1; n <= 3; n++) expect((await create(`job${n}`)).status).toBe(201);
    const refused = await create('job4');
    expect(refused.status).toBe(402);
    expect(refused.body.error.code).toBe('PLAN_LIMIT_REACHED');

    await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'growth' }).expect(409);
  });

  it('ends the plan when Stripe cancels the subscription', async () => {
    stripeStub.subscriptions.retrieve.mockResolvedValue(stripeSubscription());
    await deliver('customer.subscription.created', { id: 'sub_e2e' }).expect(200);
    stripeStub.subscriptions.retrieve.mockResolvedValue(stripeSubscription({ status: 'canceled' }));
    await deliver('customer.subscription.deleted', { id: 'sub_e2e' }).expect(200);
    expect((await api(app).get('/api/subscriptions/current').set(headers)).body.data).toBeNull();
    expect((await api(app).get('/api/me').set(headers)).body.data.usage.plan).toBe('free');
    expect((await sql('SELECT count(*)::int AS n FROM subscriptions'))[0].n).toBe(1);
  });

  it('refuses webhooks without a valid signature', async () => {
    const { payload } = signedStripeEvent('customer.subscription.updated', { id: 'sub_e2e' });
    const response = await api(app)
      .post('/api/webhooks/stripe')
      .set('stripe-signature', 't=1,v1=forged')
      .set('content-type', 'application/json')
      .send(payload)
      .expect(400);
    expect(response.body.error.code).toBe('INVALID_SIGNATURE');
    expect(stripeStub.subscriptions.retrieve).not.toHaveBeenCalled();
  });

  it('opens the billing portal only for customers', async () => {
    await api(app).post('/api/subscriptions/portal').set(headers).expect(404);
    await api(app).post('/api/subscriptions/checkout').set(headers).send({ plan: 'growth' });
    const portal = await api(app).post('/api/subscriptions/portal').set(headers).expect(200);
    expect(portal.body.data.url).toBe('https://billing.stripe.test/portal');
  });

  it('requires sign-in for subscription routes', async () => {
    await api(app).get('/api/subscriptions/current').expect(401);
    await api(app).post('/api/subscriptions/checkout').send({ plan: 'starter' }).expect(401);
  });
});