All files / modules/users/services invitation.service.ts

98.8% Statements 83/84
80% Branches 20/25
100% Functions 12/12
98.76% Lines 80/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 2902x             2x 2x 2x 2x 2x 2x 2x 2x       2x 17x 17x       17x   17x   17x 17x 17x                     6x     6x       6x 1x       5x               5x 1x       4x         4x 1x     3x 1x       2x     2x 2x     2x                     2x     2x   2x   2x               2x   2x         2x             3x       3x 1x     2x 1x       1x         1x         1x     1x 1x     1x 1x   1x     1x 1x   1x   1x             3x       3x 1x     2x 1x       1x   1x             3x       3x 1x       2x 1x 1x     2x             3x                       3x 3x   3x   3x                                   2x                           3x         3x             4x                    
import {
  Injectable,
  Logger,
  NotFoundException,
  ConflictException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import * as crypto from 'crypto';
import { Invitation, InvitationStatus } from '../entities/invitation.entity';
import { User } from '../../auth/entities/user.entity';
import { Tenant } from '../../tenants/entities/tenant.entity';
import { EmailService } from '../../email/services/email.service';
import { InviteUserDto, InvitationResponseDto } from '../dto/invite-user.dto';
 
@Injectable()
export class InvitationService {
  private readonly logger = new Logger(InvitationService.name);
  private readonly invitationExpirationDays = 7;
 
  constructor(
    @InjectRepository(Invitation)
    private readonly invitationRepository: Repository<Invitation>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Tenant)
    private readonly tenantRepository: Repository<Tenant>,
    private readonly emailService: EmailService,
    private readonly configService: ConfigService,
  ) {}
 
  /**
   * Send an invitation to join the tenant
   */
  async invite(
    dto: InviteUserDto,
    inviterId: string,
    tenantId: string,
  ): Promise<InvitationResponseDto> {
    const email = dto.email.toLowerCase().trim();
 
    // Check if user already exists in this tenant
    const existingUser = await this.userRepository.findOne({
      where: { email, tenant_id: tenantId },
    });
 
    if (existingUser) {
      throw new ConflictException('Este email ya está registrado en la organización');
    }
 
    // Check if there's already a pending invitation for this email
    const existingInvitation = await this.invitationRepository.findOne({
      where: {
        email,
        tenant_id: tenantId,
        status: 'pending' as InvitationStatus,
      },
    });
 
    if (existingInvitation) {
      throw new ConflictException('Ya existe una invitación pendiente para este email');
    }
 
    // Get inviter and tenant info for the email
    const [inviter, tenant] = await Promise.all([
      this.userRepository.findOne({ where: { id: inviterId } }),
      this.tenantRepository.findOne({ where: { id: tenantId } }),
    ]);
 
    if (!inviter) {
      throw new NotFoundException('Usuario invitador no encontrado');
    }
 
    if (!tenant) {
      throw new NotFoundException('Organización no encontrada');
    }
 
    // Generate secure token
    const token = this.generateSecureToken();
 
    // Calculate expiration date
    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + this.invitationExpirationDays);
 
    // Create invitation record
    const invitation = this.invitationRepository.create({
      tenant_id: tenantId,
      email,
      token,
      status: 'pending' as InvitationStatus,
      expires_at: expiresAt,
      created_by: inviterId,
      message: dto.message || null,
      metadata: { role: dto.role },
    });
 
    await this.invitationRepository.save(invitation);
 
    // Send invitation email
    await this.sendInvitationEmail(invitation, inviter, tenant, dto.role);
 
    this.logger.log(`Invitation sent to ${email} for tenant ${tenant.name}`);
 
    return this.toResponseDto(invitation, dto.role);
  }
 
  /**
   * List all invitations for a tenant
   */
  async findAllByTenant(tenantId: string): Promise<InvitationResponseDto[]> {
    // First, update any expired invitations
    await this.expireOldInvitations(tenantId);
 
    const invitations = await this.invitationRepository.find({
      where: { tenant_id: tenantId },
      order: { created_at: 'DESC' },
    });
 
    return invitations.map((inv) => this.toResponseDto(inv, inv.metadata?.role || 'member'));
  }
 
  /**
   * Resend an invitation email
   */
  async resend(token: string, inviterId: string, tenantId: string): Promise<InvitationResponseDto> {
    const invitation = await this.invitationRepository.findOne({
      where: { token, tenant_id: tenantId },
    });
 
    if (!invitation) {
      throw new NotFoundException('Invitación no encontrada');
    }
 
    if (invitation.status !== 'pending') {
      throw new BadRequestException('Solo se pueden reenviar invitaciones pendientes');
    }
 
    // Get inviter and tenant info
    const [inviter, tenant] = await Promise.all([
      this.userRepository.findOne({ where: { id: inviterId } }),
      this.tenantRepository.findOne({ where: { id: tenantId } }),
    ]);
 
    Iif (!inviter || !tenant) {
      throw new NotFoundException('Usuario o organización no encontrada');
    }
 
    // Generate new token
    const newToken = this.generateSecureToken();
 
    // Reset expiration
    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + this.invitationExpirationDays);
 
    // Update invitation
    invitation.token = newToken;
    invitation.expires_at = expiresAt;
 
    await this.invitationRepository.save(invitation);
 
    // Resend email
    const role = invitation.metadata?.role || 'member';
    await this.sendInvitationEmail(invitation, inviter, tenant, role);
 
    this.logger.log(`Invitation resent to ${invitation.email}`);
 
    return this.toResponseDto(invitation, role);
  }
 
  /**
   * Cancel a pending invitation
   */
  async cancel(id: string, tenantId: string): Promise<void> {
    const invitation = await this.invitationRepository.findOne({
      where: { id, tenant_id: tenantId },
    });
 
    if (!invitation) {
      throw new NotFoundException('Invitación no encontrada');
    }
 
    if (invitation.status !== 'pending') {
      throw new BadRequestException('Solo se pueden cancelar invitaciones pendientes');
    }
 
    // Hard delete the invitation
    await this.invitationRepository.remove(invitation);
 
    this.logger.log(`Invitation ${id} cancelled for ${invitation.email}`);
  }
 
  /**
   * Find invitation by token (for accepting invitations)
   */
  async findByToken(token: string): Promise<Invitation | null> {
    const invitation = await this.invitationRepository.findOne({
      where: { token },
    });
 
    if (!invitation) {
      return null;
    }
 
    // Check if expired
    if (invitation.expires_at < new Date() && invitation.status === 'pending') {
      invitation.status = 'expired';
      await this.invitationRepository.save(invitation);
    }
 
    return invitation;
  }
 
  /**
   * Generate a cryptographically secure token
   */
  private generateSecureToken(): string {
    return crypto.randomBytes(32).toString('hex');
  }
 
  /**
   * Send invitation email
   */
  private async sendInvitationEmail(
    invitation: Invitation,
    inviter: User,
    tenant: Tenant,
    role: string,
  ): Promise<void> {
    const appUrl = this.configService.get<string>('APP_URL', 'http://localhost:3000');
    const inviteUrl = `${appUrl}/invite/${invitation.token}`;
 
    const expiresIn = `${this.invitationExpirationDays} días`;
 
    await this.emailService.sendTemplateEmail({
      to: { email: invitation.email },
      templateKey: 'invitation',
      variables: {
        inviterName: inviter.fullName || inviter.email,
        tenantName: tenant.name,
        role: this.translateRole(role),
        inviteLink: inviteUrl,
        expiresIn,
        appName: this.configService.get<string>('APP_NAME', 'Template SaaS'),
      },
    });
  }
 
  /**
   * Update expired invitations status
   */
  private async expireOldInvitations(tenantId: string): Promise<void> {
    await this.invitationRepository
      .createQueryBuilder()
      .update(Invitation)
      .set({ status: 'expired' as InvitationStatus })
      .where('tenant_id = :tenantId', { tenantId })
      .andWhere('status = :status', { status: 'pending' })
      .andWhere('expires_at < NOW()')
      .execute();
  }
 
  /**
   * Translate role for display
   */
  private translateRole(role: string): string {
    const translations: Record<string, string> = {
      admin: 'Administrador',
      member: 'Miembro',
      viewer: 'Visor',
    };
    return translations[role] || role;
  }
 
  /**
   * Convert invitation to response DTO
   */
  private toResponseDto(invitation: Invitation, role: string): InvitationResponseDto {
    return {
      id: invitation.id,
      email: invitation.email,
      role,
      status: invitation.status,
      expires_at: invitation.expires_at,
      created_at: invitation.created_at,
    };
  }
}