All files / libs/payout-calculation/payments/core/src/lib/save payments-save.service.ts

97.86% Statements 367/375
79.68% Branches 51/64
100% Functions 8/8
97.86% Lines 367/375

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 3761x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 14x 14x 14x 14x 14x 14x 14x 4x 4x 14x 14x 7x 7x 14x 14x 8x       8x 8x 8x 14x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 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 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 8x 8x 8x 8x 8x 8x 8x 12x 12x 12x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 12x 12x 12x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 12x 12x 12x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 4x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 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 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 13x 13x 13x 13x 13x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 13x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 8x 8x 8x 8x 8x 8x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 25x 25x 25x 25x 25x 25x 25x 1x 1x  
import { forwardRef as CircularDependency, Inject, Injectable } from '@nestjs/common';
import { keyBy, omit, partition } from 'lodash-es';
import { In, type QueryRunner } from 'typeorm';
 
import { Creating, Payment, type Company, type PaymentLock } from '@amalia/core/models';
import { PaymentType } from '@amalia/core/types';
import { OverwritesService } from '@amalia/data-correction/overwrites/core';
import { promiseAllSettledAutoThrow } from '@amalia/ext/typescript';
 
import { PaymentsOverwriteService } from '../overwrites/payments-overwrite.service';
import { PaymentLockService } from '../paymentLock/paymentLock.service';
 
import { type PaymentMergeResult } from './payments-save.types';
 
@Injectable()
export class PaymentsSaveService {
  public constructor(
    @Inject(CircularDependency(() => PaymentsOverwriteService))
    private readonly paymentsOverwriteService: PaymentsOverwriteService,
    @Inject(CircularDependency(() => OverwritesService))
    private readonly overwriteService: OverwritesService,
    private readonly paymentLockService: PaymentLockService,
  ) {}
 
  public async processPayments(
    company: Company,
    paymentsDiffToApply: PaymentMergeResult,
    parentQueryRunner: QueryRunner,
  ): Promise<void> {
    const paymentLocks = await this.paymentLockService.getPaymentLocks(company);
 
    if (paymentsDiffToApply.paymentsToRemove && paymentsDiffToApply.paymentsToRemove.length > 0) {
      await this.deletePayments(company, paymentsDiffToApply.paymentsToRemove, paymentLocks, parentQueryRunner);
    }
 
    if (paymentsDiffToApply.paymentsToCreate && paymentsDiffToApply.paymentsToCreate.length > 0) {
      await this.createPayments(company, paymentsDiffToApply.paymentsToCreate, paymentLocks, parentQueryRunner);
    }
 
    if (paymentsDiffToApply.paymentsToEdit && paymentsDiffToApply.paymentsToEdit.length > 0) {
      if (paymentsDiffToApply.paymentsToEdit.some((pdta) => !pdta.previousPayment.id)) {
        // Throw an error here, or else typeorm will go for a creation and that's not what we want here.
        throw new Error("Missing id or previous payment for a payment we're supposed to edit");
      }
 
      await this.editPayments(company, paymentsDiffToApply.paymentsToEdit, paymentLocks, parentQueryRunner);
    }
  }
 
  private async createPayments(
    company: Company,
    payments: Creating<Payment>[],
    paymentLocks: PaymentLock[],
    parentQueryRunner: QueryRunner,
  ): Promise<void> {
    // For now, we only handle the "period" lock.
    const [creatablePayments, nonCreatablePayments] = PaymentLockService.partitionLockedPayments(
      paymentLocks,
      payments,
    );
 
    // Create the payments in the database.
    const promises1 = await promiseAllSettledAutoThrow([
      // Save all payments that can be saved as-is.
      parentQueryRunner.manager.getRepository<Payment>(Payment).save(creatablePayments),
      // For each non-creatable payment, create a payment with a 0 amount.
      // It seems counterintuitive but the fact that we can link a payment to it even if that
      // payment shouldn't exist gives us the possibility to get the payment metadata.
      parentQueryRunner.manager.getRepository<Payment>(Payment).save(
        nonCreatablePayments.map((p) => ({
          ...p,
          totalValue: 0,
          value: 0,
        })),
      ),
    ]);
 
    const createdNonCreatablePayments = promises1[1];
 
    // The issue is that because we changed the amount for 0, we're not able to save the diff anymore because we lost the amount.
    // We need a consolidated list of the payments with their id and the amount, so we're rebuilding it here.
    const createdNonCreatablePaymentsWithIds = nonCreatablePayments.map((p, index) => ({
      ...p,
      id: createdNonCreatablePayments[index].id,
      createdAt: createdNonCreatablePayments[index].createdAt,
      updatedAt: createdNonCreatablePayments[index].updatedAt,
    }));
 
    // Register the diffs of the payments we couldn't save.
    await this.paymentLockService.registerDiffs(
      company,
      { paymentsCreated: createdNonCreatablePaymentsWithIds },
      parentQueryRunner,
    );
  }
 
  /**
   * Save payment (eventually apply overwrites before saving if needed).
   *
   * This function needs a query runner because operations have to run in a transaction (save payments with their overwrites).
   *
   * @param company
   * @param paymentMergeResults
   * @param paymentLocks
   * @param parentQueryRunner
   */
  private async editPayments(
    company: Company,
    paymentMergeResults: PaymentMergeResult['paymentsToEdit'],
    paymentLocks: PaymentLock[],
    parentQueryRunner: QueryRunner,
  ): Promise<Payment[]> {
    const [currentlySplitPayments, nonSplitPaymentsMergeResult] = partition(
      paymentMergeResults,
      (p) => p.previousPayment.totalValue !== p.previousPayment.value,
    );
 
    // Relation to split payments should have been resolved by the level above: if the totalAmount is different from the value,
    // then payment has a split. If we aren't able to link it to anything, it means that the split disappeared, and we might have
    // an issue somewhere.
    if (currentlySplitPayments.some((p) => !p.previousPayment.splits?.length)) {
      const idsToDisplay = currentlySplitPayments
        .filter((p) => !p.previousPayment.splits?.length)
        .map((p) => p.previousPayment.id);
      throw new Error(`${company.name} - Cannot find splits for some of those payments: ${idsToDisplay.join(', ')}`);
    }
 
    const splitPaymentsMergeResult = currentlySplitPayments.flatMap((masterPayment) => {
      const updatedSplits = masterPayment.previousPayment.splits!.map(
        (s): { previousPayment: Payment; newPayment: Payment } => {
          // Get the current proportion of the split (for instance 20%).
          const proportion = s.value / masterPayment.previousPayment.totalValue!;
 
          // Now edit the split to reflect the proportion with the new value.
          return {
            previousPayment: s,
            newPayment: {
              ...s,
              totalValue: masterPayment.newPayment.totalValue,
              value: masterPayment.newPayment.totalValue! * proportion,
            },
          };
        },
      );
 
      // Now return the updated master payment, and all its updated splits.
      const newMasterPayment: Payment = {
        ...masterPayment.newPayment,
        value: masterPayment.newPayment.totalValue! - updatedSplits.reduce((acc, s) => acc + s.newPayment.value, 0),
        totalValue: masterPayment.newPayment.totalValue,
        // Not saving the splits with the entity, instead we're saving each individual payment.
        splits: undefined,
      };
 
      return [
        {
          ...masterPayment,
          newPayment: newMasterPayment,
        },
        ...updatedSplits,
      ];
    });
 
    const paymentMergeResultsWithSplitResults = nonSplitPaymentsMergeResult.concat(splitPaymentsMergeResult);
 
    const payments = paymentMergeResultsWithSplitResults.map((pdta) => pdta.newPayment);
 
    // Put the value of the paymentPeriod.id in paymentPeriodId.
    // It's the same for typeorm, but it's easier to handle for overwrites.
    let finalPayments: Payment[] = payments.map((p) => ({
      ...p,
      paymentPeriod: undefined,
      paymentPeriodId: p.paymentPeriod?.id || p.paymentPeriodId,
    }));
 
    // Populate the payments with their overwrites.
    const paymentsWithTheirOverwrites = await this.paymentsOverwriteService.populatePaymentsWithOverwrites(
      company,
      finalPayments,
    );
 
    // Then, merge payments with their overwritten value.
    finalPayments = await Promise.all(
      paymentsWithTheirOverwrites.map(async (p): Promise<Payment> => {
        const paymentOutput = { ...p };
        // Loop on overwrites to merge them in the payment.
        for (const overwriteToApply of p.overwrites) {
          const { sourceValue, overwriteValue, field } = overwriteToApply;
          const currentFieldValue = p[field as keyof Pick<Payment, 'paymentPeriodId'>];
 
          // If the source value of to overwrite is no longer the value
          // of the output from the calculation engine, update it.
          if (sourceValue !== currentFieldValue) {
            // One by one since we're already in a Promise.all.
            await this.overwriteService.patch(
              company,
              overwriteToApply,
              { sourceValue: currentFieldValue },
              parentQueryRunner,
            );
          }
 
          // Then rewrite the property in the payment.
          paymentOutput[field as keyof Pick<Payment, 'paymentPeriodId'>] = overwriteValue as string;
        }
 
        // Remove the overwrites key from the output, it'll no longer be used.
        return omit(paymentOutput, 'overwrites');
      }),
    );
 
    const [editablePayments, nonEditablePayments] = PaymentLockService.partitionLockedPayments(
      paymentLocks,
      finalPayments,
    );
 
    // For those we can't save, rebuild the list to get their previous value, so we can build the diff.
    const nonEditablePaymentsWithPreviousValue = nonEditablePayments.map((p) => ({
      newPayment: p,
      previousPayment: paymentMergeResultsWithSplitResults.find((pmr1) => p.id === pmr1.previousPayment.id)!
        .previousPayment,
    }));
 
    // Save the payments that can be saved.
    const updatePayments = await parentQueryRunner.manager.getRepository<Payment>(Payment).save(editablePayments);
 
    await promiseAllSettledAutoThrow([
      // Flush payments diffs for the payments we could actually save.
      this.paymentLockService.flushDiffs(company, editablePayments, parentQueryRunner),
 
      // Save diffs of edited payments.
      this.paymentLockService.registerDiffs(
        company,
        { paymentsToEdit: nonEditablePaymentsWithPreviousValue },
        parentQueryRunner,
      ),
    ]);
 
    return updatePayments;
  }
 
  private async deletePayments(
    company: Company,
    payments: Payment[],
    paymentLocks: PaymentLock[],
    parentQueryRunner: QueryRunner,
  ): Promise<void> {
    // If we're deleting a split payment, we have to remove its splits as well.
    const paymentsWithSplits = payments.flatMap((payment) => [payment, ...(payment.splits ?? [])]);
 
    const [deletablePayments, nonDeletablePayments] = PaymentLockService.partitionLockedPayments(
      paymentLocks,
      paymentsWithSplits,
    );
 
    const deletablePaymentIds = deletablePayments.map((p) => p.id);
 
    // We save payments and update the diffs in the same transaction, so we can't
    // Promise.all in case one of them throws.
    await promiseAllSettledAutoThrow([
      // Actually delete the payments in database.
      parentQueryRunner.manager.getRepository<Payment>(Payment).delete({
        company: { id: company.id },
        id: In(deletablePaymentIds),
      }),
 
      // Flush payments diffs for the payments we could actually save.
      this.paymentLockService.flushDiffs(company, deletablePayments, parentQueryRunner),
    ]);
 
    // Register the diffs of the payments we couldn't save.
    await this.paymentLockService.registerDiffs(company, { paymentsToRemove: nonDeletablePayments }, parentQueryRunner);
  }
 
  /**
   * Given the list of payments that are in db and the one we just extracted from the statement,
   * return the updated list of payments for this statement and the orphans payments that
   * need to be pruned.
   *
   * @param previousPayments
   * @param currentPayments
   * @param paymentLocks
   */
  public static mergePayments(
    previousPayments: Payment[],
    currentPayments: Partial<Payment>[],
    paymentLocks: PaymentLock[],
  ): PaymentMergeResult {
    // Build a hashmap of payments that are in db to avoid doing too many finds.
    const previousPaymentsHashmap: Record<string, Payment> = keyBy(previousPayments, (p) =>
      PaymentsSaveService.getPaymentDeduplicationKey(p),
    );
 
    // Also build locks only once.
    const paymentLocksPeriodIds = paymentLocks.map((p) => p.period.id);
 
    const paymentsToCreate: PaymentMergeResult['paymentsToCreate'] = [];
    const paymentsToEdit: PaymentMergeResult['paymentsToEdit'] = [];
 
    // For each currentPayment, try to grab one from the database.
    currentPayments.forEach((p) => {
      const key = PaymentsSaveService.getPaymentDeduplicationKey(p);
      const existingPayment = previousPaymentsHashmap[key] as Payment | undefined;
 
      // For new payments.
      if (existingPayment) {
        paymentsToEdit.push({
          previousPayment: existingPayment,
          // Completing the new payment, we bring all values excepted id.
          newPayment: {
            ...(p as Payment),
            id: existingPayment.id,
            // If it's a hold and release payment, it could have been released already.
            // If that's the case, reset the paymentPeriod in the line.
            paymentPeriodId: this.getPaymentPeriodIdForPaymentMerge(existingPayment, p, paymentLocksPeriodIds)!,
            // Reset the valueBeforeDeletion since we're editing the payment, in case the payment was soft-deleted.
            valueBeforeDeletion: null,
          },
        });
      } else {
        paymentsToCreate.push(p as Payment);
      }
    });
 
    // Orphans payments are the ones that were not picked during the previous evaluation.
    const pickedPaymentIds = new Set(paymentsToEdit.map((p) => p.previousPayment.id).filter(Boolean));
    const paymentsToRemove = previousPayments.filter((p) => !pickedPaymentIds.has(p.id));
 
    return {
      paymentsToCreate,
      paymentsToEdit,
      paymentsToRemove,
    };
  }
 
  private static getPaymentPeriodIdForPaymentMerge(
    existingPayment: Payment,
    newPayment: Partial<Payment>,
    paymentLocksPeriodIds: string[],
  ): string | null {
    // For non hold and release payment, just apply the value we have in the payment.
    if (newPayment.type !== PaymentType.LINE_HOLD) {
      return newPayment.paymentPeriod?.id || newPayment.paymentPeriodId || null;
    }
 
    // For hold and release payments, reset the payment period if it's not locked.
    // This way, it allows admins to make mistakes while configuring the release condition, since
    // the payment will go back to being locked when the statement it's coming from is recalculated.
    // However, if the payment period is locked, we have to keep the payment on it.
 
    // The payment is already released on a locked period, keep it as-is
    // Else reset the value.
    return paymentLocksPeriodIds.includes(existingPayment.paymentPeriodId!)
      ? existingPayment.paymentPeriodId || null
      : null;
  }
 
  /**
   * For each payment, create a deduplication key to retrieve it into the list
   * of payments that are attached to the statement.
   *
   * @param payment
   */
  private static readonly getPaymentDeduplicationKey = (payment: Partial<Payment>) =>
    [
      `type:${payment.type ?? ''}`,
      `user:${payment.user?.id || payment.userId || ''}`,
      `plan:${payment.plan?.id || payment.planId || ''}`,
      `ruleId:${payment.ruleId ?? ''}`,
      `deal:${payment.dealExternalId ?? ''}`,
      `adj:${payment.adjustment?.id ?? ''}`,
      // In case of payment split, we also need a paymentPeriod.
      `pay:${(payment.type === PaymentType.RULE_SPLIT && payment.paymentPeriod?.id) ?? ''}`,
    ].join(';');
}