All files / libs/payout-calculation/statements/core/src/modules/statementsDatasets statementDatasetsOverwrites.service.ts

72.24% Statements 216/299
29.16% Branches 7/24
83.33% Functions 5/6
72.24% Lines 216/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 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 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x                                                                                                                             1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x                   4x 4x 4x 4x     4x 4x     4x 4x     4x 4x 4x 4x 4x 4x 1x  
import { forwardRef as CircularDependency, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { isNil } from 'lodash-es';
 
import { type Company, type CustomObject, type Filter, type Statement, type Variable } from '@amalia/core/models';
import {
  mapCustomObjectToDatasetRow,
  OverwriteTypesEnum,
  type ComputedStatement,
  type DatasetRow,
} from '@amalia/core/types';
import { RecordContentPropertyType } from '@amalia/data-capture/connectors/types';
import { CustomObjectsService } from '@amalia/data-capture/records/core';
import { OverwritesService } from '@amalia/data-correction/overwrites/core';
import { OverwriteScopeEnum } from '@amalia/data-correction/overwrites/types';
import { assert } from '@amalia/ext/typescript';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { type CurrencyValue } from '@amalia/kernel/monetary/types';
import { FiltersService, VariablesService } from '@amalia/payout-definition/designer/core';
 
import { type AddDatasetRowsDto } from './dto/addDatasetRowsDto';
import { type CreateStatementDatasetOverwriteDto } from './dto/createDatasetOverwrite.dto';
import { type DeleteDatasetOverwriteDto } from './dto/deleteDatasetOverwrite.dto';
import { StatementDatasetsService } from './statementDatasets.service';
 
@Injectable()
export class StatementDatasetsOverwritesService {
  public constructor(
    private readonly customObjectsService: CustomObjectsService,
 
    private readonly filtersService: FiltersService,
    private readonly variablesService: VariablesService,
    @Inject(CircularDependency(() => StatementDatasetsService))
    private readonly statementDatasetsService: StatementDatasetsService,
    private readonly overwriteService: OverwritesService,
  ) {}
 
  /**
   * Add rows to statement dataset.
   * @param company
   * @param authenticatedContext
   * @param statement
   * @param datasetId
   * @param addDatasetRowsDto
   */
  public async addRows(
    company: Company,
    authenticatedContext: AuthenticatedContext,
    statement: Statement,
    datasetId: string,
    addDatasetRowsDto: AddDatasetRowsDto,
  ): Promise<DatasetRow[]> {
    assert(statement.forecast?.results, 'Results missing on statement');
    const filterId = StatementDatasetsOverwritesService.getDatasetFilterId(statement.forecast.results, datasetId);
 
    if (!filterId) {
      throw new NotFoundException(`No filter found for dataset ${datasetId}`);
    }
 
    const datasetRows: DatasetRow[] = [];
    for (const customObjectId of addDatasetRowsDto.customObjectIds) {
      const customObject = await this.customObjectsService.findOne(company, customObjectId);
 
      const overwriteToApply = {
        company,
        companyId: company.id,
        creator: authenticatedContext.user,
        statement,
        appliesToDealName: customObject.name,
        appliesToExternalId: customObject.externalId,
        appliesToDefinitionId: customObject.definitionId,
        createdOnStatementId: statement.id,
        field: OverwriteTypesEnum.FILTER_ROW_ADD,
        filterId,
        sourceValue: null,
        overwriteValue: null,
        overwriteType: OverwriteTypesEnum.FILTER_ROW_ADD,
        statementId: statement.id,
        scope: OverwriteScopeEnum.FORECAST,
      };
 
      const createdOverwrite = await this.overwriteService.applyOverwrite(
        company,
        authenticatedContext,
        overwriteToApply,
      );
 
      datasetRows.push(mapCustomObjectToDatasetRow(customObject, [createdOverwrite]));
    }
 
    return datasetRows;
  }
 
  private static getDatasetFilterId(statementResults: ComputedStatement, datasetId: string): string {
    const datasetIdMetadata = datasetId.split(':');
    return statementResults.definitions.filters[datasetIdMetadata[2]].id;
  }
 
  public async createOverwrite(
    company: Company,
    authenticatedContext: AuthenticatedContext,
    statement: Statement,
    datasetId: string,
    createStatementOverwriteDto: CreateStatementDatasetOverwriteDto,
  ) {
    assert(createStatementOverwriteDto.rowExternalId, 'createStatementOverwriteDto.rowExternalId not found');
    assert(createStatementOverwriteDto.definitionId, 'createStatementOverwriteDto.definition not found');
    const row = await this.statementDatasetsService.getDatasetRow(
      company,
      statement.id,
      datasetId,
      createStatementOverwriteDto.rowExternalId,
      createStatementOverwriteDto.calculationType,
    );
 
    const datasetRowValue = row.content[createStatementOverwriteDto.field];
 
    const currency = (datasetRowValue as CurrencyValue | undefined)?.symbol;
    const customObject = await this.customObjectsService.findByDefinitionAndExternalId(
      company,
      createStatementOverwriteDto.definitionId,
      createStatementOverwriteDto.rowExternalId,
      false,
    );
 
    assert(customObject, new NotFoundException('Custom object not found'));
 
    const variable = await this.variablesService.findById(company, createStatementOverwriteDto.variableId);
 
    assert(variable, new NotFoundException('Variable for overwrite not found'));
 
    const { overwritesToClear, sourceValue: overwriteSourceValue } = await this.getOverwritesToClearAndSourceValue(
      company,
      customObject,
      statement,
      createStatementOverwriteDto.scope,
      createStatementOverwriteDto.field,
      variable,
    );
 
    const overwriteToApply = {
      ...createStatementOverwriteDto,
      company,
      companyId: company.id,
      creator: authenticatedContext.user,
      sourceValue: overwriteSourceValue || {
        [createStatementOverwriteDto.field]: datasetRowValue as RecordContentPropertyType,
      },
      currency,
      statement: createStatementOverwriteDto.scope === OverwriteScopeEnum.STATEMENT ? statement : undefined,
      appliesToDealName: customObject.name,
      appliesToExternalId: createStatementOverwriteDto.rowExternalId,
      appliesToDefinitionId: createStatementOverwriteDto.definitionId,
      createdOnStatementId: statement.id,
      overwriteType: OverwriteTypesEnum.FIELD,
      variable,
      scope: createStatementOverwriteDto.scope,
    };
 
    return this.overwriteService.applyOverwrite(company, authenticatedContext, overwriteToApply, overwritesToClear);
  }
 
  public async deleteRowOverwrite(
    company: Company,
    authenticatedContext: AuthenticatedContext,
    statement: Statement,
    datasetId: string,
    rowExternalId: string,
    deleteDatasetOverwriteDto: DeleteDatasetOverwriteDto,
  ) {
    // Will check a notFound exception if no row found.
    await this.statementDatasetsService.getDatasetRow(
      company,
      statement.id,
      datasetId,
      rowExternalId,
      deleteDatasetOverwriteDto.calculationType,
    );

    assert(deleteDatasetOverwriteDto.definitionId, 'definitionId on overwrite missing');

    // if filter overwrite then no need for value / source value
    const customObject = await this.customObjectsService.findByDefinitionAndExternalId(
      company,
      deleteDatasetOverwriteDto.definitionId,
      rowExternalId,
      false,
    );

    assert(customObject, 'customObject to overwrite not found');

    const filter = await this.filtersService.findById(company, deleteDatasetOverwriteDto.filterId, []);

    const { overwritesToClear } = await this.getOverwritesToClearAndSourceValue(
      company,
      customObject,
      statement,
      deleteDatasetOverwriteDto.scope,
      OverwriteTypesEnum.FILTER_ROW_REMOVE,
      undefined,
      filter,
    );

    return this.overwriteService.applyOverwrite(
      company,
      authenticatedContext,
      {
        company,
        companyId: company.id,
        creator: authenticatedContext.user,
        statement: deleteDatasetOverwriteDto.scope === OverwriteScopeEnum.STATEMENT ? statement : undefined,
        appliesToDealName: customObject.name,
        appliesToExternalId: rowExternalId,
        appliesToDefinitionId: deleteDatasetOverwriteDto.definitionId,
        createdOnStatementId: statement.id,
        field: OverwriteTypesEnum.FILTER_ROW_REMOVE,
        overwriteType: OverwriteTypesEnum.FILTER_ROW_REMOVE,
        scope: deleteDatasetOverwriteDto.scope,
        filter,
        sourceValue: null,
        overwriteValue: null,
      },
      overwritesToClear,
    );
  }
 
  private async getOverwritesToClearAndSourceValue(
    company: Company,
    customObject: CustomObject,
    statement: Statement,
    scope: OverwriteScopeEnum,
    field?: string,
    variable?: Variable,
    filter?: Filter,
  ) {
    const overwritesToClear = [];
    const overwriteToClear = await this.overwriteService.findOneByCustomObjectAndFieldAndStatementAndVariableAndFilter(
      company,
      field,
      customObject,
      scope === OverwriteScopeEnum.STATEMENT ? statement : undefined,
      variable,
      filter,
    );
    if (overwriteToClear) {
      overwritesToClear.push(overwriteToClear);
    }
 
    // In the case we apply a Global Overwrite on a Statement where a "Statement Overwrite"
    // already exist we need to clean as well the statement overwrite
    let overwriteStatementToClearWhenGlobalSet;
    if (scope === OverwriteScopeEnum.GLOBAL) {
      overwriteStatementToClearWhenGlobalSet =
        await this.overwriteService.findOneByCustomObjectAndFieldAndStatementAndVariableAndFilter(
          company,
          field,
          customObject,
          statement,
          variable,
          filter,
        );
 
      if (overwriteStatementToClearWhenGlobalSet) {
        overwritesToClear.push(overwriteStatementToClearWhenGlobalSet);
      }
    }
    // On the contrary if we have a Global Overwrite that exist, and we apply on top a Statement Overwrite,
    // the new Statement overwrite should have the source value of the Global Overwrite source value
    let overwriteSourceValue;
    if (scope === OverwriteScopeEnum.STATEMENT) {
      overwriteSourceValue = await this.overwriteService.findOneByCustomObjectAndFieldAndStatementAndVariableAndFilter(
        company,
        field,
        customObject,
        undefined,
        variable,
        filter,
      );
    }
 
    let sourceValue;
    // replace the source value if an Overwrite already exist
    if (!isNil(overwriteToClear?.sourceValue)) {
      sourceValue = overwriteToClear.sourceValue;
    }
    // replace the source value if another Overwrite already exist (if global and statement)
    if (!isNil(overwriteStatementToClearWhenGlobalSet?.sourceValue)) {
      sourceValue = overwriteStatementToClearWhenGlobalSet.sourceValue;
    }
    // replace source value if we are on another overwrite
    if (!isNil(overwriteSourceValue?.sourceValue)) {
      sourceValue = overwriteSourceValue.sourceValue;
    }
 
    return {
      overwritesToClear,
      sourceValue,
    };
  }
}