All files / libs/tenants/teams/core/src/lib/use-cases create-team.use-case.ts

93.1% Statements 108/116
82.35% Branches 14/17
100% Functions 5/5
93.1% Lines 108/116

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 1171x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 5x 5x 5x 5x 5x 5x 15x 15x 15x 4x 4x           4x 4x 4x 15x 1x 1x 1x       15x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 7x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 15x 15x 15x 15x 1x  
import {
  ConflictException,
  ForbiddenException,
  Logger,
  NotFoundException,
  UnprocessableEntityException,
} from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
 
import { Company, Team, TEAM_NAME_UNIQUE_CONSTRAINT } from '@amalia/core/models';
import { isUniqueViolationError } from '@amalia/ext/typeorm';
import { assert, toError } from '@amalia/ext/typescript';
import { canModifyTeams, defineAbilityFor } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { CreateTeamRequest } from '@amalia/tenants/teams/types';
 
import { TeamCreatedEvent } from '../events/team-created-event';
 
export class CreateTeamUseCase {
  private readonly logger = new Logger(CreateTeamUseCase.name);
 
  public constructor(
    private readonly eventBus: EventBus,
    @InjectRepository(Team)
    private readonly teamsRepository: Repository<Team>,
  ) {}
 
  public async execute({
    company,
    authenticatedContext,
    createTeamRequest,
  }: {
    company: Company;
    authenticatedContext: AuthenticatedContext;
    createTeamRequest: CreateTeamRequest;
  }) {
    this.assertCanExecute(authenticatedContext);
    const parentTeam = await this.getAndValidateParentTeam(company, createTeamRequest.parentTeamId);
 
    try {
      const createdTeam = await this.teamsRepository.save({
        company,
        user: authenticatedContext.user,
        name: createTeamRequest.name,
        parentTeamId: parentTeam?.id ?? null,
        parentTeam,
      });
 
      this.publishLog({ authenticatedContext, team: createdTeam }).catch((err) => {
        this.logger.error({
          message: 'Failed to publish TeamCreatedEvent',
          error: toError(err),
          team: createdTeam,
        });
      });
 
      return createdTeam;
    } catch (err) {
      if (isUniqueViolationError(err) && err.driverError.constraint === TEAM_NAME_UNIQUE_CONSTRAINT) {
        throw new ConflictException(`A team with the name ${createTeamRequest.name} already exists`);
      }

      throw err;
    }
  }
 
  private async publishLog({
    authenticatedContext,
    team,
  }: {
    authenticatedContext: AuthenticatedContext;
    team: Pick<Team, 'id' | 'name' | 'parentTeam'>;
  }) {
    await this.eventBus.publish(
      new TeamCreatedEvent({
        authenticatedContext,
        object: RecordObject.TEAM,
        type: RecordType.CREATE,
        values: {
          target: { id: team.id, name: team.name },
          newValues: {
            name: team.name,
            parentTeam: team.parentTeam?.name ?? null,
          },
        },
      }),
    );
  }
 
  private async getAndValidateParentTeam(company: Company, parentTeamId: CreateTeamRequest['parentTeamId']) {
    if (!parentTeamId) {
      return undefined;
    }
 
    const parentTeam = await this.teamsRepository.findOne({
      where: {
        company: { id: company.id },
        id: parentTeamId,
      },
    });
 
    assert(parentTeam, new NotFoundException(`Parent team with id ${parentTeamId} not found`));
    assert(!parentTeam.archived, new UnprocessableEntityException(`Team ${parentTeam.name} is archived`));
 
    return parentTeam;
  }
 
  private assertCanExecute(authenticatedContext: AuthenticatedContext) {
    const ability = defineAbilityFor(authenticatedContext);
 
    assert(canModifyTeams(ability), new ForbiddenException('You do not have the permission to create teams'));
  }
}