All files / libs/reporting/dashboards/core/src/lib dashboards.service.ts

74.25% Statements 124/167
26.31% Branches 5/19
50% Functions 2/4
74.25% Lines 124/167

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 1681x 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 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 5x                 5x 5x 5x 5x     5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x       1x 1x                                                       1x  
import { Injectable } from '@nestjs/common';
import { intersection, isEmpty, keyBy, last, uniq, uniqBy } from 'lodash-es';
 
import { type Company, type Team, type User, type Variable } from '@amalia/core/models';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { PlansService } from '@amalia/payout-definition/designer/core';
import { PeriodsService } from '@amalia/payout-definition/periods/core';
import { PlanIsHiddenQueryChoices } from '@amalia/payout-definition/plans/types';
import {
  GetReportContentWithoutAuthenticationUseCase,
  PresetReportBuilder,
} from '@amalia/reporting/custom-reports/core';
import { buildCustomReportColumns, CustomReportsPresetsEnum } from '@amalia/reporting/custom-reports/shared';
import { Statistics } from '@amalia/reporting/dashboards/types';
import { TeamRole } from '@amalia/tenants/assignments/teams/types';
import { TeamsService } from '@amalia/tenants/teams/core';
import { HierarchyContextService } from '@amalia/tenants/teams/hierarchy/core';
 
@Injectable()
export class DashboardsService {
  public constructor(
    private readonly getReportContentWithoutAuthenticationUseCase: GetReportContentWithoutAuthenticationUseCase,
    private readonly periodsService: PeriodsService,
    private readonly plansService: PlansService,
    private readonly teamsService: TeamsService,
    private readonly hierarchyContextService: HierarchyContextService,
  ) {}
 
  /**
   * Retrieve dashboard widget.
   * @param company
   * @param authenticatedContext
   * @param reportId
   * @param periodId If you want results for a given period.
   * @param referenceDate If you want results based on a selected date.
   * @param planIds If you want to narrow down the results to given plans.
   * @param teamIds If you want to narrow down the results to given teams.
   * @param userIds If you want to narrow down the results to given users.
   * @param limit If you want to narrow down the results to given users.
   */
  public async getWidget(
    company: Company,
    authenticatedContext: AuthenticatedContext,
    reportId: CustomReportsPresetsEnum,
    {
      planIds,
      teamIds,
      userIds,
      limit,
      periodIds,
      referenceDate,
      planHiddenStatus,
    }: {
      periodIds?: string[];
      referenceDate?: Date;
      year?: number;
      planIds?: string[];
      teamIds?: string[];
      userIds?: string[];
      limit?: number;
      planHiddenStatus?: PlanIsHiddenQueryChoices;
    },
  ): Promise<Statistics> {
    // If 1 plan is selected, we can retrieve plan kpi fields.
    const additionalVariables =
      !!planIds &&
      !isEmpty(planIds) &&
      planIds.length === 1 &&
      [CustomReportsPresetsEnum.PRESET_EARNED_OVER_TIME, CustomReportsPresetsEnum.PRESET_PLAN_KPIS].includes(reportId)
        ? await this.getKpiVariables(company, planIds[0])
        : [];
 
    const interpretedPeriodIds = periodIds
      ? await this.periodsService.interpretPeriodParamsArray(company, periodIds, referenceDate)
      : null;
 
    const lastPeriod = await this.periodsService.findOne(company, last(interpretedPeriodIds)!);
    const subordinates = uniqBy(
      [
        ...(await this.hierarchyContextService.getSubordinates(company, authenticatedContext, lastPeriod.startDate, {
          userIds,
          planIds,
          teamIds,
        })),
        ...(await this.hierarchyContextService.getSubordinates(company, authenticatedContext, lastPeriod.endDate, {
          userIds,
          planIds,
          teamIds,
        })),
      ],
      (u) => u.id,
    );
 
    const widgetReport = new PresetReportBuilder(company, reportId)
      .setPlanVisibility(planHiddenStatus || PlanIsHiddenQueryChoices.LIVE)
      .addRuleVariables(additionalVariables)
      .addUserIdsInFilter(subordinates.map((u) => u.id))
      .addPlanIdsInFilter(planIds);
 
    if (interpretedPeriodIds) {
      widgetReport.addPeriodIdFilter(interpretedPeriodIds);
    }
 
    if (teamIds) {
      const userTeamIdsForPeriod = await this.getUserTeamIdsForPeriod(
        company,
        authenticatedContext.user,
        teamIds,
        last(interpretedPeriodIds),
      );
      widgetReport.addTeamIdsInFilter(userTeamIdsForPeriod);
    }
 
    const { report, hasEmptyFilters } = widgetReport.build();
 
    if (hasEmptyFilters) {
      return { definitions: {}, records: [] };
    }
 
    const currencies = uniq(subordinates.map((u) => u.currency));
 
    const { records, manifestsMap } = await this.getReportContentWithoutAuthenticationUseCase.execute(company, report, {
      configuration: report.configuration,
      pagination: { limit, page: 0 },
      options: { convertToCompanyCurrency: currencies.length !== 1 },
    });
 
    return {
      definitions: keyBy(buildCustomReportColumns(report, manifestsMap), 'identifier'),
      records: records.items,
    };
  }
 
  private async getKpiVariables(company: Company, planId: string): Promise<Variable[]> {
    const plan = await this.plansService.findById(company, planId, ['highlightedKpis', 'highlightedKpis.variable']);
    return (plan.highlightedKpis ?? []).map((k) => k.variable!);
  }
 
  private async getUserTeamIdsForPeriod(
    company: Company,
    user: User,
    teamIds: string[],
    periodId?: string,
  ): Promise<Team['id'][]> {
    if (isEmpty(teamIds)) {
      return [];
    }

    // If there is some teams, please fill the hierarchy scope if user is authorized
    // to be sure to have all data for dashboard
    const period = periodId ? await this.periodsService.getById(company, periodId) : undefined;
    const teamsManagers = await this.teamsService.findAllWhereUserAssignedOrManager(
      company,
      user.id,
      period || undefined,
      TeamRole.TEAM_MANAGER,
    );
    const teamsManagersInIds = intersection(
      teamsManagers.map((t) => t.id),
      teamIds,
    );
    const teamsWithChildren = await this.teamsService.populateTeamChildren(
      teamsManagers.filter((t) => teamsManagersInIds.includes(t.id)),
    );
    return uniq([...teamIds, ...teamsWithChildren]);
  }
}