All files / libs/tenants/teams/hierarchy/shared/src/lib HierarchyContext.ts

94.53% Statements 242/256
87.5% Branches 35/40
71.42% Functions 10/14
94.53% Lines 242/256

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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 2571x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x     15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 74x 74x 94x 94x 74x 74x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x     7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 14x 14x 7x 14x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 40x 40x 40x 40x 40x 6x 6x 34x 34x 34x 34x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 82x 82x 54x 54x 23x 54x 4x 4x 4x 54x 34x 34x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 85x 85x 85x 85x 182x 70x 182x 182x 182x 182x 182x 182x 182x 85x 85x 85x 85x 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 { pick, uniqBy } from 'lodash-es';
import { type SetRequired } from 'type-fest';
 
import { dateIsInAssignmentRange, doPeriodsOverlap, toTimestamp, type UnixTimestampInSeconds } from '@amalia/ext/dates';
import { TeamRole, type TeamAssignment } from '@amalia/tenants/assignments/teams/types';
import { type HierarchyContextDehydrated, type HierarchyContextInterface } from '@amalia/tenants/teams/hierarchy/types';
import { type TeamContract } from '@amalia/tenants/teams/types';
import { UserRole, type UserContract } from '@amalia/tenants/users/types';
 
export class HierarchyContext implements HierarchyContextInterface {
  private subTeamsOfEachTeam: HierarchyContextDehydrated['subTeamsOfEachTeam'];
 
  private readonly currentUserAssignments: TeamAssignment[];
 
  public constructor(
    private readonly currentUser: UserContract,
    private readonly teamAssignments: SetRequired<TeamAssignment, 'user'>[],
    teamHierarchy: TeamContract[],
  ) {
    // Check team assignments contains users.
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Falsy when relation isn't loaded.
    if (teamAssignments.some((ta) => !ta.user)) {
      throw new Error('Hierarchy Context should be instantiated with its users.');
    }
 
    this.currentUserAssignments = teamAssignments.filter((t) => t.user.id === currentUser.id);
 
    this.subTeamsOfEachTeam = [UserRole.MANAGER, UserRole.READ_ONLY_MANAGER].includes(currentUser.role)
      ? // If the current user is a manager, populate the subteams.
        // Build the list of teamIds in the hierarchy where the current user can be manager.
        // It avoids dumping the full hierarchy in this class.
        pick(
          HierarchyContext.buildSubTeamsHierarchyTree(teamHierarchy),
          // Filter the list of assignments to retrieve those where the current user is manager.
          this.currentUserAssignments
            .filter((managerAssignment) => managerAssignment.teamRole === TeamRole.TEAM_MANAGER)
            .map((ta) => ta.teamId),
        )
      : {};
  }
 
  /**
   * Get team assignments of the current user at a given date.
   * @param date
   */
  public getUserTeamAssignments(date: Date | UnixTimestampInSeconds): TeamAssignment[] {
    const observationDateTimestamp = toTimestamp(date);
    return this.currentUserAssignments.filter((teamAssignment) =>
      dateIsInAssignmentRange(observationDateTimestamp, teamAssignment),
    );
  }
 
  /**
   * Returns true if the user is a member of the team at a given date.
   *
   * It doesn't support hierarchy, it's only for direct team assignment.
   *
   * @param teamId
   * @param date
   */
  public isTeamMember(teamId: TeamContract['id'], date: Date | UnixTimestampInSeconds): boolean {
    return this.getUserTeamAssignments(date)
      .map((ta) => ta.teamId)
      .includes(teamId);
  }
 
  /**
   * Returns true if the user is managing a specific team at a given date.
   *
   * It supports hierarchy.
   *
   * @param teamId
   * @param date
   */
  public isTeamManager(teamId: TeamContract['id'], date: Date | UnixTimestampInSeconds): boolean {
    return this.getTeamIdsWhereUserIsManager(date).includes(teamId);
  }
 
  private getOngoingManagerAssignmentsOfCurrentUser(observationDateTimestamp: number): TeamAssignment[] {
    return this.currentUserAssignments.filter(
      (managerAssignment) =>
        managerAssignment.teamRole === TeamRole.TEAM_MANAGER &&
        dateIsInAssignmentRange(observationDateTimestamp, managerAssignment),
    );
  }
 
  /**
   * Return the list of users that the current person managed at least one day.
   *
   * It can be interesting for instance if you want to see all statements that can be
   * accessed by a manager. We cannot do an SQL query with the dates of each assignment,
   * so we're going to gather all statements for all the users managed by that person at least
   * one day, then we'll filter out the statements by calling the "isManager" method for
   * the start date of each of them.
   */
  public getAllPeopleCurrentUserManagedAtLeastOneDay(): UserContract[] {
    const currentUserManagerAssignments = this.currentUserAssignments.filter(
      (managerAssignment) => managerAssignment.teamRole === TeamRole.TEAM_MANAGER,
    );
 
    if (!currentUserManagerAssignments.length) {
      return [];
    }
 
    // For each manager assignment I had.
    return uniqBy(
      currentUserManagerAssignments.flatMap((currentUserManagerAssignment) => {
        // Get the list of the teams managed during this period. It's my team and its subteams.
        const teamIdsManagedDuringThisAssignment = new Set([
          currentUserManagerAssignment.teamId,
          ...(this.subTeamsOfEachTeam[currentUserManagerAssignment.teamId] ?? []),
        ]);
 
        return this.teamAssignments
          .filter(
            (employeeAssignment) =>
              // Remove myself
              employeeAssignment.user.id !== currentUserManagerAssignment.user!.id &&
              // Return all the people that have been in one of those teams.
              teamIdsManagedDuringThisAssignment.has(employeeAssignment.teamId) &&
              // And their assignment dates overlaps with when I was manager.
              doPeriodsOverlap(
                {
                  startDate: currentUserManagerAssignment.effectiveAsOf,
                  endDate: currentUserManagerAssignment.effectiveUntil,
                },
                {
                  startDate: employeeAssignment.effectiveAsOf,
                  endDate: employeeAssignment.effectiveUntil,
                },
              ),
          )
          .map((employeeAssignment) => employeeAssignment.user);
      }),
      'id',
    );
  }
 
  /**
   * Get the list of team ids that are managed by the current user.
   * @param date
   */
  public getTeamIdsWhereUserIsManager(date: Date | UnixTimestampInSeconds): TeamContract['id'][] {
    const observationDateTimestamp = toTimestamp(date);
 
    const ongoingManagerAssignments = this.getOngoingManagerAssignmentsOfCurrentUser(observationDateTimestamp);
 
    if (!ongoingManagerAssignments.length) {
      return [];
    }
 
    // Compute the list of teams where the current user is manager based on the hierarchy.
    return ongoingManagerAssignments.flatMap((ma) => [ma.teamId, ...(this.subTeamsOfEachTeam[ma.teamId] ?? [])]);
  }
 
  /**
   * Get the list of all team assignments for which the current user is manager at a given date.
   * @param date
   */
  public getSubordinates(date: Date | UnixTimestampInSeconds) {
    const observationDateTimestamp = toTimestamp(date);
 
    const listOfTeamsWhereCurrentUserIsCurrentlyManager = this.getTeamIdsWhereUserIsManager(observationDateTimestamp);
 
    const listOfTeamsWhereCurrentUserIsAssignedAsManager = new Set(
      this.getOngoingManagerAssignmentsOfCurrentUser(observationDateTimestamp).map((ma) => ma.teamId),
    );
 
    // Knowing all the teams where the current user has authority on the given date, we can filter assignments.
    return this.teamAssignments.filter(
      (employeeAssignment) =>
        listOfTeamsWhereCurrentUserIsCurrentlyManager.includes(employeeAssignment.teamId) &&
        dateIsInAssignmentRange(observationDateTimestamp, employeeAssignment) &&
        // The user is me
        (employeeAssignment.user.id === this.currentUser.id ||
          // OR the user is not a manager.
          employeeAssignment.teamRole !== TeamRole.TEAM_MANAGER ||
          // OR the user is a manager of a team I manage (but not at the same level as me).
          // Because business rules states that if we're two manager of the same team,
          // we technically don't manage each others.
          !listOfTeamsWhereCurrentUserIsAssignedAsManager.has(employeeAssignment.teamId)),
    );
  }
 
  public getSubordinateIds(date: Date | UnixTimestampInSeconds) {
    return this.getSubordinates(date).map((employeeAssignment) => employeeAssignment.user.id);
  }
 
  /**
   * Return true if the current user is manager of a given employee at a given date.
   *
   * @param employeeId - UserId of the employee.
   * @param date
   */
  public isManagerOf(employeeId: string, date: Date | UnixTimestampInSeconds) {
    return this.getSubordinates(date).some((employeeAssignment) => employeeAssignment.user.id === employeeId);
  }
 
  /**
   * Builds a hashmap. Key is the teamId, value is an array containing the id of all
   * teams that are a subteam of the teamId.
   *
   * @param teamHierarchy
   * @private
   */
  private static buildSubTeamsHierarchyTree(
    teamHierarchy: TeamContract[],
  ): Record<TeamContract['id'], TeamContract['id'][]> {
    return teamHierarchy.reduce(
      (acc, curr) => {
        const parsingOfMyChildren = curr.childrenTeams.length
          ? HierarchyContext.buildSubTeamsHierarchyTree(curr.childrenTeams)
          : {};
 
        return {
          ...acc,
          ...parsingOfMyChildren,
          [curr.id]: Object.keys(parsingOfMyChildren),
        };
      },
      {} as Record<TeamContract['id'], TeamContract['id'][]>,
    );
  }
 
  /**
   * Returning undefined to avoid having it unintentionally in a DTO.
   */
  public toString() {
    return undefined;
  }
 
  /**
   * Transform the manager scope, to put it in a key value storage or to send
   * it to the frontend.
   */
  public dehydrate(): HierarchyContextDehydrated {
    return {
      teamAssignments: this.teamAssignments,
      subTeamsOfEachTeam: this.subTeamsOfEachTeam,
    };
  }
 
  /**
   * Given an objectManagerScope, builds a class.
   *
   * @param currentUser
   * @param objectManagerScope
   */
  public static hydrate(currentUser: UserContract, objectManagerScope: HierarchyContextDehydrated) {
    const hierarchyContext = new HierarchyContext(currentUser, objectManagerScope.teamAssignments, []);
 
    hierarchyContext.subTeamsOfEachTeam = objectManagerScope.subTeamsOfEachTeam;
 
    return hierarchyContext;
  }
}