All files / libs/amalia-lang/formula/evaluate/shared/src/functions/misc/sum index.ts

100% Statements 63/63
100% Branches 3/3
100% Functions 3/3
100% Lines 63/63

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 641x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { AmaliaFunctionCategory, AmaliaFunctionKeys, type AmaliaFormula } from '@amalia/amalia-lang/formula/types';
import { TokenType } from '@amalia/amalia-lang/tokens/types';
import { FormatsEnum } from '@amalia/data-capture/fields/types';
 
import { CalculationParser } from '../../../CalculationParser';
import { SanitizeFormula } from '../../../sanitizeFormula';
import { AmaliaFunctionRawArgs } from '../../AmaliaFunction';
import { getValueOrFormula } from '../../utils';
 
export const miscSum = new AmaliaFunctionRawArgs<number>({
  name: AmaliaFunctionKeys.SUM,
  category: AmaliaFunctionCategory.MISC,
  nbParamsRequired: 2,
  description: 'Sum a parameter based on a filtered dataset',
 
  generateComputedFunctionResult: (args) => ({
    array: getValueOrFormula(args[0]),
    formula: SanitizeFormula.amaliaFormulaToMathJs(getValueOrFormula(args[1])) as AmaliaFormula,
  }),
 
  parametersToEscapeOnParse: [0, 1],
 
  execMock: (): number => 1,
  exec: (args, _, scope) => CalculationParser.getFunctionResult(args, scope, AmaliaFunctionKeys.SUM),
 
  params: [
    {
      name: 'dataset',
      description: 'Filters or Links',
      validTokenTypes: [TokenType.FILTER, TokenType.LINK],
      validFormats: [FormatsEnum.table],
    },
    {
      name: 'parameter',
      description: 'Variables, fields or properties to sum.',
      validTokenTypes: [
        TokenType.VARIABLE,
        TokenType.FIELD,
        TokenType.PROPERTY,
        TokenType.FUNCTION,
        TokenType.VIRTUAL_PROPERTY,
      ],
      validTokenValues: {
        [TokenType.FUNCTION]: [AmaliaFunctionKeys.IF, AmaliaFunctionKeys.DEFAULT],
      },
    },
  ],
 
  examples: [
    {
      desc: 'Returns the summed amount of filtered opportunities.',
      formula: 'SUM(filter.closedInQuarter, opportunity.amount)' as AmaliaFormula,
    },
    {
      desc: 'Returns the summed amount of filtered opportunity line items based on its link with the opportunity.',
      formula: 'SUM(opportunity.oppToLineItemsLink, opportunity.oppToLineItemsLink.amount)' as AmaliaFormula,
    },
    {
      desc: 'Returns the summed amount of filtered opportunities when the type is not renewal.',
      formula: 'SUM(filter.closedInQuarter, IF(opportunity.type="Renewal", 0, opportunity.amount)' as AmaliaFormula,
    },
  ],
});