All files / libs/payout-definition/periods/core/src/lib periods.controller.ts

95.65% Statements 44/46
46.15% Branches 6/13
100% Functions 3/3
95.65% Lines 44/46

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 471x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x  
import { BadRequestException, Controller, Get, Inject, Param, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
 
import { Company } from '@amalia/core/models';
import { isDateValid } from '@amalia/ext/dates';
import { BooleanPipe, EnumPipe, StringPipe } from '@amalia/kernel/api';
import { AmaliaAuthGuard, CurrentUserCompany, PoliciesGuard } from '@amalia/kernel/auth/core';
import { PeriodFrequencyEnum, type PeriodResponseDto } from '@amalia/payout-definition/periods/types';
 
import { formatPeriodResponse } from './dto/period.dto';
import { PeriodsService } from './periods.service';
 
@UseGuards(AmaliaAuthGuard, PoliciesGuard)
@ApiBearerAuth()
@ApiTags('periods')
@Controller('periods')
export class PeriodsController {
  public constructor(
    @Inject(PeriodsService)
    private readonly periodService: PeriodsService,
  ) {}
 
  @Get(':date')
  public async findByDate(
    @CurrentUserCompany() company: Company,
    @Param('date', new StringPipe()) dateRaw: string,
    @Query('frequency', new EnumPipe({ enum: PeriodFrequencyEnum, optional: true })) frequency?: PeriodFrequencyEnum,
    @Query('shouldCreate', new BooleanPipe({ optional: true })) shouldCreate?: boolean,
  ): Promise<PeriodResponseDto | PeriodResponseDto[]> {
    const date = new Date(dateRaw);
 
    if (!isDateValid(date)) {
      throw new BadRequestException('Date is invalid');
    }
 
    const period = await this.periodService.findPeriod(company, date, shouldCreate, frequency);
 
    return formatPeriodResponse(period);
  }
 
  @Get()
  public async find(@CurrentUserCompany() company: Company): Promise<PeriodResponseDto | PeriodResponseDto[]> {
    const periods = await this.periodService.list(company);
    return periods.toSorted((a, b) => b.startDate - a.startDate).map((p) => formatPeriodResponse(p));
  }
}