All files / libs/amalia-lang/formula/parsing/src/lib/formula-parser FormulaParser.ts

93.98% Statements 578/615
88.09% Branches 74/84
100% Functions 10/10
93.98% Lines 578/615

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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 6161x 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 23x 23x 23x 23x 23x 23x 23x 1x 1x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 1x 1x 1x 1x 1x 1x 1x 56x 742x 695x 695x 47x 47x 47x 47x 742x 46x 742x 9x 9x 9x 9x 20x 9x 9x 47x 47x 56x 56x 1x 1x 1x 1x 1x 1x 1x 57x 57x 57x 57x 57x 57x 57x 1x 1x 1x     1x 57x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 635x 115x 115x 51x 51x 51x 51x 51x 51x 51x 51x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 27x 27x 27x 27x 13x 27x 5x 5x 22x 22x 27x 1x 1x 1x 21x 21x 21x 27x 3x 3x 18x 27x 1x 1x 17x 17x 17x 104x 104x 104x 104x 104x 104x 104x 5x 5x 5x 5x 5x 5x 2x 2x 2x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x                       3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 61x 61x 105x 105x 105x 105x 105x 105x 105x 21x 21x 84x 84x 84x 84x 84x 84x 84x 84x 84x 84x 82x 105x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 105x 57x   57x     57x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 45x 57x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 61x 61x 61x 61x 104x 104x 104x 104x 104x 104x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 104x 104x 3x 1x 3x 3x 3x 104x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 314x 314x 314x 314x 26x 314x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 27x 27x 27x 27x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 1x 1x 1x           1x 1x 11x 11x 4x 4x 4x 4x           4x 4x 4x 4x     4x 4x 4x 2x 2x 2x 2x           2x     2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 11x 11x 5x 5x 11x 11x 1x 11x 11x 1x 1x 5x 5x 5x 5x 3x 5x 1x 1x 1x 1x 5x 1x 5x 5x 1x 1x 128x 128x 1x  
import { pickBy, uniq, uniqBy } from 'lodash-es';
import { match, P } from 'ts-pattern';
 
import { commonMathJs } from '@amalia/amalia-lang/amalia-mathjs';
import {
  AmaliaFunction,
  ConstantNode,
  SanitizeFormula,
  type AccessorNode,
  type MathNode,
} from '@amalia/amalia-lang/formula/evaluate/shared';
import { type AmaliaFormula } from '@amalia/amalia-lang/formula/types';
import { AmaliaAccessorKeywords, VariableType, type Variable } from '@amalia/amalia-lang/tokens/types';
import { ConfigurationError, type EngineErrorContext } from '@amalia/core/types';
import {
  CustomObjectDefinitionType,
  VirtualCustomObjects,
  type BaseCustomObjectDefinition,
  type CustomObjectDefinition,
} from '@amalia/data-capture/record-models/types';
import { assert } from '@amalia/ext/typescript';
import {
  ComputedItemTypes,
  DatasetType,
  type ComputedFunctionArgs,
  type ComputedFunctionArgs_GETATINDEX,
  type ComputedFunctionArgs_SUM,
  type ComputedFunctionResult,
  type ComputedItem,
  type Dataset,
} from '@amalia/payout-calculation/types';
import { RuleType, type Filter, type Plan, type Relationship } from '@amalia/payout-definition/plans/types';
import { TEAM_KEYWORDS_IN_CALCULATION_ENGINE } from '@amalia/tenants/teams/types';
import { USER_PROPERTIES_ADMISSIBLE_IN_CALCULATION_ENGINE } from '@amalia/tenants/users/types';
 
import { type DefinitionsContainer } from '../DefinitionsContainer';
 
import { computedItemToErrorContext } from './computed-item-to-error-context';
import { ItemsGenerators } from './itemsGenerators';
 
const AmaliaFunctions = AmaliaFunction.getAllFunctions();
 
type TPlan = Pick<Plan, 'forecast' | 'id' | 'isForecasted'>;
 
export interface ParsedProperty {
  propertyMachineName: string;
  definitionName: CustomObjectDefinition['machineName'];
  relationLevel: string;
}
 
export class FormulaParser {
  public constructor(
    private readonly definitionsContainer: DefinitionsContainer<
      TPlan,
      Pick<Relationship, 'fromDefinitionMachineName' | 'id' | 'name' | 'toDefinitionMachineName'>,
      Pick<Filter, 'id' | 'machineName' | 'object' | 'planId' | 'virtualObjectMachineName'>,
      Pick<Variable, 'formula' | 'id' | 'machineName' | 'objectId' | 'planId' | 'type'>
    >,
  ) {}
 
  public extractNodes({
    formula,
    context = {},
    parentIds = [],
    parentDatasetId = null,
    currentObjectDefinition = null,
    toCustomObjectDefinition = null,
    relationLevel = '',
    plan = null,
    ignoreChecks = false,
  }: {
    formula: string;
    context?: EngineErrorContext;
    parentIds?: string[];
    parentDatasetId?: string | null;
    currentObjectDefinition?: BaseCustomObjectDefinition | null;
    toCustomObjectDefinition?: BaseCustomObjectDefinition | null;
    relationLevel?: string;
    plan?: TPlan | null;
    ignoreChecks?: boolean;
  }): {
    computedItems: ComputedItem[];
    datasets: Dataset[];
    relationshipLevelsFound: string[];
    properties: ParsedProperty[];
  } {
    // Use MathJs to extract nodes in the formula.
    const nodes = FormulaParser.getNodesFromFormula(context, formula);
 
    const { computedItems, relationshipLevelsFound, datasets, properties } = this.traverseAccessorNodes(
      nodes,
      context,
      parentIds,
      parentDatasetId,
      currentObjectDefinition,
      toCustomObjectDefinition,
      relationLevel,
      plan,
      ignoreChecks,
    );
 
    return {
      relationshipLevelsFound,
      computedItems: [...computedItems, ...FormulaParser.traverseFunctionNodes(nodes, parentIds)],
      datasets,
      properties,
    };
  }
 
  /**
   * For some functions, avoid classic parsing on some parameters by ignoring them.
   *
   * It usually means that they should be parsed in another context (for instance a dataset or a different period).
   */
  private static escapeFunctionArguments(nodes: MathNode) {
    return nodes.transform((node) => {
      if (!commonMathJs.isFunctionNode(node)) {
        return node;
      }
 
      // If there is an "escaper" for the current function.
      if (
        commonMathJs.isFunctionNode(node) &&
        node.fn.toString() in AmaliaFunctions &&
        AmaliaFunctions[node.fn.toString() as keyof typeof AmaliaFunctions].parametersToEscapeOnParse
      ) {
        const { parametersToEscapeOnParse } = AmaliaFunctions[node.fn.toString() as keyof typeof AmaliaFunctions];
 
        // Replace each argument that should be escaped by a constant.
        parametersToEscapeOnParse?.forEach((index) => {
          node.args[index] = new ConstantNode(node.args[index]?.toString());
        });
      }
 
      return node;
    });
  }
 
  /**
   * Retrieve mathjs nodes from formula, also apply some transformation.
   * @param context
   * @param formula
   */
  private static getNodesFromFormula(context: EngineErrorContext, formula: string): MathNode {
    try {
      const formulaLowerCase = SanitizeFormula.sanitizeFormula(formula);
      const nodes = commonMathJs.parse(formulaLowerCase);
 
      // Escape some arguments to avoid evaluating them in the current context (see documentation).
      return FormulaParser.escapeFunctionArguments(nodes);
    } catch (e) {
      if (e instanceof SyntaxError) {
        throw new ConfigurationError(`Formula Syntax Error: ${e.message}`, context);
      } else {
        throw e;
      }
    }
  }
 
  /**
   * Traverse AccessorNodes (statement.machin, opportunity.bidule...) to extract variables, relations...
   *
   * @param nodes
   * @param context
   * @param parentIds
   * @param parentDatasetId
   * @param customObjectDefinition
   * @param toCustomObjectDefinition
   * @param relationLevel
   * @param plan
   * @param ignoreChecks
   */
  private traverseAccessorNodes(
    nodes: MathNode,
    context: EngineErrorContext,
    parentIds: string[],
    parentDatasetId: string | null,
    customObjectDefinition: BaseCustomObjectDefinition | null,
    toCustomObjectDefinition: BaseCustomObjectDefinition | null,
    relationLevel: string,
    plan: TPlan | null,
    ignoreChecks: boolean = false,
  ): {
    computedItems: ComputedItem[];
    relationshipLevelsFound: string[];
    datasets: Dataset[];
    properties: ParsedProperty[];
  } {
    const allAccessorNodes: AccessorNode[] = [];
 
    nodes.traverse((node) => {
      if (commonMathJs.isAccessorNode(node)) {
        allAccessorNodes.push(node);
      }
    });
 
    const objectsToEvaluate: ComputedItem[] = [];
    const relationshipLevelsFound: string[] = [];
    const datasets: Dataset[] = [];
    const parsedProperties: ParsedProperty[] = [];
 
    allAccessorNodes.forEach((node) => {
      const nodeIdentifier = node.toString().split('.');
      const [objectName, propertyName] = nodeIdentifier;
 
      match({
        objectName,
        propertyName,
        customObjectDefinition,
        toCustomObjectDefinition,
      })
        .with(
          { objectName: AmaliaAccessorKeywords.teamAssignment },
          { objectName: AmaliaAccessorKeywords.planAssignement },
          { objectName: AmaliaAccessorKeywords.statementPeriod },
          { objectName: AmaliaAccessorKeywords.statementMetric },
          // Keywords.
          //  - statementPeriod.startDate
          //  - planAssignement.effectiveAsOf
          //  - statementMetric.teamMrr
 
          // Will be injected on parser, nothing to do.
          () => {},
        )
        .with(
          { objectName: VariableType.statement },
          { objectName: VariableType.user },
          { objectName: VariableType.team },
          { objectName: VariableType.plan },
          // Global variables.
          //   - statement.myVariable
          //   - user.quota
          //   - plan.quota
          //   - team.quota
          () => {
            // If we're requesting an attribute from user like firstName, do not add the variable since it's already in the user.
            // However, careful on what we expose to avoid data leak.
            if (
              objectName === VariableType.user &&
              USER_PROPERTIES_ADMISSIBLE_IN_CALCULATION_ENGINE.includes(propertyName)
            ) {
              return;
            }
 
            // If we're requesting special keywords on team.
            if (objectName === VariableType.team && TEAM_KEYWORDS_IN_CALCULATION_ENGINE.includes(propertyName)) {
              // Do not add / parse the variable as it's already in the scope.
              return;
            }
 
            const variableDefinition = this.definitionsContainer.getVariable(propertyName, plan);
 
            if (!variableDefinition) {
              throw new ConfigurationError(`Variable ${propertyName} on ${objectName} not found`, context);
            }
 
            if (variableDefinition.type !== objectName) {
              throw new ConfigurationError(`Variable ${propertyName} does not apply to ${objectName}`, context);
            }
 
            objectsToEvaluate.push(ItemsGenerators.generateGlobalVariable(propertyName, objectName, parentIds));
          },
        )
        .with(
          { objectName: AmaliaAccessorKeywords.filter },
          // Filters.
          //   - filter.dealsClosedInPeriod
          //   - filter.metricsByTeamMember
          () => {
            // If it's a normal filter.
            const filterMachineName = propertyName;
            const filterDefinition = this.definitionsContainer.getFilter(filterMachineName, plan);
 
            if (
              filterDefinition?.virtualObjectMachineName &&
              [VirtualCustomObjects.OBJECT_METRIC, VirtualCustomObjects.STATEMENT_METRIC].includes(
                filterDefinition.virtualObjectMachineName,
              )
            ) {
              // Filter is on a metric.
              datasets.push(
                ItemsGenerators.generateFilterDataset(
                  {
                    type: DatasetType.metrics,
                    filterMachineName,
                    customObjectDefinition: { machineName: filterDefinition.virtualObjectMachineName },
                  },
                  parentIds,
                ),
              );
            } else if (filterDefinition?.virtualObjectMachineName === VirtualCustomObjects.QUOTA) {
              // Filter is on a virtual object definition.
              datasets.push(
                ItemsGenerators.generateFilterDataset(
                  {
                    type: DatasetType.quota,
                    filterMachineName,
                    customObjectDefinition: { machineName: filterDefinition.virtualObjectMachineName },
                  },
                  parentIds,
                ),
              );
            } else {
              if (!filterDefinition) {
                throw new ConfigurationError(`Cannot find filter ${filterMachineName}`, context);
              }
 
              datasets.push(
                ItemsGenerators.generateFilterDataset(
                  {
                    type: DatasetType.filter,
                    filterMachineName: propertyName,
                    customObjectDefinition: { machineName: filterDefinition.object!.machineName },
                  },
                  parentIds,
                ),
              );
            }
          },
        )
        .with(
          { customObjectDefinition: P.nonNullable, objectName: AmaliaAccessorKeywords.row },
          { customObjectDefinition: P.nonNullable, objectName: customObjectDefinition?.machineName },
          // Fields, properties or relations of the current object.
          //   - opportunity.ownerId for instance (fields of the definition)
          //   - opportunity.amountConverted for instance (object variable of the current line).
          //   - $row.myVariable
          //   - opportunity.previousOpportunity.amount for instance (fields of the definition of the relationship)
          //   - opportunity.previousOpportunity.amountConverted for instance (object variable of the relationship)
          //   - opportunity.pouet.plop.swag.amount (going deep into relationships)
          ({ customObjectDefinition }) => {
            // Declaring a recursive function that is going to be called for each relation level.
            const recursion = (
              currentCustomObjectDefinition: Pick<CustomObjectDefinition, 'id' | 'machineName' | 'properties'>,
              currentLevel: number,
            ) => {
              const currentPropertyName = nodeIdentifier[currentLevel];
 
              // The recursion stops when we parsed all parts.
              if (!currentPropertyName) {
                return;
              }
 
              const currentRelationLevel = FormulaParser.joinRelations(
                relationLevel,
                nodeIdentifier.slice(1, currentLevel),
              );
 
              const { properties, machineName, id } = currentCustomObjectDefinition;
 
              if (
                Object.values(VirtualCustomObjects).includes(machineName as VirtualCustomObjects) ||
                properties[currentPropertyName]
              ) {
                // If the current property is in the schema, add it to properties.
                // Let's just check it's not also a relation.
                const matchingRelation = this.definitionsContainer.getRelationshipFromName(currentPropertyName);
 
                assert(
                  !matchingRelation || matchingRelation.fromDefinitionMachineName !== machineName,
                  new ConfigurationError(
                    `Accessor ${machineName}.${currentPropertyName} can refer to either a property or a relationship, which makes it ambiguous. Please rename one of them.`,
                    context,
                  ),
                );
 
                parsedProperties.push({
                  definitionName: currentCustomObjectDefinition.machineName,
                  propertyMachineName: currentPropertyName,
                  relationLevel: currentRelationLevel,
                });
              } else if (
                customObjectDefinition.type === CustomObjectDefinitionType.VIRTUAL &&
                currentPropertyName === 'user'
              ) {
                // For virtual definitions, some fields are neither primitive type nor links, we can't
                // exactly parse them like something we handle in Amalia, so we better skip that parsing.
              } else if (this.definitionsContainer.getRelationshipFromName(currentPropertyName)) {
                // If the current property refers to a relation, we have to go down in it.
 
                // Make sure it's not an object variable as well.
                const variableDefinition = this.definitionsContainer.getVariable(currentPropertyName, plan);
 
                assert(
                  !variableDefinition || variableDefinition.objectId !== id,
                  new ConfigurationError(
                    `Accessor ${machineName}.${currentPropertyName} can refer to either a field or a relationship, which makes it ambiguous. Please rename one of them.`,
                    context,
                  ),
                );
 
                // Fetch the relation.
                const relationship = this.definitionsContainer.getRelationshipFromName(currentPropertyName);
 
                assert(relationship, `Relationship not found for ${currentPropertyName}`);
 
                // Register the relation level.
                relationshipLevelsFound.push(FormulaParser.joinRelations(currentRelationLevel, [relationship.name]));
 
                const relationDefinition = this.definitionsContainer.getCustomObjectDefinitionByMachineName(
                  relationship.toDefinitionMachineName,
                );
 
                assert(
                  relationDefinition,
                  new ConfigurationError(
                    `Definition ${relationship.toDefinitionMachineName} not found in relation ${relationship.name}`,
                    context,
                  ),
                );
 
                // Continue.
                recursion(relationDefinition, currentLevel + 1);
              } else {
                // It's not in the definition and it's not a relation so it should be an object variable.
                const variableDefinition = this.definitionsContainer.getVariable(currentPropertyName, plan);
 
                assert(
                  variableDefinition,
                  new ConfigurationError(`Variable ${currentPropertyName} on ${machineName} not found`, context),
                );
 
                assert(
                  ignoreChecks || variableDefinition.objectId === id,
                  new ConfigurationError(`Variable ${currentPropertyName} does not apply to ${machineName}`, context),
                );
 
                // Then add the variable in objects to evaluate.
                objectsToEvaluate.push(
                  ItemsGenerators.generateObjectVariable(
                    currentPropertyName,
                    machineName,
                    parentIds,
                    parentDatasetId || undefined,
                    currentRelationLevel,
                  ),
                );
              }
            };
 
            recursion(customObjectDefinition, 1);
          },
        )
        .with(
          { toCustomObjectDefinition: P.nonNullable, objectName: toCustomObjectDefinition?.machineName },
          // To Custom Object Definition in the context of a relation condition.
          //   - $row.id = ->invoice.id<- (matching the toDefinition in a relation condition)
          ({ toCustomObjectDefinition }) => {
            assert(
              propertyName in toCustomObjectDefinition.properties,
              new ConfigurationError(
                `Only source columns of the destination object can be used in a formula of a link (got ${propertyName})`,
              ),
            );
 
            parsedProperties.push({
              definitionName: toCustomObjectDefinition.machineName,
              propertyMachineName: propertyName,
              relationLevel: '',
            });
          },
        )
        .otherwise(() => {
          const scope = customObjectDefinition
            ? `in object definition ${customObjectDefinition.machineName}`
            : 'in the global scope';
 
          throw new ConfigurationError(`Cannot parse ${objectName}.${propertyName} ${scope}`, context);
        });
    });
 
    // Avoid extra work in the previous layer by removing doubles immediately.
    return {
      relationshipLevelsFound: uniq(relationshipLevelsFound.filter(Boolean)),
      computedItems: uniqBy(objectsToEvaluate, 'id'),
      datasets: uniqBy(datasets, 'id'),
      properties: uniqBy(parsedProperties, 'propertyMachineName'),
    };
  }
 
  /**
   * Traverse FunctionNodes (SUM, convertCurrency...) to grab extra items to evaluate.
   *
   * @param nodes
   * @param parentIds
   */
  private static traverseFunctionNodes(nodes: MathNode, parentIds: string[]): ComputedFunctionResult[] {
    const functionsToEvaluate: ComputedFunctionResult[] = [];
 
    nodes.traverse((node) => {
      // If there is a generator for the current function, run it.
      if (
        commonMathJs.isFunctionNode(node) &&
        node.fn.name in AmaliaFunctions &&
        AmaliaFunctions[node.fn.name as keyof typeof AmaliaFunctions].generateComputedFunctionResult
      ) {
        const args = AmaliaFunctions[node.fn.name as keyof typeof AmaliaFunctions].generateComputedFunctionResult!(
          node.args,
        );
        const filterArgs = pickBy(args, (a: unknown) => a !== undefined) as ComputedFunctionArgs;
 
        // We have the arguments of the function, now generate a ComputedFunctionResult from it.
        const functionToEvaluate = ItemsGenerators.generateComputedFunctionResult(
          {
            type: ComputedItemTypes.FUNCTION_RESULT,
            function: node.fn.name,
            args: filterArgs,
          },
          parentIds,
        );
 
        functionsToEvaluate.push(functionToEvaluate);
      }
    });
 
    return functionsToEvaluate;
  }
 
  /**
   * Given a computedItem, return the formula we should parse to gather its dependencies.
   *
   * @param computedItem
   * @param plan
   * @param zerosNonPayoutRules
   */
  public getFormulasOfComputedItem(
    computedItem: ComputedItem,
    plan: TPlan | null,
    zerosNonPayoutRules: boolean = true,
  ): AmaliaFormula[] {
    return match(computedItem)
      .with({ type: ComputedItemTypes.VARIABLE }, (computedVariable) => {
        const variableDefinition = this.definitionsContainer.getVariable(computedVariable.variableMachineName, plan);
 
        if (!variableDefinition) {
          throw new ConfigurationError(
            `Variable not found: ${computedItem.variableMachineName}`,
            computedItemToErrorContext(computedItem),
          );
        }
 
        return [variableDefinition.formula as AmaliaFormula];
      })
      .with({ type: ComputedItemTypes.RULE }, (computedRule) => {
        assert(plan, 'Plan not given in rule formula parser');
 
        const ruleDefinition = this.definitionsContainer.getRuleByMachineName(computedRule.ruleMachineName, plan);
        if (!ruleDefinition) {
          throw new ConfigurationError(
            `Couldn't find the rule ${computedRule.ruleMachineName}, is it in the right scope?`,
            computedItemToErrorContext(computedRule),
          );
        }
 
        // If rule is non-payout, its currency value would be zero. In the case that it has a KPI displayed
        // on the header, its computation is going to be handled as a regular kpi.
        if (zerosNonPayoutRules && ruleDefinition.type === RuleType.NON_PAYOUT) {
          return ['0'];
        }
 
        // For Line Payout and HnR, we expect a commission variable and a filter.
        if ([RuleType.HOLD_AND_RELEASE, RuleType.LINE_PAYOUT].includes(ruleDefinition.type)) {
          const commissionVariable =
            ruleDefinition.commissionVariableId &&
            this.definitionsContainer.getVariableById(ruleDefinition.commissionVariableId);
          if (!commissionVariable) {
            throw new ConfigurationError(
              `Commission variable not found for rule ${ruleDefinition.machineName}`,
              computedItemToErrorContext(computedItem),
            );
          }
          if (!ruleDefinition.filter) {
            throw new ConfigurationError(`Rule ${ruleDefinition.machineName} should have a filter.`);
          }
          return [
            `SUM(filter.${ruleDefinition.filter.machineName}, ${ruleDefinition.filter.object!.machineName}.${commissionVariable.machineName})` as AmaliaFormula,
          ];
        }
 
        // If the rule has a filter, then it's a SUM in our engine, transform the formula right now.
        if (ruleDefinition.filter) {
          return [`SUM(filter.${ruleDefinition.filter.machineName}, ${ruleDefinition.formula})` as AmaliaFormula];
        }
 
        return [ruleDefinition.formula as AmaliaFormula];
      })
      .with({ type: ComputedItemTypes.FUNCTION_RESULT }, (computedFunctionResult) =>
        // TODO: refactor needed -- should be more generic
        FormulaParser.getFormulasOfFunctionResult(computedFunctionResult),
      )
      .otherwise(() => {
        throw new Error('Cannot retrieve formulas of item.');
      });
  }
 
  private static getFormulasOfFunctionResult(computedItem: ComputedFunctionResult) {
    switch (computedItem.function) {
      case 'SUM':
      case 'rowMarginalIndex':
      case 'rowTiersIndex':
        return [(computedItem.args as ComputedFunctionArgs_SUM).formula];
      case 'GETATINDEX':
        return [
          (computedItem.args as ComputedFunctionArgs_GETATINDEX).formula,
          (computedItem.args as ComputedFunctionArgs_GETATINDEX).predicate,
        ].filter(Boolean);
      default:
        throw new Error(`Cannot retrieve formulas of function ${computedItem.function}.`);
    }
  }
 
  public static joinRelations(currentRelationLevel: string | null, newRelationNames: string[] | string): string {
    return (currentRelationLevel ?? '').split('.').concat(newRelationNames).filter(Boolean).join('.');
  }
}