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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 1x 1x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 3x 3x 4x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 7x 8x 7x 7x 7x 7x 7x 7x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 9x 9x 5x 5x 8x 8x 5x 5x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 2x 7x 1x | import { HttpException, HttpStatus, Inject, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { omit, pick, sum } from 'lodash-es';
import { DataSource, type Repository } from 'typeorm';
import { Creating, Payment, type Company } from '@amalia/core/models';
import { toError } from '@amalia/ext/typescript';
import { type PaymentSplitConfigurationDto, type PaymentSplitPartDto } from '../dto/paymentSplit.dto';
import { PaymentLockService } from '../paymentLock/paymentLock.service';
import { PaymentsService } from '../payments.service';
@Injectable()
export class PaymentsSplitService {
private readonly logger = new Logger(PaymentsSplitService.name);
public constructor(
private readonly connection: DataSource,
@Inject(PaymentsService)
private readonly paymentsService: PaymentsService,
@Inject(PaymentLockService)
private readonly paymentLockService: PaymentLockService,
) {}
public async getAllDetailsForMasterPaymentId(company: Company, masterPaymentId: string) {
const [masterPayment, childrenPayments] = await Promise.all([
this.paymentsService.findById(company, masterPaymentId),
this.paymentsService.findByMasterPaymentId(company, masterPaymentId),
]);
if (!masterPayment) {
throw new NotFoundException(`No payment found for details: ${masterPaymentId}`);
}
return this.paymentsService.formatPayments(company.id, [masterPayment, ...childrenPayments]);
}
public async removeSplitForMasterPaymentId(company: Company, masterPaymentId: string) {
const masterPayment = await this.paymentsService.findById(company, masterPaymentId);
if (!masterPayment) {
throw new NotFoundException('No payment found for delete split');
}
// Verify that payment periods of the split we're deleting are not locked.
await this.checkSplitIsRemovable(company, masterPaymentId);
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const paymentRepo = queryRunner.manager.getRepository<Payment>(Payment);
// Set value of master to be the total value, as original
masterPayment.value = masterPayment.totalValue!;
await paymentRepo.save(masterPayment);
// Delete all children payments
await paymentRepo.delete({
company: { id: company.id },
masterPaymentId,
});
await queryRunner.commitTransaction();
} catch (err) {
const error = toError(err);
this.logger.error({ message: 'Error on removing payment split', error, company: pick(company, ['id', 'name']) });
await queryRunner.rollbackTransaction();
throw new HttpException('Removing payment split failed, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
await queryRunner.release();
}
}
public async addSplitForMasterPaymentId(
company: Company,
masterPaymentId: string,
splitConfiguration: PaymentSplitConfigurationDto,
) {
const masterPayment = await this.paymentsService.findById(company, masterPaymentId, [
'period',
'plan',
'user',
'statement',
'rule',
'adjustment',
'challenge',
]);
if (!masterPayment) {
throw new NotFoundException('No payment found for add split');
}
if (masterPayment.totalValue && masterPayment.value !== masterPayment.totalValue) {
throw new NotFoundException("Can't split an already split payment");
}
// Verifying total amount to not create money from nothing
const sumOfSplitParts = sum(splitConfiguration.splitParts.map((part) => +part.value));
// Verify that payment periods are not locked.
await this.checkSplitIsCreatable(company, masterPayment, splitConfiguration);
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const paymentRepo = queryRunner.manager.getRepository<Payment>(Payment);
// Update master with its total value, and with its new value
masterPayment.totalValue = masterPayment.value;
masterPayment.value -= sumOfSplitParts;
await paymentRepo.save(masterPayment);
// Create all children payments
for (const splitConfig of splitConfiguration.splitParts) {
await this.savePaymentSplit(paymentRepo, masterPayment, splitConfig);
}
await queryRunner.commitTransaction();
} catch (err) {
const error = toError(err);
this.logger.error({ message: 'Error on adding payment split', error, company: pick(company, ['id', 'name']) });
await queryRunner.rollbackTransaction();
throw new HttpException('Adding payment split failed, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
} finally {
await queryRunner.release();
}
}
/**
* Save a payment split based on master payment and split config.
* @param paymentRepository
* @param masterPayment
* @param paymentSplitConfig
* @private
*/
private async savePaymentSplit(
paymentRepository: Repository<Payment>,
masterPayment: Payment,
paymentSplitConfig: PaymentSplitPartDto,
) {
try {
const paymentToCreate: Creating<Payment> = {
...omit(masterPayment, ['id', 'createdAt', 'updatedAt']),
value: paymentSplitConfig.value,
paymentPeriodId: paymentSplitConfig.paymentPeriodId,
masterPayment,
totalValue: masterPayment.totalValue,
};
return await paymentRepository.save(paymentToCreate);
} catch {
throw new HttpException('Unable to save a split payment', HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Throws an error if the split contains a locked period.
*
* @param company
* @param masterPaymentId
* @private
*/
private async checkSplitIsRemovable(company: Company, masterPaymentId: string) {
const [paymentsOnTheSplit, paymentLocks] = await Promise.all([
this.paymentsService.findByMasterPaymentId(company, masterPaymentId),
this.paymentLockService.getPaymentLocks(company),
]);
const splitAppliedOnPeriodIds = new Set(paymentsOnTheSplit.map((p) => p.paymentPeriodId));
const lockedPeriodsContainedInSplitConfig = paymentLocks.filter((lc) => splitAppliedOnPeriodIds.has(lc.period.id));
if (lockedPeriodsContainedInSplitConfig.length > 0) {
throw new HttpException(
`Cannot delete split because of locked period(s): ${lockedPeriodsContainedInSplitConfig
.map((lc) => lc.period.name)
.join(', ')}`,
423,
);
}
}
/**
* Throws an error if the split we're about to create contains a locked period.
*
* @param company
* @param masterPayment
* @param splitConfiguration
* @private
*/
private async checkSplitIsCreatable(
company: Company,
masterPayment: Payment,
splitConfiguration: PaymentSplitConfigurationDto,
) {
const paymentLocks = await this.paymentLockService.getPaymentLocks(company);
const splitDestinationPeriodIds = new Set(
([] as string[])
// Check that the payment period of the split is not on a locked period.
.concat(masterPayment.paymentPeriodId ? [masterPayment.paymentPeriodId] : [])
// Check that no splits are targeted on a locked period.
.concat(splitConfiguration.splitParts.map((sp) => sp.paymentPeriodId)),
);
const lockedPeriodsContainedInSplitConfig = paymentLocks.filter((lc) =>
splitDestinationPeriodIds.has(lc.period.id),
);
if (lockedPeriodsContainedInSplitConfig.length > 0) {
throw new HttpException(
`Cannot apply split because of locked period(s): ${lockedPeriodsContainedInSplitConfig
.map((lc) => lc.period.name)
.join(', ')}`,
423,
);
}
}
}
|