All files / libs/payout-calculation/compute-engine/core-statement-calculation-cache/src/statementCalculationCache StatementCalculation.cache.ts

52.17% Statements 156/299
83.33% Branches 5/6
25% Functions 3/12
52.17% Lines 156/299

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 3001x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x                               1x 1x       1x 1x       1x 1x       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 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 { Logger } from '@nestjs/common';
import { In, type DataSource } from 'typeorm';
 
import { FormulaParser, type DefinitionsContainer } from '@amalia/amalia-lang/formula/parsing';
import { type VariableValuesService } from '@amalia/assignments/quotas/core';
import {
  DataRefreshment,
  Overwrite,
  type Plan,
  type Relationship,
  type Rule,
  type Variable,
  type VariableValue,
} from '@amalia/core/models';
import { OverwriteTypesEnum } from '@amalia/core/types';
import { type CustomObjectDefinition } from '@amalia/data-capture/record-models/types';
import { type CurrencySymbolsEnum } from '@amalia/ext/iso-4217';
import { assert } from '@amalia/ext/typescript';
import {
  type DefinitionsContainerFactory,
  type FiltersService,
  type RelationshipsService,
  type RulesService,
  type VariablesService,
} from '@amalia/payout-definition/designer/core';
import { type Period } from '@amalia/payout-definition/periods/types';
import { type Plan as CalculationPlan } from '@amalia/payout-definition/plans/types';
import { type CurrencyRatesService } from '@amalia/tenants/companies/currency-rates/core';
import { type Company } from '@amalia/tenants/companies/types';
import { type TeamContract } from '@amalia/tenants/teams/types';
import { type UserContract } from '@amalia/tenants/users/types';
 
import { type StatementCalculationCacheScope } from './statementCalculationCache.factory';
import { type StoppableCalculation } from './stoppableCalculation';
 
type CompanyWithRates = Company & { rates?: Record<number, Record<string, number>> };
 
interface LastRefreshmentsData {
  lastRefreshmentUpdatedAt: number | null;
  lastOverwriteIsCleared: boolean | null;
  lastOverwriteId: string | null;
  lastRefreshmentId: string | null;
}
 
export class StatementCalculationCache {
  private readonly logger = new Logger(StatementCalculationCache.name);
 
  private definitionsContainer: DefinitionsContainer<Plan, Relationship> | null = null;
 
  private formulaParser: FormulaParser | null = null;
 
  private readonly conversionRates: {
    currencyCode: CurrencySymbolsEnum;
    endDate: number;
    rate: number;
  }[] = [];
 
  private readonly userVariableValues = new Map<string, VariableValue[]>();
 
  private readonly teamUserVariableValues = new Map<string, VariableValue[]>();
 
  private readonly userPlanVariableValues = new Map<string, VariableValue[]>();
 
  private readonly lastObjectUpdates = new Map<string, LastRefreshmentsData>();
 
  public constructor(
    private readonly connection: DataSource,
    public readonly company: Company,
    public readonly calculation: StoppableCalculation | null,
    protected readonly filtersService: FiltersService,
    protected readonly rulesService: RulesService,
    protected readonly variablesService: VariablesService,
    private readonly currencyRatesService: CurrencyRatesService,
    private readonly variableValuesService: VariableValuesService,
    protected readonly relationshipsService: RelationshipsService,
    protected readonly definitionsContainerFactory: DefinitionsContainerFactory,
  ) {}
 
  /**
   * Load all the definitions from the designer in the cache.
   */
  public async init(scope: StatementCalculationCacheScope): Promise<void> {
    const { planId, ruleIds } = scope;
    const startDate = Date.now();

    this.definitionsContainer = await this.definitionsContainerFactory.getDefinitionsContainer(
      this.company,
      planId,
      ruleIds,
      this.calculation?.type,
    );

    this.formulaParser = new FormulaParser(this.definitionsContainer);

    const now = Date.now();
    this.logger.debug({ message: `StatementCalculationCache init: ${now - startDate}ms`, timingMs: now - startDate });
  }
 
  public getDefinitions(): DefinitionsContainer<Plan, Relationship> {
    assert(this.definitionsContainer, 'Definitions container not bootstrapped');
    return this.definitionsContainer;
  }
 
  public getFormulaParser(): FormulaParser {
    assert(this.formulaParser, 'Formula parser not bootstrapped');
    return this.formulaParser;
  }
 
  public async fetchRuleById(id: string): Promise<Rule> {
    const foundRule = this.definitionsContainer?.getRuleById(id);
    return foundRule || (await this.rulesService.findById(this.company, id, ['commissionVariable', 'filter']));
  }
 
  public async getConversionRate(currencyCode: CurrencySymbolsEnum, endDate: Period['endDate']): Promise<number> {
    let conversionRate = this.conversionRates.find((r) => r.currencyCode === currencyCode && r.endDate === endDate);

    if (!conversionRate) {
      const rate: number = await this.getConversionRateCurrency(this.company, currencyCode, endDate);

      conversionRate = {
        currencyCode,
        endDate,
        rate,
      };

      this.conversionRates.push(conversionRate);
    }

    return conversionRate.rate;
  }
 
  public async getConversionRateCurrency(
    company: CompanyWithRates,
    currencySymbol: CurrencySymbolsEnum,
    date: number,
  ): Promise<number> {
    // Should be converted to company.currency
    if (currencySymbol !== company.currency && !company.rates?.[date]?.[currencySymbol]) {
      return this.currencyRatesService.findCurrencyRate(company, currencySymbol, date);
    }
    return 1;
  }
 
  private static getCompositeKey(user: UserContract, period: Period, variable: Variable) {
    return `${user.id}:${period.id}:${variable.id}`;
  }
 
  /**
   * Get user variable values.
   * @param variable
   * @param user
   * @param period
   */
  public async getUserVariableValues(variable: Variable, user: UserContract, period: Period) {
    let userVariableValues = this.userVariableValues.get(
      StatementCalculationCache.getCompositeKey(user, period, variable),
    );

    if (!userVariableValues) {
      userVariableValues = await this.variableValuesService.findAll(
        this.company,
        variable.id,
        user.id,
        null,
        null,
        undefined,
        period,
      );
      this.userVariableValues.set(
        StatementCalculationCache.getCompositeKey(user, period, variable),
        userVariableValues,
      );
    }

    return userVariableValues;
  }
 
  /**
   * Get plan variable values.
   * @param variable
   * @param user
   * @param plan
   * @param period
   */
  public async getPlanVariableValues(variable: Variable, user: UserContract, plan: CalculationPlan, period: Period) {
    let planVariableValues = this.userPlanVariableValues.get(
      StatementCalculationCache.getCompositeKey(user, period, variable),
    );

    if (!planVariableValues) {
      planVariableValues = await this.variableValuesService.findAll(
        this.company,
        variable.id,
        null,
        plan.id,
        null,
        undefined,
        period,
      );
      this.userPlanVariableValues.set(
        StatementCalculationCache.getCompositeKey(user, period, variable),
        planVariableValues,
      );
    }

    return planVariableValues;
  }
 
  /**
   * Get team variable values.
   * @param variable
   * @param user
   * @param teams
   * @param period
   */
  public async getTeamVariableValues(
    variable: Variable,
    user: UserContract,
    teams: Pick<TeamContract, 'id'>[],
    period: Period,
  ): Promise<VariableValue[]> {
    // If you don't have teams, you can't have team variables.
    if (!teams.length) {
      return [];
    }
 
    let teamVariableValues = this.teamUserVariableValues.get(
      StatementCalculationCache.getCompositeKey(user, period, variable),
    );
 
    if (!teamVariableValues) {
      teamVariableValues = await this.variableValuesService.findAll(
        this.company,
        variable.id,
        null,
        null,
        teams.map((t) => t.id),
        undefined,
        period,
      );
      this.teamUserVariableValues.set(
        StatementCalculationCache.getCompositeKey(user, period, variable),
        teamVariableValues,
      );
    }
 
    // Normally team variable values are not empty. Still ensure that
    return teamVariableValues.filter((vv) => vv.value !== null);
  }
 
  public async getLastUpdateOfCustomObjects(
    customObjectDefinition: Pick<CustomObjectDefinition, 'id'>,
  ): Promise<LastRefreshmentsData> {
    const { id: customObjectDefinitionId } = customObjectDefinition;

    if (this.lastObjectUpdates.has(customObjectDefinitionId)) {
      return this.lastObjectUpdates.get(customObjectDefinitionId) as LastRefreshmentsData;
    }

    const [lastOverwrite, lastRefreshment] = await Promise.all([
      // Fetch last overwrite on the custom object.
      this.connection.getRepository(Overwrite).findOne({
        where: {
          company: { id: this.company.id },
          appliesToDefinitionId: customObjectDefinitionId,
          overwriteType: In([
            OverwriteTypesEnum.PROPERTY,
            OverwriteTypesEnum.FIELD,
            OverwriteTypesEnum.FILTER_ROW_ADD,
            OverwriteTypesEnum.FILTER_ROW_REMOVE,
          ]),
        },
        order: { updatedAt: 'DESC' },
      }),
      // Fetch last refreshment of the custom object.
      this.connection.getRepository(DataRefreshment).findOne({
        where: {
          company: { id: this.company.id },
          customObjectDefinitionId,
        },
        order: { updatedAt: 'DESC' },
      }),
    ]);

    const output = {
      lastOverwriteId: lastOverwrite?.id || null,
      // We need to bust the cache when an overwrite is created then immediately deleted.
      lastOverwriteIsCleared: !!lastOverwrite?.clearedAt,
      lastRefreshmentId: lastRefreshment?.id || null,
      // If a calculation is launched during a refreshment, then having it updated means new
      // objects are coming, so we should burst the cache to avoid missing new objects.
      lastRefreshmentUpdatedAt: lastRefreshment ? lastRefreshment.updatedAt.getTime() : null,
    };

    this.lastObjectUpdates.set(customObjectDefinitionId, output);

    return output;
  }
}