Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PB-1841] feat: added change users role in workspace team #294

Merged
merged 3 commits into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/modules/workspaces/dto/change-user-role.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
import { User } from '../../user/user.domain';
import { WorkspaceRole } from '../guards/workspace-required-access.decorator';

export class ChangeUserRoleDto {
@ApiProperty({
example: 'User Id',
description: 'Uuid of user to modify',
})
@IsNotEmpty()
userId: User['uuid'];

@ApiProperty({
example: 'TEAM_MANAGER',
description: 'Role to be assigned to user',
})
@IsNotEmpty()
role: Omit<WorkspaceRole, 'OWNER'>;
}
14 changes: 14 additions & 0 deletions src/modules/workspaces/repositories/team.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,20 @@ export class SequelizeWorkspaceTeamRepository {
};
}

async getTeamUser(
userUuid: UserAttributes['uuid'],
teamId: WorkspaceTeamAttributes['id'],
): Promise<WorkspaceTeamUser | null> {
const teamUser = await this.teamUserModel.findOne({
where: {
memberId: userUuid,
teamId,
},
});

return teamUser ? this.teamUserToDomain(teamUser) : null;
}

async getTeamById(
teamId: WorkspaceTeamAttributes['id'],
): Promise<WorkspaceTeam | null> {
Expand Down
34 changes: 34 additions & 0 deletions src/modules/workspaces/workspaces.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { DeepMocked, createMock } from '@golevelup/ts-jest';
import { BadRequestException } from '@nestjs/common';
import { WorkspacesController } from './workspaces.controller';
import { WorkspacesUsecases } from './workspaces.usecase';
import { WorkspaceRole } from './guards/workspace-required-access.decorator';

describe('Workspace Controller', () => {
let workspacesController: WorkspacesController;
let workspacesUsecases: DeepMocked<WorkspacesUsecases>;

beforeEach(async () => {
workspacesUsecases = createMock<WorkspacesUsecases>();

workspacesController = new WorkspacesController(workspacesUsecases);
});

it('should be defined', () => {
expect(workspacesController).toBeDefined();
});

describe('PATCH /:workspaceId/teams/:teamId/members/role', () => {
it('When there is an error while updating user role, then the error is returned', async () => {
workspacesUsecases.changeUserRole.mockRejectedValueOnce(
new BadRequestException(),
);
await expect(
workspacesController.changeMemberRole('', '', {
userId: '',
role: WorkspaceRole.MEMBER,
}),
).rejects.toThrow(BadRequestException);
});
});
});
17 changes: 17 additions & 0 deletions src/modules/workspaces/workspaces.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
WorkspaceRole,
} from './guards/workspace-required-access.decorator';
import { CreateWorkspaceInviteDto } from './dto/create-workspace-invite.dto';
import { WorkspaceTeamAttributes } from './attributes/workspace-team.attributes';
import { ChangeUserRoleDto } from './dto/change-user-role.dto';

@ApiTags('Workspaces')
@Controller('workspaces')
Expand Down Expand Up @@ -98,4 +100,19 @@ export class WorkspacesController {
async getTeamMembers() {
throw new NotImplementedException();
}

@Patch('/:workspaceId/teams/:teamId/members/role')
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
@UseGuards(WorkspaceGuard)
@WorkspaceRequiredAccess(AccessContext.WORKSPACE, WorkspaceRole.OWNER)
async changeMemberRole(
@Param('workspaceId') workspaceId: WorkspaceAttributes['id'],
@Param('teamId') teamId: WorkspaceTeamAttributes['id'],
@Body() changeUserRoleBody: ChangeUserRoleDto,
) {
return this.workspaceUseCases.changeUserRole(
workspaceId,
teamId,
changeUserRoleBody,
);
}
}
164 changes: 164 additions & 0 deletions src/modules/workspaces/workspaces.usecase.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ import {
newUser,
newWorkspace,
newWorkspaceInvite,
newWorkspaceTeam,
newWorkspaceUser,
} from '../../../test/fixtures';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { PreCreatedUser } from '../user/pre-created-user.domain';
import { BridgeService } from '../../externals/bridge/bridge.service';
import { SequelizeWorkspaceTeamRepository } from './repositories/team.repository';
import { WorkspaceRole } from './guards/workspace-required-access.decorator';
import { WorkspaceTeamUser } from './domains/workspace-team-user.domain';

jest.mock('../../middlewares/passport', () => {
const originalModule = jest.requireActual('../../middlewares/passport');
Expand All @@ -29,6 +33,7 @@ jest.mock('../../middlewares/passport', () => {
describe('WorkspacesUsecases', () => {
let service: WorkspacesUsecases;
let workspaceRepository: SequelizeWorkspaceRepository;
let teamRepository: SequelizeWorkspaceTeamRepository;
let userRepository: SequelizeUserRepository;
let userUsecases: UserUseCases;
let mailerService: MailerService;
Expand All @@ -46,6 +51,9 @@ describe('WorkspacesUsecases', () => {
workspaceRepository = module.get<SequelizeWorkspaceRepository>(
SequelizeWorkspaceRepository,
);
teamRepository = module.get<SequelizeWorkspaceTeamRepository>(
SequelizeWorkspaceTeamRepository,
);
userRepository = module.get<SequelizeUserRepository>(
SequelizeUserRepository,
);
Expand Down Expand Up @@ -311,6 +319,162 @@ describe('WorkspacesUsecases', () => {
});
});

describe('changeUserRole', () => {
it('When team does not exist, then error is throw', async () => {
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
jest.spyOn(teamRepository, 'getTeamById').mockResolvedValue(null);

await expect(
service.changeUserRole('workspaceId', 'teamId', {
userId: 'userId',
role: WorkspaceRole.MEMBER,
}),
).rejects.toThrow(NotFoundException);
});

it('When user is not part of team, then error is throw', async () => {
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
jest
.spyOn(teamRepository, 'getTeamById')
.mockResolvedValue(newWorkspaceTeam());
jest.spyOn(teamRepository, 'getTeamUser').mockResolvedValue(null);

await expect(
service.changeUserRole('workspaceId', 'teamId', {
userId: 'useriD',
role: WorkspaceRole.MEMBER,
}),
).rejects.toThrow(NotFoundException);
});

it('When user does not exist, then error is throw', async () => {
jest
.spyOn(teamRepository, 'getTeamById')
.mockResolvedValue(newWorkspaceTeam());
jest.spyOn(teamRepository, 'getTeamUser').mockResolvedValue(
new WorkspaceTeamUser({
id: '',
teamId: '',
memberId: '',
createdAt: new Date(),
updatedAt: new Date(),
}),
);
jest.spyOn(userRepository, 'findByUuid').mockResolvedValue(null);

await expect(
service.changeUserRole('workspaceId', 'teamId', {
userId: 'userId',
role: WorkspaceRole.MEMBER,
}),
).rejects.toThrow(BadRequestException);
});

it('When user is member is updated to manager, then team manager is updated correctly', async () => {
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
const member = newUser();
const team = newWorkspaceTeam();

jest.spyOn(teamRepository, 'getTeamById').mockResolvedValue(team);
jest.spyOn(teamRepository, 'getTeamUser').mockResolvedValue(
new WorkspaceTeamUser({
id: '',
teamId: team.id,
memberId: member.uuid,
createdAt: new Date(),
updatedAt: new Date(),
}),
);
jest.spyOn(userRepository, 'findByUuid').mockResolvedValue(member);

await service.changeUserRole('workspaceId', 'teamId', {
userId: 'userId',
role: WorkspaceRole.MANAGER,
});

expect(teamRepository.updateById).toHaveBeenCalledWith(team.id, {
managerId: member.uuid,
});
});

it('When user is manager is updated to member, then owner is assigned as manager', async () => {
apsantiso marked this conversation as resolved.
Show resolved Hide resolved
const manager = newUser();
const workspaceOwner = newUser();
const team = newWorkspaceTeam({ manager: manager });
const workspace = newWorkspace({ owner: workspaceOwner });

jest.spyOn(teamRepository, 'getTeamById').mockResolvedValue(team);
jest.spyOn(teamRepository, 'getTeamUser').mockResolvedValue(
new WorkspaceTeamUser({
id: '',
teamId: team.id,
memberId: manager.uuid,
createdAt: new Date(),
updatedAt: new Date(),
}),
);
jest.spyOn(userRepository, 'findByUuid').mockResolvedValue(manager);
jest.spyOn(workspaceRepository, 'findById').mockResolvedValue(workspace);

await service.changeUserRole('workspaceId', 'teamId', {
userId: 'userId',
role: WorkspaceRole.MEMBER,
});

expect(teamRepository.updateById).toHaveBeenCalledWith(team.id, {
managerId: workspaceOwner.uuid,
});
});

it('When user is already manager and tries to update their role to manager, then it does nothing ', async () => {
const manager = newUser();
const workspaceOwner = newUser();
const team = newWorkspaceTeam({ manager: manager });
const workspace = newWorkspace({ owner: workspaceOwner });

jest.spyOn(teamRepository, 'getTeamById').mockResolvedValue(team);
jest.spyOn(teamRepository, 'getTeamUser').mockResolvedValue(
new WorkspaceTeamUser({
id: '',
teamId: team.id,
memberId: manager.uuid,
createdAt: new Date(),
updatedAt: new Date(),
}),
);
jest.spyOn(userRepository, 'findByUuid').mockResolvedValue(manager);
jest.spyOn(workspaceRepository, 'findById').mockResolvedValue(workspace);

await service.changeUserRole('workspaceId', 'teamId', {
userId: 'userId',
role: WorkspaceRole.MANAGER,
});

expect(teamRepository.updateById).not.toHaveBeenCalled();
});

it('When user is already member and tries to update their role to member, then it does nothing', async () => {
const member = newUser();
const team = newWorkspaceTeam();

jest.spyOn(teamRepository, 'getTeamById').mockResolvedValue(team);
jest.spyOn(teamRepository, 'getTeamUser').mockResolvedValue(
new WorkspaceTeamUser({
id: '',
teamId: team.id,
memberId: member.uuid,
createdAt: new Date(),
updatedAt: new Date(),
}),
);
jest.spyOn(userRepository, 'findByUuid').mockResolvedValue(member);

await service.changeUserRole('workspaceId', 'teamId', {
userId: 'userId',
role: WorkspaceRole.MEMBER,
});

expect(teamRepository.updateById).not.toHaveBeenCalled();
});
});

describe('getAssignableSpaceInWorkspace', () => {
const workspace = newWorkspace();
const workspaceDefaultUser = newUser();
Expand Down
52 changes: 52 additions & 0 deletions src/modules/workspaces/workspaces.usecase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import { CreateWorkspaceInviteDto } from './dto/create-workspace-invite.dto';
import { MailerService } from '../../externals/mailer/mailer.service';
import { ConfigService } from '@nestjs/config';
import { Sign } from '../../middlewares/passport';
import { ChangeUserRoleDto } from './dto/change-user-role.dto';
import { WorkspaceTeamAttributes } from './attributes/workspace-team.attributes';
import { WorkspaceRole } from './guards/workspace-required-access.decorator';

@Injectable()
export class WorkspacesUsecases {
Expand Down Expand Up @@ -328,6 +331,55 @@ export class WorkspacesUsecases {
return this.workspaceRepository.findById(workspaceId);
}

async changeUserRole(
workspaceId: WorkspaceAttributes['id'],
teamId: WorkspaceTeamAttributes['id'],
changeUserRoleDto: ChangeUserRoleDto,
): Promise<void> {
const { role, userId } = changeUserRoleDto;

const [team, teamUser] = await Promise.all([
this.teamRepository.getTeamById(teamId),
this.teamRepository.getTeamUser(userId, teamId),
]);

if (!team) {
throw new NotFoundException('Team not found.');
}

if (!teamUser) {
throw new NotFoundException('User not part of the team.');
}

const user = await this.userRepository.findByUuid(teamUser.memberId);

if (!user) {
throw new BadRequestException();
}

const isUserAlreadyManager = team.isUserManager(user);

let newManagerId: UserAttributes['uuid'];

if (role === WorkspaceRole.MEMBER && isUserAlreadyManager) {
const workspaceOwner =
await this.workspaceRepository.findById(workspaceId);
newManagerId = workspaceOwner.ownerId;
}

if (role === WorkspaceRole.MANAGER && !isUserAlreadyManager) {
newManagerId = user.uuid;
}

if (!newManagerId) {
return;
}

await this.teamRepository.updateById(team.id, {
managerId: newManagerId,
});
}

findUserInTeam(
userUuid: string,
teamId: string,
Expand Down
Loading