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

90.78% Statements 197/217
76.66% Branches 23/30
88.88% Functions 8/9
90.78% Lines 197/217

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 2181x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 1x 1x 27x 27x 27x 27x 27x 1x 1x 8x 8x 8x 8x 8x 8x             8x 1x 1x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 4x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 3x 3x 16x 16x 16x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 32x 32x 19x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x                             1x  
import { ConflictException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { partition } from 'lodash-es';
import { In, Repository, type QueryRunner } from 'typeorm';
 
import { Creating, PaymentDiff, PaymentDiffType, PaymentLock, type Company, type Payment } from '@amalia/core/models';
import { isUniqueViolationError } from '@amalia/ext/typeorm';
import { promiseAllSettledAutoThrow } from '@amalia/ext/typescript';
 
import { type PaymentMergeResult } from '../save/payments-save.types';
 
@Injectable()
export class PaymentLockService {
  public constructor(
    @InjectRepository(PaymentLock)
    private readonly paymentLockRepository: Repository<PaymentLock>,
    @InjectRepository(PaymentDiff)
    private readonly paymentDiffRepository: Repository<PaymentDiff>,
  ) {}
 
  public getPaymentLocks(company: Company): Promise<PaymentLock[]> {
    return this.paymentLockRepository.find({
      where: { company: { id: company.id } },
      relations: ['period'],
    });
  }
 
  public async lockContext(company: Company, context: PaymentLock) {
    try {
      return await this.paymentLockRepository.save({
        companyId: company.id,
        periodId: context.period.id,
      });
    } catch (e) {
      if (isUniqueViolationError(e)) {
        throw new ConflictException('This period is already locked');
      } else {
        throw e;
      }
    }
  }
 
  public async unlockContext(company: Company, context: PaymentLock) {
    await this.paymentLockRepository.delete({
      companyId: company.id,
      periodId: context.period.id,
    });
  }
 
  /**
   * If we couldn't save the payments because the contexts were locked, register
   * the diffs in the Audit table.
   *
   * I wish we could save them all, like shelter cats.
   *
   * @param company
   * @param paymentsDiffToApply
   * @param parentQueryRunner
   */
  public async registerDiffs(
    company: Company,
    paymentsDiffToApply: PaymentMergeResult,
    parentQueryRunner: QueryRunner,
  ) {
    // Put released payments aside.
    const [justReleasedPayments, otherEditedPayments] = partition(
      paymentsDiffToApply.paymentsToEdit ?? [],
      ({ newPayment, previousPayment }) =>
        (newPayment.paymentPeriod?.id || newPayment.paymentPeriodId) !==
        (previousPayment.paymentPeriod?.id || previousPayment.paymentPeriodId),
    );
 
    // And now partition editions, those that have 0 diff will be deleted.
    const [editionDiffWithChange, editionDiffWithoutChange] = partition(
      otherEditedPayments,
      ({ newPayment, previousPayment }) => newPayment.value !== previousPayment.value,
    );
 
    const diffs: Creating<PaymentDiff>[] = [
      ...(paymentsDiffToApply.paymentsCreated ?? []).map((payment) => ({
        diffType: PaymentDiffType.NEW,
        company,
        companyId: company.id,
        payment,
        paymentId: payment.id,
        paymentPeriodId: payment.paymentPeriod?.id || payment.paymentPeriodId!,
        currency: payment.currency,
        oldValue: 0,
        newValue: payment.value,
        rate: payment.rate,
        applied: false,
      })),
      ...editionDiffWithChange.map(({ newPayment, previousPayment }) => ({
        diffType: PaymentDiffType.EDIT,
        company,
        companyId: company.id,
        payment: newPayment,
        paymentId: newPayment.id,
        paymentPeriodId: newPayment.paymentPeriodId!,
        currency: newPayment.currency,
        oldValue: previousPayment.value,
        newValue: newPayment.value,
        rate: newPayment.rate,
        applied: false,
      })),
      ...justReleasedPayments.map(({ newPayment }) => ({
        diffType: PaymentDiffType.RELEASE,
        company,
        companyId: company.id,
        payment: newPayment,
        paymentId: newPayment.id,
        paymentPeriodId: newPayment.paymentPeriodId!,
        currency: newPayment.currency,
        oldValue: 0, // The payment just appeared on the period.
        newValue: newPayment.value,
        rate: newPayment.rate,
        applied: false,
      })),
      ...(paymentsDiffToApply.paymentsToRemove ?? []).map((payment) => ({
        diffType: PaymentDiffType.DELETE,
        company,
        companyId: company.id,
        payment,
        paymentId: payment.id,
        paymentPeriodId: payment.paymentPeriodId!,
        currency: payment.currency,
        oldValue: payment.value,
        newValue: 0,
        rate: payment.rate,
        applied: false,
      })),
    ];
 
    // Upsert the diffs in db.
    await parentQueryRunner.manager.getRepository(PaymentDiff).upsert(diffs, ['paymentId']);
 
    await promiseAllSettledAutoThrow(
      [
        // The edition diff that have no difference in amount should be deleted since they're reset.
        parentQueryRunner.manager.getRepository(PaymentDiff).delete({
          paymentId: In(editionDiffWithoutChange.map((d) => d.newPayment.id)),
        }),
 
        // Delete the DELETION diffs with a 0 amount, because it can be a new payment that were added then deleted.
        // We cannot just filter them out of the map above, because we need them to be upserted first.
        paymentsDiffToApply.paymentsToRemove &&
          parentQueryRunner.manager.getRepository(PaymentDiff).delete({
            paymentId: In(paymentsDiffToApply.paymentsToRemove.filter((p) => p.value === 0).map((p) => p.id)),
          }),
      ].filter(Boolean),
    );
  }
 
  /**
   * If a context was locked then unlocked, we have to flush the diffs of the
   * payments we successfully saved.
   *
   * @param company
   * @param payments
   * @param parentQueryRunner
   */
  public async flushDiffs(company: Company, payments: Payment[], parentQueryRunner: QueryRunner) {
    if (!payments.length) {
      return;
    }
 
    await parentQueryRunner.manager.getRepository(PaymentDiff).delete({
      company: { id: company.id },
      paymentId: In(payments.map((p) => p.id)),
    });
  }
 
  public static partitionLockedPayments(
    paymentLocks: PaymentLock[],
    payments: Payment[],
  ): [nonLockedPayments: Payment[], lockedPayments: Payment[]];
  public static partitionLockedPayments(
    paymentLocks: PaymentLock[],
    payments: Creating<Payment>[],
  ): [nonLockedPayments: Creating<Payment>[], lockedPayments: Creating<Payment>[]];
  public static partitionLockedPayments(
    paymentLocks: PaymentLock[],
    payments: Creating<Payment>[] | Payment[],
  ): [nonLockedPayments: Creating<Payment>[] | Payment[], lockedPayments: Creating<Payment>[] | Payment[]] {
    const lockedPeriodIds = new Set(paymentLocks.map((lc) => lc.period.id));
 
    // For now, we only handle the "period" lock.
    const callback = (p: Creating<Payment>) => {
      const paymentPeriodId = p.paymentPeriod?.id || p.paymentPeriodId;
      return !paymentPeriodId || !lockedPeriodIds.has(paymentPeriodId);
    };
 
    // Partition is a lodash function that filters using the callback, put truthies first then falsies in second position.
    return partition(payments, callback);
  }
 
  /**
   * List all diffs for a company.
   *
   * @param company
   */
  public listPaymentDiffs(company: Company) {
    return this.paymentDiffRepository.find({
      where: { company: { id: company.id } },
      relations: [
        'paymentPeriod',
        'payment',
        'payment.user',
        'payment.plan',
        'payment.period',
        'payment.rule',
        'payment.rule.commissionVariable',
        'payment.rule.commissionVariable.object',
      ],
    });
  }
}