import { Injectable } from '@nestjs/common'; import { ClerkService } from '../clerk/clerk.service.js'; import { AppException } from '../common/exceptions/app.exception.js'; import { Prisma, type User, type UserRole } from '../generated/prisma/client.js'; import { PrismaService } from '../prisma/prisma.service.js'; @Injectable() export class UsersService { constructor( private readonly prisma: PrismaService, private readonly clerk: ClerkService, ) {} /** * The account behind a Clerk user, created on first sign-in. Matched by Clerk id, * then by verified email, so a recreated Clerk account keeps its account and usage. */ async findOrCreateFromClerk(clerkUserId: string): Promise { const existing = await this.prisma.db.user.findUnique({ where: { clerkUserId } }); if (existing) return existing; const { email, name } = await this.clerk.getVerifiedProfile(clerkUserId); try { return await this.prisma.db.$transaction(async (tx) => { const byEmail = await tx.user.findUnique({ where: { email } }); if (byEmail) return tx.user.update({ where: { id: byEmail.id }, data: { clerkUserId, name: byEmail.name ?? name } }); if (await tx.user.count({ where: { email, deletedAt: { not: null } } })) { throw new AppException(403, 'ACCOUNT_DISABLED', 'This account has been closed. Please contact us.'); } return tx.user.create({ data: { clerkUserId, email, name } }); }); } catch (error) { const raced = error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002'; const winner = raced ? await this.prisma.db.user.findUnique({ where: { clerkUserId } }) : null; if (winner) return winner; throw error; } } /** Accounts are created by signing in; this only changes the role of an existing one. */ async setRole(email: string, role: UserRole): Promise { const user = await this.prisma.db.user.findUnique({ where: { email: email.trim().toLowerCase() } }); if (!user) throw new AppException(404, 'USER_NOT_FOUND', `No account for ${email}. Sign in to Prevision once first.`); return this.prisma.db.user.update({ where: { id: user.id }, data: { role } }); } }