import { Injectable, Inject, NotFoundException, ConflictException, BadRequestException, ForbiddenException, } from '@nestjs/common'; import * as argon2 from 'argon2'; import { PrismaService } from '../prisma/prisma.service'; import { AuditService } from '../audit/audit.service'; import { STORAGE_PROVIDER, IStorageProvider } from '../storage/storage.interface'; import { AdminCreateUserDto, AdminUpdateUserDto, UpdateSystemSettingDto } from './dto/admin.dto'; import { UserRole, UserStatus, FileCategory, FileStatus } from '@prisma/client'; @Injectable() export class AdminService { constructor( private readonly prisma: PrismaService, private readonly auditService: AuditService, @Inject(STORAGE_PROVIDER) private readonly storageService: IStorageProvider, ) {} /** * List users with search, role filter, status filter, and pagination */ async listUsers(params: { search?: string; role?: UserRole; status?: UserStatus; page?: number; limit?: number; requesterRole?: UserRole | string; canViewOtherUsers?: boolean; requesterId?: string; }) { const isSuperAdmin = params.requesterRole === UserRole.SUPER_ADMIN || params.requesterRole === 'SUPER_ADMIN'; const isAdmin = params.requesterRole === UserRole.ADMIN || params.requesterRole === 'ADMIN'; const hasPermission = isSuperAdmin || isAdmin || !!params.canViewOtherUsers; if (!hasPermission) { throw new ForbiddenException( 'Access denied. Only Super Admin, Administrators, or authorized users with "canViewOtherUsers" permission can view other users\' information.', ); } const page = params.page || 1; const limit = params.limit || 50; const skip = (page - 1) * limit; const where: any = {}; if (params.role) where.role = params.role; if (params.status) where.status = params.status; if (params.search) { where.OR = [ { email: { contains: params.search } }, { username: { contains: params.search } }, { fullName: { contains: params.search } }, ]; } const [total, users] = await Promise.all([ this.prisma.user.count({ where }), this.prisma.user.findMany({ where, take: limit, skip, orderBy: { createdAt: 'desc' }, include: { _count: { select: { files: { where: { isSoftDeleted: false } }, folders: true, }, }, }, }), ]); return { total, page, limit, users: users.map((u) => ({ id: u.id, email: u.email, username: u.username, fullName: u.fullName, companyName: u.companyName, allowedCompanies: u.allowedCompanies, role: u.role, status: u.status, storageQuotaBytes: u.storageQuotaBytes.toString(), storageUsedBytes: u.storageUsedBytes.toString(), canCreateShareLinks: u.canCreateShareLinks, canDeleteFiles: u.canDeleteFiles, canViewOtherUsers: u.role === UserRole.SUPER_ADMIN ? true : (u.canViewOtherUsers ?? false), remoteFileServerUrl: u.remoteFileServerUrl, canUseRemoteServer: u.canUseRemoteServer, fileCount: u._count.files, folderCount: u._count.folders, createdAt: u.createdAt, updatedAt: u.updatedAt, lastLoginAt: u.lastLoginAt, viewablePassword: isSuperAdmin ? (u.viewablePassword || null) : undefined, })), }; } /** * Create a new user from administrative console */ async createUser(dto: AdminCreateUserDto, creatorUserId: string, creatorRole?: UserRole | string) { const isSuperAdmin = creatorRole === UserRole.SUPER_ADMIN || creatorRole === 'SUPER_ADMIN'; if (dto.canViewOtherUsers && !isSuperAdmin) { throw new ForbiddenException('Only Super Admin can grant "canViewOtherUsers" permission'); } const [existingEmail, existingUsername] = await Promise.all([ this.prisma.user.findUnique({ where: { email: dto.email.toLowerCase() } }), this.prisma.user.findUnique({ where: { username: dto.username.toLowerCase() } }), ]); if (existingEmail) throw new ConflictException('Email already registered'); if (existingUsername) throw new ConflictException('Username already taken'); const passwordHash = await argon2.hash(dto.password, { type: argon2.argon2id }); const quota = dto.storageQuotaBytes ? BigInt(dto.storageQuotaBytes) : BigInt(5368709120); const canViewOtherUsers = isSuperAdmin ? (dto.role === UserRole.SUPER_ADMIN ? true : (dto.canViewOtherUsers ?? false)) : false; const user = await this.prisma.$transaction(async (tx) => { const createdUser = await tx.user.create({ data: { email: dto.email.toLowerCase(), username: dto.username.toLowerCase(), fullName: dto.fullName.trim(), companyName: dto.companyName && dto.companyName.trim() ? dto.companyName.trim() : 'Ecohub', allowedCompanies: dto.allowedCompanies !== undefined ? (dto.allowedCompanies ? dto.allowedCompanies.trim() : null) : null, passwordHash, viewablePassword: dto.password, role: dto.role || UserRole.USER, status: UserStatus.ACTIVE, storageQuotaBytes: quota, canCreateShareLinks: dto.canCreateShareLinks ?? (dto.role === UserRole.SUPER_ADMIN || dto.role === UserRole.ADMIN), canDeleteFiles: dto.canDeleteFiles ?? true, canViewOtherUsers, remoteFileServerUrl: dto.remoteFileServerUrl && dto.remoteFileServerUrl.trim() ? dto.remoteFileServerUrl.trim() : null, canUseRemoteServer: dto.canUseRemoteServer ?? true, }, }); // Automatic root folder creation await tx.folder.create({ data: { ownerId: createdUser.id, parentId: null, name: 'Root', logicalPath: '/', }, }); return createdUser; }); await this.auditService.log({ actorUserId: creatorUserId, action: 'ADMIN_CREATED_USER', resourceType: 'USER', resourceId: user.id, targetUserId: user.id, details: { email: user.email, role: user.role, remoteFileServerUrl: user.remoteFileServerUrl }, }); return { id: user.id, email: user.email, username: user.username, fullName: user.fullName, companyName: user.companyName, allowedCompanies: user.allowedCompanies, role: user.role, status: user.status, storageQuotaBytes: user.storageQuotaBytes.toString(), storageUsedBytes: user.storageUsedBytes.toString(), canCreateShareLinks: user.canCreateShareLinks, canDeleteFiles: user.canDeleteFiles, canViewOtherUsers: user.role === UserRole.SUPER_ADMIN ? true : (user.canViewOtherUsers ?? false), remoteFileServerUrl: user.remoteFileServerUrl, canUseRemoteServer: user.canUseRemoteServer, createdAt: user.createdAt, }; } /** * Update user properties (role, status, quota, full name, password) */ async updateUser(id: string, dto: AdminUpdateUserDto, actorUserId: string, actorRole?: UserRole | string) { const user = await this.prisma.user.findUnique({ where: { id } }); if (!user) throw new NotFoundException('User not found'); const isSuperAdmin = actorRole === UserRole.SUPER_ADMIN || actorRole === 'SUPER_ADMIN'; const updateData: any = {}; if (dto.fullName) updateData.fullName = dto.fullName.trim(); if (dto.companyName !== undefined) updateData.companyName = dto.companyName.trim() || 'Ecohub'; if (dto.allowedCompanies !== undefined) { updateData.allowedCompanies = dto.allowedCompanies && dto.allowedCompanies.trim() ? dto.allowedCompanies.trim() : null; } if (dto.role) updateData.role = dto.role; if (dto.status) updateData.status = dto.status; if (dto.storageQuotaBytes !== undefined) { updateData.storageQuotaBytes = BigInt(dto.storageQuotaBytes); } if (dto.canCreateShareLinks !== undefined) { updateData.canCreateShareLinks = dto.canCreateShareLinks; } if (dto.canDeleteFiles !== undefined) { updateData.canDeleteFiles = dto.canDeleteFiles; } if (dto.canViewOtherUsers !== undefined) { if (!isSuperAdmin) { throw new ForbiddenException('Only Super Admin can grant or revoke "canViewOtherUsers" permission'); } updateData.canViewOtherUsers = dto.canViewOtherUsers; } if (dto.remoteFileServerUrl !== undefined) { updateData.remoteFileServerUrl = dto.remoteFileServerUrl && dto.remoteFileServerUrl.trim() ? dto.remoteFileServerUrl.trim() : null; } if (dto.canUseRemoteServer !== undefined) { updateData.canUseRemoteServer = dto.canUseRemoteServer; } if (dto.newPassword) { updateData.passwordHash = await argon2.hash(dto.newPassword, { type: argon2.argon2id }); updateData.viewablePassword = dto.newPassword; } const updated = await this.prisma.user.update({ where: { id }, data: updateData, }); await this.auditService.log({ actorUserId, action: 'ADMIN_UPDATED_USER', resourceType: 'USER', resourceId: id, targetUserId: id, details: { changes: Object.keys(updateData) }, }); return { id: updated.id, email: updated.email, username: updated.username, fullName: updated.fullName, companyName: updated.companyName, allowedCompanies: updated.allowedCompanies, role: updated.role, status: updated.status, storageQuotaBytes: updated.storageQuotaBytes.toString(), storageUsedBytes: updated.storageUsedBytes.toString(), canCreateShareLinks: updated.canCreateShareLinks, canDeleteFiles: updated.canDeleteFiles, canViewOtherUsers: updated.role === UserRole.SUPER_ADMIN ? true : (updated.canViewOtherUsers ?? false), remoteFileServerUrl: updated.remoteFileServerUrl, canUseRemoteServer: updated.canUseRemoteServer, updatedAt: updated.updatedAt, }; } /** * Reset user password from Admin Console (Superadmin & Admin) */ async resetUserPassword(targetUserId: string, newPassword: string, actorUserId: string) { const user = await this.prisma.user.findUnique({ where: { id: targetUserId } }); if (!user) throw new NotFoundException('User not found'); const passwordHash = await argon2.hash(newPassword, { type: argon2.argon2id }); await this.prisma.user.update({ where: { id: targetUserId }, data: { passwordHash, viewablePassword: newPassword, }, }); // Revoke any active refresh tokens for this user await this.prisma.refreshToken.updateMany({ where: { userId: targetUserId, revokedAt: null }, data: { revokedAt: new Date() }, }); await this.auditService.log({ actorUserId, action: 'ADMIN_RESET_USER_PASSWORD', resourceType: 'USER', resourceId: targetUserId, targetUserId, details: { username: user.username }, }); return { success: true, message: `Password for user "${user.username}" reset successfully`, }; } /** * User-wise File Explorer: browse files belonging to a specific user */ async getUserFiles( targetUserId: string, params: { folderId?: string; category?: FileCategory; search?: string; page?: number; limit?: number; }, adminUserId: string, requesterRole?: UserRole | string, canViewOtherUsers?: boolean, ) { const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN'; if (targetUserId !== adminUserId && !isSuperAdmin && !canViewOtherUsers) { throw new ForbiddenException( 'Access denied. Only Super Admin or authorized users with "canViewOtherUsers" permission can view other users\' files.', ); } const user = await this.prisma.user.findUnique({ where: { id: targetUserId } }); if (!user) throw new NotFoundException('Target user not found'); const page = params.page || 1; const limit = params.limit || 50; const skip = (page - 1) * limit; const where: any = { ownerId: targetUserId, isSoftDeleted: false, }; if (params.folderId) where.folderId = params.folderId; if (params.category) where.fileCategory = params.category; if (params.search) where.originalFilename = { contains: params.search }; const [total, files] = await Promise.all([ this.prisma.fileAsset.count({ where }), this.prisma.fileAsset.findMany({ where, take: limit, skip, orderBy: { createdAt: 'desc' }, include: { folder: { select: { id: true, name: true, logicalPath: true } }, }, }), ]); await this.auditService.log({ actorUserId: adminUserId, action: 'ADMIN_EXPLORED_USER_FILES', resourceType: 'USER', targetUserId, details: { filesCount: files.length }, }); return { targetUser: { id: user.id, email: user.email, username: user.username, fullName: user.fullName, storageQuotaBytes: user.storageQuotaBytes.toString(), storageUsedBytes: user.storageUsedBytes.toString(), }, total, page, limit, files: files.map((f) => ({ id: f.id, folderId: f.folderId, folderName: f.folder?.name || 'Root', originalFilename: f.originalFilename, mimeType: f.mimeType, fileExtension: f.fileExtension, fileSizeBytes: f.fileSizeBytes.toString(), fileCategory: f.fileCategory, status: f.status, durationSeconds: f.durationSeconds, width: f.width, height: f.height, hasThumbnail: !!f.thumbnailStorageKey, hasHlsStream: !!f.hlsMasterPlaylistKey, createdAt: f.createdAt, })), }; } /** * Browse folders belonging to a specific user */ async getUserFolders( targetUserId: string, adminUserId: string, requesterRole?: UserRole | string, canViewOtherUsers?: boolean, ) { const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN'; if (targetUserId !== adminUserId && !isSuperAdmin && !canViewOtherUsers) { throw new ForbiddenException( 'Access denied. Only Super Admin or authorized users with "canViewOtherUsers" permission can view other users\' folders.', ); } const user = await this.prisma.user.findUnique({ where: { id: targetUserId } }); if (!user) throw new NotFoundException('Target user not found'); const folders = await this.prisma.folder.findMany({ where: { ownerId: targetUserId }, orderBy: { logicalPath: 'asc' }, select: { id: true, name: true, logicalPath: true, parentId: true, createdAt: true, }, }); return { folders }; } /** * Search and list system resources (Files or Folders) for permission dropdown selection */ async getResources( params: { type?: 'FILE' | 'FOLDER'; ownerId?: string; search?: string; limit?: number; }, adminUserId: string, requesterRole?: UserRole | string, canViewOtherUsers?: boolean, ) { const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN'; if (!isSuperAdmin && !canViewOtherUsers) { if (params.ownerId && params.ownerId !== adminUserId) { throw new ForbiddenException( 'Access denied. Only Super Admin or authorized users can view other users\' resources.', ); } params.ownerId = adminUserId; } const limit = params.limit ? Math.min(params.limit, 200) : 100; const type = params.type || 'FILE'; if (type === 'FOLDER') { const folders = await this.prisma.folder.findMany({ where: { ...(params.ownerId ? { ownerId: params.ownerId } : {}), ...(params.search ? { name: { contains: params.search } } : {}), }, take: limit, orderBy: { logicalPath: 'asc' }, include: { owner: { select: { id: true, fullName: true, email: true, username: true, companyName: true }, }, }, }); return { type: 'FOLDER', items: folders.map((f) => ({ id: f.id, name: f.name, logicalPath: f.logicalPath, ownerId: f.ownerId, ownerName: f.owner?.fullName || f.owner?.username || f.owner?.email, ownerEmail: f.owner?.email, ownerCompany: f.owner?.companyName, })), }; } // Default to FILE const files = await this.prisma.fileAsset.findMany({ where: { isSoftDeleted: false, ...(params.ownerId ? { ownerId: params.ownerId } : {}), ...(params.search ? { originalFilename: { contains: params.search } } : {}), }, take: limit, orderBy: { createdAt: 'desc' }, include: { owner: { select: { id: true, fullName: true, email: true, username: true, companyName: true }, }, folder: { select: { id: true, name: true, logicalPath: true }, }, }, }); return { type: 'FILE', items: files.map((f) => ({ id: f.id, name: f.originalFilename, sizeBytes: f.fileSizeBytes.toString(), category: f.fileCategory, mimeType: f.mimeType, folderName: f.folder?.name || 'Root', ownerId: f.ownerId, ownerName: f.owner?.fullName || f.owner?.username || f.owner?.email, ownerEmail: f.owner?.email, ownerCompany: f.owner?.companyName, })), }; } /** * System-wide storage overview and statistics */ async getStorageOverview() { const [userCount, activeUserCount, totalFiles, videoFiles] = await Promise.all([ this.prisma.user.count(), this.prisma.user.count({ where: { status: UserStatus.ACTIVE } }), this.prisma.fileAsset.count({ where: { isSoftDeleted: false } }), this.prisma.fileAsset.count({ where: { fileCategory: FileCategory.VIDEO, isSoftDeleted: false } }), ]); const users = await this.prisma.user.findMany({ select: { storageQuotaBytes: true, storageUsedBytes: true }, }); const totalQuota = users.reduce((acc, u) => acc + u.storageQuotaBytes, BigInt(0)); const totalUsed = users.reduce((acc, u) => acc + u.storageUsedBytes, BigInt(0)); // Category breakdown const categoryCounts = await this.prisma.fileAsset.groupBy({ by: ['fileCategory'], where: { isSoftDeleted: false }, _count: { id: true }, _sum: { fileSizeBytes: true }, }); // Video transcoding statuses const [videoReady, videoProcessing, videoFailed] = await Promise.all([ this.prisma.fileAsset.count({ where: { fileCategory: FileCategory.VIDEO, status: FileStatus.READY, isSoftDeleted: false }, }), this.prisma.fileAsset.count({ where: { fileCategory: FileCategory.VIDEO, status: { in: [FileStatus.PROCESSING, FileStatus.PENDING, FileStatus.UPLOADING] }, isSoftDeleted: false, }, }), this.prisma.fileAsset.count({ where: { fileCategory: FileCategory.VIDEO, status: FileStatus.FAILED, isSoftDeleted: false }, }), ]); const usagePercentage = totalQuota > BigInt(0) ? Number((totalUsed * BigInt(100)) / totalQuota) : 0; const breakdown = categoryCounts.map((c) => ({ category: c.fileCategory, count: c._count.id, sizeBytes: c._sum.fileSizeBytes ? Number(c._sum.fileSizeBytes) : 0, totalBytes: c._sum.fileSizeBytes ? c._sum.fileSizeBytes.toString() : '0', })); return { userCount, totalUsers: userCount, activeUserCount, totalFiles, videoFiles, totalQuotaBytes: Number(totalQuota), totalUsedBytes: Number(totalUsed), usagePercentage, utilizationPercentage: usagePercentage, categoryBreakdown: breakdown, categories: breakdown, videoStats: { ready: videoReady, processing: videoProcessing, failed: videoFailed, }, }; } /** * Get all system settings */ async getSettings() { const defaultSettings = [ { key: 'MAX_FILE_SIZE_BYTES', value: '5368709120', description: 'Maximum allowed single file upload size (5 GB)' }, { key: 'ALLOWED_EXTENSIONS', value: 'mp4,mov,avi,mkv,webm,flv,wmv,m4v,pdf,docx,xlsx,pptx,txt,zip,rar,7z,tar,gz,jpg,jpeg,png,webp,svg,gif,mp3,wav,aac,flac', description: 'Comma-separated list of allowed file extensions' }, { key: 'STORAGE_BASE_PATH', value: './storage', description: 'Dynamic storage directory location (Superadmin can change location anytime)' }, { key: 'REMOTE_FILE_SERVER_URL', value: '', description: 'Optional Remote File Server Link / URL for external video uploads and mirroring' }, ]; for (const def of defaultSettings) { await this.prisma.systemSetting.upsert({ where: { key: def.key }, update: {}, create: def, }); } return this.prisma.systemSetting.findMany({ orderBy: { key: 'asc' }, }); } /** * Update system setting */ async updateSetting(dto: UpdateSystemSettingDto, adminUserId: string) { const setting = await this.prisma.systemSetting.upsert({ where: { key: dto.key }, update: { value: dto.value }, create: { key: dto.key, value: dto.value }, }); await this.auditService.log({ actorUserId: adminUserId, action: 'ADMIN_UPDATED_SYSTEM_SETTING', resourceType: 'SETTING', resourceId: dto.key, details: { key: dto.key, value: dto.value }, }); return setting; } /** * Get all distinct company names registered in the system */ async getUniqueCompanies(): Promise { const users = await this.prisma.user.findMany({ select: { companyName: true, allowedCompanies: true }, }); const set = new Set(); set.add('Ecohub'); for (const u of users) { if (u.companyName && u.companyName.trim()) { set.add(u.companyName.trim()); } if (u.allowedCompanies && u.allowedCompanies.trim() && u.allowedCompanies.trim() !== '*') { try { const raw = u.allowedCompanies.trim(); if (raw.startsWith('[') && raw.endsWith(']')) { const parsed = JSON.parse(raw); if (Array.isArray(parsed)) { for (const c of parsed) { if (c && typeof c === 'string' && c.trim()) { set.add(c.trim()); } } } } else { const list = raw.split(',').map((s) => s.trim()).filter(Boolean); for (const c of list) set.add(c); } } catch { // ignore parsing error } } } // Check system_organizations in SystemSetting try { const setting = await this.prisma.systemSetting.findUnique({ where: { key: 'system_organizations' }, }); if (setting && setting.value) { const orgList = JSON.parse(setting.value); if (Array.isArray(orgList)) { for (const org of orgList) { if (org && typeof org === 'string' && org.trim()) { set.add(org.trim()); } } } } } catch { // ignore } return Array.from(set).sort((a, b) => a.localeCompare(b)); } /** * Register a new organization name in the system */ async createOrganization(name: string): Promise { const trimmed = name ? name.trim() : ''; if (!trimmed) { return this.getUniqueCompanies(); } try { const setting = await this.prisma.systemSetting.findUnique({ where: { key: 'system_organizations' }, }); const set = new Set(); if (setting && setting.value) { try { const parsed = JSON.parse(setting.value); if (Array.isArray(parsed)) { for (const item of parsed) set.add(item); } } catch {} } set.add(trimmed); await this.prisma.systemSetting.upsert({ where: { key: 'system_organizations' }, create: { key: 'system_organizations', value: JSON.stringify(Array.from(set)), description: 'Persistent list of registered system organizations', }, update: { value: JSON.stringify(Array.from(set)), }, }); } catch (err) { // Ignore if systemSetting table query fails } return this.getUniqueCompanies(); } /** * Permanently delete user and clean up physical storage files */ async deleteUser( targetUserId: string, requesterId: string, requesterRole?: UserRole | string, requesterCompanyName?: string, ) { if (targetUserId === requesterId) { throw new BadRequestException('You cannot delete your own account.'); } const targetUser = await this.prisma.user.findUnique({ where: { id: targetUserId }, include: { files: { select: { id: true, internalStorageKey: true, thumbnailStorageKey: true } }, }, }); if (!targetUser) { throw new NotFoundException('User not found.'); } const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN'; const isAdmin = requesterRole === UserRole.ADMIN || requesterRole === 'ADMIN'; if (targetUser.role === UserRole.SUPER_ADMIN) { if (!isSuperAdmin) { throw new ForbiddenException('Only a Super Administrator can delete another Super Administrator.'); } const superAdminCount = await this.prisma.user.count({ where: { role: UserRole.SUPER_ADMIN }, }); if (superAdminCount <= 1) { throw new BadRequestException('Cannot delete the last remaining Super Administrator account.'); } } else if (targetUser.role === UserRole.ADMIN && !isSuperAdmin) { throw new ForbiddenException('Only a Super Administrator can delete Administrator accounts.'); } // Restriction: Administrators cannot delete users belonging to another company if (!isSuperAdmin && isAdmin) { const adminCompany = (requesterCompanyName || 'Ecohub').trim().toLowerCase(); const userCompany = (targetUser.companyName || 'Ecohub').trim().toLowerCase(); if (adminCompany !== userCompany) { throw new ForbiddenException( 'Administrators cannot delete users belonging to another company. Only Super Admin has this permission.', ); } } // Clean up physical storage files for this user for (const f of targetUser.files) { try { if (f.internalStorageKey) await this.storageService.delete(f.internalStorageKey); if (f.thumbnailStorageKey) await this.storageService.delete(f.thumbnailStorageKey); } catch (err) { // Silently continue if file was already removed from storage } } // Explicitly delete any file permissions involving this user await this.prisma.filePermission.deleteMany({ where: { OR: [ { ownerId: targetUserId }, { granteeUserId: targetUserId }, { grantedByUserId: targetUserId }, ], }, }); // Delete user from DB (Prisma cascade handles files, folders, sessions, tokens) await this.prisma.user.delete({ where: { id: targetUserId }, }); await this.auditService.log({ actorUserId: requesterId, action: 'USER_DELETED', resourceType: 'USER', resourceId: targetUserId, details: { username: targetUser.username, email: targetUser.email, fullName: targetUser.fullName, role: targetUser.role, companyName: targetUser.companyName, }, }); return { success: true, message: `User "${targetUser.fullName}" (@${targetUser.username}) deleted successfully.`, }; } /** * Delete an entire company and all its user accounts and physical files (Super Admin Only) */ async deleteCompany(companyName: string, requesterId: string, requesterRole?: UserRole | string) { const isSuperAdmin = requesterRole === UserRole.SUPER_ADMIN || requesterRole === 'SUPER_ADMIN'; if (!isSuperAdmin) { throw new ForbiddenException('Only Super Administrator can delete an entire company.'); } const trimmedCompany = companyName.trim(); if (!trimmedCompany) { throw new BadRequestException('Company name is required.'); } // Find all users belonging to this company const users = await this.prisma.user.findMany({ where: { companyName: trimmedCompany }, include: { files: { select: { id: true, internalStorageKey: true, thumbnailStorageKey: true } }, }, }); if (users.length === 0) { return { success: true, message: `Company "${trimmedCompany}" has no registered users.` }; } // Prevent deleting if it contains the only remaining Super Administrator const containsRequester = users.some((u) => u.id === requesterId); if (containsRequester) { const totalSuperAdmins = await this.prisma.user.count({ where: { role: UserRole.SUPER_ADMIN } }); const superAdminsInCompany = users.filter((u) => u.role === UserRole.SUPER_ADMIN).length; if (totalSuperAdmins - superAdminsInCompany < 1) { throw new BadRequestException('Cannot delete this company because it contains the only remaining Super Administrator.'); } } // Clean up physical storage files for all users in this company for (const u of users) { for (const f of u.files) { try { if (f.internalStorageKey) await this.storageService.delete(f.internalStorageKey); if (f.thumbnailStorageKey) await this.storageService.delete(f.thumbnailStorageKey); } catch (err) {} } } const userIds = users.map((u) => u.id); // Delete permissions involving these users await this.prisma.filePermission.deleteMany({ where: { OR: [ { ownerId: { in: userIds } }, { granteeUserId: { in: userIds } }, { grantedByUserId: { in: userIds } }, ], }, }); // Delete users from DB (Cascade deletes folders, files, upload sessions, tokens) await this.prisma.user.deleteMany({ where: { id: { in: userIds } }, }); await this.auditService.log({ actorUserId: requesterId, action: 'COMPANY_DELETED', resourceType: 'COMPANY', resourceId: trimmedCompany, details: { companyName: trimmedCompany, deletedUserCount: users.length, }, }); return { success: true, message: `Company "${trimmedCompany}" and its ${users.length} user accounts and files were completely deleted.`, }; } /** * Rename or edit company name across all associated users (Super Admin & Admin) */ async updateCompanyName( oldName: string, newName: string, requesterId: string, requesterRole?: UserRole | string, ) { const trimmedOld = oldName.trim(); const trimmedNew = newName.trim(); if (!trimmedNew) { throw new BadRequestException('New company name cannot be empty.'); } const updated = await this.prisma.user.updateMany({ where: { companyName: trimmedOld }, data: { companyName: trimmedNew }, }); await this.auditService.log({ actorUserId: requesterId, action: 'COMPANY_RENAMED', resourceType: 'COMPANY', resourceId: trimmedOld, details: { oldName: trimmedOld, newName: trimmedNew, usersAffected: updated.count }, }); return { success: true, message: `Company renamed to "${trimmedNew}" for ${updated.count} users.`, }; } }