Passed
Pull Request — master (#220)
by
unknown
01:47
created

server/src/Infrastructure/HumanResource/PayrollElements/Action/DownloadPayrollElementsAction.ts   A

Complexity

Total Complexity 1
Complexity/F 1

Size

Lines of Code 67
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 1
eloc 61
mnd 0
bc 0
fnc 1
dl 0
loc 67
bpm 0
cpm 1
noi 0
c 0
b 0
f 0
rs 10

1 Function

Rating   Name   Duplication   Size   Complexity  
A DownloadPayrollElementsAction.index 0 32 1
1
import { Get, Controller, Inject, UseGuards, Res } from '@nestjs/common';
2
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
3
import { IQueryBus } from '@nestjs/cqrs';
4
import { AuthGuard } from '@nestjs/passport';
5
import { PassThrough } from 'stream';
6
import { Response } from 'express';
7
import { PDFService } from '@t00nday/nestjs-pdf';
8
import { UserRole } from 'src/Domain/HumanResource/User/User.entity';
9
import { RolesGuard } from 'src/Infrastructure/HumanResource/User/Security/RolesGuard';
10
import { Roles } from 'src/Infrastructure/HumanResource/User/Decorator/Roles';
11
import { IDateUtils } from 'src/Application/IDateUtils';
12
import { GetPayrollElementsQuery } from 'src/Application/HumanResource/PayrollElements/Query/GetPayrollElementsQuery';
13
14
const formatMoney = (amount: number): string => {
15
  return new Intl.NumberFormat('fr-FR', {
16
    style: 'currency',
17
    currency: 'EUR'
18
  }).format(amount);
19
};
20
21
@Controller('payroll_elements')
22
@ApiTags('Human Resource')
23
@ApiBearerAuth()
24
@UseGuards(AuthGuard('bearer'), RolesGuard)
25
export class DownloadPayrollElementsAction {
26
  constructor(
27
    @Inject('IQueryBus')
28
    private readonly queryBus: IQueryBus,
29
    private readonly pdfService: PDFService,
30
    @Inject('IDateUtils')
31
    private readonly dateUtils: IDateUtils
32
  ) {}
33
34
  @Get()
35
  @Roles(UserRole.COOPERATOR, UserRole.ACCOUNTANT)
36
  @ApiOperation({ summary: 'Download payroll elements' })
37
  public async index(@Res() res: Response) {
38
    const elements = await this.queryBus.execute(new GetPayrollElementsQuery());
39
40
    console.log(elements);
41
42
    const now = new Date();
43
44
    const locals = {
45
      elements,
46
      now,
47
      formatMoney,
48
      dateUtils: this.dateUtils
49
    };
50
51
    const buffer = await this.pdfService
52
      .toBuffer('PayrollElements', { locals })
53
      .toPromise();
54
55
    const yearMonth = this.dateUtils.format(now, 'y-MM');
56
    const fileName = `${yearMonth}-elements-paie-fairness.pdf`;
57
58
    res.set('Content-Disposition', `attachment; filename=${fileName}`);
59
    res.set('Content-Type', 'application/pdf');
60
    res.set('Content-Length', buffer.length.toString());
61
62
    const stream = new PassThrough();
63
    stream.end(buffer);
64
    stream.pipe(res);
65
  }
66
}
67