Skip to content
Extraits de code Groupes Projets
Valider 09ba5474 rédigé par Mohamed Lemine BAILLAHI's avatar Mohamed Lemine BAILLAHI
Parcourir les fichiers

Merge branch 'feature/MLC-296' into 'develop'

MLC-296/integrate agency data retrieval and implement filtering by agency name

See merge request !7
parents d188e442 daf76e04
Branches
1 requête de fusion!7MLC-296/integrate agency data retrieval and implement filtering by agency name
Affichage de
avec 267 ajouts et 60 suppressions
......@@ -19,3 +19,8 @@
- MLC-296/Created getManagerById and getAllManagers methods using ManagerResponseDTO (with @Builder)
- MLC-253/Update the isAgentExists method.
- MLC-251/implement CRUD operations for Sessions & ActivityHistory
- MLC-296/Integrated call to agency-service to fetch agency details by IDs
- MLC-296/Updated AgentService to enrich AgentResponseDTO with agency name
- MLC-296/Added agency name filtering support (case-insensitive, partial match)
- MLC-296/Fixed data type mismatch for agencyId (String → Long)
......@@ -34,7 +34,7 @@
<dependency>
<groupId>com.marketingconfort</groupId>
<artifactId>mobiloca-common</artifactId>
<version>0.0.11-RELEASE</version>
<version>0.0.18-RELEASE</version>
</dependency>
<dependency>
......
......@@ -26,4 +26,7 @@ public class Message {
public static final String SESSION_NOT_FOUND = "Session not found with ID: ";
public static final String SESSION_NO_CURRENT_SESSION = "No current session found for user ID: ";
public static final String TECHNICAL_ERROR = "An unexpected error occurred. Please try again later.";
public static final String AGENCY_NOT_FOUND = "Agency not found for ID: %s";
}
\ No newline at end of file
......@@ -26,8 +26,10 @@ public class Paths {
// === External Agency ===
public static final String GET_AGENCY_NAME_BY_ID = "/name/{id}";
public static final String GET_AGENCY_NAME_BY_ID = "/{id}/name";
public static final String AGENCY_EXISTS = "/exists/{agencyId}";
public static final String GET_AGENCIES_BY_IDS="/by-ids";
public static final String GET_ALL_AGENCIES="/agencies/all";
......
......@@ -68,6 +68,7 @@ public class AgentController {
@RequestParam(required = false) String cinSearch,
@RequestParam(required = false) String agencySearch,
@RequestParam(required = false) String roleSearch,
@RequestParam(required = false) List<Long> roleFilter,
@RequestParam(required = false) String statusSearch,
@RequestParam(required = false) String phoneNumberSearch,
......@@ -82,10 +83,10 @@ public class AgentController {
@RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
LocalDate endDate
) {
) throws FunctionalException {
Page<AgentResponseDTO> result = agentService.getAllAgents(
page, size, sortBy, sortDirection,
idSearch, nameSearch, cinSearch, agencySearch, roleSearch,
idSearch, nameSearch, cinSearch, agencySearch, roleSearch,roleFilter,
statusSearch, phoneNumberSearch, createdDate, startDate, endDate
);
return ResponseEntity.ok(result);
......
......@@ -12,7 +12,7 @@ import org.springframework.web.multipart.MultipartFile;
@AllArgsConstructor
@NoArgsConstructor
public class AgentRequestDTO extends UserRequestDTO{
private String agencyId;
private Long agencyId;
private Long roleId;
private ContractType contractType;
private MultipartFile photo;
......
package com.marketingconfort.mobiloca.dto.response;
import com.marketingconfort.mobiloca.common.User.dtos.AgencyDTO;
import com.marketingconfort.mobiloca.common.User.enums.ContractType;
import com.marketingconfort.mobiloca.dto.UserDTO;
import com.marketingconfort.mobiloca.dto.UserDTO;
......@@ -13,8 +14,8 @@ import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
public class AgentResponseDTO extends UserDTO {
private String agencyId;
private String agencyName;
private RoleDTO role;
private AgencyDTO agency;
private ContractType contractType;
private String roleName;
}
package com.marketingconfort.mobiloca.dto.response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class RoleDTO {
private Long id;
private String name;
}
package com.marketingconfort.mobiloca.externalService;
import com.marketingconfort.mobiloca.common.User.dtos.AgencyDTO;
import com.marketingconfort.starter.core.exceptions.FunctionalException;
import java.util.List;
import java.util.Set;
public interface AgencyService {
boolean agencyExists(String agencyId);
String getAgencyNameById(String agencyId);
boolean agencyExists(Long agencyId);
AgencyDTO getAgencyById(Long agencyId) throws FunctionalException;
List<AgencyDTO> getAgenciesByIds(Set<Long> ids) throws FunctionalException;
List<AgencyDTO> getAllAgencies() throws FunctionalException;
}
package com.marketingconfort.mobiloca.externalService.impl;
import com.marketingconfort.mobiloca.common.User.dtos.AgencyDTO;
import com.marketingconfort.mobiloca.constants.Message;
import com.marketingconfort.mobiloca.constants.Paths;
import com.marketingconfort.mobiloca.externalService.AgencyService;
import com.marketingconfort.starter.core.exceptions.FunctionalException;
import com.marketingconfort.starter.core.services.MCRestTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Slf4j
......@@ -20,8 +28,9 @@ public class AgencyServiceImpl implements AgencyService {
private String agencyServiceUrl;
@Override
public boolean agencyExists(String agencyId) {
String url = agencyServiceUrl + Paths.AGENCY_EXISTS.replace("{agencyId}", agencyId);
public boolean agencyExists(Long agencyId) {
String url = agencyServiceUrl + Paths.AGENCY_EXISTS.replace("{agencyId}", String.valueOf(agencyId));
try {
log.info("Checking existence of agency with ID: {}", agencyId);
......@@ -42,19 +51,73 @@ public class AgencyServiceImpl implements AgencyService {
}
@Override
public String getAgencyNameById(String agencyId) {
public AgencyDTO getAgencyById(Long agencyId) throws FunctionalException {
try {
String url = agencyServiceUrl + Paths.GET_AGENCY_NAME_BY_ID.replace("{id}", agencyId);
ResponseEntity<String> response = mcRestTemplateService.getForObject(url, String.class);
String url = agencyServiceUrl + Paths.GET_AGENCY_NAME_BY_ID.replace("{id}", String.valueOf(agencyId));
ResponseEntity<AgencyDTO> response = mcRestTemplateService.getForObject(url, AgencyDTO.class);
if (response.getStatusCode().is2xxSuccessful()) {
return response.getBody();
} else {
log.warn("Agency service returned error: {}", response.getStatusCode());
throw new FunctionalException(String.format(Message.AGENCY_NOT_FOUND, agencyId));
}
} catch (HttpClientErrorException.NotFound e) {
log.warn("Agency not found for ID {}", agencyId);
throw new FunctionalException(String.format(Message.AGENCY_NOT_FOUND, agencyId));
} catch (Exception e) {
log.error("Error fetching agency name for ID {}: {}", agencyId, e.getMessage());
log.error("Error retrieving agency {}: {}", agencyId, e.getMessage());
throw new FunctionalException(Message.TECHNICAL_ERROR);
}
return null;
}
@Override
public List<AgencyDTO> getAgenciesByIds(Set<Long> ids) throws FunctionalException {
if (ids == null || ids.isEmpty()) {
throw new FunctionalException("List empty");
}
String joinedIds = ids.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
String url = agencyServiceUrl + Paths.GET_AGENCIES_BY_IDS + "?ids=" + joinedIds;
try {
log.info("Fetching agencies by IDs: {}", ids);
ResponseEntity<AgencyDTO[]> response = mcRestTemplateService.getForObject(url, AgencyDTO[].class);
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
return List.of(response.getBody());
} else {
log.warn("Failed to fetch agencies. Status: {}", response.getStatusCode());
throw new FunctionalException("Failed to retrieve agencies.");
}
} catch (Exception e) {
log.error("Error while calling agency service for IDs {}: {}", ids, e.getMessage(), e);
throw new FunctionalException(Message.TECHNICAL_ERROR);
}
}
@Override
public List<AgencyDTO> getAllAgencies() throws FunctionalException {
String url = agencyServiceUrl + Paths.GET_ALL_AGENCIES;
try {
ResponseEntity<AgencyDTO[]> response = mcRestTemplateService.getForObject(url, AgencyDTO[].class);
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
return List.of(response.getBody());
} else {
throw new FunctionalException("Failed to retrieve all agencies.");
}
} catch (Exception e) {
log.error("Error in getAllAgencies(): {}", e.getMessage(), e);
throw new FunctionalException("Technical error when calling the agency API.");
}
}
}
package com.marketingconfort.mobiloca.mapper;
import com.marketingconfort.mobiloca.common.User.dtos.AgencyDTO;
import com.marketingconfort.mobiloca.common.User.models.Agent;
import com.marketingconfort.mobiloca.dto.request.AgentRequestDTO;
import com.marketingconfort.mobiloca.dto.response.AgentResponseDTO;
import com.marketingconfort.mobiloca.externalService.AgencyService;
import com.marketingconfort.starter.core.exceptions.FunctionalException;
import com.marketingconfort.starter.core.exceptions.S3FunctionalException;
import com.marketingconfort.starter.core.services.S3FileService;
import lombok.AllArgsConstructor;
......@@ -18,6 +20,7 @@ public class AgentMapper {
private final AddressMapper addressMapper;
private final S3FileService s3FileService;
private final AgencyService agencyService;
private final RoleMapper roleMapper;
public Agent toEntity(AgentRequestDTO dto) throws S3FunctionalException {
Agent agent = modelMapper.map(dto, Agent.class);
......@@ -34,17 +37,17 @@ public class AgentMapper {
return agent;
}
public AgentResponseDTO toDto(Agent agent) {
public AgentResponseDTO toDto(Agent agent) {
AgentResponseDTO dto = modelMapper.map(agent, AgentResponseDTO.class);
dto.setPrimaryAddress(addressMapper.toDto(agent.getPrimaryAddress()));
if (agent.getAgencyId() != null) {
String agencyName = agencyService.getAgencyNameById(agent.getAgencyId());
dto.setAgencyName(agencyName);
if(agent.getRole()!=null){
dto.setRole(roleMapper.toDto(agent.getRole()));
}
return dto;
}
}
package com.marketingconfort.mobiloca.mapper;
import com.marketingconfort.mobiloca.common.User.models.Role;
import com.marketingconfort.mobiloca.dto.response.RoleDTO;
import lombok.AllArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class RoleMapper {
private final ModelMapper modelMapper;
public RoleDTO toDto(Role role) {
return modelMapper.map(role, RoleDTO.class);
}
public Role toEntity(RoleDTO dto) {
return modelMapper.map(dto, Role.class);
}
}
......@@ -7,7 +7,7 @@ import org.springframework.stereotype.Repository;
@Repository
public interface AgentRepository extends JpaRepository<Agent, Long>, JpaSpecificationExecutor<Agent> {
boolean existsByEmail(String email);
boolean existsByEmailAndIdNot(String email, Long id);
boolean existsByFirstNameAndLastNameAndIdNot(String firstName, String lastName, Long id);
}
......@@ -7,5 +7,7 @@ import org.springframework.stereotype.Repository;
@Repository
public interface ClientRepository extends JpaRepository<Client, Long>, JpaSpecificationExecutor<Client> {
boolean existsByEmail(String email);
boolean existsByEmailAndIdNot(String email, Long id);
boolean existsByFirstNameAndLastNameAndIdNot(String firstName, String lastName, Long id);
}
......@@ -4,5 +4,5 @@ import com.marketingconfort.mobiloca.dto.AddressDTO;
import com.marketingconfort.starter.core.exceptions.FunctionalException;
public interface AddressService {
AddressDTO addAddress (AddressDTO addressDTO, long userId) throws FunctionalException;
void addAddress (AddressDTO addressDTO, long userId) throws FunctionalException;
}
......@@ -33,12 +33,13 @@ public interface AgentService {
String cinSearch,
String agencySearch,
String roleSearch,
List<Long> roleIds,
String statusSearch,
String phoneNumberSearch,
LocalDate createdDate,
LocalDate startDate,
LocalDate endDate
);
) throws FunctionalException;
AgentResponseDTO getAgentById(Long id) throws FunctionalException;
......
......@@ -16,7 +16,7 @@ public interface ClientService {
ClientResponseDTO updateClient(ClientRequestDTO request) throws FunctionalException, S3FunctionalException;
ClientResponseDTO getClientByID(long id) throws FunctionalException;
public Page<ClientResponseDTO> getAllClients(
Page<ClientResponseDTO> getAllClients(
int page,
int size,
String sortBy,
......@@ -31,8 +31,8 @@ public interface ClientService {
LocalDate endDate
);
public void changeClientStatus(Long id, UserStatus newStatus) throws FunctionalException;
void changeClientStatus(Long id, UserStatus newStatus) throws FunctionalException;
public void deleteClient(Long id) throws FunctionalException;
void deleteClient(Long id) throws FunctionalException;
}
......@@ -22,7 +22,7 @@ public class AddressServiceImpl implements AddressService {
private final UserRepository userRepository;
@Override
public AddressDTO addAddress(AddressDTO addressDTO, long userId) throws FunctionalException {
public void addAddress(AddressDTO addressDTO, long userId) throws FunctionalException {
if (!userRepository.existsById(userId)) {
log.error(Message.USER_NOT_FOUND+ userId);
throw new FunctionalException(Message.USER_NOT_FOUND + userId);
......@@ -30,7 +30,7 @@ public class AddressServiceImpl implements AddressService {
Address address = addressMapper.toEntity(addressDTO);
//address.setUser(userRepository.findById(userId).get());
address = addressRepository.save(address);
return addressMapper.toDto(address) ;
addressMapper.toDto(address);
}
}
package com.marketingconfort.mobiloca.service.impl;
import com.marketingconfort.mobiloca.common.Agency.dtos.ManagerResponseDTO;
import com.marketingconfort.mobiloca.common.User.dtos.AgencyDTO;
import com.marketingconfort.mobiloca.common.User.enums.UserStatus;
import com.marketingconfort.mobiloca.common.User.models.Agent;
import com.marketingconfort.mobiloca.common.User.models.Role;
......@@ -14,6 +15,7 @@ import com.marketingconfort.mobiloca.repository.RoleRepository;
import com.marketingconfort.mobiloca.service.AgentService;
import com.marketingconfort.mobiloca.utils.SpecificationUtils;
import com.marketingconfort.mobiloca.utils.StringUtils;
import com.marketingconfort.mobiloca.utils.UserUtils;
import com.marketingconfort.mobiloca.utils.ValidationUtils;
import com.marketingconfort.starter.core.dtos.requests.ClientRegistrationRequest;
import com.marketingconfort.starter.core.dtos.requests.UpdateUserInformationRequest;
......@@ -32,7 +34,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
......@@ -43,10 +46,10 @@ public class AgentServiceImpl implements AgentService {
private final RoleRepository roleRepository;
private final AgentMapper agentMapper;
private final AuthService authService;
private final AgencyService agencyExternalService;
private final AgencyService agencyService;
private void checkAgentDuplicate(AgentRequestDTO request) throws FunctionalException {
if (agentRepository.existsByEmail(request.getEmail())) {
if (agentRepository.existsByEmailAndIdNot(request.getEmail(), request.getId())) {
throw new FunctionalException(Message.EMAIL_ALREADY_EXISTS + request.getEmail());
}
......@@ -63,13 +66,6 @@ public class AgentServiceImpl implements AgentService {
@Override
public AgentResponseDTO createAgent(AgentRequestDTO request) throws FunctionalException, TechnicalException, S3FunctionalException {
checkAgentDuplicate(request);
boolean agencyExists = agencyExternalService.agencyExists(request.getAgencyId());
if (!agencyExists) {
throw new FunctionalException("Agency with ID " + request.getAgencyId() + " does not exist.");
}
ValidationUtils.validateUserBase(
request.getEmail(),
request.getFirstName(),
......@@ -77,17 +73,29 @@ public class AgentServiceImpl implements AgentService {
request.getPhoneNumber()
);
ValidationUtils.validateAddress(request.getPrimaryAddress());
ValidationUtils.validateAgentFields(request.getRoleId(), request.getAgencyId());
checkAgentDuplicate(request);
boolean agencyExists = agencyService.agencyExists(request.getAgencyId());
if (!agencyExists) {
throw new FunctionalException("Agency with ID " + request.getAgencyId() + " does not exist.");
}
Agent agent = agentMapper.toEntity(request);
Role role = roleRepository.findById(request.getRoleId())
.orElseThrow(() -> new FunctionalException(Message.ROLE_NOT_FOUND + request.getRoleId()));
agent.setRole(role);
agent.setAgencyId(request.getAgencyId());
agent.setCreatedDate(LocalDate.now());
Agent savedAgent = agentRepository.save(agent);
agent.setStatus(UserStatus.PENDING);
String password = StringUtils.generatePassword(10);
......@@ -103,38 +111,41 @@ public class AgentServiceImpl implements AgentService {
log.error("Erreur lors de l'inscription dans Keycloak : {}", e.getMessage());
}
Agent savedAgent = agentRepository.save(agent);
return agentMapper.toDto(savedAgent);
}
@Override
public AgentResponseDTO updateAgent(AgentRequestDTO request) throws FunctionalException, S3FunctionalException {
agentRepository.findById(request.getId())
Agent existingAgent = agentRepository.findById(request.getId())
.orElseThrow(() -> new FunctionalException(Message.USER_NOT_FOUND + request.getId()));
checkAgentDuplicate(request);
Agent existingAgent = agentMapper.toEntity(request);
UserUtils.updateUserBaseFields(existingAgent, request);
Role role = roleRepository.findById(request.getRoleId())
.orElseThrow(() -> new FunctionalException(Message.ROLE_NOT_FOUND + request.getRoleId()));
existingAgent.setRole(role);
boolean agencyExists = agencyExternalService.agencyExists(request.getAgencyId());
boolean agencyExists = agencyService.agencyExists(request.getAgencyId());
if (!agencyExists) {
throw new FunctionalException("Agency with ID " + request.getAgencyId() + " does not exist.");
}
existingAgent.setAgencyId(request.getAgencyId());
existingAgent.setUpdatedDate(LocalDate.now());
agentRepository.save(existingAgent);
authService.updateUserInformation(new UpdateUserInformationRequest(
existingAgent.getEmail(),
existingAgent.getFirstName(),
existingAgent.getLastName()
));
agentRepository.save(existingAgent);
return agentMapper.toDto(agentRepository.findById(existingAgent.getId()).get());
}
......@@ -156,6 +167,14 @@ public class AgentServiceImpl implements AgentService {
agent.setUpdatedDate(LocalDate.now());
agentRepository.save(agent);
}
public List<Long> findAgencyByName(String nameSearch) throws FunctionalException {
List<AgencyDTO> allAgencies = agencyService.getAllAgencies();
return allAgencies.stream()
.filter(a -> a.name() != null && a.name().toLowerCase().contains(nameSearch.toLowerCase()))
.map(AgencyDTO::id)
.filter(Objects::nonNull)
.toList();
}
@Override
public Page<AgentResponseDTO> getAllAgents(
......@@ -168,12 +187,13 @@ public class AgentServiceImpl implements AgentService {
String cinSearch,
String agencySearch,
String roleSearch,
List<Long> roleIds,
String statusSearch,
String phoneNumberSearch,
LocalDate createdDate,
LocalDate startDate,
LocalDate endDate
) {
) throws FunctionalException {
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortDirection), sortBy));
Specification<Agent> spec = Specification.where(null);
......@@ -192,18 +212,31 @@ public class AgentServiceImpl implements AgentService {
spec = spec.and(SpecificationUtils.likeIgnoreCase("cin", cinSearch));
}
if (agencySearch != null && !agencySearch.isBlank()) {
List<Long> agencyIdsMatchingSearch = findAgencyByName(agencySearch);
if (!agencyIdsMatchingSearch.isEmpty()) {
spec = spec.and((root, query, cb) -> root.get("agencyId").in(agencyIdsMatchingSearch));
} else {
spec = spec.and((root, query, cb) -> cb.disjunction());
}
}
if (phoneNumberSearch != null && !phoneNumberSearch.isBlank()) {
spec = spec.and(SpecificationUtils.likeIgnoreCase("phoneNumber", phoneNumberSearch));
}
if (statusSearch != null && !statusSearch.isBlank()) {
spec = spec.and(SpecificationUtils.equalIgnoreCase("status", statusSearch));
spec = spec.and(SpecificationUtils.likeIgnoreCase("status", statusSearch));
}
if (roleSearch != null && !roleSearch.isBlank()) {
spec = spec.and(SpecificationUtils.likeNestedIgnoreCase("role.name", roleSearch));
}
if (roleIds != null && !roleIds.isEmpty()) {
spec = spec.and((root, query, cb) -> root.get("role").get("id").in(roleIds));
}
if (createdDate != null) {
spec = spec.and(SpecificationUtils.betweenDates("createdDate",
createdDate.atStartOfDay().toLocalDate(),
......@@ -219,14 +252,47 @@ public class AgentServiceImpl implements AgentService {
}
Page<Agent> agentPage = agentRepository.findAll(spec, pageable);
return agentPage.map(agentMapper::toDto);
Set<Long> agencyIds = agentPage.stream()
.map(Agent::getAgencyId)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Map<Long, AgencyDTO> agencyDTOMap = new HashMap<>();
if (!agencyIds.isEmpty()) {
try {
List<AgencyDTO> agencies = agencyService.getAgenciesByIds(agencyIds);
agencyDTOMap = agencies.stream()
.collect(Collectors.toMap(AgencyDTO::id, Function.identity()));
} catch (FunctionalException ignored) {
}
}
Map<Long, AgencyDTO> finalAgencyDTOMap = agencyDTOMap;
return agentPage.map(agent -> {
AgentResponseDTO dto = agentMapper.toDto(agent);
if (agent.getAgencyId() != null) {
dto.setAgency(finalAgencyDTOMap.get(agent.getAgencyId()));
}
return dto;
});
}
@Override
public AgentResponseDTO getAgentById(Long id) throws FunctionalException {
Agent agent = agentRepository.findById(id)
.orElseThrow(() -> new FunctionalException(Message.USER_NOT_FOUND + id));
return agentMapper.toDto(agent);
AgentResponseDTO dto = agentMapper.toDto(agent);
if (agent.getAgencyId() != null) {
AgencyDTO agencyDTO = agencyService.getAgencyById(agent.getAgencyId());
dto.setAgency(agencyDTO);
}
return dto;
}
@Override
......@@ -268,5 +334,4 @@ public class AgentServiceImpl implements AgentService {
}
}
......@@ -3,7 +3,6 @@ package com.marketingconfort.mobiloca.service.impl;
import com.marketingconfort.mobiloca.common.User.enums.UserStatus;
import com.marketingconfort.mobiloca.common.User.models.Client;
import com.marketingconfort.mobiloca.constants.Message;
import com.marketingconfort.mobiloca.dto.AddressDTO;
import com.marketingconfort.mobiloca.dto.response.ClientResponseDTO;
import com.marketingconfort.mobiloca.dto.request.ClientRequestDTO;
import com.marketingconfort.mobiloca.mapper.ClientMapper;
......@@ -12,6 +11,7 @@ import com.marketingconfort.mobiloca.service.AddressService;
import com.marketingconfort.mobiloca.service.ClientService;
import com.marketingconfort.mobiloca.utils.SpecificationUtils;
import com.marketingconfort.mobiloca.utils.StringUtils;
import com.marketingconfort.mobiloca.utils.UserUtils;
import com.marketingconfort.mobiloca.utils.ValidationUtils;
import com.marketingconfort.starter.core.dtos.requests.ClientRegistrationRequest;
import com.marketingconfort.starter.core.dtos.requests.UpdateUserInformationRequest;
......@@ -42,16 +42,25 @@ public class ClientServiceImpl implements ClientService {
private final ClientMapper clientMapper;
private final AuthService authService;
private void checkClientDuplicate(ClientRequestDTO request) throws FunctionalException {
if (request.getEmail() != null && clientRepository.existsByEmailAndIdNot(request.getEmail(), request.getId())) {
log.error(Message.EMAIL_ALREADY_EXISTS + request.getEmail());
throw new FunctionalException(Message.EMAIL_ALREADY_EXISTS + request.getEmail());
}
if (request.getFirstName() != null && request.getLastName() != null) {
boolean exists = clientRepository.existsByFirstNameAndLastNameAndIdNot(
request.getFirstName(), request.getLastName(), request.getId());
if (exists) {
throw new FunctionalException(Message.NAME_ALREADY_EXISTS +
request.getFirstName() + " " + request.getLastName());
}
}
}
@Override
@Transactional(rollbackFor = FunctionalException.class)
public ClientResponseDTO createClient(ClientRequestDTO request) throws FunctionalException, TechnicalException, S3FunctionalException {
if (clientRepository.existsByEmail(request.getEmail())) {
log.error(Message.EMAIL_ALREADY_EXISTS + request.getEmail());
throw new FunctionalException(Message.EMAIL_ALREADY_EXISTS + request.getEmail());
}
ValidationUtils.validateUserBase(
request.getEmail(),
request.getFirstName(),
......@@ -59,10 +68,14 @@ public class ClientServiceImpl implements ClientService {
request.getPhoneNumber()
);
checkClientDuplicate(request);
Client client = clientMapper.toEntity(request);
client.setCreatedDate(LocalDate.now());
client.setStatus(UserStatus.PENDING);
Client savedClient = clientRepository.save(client);
if (request.getPrimaryAddress() != null) {
......@@ -83,10 +96,12 @@ public class ClientServiceImpl implements ClientService {
@Transactional
public ClientResponseDTO updateClient(ClientRequestDTO request) throws FunctionalException, S3FunctionalException {
clientRepository.findById(request.getId())
Client existingClient = clientRepository.findById(request.getId())
.orElseThrow(() -> new FunctionalException(Message.USER_NOT_FOUND + request.getId()));
Client existingClient = clientMapper.toEntity(request);
checkClientDuplicate(request);
UserUtils.updateUserBaseFields(existingClient, request);
existingClient.setUpdatedDate(LocalDate.now());
......
0% ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter