# Code coverage report for modules/storage/services/storage.service.ts

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

95.9% Statements 117/122
90% Branches 36/40
100% Functions 17/17
96.46% Lines 109/113

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
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    4312x

    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

    2x

    2x
    53x

    53x

    53x

    53x
    53x

    16x
    1x

    15x
    1x

    14x
    5x

    9x
    9x
    2x

    7x
    7x
    7x
    7x

    7x

    7x

    7x

    7x

    7x

    7x
    1x

    6x
    1x
    1x

    5x
    5x
    2x
    2x

    3x

    3x

    3x

    3x

    8x
    8x

    8x

    8x
    1x

    8x
    1x

    8x
    1x

    8x

    8x
    15x

    2x

    2x
    1x

    1x

    4x

    4x
    2x

    2x

    2x

    6x

    6x
    1x

    5x
    5x
    5x

    5x

    5x

    5x

    5x
    1x

    4x
    4x
    4x

    4x
    4x

    1x

    5x

    5x

    1x

    1x

    5x

    5x
    5x
    5x

    5x

    5x

    15x
    15x

    14x
    87x

    7x

    9x

    9x
    7x

    2x
    2x

    2x
    1x
    1x

    24x

     import {
      Injectable,
      Logger,
      BadRequestException,
      NotFoundException,
      ForbiddenException,
    } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository, IsNull, Like, ILike } from 'typeorm';
    import { v4 as uuid } from 'uuid';
    import { FileEntity, FileStatus, FileVisibility } from '../entities/file.entity';
    import { PendingUploadEntity } from '../entities/pending-upload.entity';
    import { StorageUsageEntity } from '../entities/storage-usage.entity';
    import { S3Provider } from '../providers/s3.provider';
    import {
      GetUploadUrlDto,
      ConfirmUploadDto,
      ListFilesDto,
      UpdateFileDto,
      PresignedUrlResponseDto,
      FileResponseDto,
      FileListResponseDto,
      DownloadUrlResponseDto,
      StorageUsageResponseDto,
    } from '../dto';

    // Allowed MIME types
    const ALLOWED_MIME_TYPES: Record<string, string[]> = {
      images: ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'],
      documents: [
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      ],
      spreadsheets: [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      ],
      data: ['text/csv', 'application/json', 'text/plain'],
    };

    const BLOCKED_EXTENSIONS = ['.exe', '.bat', '.sh', '.php', '.js', '.cmd', '.com', '.scr'];

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

      constructor(
        @InjectRepository(FileEntity)
        private readonly fileRepository: Repository<FileEntity>,
        @InjectRepository(PendingUploadEntity)
        private readonly pendingUploadRepository: Repository<PendingUploadEntity>,
        @InjectRepository(StorageUsageEntity)
        private readonly usageRepository: Repository<StorageUsageEntity>,
        private readonly s3Provider: S3Provider,
      ) {}

      async getUploadUrl(
        tenantId: string,
        userId: string,
        dto: GetUploadUrlDto,
      ): Promise<PresignedUrlResponseDto> {
        // Validate storage is configured
        if (!this.s3Provider.isConfigured()) {
          throw new BadRequestException('Storage not configured');
        }

        // Validate MIME type
        if (!this.isAllowedMimeType(dto.mimeType)) {
          throw new BadRequestException(`File type not allowed: ${dto.mimeType}`);
        }

        // Validate extension
        if (this.hasBlockedExtension(dto.filename)) {
          throw new BadRequestException('File extension not allowed');
        }

        // Check storage limits
        const canUpload = await this.canUpload(tenantId, dto.sizeBytes);
        if (!canUpload.allowed) {
          throw new ForbiddenException(canUpload.reason);
        }

        // Generate upload ID and path
        const uploadId = uuid();
        const folder = dto.folder || 'files';
        const path = this.s3Provider.generatePath(tenantId, folder, uploadId, dto.filename);
        const bucket = this.s3Provider.getBucket();

        // Get presigned URL
        const presigned = await this.s3Provider.getUploadUrl({
          bucket,
          key: path,
          contentType: dto.mimeType,
          contentLength: dto.sizeBytes,
          metadata: {
            'tenant-id': tenantId,
            'upload-id': uploadId,
            'user-id': userId,
          },
        });

        // Save pending upload
        const pendingUpload = this.pendingUploadRepository.create({
          id: uploadId,
          tenant_id: tenantId,
          user_id: userId,
          filename: this.sanitizeFilename(dto.filename),
          original_name: dto.filename,
          mime_type: dto.mimeType,
          size_bytes: dto.sizeBytes,
          folder,
          bucket,
          path,
          provider: this.s3Provider.getProvider(),
          expires_at: presigned.expiresAt,
        });

        await this.pendingUploadRepository.save(pendingUpload);

        return {
          uploadId,
          url: presigned.url,
          expiresAt: presigned.expiresAt,
          maxSize: dto.sizeBytes,
        };
      }

      async confirmUpload(
        tenantId: string,
        userId: string,
        dto: ConfirmUploadDto,
      ): Promise<FileResponseDto> {
        // Find pending upload
        const pending = await this.pendingUploadRepository.findOne({
          where: {
            id: dto.uploadId,
            tenant_id: tenantId,
            status: 'pending',
          },
        });

        if (!pending) {
          throw new NotFoundException('Upload not found or expired');
        }

        if (pending.expires_at < new Date()) {
          await this.pendingUploadRepository.update(pending.id, { status: 'expired' });
          throw new BadRequestException('Upload expired');
        }

        // Verify file exists in S3
        const headResult = await this.s3Provider.headObject(pending.path);
        if (!headResult) {
          await this.pendingUploadRepository.update(pending.id, { status: 'failed' });
          throw new BadRequestException('File not found in storage');
        }

        // Create file record
        const file = this.fileRepository.create({
          tenant_id: tenantId,
          uploaded_by: userId,
          filename: pending.filename,
          original_name: pending.original_name,
          mime_type: pending.mime_type,
          size_bytes: headResult.contentLength,
          bucket: pending.bucket,
          path: pending.path,
          provider: pending.provider,
          folder: pending.folder,
          status: FileStatus.READY,
          visibility: FileVisibility.PRIVATE,
          metadata: dto.metadata || {},
        });

        await this.fileRepository.save(file);

        // Mark pending as completed
        await this.pendingUploadRepository.update(pending.id, {
          status: 'completed',
          completed_at: new Date(),
        });

        return this.toFileResponse(file);
      }

      async listFiles(tenantId: string, dto: ListFilesDto): Promise<FileListResponseDto> {
        const { page = 1, limit = 20, folder, mimeType, search } = dto;
        const skip = (page - 1) * limit;

        const where: any = {
          tenant_id: tenantId,
          deleted_at: IsNull(),
          status: FileStatus.READY,
        };

        if (folder) {
          where.folder = folder;
        }

        if (mimeType) {
          where.mime_type = Like(`${mimeType}%`);
        }

        if (search) {
          where.original_name = ILike(`%${search}%`);
        }

        const [files, total] = await this.fileRepository.findAndCount({
          where,
          order: { created_at: 'DESC' },
          skip,
          take: limit,
        });

        return {
          data: files.map((f) => this.toFileResponse(f)),
          total,
          page,
          limit,
          totalPages: Math.ceil(total / limit),
        };
      }

      async getFile(tenantId: string, fileId: string): Promise<FileResponseDto> {
        const file = await this.fileRepository.findOne({
          where: {
            id: fileId,
            tenant_id: tenantId,
            deleted_at: IsNull(),
          },
        });

        if (!file) {
          throw new NotFoundException('File not found');
        }

        return this.toFileResponse(file);
      }

      async getDownloadUrl(tenantId: string, fileId: string): Promise<DownloadUrlResponseDto> {
        const file = await this.fileRepository.findOne({
          where: {
            id: fileId,
            tenant_id: tenantId,
            deleted_at: IsNull(),
            status: FileStatus.READY,
          },
        });

        if (!file) {
          throw new NotFoundException('File not found');
        }

        const result = await this.s3Provider.getDownloadUrl(file.path);

        return {
          url: result.url,
          expiresAt: result.expiresAt,
        };
      }

      async updateFile(
        tenantId: string,
        fileId: string,
        dto: UpdateFileDto,
      ): Promise<FileResponseDto> {
        const file = await this.fileRepository.findOne({
          where: {
            id: fileId,
            tenant_id: tenantId,
            deleted_at: IsNull(),
          },
        });

        if (!file) {
          throw new NotFoundException('File not found');
        }

        if (dto.folder) file.folder = dto.folder;
        if (dto.visibility) file.visibility = dto.visibility;
        if (dto.metadata) file.metadata = { ...file.metadata, ...dto.metadata };

        await this.fileRepository.save(file);

        return this.toFileResponse(file);
      }

      async deleteFile(tenantId: string, fileId: string): Promise<void> {
        const file = await this.fileRepository.findOne({
          where: {
            id: fileId,
            tenant_id: tenantId,
            deleted_at: IsNull(),
          },
        });

        if (!file) {
          throw new NotFoundException('File not found');
        }

        // Soft delete
        file.deleted_at = new Date();
        file.status = FileStatus.DELETED;
        await this.fileRepository.save(file);

        // Delete from S3 (optional - could be done via background job)
        try {
          await this.s3Provider.deleteObject(file.path);
        } catch (error) {
          this.logger.warn(`Failed to delete file from S3: ${file.path}`, error);
        }
      }

      async getUsage(tenantId: string): Promise<StorageUsageResponseDto> {
        let usage = await this.usageRepository.findOne({
          where: { tenant_id: tenantId },
        });

        if (!usage) {
          // Create default usage record
          usage = this.usageRepository.create({
            tenant_id: tenantId,
            total_files: 0,
            total_bytes: 0,
          });
          await this.usageRepository.save(usage);
        }

        // Get files by folder
        const folderStats = await this.fileRepository
          .createQueryBuilder('f')
          .select('f.folder', 'folder')
          .addSelect('COUNT(*)', 'count')
          .where('f.tenant_id = :tenantId', { tenantId })
          .andWhere('f.deleted_at IS NULL')
          .andWhere('f.status = :status', { status: FileStatus.READY })
          .groupBy('f.folder')
          .getRawMany();

        const filesByFolder: Record<string, number> = {};
        for (const stat of folderStats) {
          filesByFolder[stat.folder] = parseInt(stat.count, 10);
        }

        const usagePercent = usage.max_bytes
          ? Math.round((Number(usage.total_bytes) / Number(usage.max_bytes)) * 10000) / 100
          : 0;

        return {
          totalFiles: usage.total_files,
          totalBytes: Number(usage.total_bytes),
          maxBytes: usage.max_bytes ? Number(usage.max_bytes) : null,
          maxFileSize: usage.max_file_size ? Number(usage.max_file_size) : null,
          usagePercent,
          filesByFolder,
        };
      }

      // ==================== Helper Methods ====================

      private isAllowedMimeType(mimeType: string): boolean {
        const allAllowed = Object.values(ALLOWED_MIME_TYPES).flat();
        return allAllowed.includes(mimeType);
      }

      private hasBlockedExtension(filename: string): boolean {
        const lower = filename.toLowerCase();
        return BLOCKED_EXTENSIONS.some((ext) => lower.endsWith(ext));
      }

      private sanitizeFilename(filename: string): string {
        return filename.replace(/[^a-zA-Z0-9.-]/g, '_');
      }

      private async canUpload(
        tenantId: string,
        sizeBytes: number,
      ): Promise<{ allowed: boolean; reason?: string }> {
        const usage = await this.usageRepository.findOne({
          where: { tenant_id: tenantId },
        });

        if (!usage) {
          return { allowed: true };
        }

        if (usage.max_file_size && sizeBytes > Number(usage.max_file_size)) {
          return {
            allowed: false,
            reason: `File size exceeds limit (max: ${this.formatBytes(Number(usage.max_file_size))})`,
          };
        }

        Iif (
          usage.max_bytes &&
          Number(usage.total_bytes) + sizeBytes > Number(usage.max_bytes)
        ) {
          return {
            allowed: false,
            reason: `Storage limit exceeded (max: ${this.formatBytes(Number(usage.max_bytes))})`,
          };
        }

        return { allowed: true };
      }

      private formatBytes(bytes: number): string {
        if (bytes < 1024) return `${bytes} B`;
        Iif (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
        if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
        return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
      }

      private toFileResponse(file: FileEntity): FileResponseDto {
        return {
          id: file.id,
          filename: file.filename,
          originalName: file.original_name,
          mimeType: file.mime_type,
          sizeBytes: Number(file.size_bytes),
          folder: file.folder,
          visibility: file.visibility,
          thumbnails: file.thumbnails,
          metadata: file.metadata,
          createdAt: file.created_at,
          updatedAt: file.updated_at,
        };
      }
    }