|
1
|
|
|
import { Inject } from '@nestjs/common'; |
|
2
|
|
|
import { CommandHandler } from '@nestjs/cqrs'; |
|
3
|
|
|
import { SchoolNotFoundException } from 'src/Domain/School/Exception/SchoolNotFoundException'; |
|
4
|
|
|
import { ISchoolRepository } from 'src/Domain/School/Repository/ISchoolRepository'; |
|
5
|
|
|
import { IDiscountRepository } from 'src/Domain/School/Repository/IDiscountRepository'; |
|
6
|
|
|
import { Discount } from 'src/Domain/School/Discount.entity'; |
|
7
|
|
|
import { CreateDiscountCommand } from './CreateDiscountCommand'; |
|
8
|
|
|
import { IsDiscountAlreadyExist } from 'src/Domain/School/Specification/Discount/IsDiscountAlreadyExist'; |
|
9
|
|
|
import { DiscountAlreadyExistException } from 'src/Domain/School/Exception/DiscountAlreadyExistException'; |
|
10
|
|
|
|
|
11
|
|
|
@CommandHandler(CreateDiscountCommand) |
|
12
|
|
|
export class CreateDiscountCommandHandler { |
|
13
|
|
|
constructor( |
|
14
|
|
|
@Inject('ISchoolRepository') |
|
15
|
|
|
private readonly schoolRepository: ISchoolRepository, |
|
16
|
|
|
@Inject('IDiscountRepository') |
|
17
|
|
|
private readonly discountRepository: IDiscountRepository, |
|
18
|
|
|
private readonly isDiscountAlreadyExist: IsDiscountAlreadyExist, |
|
19
|
|
|
) {} |
|
20
|
|
|
|
|
21
|
|
|
public async execute(command: CreateDiscountCommand): Promise<string> { |
|
22
|
|
|
const { amount, value, type, schoolId } = command; |
|
23
|
|
|
|
|
24
|
|
|
const school = await this.schoolRepository.findOneById(schoolId); |
|
25
|
|
|
if (!school) { |
|
26
|
|
|
throw new SchoolNotFoundException(); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
const roundedAmount = Math.round(amount * 100); |
|
30
|
|
|
const roundedValue = Math.round(value * 100); |
|
31
|
|
|
|
|
32
|
|
|
if (true === (await this.isDiscountAlreadyExist.isSatisfiedBy(roundedAmount, school))) { |
|
33
|
|
|
throw new DiscountAlreadyExistException(); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
const savedDiscount = await this.discountRepository.save( |
|
37
|
|
|
new Discount( |
|
38
|
|
|
type, |
|
39
|
|
|
roundedAmount, |
|
40
|
|
|
roundedValue, |
|
41
|
|
|
school |
|
42
|
|
|
) |
|
43
|
|
|
); |
|
44
|
|
|
|
|
45
|
|
|
return savedDiscount.getId(); |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|