import { randomUUID } from 'node:crypto' import { type CreateInvitationResult, Failure, Ok, type ProblemDetails, problems, type Result, } from '@superlist/shared' import { invitationEmail } from '@/lib/emails/invitation' import { logger } from '@/lib/logger' import { type Email, sendEmail } from '@/lib/mailer' import type { Database } from '@/lib/prisma' import { invitationUrl } from '@/lib/web-app-url' /** Invitations expire after seven days. */ const INVITATION_TTL_MS = 7 * 24 * 60 * 60 * 1000 type Mailer = (email: Email) => Promise type CreateInvitationDependencies = { mailer?: Mailer now?: () => Date generateToken?: () => string } /** * Invites an email address to collaborate on a list. * * - If the email already has an account, membership is granted immediately so * the list shows up the next time they sign in. * - Otherwise a `pending` invitation is stored and the accept link is emailed. */ export class CreateInvitation { private readonly mailer: Mailer private readonly now: () => Date private readonly generateToken: () => string constructor( private readonly db: Database, dependencies: CreateInvitationDependencies = {}, ) { this.mailer = dependencies.mailer ?? sendEmail this.now = dependencies.now ?? (() => new Date()) this.generateToken = dependencies.generateToken ?? (() => randomUUID()) } async execute(input: { listId: string email: string invitedById: string }): Promise> { const email = input.email.trim().toLowerCase() const inviterMembership = await this.db.shoppingListMember.findUnique({ where: { listId_userId: { listId: input.listId, userId: input.invitedById } }, }) if (!inviterMembership) { return Failure(problems.notFound('La lista no existe o no tienes acceso.')) } if (inviterMembership.role !== 'owner') { return Failure(problems.forbidden('Solo el propietario puede invitar colaboradores.')) } const list = await this.db.shoppingList.findUnique({ where: { id: input.listId }, select: { id: true, name: true }, }) if (!list) { return Failure(problems.notFound('La lista no existe o no tienes acceso.')) } const invitedUser = await this.db.user.findUnique({ where: { email } }) if (invitedUser) { const alreadyMember = await this.db.shoppingListMember.findUnique({ where: { listId_userId: { listId: input.listId, userId: invitedUser.id } }, }) if (alreadyMember) { return Failure(problems.conflict('Esa persona ya colabora en la lista.')) } } else { const pending = await this.db.shoppingListInvitation.findFirst({ where: { listId: input.listId, email, status: 'pending' }, }) if (pending) { return Failure(problems.conflict('Ya hay una invitación pendiente para ese correo.')) } } const token = this.generateToken() const invitation = await this.db.shoppingListInvitation.create({ data: { listId: input.listId, email, token, invitedById: input.invitedById, expiresAt: new Date(this.now().getTime() + INVITATION_TTL_MS), status: invitedUser ? 'accepted' : 'pending', acceptedAt: invitedUser ? this.now() : null, }, }) if (invitedUser) { await this.db.shoppingListMember.create({ data: { listId: input.listId, userId: invitedUser.id, role: 'collaborator' }, }) } const inviter = await this.db.user.findUnique({ where: { id: input.invitedById }, select: { name: true }, }) const message = { to: email, ...invitationEmail({ inviterName: inviter?.name ?? 'Alguien', listName: list.name, acceptUrl: invitationUrl(token), }), } if (invitedUser) { // Best effort: the person already sees the list, so a mail failure is not fatal. await this.mailer(message).catch((error: unknown) => { logger.warn({ err: error, to: email }, 'could not send the invitation email') }) return Ok({ status: 'added', email }) } try { await this.mailer(message) } catch (error) { // Without the email the invitee cannot know about the list: undo everything. await this.db.shoppingListInvitation.delete({ where: { id: invitation.id } }) logger.error({ err: error, to: email }, 'failed to send the invitation email') return Failure( problems.unavailable('No pudimos enviar la invitación por correo. Inténtalo de nuevo.'), ) } return Ok({ status: 'invited', email }) } }