super-admin.service.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { Injectable, NotFoundException } from '@nestjs/common';
  2. import { TenantService } from '../tenant/tenant.service';
  3. import { UserService } from '../user/user.service';
  4. import { User } from '../user/user.entity';
  5. import { UserRole } from '../user/user-role.enum';
  6. @Injectable()
  7. export class SuperAdminService {
  8. constructor(
  9. private readonly tenantService: TenantService,
  10. private readonly userService: UserService,
  11. ) { }
  12. async getAllTenants(page?: number, limit?: number) {
  13. return this.tenantService.findAll(page, limit);
  14. }
  15. async createTenant(name: string, domain?: string, adminUserId?: string, parentId?: string) {
  16. const tenant = await this.tenantService.create(name, domain, parentId);
  17. if (adminUserId) {
  18. await this.tenantService.addMember(tenant.id, adminUserId, UserRole.TENANT_ADMIN);
  19. }
  20. return tenant;
  21. }
  22. async assignUserToTenant(userId: string, tenantId: string, role: UserRole = UserRole.TENANT_ADMIN) {
  23. // Find existing members of this tenant
  24. const members = await this.tenantService.getMembers(tenantId);
  25. // Remove existing admins from this tenant (unlinking them, not changing their role)
  26. for (const member of members.data) {
  27. if (member.role === UserRole.TENANT_ADMIN || member.role === UserRole.SUPER_ADMIN) {
  28. await this.tenantService.removeMember(tenantId, member.userId);
  29. }
  30. }
  31. // Add the new admin association for this tenant
  32. return this.tenantService.addMember(tenantId, userId, role);
  33. }
  34. async createTenantAdmin(tenantId: string, username: string, password?: string) {
  35. const defaultPassword = password || Math.random().toString(36).slice(-8);
  36. const result = await this.userService.createUser(
  37. username,
  38. defaultPassword,
  39. false, // isAdmin
  40. tenantId,
  41. username // displayName
  42. );
  43. return {
  44. user: result.user,
  45. defaultPassword: defaultPassword
  46. };
  47. }
  48. async updateTenant(tenantId: string, data: { name?: string; domain?: string; parentId?: string }) {
  49. return this.tenantService.update(tenantId, data);
  50. }
  51. async deleteTenant(tenantId: string) {
  52. return this.tenantService.remove(tenantId);
  53. }
  54. // NOTE: Model Management would be added here depending on ModelService functionality
  55. }