File size: 5,623 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
import { Inject, Injectable, Logger } from '@nestjs/common';
import type Stripe from 'stripe';
import { AppException } from '../common/exceptions/app.exception.js';
import { APP_CONFIG } from '../config/app-config.js';
import type { AppConfig, PlanId } from '../config/app-config.interface.js';
import { SubscriptionStatus, type Subscription, type User } from '../generated/prisma/client.js';
import { PrismaService } from '../prisma/prisma.service.js';
import { STRIPE_CLIENT } from '../stripe/stripe.constants.js';
import { activeSubscriptionWhere } from './active-subscription.js';
import type { RedirectUrlDto } from './dto/redirect-url.dto.js';

@Injectable()
export class SubscriptionsService {
  private readonly logger = new Logger(SubscriptionsService.name);

  constructor(
    private readonly prisma: PrismaService,
    @Inject(STRIPE_CLIENT) private readonly stripe: Stripe,
    @Inject(APP_CONFIG) private readonly config: AppConfig,
  ) {}

  current(userId: string): Promise<Subscription | null> {
    return this.prisma.db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } });
  }

  async createCheckout(user: User, plan: PlanId): Promise<RedirectUrlDto> {
    if (await this.current(user.id)) {
      throw new AppException(409, 'ALREADY_SUBSCRIBED', 'You already have a plan. Manage it from your account.');
    }
    const { stripe: stripeConfig, appUrl } = this.config;
    const session = await this.stripe.checkout.sessions.create({
      mode: 'subscription',
      customer: await this.customerFor(user),
      client_reference_id: user.id,
      line_items: [{ price: stripeConfig.plans[plan].priceId, quantity: 1 }],
      subscription_data: { metadata: { userId: user.id } },
      allow_promotion_codes: true,
      // Prices are in US dollars; don't convert them to the visitor's local currency.
      adaptive_pricing: { enabled: false },
      success_url: `${appUrl}/studio?checkout=success`,
      cancel_url: `${appUrl}/studio?checkout=cancelled`,
      branding_settings: {
        display_name: 'Prevision',
        button_color: '#4263eb',
        background_color: '#f6f6f4',
        border_style: 'rounded',
        font_family: 'inter',
        ...(stripeConfig.logoUrl && { logo: { type: 'url', url: stripeConfig.logoUrl } }),
      },
    });
    if (!session.url) throw new AppException(502, 'CHECKOUT_UNAVAILABLE', 'Checkout is unavailable. Please try again.');
    return { url: session.url };
  }

  async createPortal(user: User): Promise<RedirectUrlDto> {
    if (!user.stripeCustomerId) throw new AppException(404, 'NO_SUBSCRIPTION', 'You have no plan to manage yet.');
    const session = await this.stripe.billingPortal.sessions.create({
      customer: user.stripeCustomerId,
      return_url: `${this.config.appUrl}/studio`,
      configuration: this.config.stripe.portalConfigurationId,
    });
    return { url: session.url };
  }

  /** Copies a subscription's current state from Stripe. Safe to repeat and to receive out of order. */
  async syncFromStripe(stripeSubscriptionId: string): Promise<void> {
    const subscription = await this.stripe.subscriptions.retrieve(stripeSubscriptionId);
    const userId = await this.userIdFor(subscription);
    if (!userId) {
      this.logger.warn(`No account for Stripe subscription ${subscription.id}`);
      return;
    }
    const item = subscription.items.data[0];
    const plan = this.planFor(item.price.id);
    if (!plan) {
      this.logger.warn(`Stripe subscription ${subscription.id} uses an unknown price ${item.price.id}`);
      return;
    }
    const status = toStatus(subscription.status);
    if (!status) {
      this.logger.warn(`Stripe subscription ${subscription.id} has an unknown status ${subscription.status}`);
      return;
    }
    const data = {
      userId,
      stripePriceId: item.price.id,
      plan,
      status,
      currentPeriodStart: new Date(item.current_period_start * 1000),
      currentPeriodEnd: new Date(item.current_period_end * 1000),
      cancelAtPeriodEnd: subscription.cancel_at_period_end,
    };
    await this.prisma.db.subscription.upsert({
      where: { stripeSubscriptionId: subscription.id },
      create: { stripeSubscriptionId: subscription.id, ...data },
      update: data,
    });
  }

  private async customerFor(user: User): Promise<string> {
    if (user.stripeCustomerId) return user.stripeCustomerId;
    const customer = await this.stripe.customers.create(
      { email: user.email, name: user.name ?? undefined, metadata: { userId: user.id } },
      { idempotencyKey: `customer-${user.id}` },
    );
    await this.prisma.db.user.update({ where: { id: user.id }, data: { stripeCustomerId: customer.id } });
    return customer.id;
  }

  private async userIdFor(subscription: Stripe.Subscription): Promise<string | null> {
    if (subscription.metadata.userId) return subscription.metadata.userId;
    const customerId = typeof subscription.customer === 'string' ? subscription.customer : subscription.customer.id;
    const user = await this.prisma.db.user.findUnique({ where: { stripeCustomerId: customerId }, select: { id: true } });
    return user?.id ?? null;
  }

  private planFor(priceId: string): PlanId | null {
    const entry = Object.entries(this.config.stripe.plans).find(([, plan]) => plan.priceId === priceId);
    return (entry?.[0] as PlanId | undefined) ?? null;
  }
}

const STATUSES = new Set<string>(Object.values(SubscriptionStatus));
const toStatus = (status: string): SubscriptionStatus | null => (STATUSES.has(status) ? (status as SubscriptionStatus) : null);