|
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
|
|
|
|