All files / modules/users users.service.ts

100% Statements 25/25
100% Branches 3/3
100% Functions 5/5
100% Lines 23/23

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 722x 2x 2x 2x     2x     13x               4x             4x                 3x       3x 2x     1x       6x       6x 1x       5x 5x 25x 6x       5x   5x       8x 8x      
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../auth/entities/user.entity';
 
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}
 
  async findAllByTenant(
    tenantId: string,
    page: number,
    limit: number,
  ): Promise<{ data: Partial<User>[]; total: number; page: number; limit: number }> {
    const [users, total] = await this.userRepository.findAndCount({
      where: { tenant_id: tenantId },
      skip: (page - 1) * limit,
      take: limit,
      order: { created_at: 'DESC' },
    });
 
    return {
      data: users.map(this.sanitizeUser),
      total,
      page,
      limit,
    };
  }
 
  async findOne(id: string, tenantId: string): Promise<Partial<User>> {
    const user = await this.userRepository.findOne({
      where: { id, tenant_id: tenantId },
    });
 
    if (!user) {
      throw new NotFoundException('Usuario no encontrado');
    }
 
    return this.sanitizeUser(user);
  }
 
  async update(id: string, updateDto: any, tenantId: string): Promise<Partial<User>> {
    const user = await this.userRepository.findOne({
      where: { id, tenant_id: tenantId },
    });
 
    if (!user) {
      throw new NotFoundException('Usuario no encontrado');
    }
 
    // Update allowed fields
    const allowedFields = ['first_name', 'last_name', 'phone', 'avatar_url', 'metadata'];
    for (const field of allowedFields) {
      if (updateDto[field] !== undefined) {
        (user as any)[field] = updateDto[field];
      }
    }
 
    await this.userRepository.save(user);
 
    return this.sanitizeUser(user);
  }
 
  private sanitizeUser(user: User): Partial<User> {
    const { password_hash, ...sanitized } = user;
    return sanitized;
  }
}