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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 | 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 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1x 8x 8x 8x 8x 8x 8x 8x 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 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 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 1x 1x 1x 1x 1x 1x 1x 1x 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 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 15x 15x 15x 14x 14x 14x 14x 14x 14x 15x 15x 15x 14x 14x 14x 14x 14x 14x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 4x 4x 32x 32x 18x 18x 1x 1x 35x 35x 35x 2x 35x 35x 35x 7x 35x 35x 35x 26x 35x 35x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 3x 3x 22x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x | import {
ForbiddenException,
forwardRef as CircularDependency,
Inject,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { pick, uniqBy } from 'lodash-es';
import { paginate } from 'nestjs-typeorm-paginate';
import { DataSource, In, IsNull, Repository, type FindOneOptions, type QueryRunner } from 'typeorm';
import { Payment, type Company, type Period, type Plan, type User } from '@amalia/core/models';
import {
PaymentAggregatedItem,
PaymentAggregatedListWithFlag,
PaymentType,
toPaginatedResponse,
type CommissionReportFilters,
type Option,
type PaymentCategory,
type PaymentContract,
} from '@amalia/core/types';
import { PaginatedQuery, PaginatedResponse } from '@amalia/core-http-types';
import { canViewHiddenPlans, defineAbilityFor, filterMyManageesScope } from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { PlanIsHiddenQueryChoices } from '@amalia/payout-definition/plans/types';
import { CompaniesService } from '@amalia/tenants/companies/core';
import { CurrencyRatesService } from '@amalia/tenants/companies/currency-rates/core';
import { HierarchyContextService } from '@amalia/tenants/teams/hierarchy/core';
import { type UserCurrencyChangedEvent } from '@amalia/tenants/users/profile/events';
import { formatPaymentResponse } from './dto/paymentResponse.dto';
import { PaymentsOverwriteService } from './overwrites/payments-overwrite.service';
import { PaymentsFinder } from './paymentFinder/paymentsFinder';
import { PaymentLockService } from './paymentLock/paymentLock.service';
import { PaymentsSaveService } from './save/payments-save.service';
/**
* Service payment.
*/
@Injectable()
export class PaymentsService {
public constructor(
private readonly connection: DataSource,
@InjectRepository(Payment)
private readonly paymentRepository: Repository<Payment>,
@Inject(CurrencyRatesService)
private readonly currencyRatesService: CurrencyRatesService,
private readonly companiesService: CompaniesService,
@Inject(CircularDependency(() => PaymentsOverwriteService))
private readonly paymentsOverwriteService: PaymentsOverwriteService,
@Inject(CircularDependency(() => PaymentsSaveService))
private readonly paymentsSaveService: PaymentsSaveService,
@Inject(CircularDependency(() => PaymentLockService))
private readonly paymentsLockService: PaymentLockService,
private readonly hierarchyContextService: HierarchyContextService,
) {}
/**
* Find payment by id.
* @param company
* @param id
* @param relations
*/
public async findById(company: Company, id: string, relations?: string[]): Promise<Payment | null> {
return this.paymentRepository.findOne({
where: {
id,
company: { id: company.id },
},
relations,
});
}
public async findByMasterPaymentId(company: Company, paymentId: string): Promise<Payment[]> {
return this.paymentRepository.find({
where: {
company: { id: company.id },
masterPaymentId: paymentId,
},
});
}
public async getChallengePayments(company: Company, challengeId: string): Promise<Payment[]> {
return this.paymentRepository.find({
where: {
company: { id: company.id },
challengeId,
},
});
}
public async getMultipleStatementsPayments(
company: Company,
statementIds: string[],
types: PaymentType[],
): Promise<Payment[]> {
return this.paymentRepository.find({
where: {
company: { id: company.id },
statement: { id: In(statementIds) },
type: In(types),
},
});
}
public async getStatementPayments(
company: Company,
statementId: string,
parentQueryRunner: QueryRunner,
relations: string[] = [],
): Promise<Payment[]> {
return parentQueryRunner.manager.getRepository<Payment>(Payment).find({
where: { company: { id: company.id }, statement: { id: statementId } },
relations,
});
}
/**
* Get the list of payments on hold for users.
*
* @param company
* @param userIds
*/
public async findOnHoldPayments(company: Company, userIds: User['id'][]): Promise<Payment[]> {
if (!userIds.length) {
return [];
}
return this.connection.manager.getRepository(Payment).find({
where: {
company: { id: company.id },
userId: In(userIds),
type: PaymentType.LINE_HOLD,
paymentPeriodId: IsNull(),
masterPaymentId: IsNull(),
},
relations: ['splits'],
});
}
public async areStatementUsingHnrOrSplit(companyId: string, periodId: string): Promise<boolean> {
const count = await this.paymentRepository.count({
where: {
periodId,
companyId,
type: In([PaymentType.RULE_SPLIT, PaymentType.LINE_HOLD]),
},
});
// We return true if we find at least one statement containing HnR or split rules
return count > 0;
}
public async computeSumsForCompanyAndPeriod(
companyId: string,
period: Period,
userIds: string[],
planHiddenStatus: PlanIsHiddenQueryChoices,
planIds?: Plan['id'][],
): Promise<PaymentAggregatedListWithFlag> {
// ====== ACHIEVEMENT ======
const qbAchieved = this.connection
.getRepository(Payment)
.createQueryBuilder('achievement_payment')
.select("'achievement'", 'type')
.addSelect('SUM(achievement_payment.value)')
.addSelect('achievement_payment."userId"')
.addSelect('achievement_payment."planId"')
.addSelect('MIN(achievement_payment.currency)', 'currency')
.addSelect('achievement_payment.rate', 'rate')
.leftJoin('period', 'achievement_period', 'achievement_payment."periodId" = achievement_period.id')
.leftJoin('plan', 'achievement_plan', 'achievement_payment."planId" = achievement_plan.id')
.where('achievement_payment."companyId" = :companyId', { companyId })
.andWhere('achievement_period."endDate" = :endDate', { endDate: period.endDate })
.andWhere('achievement_payment."userId" = ANY (:userIds)', { userIds });
if (planIds?.length) {
qbAchieved.andWhere('achievement_payment."planId" IN (:...planIds)', { planIds });
}
if (planHiddenStatus !== PlanIsHiddenQueryChoices.BOTH) {
qbAchieved.andWhere('achievement_plan."isHidden" = :isHidden', {
isHidden: planHiddenStatus === PlanIsHiddenQueryChoices.HIDDEN,
});
}
qbAchieved.addGroupBy('achievement_payment."userId"');
qbAchieved.addGroupBy('achievement_payment."planId"');
qbAchieved.addGroupBy('achievement_payment."rate"');
// ====== HOLD ======
const qbHold = this.connection
.getRepository(Payment)
.createQueryBuilder('hold_payment')
.select("'hold'", 'type')
.addSelect('SUM(hold_payment.value)')
.addSelect('hold_payment."userId"')
.addSelect('hold_payment."planId"')
.addSelect('MIN(hold_payment.currency)', 'currency')
.addSelect('hold_payment.rate', 'rate')
.leftJoin('period', 'hold_period', 'hold_payment."periodId" = hold_period.id')
.leftJoin('period', 'hold_paymentPeriod', 'hold_payment."paymentPeriodId" = hold_paymentPeriod.id')
.leftJoin('plan', 'hold_plan', 'hold_payment."planId" = hold_plan.id')
.where('hold_payment."companyId" = :companyId', { companyId })
.andWhere('hold_payment."userId" = ANY (:userIds)', { userIds })
.andWhere(
// Example: current period = Q4 2024n this return all payments created on Q1,Q2,Q3,Q4 2024 that are not released
// or that are released after Q4 2024
'hold_period."startDate" <= :startDate AND (hold_payment."paymentPeriodId" IS NULL OR "hold_paymentPeriod"."startDate" > :startDate)',
{ startDate: period.startDate },
);
if (planIds?.length) {
qbHold.andWhere('hold_payment."planId" IN (:...planIds)', { planIds });
}
if (planHiddenStatus !== PlanIsHiddenQueryChoices.BOTH) {
qbHold.andWhere('hold_plan."isHidden" = :isHidden', {
isHidden: planHiddenStatus === PlanIsHiddenQueryChoices.HIDDEN,
});
}
qbHold.addGroupBy('hold_payment."userId"');
qbHold.addGroupBy('hold_payment."planId"');
qbHold.addGroupBy('hold_payment.rate');
// ====== PAID ======
const qbPaid = this.connection
.getRepository(Payment)
.createQueryBuilder('paid_payment')
.select("'paid'", 'type')
.addSelect('SUM(paid_payment.value)')
.addSelect('paid_payment."userId"')
.addSelect('paid_payment."planId"')
.addSelect('MIN(paid_payment.currency)', 'currency')
.addSelect('paid_payment.rate', 'rate')
.leftJoin('period', 'paid_period', 'paid_payment."paymentPeriodId" = paid_period.id')
.leftJoin('plan', 'paid_plan', 'paid_payment."planId" = paid_plan.id')
.where('paid_payment."companyId" = :companyId', { companyId })
.andWhere('paid_payment."userId" = ANY (:userIds)', { userIds })
.andWhere('paid_period."endDate" = :endDate', {
endDate: period.endDate,
});
if (planIds?.length) {
qbPaid.andWhere('paid_payment."planId" IN (:...planIds)', { planIds });
}
if (planHiddenStatus !== PlanIsHiddenQueryChoices.BOTH) {
qbPaid.andWhere('paid_plan."isHidden" = :isHidden', {
isHidden: planHiddenStatus === PlanIsHiddenQueryChoices.HIDDEN,
});
}
qbPaid.addGroupBy('paid_payment."userId"');
qbPaid.addGroupBy('paid_payment."planId"');
qbPaid.addGroupBy('paid_payment.rate');
// ====== OUTPUT ======
const [achievementResult, holdResult, paidResult] = await Promise.all([
qbAchieved.execute() as Promise<PaymentAggregatedItem[]>,
qbHold.execute() as Promise<PaymentAggregatedItem[]>,
qbPaid.execute() as Promise<PaymentAggregatedItem[]>,
]);
const results = [...achievementResult, ...holdResult, ...paidResult];
return results.reduce((acc, resultItem) => {
// Check types to avoid Snyk detecting a prototype pollution error.
if (!['achievement', 'hold', 'paid'].includes(resultItem.type)) {
throw new Error('In payment aggregation, type not found');
}
const currentType = resultItem.type;
acc[currentType] = (currentType in acc ? acc[currentType] : []).concat(resultItem);
return acc;
}, {} as PaymentAggregatedListWithFlag);
}
/**
* Compute payment sums given a company and filter data
* @param companyId
* @param currentPeriod
* @param filters
*/
public async computeSumsForCompany(
companyId: string,
currentPeriod: Period,
filters: CommissionReportFilters = {},
): Promise<Partial<PaymentAggregatedListWithFlag>> {
// Compute sum for achievement payment
const achievementPaymentQuery = this.paymentRepository
.createQueryBuilder('achievement_payment')
.select('SUM(achievement_payment.value / achievement_payment.rate)', 'sum')
.addSelect('MIN(achievement_payment.currency)', 'currency')
.addSelect('1', 'rate')
.leftJoin('achievement_payment.plan', 'plan')
.where('achievement_payment."companyId" = :companyId', { companyId });
PaymentsFinder.applyFilterOnQuery(achievementPaymentQuery, filters);
// Compute sum for paid payment
const paidPaymentQuery = this.paymentRepository
.createQueryBuilder('paid_payment')
.leftJoinAndSelect('paid_payment.paymentPeriod', 'paymentPeriod')
.select('SUM(paid_payment.value / paid_payment.rate)', 'sum')
.addSelect('MIN(paid_payment.currency)', 'currency')
.addSelect('1', 'rate')
.leftJoin('paid_payment.plan', 'plan')
.where('paid_payment."companyId" = :companyId', { companyId })
.andWhere('( paid_payment."paymentPeriodId" is NOT NULL AND "paymentPeriod"."startDate" <= :startDate )', {
startDate: currentPeriod.startDate,
});
PaymentsFinder.applyFilterOnQuery(paidPaymentQuery, filters);
const [achievementResult, paidResult] = await Promise.all([
achievementPaymentQuery.getRawOne<PaymentAggregatedItem>(),
paidPaymentQuery.getRawOne<PaymentAggregatedItem>(),
]);
return {
...(achievementResult
? {
achievement: [{ ...achievementResult, type: 'achievement' as PaymentCategory }],
}
: null),
...(paidResult ? { paid: [{ ...paidResult, type: 'paid' as PaymentCategory }] } : null),
};
}
/**
* Paginate payments. We can use filter by plan, user, rules and paymentPeriods.
* @param authenticatedContext
* @param filters
* @param pagination
*/
public async paginate(
authenticatedContext: AuthenticatedContext,
filters: CommissionReportFilters,
pagination: Pick<PaginatedQuery, 'desc' | 'limit' | 'page' | 'search' | 'sort'>,
): Promise<PaginatedResponse<PaymentContract>> {
// Make sure user can see hidden plans if required.
PaymentsService.checkPlanIsHiddenQueryChoice(
authenticatedContext,
filters.planHiddenStatus ?? PlanIsHiddenQueryChoices.LIVE,
);
// Get the list of users we can export based on access rights of current user.
const filteredByTeamUserIds = await this.filterUserIdsByTeam(
authenticatedContext.user.company,
authenticatedContext,
filters.userIds ?? null,
filters.teamIds ?? null,
);
// Refilter (is this really needed? not sure).
const userIds = filterMyManageesScope(authenticatedContext, filteredByTeamUserIds);
const queryBuilder = PaymentsFinder.createQueryBuilder(
this.paymentRepository,
authenticatedContext.user.companyId,
{
...filters,
userIds,
},
pagination.search,
)
.select([
// Select everything from payment
'payment',
'period',
'paymentPeriod',
'adjustment',
'user.firstName',
'user.lastName',
'user.pictureURL',
'user.id',
'plan',
'rule',
'commissionVariable',
// Sort aliases => used to sort result using query parameters (no caps or points allowed)
"concat(user.firstName, ' ', user.lastName) AS payment_username",
'payment.id AS payment_id',
'payment.dealExternalId AS payment_dealexternalid',
'payment.dealName AS payment_dealname',
'period.startDate AS payment_achievementperiod',
'plan.name AS payment_plan',
'plan.isHidden AS payment_planstatus',
'rule.name AS payment_rule',
'commissionVariable.name AS payment_field',
'payment.value AS payment_value',
'paymentPeriod.startDate AS payment_paymentperiod',
])
.orderBy(pagination.sort ?? 'payment_username', pagination.desc ? 'DESC' : 'ASC');
if (pagination.sort !== 'payment_username') {
queryBuilder.addOrderBy('payment_username');
}
queryBuilder.addOrderBy('period.startDate').addOrderBy('payment.id');
const payments = await paginate<Payment>(queryBuilder, {
page: (pagination.page ?? 0) + 1,
limit: pagination.limit ?? 20,
}).then(toPaginatedResponse);
return {
...payments,
items: await this.formatPayments(authenticatedContext.user.companyId, payments.items),
};
}
public async getFacets(
companyId: string,
filters: CommissionReportFilters = {},
search?: string,
): Promise<{ plans: Option[] }> {
const queryBuilder = PaymentsFinder.createQueryBuilder(this.paymentRepository, companyId, filters, search);
queryBuilder.select('DISTINCT plan.id, plan.name');
const plans: Plan[] = uniqBy(await queryBuilder.getRawMany(), 'id');
return {
plans: plans.map(
(plan) =>
({
label: plan.name,
value: plan.id,
}) as Option,
),
};
}
/**
* Format payment response, including deal name.
* @param companyId
* @param payments
* @private
*/
public async formatPayments(companyId: string, payments: Payment[]): Promise<PaymentContract[]> {
const company = { id: companyId } as Company;
// And add overwrites to the response.
const paymentsWithOverwrites = await this.paymentsOverwriteService.populatePaymentsWithOverwrites(
company,
payments,
['creator'],
);
// Compute everything per line and return the result.
return paymentsWithOverwrites.map((p) => {
const variable = p.rule?.commissionVariable;
const variableName = variable?.name;
const definition = p.adjustment?.rowDefinition || variable?.object;
return {
...formatPaymentResponse(p),
variableName,
dealName: PaymentsService.getDealName(p),
dealObjectName: definition?.name,
overwrites: p.overwrites.map((o) => ({
...o,
creator: pick(o.creator, ['id', 'firstName', 'lastName']),
})),
};
});
}
public static getDealName(payment: Payment): string {
switch (true) {
// If we matched a deal, return its name.
case !!payment.dealName:
return payment.dealName;
// If we didn't have a name column (but we have a deal), return its external id.
case !!payment.dealExternalId:
return payment.dealExternalId;
// Here it's for payments that are not related to a deal.
default:
return '';
}
}
public async changeUserPaymentsCurrency(event: UserCurrencyChangedEvent) {
const { companyId, userId, oldCurrency, newCurrency } = event;
const company = await this.companiesService.findById(companyId);
// Get all unreleased payments that are in the old currency and concerning this user
const paymentsToUpdate = await this.paymentRepository.find({
where: {
company: { id: company.id },
user: { id: userId },
currency: oldCurrency,
paymentPeriod: IsNull(),
},
relations: ['period'],
});
// Cache that store the rate of the new currency at a specific time. [timestamp] = rate
const newRates: Record<number, number> = {};
// new value = (old value / old rate) * new rate
for (const p of paymentsToUpdate) {
// If we don't already have a rate, fetch it at the time the payment was created
if (!newRates[p.period.startDate]) {
newRates[p.period.startDate] = await this.currencyRatesService.findCurrencyRate(
company,
newCurrency,
p.period.startDate,
);
}
// Compute the new value
const newPaymentValue = (p.value / p.rate) * newRates[p.period.startDate];
const newTotalValue = (p.totalValue! / p.rate) * newRates[p.period.startDate];
// This part update the payment. Normally this shouldn't have an impact on locked
// payments because we're keeping the same value, adjusted with the rate of the payment
// itself.
await this.paymentRepository.update(p.id, {
currency: newCurrency,
rate: newRates[p.period.startDate],
value: newPaymentValue,
totalValue: newTotalValue,
});
}
}
public async isPaymentLocked(company: Company, findOneQuery: FindOneOptions<Payment>['where']) {
const [paymentLocks, payment] = await Promise.all([
this.paymentsLockService.getPaymentLocks(company),
this.paymentRepository.findOne({
where: {
...(findOneQuery as object),
company: { id: company.id },
masterPaymentId: IsNull(),
},
relations: ['splits'],
}),
]);
if (!payment) {
throw new NotFoundException('Payment not found for the adjustment');
}
const [, lockedPayments] = PaymentLockService.partitionLockedPayments(paymentLocks, [
payment,
...(payment.splits ?? []),
]);
return lockedPayments.length > 0;
}
public processPayments(...args: Parameters<PaymentsSaveService['processPayments']>) {
return this.paymentsSaveService.processPayments(...args);
}
public listPaymentDiffs(...args: Parameters<PaymentLockService['listPaymentDiffs']>) {
return this.paymentsLockService.listPaymentDiffs(...args);
}
public getPaymentLocks(...args: Parameters<PaymentLockService['getPaymentLocks']>) {
return this.paymentsLockService.getPaymentLocks(...args);
}
public async deletePayment(
parentQueryRunner: QueryRunner,
{
companyId,
planId,
statementId,
periodId,
}: { companyId: string; planId: string; statementId: string; periodId: string },
) {
return parentQueryRunner.manager.getRepository<Payment>(Payment).delete({
companyId,
statementId,
planId,
periodId,
});
}
public static checkPlanIsHiddenQueryChoice(
authenticatedContext: AuthenticatedContext,
value: PlanIsHiddenQueryChoices,
) {
if (value !== PlanIsHiddenQueryChoices.LIVE && !canViewHiddenPlans(defineAbilityFor(authenticatedContext))) {
throw new ForbiddenException('This user cannot query hidden plans.');
}
}
public async filterUserIdsByTeam(
company: Company,
authenticatedContext: AuthenticatedContext,
userIds: string[] | null,
teamIds: string[] | null,
period: Period | null = null,
): Promise<string[]> {
return (
await this.hierarchyContextService.getSubordinates(
company,
authenticatedContext,
period ? period.endDate : new Date(),
{
teamIds,
userIds,
},
period,
)
).map((u) => u.id);
}
}
|