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

94.79% Statements 255/269
48.97% Branches 24/49
85.71% Functions 6/7
94.79% Lines 255/269

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 2701x 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 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 3x 3x 3x 4x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 4x 4x 4x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x     5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x                     1x  
import {
  Body,
  Controller,
  Delete,
  ForbiddenException,
  Get,
  Inject,
  Logger,
  NotFoundException,
  Param,
  Patch,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
 
import { Company } from '@amalia/core/models';
import { PaymentsOfPeriod, type Option, type PaymentContract } from '@amalia/core/types';
import { type PaginatedQuery, type PaginatedResponse } from '@amalia/core-http-types';
import { ClearOverwriteDto } from '@amalia/data-correction/overwrites/core';
import { BooleanPipe, EnumPipe, Pagination, StringPipe, UuidPipe } from '@amalia/kernel/api';
import {
  AmaliaAuthGuard,
  CheckPolicies,
  CurrentAuthenticatedContext,
  CurrentUserCompany,
  PoliciesGuard,
} from '@amalia/kernel/auth/core';
import {
  canDeletePayments,
  canOverwritePayments,
  canViewDashboardPayments,
  canViewPayments,
  canViewStatements,
  defineAbilityFor,
  filterMyManageesScope,
} from '@amalia/kernel/auth/shared';
import { type AuthenticatedContext } from '@amalia/kernel/auth/types';
import { PeriodsService } from '@amalia/payout-definition/periods/core';
import { PlanIsHiddenQueryChoices } from '@amalia/payout-definition/plans/types';
 
import { PatchPaymentDto } from './dto/patchPayment.dto';
import { PaymentsOverwriteService } from './overwrites/payments-overwrite.service';
import { PaymentsService } from './payments.service';
import { DeletePaymentUseCase } from './use-cases/delete-payment/delete-payment.use-case';
 
@UseGuards(AmaliaAuthGuard, PoliciesGuard)
@ApiBearerAuth()
@ApiTags('payments')
@Controller('payments')
export class PaymentsController {
  private readonly logger = new Logger(PaymentsController.name);
 
  public constructor(
    @Inject(PaymentsService)
    private readonly paymentsService: PaymentsService,
    private readonly periodsService: PeriodsService,
    private readonly paymentsOverwriteService: PaymentsOverwriteService,
    private readonly deletePaymentUseCase: DeletePaymentUseCase,
  ) {}
 
  @Get('by-period/:currentPeriodId')
  @CheckPolicies((ability) => canViewStatements(ability) || canViewPayments(ability))
  public async computeAmountsForCompanyAndPeriod(
    @CurrentUserCompany() company: Company,
    @CurrentAuthenticatedContext() authenticatedContext: AuthenticatedContext,
    @Param('currentPeriodId', new UuidPipe()) currentPeriodId: string,
    @Query('planIds', new UuidPipe({ optional: true, multiple: true })) planIds?: string[],
    @Query('ruleIds', new UuidPipe({ optional: true, multiple: true })) ruleIds?: string[],
    // Do not use UuidPipe as period can be keyword such as LAST_3_MONTH
    @Query('periodIds', new StringPipe({ multiple: true, optional: true })) periodIds?: string[] | null,
    // Do not use UuidPipe as period can be keyword such as LAST_3_MONTH
    @Query('paymentPeriodIds', new StringPipe({ optional: true, multiple: true })) paymentPeriodIds?: string[],
    @Query('teamIds', new UuidPipe({ optional: true, multiple: true })) teamIds?: string[],
    @Query('userIds', new UuidPipe({ optional: true, multiple: true })) filterUserIds?: string[],
    @Query('type', new StringPipe({ optional: true })) type?: 'commissionReport',
    @Query('planHiddenStatus', new EnumPipe({ optional: true, enum: PlanIsHiddenQueryChoices }))
    planHiddenStatus: PlanIsHiddenQueryChoices = PlanIsHiddenQueryChoices.LIVE,
  ): Promise<PaymentsOfPeriod> {
    PaymentsService.checkPlanIsHiddenQueryChoice(authenticatedContext, planHiddenStatus);
 
    const periodIdsToPass = await this.periodsService.interpretPeriodParamsArray(company, periodIds);
    const paymentPeriodIdsToPass = await this.periodsService.interpretPeriodParamsArray(company, paymentPeriodIds);
 
    const currentPeriod = await this.periodsService.findOne(company, currentPeriodId);
 
    const userIds = await this.paymentsService.filterUserIdsByTeam(
      company,
      authenticatedContext,
      filterUserIds || null,
      teamIds || null,
      currentPeriod,
    );
 
    const [amountsPerCategory, containsHoldRules] = await Promise.all([
      type === 'commissionReport'
        ? this.paymentsService.computeSumsForCompany(company.id, currentPeriod, {
            userIds,
            planIds,
            ruleIds,
            periodIds: periodIdsToPass,
            paymentPeriodIds: paymentPeriodIdsToPass,
            planHiddenStatus,
          })
        : this.paymentsService.computeSumsForCompanyAndPeriod(
            company.id,
            currentPeriod,
            userIds,
            planHiddenStatus,
            planIds,
          ),
      this.paymentsService.areStatementUsingHnrOrSplit(company.id, currentPeriodId),
    ]);
 
    return {
      ...amountsPerCategory,
      containsHoldRules,
    };
  }
 
  @Get('paginate')
  @CheckPolicies((ability) => canViewPayments(ability) || canViewDashboardPayments(ability))
  public async findAll(
    @CurrentUserCompany() company: Company,
    @CurrentAuthenticatedContext() authenticatedContext: AuthenticatedContext,
    @Pagination() pagination: PaginatedQuery,
 
    @Query('userIds', new UuidPipe({ optional: true, multiple: true })) userIds: string[] | null = null,
    @Query('planIds', new UuidPipe({ optional: true, multiple: true })) planIds: string[] | null = null,
    @Query('teamIds', new UuidPipe({ optional: true, multiple: true })) teamIds: string[] | null = null,
    @Query('ruleIds', new UuidPipe({ optional: true, multiple: true })) ruleIds: string[] | null = null,
    // Do not use UuidPipe as period can be keyword such as LAST_3_MONTH
    @Query('periodIds', new StringPipe({ multiple: true, optional: true })) periodIds: string[] | null = null,
    // Do not use UuidPipe as period can be keyword such as LAST_3_MONTH
    @Query('paymentPeriodIds', new StringPipe({ optional: true, multiple: true }))
    paymentPeriodIds: string[] | null = null,
    @Query('planHiddenStatus', new EnumPipe({ optional: true, enum: PlanIsHiddenQueryChoices }))
    planHiddenStatus: PlanIsHiddenQueryChoices = PlanIsHiddenQueryChoices.LIVE,
    @Query('onlyPaymentsInError', new BooleanPipe({ optional: true })) onlyPaymentsInError?: boolean,
  ): Promise<PaginatedResponse<PaymentContract>> {
    const periodIdsToPass = await this.periodsService.interpretPeriodParamsArray(company, periodIds);
    const paymentPeriodIdsToPass = await this.periodsService.interpretPeriodParamsArray(company, paymentPeriodIds);
 
    return this.paymentsService.paginate(
      authenticatedContext,
      {
        teamIds: teamIds || undefined,
        userIds: userIds || undefined,
        planIds: planIds || undefined,
        ruleIds: ruleIds || undefined,
        periodIds: periodIdsToPass,
        paymentPeriodIds: paymentPeriodIdsToPass,
        planHiddenStatus,
        onlyPaymentsInError,
      },
      pagination,
    );
  }
 
  @Get('facets')
  @CheckPolicies((ability) => canViewPayments(ability) || canViewDashboardPayments(ability))
  public async getFilters(
    @CurrentUserCompany() company: Company,
    @CurrentAuthenticatedContext() authenticatedContext: AuthenticatedContext,
    @Query('userIds', new UuidPipe({ optional: true, multiple: true })) userIds: string[] | null,
    @Query('planIds', new UuidPipe({ optional: true, multiple: true })) planIds: string[] | null,
    @Query('teamIds', new UuidPipe({ optional: true, multiple: true })) teamIds: string[] | null,
    @Query('ruleIds', new UuidPipe({ optional: true, multiple: true })) ruleIds: string[] | null,
    // Do not use UuidPipe as period can be keywork such as LAST_3_MONTH
    @Query('periodIds', new StringPipe({ multiple: true, optional: true })) periodIds: string[] | null,
    // Do not use UuidPipe as period can be keywork such as LAST_3_MONTH
    @Query('paymentPeriodIds', new StringPipe({ optional: true, multiple: true })) paymentPeriodIds: string[] | null,
    @Query('q', new StringPipe({ optional: true })) search: string,
    @Query('planHiddenStatus', new EnumPipe({ optional: true, enum: PlanIsHiddenQueryChoices }))
    planHiddenStatus: PlanIsHiddenQueryChoices = PlanIsHiddenQueryChoices.LIVE,
  ): Promise<{ plans: Option[] }> {
    PaymentsService.checkPlanIsHiddenQueryChoice(authenticatedContext, planHiddenStatus);
 
    const filteredByTeamUserIds = await this.paymentsService.filterUserIdsByTeam(
      company,
      authenticatedContext,
      userIds,
      teamIds,
    );
 
    const managees = filterMyManageesScope(authenticatedContext, filteredByTeamUserIds);
 
    const periodIdsToPass = await this.periodsService.interpretPeriodParamsArray(company, periodIds);
    const paymentPeriodIdsToPass = await this.periodsService.interpretPeriodParamsArray(company, paymentPeriodIds);
 
    return this.paymentsService.getFacets(
      company.id,
      {
        userIds: managees,
        planIds: planIds || undefined,
        ruleIds: ruleIds || undefined,
        periodIds: periodIdsToPass,
        paymentPeriodIds: paymentPeriodIdsToPass,
        planHiddenStatus,
      },
      search,
    );
  }
 
  @Patch(':id')
  @CheckPolicies((ability) => canOverwritePayments(ability))
  public async patchPayment(
    @Param('id', new UuidPipe()) id: string,
    @Body() patchPaymentDto: PatchPaymentDto,
    @CurrentAuthenticatedContext() authenticatedContext: AuthenticatedContext,
    @CurrentUserCompany() company: Company,
  ): Promise<PaymentContract> {
    this.logger.log(`Patch payment ${id} with period ${patchPaymentDto.paymentPeriodId}`);
 
    const ability = defineAbilityFor(authenticatedContext);
 
    if (!canOverwritePayments(ability)) {
      throw new ForbiddenException("You don't have access to this data");
    }
 
    const payment = await this.paymentsService.findById(company, id);
    if (!payment) {
      throw new NotFoundException('Payment not found');
    }
 
    return this.paymentsOverwriteService.update(company, payment, authenticatedContext, {
      paymentPeriodId: patchPaymentDto.paymentPeriodId,
    });
  }
 
  @Post(':id/clear')
  @CheckPolicies((ability) => canOverwritePayments(ability))
  public async clearPayment(
    @Param('id', new UuidPipe()) id: string,
    @Body() clearOverwriteDto: ClearOverwriteDto,
    @CurrentAuthenticatedContext() authenticatedContext: AuthenticatedContext,
    @CurrentUserCompany() company: Company,
  ): Promise<PaymentContract> {
    this.logger.log(`Clear payment ${id}`);
 
    const payment = await this.paymentsService.findById(company, id);
    if (!payment) {
      throw new NotFoundException('Payment not found');
    }
 
    return this.paymentsOverwriteService.clearPaymentOverwrite(
      company,
      authenticatedContext,
      payment,
      clearOverwriteDto.overwriteId,
      payment.statementId,
    );
  }
 
  @Delete(':paymentId')
  @CheckPolicies((ability) => canDeletePayments(ability))
  public async deletePayment(
    @Param('paymentId', new UuidPipe()) paymentId: PaymentContract['id'],
    @CurrentAuthenticatedContext() authenticatedContext: AuthenticatedContext,
  ): Promise<void> {
    this.logger.log(`Delete payment ${paymentId}`);

    await this.deletePaymentUseCase.execute({
      authenticatedContext,
      paymentId,
    });
  }
}