1
|
|
|
import {CommandHandler} from '@nestjs/cqrs'; |
2
|
|
|
import {Inject} from '@nestjs/common'; |
3
|
|
|
import {CreateUserCommand} from './CreateUserCommand'; |
4
|
|
|
import {IUserRepository} from 'src/Domain/HumanResource/User/Repository/IUserRepository'; |
5
|
|
|
import {IPasswordEncoder} from 'src/Application/IPasswordEncoder'; |
6
|
|
|
import {User, UserRole} from 'src/Domain/HumanResource/User/User.entity'; |
7
|
|
|
import {IsEmailAlreadyExist} from 'src/Domain/HumanResource/User/Specification/IsEmailAlreadyExist'; |
8
|
|
|
import {EmailAlreadyExistException} from 'src/Domain/HumanResource/User/Exception/EmailAlreadyExistException'; |
9
|
|
|
import {IDateUtils} from 'src/Application/IDateUtils'; |
10
|
|
|
import {EntryDateMissingException} from 'src/Domain/HumanResource/User/Exception/EntryDateMissingException'; |
11
|
|
|
|
12
|
|
|
@CommandHandler(CreateUserCommand) |
13
|
|
|
export class CreateUserCommandHandler { |
14
|
|
|
constructor( |
15
|
|
|
@Inject('IUserRepository') |
16
|
|
|
private readonly userRepository: IUserRepository, |
17
|
|
|
@Inject('IPasswordEncoder') |
18
|
|
|
private readonly passwordEncoder: IPasswordEncoder, |
19
|
|
|
@Inject('IDateUtils') |
20
|
|
|
private readonly dateUtils: IDateUtils, |
21
|
|
|
private readonly isEmailAlreadyExist: IsEmailAlreadyExist |
22
|
|
|
) {} |
23
|
|
|
|
24
|
|
|
public async execute(command: CreateUserCommand): Promise<string> { |
25
|
|
|
const {firstName, lastName, password, entryDate, role} = command; |
26
|
|
|
const email = command.email.toLowerCase(); |
27
|
|
|
|
28
|
|
|
if (true === (await this.isEmailAlreadyExist.isSatisfiedBy(email))) { |
29
|
|
|
throw new EmailAlreadyExistException(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (role !== UserRole.ACCOUNTANT && !entryDate) { |
33
|
|
|
throw new EntryDateMissingException(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
const hashPassword = await this.passwordEncoder.hash(password); |
37
|
|
|
const apiToken = await this.passwordEncoder.hash(email + password); |
38
|
|
|
const user = await this.userRepository.save( |
39
|
|
|
new User( |
40
|
|
|
firstName, |
41
|
|
|
lastName, |
42
|
|
|
email, |
43
|
|
|
apiToken, |
44
|
|
|
hashPassword, |
45
|
|
|
role, |
46
|
|
|
entryDate ? this.dateUtils.format(entryDate, 'y-MM-dd') : null |
47
|
|
|
) |
48
|
|
|
); |
49
|
|
|
|
50
|
|
|
return user.getId(); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|