All files / libs/reporting/custom-reports/shared/src/lib/business/mainColumns getMainColumnsFromPlanTemplate.ts

100% Statements 52/52
71.42% Branches 15/21
100% Functions 2/2
100% Lines 52/52

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 531x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 4x 4x 2x 2x 3x 3x 3x 3x 3x 2x 2x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x  
import { keyBy, uniqBy } from 'lodash-es';
 
import { type Variable } from '@amalia/amalia-lang/tokens/types';
import { type PlanTemplateDehydrated } from '@amalia/payout-calculation/types';
import { type HighlightedKpiIdentifier } from '@amalia/payout-definition/plans/types';
 
const extractStatementVariablesFromPayout = (formula: string) =>
  [...formula.matchAll(/statement\.(?<variable>\w+)/giu)].map((match) => match.groups?.['variable']).filter(Boolean);
 
export const getMainColumnsFromPlanTemplate = (
  planTemplate: PlanTemplateDehydrated,
): {
  highlightedKpis: (Variable & { highlightedKpiIdentifier: HighlightedKpiIdentifier })[];
  rules: {
    ruleName: string;
    variables: (Variable & { isPayoutVariable?: boolean })[];
  }[];
} => {
  const variableDefinitionsById = keyBy(Object.values(planTemplate.definitions.variables), 'id');
 
  const planRuleCategories = (planTemplate.definitions.plan.categoriesV2 ?? []).map((c) => c.name);
 
  return {
    highlightedKpis: (planTemplate.definitions.plan.highlightedKpis ?? [])
      .toSorted((a, b) => a.identifier.localeCompare(b.identifier))
      .map((hk) => ({ ...variableDefinitionsById[hk.variableId], highlightedKpiIdentifier: hk.identifier }))
      .filter((v) => !!v.machineName),
    rules: (planTemplate.definitions.plan.planRules ?? [])
      // Sort rule by designer order => we need to sort by category first, then by rule index
      .toSorted((a, b) => {
        const categoryAIndex = planRuleCategories.indexOf(a.category ?? '');
        const categoryBIndex = planRuleCategories.indexOf(b.category ?? '');
        return categoryAIndex === categoryBIndex ? a.index - b.index : categoryAIndex - categoryBIndex;
      })
      .map((pr) => ({
        ruleName: pr.rule!.name,
        // Variables used for payout
        variables: uniqBy(
          [
            ...extractStatementVariablesFromPayout(pr.rule!.formula).map((m) => ({
              ...planTemplate.definitions.variables[m],
              isPayoutVariable: true,
            })),
            ...(pr.kpisToDisplay ?? []).flatMap((section) =>
              section.kpis.map((kpi): Variable | undefined => variableDefinitionsById[kpi.id]),
            ),
          ].filter((v): v is Variable & { isPayoutVariable?: boolean } => !!v?.id),
          (v) => v.id,
        ),
      })),
  };
};