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 { return this.prisma.db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } }); } async createCheckout(user: User, plan: PlanId): Promise { 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 { 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 { 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 { 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 { 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(Object.values(SubscriptionStatus)); const toStatus = (status: string): SubscriptionStatus | null => (STATUSES.has(status) ? (status as SubscriptionStatus) : null);