All files / libs/tenants/teams/core/src/lib teams.service.ts

65.05% Statements 121/186
54.54% Branches 6/11
25% Functions 2/8
65.05% Lines 121/186

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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 1871x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                     1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x                             1x 1x 1x 1x 1x 1x 1x 1x                         1x  
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { flatten, orderBy, uniq, uniqBy } from 'lodash-es';
import { DataSource, In, Repository } from 'typeorm';
 
import { Team, TeamAssignment, type Company } from '@amalia/core/models';
import { getViewTeamsSubset, SubsetsAccessHelper } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { type Period } from '@amalia/payout-definition/periods/types';
import { TeamRole } from '@amalia/tenants/assignments/teams/types';
 
/**
 * Service team.
 */
@Injectable()
export class TeamsService {
  public constructor(
    private readonly connection: DataSource,
 
    @InjectRepository(Team)
    private readonly teamRepository: Repository<Team>,
    @InjectRepository(TeamAssignment)
    private readonly teamAssignmentRepository: Repository<TeamAssignment>,
  ) {}
 
  /**
   * Find all teams attached to a company
   * @param company company to search teams for
   * @param authenticatedContext
   */
  public async findAll(company: Company, authenticatedContext: AuthenticatedContext): Promise<Team[]> {
    const queryBuilder = this.connection
      .createQueryBuilder(Team, 'team')
      .where('team.company = :companyId', { companyId: company.id })
      .leftJoinAndSelect('team.parentTeam', 'parentTeam')
      .leftJoinAndSelect('team.childrenTeams', 'childrenTeams');

    SubsetsAccessHelper.addConditionForQueryBuilder(authenticatedContext, getViewTeamsSubset, 'team.id', queryBuilder);

    return queryBuilder.getMany();
  }
 
  public async populateTeamChildren(teams: Team[]): Promise<string[]> {
    return uniq(
      flatten(
        await Promise.all(
          teams.map(async (team) => {
            const { teamChildren } = await this.buildTeamHierarchy(team);
            return [team.id, ...teamChildren.map((tc) => tc.id)];
          }),
        ),
      ),
    );
  }
 
  /**
   * Find all teams where the user is assigned or is manager
   * @param company
   * @param userId - Id of the user
   * @param period
   * @param teamRole - If we only want all users' teams where user is either manager or employee
   * @param useHierarchy - Include SubTeams for user's Manager teams
   */
  public async findAllWhereUserAssignedOrManager(
    company: Pick<Company, 'id'>,
    userId: string,
    period?: Period,
    teamRole: TeamRole | null = null,
    useHierarchy: boolean = false,
  ): Promise<Team[]> {
    if (!userId || !company.id) {
      throw new NotFoundException('No param id');
    }
 
    const queryBuilder = this.teamAssignmentRepository.createQueryBuilder('teamAssignment');
    queryBuilder.where('teamAssignment.company = :companyId', { companyId: company.id });
    queryBuilder.leftJoinAndSelect('teamAssignment.team', 'team');
    queryBuilder.andWhere('teamAssignment.user = :userId', {
      userId,
    });
    if (teamRole) {
      queryBuilder.andWhere('teamAssignment.teamRole = :teamRole', {
        teamRole,
      });
    }
    if (period) {
      // Period StartDate <= EffectiveUntil + Period EndDate >= EffectiveAsOf
      const { startDate, endDate } = period;
      queryBuilder.andWhere(
        '(teamAssignment.effectiveAsOf IS NULL OR teamAssignment.effectiveAsOf <= :endDate)' +
          ' AND (teamAssignment.effectiveUntil IS NULL OR teamAssignment.effectiveUntil >= :startDate)',
        { endDate, startDate },
      );
    }
    const userTeamAssignments = orderBy(await queryBuilder.getMany(), 'createdAt');
 
    const userTeamManagers = userTeamAssignments.filter((ta) => ta.teamRole === TeamRole.TEAM_MANAGER);
 
    let userTeams;
 
    if (useHierarchy) {
      const managerTeamsAndSubTeams = await this.populateTeamChildren(userTeamManagers.map((ass) => ass.team!));
      userTeams = uniq([...userTeamAssignments.map((ta) => ta.team!.id), ...managerTeamsAndSubTeams]);
    } else {
      userTeams = uniq(userTeamAssignments.map((ta) => ta.team!.id));
    }
 
    return this.teamRepository.find({
      where: {
        company: { id: company.id },
        id: In(userTeams),
      },
      relations: ['teamAssignments', 'teamAssignments.user'],
    });
  }
 
  /**
   *  Build the whole hierarchy of a team, including sub-parent, parent,  child, subchilds, sub-subChilds, etc...
   * @param team
   * @param depth the deps of the parent / children hierarchy
   * @returns the full hierarchy in 2 records, teamParents and teamChildren
   */
  public async buildTeamHierarchy(team: Team, depth?: number) {
    const parents = await this.connection.getTreeRepository(Team).findAncestors(team, { depth });
    const children = await this.connection.getTreeRepository(Team).findDescendants(team, { depth });

    return {
      teamParents: parents.filter((t) => t.id !== team.id),
      teamChildren: children.filter((t) => t.id !== team.id),
    };
  }
 
  /**
   * Given a list of team, returns the list of parent teams of those teams.
   * @param teams
   */
  public async getParentTeams(teams: Team[]) {
    const parentTeams = (
      await Promise.all(teams.map((t) => this.connection.getTreeRepository(Team).findAncestors(t)))
    ).flat();

    return uniqBy(parentTeams, (t) => t.id);
  }
 
  /**
   * Find team by id.
   * @param company
   * @param id of the team
   * @throws {NotFoundException}
   */
  public async findById(company: Company, id: string): Promise<Team> {
    const team = await this.teamRepository.findOne({
      where: {
        company: { id: company.id },
        id,
      },
      relations: ['parentTeam', 'childrenTeams'],
    });

    if (!team) {
      throw new NotFoundException();
    }

    return team;
  }
 
  /**
   * Find a list of teams via their ids
   * @param company
   * @param ids
   * @returns
   */
  public async findByIds(company: Company, ids?: string[]): Promise<Team[]> {
    if (!ids || ids.length === 0) {
      return [];
    }

    return this.teamRepository.find({
      where: {
        company: { id: company.id },
        id: In(ids),
      },
      relations: ['parentTeam', 'childrenTeams'],
    });
  }
}