penisularhr / src / modules / monthly-record / monthly-record.controller.ts
monthly-record.controller.ts
Raw
import {
  Body,
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  Patch,
  Query,
} from '@nestjs/common';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
import moment from 'moment';

import { type PageDto } from '../../common/dto/page.dto';
import { RoleType } from '../../constants';
import { ApiPageOkResponse, Auth, Whitelist } from '../../decorators';
import {
  AccountHasClosedException,
  MonthlyRecordNotFoundException,
} from '../../exceptions';
import { ApiConfigService } from '../../shared/services/api-config.service';
// import { UserEntity } from '../user/user.entity';
import { MonthlyRecordPageOptionsDto } from './dtos/get-monthly-record-page.dto';
import { MonthlyRecordDto } from './dtos/monthly-record.dto';
import { UpdateMonthlyRecordDto } from './dtos/update-monthly-record.dto';
import { MonthlyRecordService } from './monthly-record.service';

@Controller('monthly-records')
@ApiTags('monthly-records')
export class MonthlyRecordController {
  constructor(
    private monthlyRecordService: MonthlyRecordService,
    private configService: ApiConfigService,
  ) {}

  @Get()
  @Whitelist()
  @Auth([RoleType.ADMIN, RoleType.USER])
  @HttpCode(HttpStatus.OK)
  @ApiPageOkResponse({
    type: MonthlyRecordDto,
    description: 'Get monthly records list',
  })
  async getMonthlyRecords(
    @Query() query: MonthlyRecordPageOptionsDto,
  ): Promise<PageDto<MonthlyRecordDto>> {
    return this.monthlyRecordService.findMany(query);
  }

  @Patch(':id')
  @Whitelist()
  @Auth([RoleType.ADMIN, RoleType.USER])
  @HttpCode(HttpStatus.OK)
  @ApiOkResponse()
  async updatePublicHoliday(
    // @AuthUser() user: UserEntity,
    @Param('id') id: Uuid,
    @Body() body: UpdateMonthlyRecordDto,
  ): Promise<MonthlyRecordDto> {
    const toPatchEntity = await this.monthlyRecordService.findOne({
      id,
    });

    if (!toPatchEntity) {
      throw new MonthlyRecordNotFoundException();
    }

    const currentDate = moment.utc();

    const recordDateMonth = moment.utc(toPatchEntity.date).month();
    const currentMonth = moment.utc().month();

    if (
      this.configService.isProduction &&
      currentMonth - recordDateMonth >= 1 &&
      currentDate.date() > 7
    ) {
      throw new AccountHasClosedException();
    }

    const monthlyRecordEntity =
      await this.monthlyRecordService.updateMonthlyRecord(toPatchEntity, body);

    return monthlyRecordEntity.toDto();
  }
}