All files / libs/payout-calculation/statements/shared/src/lib/get-user-team-role-from-user-statements-list getUserTeamRoleFromUserStatementsList.ts

100% Statements 47/47
96.55% Branches 28/29
100% Functions 3/3
100% Lines 47/47

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 481x 1x 1x 1x 1x 5x 5x 5x 4x 4x 4x 4x 5x 1x 1x 5x 1x 1x 2x 2x 2x 2x 1x 1x 11x 1x 1x 11x 1x 1x 11x 11x 1x 1x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x  
import { type ComputedTeam, type Statement } from '@amalia/core/types';
import { type Period } from '@amalia/payout-definition/periods/types';
import { TeamRole } from '@amalia/tenants/assignments/teams/types';
 
export const sortComputedTeams = (t1: ComputedTeam, t2: ComputedTeam) => {
  // If team is archived, put it at the end
  if (t1.isTeamArchived && !t2.isTeamArchived) return 1;
  if (!t1.isTeamArchived && t2.isTeamArchived) return -1;
 
  // If user is manager on t1 and not in t2, or the inverse, manage this
  const isT1Manager = t1.teamRole === TeamRole.TEAM_MANAGER;
  const isT2Manager = t2.teamRole === TeamRole.TEAM_MANAGER;
  if (isT1Manager && !isT2Manager) {
    return -1;
  }
  if (!isT1Manager && isT2Manager) {
    return 1;
  }
 
  // Otherwise, if he has the same role on both teams, sort them by name
  return t1.name.localeCompare(t2.name);
};
 
export const filterComputedTeamsOverPeriod = (team?: ComputedTeam, period?: Period) => {
  if (!team || !period) {
    return false;
  }
  if (team.effectiveAsOf && team.effectiveAsOf >= period.endDate) {
    return false;
  }
  return !(team.effectiveUntil && team.effectiveUntil <= period.startDate);
};
 
export const getUserTeamFromUserStatement = (statement?: Statement): ComputedTeam | null => {
  if (statement) {
    const userTeams = (statement.resultSummary?.computedTeams ?? [])
      .filter((team) => filterComputedTeamsOverPeriod(team, statement.period))
      .sort(sortComputedTeams);
 
    // Return the most convenient team, with isManager at true if user is manager
    return (
      userTeams.find((t) => t.teamId === statement.resultSummary?.planAssignment?.mainTeamId) ?? userTeams.at(0) ?? null
    );
  }
 
  return null;
};