Skip to content
Merged
Changes from all 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
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { HttpException, HttpStatus, Inject, Injectable, InternalServerErrorException, Scope } from '@nestjs/common';
import AbstractUseCase from '../../../common/abstract-use.case.js';
import { IGlobalDatabaseContext } from '../../../common/application/global-database-context.interface.js';
import { BaseType } from '../../../common/data-injection.tokens.js';
import { Messages } from '../../../exceptions/text/messages.js';
import { RegisteredUserDs } from '../application/data-structures/registered-user.ds.js';
import { IDeleteUserAccount } from './user-use-cases.interfaces.js';
import { SaasCompanyGatewayService } from '../../../microservices/gateways/saas-gateway.ts/saas-company-gateway.service.js';
import { isSaaS } from '../../../helpers/app/is-saas.js';

@Injectable()
@Injectable({ scope: Scope.REQUEST })
export class DeleteUserAccountUseCase
extends AbstractUseCase<string, Omit<RegisteredUserDs, 'token'>>
implements IDeleteUserAccount
{
constructor(
@Inject(BaseType.GLOBAL_DB_CONTEXT)
protected _dbContext: IGlobalDatabaseContext,
private readonly saasCompanyGatewayService: SaasCompanyGatewayService,
) {
super();
}
Expand All @@ -28,7 +31,34 @@ export class DeleteUserAccountUseCase
HttpStatus.BAD_REQUEST,
);
}
await this._dbContext.userRepository.deleteUserEntity(foundUser);

const userCompanyId = foundUser.company.id;

const usersCountInCompany = await this._dbContext.userRepository.countUsersInCompany(userCompanyId);

if (usersCountInCompany <= 1) {
const foundFullCompany = await this._dbContext.companyInfoRepository.findFullCompanyInfoByUserId(userId);
const { users, connections, invitations, id } = foundFullCompany;
if (isSaaS()) {
const deleteResult = await this.saasCompanyGatewayService.deleteCompany(id);
if (!deleteResult) {
throw new InternalServerErrorException(Messages.SAAS_DELETE_COMPANY_FAILED_UNHANDLED_ERROR);
}
}
if (users.length) {
await this._dbContext.userRepository.remove(users);
}
if (connections.length) {
await this._dbContext.connectionRepository.remove(connections);
}
if (invitations.length) {
await this._dbContext.invitationInCompanyRepository.remove(invitations);
}
await this._dbContext.companyInfoRepository.remove(foundFullCompany);
} else {
await this._dbContext.userRepository.deleteUserEntity(foundUser);
}

return {
id: foundUser.id,
email: foundUser.email,
Expand Down