# Code coverage report for modules/notifications/services/devices.service.ts

# All files / modules/notifications/services devices.service.ts

77.77% Statements 42/54
39.13% Branches 9/23
83.33% Functions 10/12
76.92% Lines 40/52

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
    1881x

    1x
    1x
    1x

    1x
    14x

    14x

    2x

    1x

    4x

    4x
    2x

    2x

    2x

    2x

    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    1x

    1x

    1x
    1x

    1x

    2x

    1x
    1x

    1x

    2x

    2x
    1x

    1x

    1x

    1x

    1x

    1x

     import {
      Injectable,
      Logger,
      NotFoundException,
      ConflictException,
    } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { UserDevice } from '../entities';
    import { RegisterDeviceDto, UpdateDeviceDto } from '../dto';

    @Injectable()
    export class DevicesService {
      private readonly logger = new Logger(DevicesService.name);

      constructor(
        @InjectRepository(UserDevice)
        private readonly deviceRepository: Repository<UserDevice>,
      ) {}

      async findByUser(userId: string, tenantId: string): Promise<UserDevice[]> {
        return this.deviceRepository.find({
          where: { user_id: userId, tenant_id: tenantId },
          order: { last_used_at: 'DESC' },
        });
      }

      async findActiveByUser(userId: string, tenantId: string): Promise<UserDevice[]> {
        return this.deviceRepository.find({
          where: { user_id: userId, tenant_id: tenantId, is_active: true },
          order: { last_used_at: 'DESC' },
        });
      }

      async findById(
        deviceId: string,
        userId: string,
        tenantId: string,
      ): Promise<UserDevice> {
        const device = await this.deviceRepository.findOne({
          where: { id: deviceId, user_id: userId, tenant_id: tenantId },
        });

        if (!device) {
          throw new NotFoundException('Dispositivo no encontrado');
        }

        return device;
      }

      async register(
        userId: string,
        tenantId: string,
        dto: RegisterDeviceDto,
      ): Promise<UserDevice> {
        // Check if device already exists
        const existing = await this.deviceRepository.findOne({
          where: {
            user_id: userId,
            device_token: dto.deviceToken,
          },
        });

        if (existing) {
          // Update existing device
          existing.is_active = true;
          existing.last_used_at = new Date();
          existing.device_name = dto.deviceName || existing.device_name;
          existing.browser = dto.browser || existing.browser;
          existing.browser_version = dto.browserVersion || existing.browser_version;
          existing.os = dto.os || existing.os;
          existing.os_version = dto.osVersion || existing.os_version;

          this.logger.log(`Device ${existing.id} reactivated for user ${userId}`);
          return this.deviceRepository.save(existing);
        }

        // Create new device
        const device = this.deviceRepository.create({
          user_id: userId,
          tenant_id: tenantId,
          device_token: dto.deviceToken,
          device_type: dto.deviceType || 'web',
          device_name: dto.deviceName,
          browser: dto.browser,
          browser_version: dto.browserVersion,
          os: dto.os,
          os_version: dto.osVersion,
          is_active: true,
          last_used_at: new Date(),
        });

        const saved = await this.deviceRepository.save(device);
        this.logger.log(`Device ${saved.id} registered for user ${userId}`);

        return saved;
      }

      async update(
        deviceId: string,
        userId: string,
        tenantId: string,
        dto: UpdateDeviceDto,
      ): Promise<UserDevice> {
        const device = await this.findById(deviceId, userId, tenantId);

        Iif (dto.deviceName !== undefined) {
          device.device_name = dto.deviceName;
        }

        Iif (dto.isActive !== undefined) {
          device.is_active = dto.isActive;
        }

        return this.deviceRepository.save(device);
      }

      async unregister(
        deviceId: string,
        userId: string,
        tenantId: string,
      ): Promise<void> {
        const device = await this.findById(deviceId, userId, tenantId);

        // Soft delete - mark as inactive
        device.is_active = false;
        await this.deviceRepository.save(device);

        this.logger.log(`Device ${deviceId} unregistered for user ${userId}`);
      }

      async delete(
        deviceId: string,
        userId: string,
        tenantId: string,
      ): Promise<void> {
        const result = await this.deviceRepository.delete({
          id: deviceId,
          user_id: userId,
          tenant_id: tenantId,
        });

        if (result.affected === 0) {
          throw new NotFoundException('Dispositivo no encontrado');
        }

        this.logger.log(`Device ${deviceId} deleted for user ${userId}`);
      }

      async markAsUsed(deviceId: string): Promise<void> {
        await this.deviceRepository.update(deviceId, {
          last_used_at: new Date(),
        });
      }

      async markAsInactive(deviceId: string): Promise<void> {
        await this.deviceRepository.update(deviceId, {
          is_active: false,
        });

        this.logger.warn(`Device ${deviceId} marked as inactive (subscription expired)`);
      }

      async countActiveDevices(userId: string, tenantId: string): Promise<number> {
        return this.deviceRepository.count({
          where: { user_id: userId, tenant_id: tenantId, is_active: true },
        });
      }

      async cleanupInactiveDevices(daysInactive: number = 90): Promise<number> {
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - daysInactive);

        const result = await this.deviceRepository
          .createQueryBuilder()
          .delete()
          .where('is_active = :inactive', { inactive: false })
          .andWhere('last_used_at < :cutoff', { cutoff: cutoffDate })
          .execute();

        Iif (result.affected && result.affected > 0) {
          this.logger.log(`Cleaned up ${result.affected} inactive devices`);
        }

        return result.affected || 0;
      }
    }