Passed
Pull Request — master (#78)
by Mathieu
01:39
created

server/src/Application/Billing/Command/Quote/CreateQuoteCommandHandler.ts   A

Complexity

Total Complexity 4
Complexity/F 4

Size

Lines of Code 49
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 42
mnd 3
bc 3
fnc 1
dl 0
loc 49
rs 10
bpm 3
cpm 4
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A CreateQuoteCommandHandler.execute 0 23 4
1
import {CommandHandler} from '@nestjs/cqrs';
2
import {Inject} from '@nestjs/common';
3
import {CreateQuoteCommand} from './CreateQuoteCommand';
4
import {IQuoteRepository} from 'src/Domain/Billing/Repository/IQuoteRepository';
5
import {Quote} from 'src/Domain/Billing/Quote.entity';
6
import {IProjectRepository} from 'src/Domain/Project/Repository/IProjectRepository';
7
import {ICustomerRepository} from 'src/Domain/Customer/Repository/ICustomerRepository';
8
import {Customer} from 'src/Domain/Customer/Customer.entity';
9
import {CustomerNotFoundException} from 'src/Domain/Customer/Exception/CustomerNotFoundException';
10
import {QuoteIdGenerator} from 'src/Domain/Billing/Quote/QuoteIdGenerator';
11
import {InvalidProjectException} from 'src/Domain/Billing/Exception/InvalidProjectException';
12
13
@CommandHandler(CreateQuoteCommand)
14
export class CreateQuoteCommandHandler {
15
  constructor(
16
    @Inject('IQuoteRepository')
17
    private readonly quoteRepository: IQuoteRepository,
18
    @Inject('ICustomerRepository')
19
    private readonly customerRepository: ICustomerRepository,
20
    @Inject('IProjectRepository')
21
    private readonly projectRepository: IProjectRepository,
22
    private readonly quoteIdGenerator: QuoteIdGenerator
23
  ) {}
24
25
  public async execute(command: CreateQuoteCommand): Promise<string> {
26
    const {customerId, status, user, projectId} = command;
27
    let project = null;
28
29
    const customer = await this.customerRepository.findOneById(customerId);
30
    if (!(customer instanceof Customer)) {
31
      throw new CustomerNotFoundException();
32
    }
33
34
    if (projectId) {
35
      project = await this.projectRepository.findOneById(projectId);
36
      if (!project || project.getCustomer().getId() !== customer.getId()) {
37
        throw new InvalidProjectException();
38
      }
39
    }
40
41
    const quoteId = await this.quoteIdGenerator.generate();
42
    const quote = await this.quoteRepository.save(
43
      new Quote(quoteId, status, user, customer, project)
44
    );
45
46
    return quote.getId();
47
  }
48
}
49