# All files / modules/audit/services audit.service.ts

90.27% Statements 65/72
74.19% Branches 23/31
100% Functions 13/13
89.7% Lines 61/68

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
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    3212x
    2x
    2x
    2x
    2x

    2x

    23x

    23x

    4x

    4x

    4x

    6x

    6x

    6x
    1x

    6x
    1x

    6x
    1x

    6x

    6x
    1x

    5x

    5x

    6x

    6x

    6x

    2x

    2x

    2x

    2x

    3x

    3x

    3x

    3x
    1x

    3x
    1x

    3x

    3x

    3x

    3x

    3x

    3x

    2x
    2x

    2x

    2x

    2x
    2x

    2x

    2x

    3x

    2x

    4x

    1x
    1x

    1x
    2x
    1x

    1x

     import { Injectable } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository, Between, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
    import { AuditLog, AuditAction } from '../entities/audit-log.entity';
    import { ActivityLog, ActivityType } from '../entities/activity-log.entity';
    import { QueryAuditLogsDto } from '../dto/query-audit.dto';
    import { QueryActivityLogsDto } from '../dto/query-activity.dto';
    import { CreateActivityLogDto } from '../dto/create-activity.dto';

    export interface CreateAuditLogParams {
      tenant_id: string;
      user_id?: string;
      action: AuditAction;
      entity_type: string;
      entity_id?: string;
      old_values?: Record<string, any>;
      new_values?: Record<string, any>;
      ip_address?: string;
      user_agent?: string;
      endpoint?: string;
      http_method?: string;
      response_status?: number;
      duration_ms?: number;
      description?: string;
      metadata?: Record<string, any>;
    }

    export interface PaginatedResult<T> {
      data: T[];
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    }

    @Injectable()
    export class AuditService {
      constructor(
        @InjectRepository(AuditLog)
        private readonly auditLogRepository: Repository<AuditLog>,
        @InjectRepository(ActivityLog)
        private readonly activityLogRepository: Repository<ActivityLog>,
      ) {}

      /**
       * Create an audit log entry
       */
      async createAuditLog(params: CreateAuditLogParams): Promise<AuditLog> {
        const changedFields = this.detectChangedFields(
          params.old_values,
          params.new_values,
        );

        const auditLog = this.auditLogRepository.create({
          ...params,
          changed_fields: changedFields,
        });

        return this.auditLogRepository.save(auditLog);
      }

      /**
       * Query audit logs with filters and pagination
       */
      async queryAuditLogs(
        tenantId: string,
        query: QueryAuditLogsDto,
      ): Promise<PaginatedResult<AuditLog>> {
        const { user_id, action, entity_type, entity_id, from_date, to_date, page = 1, limit = 20 } = query;

        const queryBuilder = this.auditLogRepository
          .createQueryBuilder('audit')
          .where('audit.tenant_id = :tenantId', { tenantId });

        if (user_id) {
          queryBuilder.andWhere('audit.user_id = :user_id', { user_id });
        }

        if (action) {
          queryBuilder.andWhere('audit.action = :action', { action });
        }

        if (entity_type) {
          queryBuilder.andWhere('audit.entity_type = :entity_type', { entity_type });
        }

        Iif (entity_id) {
          queryBuilder.andWhere('audit.entity_id = :entity_id', { entity_id });
        }

        if (from_date && to_date) {
          queryBuilder.andWhere('audit.created_at BETWEEN :from_date AND :to_date', {
            from_date,
            to_date,
          });
        } else Iif (from_date) {
          queryBuilder.andWhere('audit.created_at >= :from_date', { from_date });
        } else Iif (to_date) {
          queryBuilder.andWhere('audit.created_at <= :to_date', { to_date });
        }

        queryBuilder
          .orderBy('audit.created_at', 'DESC')
          .skip((page - 1) * limit)
          .take(limit);

        const [data, total] = await queryBuilder.getManyAndCount();

        return {
          data,
          total,
          page,
          limit,
          totalPages: Math.ceil(total / limit),
        };
      }

      /**
       * Get audit log by ID
       */
      async getAuditLogById(tenantId: string, id: string): Promise<AuditLog | null> {
        return this.auditLogRepository.findOne({
          where: { id, tenant_id: tenantId },
        });
      }

      /**
       * Get audit logs for a specific entity
       */
      async getEntityAuditHistory(
        tenantId: string,
        entityType: string,
        entityId: string,
      ): Promise<AuditLog[]> {
        return this.auditLogRepository.find({
          where: {
            tenant_id: tenantId,
            entity_type: entityType,
            entity_id: entityId,
          },
          order: { created_at: 'DESC' },
        });
      }

      /**
       * Create an activity log entry
       */
      async createActivityLog(
        tenantId: string,
        userId: string,
        dto: CreateActivityLogDto,
        context?: { ip_address?: string; user_agent?: string; session_id?: string },
      ): Promise<ActivityLog> {
        const activityLog = this.activityLogRepository.create({
          tenant_id: tenantId,
          user_id: userId,
          ...dto,
          ip_address: context?.ip_address,
          user_agent: context?.user_agent,
          session_id: context?.session_id,
        });

        return this.activityLogRepository.save(activityLog);
      }

      /**
       * Query activity logs with filters and pagination
       */
      async queryActivityLogs(
        tenantId: string,
        query: QueryActivityLogsDto,
      ): Promise<PaginatedResult<ActivityLog>> {
        const { user_id, activity_type, resource_type, from_date, to_date, page = 1, limit = 20 } = query;

        const queryBuilder = this.activityLogRepository
          .createQueryBuilder('activity')
          .where('activity.tenant_id = :tenantId', { tenantId });

        Iif (user_id) {
          queryBuilder.andWhere('activity.user_id = :user_id', { user_id });
        }

        if (activity_type) {
          queryBuilder.andWhere('activity.activity_type = :activity_type', { activity_type });
        }

        if (resource_type) {
          queryBuilder.andWhere('activity.resource_type = :resource_type', { resource_type });
        }

        Iif (from_date && to_date) {
          queryBuilder.andWhere('activity.created_at BETWEEN :from_date AND :to_date', {
            from_date,
            to_date,
          });
        } else Iif (from_date) {
          queryBuilder.andWhere('activity.created_at >= :from_date', { from_date });
        } else Iif (to_date) {
          queryBuilder.andWhere('activity.created_at <= :to_date', { to_date });
        }

        queryBuilder
          .orderBy('activity.created_at', 'DESC')
          .skip((page - 1) * limit)
          .take(limit);

        const [data, total] = await queryBuilder.getManyAndCount();

        return {
          data,
          total,
          page,
          limit,
          totalPages: Math.ceil(total / limit),
        };
      }

      /**
       * Get user activity summary
       */
      async getUserActivitySummary(
        tenantId: string,
        userId: string,
        days: number = 30,
      ): Promise<{ activity_type: ActivityType; count: number }[]> {
        const fromDate = new Date();
        fromDate.setDate(fromDate.getDate() - days);

        const result = await this.activityLogRepository
          .createQueryBuilder('activity')
          .select('activity.activity_type', 'activity_type')
          .addSelect('COUNT(*)', 'count')
          .where('activity.tenant_id = :tenantId', { tenantId })
          .andWhere('activity.user_id = :userId', { userId })
          .andWhere('activity.created_at >= :fromDate', { fromDate })
          .groupBy('activity.activity_type')
          .getRawMany();

        return result.map((r) => ({
          activity_type: r.activity_type,
          count: parseInt(r.count, 10),
        }));
      }

      /**
       * Get audit statistics for dashboard
       */
      async getAuditStats(
        tenantId: string,
        days: number = 7,
      ): Promise<{
        total_actions: number;
        actions_by_type: { action: AuditAction; count: number }[];
        top_users: { user_id: string; count: number }[];
      }> {
        const fromDate = new Date();
        fromDate.setDate(fromDate.getDate() - days);

        const [totalActions, actionsByType, topUsers] = await Promise.all([
          this.auditLogRepository.count({
            where: {
              tenant_id: tenantId,
              created_at: MoreThanOrEqual(fromDate),
            },
          }),
          this.auditLogRepository
            .createQueryBuilder('audit')
            .select('audit.action', 'action')
            .addSelect('COUNT(*)', 'count')
            .where('audit.tenant_id = :tenantId', { tenantId })
            .andWhere('audit.created_at >= :fromDate', { fromDate })
            .groupBy('audit.action')
            .getRawMany(),
          this.auditLogRepository
            .createQueryBuilder('audit')
            .select('audit.user_id', 'user_id')
            .addSelect('COUNT(*)', 'count')
            .where('audit.tenant_id = :tenantId', { tenantId })
            .andWhere('audit.created_at >= :fromDate', { fromDate })
            .andWhere('audit.user_id IS NOT NULL')
            .groupBy('audit.user_id')
            .orderBy('count', 'DESC')
            .limit(10)
            .getRawMany(),
        ]);

        return {
          total_actions: totalActions,
          actions_by_type: actionsByType.map((r) => ({
            action: r.action,
            count: parseInt(r.count, 10),
          })),
          top_users: topUsers.map((r) => ({
            user_id: r.user_id,
            count: parseInt(r.count, 10),
          })),
        };
      }

      /**
       * Detect changed fields between old and new values
       */
      private detectChangedFields(
        oldValues?: Record<string, any>,
        newValues?: Record<string, any>,
      ): string[] {
        if (!oldValues || !newValues) return [];

        const changedFields: string[] = [];
        const allKeys = new Set([...Object.keys(oldValues), ...Object.keys(newValues)]);

        for (const key of allKeys) {
          if (JSON.stringify(oldValues[key]) !== JSON.stringify(newValues[key])) {
            changedFields.push(key);
          }
        }

        return changedFields;
      }
    }