All files / src/modules/users users.service.ts

90.24% Statements 74/82
82.5% Branches 33/40
100% Functions 10/10
89.74% Lines 70/78

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 27713x 13x 13x   13x     13x 19x   19x       1x                           2x                             8x 8x     8x         8x 1x       7x 7x 4x 4x     7x                             7x 7x   1x 1x               9x 9x   9x                                     9x 2x       7x               7x 7x         2x 2x               8x 8x   8x 1x       7x 7x 2x       5x 5x 1x       4x         4x         4x         4x 2x         2x 2x             6x 4x   2x 2x           1x         2x 2x               1x               5x                     5x         5x             5x 5x   5x 20x 9x   11x       5x     5x           5x                        
import { Injectable, Logger, NotFoundException, BadRequestException, ForbiddenException } from '@nestjs/common';
import { MediaService } from '@app/modules/media/media.service';
import { PrismaService } from '@app/modules/prisma/prisma.service';
import { UpdateUserDto } from '@app/modules/users/dto/update-user.dto';
import { sanitizeHtml } from '@app/utils/sanitize';
 
@Injectable()
export class UsersService {
  private readonly logger = new Logger(UsersService.name);
 
  constructor(private readonly prisma: PrismaService, private readonly media: MediaService) {}
 
  /** Return *all* users (demo only – add paging / auth in prod!) */
  findAll() {
    return this.prisma.client.user.findMany({
      select: {
        id: true,
        email: true,
        name: true,
        createdAt: true,
        updatedAt: true,
        createdById: true,
        updatedById: true,
      },
    });
  }
 
  async findOneById(id: number) {
    return this.prisma.client.user.findUnique({
      where: { id },
      select: {
        id: true,
        email: true,
        name: true,
        createdAt: true,
        updatedAt: true,
        createdById: true,
        updatedById: true,
      },
    });
  }
 
  async update(id: number, updateUserDto: UpdateUserDto) {
    try {
      this.logger.debug(`Updating user ${id}`);
 
      // Verify user exists
      const existingUser = await this.prisma.client.user.findUnique({
        where: { id },
        select: { id: true },
      });
 
      if (!existingUser) {
        throw new NotFoundException(`User #${id} not found`);
      }
 
      // Sanitize bio field if provided
      const sanitizedData = { ...updateUserDto };
      if (sanitizedData.bio) {
        sanitizedData.bio = sanitizeHtml(sanitizedData.bio);
        this.logger.debug(`Sanitized bio field for user ${id}`);
      }
 
      const updatedUser = await this.prisma.client.user.update({
        where: { id },
        data: sanitizedData,
        select: {
          id: true,
          email: true,
          name: true,
          bio: true,
          createdAt: true,
          updatedAt: true,
          createdById: true,
          updatedById: true,
        },
      });
 
      this.logger.log(`User ${id} updated successfully`);
      return updatedUser;
    } catch (error) {
      if (error instanceof NotFoundException) {
        throw error;
      }
      this.logger.error(`Error updating user ${id}:`, error);
      throw new Error('Failed to update user profile');
    }
  }
 
  async getPublicProfile(id: number) {
    try {
      this.logger.debug(`Fetching public profile for user ${id}`);
 
      const user = await this.prisma.client.user.findUnique({
        where: { id },
        select: {
          id: true,
          name: true,
          bio: true,
          role: true,
          createdAt: true,
          avatarMedia: true,
          agency: {
            select: {
              id: true,
              name: true,
              isVerified: true,
            },
          },
        },
      });
 
      if (!user) {
        throw new NotFoundException(`User #${id} not found`);
      }
 
      // Get published listings count
      const listingsCount = await this.prisma.client.listing.count({
        where: {
          userId: id,
          status: 'PUBLISHED',
          deletedAt: null,
        },
      });
 
      this.logger.debug(`Fetched public profile for user ${id}`);
      return {
        ...user,
        listingsCount,
      };
    } catch (error) {
      if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error;
      }
      this.logger.error(`Error fetching public profile for user ${id}:`, error);
      throw new Error('Failed to fetch public profile');
    }
  }
 
  async uploadAvatar(userId: number, file: any) {
    try {
      this.logger.debug(`User ${userId} uploading avatar`);
 
      if (!file) {
        throw new BadRequestException('No file provided');
      }
 
      // Validate file type - only allow images
      const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
      if (!allowedMimeTypes.includes(file.mimetype)) {
        throw new BadRequestException(`Invalid file type. Only image files are allowed (JPEG, PNG, WebP, GIF). Received: ${file.mimetype}`);
      }
 
      // Validate file size (10MB limit for images)
      const maxSize = 10 * 1024 * 1024; // 10MB
      if (file.buffer && file.buffer.length > maxSize) {
        throw new BadRequestException('File too large. Maximum size is 10MB.');
      }
 
      // Verify user exists
      const user = await this.prisma.client.user.findUnique({
        where: { id: userId },
        select: { id: true },
      });
 
      Iif (!user) {
        throw new NotFoundException(`User #${userId} not found`);
      }
 
      // Normalize Multer file shape to what MediaService expects
      const uploadFile = {
        buffer: file.buffer,
        mimetype: file.mimetype,
        originalname: file.originalname || 'avatar.png',
      };
      const media = await this.media.uploadMedia(uploadFile as any, 'IMAGE', userId);
      await this.prisma.client.user.update({
        where: { id: userId },
        data: { avatarMediaId: media.id },
      });
 
      this.logger.log(`User ${userId} uploaded avatar ${media.id}`);
      return {
        id: media.id,
        key: media.storageKey,
        avatarMediaId: media.id,
        avatarUrl: `/media/${media.storageKey}`
      };
    } catch (error) {
      if (error instanceof NotFoundException || error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error;
      }
      this.logger.error(`Error uploading avatar for user ${userId}:`, error);
      throw new Error('Failed to upload avatar');
    }
  }
 
  listNotifications(userId: number) {
    // @ts-ignore
    return this.prisma.client.notification.findMany({ where: { userId }, orderBy: { createdAt: 'desc' } });
  }
 
  async markNotificationRead(userId: number, id: number) {
    // @ts-ignore
    const n = await this.prisma.client.notification.findUnique({ where: { id } });
    if (!n || n.userId !== userId) return { ok: true };
    // @ts-ignore
    await this.prisma.client.notification.update({ where: { id }, data: { readAt: new Date() } });
    return { ok: true };
  }
 
  setNotificationPrefs(userId: number, body: any) {
    // @ts-ignore
    return this.prisma.client.notificationPreference.upsert({
      where: { userId },
      update: { channels: body.channels as any, topics: body.topics as any },
      create: { userId, channels: (body.channels || {}) as any, topics: (body.topics || null) as any },
    });
  }
 
  async getMyStats(userId: number) {
    const user = await this.prisma.client.user.findUnique({
      where: { id: userId },
      select: {
        name: true,
        phone: true,
        avatarMediaId: true,
        agencyId: true,
        email: true,
      },
    });
 
    Iif (!user) {
      return null;
    }
 
    // Calculate profile completeness
    const fieldChecks = {
      name: user.name,
      phone: user.phone,
      avatar: user.avatarMediaId,
      agency: user.agencyId,
    };
 
    const missingFields: string[] = [];
    let completedCount = 0;
 
    for (const [fieldName, value] of Object.entries(fieldChecks)) {
      if (value !== null && value !== undefined) {
        completedCount++;
      } else {
        missingFields.push(fieldName);
      }
    }
 
    const percentage = Math.round((completedCount / Object.keys(fieldChecks).length) * 100);
 
    // Get counts for various user activities
    const [listings, favorites, conversations] = await Promise.all([
      this.prisma.client.listing.count({ where: { userId } }),
      this.prisma.client.listingFavorite.count({ where: { userId } }),
      this.prisma.client.conversationParticipant.count({ where: { userId } }),
    ]);
 
    return {
      profileCompleteness: {
        percentage,
        missingFields,
      },
      activityCounts: {
        listings,
        favorites,
        conversations,
      },
    };
  }
}