All files / libs/payout-calculation/compute-engine/core-plan-template/src/planTemplate/userStatement UserStatement.ts

78.78% Statements 442/561
83.92% Branches 47/56
44.44% Functions 16/36
78.78% Lines 442/561

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 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 5621x 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 1x 1x 1x             1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 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     1x 1x 2x     2x 2x 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 2x 2x 2x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 5x 5x 5x 3x 3x 5x 3x 3x 3x 3x 3x 11x 11x 11x 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 1x 1x                   1x 1x 1x 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 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 3x 1x 1x     1x 1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 2x 2x 3x 3x 3x 3x 1x 1x     1x 1x 1x 1x 2x 2x 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  
import { add, get, isNil, mapValues, omit, pick, pickBy, set } from 'lodash-es';
 
import { type Variable } from '@amalia/amalia-lang/tokens/types';
import {
  type Company,
  type Filter,
  type Overwrite,
  type Plan,
  type PlanAssignment,
  type TeamAssignment,
} from '@amalia/core/models';
import {
  emptyAssignmentList,
  OverwriteTypesEnum,
  type AssignmentListScope,
  type ComputedStatement,
  type ComputedStatementSummary,
  type ComputedTeam,
  type DatasetRow,
  type Statement,
  type StatementDataset,
  type StatementParentTeams,
} from '@amalia/core/types';
import { type BaseCustomObjectDefinition } from '@amalia/data-capture/record-models/types';
import { type CurrencySymbolsEnum } from '@amalia/ext/iso-4217';
import { assert } from '@amalia/ext/typescript';
import {
  ComputedItemTypes,
  type ComputedOverwrite,
  type ComputedRule,
  type ComputedVariable,
  type ComputeEngineResult,
  type Dataset,
  type TimeDebug,
} from '@amalia/payout-calculation/types';
import { formatPlanResponse } from '@amalia/payout-definition/designer/core';
import { RuleType, type Relationship } from '@amalia/payout-definition/plans/types';
import { type AssignmentType, type MatchScope } from '@amalia/tenants/teams/types';
import { toUserResponseDto } from '@amalia/tenants/users/core';
 
import { type PlanTemplate } from '../planTemplateBuilder/PlanTemplate';
 
import { UserStatementReports, type StatementReport } from './UserStatementReports';
 
// TODO: move that somewhere else (mappers?)
export const overwriteToComputedOverwrite = (overwrite: Overwrite): ComputedOverwrite => ({
  id: overwrite.id,
  createdAt: overwrite.createdAt,
  sourceValue: overwrite.sourceValue,
  overwriteValue: overwrite.overwriteValue,
  creator: `${overwrite.creator.firstName} ${overwrite.creator.lastName}`,
  scope: overwrite.scope,
});
 
const formatTeamAssignments = (ta: TeamAssignment): ComputedTeam => {
  assert(ta.team, 'Relation team not found in UserStatement');
 
  return {
    teamId: ta.team.id,
    teamAssignmentId: ta.id,
    teamRole: ta.teamRole,
    name: ta.team.name,
    effectiveAsOf: ta.effectiveAsOf,
    effectiveUntil: ta.effectiveUntil,
    isTeamArchived: ta.team.archived,
  };
};
 
/**
 * Represents a user statement for a given period.
 */
export class UserStatement extends UserStatementReports {
  // ===> DEFINITIONS
 
  // All the definitions, they come from the template.
  private readonly definitions: {
    // Plan, which contains rules, kpi config, categories, ...
    plan: Plan | null;
 
    // Indexed by machineName
    filters: Record<Filter['machineName'], Filter>;
 
    // Indexed by machineName
    variables: Record<Variable['machineName'], Variable>;
 
    // Indexed by machineName.
    customObjects: Record<BaseCustomObjectDefinition['machineName'], BaseCustomObjectDefinition>;
 
    // Indexed by machineName.
    relationships: Record<Relationship['name'], Relationship>;
  };
 
  // ===> CONTEXT
  private readonly company: Company;
 
  private statementId?: string;
 
  // It contains the user and dates of his/her assignment.
  private readonly planAssignment?: PlanAssignment;
 
  private readonly teamAssignments?: TeamAssignment[];
 
  // Parent teams of the user during statement computation.
  private readonly parentTeamAssignments?: StatementParentTeams[];
 
  private readonly allAssignments = emptyAssignmentList;
 
  private readonly teamUsedDuringCalculationId: string | null = null;
 
  // Indexed by variable machine name.
  private readonly overwritesOnGlobalVariables: Record<string, Overwrite[]> = {};
 
  // ===> EVALUATIONS
 
  // Current plan template.
  public readonly planTemplate: PlanTemplate | null = null;
 
  private readonly datasets: Dataset[] = [];
 
  private readonly statementDatasets = new Map<string, StatementDataset>();
 
  public readonly computedItems: (ComputedRule | ComputedVariable)[] = [];
 
  // Store rates we've seen during the calculation of the statement.
  private readonly rates: Partial<Record<CurrencySymbolsEnum, number>> = {};
 
  public constructor(
    company: Company,
    {
      planTemplate,
      planAssignment,
      overwrites,
      teamAssignments,
      teamUsedDuringCalculationId,
      allAssignments,
      parentTeamAssignments,
    }: {
      planTemplate: PlanTemplate;
      planAssignment?: PlanAssignment;
      overwrites?: Overwrite[];
      teamAssignments?: TeamAssignment[];
      teamUsedDuringCalculationId?: string;
      allAssignments?: AssignmentListScope;
      parentTeamAssignments?: StatementParentTeams[];
    },
  ) {
    super();
 
    this.company = company;
    this.planTemplate = planTemplate;
    this.teamAssignments = teamAssignments;
    this.parentTeamAssignments = parentTeamAssignments;
    this.planAssignment = planAssignment;
    this.definitions = planTemplate.getDefinitions();
    this.teamUsedDuringCalculationId = teamUsedDuringCalculationId || null;
    if (overwrites) {
      this.loadOverwrites(overwrites);
    }
 
    if (allAssignments) {
      Object.entries(allAssignments).forEach(([role, scopes]) => {
        Object.entries(scopes).forEach(([scope, depths]) => {
          Object.entries(depths).forEach(([depth, assignments]) => {
            set(
              this.allAssignments,
              [role, scope, depth],
              assignments
                .map((a) => ({
                  effectiveUntil: a.effectiveUntil,
                  effectiveAsOf: a.effectiveAsOf,
                  user: a.user,
                  teamId: a.teamId,
                  hierarchy: a.hierarchy,
                }))
                // Remove users that don't have an externalId.
                .filter((a) => !isNil(a.user?.externalId)),
            );
          });
        });
      });
    }
  }
 
  public toJSON() {
    throw new Error('Do not access computedStatement directly, use getComputedStatement() instead');
  }
 
  public getPlanTemplate(): PlanTemplate {
    assert(this.planTemplate, 'Cannot query the plan template in this context');
    return this.planTemplate;
  }
 
  public getPlanAssignment() {
    return this.planAssignment;
  }
 
  public getPlan() {
    return this.planTemplate ? this.planTemplate.getPlan() : null;
  }
 
  public getUser() {
    return this.planAssignment ? this.planAssignment.user : null;
  }
 
  public getCompany() {
    return this.company;
  }
 
  public getStatementId() {
    return this.statementId;
  }
 
  public setStatementId(statementId: string) {
    this.statementId = statementId;
  }
 
  public getFilterDefinition(machineName: string) {
    return this.definitions.filters[machineName];
  }
 
  public getCustomObjectDefinition(machineName: string) {
    return this.definitions.customObjects[machineName];
  }
 
  public getVariableDefinition(machineName: string) {
    if (!(machineName in this.definitions.variables)) {
      throw new Error('pb');
    }
    return this.definitions.variables[machineName];
  }
 
  public getRuleDefinition(machineName: string) {
    return (this.definitions.plan!.planRules ?? []).find((r) => r.rule.machineName === machineName)?.rule;
  }
 
  public getRelationship(machineName: string) {
    return this.definitions.relationships[machineName];
  }
 
  public getDefinitions() {
    return this.definitions;
  }
 
  public getAssignments(
    role: AssignmentType,
    scope: MatchScope,
    depth: number,
  ): (TeamAssignment & { hierarchy: string[] })[] {
    return get(this.allAssignments, `${role}.${scope}.${depth}`, []) as (TeamAssignment & { hierarchy: string[] })[];
  }
 
  public getAssignmentsToStore(): Pick<Statement, 'directTeamAssignments' | 'parentTeamAssignments'> {
    return {
      parentTeamAssignments: this.parentTeamAssignments,
      directTeamAssignments: (this.teamAssignments ?? []).map((ta) => ({
        id: ta.id,
        teamId: ta.teamId,
        teamName: ta.team!.name,
      })),
    };
  }
 
  // ======================= OVERWRITES =======================
 
  /**
   * Instead of doing a lot of `find`, build a hashmaps to reduce cost of fetching them in the calculation context.
   *
   * @param overwrites
   */
  public loadOverwrites(overwrites: Overwrite[]) {
    overwrites
      // Removing overwrites on rows since they are handled in the dataset layer.
      .filter(
        (o) => !o.appliesToDefinitionId && !o.appliesToExternalId && o.overwriteType !== OverwriteTypesEnum.PAYMENT,
      )
      .forEach((o) => {
        assert(o.variable, 'Relation variable missing on loadOverwrites');
        const overwritesAlreadyOnVariable =
          o.variable.machineName in this.overwritesOnGlobalVariables &&
          this.overwritesOnGlobalVariables[o.variable.machineName];
        this.overwritesOnGlobalVariables[o.variable.machineName] = (overwritesAlreadyOnVariable || []).concat(o);
      });
  }
 
  public findOverwritesForComputedItem(computedVariable: ComputedVariable) {
    const variableDefinition = this.getVariableDefinition(computedVariable.variableMachineName);
    return computedVariable.variableMachineName in this.overwritesOnGlobalVariables
      ? this.overwritesOnGlobalVariables[computedVariable.variableMachineName].filter(
          (overwrite) => overwrite.variableId === variableDefinition.id,
        )
      : [];
  }
 
  // ======================= RESULTS =======================
 
  /**
   * Get the total by summing all ComputedRule results that are payout.
   */
  public getTotal() {
    assert(this.planTemplate, 'Plan template not loaded in user statement');
 
    const payingRulesMachineNames = (this.planTemplate.getPlan().planRules ?? []).reduce<string[]>((acc, r) => {
      // Even if you're not going to be paid for some kind of rules, we have to sum them all
      // to register the `achieved` value.
      if ([RuleType.HOLD_AND_RELEASE, RuleType.LINE_PAYOUT, RuleType.PAYOUT, RuleType.SPLIT].includes(r.rule.type)) {
        acc.push(r.rule.machineName);
      }
      return acc;
    }, []);
 
    return this.computedItems
      .filter(
        (c): c is ComputedRule =>
          c.type === ComputedItemTypes.RULE &&
          payingRulesMachineNames.includes(c.ruleMachineName) &&
          typeof c.value === 'number' &&
          // Failsafe to prevent `NaN` values to be summed in total
          Number.isFinite(c.value),
      )
      .reduce((acc, curr) => add(acc, curr.value || 0), 0);
  }
 
  /**
   * Format the output before saving it in database.
   */
  public getComputedStatement(): {
    full: ComputedStatement;
    summary: ComputedStatementSummary;
    calculationTime: number;
    total: number;
  } {
    assert(this.planAssignment, 'Plan assignment not found for computed statement');
    assert(this.definitions.plan, 'Cannot extract the plan in UserStatement');
 
    const full: ComputedStatement = {
      definitions: {
        plan: formatPlanResponse(this.definitions.plan),
        customObjects: mapValues(
          this.definitions.customObjects,
          (cod) => ({ ...omit(cod, ['schema']), schema: {} }) as BaseCustomObjectDefinition,
        ),
        // @ts-expect-error -- Fix lodash types
        relationships: mapValues(
          this.definitions.relationships,
          (relationship: Relationship): Partial<Relationship> =>
            pick(relationship, [
              'fromDefinitionField',
              'toDefinitionField',
              'name',
              'type',
              'condition',
              'fromDefinitionMachineName',
              'toDefinitionMachineName',
              'id',
            ]),
        ),
        variables: mapValues(this.definitions.variables, (variable) =>
          pick(variable, [
            'id',
            'machineName',
            'name',
            'description',
            'type',
            'format',
            'formula',
            'formatOptions',
            'formulaOptions',
            'frequency',
          ]),
        ),
        filters: mapValues(this.definitions.filters, (filter: Filter) => {
          const customObjectDefinitionMachineName = filter.object?.machineName || filter.virtualObjectMachineName;
          assert(customObjectDefinitionMachineName, 'customObjectDefinitionMachineName empty in getComputedStatement');
          return {
            ...pick(filter, [
              'id',
              'name',
              'machineName',
              'condition',
              'company',
              'formulaBuilder',
              'orderBy',
              'uniqueBy',
            ]),
            customObjectDefinitionMachineName,
          };
        }),
      },
      planAssignment: {
        user: toUserResponseDto(this.planAssignment.user),
        id: this.planAssignment.id,
        effectiveAsOf: this.planAssignment.effectiveAsOf,
        effectiveUntil: this.planAssignment.effectiveUntil,
        mainTeamId: this.planAssignment.mainTeamId,
        plan: pick(this.planAssignment.plan, ['id', 'name']),
      },
      computedTeams: (this.teamAssignments ?? []).map(formatTeamAssignments),
      teamUsedDuringCalculationId: this.teamUsedDuringCalculationId,
      datasets: this.datasets,
      computedObjects: this.computedItems,
      rates: this.rates,
    };
 
    return {
      full,
      summary: UserStatement.getStatementSummary(full),
      total: this.getTotal(),
      calculationTime: this.getCalculationTime(),
    };
  }
 
  /**
   * Pick in the statement what is needed to build the list view to avoid blasting
   * the full result to the frontend and reduce the footprint on the database when querying.
   */
  private static readonly getStatementSummary = (
    computedStatementFull: ComputedStatement,
  ): ComputedStatementSummary => {
    const statementPlan = computedStatementFull.definitions.plan;
 
    // Pick in the plan the variables needed to build the highlighted kpis.
    const neededVariablesIds = statementPlan.highlightedKpis
      .reduce<(string | null)[]>((acc, hk) => acc.concat(hk.variableId, hk.minimumVariableId, hk.maximumVariableId), [])
      .filter(Boolean);
 
    // If plan use a variable to display total, we need to retrieve this variable in resultSummary.
    if (statementPlan.useVariableInsteadOfTotal && statementPlan.totalVariableId) {
      neededVariablesIds.push(statementPlan.totalVariableId);
    }
 
    // Fetch their definition.
    const variableDefinitions = pickBy(computedStatementFull.definitions.variables, (v) =>
      neededVariablesIds.includes(v.id),
    );
 
    // Fetch their machine name.
    // I have to make this bounce because highlighted kpis are stored by id and not machineName.
    const variablesMachineName = new Set(Object.values(variableDefinitions).map((v) => v.machineName));
 
    const filteredComputedObjects = computedStatementFull.computedObjects.filter(
      (computedItem) =>
        computedItem.type === ComputedItemTypes.VARIABLE && variablesMachineName.has(computedItem.variableMachineName),
    );
 
    // Fetch their value in computed objects.
    return {
      definitions: {
        // @ts-expect-error -- Fix lodash types
        plan: pick(statementPlan, ['highlightedKpis', 'id', 'name', 'totalVariableId']),
        variables: variableDefinitions,
      },
      planAssignment: pick(computedStatementFull.planAssignment, ['mainTeamId']),
      // Only send picked variables.
      computedObjects: filteredComputedObjects,
      // List of teams where user is assigned
      computedTeams: computedStatementFull.computedTeams,
    };
  };
 
  public getStatementDatasets() {
    return [...this.statementDatasets.values()];
  }
 
  /**
   * Build the statement report for analysis purpose.
   *
   * @param id
   */
  public override computeStatementReport(id: string): StatementReport {
    return super.computeStatementReport(
      id,
      `${this.planAssignment!.user.firstName} ${this.planAssignment!.user.lastName}`,
      this.planAssignment!.plan.name,
    );
  }
 
  /**
   * Add seen currencies in the dictionary.
   * @param symbol
   * @param rate
   */
  public registerCurrencyRate(symbol: CurrencySymbolsEnum, rate: number) {
    this.rates[symbol] = rate;
  }
 
  // ======================= COMPUTED ITEMS =======================
 
  public saveGlobalComputedItem(computedItem: ComputedRule | ComputedVariable) {
    this.computedItems.push(computedItem);
  }
 
  /**
   * Given an id, fetch the item.
   *
   * @param computedItemIds
   * @param datasetIds
   */
  public getComputedItemsById(computedItemIds: string[], datasetIds?: string[]) {
    const foundInGlobal = this.computedItems.filter((ci) => computedItemIds.includes(ci.id));
    const foundInDataset = (datasetIds?.length ? this.datasets.filter((d) => datasetIds.includes(d.id)) : this.datasets)
      .map((d) => ({
        datasetId: d.id,
        items: d.computedItems.filter((ci) => computedItemIds.includes(ci.id)),
      }))
      .filter((d) => d.items.length);
    return { foundInGlobal, foundInDataset };
  }
 
  public getAllComputedItems() {
    return this.computedItems;
  }
 
  // ======================= DATASETS =======================
 
  public getDataset(datasetId: string): Dataset | undefined {
    return this.datasets.find((f) => f.id === datasetId);
  }
 
  public getDatasetRows(datasetId: string): DatasetRow[] | undefined {
    return this.statementDatasets.get(datasetId)?.rows;
  }
 
  public writeInDataset(datasetId: string, pathWithContent: string, valueWithFormat: ComputeEngineResult): void {
    const statementDataset = this.statementDatasets.get(datasetId);
    assert(statementDataset, 'Dataset not found in writeInDataset');
    const rows = [...statementDataset.rows];
    set(rows, pathWithContent, valueWithFormat);

    this.statementDatasets.set(datasetId, {
      ...statementDataset,
      rows,
    });
  }
 
  public saveDataset(dataset: Dataset, rows: DatasetRow[], timeDebug?: TimeDebug, fromCache?: boolean) {
    this.datasets.push({
      ...dataset,
      // Remove the non-computed items coming from the template.
      computedItems: [],
      timeDebug,
    });
 
    this.statementDatasets.set(dataset.id, {
      datasetId: dataset.id,
      datasetType: dataset.type,
      customObjectDefinitionMachineName: dataset.customObjectDefinition.machineName,
      rows,
      fromCache,
    });
  }
 
  public saveComputedItemInDataset(computedItem: ComputedVariable, datasetId: string): void {
    const dataset = this.datasets.find((d) => d.id === datasetId);
 
    if (!dataset) {
      throw new Error('Cannot push into a dataset that was not evaluated');
    }
 
    dataset.computedItems = dataset.computedItems.concat(computedItem);
  }
}