mirror of
https://github.com/SyncrowIOT/backend.git
synced 2025-07-10 15:17:41 +00:00
finished Update invited user endpoint
This commit is contained in:
@ -760,6 +760,12 @@ export class ControllerRoute {
|
||||
public static readonly CREATE_USER_INVITATION_DESCRIPTION =
|
||||
'This endpoint creates an invitation for a user to assign to role and spaces.';
|
||||
|
||||
public static readonly UPDATE_USER_INVITATION_SUMMARY =
|
||||
'Update user invitation';
|
||||
|
||||
public static readonly UPDATE_USER_INVITATION_DESCRIPTION =
|
||||
'This endpoint updates an invitation for a user to assign to role and spaces.';
|
||||
|
||||
public static readonly ACTIVATION_CODE_SUMMARY =
|
||||
'Activate Invitation Code';
|
||||
|
||||
|
@ -1,5 +1,13 @@
|
||||
import { InviteUserService } from '../services/invite-user.service';
|
||||
import { Body, Controller, Post, Req, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Param,
|
||||
Post,
|
||||
Put,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
|
||||
import { AddUserInvitationDto } from '../dtos/add.invite-user.dto';
|
||||
import { ControllerRoute } from '@app/common/constants/controller-route';
|
||||
@ -9,6 +17,7 @@ import { Permissions } from 'src/decorators/permissions.decorator';
|
||||
import { JwtAuthGuard } from '@app/common/guards/jwt.auth.guard';
|
||||
import { CheckEmailDto } from '../dtos/check-email.dto';
|
||||
import { ActivateCodeDto } from '../dtos/active-code.dto';
|
||||
import { UpdateUserInvitationDto } from '../dtos/update.invite-user.dto';
|
||||
|
||||
@ApiTags('Invite User Module')
|
||||
@Controller({
|
||||
@ -67,4 +76,21 @@ export class InviteUserController {
|
||||
activateCodeDto,
|
||||
);
|
||||
}
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Put(':invitedUserUuid')
|
||||
@ApiOperation({
|
||||
summary: ControllerRoute.INVITE_USER.ACTIONS.UPDATE_USER_INVITATION_SUMMARY,
|
||||
description:
|
||||
ControllerRoute.INVITE_USER.ACTIONS.UPDATE_USER_INVITATION_DESCRIPTION,
|
||||
})
|
||||
async updateUserInvitation(
|
||||
@Param('invitedUserUuid') invitedUserUuid: string,
|
||||
@Body() updateUserInvitationDto: UpdateUserInvitationDto,
|
||||
): Promise<BaseResponseDto> {
|
||||
return await this.inviteUserService.updateUserInvitation(
|
||||
updateUserInvitationDto,
|
||||
invitedUserUuid,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
74
src/invite-user/dtos/update.invite-user.dto.ts
Normal file
74
src/invite-user/dtos/update.invite-user.dto.ts
Normal file
@ -0,0 +1,74 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import {
|
||||
ArrayMinSize,
|
||||
IsArray,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
} from 'class-validator';
|
||||
|
||||
export class UpdateUserInvitationDto {
|
||||
@ApiProperty({
|
||||
description: 'The first name of the user',
|
||||
example: 'John',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public firstName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The last name of the user',
|
||||
example: 'Doe',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public lastName: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The job title of the user',
|
||||
example: 'Software Engineer',
|
||||
required: false,
|
||||
})
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
public jobTitle?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The phone number of the user',
|
||||
example: '+1234567890',
|
||||
required: false,
|
||||
})
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
public phoneNumber?: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'The role uuid of the user',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public roleUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'The project uuid of the user',
|
||||
example: 'd290f1ee-6c54-4b01-90e6-d701748f0851',
|
||||
required: true,
|
||||
})
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
public projectUuid: string;
|
||||
@ApiProperty({
|
||||
description: 'The array of space UUIDs (at least one required)',
|
||||
example: ['b5f3c9d2-58b7-4377-b3f7-60acb711d5d9'],
|
||||
required: true,
|
||||
})
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
public spaceUuids: string[];
|
||||
constructor(dto: Partial<UpdateUserInvitationDto>) {
|
||||
Object.assign(this, dto);
|
||||
}
|
||||
}
|
@ -24,6 +24,7 @@ import { UserSpaceService } from 'src/users/services';
|
||||
import { UserDevicePermissionService } from 'src/user-device-permission/services';
|
||||
import { DeviceUserPermissionRepository } from '@app/common/modules/device/repositories';
|
||||
import { PermissionTypeRepository } from '@app/common/modules/permission/repositories';
|
||||
import { ProjectUserService } from 'src/project/services/project-user.service';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, InviteUserRepositoryModule],
|
||||
@ -47,6 +48,7 @@ import { PermissionTypeRepository } from '@app/common/modules/permission/reposit
|
||||
UserDevicePermissionService,
|
||||
DeviceUserPermissionRepository,
|
||||
PermissionTypeRepository,
|
||||
ProjectUserService,
|
||||
],
|
||||
exports: [InviteUserService],
|
||||
})
|
||||
|
@ -1,10 +1,15 @@
|
||||
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import {
|
||||
Injectable,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { AddUserInvitationDto } from '../dtos';
|
||||
import { BaseResponseDto } from '@app/common/dto/base.response.dto';
|
||||
import { UserStatusEnum } from '@app/common/constants/user-status.enum';
|
||||
import { SuccessResponseDto } from '@app/common/dto/success.response.dto';
|
||||
import { generateRandomString } from '@app/common/helper/randomString';
|
||||
import { In, IsNull, Not } from 'typeorm';
|
||||
import { In, IsNull, Not, QueryRunner } from 'typeorm';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { UserEntity } from '@app/common/modules/user/entities';
|
||||
import { RoleType } from '@app/common/constants/role.type.enum';
|
||||
@ -15,10 +20,11 @@ import {
|
||||
import { CheckEmailDto } from '../dtos/check-email.dto';
|
||||
import { UserRepository } from '@app/common/modules/user/repositories';
|
||||
import { EmailService } from '@app/common/util/email.service';
|
||||
import { SpaceEntity } from '@app/common/modules/space';
|
||||
import { SpaceEntity, SpaceRepository } from '@app/common/modules/space';
|
||||
import { ActivateCodeDto } from '../dtos/active-code.dto';
|
||||
import { UserSpaceService } from 'src/users/services';
|
||||
import { SpaceUserService } from 'src/space/services';
|
||||
import { UpdateUserInvitationDto } from '../dtos/update.invite-user.dto';
|
||||
|
||||
@Injectable()
|
||||
export class InviteUserService {
|
||||
@ -29,7 +35,7 @@ export class InviteUserService {
|
||||
private readonly inviteUserSpaceRepository: InviteUserSpaceRepository,
|
||||
private readonly userSpaceService: UserSpaceService,
|
||||
private readonly spaceUserService: SpaceUserService,
|
||||
|
||||
private readonly spaceRepository: SpaceRepository,
|
||||
private readonly dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
@ -259,4 +265,214 @@ export class InviteUserService {
|
||||
);
|
||||
}
|
||||
}
|
||||
async updateUserInvitation(
|
||||
dto: UpdateUserInvitationDto,
|
||||
invitedUserUuid: string,
|
||||
): Promise<BaseResponseDto> {
|
||||
const { projectUuid } = dto;
|
||||
|
||||
const queryRunner = this.dataSource.createQueryRunner();
|
||||
await queryRunner.startTransaction();
|
||||
|
||||
try {
|
||||
// Fetch the user's existing data in the project
|
||||
const userOldData = await this.inviteUserRepository.findOne({
|
||||
where: { uuid: invitedUserUuid, project: { uuid: projectUuid } },
|
||||
});
|
||||
|
||||
if (!userOldData) {
|
||||
throw new HttpException('User not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// Perform update actions if status is 'INVITED'
|
||||
if (
|
||||
userOldData.status === UserStatusEnum.INVITED ||
|
||||
userOldData.status === UserStatusEnum.DISABLED
|
||||
) {
|
||||
await this.updateWhenUserIsInviteOrDisable(
|
||||
queryRunner,
|
||||
dto,
|
||||
invitedUserUuid,
|
||||
);
|
||||
} else if (userOldData.status === UserStatusEnum.ACTIVE) {
|
||||
await this.updateWhenUserIsActive(queryRunner, dto, invitedUserUuid);
|
||||
}
|
||||
|
||||
await queryRunner.commitTransaction();
|
||||
|
||||
return new SuccessResponseDto({
|
||||
statusCode: HttpStatus.OK,
|
||||
success: true,
|
||||
message: 'User invitation updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
await queryRunner.rollbackTransaction();
|
||||
|
||||
// Throw an appropriate HTTP exception
|
||||
throw error instanceof HttpException
|
||||
? error
|
||||
: new HttpException(
|
||||
'An unexpected error occurred while updating the user',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
} finally {
|
||||
await queryRunner.release();
|
||||
}
|
||||
}
|
||||
|
||||
private async updateWhenUserIsInviteOrDisable(
|
||||
queryRunner: QueryRunner,
|
||||
dto: UpdateUserInvitationDto,
|
||||
invitedUserUuid: string,
|
||||
): Promise<void> {
|
||||
const { firstName, lastName, jobTitle, phoneNumber, roleUuid, spaceUuids } =
|
||||
dto;
|
||||
|
||||
// Update user invitation details
|
||||
await queryRunner.manager.update(
|
||||
this.inviteUserRepository.target,
|
||||
{ uuid: invitedUserUuid },
|
||||
{
|
||||
firstName,
|
||||
lastName,
|
||||
jobTitle,
|
||||
phoneNumber,
|
||||
roleType: { uuid: roleUuid },
|
||||
},
|
||||
);
|
||||
|
||||
// Remove old space associations
|
||||
await queryRunner.manager.delete(this.inviteUserSpaceRepository.target, {
|
||||
inviteUser: { uuid: invitedUserUuid },
|
||||
});
|
||||
|
||||
// Save new space associations
|
||||
const spaceData = spaceUuids.map((spaceUuid) => ({
|
||||
inviteUser: { uuid: invitedUserUuid },
|
||||
space: { uuid: spaceUuid },
|
||||
}));
|
||||
await queryRunner.manager.save(
|
||||
this.inviteUserSpaceRepository.target,
|
||||
spaceData,
|
||||
);
|
||||
}
|
||||
private async updateWhenUserIsActive(
|
||||
queryRunner: QueryRunner,
|
||||
dto: UpdateUserInvitationDto,
|
||||
invitedUserUuid: string,
|
||||
): Promise<void> {
|
||||
const {
|
||||
firstName,
|
||||
lastName,
|
||||
jobTitle,
|
||||
phoneNumber,
|
||||
roleUuid,
|
||||
spaceUuids,
|
||||
projectUuid,
|
||||
} = dto;
|
||||
|
||||
const user = await this.userRepository.findOne({
|
||||
where: { inviteUser: { uuid: invitedUserUuid } },
|
||||
relations: ['userSpaces.space', 'userSpaces.space.community'],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new HttpException(
|
||||
`User with invitedUserUuid ${invitedUserUuid} not found`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
// Update user details
|
||||
await queryRunner.manager.update(
|
||||
this.inviteUserRepository.target,
|
||||
{ uuid: invitedUserUuid },
|
||||
{
|
||||
firstName,
|
||||
lastName,
|
||||
jobTitle,
|
||||
phoneNumber,
|
||||
roleType: { uuid: roleUuid },
|
||||
},
|
||||
);
|
||||
|
||||
// Disassociate the user from all current spaces
|
||||
const disassociatePromises = user.userSpaces.map((userSpace) =>
|
||||
this.spaceUserService
|
||||
.disassociateUserFromSpace({
|
||||
communityUuid: userSpace.space.community.uuid,
|
||||
spaceUuid: userSpace.space.uuid,
|
||||
userUuid: user.uuid,
|
||||
projectUuid,
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
`Failed to disassociate user from space ${userSpace.space.uuid}:`,
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}),
|
||||
);
|
||||
|
||||
await Promise.allSettled(disassociatePromises);
|
||||
|
||||
// Process new spaces
|
||||
const associatePromises = spaceUuids.map(async (spaceUuid) => {
|
||||
try {
|
||||
// Fetch space details
|
||||
const spaceDetails = await this.getSpaceByUuid(spaceUuid);
|
||||
|
||||
// Fetch device UUIDs for the space
|
||||
const deviceUUIDs =
|
||||
await this.userSpaceService.getDeviceUUIDsForSpace(spaceUuid);
|
||||
|
||||
// Grant permissions to the user for all devices in the space
|
||||
await this.userSpaceService.addUserPermissionsToDevices(
|
||||
user.uuid,
|
||||
deviceUUIDs,
|
||||
);
|
||||
|
||||
// Associate the user with the new space
|
||||
await this.spaceUserService.associateUserToSpace({
|
||||
communityUuid: spaceDetails.communityUuid,
|
||||
spaceUuid: spaceUuid,
|
||||
userUuid: user.uuid,
|
||||
projectUuid,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Failed to process space ${spaceUuid}:`, error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(associatePromises);
|
||||
}
|
||||
|
||||
async getSpaceByUuid(spaceUuid: string) {
|
||||
try {
|
||||
const space = await this.spaceRepository.findOne({
|
||||
where: {
|
||||
uuid: spaceUuid,
|
||||
},
|
||||
relations: ['community'],
|
||||
});
|
||||
if (!space) {
|
||||
throw new BadRequestException(`Invalid space UUID ${spaceUuid}`);
|
||||
}
|
||||
return {
|
||||
uuid: space.uuid,
|
||||
createdAt: space.createdAt,
|
||||
updatedAt: space.updatedAt,
|
||||
name: space.spaceName,
|
||||
spaceTuyaUuid: space.community.externalId,
|
||||
communityUuid: space.community.uuid,
|
||||
};
|
||||
} catch (err) {
|
||||
if (err instanceof BadRequestException) {
|
||||
throw err; // Re-throw BadRequestException
|
||||
} else {
|
||||
throw new HttpException('Space not found', HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ import { CommunityRepository } from '@app/common/modules/community/repositories'
|
||||
import { InviteUserRepository } from '@app/common/modules/Invite-user/repositiories';
|
||||
import { ProjectUserController } from './controllers/project-user.controller';
|
||||
import { ProjectUserService } from './services/project-user.service';
|
||||
import { UserSpaceRepository } from '@app/common/modules/user/repositories';
|
||||
|
||||
const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
|
||||
@ -24,6 +25,7 @@ const CommandHandlers = [CreateOrphanSpaceHandler];
|
||||
ProjectUserService,
|
||||
ProjectRepository,
|
||||
InviteUserRepository,
|
||||
UserSpaceRepository,
|
||||
],
|
||||
exports: [ProjectService, CqrsModule],
|
||||
})
|
||||
|
Reference in New Issue
Block a user