All files / libs/payout-calculation/compute-engine/core-engine/src/engine/statementSave statementSave.service.ts

85.13% Statements 355/417
72% Branches 36/50
81.81% Functions 9/11
85.13% Lines 355/417

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 4181x 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 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 103x 6x 6x 103x 97x 97x 97x 97x 97x 97x 97x 97x 97x 103x 111x 111x 111x 103x 103x 103x 103x 103x 103x 103x 111x 111x 111x 111x 103x 103x 103x 111x           111x 111x 111x 111x 111x 103x 103x 103x 103x 103x 103x 103x 103x 111x 111x 111x 1x 1x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 103x 103x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 111x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x     8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                     1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x         2x 2x 2x 2x 2x 2x 2x 1x 1x 77x 77x 77x 77x 77x 77x 1x 1x 76x 76x 76x 77x                       77x 1x 1x 1x 1x 1x 1x 1x 1x 1x                             1x 1x 75x 75x 1x 1x 77x 77x 77x 77x 77x 77x 1x  
import { Logger } from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { isEmpty } from 'lodash-es';
import { DataSource, In, Repository } from 'typeorm';
 
import {
  Creating,
  Rule,
  Statement,
  User,
  type Company,
  type Period,
  type PlanForecast,
  type StatementForecast,
} from '@amalia/core/models';
import {
  CalculationType,
  EngineError,
  EngineErrorLevel,
  EngineErrorType,
  isBeingReviewed,
  isEngineErrorHandledProperly,
  PaymentReleaseError,
  type ComputedStatement,
  type ComputedStatementSummary,
  type Statement as StatementType,
} from '@amalia/core/types';
import { assert, promiseDotAllChunk, toError } from '@amalia/ext/typescript';
import { type UserStatement } from '@amalia/payout-calculation/compute-engine/core-plan-template';
import { type StatementCalculationCache } from '@amalia/payout-calculation/compute-engine/core-statement-calculation-cache';
import { InitWorkflowCampaignCommand } from '@amalia/payout-calculation/workflow-campaign/core';
import { CompaniesService } from '@amalia/tenants/companies/core';
 
import { StatementBadgesService } from './badges/statementBadgesService';
import { StatementChallengesService } from './challenges/statementChallenges.service';
import { StatementSaveDatasetService } from './datasets/statementSaveDataset.service';
import { StatementsMetricsService } from './metrics/statementMetrics.service';
import { StatementPaymentsService } from './payments/statementPayments.service';
 
export class StatementSaveService {
  private readonly logger = new Logger(StatementSaveService.name);
 
  public constructor(
    private readonly connection: DataSource,
    @InjectRepository(Statement)
    private readonly statementRepository: Repository<Statement>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly companiesService: CompaniesService,
    private readonly statementMetricsService: StatementsMetricsService,
    private readonly statementChallengesService: StatementChallengesService,
    private readonly statementSaveDatasetService: StatementSaveDatasetService,
    private readonly statementPaymentsService: StatementPaymentsService,
    private readonly statementBadgesService: StatementBadgesService,
    private readonly commandBus: CommandBus,
  ) {}
 
  public async saveStatement(
    company: Company,
    statementCalculationCache: StatementCalculationCache,
    statement: Partial<Statement>,
    userStatement: UserStatement,
    error: EngineError | null,
    nextPeriods: Period[],
    planForecast?: PlanForecast,
  ): Promise<Statement> {
    const isForecasted = statementCalculationCache.calculation!.type === CalculationType.FORECAST;
 
    const statementToSave = this.buildStatementToSave(
      company,
      userStatement,
      isForecasted,
      statement,
      error,
      planForecast,
    );
 
    const queryRunner = this.connection.createQueryRunner();
 
    await queryRunner.connect();
    await queryRunner.startTransaction();
 
    let savedStatement: Statement;
 
    try {
      // Save statement.
      savedStatement = await queryRunner.manager.getRepository<Statement>(Statement).save(statementToSave);
 
      const savedStatementWithCompany = {
        ...savedStatement,
        company,
      };
 
      // Save datasets.
      await this.statementSaveDatasetService.saveStatementDatasets(
        company,
        statementCalculationCache,
        savedStatement,
        userStatement,
        queryRunner,
        statementCalculationCache.calculation!.type,
      );
 
      // If it's a new statement, there can't be any adjustments.
      const adjustments = statement.id ? (statement.adjustments ?? []) : [];
 
      // For achieved calculations, extract payments and challenges.
      if (!isForecasted) {
        if (error) {
          // Delete payments if the statement has error.
          await this.statementPaymentsService.deletePaymentsLinkedToStatement(queryRunner, savedStatement, company);
        } else {
          await this.statementPaymentsService.savePayments(
            savedStatementWithCompany,
            userStatement.getStatementDatasets(),
            nextPeriods,
            adjustments,
            queryRunner,
          );
          await this.statementChallengesService.saveChallengeResults(savedStatementWithCompany, queryRunner);
        }
      }
 
      // Save metrics.
      if (!error) {
        await this.statementMetricsService.extractAndSaveMetrics(
          statementCalculationCache.calculation!.type,
          savedStatementWithCompany,
          userStatement.getStatementDatasets(),
          adjustments,
        );
      }
 
      await queryRunner.commitTransaction();
 
      if (statementCalculationCache.calculation!.type === CalculationType.STATEMENT) {
        // Perform badge awarding
        await this.statementBadgesService.awardBadges(company, savedStatement);
      }
    } catch (e) {
      // Rollback the current transaction. It will remove the new statement
      // and all the payments that were created / edited / deleted.
      await queryRunner.rollbackTransaction();

      savedStatement = await this.handleStatementError(e as Error, statementToSave, isForecasted);
    } finally {
      await queryRunner.release();
    }
 
    if (statementCalculationCache.calculation!.type === CalculationType.STATEMENT) {
      await this.commandBus.execute(
        new InitWorkflowCampaignCommand({
          periodId: savedStatement.period?.id ?? savedStatement.periodId,
          planId: savedStatement.planId,
          companyId: company.id,
        }),
      );
    }
 
    return savedStatement;
  }
 
  private buildStatementToSave(
    company: Company,
    userStatement: UserStatement,
    isForecasted: boolean,
    statement: Partial<Statement>,
    error: EngineError | null,
    planForecast?: PlanForecast,
  ): Partial<Omit<Statement, 'forecast'> & { forecast?: Creating<StatementForecast> }> {
    const { full, summary, calculationTime, total } = userStatement.getComputedStatement();
 
    if (isForecasted) {
      assert(planForecast, 'Plan forecast not given to build statement forecast');
 
      const statementForecast = this.buildStatementForecast(
        company,
        statement,
        total,
        full,
        summary,
        error,
        calculationTime,
        planForecast,
      );
 
      return {
        ...statement,
        forecast: statementForecast,
      };
    }
 
    // Apply adjustments.
    const adjustedTotal = (statement.adjustments ?? []).reduce((acc, adjustment) => acc + adjustment.amount, total);
 
    // Prepare statement to save.
    return {
      ...statement,
      total: error ? 0 : adjustedTotal,
      error: error || null,
      results: full,
      resultSummary: summary,
      calculationTime,
      updatedAt: new Date(),
      lastCalculationDate: new Date(),
    };
  }
 
  /**
   * Build statement forecast to be stored in database (with results, error, and calculationTime).
   * @param company
   * @param statement
   * @param total
   * @param full
   * @param summary
   * @param error
   * @param calculationTime
   * @param planForecast
   * @private
   */
  private buildStatementForecast(
    company: Company,
    statement: Partial<Statement>,
    total: number,
    full: ComputedStatement,
    summary: ComputedStatementSummary,
    error: EngineError | null,
    calculationTime: number,
    planForecast: PlanForecast,
  ): Creating<StatementForecast> & { id?: string } {
    const statementForecast: Creating<StatementForecast> & { id?: string } = {
      company,
      statement: statement as Statement,
      statementId: statement.id!,
      total,
      currency: statement.currency!,
      rate: statement.rate!,
      resultSummary: summary,
      results: full,
      error: error || null,
      calculationTime,
      lastCalculationDate: new Date(),
      planForecast,
    };
 
    if (statement.forecastId) {
      statementForecast.id = statement.forecastId;
    }
 
    return statementForecast;
  }
 
  /**
   * If an error happened during the save of the statement or the handling of payments, and if it's a known error, we store it in the
   * statement to avoid crashing the whole ongoing calculation.
   * If error is unknown we rethrow it, it will be managed in the calculation service.
   * @param e
   * @param statementToSave
   * @param isForecasted
   * @private
   */
  private async handleStatementError(
    e: Error,
    statementToSave: Partial<Omit<Statement, 'forecast'> & { forecast?: Creating<StatementForecast> }>,
    isForecasted: boolean,
  ): Promise<Statement> {
    if (isEngineErrorHandledProperly(e)) {
      const statementWithError = isForecasted
        ? {
            ...statementToSave,
            forecast: {
              ...statementToSave.forecast,
              error: e.getError(),
            },
          }
        : {
            ...statementToSave,
            error: e.getError(),
            total: 0,
          };

      // We re-save the statement with the error in it, outside the transaction.
      // Normally it should not throw, if it does it's because we have a non-recoverable
      // error, so it'll bubble up to the calculation.
      return this.statementRepository.save(statementWithError);
    }
    throw e;
  }
 
  /**
   * Delete statements.
   * @param companyId
   * @param statementIds
   */
  public async deleteStatements(companyId: string, statementIds: string[]) {
    const company = await this.companiesService.findById(companyId);
 
    // We're not using statementIds directly because we want to be ultra sure that they are not being reviewed.
    const statementsToDelete = await this.statementRepository.find({
      where: {
        workflowComplete: false,
        id: In(statementIds),
      },
      select: ['id', 'workflowComplete', 'workflowSteps'],
    });
 
    if (isEmpty(statementsToDelete)) {
      return;
    }
 
    this.logger.debug(`${statementsToDelete.length} statements to delete`);
 
    const statementIdsToDelete = statementsToDelete
      // Verify out validated statements as well as those where a workflow is started.
      .filter((s) => s.workflowComplete === false && isBeingReviewed(s as StatementType) === false)
      .map((s) => s.id);
 
    await promiseDotAllChunk(statementIdsToDelete, (statementId) => this.deleteStatement(company, statementId), 1);
 
    this.logger.debug('Delete Statements - metrics');
  }
 
  private async deleteStatement(company: Company, statementId: string) {
    this.logger.debug(`Delete Statement ${statementId}`);
 
    // Open a transaction to delete the statement and update challenges.
    const queryRunner = this.connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
 
    try {
      this.logger.debug(`Delete Statement ${statementId} - challenges`);
      await this.statementChallengesService.removeStatementsFromChallenges(company, [statementId], queryRunner);
      await queryRunner.manager
        .getRepository<Statement>(Statement)
        .createQueryBuilder()
        .delete()
        .from(Statement)
        .where('companyId = :companyId', { companyId: company.id })
        .andWhere('id = :statementId', { statementId })
        .execute();
      await queryRunner.commitTransaction();
    } catch (e) {
      const error = toError(e);
      this.logger.error({ message: `Error while deleting statement ${statementId}`, statementId, error });
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
 
    // Since metrics are in another database, we delete them outside the transaction.
    await this.statementMetricsService.cascadeDeleteForStatement(company, [statementId], null);
  }
 
  public async releasePaymentsForUsers(
    userIds: string[],
    period: Period,
    company: Company,
    statementCalculationCache: StatementCalculationCache,
  ) {
    if (isEmpty(userIds)) {
      return;
    }
 
    try {
      await this.statementPaymentsService.releasePayments(company, userIds, period, statementCalculationCache);
    } catch (e) {
      if (e instanceof PaymentReleaseError) {
        await this.updatePeriodStatementsError(company, period, e.statementIds, {
          level: EngineErrorLevel.ERROR,
          type: EngineErrorType.PAYMENT,
          message: e.message,
        });
      }

      // Then bubble up the error above.
      throw e;
    }
  }
 
  /**
   * Update statement error.
   * @param company
   * @param period
   * @param statementIds
   * @param error
   */
  private async updatePeriodStatementsError(
    company: Company,
    period: Period,
    statementIds: string[],
    error: EngineError,
  ) {
    return this.statementRepository.update(
      {
        id: In(statementIds),
        period: { id: period.id },
        company: { id: company.id },
      },
      { error },
    );
  }
 
  public async syncChallengesLeaderboards(company: Company, statements: Statement[]) {
    return this.statementChallengesService.resyncLeaderboards(company, statements);
  }
 
  public async getNextPeriodsToSplitStatement(
    company: Company,
    rules: Pick<Rule, 'splitVariables'>[],
    currentPeriod: Period,
  ) {
    return this.statementPaymentsService.getNextPeriodsToSplitStatement(company, rules, currentPeriod);
  }
}