All files / src/platform/documents storage.service.ts

0% Statements 0/93
0% Branches 0/73
0% Functions 0/15
0% Lines 0/86

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import {
  Injectable,
  BadRequestException,
  NotFoundException,
  Logger,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { randomUUID } from 'crypto';
import {
  Folder,
  FileDocument,
  FileVersion,
  FileShare,
  UploadSession,
  StorageUsage,
} from './schemas/storage.schema';
import { StorageProvider } from './storage-provider.interface';
import { LocalStorageProvider } from './providers/local-storage.provider';
import { AuditLogService } from '../audit/audit-log.service';
import { ActivityTimelineService } from '../activity/activity.service';
import { EventBusService } from '../events/event-bus.service';
 
const ALLOWED_MIME_TYPES = [
  'image/jpeg',
  'image/png',
  'image/gif',
  'image/webp',
  'image/svg+xml',
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'text/plain',
  'text/csv',
  'application/zip',
  'application/gzip',
];
 
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
 
@Injectable()
export class StorageService {
  private readonly logger = new Logger(StorageService.name);
  private storageProvider: StorageProvider;
 
  constructor(
    @InjectModel(Folder.name) private readonly folderModel: Model<Folder>,
    @InjectModel(FileDocument.name)
    private readonly fileModel: Model<FileDocument>,
    @InjectModel(FileVersion.name)
    private readonly versionModel: Model<FileVersion>,
    @InjectModel(FileShare.name) private readonly shareModel: Model<FileShare>,
    @InjectModel(UploadSession.name)
    private readonly uploadSessionModel: Model<UploadSession>,
    @InjectModel(StorageUsage.name)
    private readonly storageUsageModel: Model<StorageUsage>,
    private readonly auditLog: AuditLogService,
    private readonly timeline: ActivityTimelineService,
    private readonly eventBus: EventBusService,
  ) {
    this.storageProvider = new LocalStorageProvider();
  }
 
  setStorageProvider(provider: StorageProvider) {
    this.storageProvider = provider;
  }
 
  // ============================================================
  // UPLOAD FLOW
  // ============================================================
 
  async initUpload(params: {
    tenantId: string;
    userId: string;
    fileName: string;
    mimeType: string;
    size: number;
    folderId?: string;
  }): Promise<any> {
    if (!ALLOWED_MIME_TYPES.includes(params.mimeType)) {
      throw new BadRequestException(
        `MIME type not allowed: ${params.mimeType}`,
      );
    }
    if (params.size > MAX_FILE_SIZE) {
      throw new BadRequestException(
        `File size exceeds limit of ${MAX_FILE_SIZE} bytes`,
      );
    }
 
    // Check tenant storage quota
    let usage = await this.storageUsageModel
      .findOne({ tenantId: params.tenantId })
      .exec();
    if (!usage) {
      usage = await this.storageUsageModel.create({
        tenantId: params.tenantId,
        currentBytes: 0,
      });
    }
    if (usage.currentBytes + params.size > usage.maxBytes) {
      throw new BadRequestException('Tenant storage quota exceeded');
    }
 
    const uploadId = randomUUID();
    await this.uploadSessionModel.create({
      tenantId: params.tenantId,
      uploadId,
      status: 'INITIATED',
      size: params.size,
      expectedChunks: 1,
    });
 
    return { uploadId, status: 'INITIATED' };
  }
 
  async completeUpload(params: {
    tenantId: string;
    userId: string;
    uploadId: string;
    buffer: Buffer;
    fileName: string;
    mimeType: string;
    folderId?: string;
    tags?: string[];
  }): Promise<any> {
    const session = await this.uploadSessionModel
      .findOne({
        tenantId: params.tenantId,
        uploadId: params.uploadId,
        status: 'INITIATED',
      })
      .exec();
 
    if (!session) {
      throw new NotFoundException(
        'Upload session not found or already completed',
      );
    }
 
    const s3Key = `${params.tenantId}/${randomUUID()}/${params.fileName}`;
    await this.storageProvider.upload(s3Key, params.buffer, params.mimeType);
 
    const file = await this.fileModel.create({
      tenantId: params.tenantId,
      folderId: params.folderId || null,
      name: params.fileName,
      mimeType: params.mimeType,
      size: params.buffer.length,
      s3Key,
      ownerId: params.userId,
      tags: params.tags || [],
    });
 
    // Create initial version
    await this.versionModel.create({
      documentId: (file as any)._id.toString(),
      version: 1,
      s3Key,
      size: params.buffer.length,
      createdById: params.userId,
    });
 
    // Update session and storage usage
    session.status = 'COMPLETED';
    await session.save();
 
    await this.storageUsageModel
      .updateOne(
        { tenantId: params.tenantId },
        { $inc: { currentBytes: params.buffer.length } },
      )
      .exec();
 
    // Cross-service integrations
    await this.auditLog.log({
      tenantId: params.tenantId,
      userId: params.userId,
      action: 'FILE_UPLOAD',
      resource: 'File',
      resourceId: (file as any)._id.toString(),
    });
 
    await this.timeline.log({
      tenantId: params.tenantId,
      entityType: 'File',
      entityId: (file as any)._id.toString(),
      actorId: params.userId,
      activityType: 'FILE_UPLOAD',
      title: `Uploaded file: ${params.fileName}`,
      icon: 'Upload',
    });
 
    await this.eventBus.publish(
      'platform.file.uploaded.v1',
      {
        fileId: (file as any)._id.toString(),
        fileName: params.fileName,
        tenantId: params.tenantId,
      },
      params.tenantId,
    );
 
    return { ...file.toObject(), id: (file as any)._id.toString() };
  }
 
  // ============================================================
  // FILE OPERATIONS
  // ============================================================
 
  async listFiles(
    tenantId: string,
    folderId?: string,
    page = 1,
    limit = 20,
  ): Promise<any> {
    const skip = (page - 1) * limit;
    const where: any = { tenantId, deletedAt: null };
    if (folderId) where.folderId = folderId;
 
    const [data, total] = await Promise.all([
      this.fileModel
        .find(where)
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 })
        .lean()
        .exec(),
      this.fileModel.countDocuments(where).exec(),
    ]);
 
    return {
      data: data.map((d) => ({ ...d, id: (d as any)._id.toString() })),
      meta: { total, page, limit, totalPages: Math.ceil(total / limit) },
    };
  }
 
  async getFile(id: string, tenantId: string): Promise<any> {
    const file = await this.fileModel
      .findOne({ _id: id, tenantId, deletedAt: null })
      .lean()
      .exec();
    if (!file) throw new NotFoundException('File not found');
    return { ...file, id: (file as any)._id.toString() };
  }
 
  async getDownloadUrl(id: string, tenantId: string): Promise<string> {
    const file = await this.fileModel
      .findOne({ _id: id, tenantId, deletedAt: null })
      .lean()
      .exec();
    if (!file) throw new NotFoundException('File not found');
    return this.storageProvider.getDownloadUrl(file.s3Key, 3600);
  }
 
  async softDelete(id: string, tenantId: string, userId: string): Promise<any> {
    const result = await this.fileModel
      .findOneAndUpdate(
        { _id: id, tenantId },
        { $set: { deletedAt: new Date() } },
        { new: true },
      )
      .lean()
      .exec();
 
    if (!result) throw new NotFoundException('File not found');
 
    await this.auditLog.log({
      tenantId,
      userId,
      action: 'FILE_DELETE',
      resource: 'File',
      resourceId: id,
    });
 
    return { success: true };
  }
 
  async restoreFile(id: string, tenantId: string): Promise<any> {
    return this.fileModel
      .findOneAndUpdate(
        { _id: id, tenantId },
        { $set: { deletedAt: null } },
        { new: true },
      )
      .lean()
      .exec();
  }
 
  async createShareLink(
    fileId: string,
    tenantId: string,
    expiresInHours = 24,
  ): Promise<any> {
    const file = await this.fileModel
      .findOne({ _id: fileId, tenantId })
      .lean()
      .exec();
    if (!file) throw new NotFoundException('File not found');
 
    const token = randomUUID();
    const share = await this.shareModel.create({
      documentId: fileId,
      token,
      expiresAt: new Date(Date.now() + expiresInHours * 60 * 60 * 1000),
    });
 
    return { token, expiresAt: share.expiresAt };
  }
 
  // ============================================================
  // FOLDER OPERATIONS
  // ============================================================
 
  async listFolders(tenantId: string, parentFolderId?: string): Promise<any[]> {
    const where: any = { tenantId };
    if (parentFolderId) {
      where.parentFolderId = parentFolderId;
    } else {
      where.parentFolderId = null;
    }
    return this.folderModel.find(where).lean().exec();
  }
 
  async createFolder(params: {
    tenantId: string;
    name: string;
    parentFolderId?: string;
    ownerId: string;
  }): Promise<any> {
    const parentPath = params.parentFolderId
      ? (await this.folderModel.findById(params.parentFolderId).lean().exec())
          ?.path || '/'
      : '/';
    const folderPath = `${parentPath}${params.name}/`;
 
    return this.folderModel.create({
      tenantId: params.tenantId,
      name: params.name,
      parentFolderId: params.parentFolderId || null,
      path: folderPath,
      ownerId: params.ownerId,
    });
  }
 
  async updateFolder(
    id: string,
    tenantId: string,
    data: { name?: string },
  ): Promise<any> {
    return this.folderModel
      .findOneAndUpdate({ _id: id, tenantId }, data, { new: true })
      .lean()
      .exec();
  }
 
  async deleteFolder(id: string, tenantId: string): Promise<any> {
    // Check if folder has files
    const fileCount = await this.fileModel
      .countDocuments({ tenantId, folderId: id, deletedAt: null })
      .exec();
    if (fileCount > 0) {
      throw new BadRequestException(
        'Folder is not empty. Delete or move files first.',
      );
    }
    await this.folderModel.deleteOne({ _id: id, tenantId }).exec();
    return { success: true };
  }
}