import { Inject, Injectable } from '@nestjs/common'; import { AppException } from '../common/exceptions/app.exception.js'; import { APP_CONFIG } from '../config/app-config.js'; import type { AppConfig } from '../config/app-config.interface.js'; import type { Prisma, User, UserRole } from '../generated/prisma/client.js'; import { PrismaService } from '../prisma/prisma.service.js'; import { activeSubscriptionWhere } from '../subscriptions/active-subscription.js'; import { allowanceFor } from './allowance.js'; import type { GenerationCreatedDto } from './dto/generation-created.dto.js'; import type { UsageDto } from './dto/usage.dto.js'; import type { Allowance } from './interfaces/allowance.interface.js'; type Db = Pick; @Injectable() export class GenerationsService { constructor( private readonly prisma: PrismaService, @Inject(APP_CONFIG) private readonly config: AppConfig, ) {} async usage(user: Pick): Promise { const allowance = await this.allowance(this.prisma.db, user.id, user.role); return this.toUsage(allowance, await this.used(this.prisma.db, user.id, allowance)); } /** * Records a job the renderer is about to accept, against the user's allowance. * The user row lock serializes concurrent jobs, so the limit can't be passed. */ async create(userId: string, jobId: string): Promise { return this.prisma.db.$transaction(async (tx) => { const [user] = await tx.$queryRaw<{ role: UserRole }[]>` SELECT role FROM users WHERE id = ${userId}::uuid AND deleted_at IS NULL FOR UPDATE`; if (!user) throw new AppException(403, 'FORBIDDEN', 'This account cannot create visualizations.'); const allowance = await this.allowance(tx, userId, user.role); const used = await this.used(tx, userId, allowance); if (allowance.limit !== null && used >= allowance.limit) throw limitReached(allowance); const generation = await tx.generation.create({ data: { userId, jobId } }); return { generationId: generation.id, usage: this.toUsage(allowance, used + 1) }; }); } /** Gives the try back after a failed job. Repeating it changes nothing. */ async refund(generationId: string): Promise { await this.prisma.db.generation.updateMany({ where: { id: generationId, refundedAt: null }, data: { refundedAt: new Date() }, }); } private async allowance(db: Db, userId: string, role: UserRole): Promise { const subscription = await db.subscription.findFirst({ where: activeSubscriptionWhere(userId), orderBy: { currentPeriodEnd: 'desc' } }); return allowanceFor(role, subscription, this.config); } private used(db: Db, userId: string, allowance: Allowance): Promise { const where: Prisma.GenerationWhereInput = { userId, refundedAt: null }; if (allowance.countFrom) where.createdAt = { gte: allowance.countFrom }; return db.generation.count({ where }); } private toUsage({ plan, limit, renewsAt }: Allowance, used: number): UsageDto { return { plan, limit, used, remaining: limit === null ? null : Math.max(0, limit - used), renewsAt }; } } const limitReached = (allowance: Allowance) => allowance.plan === 'free' ? new AppException(402, 'NO_FREE_TRIES', "You've used all your free visualizations.") : new AppException(402, 'PLAN_LIMIT_REACHED', "You've used this month's visualizations. They renew with your plan.");