All files / libs/payout-calculation/compute-engine/core-lifecycle/src/lifecycle/usecases user-creates-calculation.use-case.ts

0% Statements 0/384
0% Branches 0/1
0% Functions 0/1
0% Lines 0/384

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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import { ForbiddenException, Injectable, Logger } from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { intersection, uniq } from 'lodash-es';
import { match } from 'ts-pattern';
import { In, Repository } from 'typeorm';

import { Calculation, Company, Plan, type Period, type Team, type User } from '@amalia/core/models';
import { CalculationRequest, CalculationStatus, CalculationType } from '@amalia/core/types';
import { assert } from '@amalia/ext/typescript';
import {
  canCalculateStatements,
  canCalculateThisForecastedStatement,
  canViewHiddenPlans,
  canViewThisPlan,
  canViewThisTeam,
  defineAbilityFor,
  getCalculateStatementsSubset,
  SubsetAccessEnum,
  SubsetsAccessHelper,
} from '@amalia/kernel/auth/shared';
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 { TeamAssignmentService } from '@amalia/tenants/assignments/teams/core';
import { RecordObject, RecordType } from '@amalia/tenants/monitoring/audit/types';
import { TeamsService } from '@amalia/tenants/teams/core';
import { AppUsersRepository } from '@amalia/tenants/users/core';
import { formatUserFullName } from '@amalia/tenants/users/types';

import { CalculationGenericEvent } from '../events/CalculationGenericEvent';

import { CreateCalculationUseCase } from './create-calculation/create-calculation.use-case';

export interface UserCreatesCalculationUseCaseArgs {
  company: Company;
  authenticatedContext: AuthenticatedContext;
  createCalculationRequest: CalculationRequest;
  dryRun?: boolean;
}

/**
 * Called when a user creates a calculation via a controller.
 *
 * Makes sure all permissions are correct, filter users seen by the access rights,
 * stops other calculations ongoing on the same statement... then actually creates the
 * calculation.
 */
@Injectable()
export class UserCreatesCalculationUseCase {
  private readonly logger = new Logger(UserCreatesCalculationUseCase.name);

  public constructor(
    private readonly eventBus: EventBus,
    @InjectRepository(Calculation)
    private readonly calculationRepository: Repository<Calculation>,
    private readonly periodService: PeriodsService,
    private readonly appUsersRepository: AppUsersRepository,
    private readonly planService: PlansService,
    private readonly teamService: TeamsService,
    private readonly teamAssignmentService: TeamAssignmentService,
    private readonly createCalculationUseCase: CreateCalculationUseCase,
  ) {}

  /**
   * Creates a calculation.
   * @param company company
   * @param authenticatedContext
   * @param createCalculationRequest
   * @param dryRun
   */
  public async execute({
    company,
    authenticatedContext,
    createCalculationRequest,
    dryRun,
  }: UserCreatesCalculationUseCaseArgs): Promise<Calculation | null> {
    const {
      periodId,
      planIds,
      teamIds,
      userIds,
      trigger,
      type: typeRaw,
      dataConnectorObjectsNames,
      shouldComputeForecast,
    } = createCalculationRequest;

    const type = typeRaw ?? CalculationType.STATEMENT;

    assert(periodId, 'No period id found for computation');

    const { teams, users, period, uniqueUserKey } = await this.getPeriodTeamUsers(
      company,
      periodId,
      teamIds,
      userIds,
      planIds,
      type,
    );

    // Stop other calculations if we're recomputing exactly one statement.
    if (!dryRun && uniqueUserKey) {
      await this.stopCalculationsOnSameStatement(company, uniqueUserKey);
    }

    // Check access rights on the thing we're calculating.
    const subsetAccess = SubsetsAccessHelper.getSubset(authenticatedContext, getCalculateStatementsSubset);

    const isSimulation = UserCreatesCalculationUseCase.isSimulation(type, userIds ?? [], authenticatedContext);

    const { shouldComputeOnlyLivePlans } = await this.checkAccessRights(
      authenticatedContext,
      isSimulation,
      subsetAccess,
      teams,
      planIds,
      company,
    );

    // Filter users I can access during the current period.
    const userIdsToCompute = await this.getUserIdsToComputeOnCreation(
      company,
      authenticatedContext,
      users,
      period,
      teams,
      subsetAccess,
      isSimulation,
    );

    // Finally, create the calculation and delegate it to the worker.
    const calculation = await this.createCalculationUseCase.execute({
      calculationEvent: {
        companyId: company.id,
        query: {
          planIds,
          periodId,
          userIds: userIdsToCompute || undefined,
          trigger,
          type,
          dataConnectorObjectsNames,
          shouldComputeForecast,
        },
        options: {
          withRollingPeriods: false,
          uniqueUserKey: uniqueUserKey || undefined,
        },
      },
      onlyLivePlans: shouldComputeOnlyLivePlans,
      dryRun,
      authenticatedContext,
    });

    if (!calculation) {
      return null;
    }

    if (!dryRun) {
      await this.auditRecord(authenticatedContext, RecordType.CREATE, calculation);
    }

    return calculation;
  }

  private async checkAccessRights(
    authenticatedContext: AuthenticatedContext,
    isSimulation: boolean,
    subsetAccess: SubsetAccessEnum,
    teams: Team[],
    planIds: Plan['id'][] | undefined,
    company: Company,
  ): Promise<{ shouldComputeOnlyLivePlans: boolean }> {
    const ability = defineAbilityFor(authenticatedContext);

    // Check the possibility to compute simulation statements.
    if (!isSimulation && (subsetAccess === SubsetAccessEnum.NOTHING || !canCalculateStatements(ability))) {
      throw new ForbiddenException("You don't have the right to calculate statement");
    }

    // Check the possibility to compute teams.
    if (teams.some((team) => !canViewThisTeam(ability, { team }))) {
      throw new ForbiddenException("You can't calculate with this team");
    }

    // Check the possibility to compute plans.
    if (planIds?.length) {
      const plans = await this.planService.findAll(company, {
        ids: planIds,
        isHiddenStatus: PlanIsHiddenQueryChoices.BOTH,
      });
      if (plans.some((plan) => !canViewThisPlan(ability, plan))) {
        throw new ForbiddenException("You can't calculate this plan");
      }
    }

    const shouldComputeOnlyLivePlans = !canViewHiddenPlans(ability);

    return { shouldComputeOnlyLivePlans };
  }

  private async getPeriodTeamUsers(
    company: Company,
    periodId: string,
    teamIds?: string[],
    userIds?: string[],
    planIds?: string[],
    type?: CalculationType,
  ): Promise<{ teams: Team[]; users: User[]; period: Period; uniqueUserKey: string | null }> {
    const period = await this.periodService.findOne(company, periodId);
    const teams = await this.teamService.findByIds(company, teamIds);

    let users: User[] = [];

    // This is useful to detect that a user has launched the calculation on the same statement,
    // so we can stop the other one. For instance, if the user is entering multiple overwrites:
    // when he enters the second one, we stop the first calculation if it was ongoing.
    // This only happens in the context of a statement, so we don't need to implement that for
    // calculations targeting a team, a plan or the full company.
    let uniqueUserKey: string | null = null;

    if (userIds?.length) {
      users = await Promise.all(userIds.map((u) => this.appUsersRepository.findOne(company, u)));

      if (users.length === 1 && planIds?.length === 1) {
        uniqueUserKey = `${periodId}::${planIds[0]}::${users[0].id}::${type}`;
      }
    }

    return {
      teams,
      users,
      period,
      uniqueUserKey,
    };
  }

  /**
   * Stop started or pending calculations with the same period, plan and user
   *
   * @param company
   * @param uniqueUserKey
   */
  private async stopCalculationsOnSameStatement(company: Company, uniqueUserKey: string) {
    this.logger.log({ message: `Stopping calculations for key ${uniqueUserKey}`, uniqueUserKey });
    await this.calculationRepository.update(
      {
        company: { id: company.id },
        uniqueUserKey,
        status: In([CalculationStatus.STARTED, CalculationStatus.PENDING]),
      },
      { status: CalculationStatus.STOPPING },
    );
  }

  private async getUserIdsToComputeOnCreation(
    company: Company,
    authenticatedContext: AuthenticatedContext,
    users: User[],
    period: Period,
    teams: Team[],
    subsetAccess: SubsetAccessEnum,
    isSimulation: boolean,
  ) {
    const usersICanCompute = match(subsetAccess)
      .with(SubsetAccessEnum.EVERYTHING, () => null)
      .with(SubsetAccessEnum.NOTHING, () =>
        // In simulation mode, the user can compute his own statement.
        isSimulation ? [authenticatedContext.user.id] : ([] as string[]),
      )
      .with(SubsetAccessEnum.MATCH_MANAGEES_WITH_DATES, () =>
        uniq(
          [
            ...authenticatedContext.hierarchy.getSubordinates(period.startDate),
            ...authenticatedContext.hierarchy.getSubordinates(period.endDate),
          ].map((ta) => ta.user.id),
        ),
      )
      .with(SubsetAccessEnum.IN_MY_SCOPE, () =>
        [
          ...authenticatedContext.adminScopesContainer!.allUsersInMyScope(period.startDate),
          ...authenticatedContext.adminScopesContainer!.allUsersInMyScope(period.endDate),
        ].map((user) => user.id),
      )
      .otherwise(() => {
        throw new Error('subset access not implemented');
      });

    if (users.length) {
      const userIds = users.map((u) => u.id);
      // People who can compute everything have null here.
      return usersICanCompute === null
        ? userIds
        : // Else make the intersection.
          intersection(usersICanCompute, userIds);
    }

    if (teams.length) {
      // Gather the list of userIds we're about to compute based on team assignments.
      const userIdsForTeam = await this.teamAssignmentService.getTeamUserIds(
        company,
        teams.map((team) => team.id),
        period,
      );

      // People who can compute everything have null here.
      return usersICanCompute === null
        ? userIdsForTeam
        : // Else make the intersection.
          intersection(usersICanCompute, userIdsForTeam);
    }

    return usersICanCompute;
  }

  /**
   * Audit record.
   * @param authenticatedContext
   * @param actionType type of action
   * @param calculation
   */
  private async auditRecord(
    authenticatedContext: AuthenticatedContext,
    actionType: RecordType,
    calculation: Calculation,
  ) {
    const { descriptor } = calculation;

    const periods: string[] = [];
    const plans: string[] = [];
    const users: string[] = [];

    descriptor.forEach((step) => {
      periods.push(step.periodName);

      step.batches.forEach((batch) => {
        plans.push(batch.planName);

        batch.users.forEach((user) => {
          users.push(formatUserFullName(user));
        });
      });
    });

    const periodNames = uniq(periods).join(', ');
    const userNames = uniq(users).join(', ');
    const planNames = uniq(plans).join(', ');

    await this.eventBus.publish(
      new CalculationGenericEvent({
        authenticatedContext,
        object: RecordObject.CALCULATION,
        type: actionType,
        values: {
          target: {
            id: calculation.id,
            name: `${periodNames} - ${userNames}`,
          },
          newValues: {
            period: periodNames,
            plan: planNames,
            user: userNames,
          },
        },
      }),
    );
  }

  private static isSimulation(
    calculationType: CalculationType,
    userIdsToCompute: string[],
    authenticatedContext: AuthenticatedContext,
  ): boolean {
    const isForecastCalculation = calculationType === CalculationType.FORECAST;
    const isOnlyOneUser = userIdsToCompute.length === 1;
    const isUserCalculatingIsOwnForecastedStatement = canCalculateThisForecastedStatement(
      defineAbilityFor(authenticatedContext),
      { userId: userIdsToCompute[0] },
    );

    return isForecastCalculation && isOnlyOneUser && isUserCalculatingIsOwnForecastedStatement;
  }
}