Skip to content

Commit

Permalink
rework add user in group use case
Browse files Browse the repository at this point in the history
  • Loading branch information
Artuomka committed Jul 31, 2024
1 parent f356c7e commit 527ae0a
Show file tree
Hide file tree
Showing 10 changed files with 37 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class VerifyInviteUserInCompanyAndConnectionGroupUseCase
newUser.company = foundInvitation.company;
const savedUser = await this._dbContext.userRepository.saveUserEntity(newUser);
if (groupId) {
const foundGroup = await this._dbContext.groupRepository.findGroupById(groupId);
const foundGroup = await this._dbContext.groupRepository.findGroupByIdWithConnectionAndUsers(groupId);
if (!foundGroup) {
throw new HttpException(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const groupCustomRepositoryExtension: IGroupRepository = {
return await qb.getMany();
},

async findGroupById(groupId: string): Promise<GroupEntity> {
async findGroupByIdWithConnectionAndUsers(groupId: string): Promise<GroupEntity> {
const qb = this.createQueryBuilder('group')
.leftJoinAndSelect('group.connection', 'connection')
.leftJoinAndSelect('group.users', 'user')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export interface IGroupRepository {

findAllUserGroupsInConnection(connectionId: string, cognitoUserName: string): Promise<Array<GroupEntity>>;

findGroupById(groupId: string): Promise<GroupEntity>;
findGroupByIdWithConnectionAndUsers(groupId: string): Promise<GroupEntity>;

findAllUserGroups(userId: string): Promise<Array<GroupEntity>>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class DeleteGroupUseCase extends AbstractUseCase<string, DeletedGroupResu
}

protected async implementation(groupId: string): Promise<DeletedGroupResultDs> {
const groupToDelete = await this._dbContext.groupRepository.findGroupById(groupId);
const groupToDelete = await this._dbContext.groupRepository.findGroupByIdWithConnectionAndUsers(groupId);
if (groupToDelete.isMain) {
throw new HttpException(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class RemoveUserFromGroupUseCase
HttpStatus.BAD_REQUEST,
);
}
const groupToUpdate = await this._dbContext.groupRepository.findGroupById(groupId);
const groupToUpdate = await this._dbContext.groupRepository.findGroupByIdWithConnectionAndUsers(groupId);
if (groupToUpdate.isMain && groupToUpdate.users.length <= 1) {
throw new HttpException(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import { AddedUserInGroupDs } from '../application/data-sctructures/added-user-i
import { IAddUserInGroup } from './use-cases.interfaces.js';
import { Messages } from '../../../exceptions/text/messages.js';
import { SaasCompanyGatewayService } from '../../../microservices/gateways/saas-gateway.ts/saas-company-gateway.service.js';
import { ConnectionEntity } from '../../connection/connection.entity.js';
import { UserEntity } from '../../user/user.entity.js';
import { sendEmailConfirmation, sendInvitationToGroup } from '../../email/send-email.js';
import { UserInvitationEntity } from '../../user/user-invitation/user-invitation.entity.js';
import { buildFoundGroupResponseDto } from '../utils/biuld-found-group-response.dto.js';
import { slackPostMessage } from '../../../helpers/index.js';
import { isSaaS } from '../../../helpers/app/is-saas.js';

export class AddUserInGroupUseCase
extends AbstractUseCase<AddUserInGroupWithSaaSDs, AddedUserInGroupDs>
Expand All @@ -27,7 +27,8 @@ export class AddUserInGroupUseCase

protected async implementation(inputData: AddUserInGroupWithSaaSDs): Promise<AddedUserInGroupDs> {
const { email, groupId, inviterId } = inputData;
const foundGroup = await this._dbContext.groupRepository.findGroupById(groupId);
const foundGroup = await this._dbContext.groupRepository.findGroupByIdWithConnectionAndUsers(groupId);

const foundConnection =
await this._dbContext.connectionRepository.getConnectionByGroupIdWithCompanyAndUsersInCompany(groupId);
if (!foundConnection) {
Expand All @@ -39,39 +40,46 @@ export class AddUserInGroupUseCase
);
}

if (!foundConnection.company) {
if (!foundConnection.company || !foundConnection.company.id) {
throw new HttpException(
{
message: Messages.COMPANY_NOT_EXISTS_IN_CONNECTION,
},
HttpStatus.NOT_FOUND,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}

const foundUser =
await this._dbContext.userRepository.findUserByEmailEndCompanyIdWithEmailVerificationAndInvitation(
email,
foundConnection.company.id,
);
const companyWithUsers = await this._dbContext.companyInfoRepository.findCompanyInfoWithUsersById(
foundConnection.company.id,
);

if (!foundUser) {
if (!companyWithUsers) {
throw new HttpException(
{
message: Messages.USER_NOT_INVITED_IN_COMPANY(email),
message: Messages.COMPANY_NOT_EXISTS_IN_CONNECTION,
},
HttpStatus.BAD_REQUEST,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
const isUserInCompany = this.isUserAlreadyInCompany(foundConnection, foundUser);
const canInviteMoreUsers = await this.saasCompanyGatewayService.canInviteMoreUsers(foundConnection.company.id);
if (!canInviteMoreUsers && !isUserInCompany) {

const foundUser = companyWithUsers.users.find((u) => u.email === email);
if (!foundUser) {
throw new HttpException(
{
message: Messages.MAXIMUM_FREE_INVITATION_REACHED,
message: Messages.USER_NOT_INVITED_IN_COMPANY(email),
},
HttpStatus.PAYMENT_REQUIRED,
HttpStatus.BAD_REQUEST,
);
}
//todo remove in future
if (isSaaS()) {
const saasFoundCompany = await this.saasCompanyGatewayService.getCompanyInfo(foundConnection.company.id);
const saasFoundUserInCompany = saasFoundCompany?.users.find((u) => u.email === email);

if (foundUser && !saasFoundUserInCompany) {
await slackPostMessage('probable desynchronization of users (adding a user to a group)');
}
}

if (foundUser && foundUser.isActive) {
const userAlreadyAdded = !!foundGroup.users.find((u) => u.id === foundUser.id);
Expand All @@ -86,7 +94,6 @@ export class AddUserInGroupUseCase

foundGroup.users.push(foundUser);
const savedGroup = await this._dbContext.groupRepository.saveNewOrUpdatedGroup(foundGroup);
delete savedGroup.connection;
return {
group: buildFoundGroupResponseDto(savedGroup),
message: Messages.USER_ADDED_IN_GROUP(foundUser.email),
Expand All @@ -110,7 +117,7 @@ export class AddUserInGroupUseCase
foundGroup.users.push(foundUser);
}
const savedGroup = await this._dbContext.groupRepository.saveNewOrUpdatedGroup(foundGroup);
delete savedGroup.connection;

const newEmailVerification =
await this._dbContext.emailVerificationRepository.createOrUpdateEmailVerification(foundUser);
const confiramtionMailResult = await sendEmailConfirmation(
Expand Down Expand Up @@ -151,17 +158,4 @@ export class AddUserInGroupUseCase
};
}
}

private isUserAlreadyInCompany(connectionWithCompanyAndUsers: ConnectionEntity, foundUser: UserEntity): boolean {
if (
!connectionWithCompanyAndUsers.company ||
!connectionWithCompanyAndUsers.company.users ||
!connectionWithCompanyAndUsers.company.users.length ||
!foundUser
) {
return false;
}
const foundUserInCompany = connectionWithCompanyAndUsers.company.users.find((u) => u.id === foundUser.id);
return !!foundUserInCompany;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class UpdateGroupTitleUseCase

protected async implementation(groupData: UpdateGroupTitleDto): Promise<FoundGroupDataInfoDs> {
const { groupId, title } = groupData;
const groupToUpdate = await this._dbContext.groupRepository.findGroupById(groupId);
const groupToUpdate = await this._dbContext.groupRepository.findGroupByIdWithConnectionAndUsers(groupId);
if (!groupToUpdate) {
throw new HttpException(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Messages } from '../../../exceptions/text/messages.js';
import { Constants } from '../../../helpers/constants/constants.js';
import { Encryptor } from '../../../helpers/encryption/encryptor.js';
import { ValidationHelper } from '../../../helpers/validators/validation-helper.js';
import { UserHelperService } from '../../user/user-helper.service.js';
import { generateGwtToken, IToken } from '../../user/utils/generate-gwt-token.js';
import { VerifyAddUserInGroupDs } from '../application/data-sctructures/verify-add-user-in-group.ds.js';
import { IVerifyAddUserInGroup } from './use-cases.interfaces.js';
Expand All @@ -20,7 +19,6 @@ export class VerifyAddUserInGroupUseCase
constructor(
@Inject(BaseType.GLOBAL_DB_CONTEXT)
protected _dbContext: IGlobalDatabaseContext,
private readonly userHelperService: UserHelperService,
) {
super();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,14 @@ export const userCustomRepositoryExtension: IUserRepository = {

async findUserByEmailEndCompanyIdWithEmailVerificationAndInvitation(
email: string,
companyId?: string,
companyId: string,
): Promise<UserEntity> {
const usersQb = this.createQueryBuilder('user')
.leftJoinAndSelect('user.email_verification', 'email_verification')
.leftJoinAndSelect('user.user_invitation', 'user_invitation')
.leftJoinAndSelect('user.company', 'company')
.where('user.email = :userEmail', { userEmail: email });
if (companyId) {
usersQb.andWhere('company.id = :companyId', { companyId: companyId });
}
.where('user.email = :userEmail', { userEmail: email })
.andWhere('company.id = :companyId', { companyId: companyId });
return await usersQb.getOne();
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface IUserRepository {

findOneUserWithEmailVerification(userId: string): Promise<UserEntity>;

findUserByEmailEndCompanyIdWithEmailVerificationAndInvitation(email: string, companyId?: string): Promise<UserEntity>;
findUserByEmailEndCompanyIdWithEmailVerificationAndInvitation(email: string, companyId: string): Promise<UserEntity>;

deleteUserEntity(user: UserEntity): Promise<UserEntity>;

Expand Down

0 comments on commit 527ae0a

Please sign in to comment.