保誠-保戶業務員媒合平台
Jack
2021-11-26 bdcaac32492b5e6223fef4304f4d86403e877022
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.pollex.pam.service;
 
import java.util.Optional;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import com.pollex.pam.domain.Customer;
import com.pollex.pam.domain.OtpTmp;
import com.pollex.pam.enums.OtpLoginTypeEnum;
import com.pollex.pam.enums.OtpTmpStatusEnum;
import com.pollex.pam.repository.CustomerRepository;
import com.pollex.pam.service.dto.CustomerRegisterDTO;
import com.pollex.pam.service.mapper.CustomerDTOMapper;
 
@Service
@Transactional
public class CustomerService {
    
    @Autowired
    CustomerRepository customerRepository;
    
    @Autowired
    CustomerDTOMapper customerDTOMapper;
    
    @Autowired
    CustomerAuthService customerAuthService;
    
    @Autowired
    OtpTmpService otpTmpService;
    
    public Customer save(Customer customer) {
        return customerRepository.save(customer);
    }
    
    public Customer registerCustomer(CustomerRegisterDTO registDTO) {
        boolean isCustomerExist = checkCustomerExist(registDTO);
        if(isCustomerExist) {
            throw new UsernameAlreadyUsedException();
            
        }else {
            String account = getCustomerAccount(registDTO);
            
            OtpTmp otpTmp = otpTmpService.findByAccountAndIndexKey(account, registDTO.getIndexKey());
            if(otpTmp.getStatus() == OtpTmpStatusEnum.VERRIFIED) {
                Customer customer = customerDTOMapper.toCustomer(registDTO);
                save(customer);
                return customer;
            }else {
                throw new IllegalArgumentException("Invalid indexKey state error. IndexKey: "
                        + registDTO.getIndexKey()
                        + " => status: " + otpTmp.getStatus());
            }
        }
        
    }
 
    private String getCustomerAccount(CustomerRegisterDTO registDTO) {
        return registDTO.getContactType() == OtpLoginTypeEnum.EMAIL?registDTO.getEmail():registDTO.getPhone();
    }
 
    private boolean checkCustomerExist(CustomerRegisterDTO registDTO) {
        String account = getCustomerAccount(registDTO);
        Optional<Customer> customer = customerRepository.findOneByEmailEqualsOrPhoneEquals(account, account);
        return customer.isPresent();
    }
}