diff --git a/Dockerfile b/Dockerfile index 5bfaa2e..ef361f5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ ENV CLOUD_CONFIG=$CLOUD_CONFIG VOLUME /tmp -ADD ./target/st-microservice-workspaces-3.11.1.jar st-microservice-workspaces.jar +ADD ./target/st-microservice-workspaces-4.5.0.jar st-microservice-workspaces.jar EXPOSE 8080 diff --git a/pom.xml b/pom.xml index 478814f..ecba563 100644 --- a/pom.xml +++ b/pom.xml @@ -14,12 +14,12 @@ com.ai.st.microservice.workspaces st-microservice-workspaces - 4.1.5 + 4.8.0 st-microservice-workspaces Microservice Workspaces - 1.8 + 11 Hoxton.RC2 @@ -122,7 +122,34 @@ com.ai.st.microservice.common st-common - 1.1.2 + 1.1.6 + + + + org.immutables + value + 2.8.2 + provided + + + + com.newrelic.logging + logback + 2.3.2 + + + + com.newrelic.agent.java + newrelic-api + 7.5.0 + compile + + + + com.newrelic.agent.java + newrelic-agent + 7.5.0 + provided @@ -145,6 +172,35 @@ org.springframework.boot spring-boot-maven-plugin + + net.revelc.code.formatter + formatter-maven-plugin + 2.18.0 + + LF + UTF-8 + + + + + format + + + + + + org.flywaydb + flyway-maven-plugin + 8.5.4 + + postgres + 123456 + jdbc:postgresql://localhost:54321/sistema-transicion + + workspaces + + + diff --git a/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplication.java b/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplication.java index ad84ff5..8372be6 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplication.java +++ b/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplication.java @@ -10,9 +10,10 @@ import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@EnableFeignClients(basePackages = {"com.ai.st.microservice.common.clients", "com.ai.st.microservice.workspaces.clients"}) +@EnableFeignClients(basePackages = { "com.ai.st.microservice.common.clients", "com.ai.st.microservice.workspaces" }) @EnableEurekaClient -@ComponentScan(value = {"com.ai.st.microservice.common.business", "com.ai.st.microservice.workspaces"}) +@ComponentScan(value = { "com.ai.st.microservice.common.business", "com.ai.st.microservice.workspaces" }) + public class StMicroserviceWorkspacesApplication { public static void main(String[] args) { diff --git a/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationStartup.java b/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationStartup.java deleted file mode 100644 index cec0b25..0000000 --- a/src/main/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationStartup.java +++ /dev/null @@ -1,198 +0,0 @@ -package com.ai.st.microservice.workspaces; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.stereotype.Component; - -import com.ai.st.microservice.workspaces.business.IntegrationStateBusiness; -import com.ai.st.microservice.workspaces.entities.DepartmentEntity; -import com.ai.st.microservice.workspaces.entities.IntegrationStateEntity; -import com.ai.st.microservice.workspaces.entities.MunicipalityEntity; -import com.ai.st.microservice.workspaces.services.IDepartmentService; -import com.ai.st.microservice.workspaces.services.IIntegrationStateService; -import com.ai.st.microservice.workspaces.services.IMunicipalityService; - -@Component -public class StMicroserviceWorkspacesApplicationStartup implements ApplicationListener { - - @Value("${spring.profiles.active}") - private String activeProfile; - - private static final Logger log = LoggerFactory.getLogger(StMicroserviceWorkspacesApplicationStartup.class); - - @Autowired - private IDepartmentService departmentService; - - @Autowired - private IMunicipalityService municipalityService; - - @Autowired - private IIntegrationStateService integrationStateService; - - @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - log.info("ST - Loading Domains ... "); - - this.initIntegrationStates(); - - if (activeProfile.equalsIgnoreCase("develop")) { - this.initMunicipalities(); - } - - } - - public void initMunicipalities() { - - Long countMunicipalities = municipalityService.getCount(); - if (countMunicipalities == 0) { - - try { - - DepartmentEntity departmentSucre = new DepartmentEntity(); - departmentSucre.setName("SUCRE"); - departmentSucre.setCode("70"); - departmentSucre = departmentService.createDepartment(departmentSucre); - - MunicipalityEntity municipalitySincelejo = new MunicipalityEntity(); - municipalitySincelejo.setName("SINCELEJO"); - municipalitySincelejo.setCode("70001"); - municipalitySincelejo.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalitySincelejo); - - MunicipalityEntity municipalityBuenavista = new MunicipalityEntity(); - municipalityBuenavista.setName("BUENAVISTA"); - municipalityBuenavista.setCode("70110"); - municipalityBuenavista.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalityBuenavista); - - MunicipalityEntity municipalityCaimito = new MunicipalityEntity(); - municipalityCaimito.setName("CAIMITO"); - municipalityCaimito.setCode("70124"); - municipalityCaimito.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalityCaimito); - - MunicipalityEntity municipalityCorozal = new MunicipalityEntity(); - municipalityCorozal.setName("COROZAL"); - municipalityCorozal.setCode("70215"); - municipalityCorozal.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalityCorozal); - - MunicipalityEntity municipalityCovenas = new MunicipalityEntity(); - municipalityCovenas.setName("COVEÑAS"); - municipalityCovenas.setCode("70221"); - municipalityCovenas.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalityCovenas); - - MunicipalityEntity municipalityChalan = new MunicipalityEntity(); - municipalityChalan.setName("CHALÁN"); - municipalityChalan.setCode("70230"); - municipalityChalan.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalityChalan); - - MunicipalityEntity municipalityOvejas = new MunicipalityEntity(); - municipalityOvejas.setName("OVEJAS"); - municipalityOvejas.setCode("70508"); - municipalityOvejas.setDepartment(departmentSucre); - municipalityService.createMunicipality(municipalityOvejas); - - DepartmentEntity departmentCundinamarca = new DepartmentEntity(); - departmentCundinamarca.setName("CUNDINAMARCA"); - departmentCundinamarca.setCode("25"); - departmentCundinamarca = departmentService.createDepartment(departmentCundinamarca); - - MunicipalityEntity municipalityFacatativa = new MunicipalityEntity(); - municipalityFacatativa.setName("FACATATIVA"); - municipalityFacatativa.setCode("25269"); - municipalityFacatativa.setDepartment(departmentCundinamarca); - municipalityService.createMunicipality(municipalityFacatativa); - - MunicipalityEntity municipalityGuaduas = new MunicipalityEntity(); - municipalityGuaduas.setName("GUADUAS"); - municipalityGuaduas.setCode("25320"); - municipalityGuaduas.setDepartment(departmentCundinamarca); - municipalityService.createMunicipality(municipalityGuaduas); - - MunicipalityEntity municipalityLaPalma = new MunicipalityEntity(); - municipalityLaPalma.setName("LA PALMA"); - municipalityLaPalma.setCode("25394"); - municipalityLaPalma.setDepartment(departmentCundinamarca); - municipalityService.createMunicipality(municipalityLaPalma); - - log.info("The domains 'municipalities' have been loaded!"); - } catch (Exception e) { - log.error("Failed to load 'municipalities' domains"); - } - - } - - } - - public void initIntegrationStates() { - - Long countStates = integrationStateService.getCount(); - if (countStates == 0) { - - try { - - IntegrationStateEntity stateStartedAutomatic = new IntegrationStateEntity(); - stateStartedAutomatic.setId(IntegrationStateBusiness.STATE_STARTED_AUTOMATIC); - stateStartedAutomatic.setName("INICIADA AUTOMÁTICA"); - stateStartedAutomatic.setDescription("La integración ha iniciado de forma automática."); - integrationStateService.createIntegrationState(stateStartedAutomatic); - - IntegrationStateEntity stateFinishedAutomatic = new IntegrationStateEntity(); - stateFinishedAutomatic.setId(IntegrationStateBusiness.STATE_FINISHED_AUTOMATIC); - stateFinishedAutomatic.setName("FINALIZADA AUTOMÁTICA"); - stateFinishedAutomatic.setDescription("La integración ha finalizado de forma automática."); - integrationStateService.createIntegrationState(stateFinishedAutomatic); - - IntegrationStateEntity stateStartedAssisted = new IntegrationStateEntity(); - stateStartedAssisted.setId(IntegrationStateBusiness.STATE_STARTED_ASSISTED); - stateStartedAssisted.setName("INICIADA ASISTIDA"); - stateStartedAssisted.setDescription("La integración ha iniciado de forma asistida."); - integrationStateService.createIntegrationState(stateStartedAssisted); - - IntegrationStateEntity stateFinishedAssisted = new IntegrationStateEntity(); - stateFinishedAssisted.setId(IntegrationStateBusiness.STATE_FINISHED_ASSISTED); - stateFinishedAssisted.setName("FINALIZADA ASISTIDA"); - stateFinishedAssisted.setDescription("La integración ha finalizado de forma asistida."); - integrationStateService.createIntegrationState(stateFinishedAssisted); - - IntegrationStateEntity stateGeneratingProduct = new IntegrationStateEntity(); - stateGeneratingProduct.setId(IntegrationStateBusiness.STATE_GENERATING_PRODUCT); - stateGeneratingProduct.setName("GENERANDO PRODUCTO"); - stateGeneratingProduct.setDescription("Se esta generando un producto."); - integrationStateService.createIntegrationState(stateGeneratingProduct); - - IntegrationStateEntity stateProductGenerated = new IntegrationStateEntity(); - stateProductGenerated.setId(IntegrationStateBusiness.STATE_GENERATED_PRODUCT); - stateProductGenerated.setName("PRODUCTO GENERADO"); - stateProductGenerated.setDescription("Se ha generado ya un producto."); - integrationStateService.createIntegrationState(stateProductGenerated); - - IntegrationStateEntity stateError = new IntegrationStateEntity(); - stateError.setId(IntegrationStateBusiness.STATE_ERROR_INTEGRATION_AUTOMATIC); - stateError.setName("ERROR REALIZANDO INTEGRACIÓN AUTOMÁTICA"); - stateError.setDescription("Ha ocurrido un error realizando la integración."); - integrationStateService.createIntegrationState(stateError); - - IntegrationStateEntity stateErrorProduct = new IntegrationStateEntity(); - stateErrorProduct.setId(IntegrationStateBusiness.STATE_ERROR_GENERATING_PRODUCT); - stateErrorProduct.setName("ERROR GENERANDO PRODUCTO"); - stateErrorProduct.setDescription("Ha ocurrido un error realizando la integración."); - integrationStateService.createIntegrationState(stateErrorProduct); - - log.info("The domains 'integration states' have been loaded!"); - } catch (Exception e) { - log.error("Failed to load 'integration states' domains"); - } - - } - - } - -} diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/AdministratorMicroserviceBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/AdministratorMicroserviceBusiness.java index 99cb96a..1eb8882 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/AdministratorMicroserviceBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/AdministratorMicroserviceBusiness.java @@ -20,6 +20,7 @@ import com.ai.st.microservice.workspaces.dto.CreateUserRoleProviderDto; import com.ai.st.microservice.workspaces.dto.administration.CustomUserDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -45,9 +46,9 @@ public class AdministratorMicroserviceBusiness { private final OperatorMicroserviceBusiness operatorBusiness; public AdministratorMicroserviceBusiness(UserFeignClient userClient, ProviderFeignClient providerClient, - ManagerFeignClient managerClient, OperatorFeignClient operatorClient, - NotificationBusiness notificationBusiness, ProviderBusiness providerBusiness, - ManagerMicroserviceBusiness managerBusiness, OperatorMicroserviceBusiness operatorBusiness) { + ManagerFeignClient managerClient, OperatorFeignClient operatorClient, + NotificationBusiness notificationBusiness, ProviderBusiness providerBusiness, + ManagerMicroserviceBusiness managerBusiness, OperatorMicroserviceBusiness operatorBusiness) { this.userClient = userClient; this.providerClient = providerClient; this.managerClient = managerClient; @@ -58,10 +59,9 @@ public AdministratorMicroserviceBusiness(UserFeignClient userClient, ProviderFei this.operatorBusiness = operatorBusiness; } - public CustomUserDto createUserFromAdministrator(String firstName, String lastName, String email, - String username, String password, CreateUserRoleProviderDto roleProvider, - CreateUserRoleAdministratorDto roleAdmin, CreateUserRoleManagerDto roleManager, - CreateUserRoleOperatorDto roleOperator) throws BusinessException { + public CustomUserDto createUserFromAdministrator(String firstName, String lastName, String email, String username, + String password, CreateUserRoleProviderDto roleProvider, CreateUserRoleAdministratorDto roleAdmin, + CreateUserRoleManagerDto roleManager, CreateUserRoleOperatorDto roleOperator) throws BusinessException { if (roleManager != null) { @@ -79,23 +79,22 @@ public CustomUserDto createUserFromAdministrator(String firstName, String lastNa } if (roleProvider != null) { - roleProvider.setProfiles(new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_DIRECTOR_PROVIDER))); + roleProvider + .setProfiles(new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_DIRECTOR_PROVIDER))); } if (roleOperator != null) { - if (!roleOperator.getRoleId().equals(RoleBusiness.ROLE_OPERATOR)) { throw new BusinessException("El rol no corresponde con un operador."); } - } - return this.createUser(firstName, lastName, email, username, password, true, roleProvider, roleAdmin, roleManager, - roleOperator); + return this.createUser(firstName, lastName, email, username, password, true, roleProvider, roleAdmin, + roleManager, roleOperator); } public CustomUserDto createUserFromManager(String firstName, String lastName, String email, String username, - String password, CreateUserRoleManagerDto roleManager) throws BusinessException { + String password, CreateUserRoleManagerDto roleManager) throws BusinessException { if (roleManager.getProfiles().size() == 0) { throw new BusinessException("Para asignar el rol de gestor se debe especificar al menos un perfil."); @@ -111,10 +110,11 @@ public CustomUserDto createUserFromManager(String firstName, String lastName, St boolean enabled = true; if (roleManager.getProfiles().contains(RoleBusiness.SUB_ROLE_SINIC_MANAGER)) { - List usersSINIC = - managerClient.findUsersByManager(roleManager.getManagerId(), new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_SINIC_MANAGER))); + List usersSINIC = managerClient.findUsersByManager(roleManager.getManagerId(), + new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_SINIC_MANAGER))); - int count = (int) usersSINIC.stream().map(user -> userClient.findById(user.getUserCode())).filter(MicroserviceUserDto::getEnabled).count(); + int count = (int) usersSINIC.stream().map(user -> userClient.findById(user.getUserCode())) + .filter(MicroserviceUserDto::getEnabled).count(); if (count > 0) { enabled = false; } @@ -124,7 +124,7 @@ public CustomUserDto createUserFromManager(String firstName, String lastName, St } public CustomUserDto createUserFromProvider(String firstName, String lastName, String email, String username, - String password, CreateUserRoleProviderDto roleProvider) throws BusinessException { + String password, CreateUserRoleProviderDto roleProvider) throws BusinessException { if (roleProvider.getProfiles().size() == 0) { throw new BusinessException("Se debe especificar al menos un perfil para el usuario."); @@ -142,9 +142,9 @@ public CustomUserDto createUserFromProvider(String firstName, String lastName, S return this.createUser(firstName, lastName, email, username, password, true, roleProvider, null, null, null); } - public CustomUserDto createUser(String firstName, String lastName, String email, String username, String password, boolean enabled, - CreateUserRoleProviderDto roleProvider, CreateUserRoleAdministratorDto roleAdmin, - CreateUserRoleManagerDto roleManager, CreateUserRoleOperatorDto roleOperator) throws BusinessException { + public CustomUserDto createUser(String firstName, String lastName, String email, String username, String password, + boolean enabled, CreateUserRoleProviderDto roleProvider, CreateUserRoleAdministratorDto roleAdmin, + CreateUserRoleManagerDto roleManager, CreateUserRoleOperatorDto roleOperator) throws BusinessException { MicroserviceUserDto userResponseDto; @@ -205,6 +205,8 @@ public CustomUserDto createUser(String firstName, String lastName, String email, createUserDto.setRoles(roles); + boolean useSinicTemplate = false; + if (roles.size() > 0) { try { @@ -224,7 +226,9 @@ public CustomUserDto createUser(String firstName, String lastName, String email, providerClient.addUserToProvide(addUser); } } catch (Exception e) { - log.error("Error asignando perfil proveedor al usuario: " + e.getMessage()); + String message = "Error asignando perfil proveedor al usuario: " + e.getMessage(); + SCMTracing.sendError(message); + log.error(message); } } else { @@ -239,7 +243,9 @@ public CustomUserDto createUser(String firstName, String lastName, String email, providerClient.addAdministratorToProvide(addUser); } } catch (Exception e) { - log.error("Error asignando role proveedor al usuario: " + e.getMessage()); + String message = "Error asignando el role proveedor al usuario: " + e.getMessage(); + SCMTracing.sendError(message); + log.error(message); } } @@ -251,6 +257,10 @@ public CustomUserDto createUser(String firstName, String lastName, String email, for (Long profileId : roleManager.getProfiles()) { + if (profileId.equals(RoleBusiness.SUB_ROLE_SINIC_MANAGER)) { + useSinicTemplate = true; + } + MicroserviceAddUserToManagerDto addUser = new MicroserviceAddUserToManagerDto(); addUser.setUserCode(userResponseDto.getId()); addUser.setProfileId(profileId); @@ -260,7 +270,9 @@ public CustomUserDto createUser(String firstName, String lastName, String email, } } catch (Exception e) { - log.error("Error adding profile to manager: " + e.getMessage()); + String message = "Error asignando el perfil al gestor: " + e.getMessage(); + SCMTracing.sendError(message); + log.error(message); } } @@ -276,12 +288,21 @@ public CustomUserDto createUser(String firstName, String lastName, String email, throw new BusinessException("El usuario necesita tener al menos un rol."); } - // send notification try { - notificationBusiness.sendNotificationCreationUser(email, password, entityName, username, - userResponseDto.getId()); + + if (useSinicTemplate) { + notificationBusiness.sendNotificationCreationSinicUser(email, password, entityName, username, + userResponseDto.getId()); + } else { + notificationBusiness.sendNotificationCreationUser(email, password, entityName, username, + userResponseDto.getId()); + } + } catch (Exception e) { - log.error(String.format("Error enviando notificación de la creación del usuario: %s", e.getMessage())); + String message = String.format("Error enviando notificación de la creación del usuario: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } return new CustomUserDto(userResponseDto); @@ -297,6 +318,9 @@ public CustomUserDto changeUserPassword(Long userId, String password) throws Bus return new CustomUserDto(response); } catch (BusinessException e) { + String message = String.format("Error cambiando la contraseña del usuario: %s", e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException(e.getMessage()); } } @@ -308,7 +332,10 @@ public CustomUserDto updateUserFromSuperAdmin(Long userId, String firstName, Str try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String message = String.format("Error consultando el usuario %d para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException("No se ha encontrado el usuario"); } @@ -329,7 +356,10 @@ public CustomUserDto updateUserFromAdministrator(Long userId, String firstName, try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String message = String.format("Error consultando el usuario %d para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException("No se ha encontrado el usuario"); } @@ -353,7 +383,10 @@ public CustomUserDto updateUserFromAdministrator(Long userId, String firstName, try { profiles = managerClient.findProfilesByUser(userId); } catch (Exception e) { - log.error("Error consultando los perfiles de un usuario gestor: " + e.getMessage()); + String message = String.format("Error consultando los perfiles del usuario %d : %s", userId, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } MicroserviceManagerProfileDto profileDto = profiles.stream() @@ -372,7 +405,10 @@ public CustomUserDto updateUserFromAdministrator(Long userId, String firstName, try { roles = providerClient.findRolesByUser(userId); } catch (Exception e) { - log.error("Error consultando los roles de un usuario proveedor: " + e.getMessage()); + String message = String.format("Error consultando los roles del usuario %d proveedor : %s", userId, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } MicroserviceProviderRoleDto roleDto = roles.stream() @@ -388,14 +424,17 @@ public CustomUserDto updateUserFromAdministrator(Long userId, String firstName, return this.updateUser(userId, firstName, lastName, email); } - public CustomUserDto updateUserFromManager(Long userId, String firstName, String lastName, String email, Long managerCode) - throws BusinessException { + public CustomUserDto updateUserFromManager(Long userId, String firstName, String lastName, String email, + Long managerCode) throws BusinessException { MicroserviceUserDto userDto; try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String message = String.format("Error consultando el usuario %d para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException("No se ha encontrado el usuario"); } @@ -408,11 +447,11 @@ public CustomUserDto updateUserFromManager(Long userId, String firstName, String MicroserviceManagerDto managerDto; try { - managerDto = managerClient.findByUserCode(userId); - } catch (Exception e) { - log.error("Error consultando gestor: " + e.getMessage()); + String message = String.format("Error consultando el gestor por usuario %d: %s", userId, e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException("No se ha podido modificar el usuario."); } @@ -423,14 +462,17 @@ public CustomUserDto updateUserFromManager(Long userId, String firstName, String return this.updateUser(userId, firstName, lastName, email); } - public CustomUserDto updateUserFromProvider(Long userId, String firstName, String lastName, String email, Long providerCode) - throws BusinessException { + public CustomUserDto updateUserFromProvider(Long userId, String firstName, String lastName, String email, + Long providerCode) throws BusinessException { MicroserviceUserDto userDto; try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String message = String.format("Error consultando el usuario %d para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException("No se ha encontrado el usuario"); } @@ -443,20 +485,20 @@ public CustomUserDto updateUserFromProvider(Long userId, String firstName, Strin MicroserviceProviderDto providerDtoByUser = null; try { - providerDtoByUser = providerClient.findByUserCode(userId); - } catch (Exception e) { - log.error("Error consultando proveedor por usuario: " + e.getMessage()); + String message = String.format("Error consultando el proveedor por usuario %d : %s", userId, + e.getMessage()); + log.warn(message); } MicroserviceProviderDto providerDtoByAdmin = null; try { - providerDtoByAdmin = providerClient.findProviderByAdministrator(userId); - } catch (Exception e) { - log.error("Error consultando proveedor por administrador: " + e.getMessage()); + String message = String.format("Error consultando el proveedor por administrador %d : %s", userId, + e.getMessage()); + log.warn(message); } if (providerDtoByAdmin == null && providerDtoByUser == null) { @@ -472,7 +514,8 @@ public CustomUserDto updateUserFromProvider(Long userId, String firstName, Strin return this.updateUser(userId, firstName, lastName, email); } - public CustomUserDto updateUser(Long userId, String firstName, String lastName, String email) throws BusinessException { + public CustomUserDto updateUser(Long userId, String firstName, String lastName, String email) + throws BusinessException { try { MicroserviceUpdateUserDto updateUser = new MicroserviceUpdateUserDto(); @@ -484,6 +527,9 @@ public CustomUserDto updateUser(Long userId, String firstName, String lastName, return new CustomUserDto(response); } catch (BusinessException e) { + String message = String.format("Error actualizando el usuario %d: %s", userId, e.getMessage()); + SCMTracing.sendError(message); + log.error(message); throw new BusinessException(e.getMessage()); } } @@ -494,7 +540,9 @@ public CustomUserDto changeStatusUserFromSuperAdmin(Long userId, Boolean status) try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String messageError = "Error consultando el usuario para la modificación: " + e.getMessage(); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el usuario"); } @@ -513,7 +561,10 @@ public CustomUserDto changeStatusUserFromAdministrator(Long userId, Boolean stat try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String messageError = String.format("Error consultando el usuario '%d' para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el usuario"); } @@ -537,7 +588,9 @@ public CustomUserDto changeStatusUserFromAdministrator(Long userId, Boolean stat try { profiles = managerClient.findProfilesByUser(userId); } catch (Exception e) { - log.error("Error consultando los perfiles de un usuario gestor: " + e.getMessage()); + String messageError = String.format("Error consultando los perfiles del usuario gestor '%d'", userId); + SCMTracing.sendError(messageError); + log.error(messageError); } MicroserviceManagerProfileDto profileDto = profiles.stream() @@ -556,7 +609,9 @@ public CustomUserDto changeStatusUserFromAdministrator(Long userId, Boolean stat try { roles = providerClient.findRolesByUser(userId); } catch (Exception e) { - log.error("Error consultando los roles de un usuario proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando los roles del usuario proveedor '%d'", userId); + SCMTracing.sendError(messageError); + log.error(messageError); } MicroserviceProviderRoleDto roleDto = roles.stream() @@ -579,7 +634,10 @@ public CustomUserDto changeStatusUserFromManager(Long userId, Boolean status, Lo try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String messageError = String.format("Error consultando el usuario '%d' para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el usuario"); } @@ -592,13 +650,15 @@ public CustomUserDto changeStatusUserFromManager(Long userId, Boolean status, Lo if (status && !userDto.getEnabled()) { List profiles = managerClient.findProfilesByUser(userId); - int count = (int) profiles.stream().map(MicroserviceManagerProfileDto::getId).filter(id -> id.equals(RoleBusiness.SUB_ROLE_SINIC_MANAGER)).count(); + int count = (int) profiles.stream().map(MicroserviceManagerProfileDto::getId) + .filter(id -> id.equals(RoleBusiness.SUB_ROLE_SINIC_MANAGER)).count(); if (count > 0) { - List usersSINIC = - managerClient.findUsersByManager(managerCode, new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_SINIC_MANAGER))); + List usersSINIC = managerClient.findUsersByManager(managerCode, + new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_SINIC_MANAGER))); - int countEnabled = (int) usersSINIC.stream().map(user -> userClient.findById(user.getUserCode())).filter(MicroserviceUserDto::getEnabled).count(); + int countEnabled = (int) usersSINIC.stream().map(user -> userClient.findById(user.getUserCode())) + .filter(MicroserviceUserDto::getEnabled).count(); if (countEnabled > 0) { throw new BusinessException("Sólo puede existir un usuario SINIC activo en el sistema"); } @@ -606,14 +666,14 @@ public CustomUserDto changeStatusUserFromManager(Long userId, Boolean status, Lo } } - MicroserviceManagerDto managerDto; try { - managerDto = managerClient.findByUserCode(userId); - } catch (Exception e) { - log.error("Error consultando gestor: " + e.getMessage()); + String messageError = String.format("Error consultando el gestor a partir del usuario '%d' : %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido modificar el usuario."); } @@ -631,7 +691,10 @@ public CustomUserDto changeStatusUserFromProvider(Long userId, Boolean status, L try { userDto = userClient.findById(userId); } catch (Exception e) { - log.error("Error consultando el usuario para la edición: " + e.getMessage()); + String messageError = String.format("Error consultando el usuario '%d' para la modificación: %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el usuario"); } @@ -644,20 +707,17 @@ public CustomUserDto changeStatusUserFromProvider(Long userId, Boolean status, L MicroserviceProviderDto providerDtoByUser = null; try { - providerDtoByUser = providerClient.findByUserCode(userId); - } catch (Exception e) { - log.error("Error consultando proveedor por usuario: " + e.getMessage()); + log.warn(String.format("No se ha encontrado el proveedor por usuario '%d' : %s", userId, e.getMessage())); } MicroserviceProviderDto providerDtoByAdmin = null; try { - providerDtoByAdmin = providerClient.findProviderByAdministrator(userId); - } catch (Exception e) { - log.error("Error consultando proveedor por administrador: " + e.getMessage()); + log.warn(String.format("No se ha encontrado el proveedor por usuario administrador '%d' : %s", userId, + e.getMessage())); } if (providerDtoByAdmin == null && providerDtoByUser == null) { @@ -665,7 +725,6 @@ public CustomUserDto changeStatusUserFromProvider(Long userId, Boolean status, L } MicroserviceProviderDto providerDto = (providerDtoByAdmin != null) ? providerDtoByAdmin : providerDtoByUser; - if (!providerDto.getId().equals(providerCode)) { throw new BusinessException("El usuario que se desea editar no pertenece al proveedor."); } @@ -708,6 +767,9 @@ public CustomUserDto changeStatusUser(Long userId, Boolean status) throws Busine } } catch (BusinessException e) { + String messageError = "Error cambiando el estado del usuario: " + e.getMessage(); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } @@ -715,9 +777,7 @@ public CustomUserDto changeStatusUser(Long userId, Boolean status) throws Busine } public List getUsersFromSuperAdmin() throws BusinessException { - List roles = new ArrayList<>(Collections.singletonList(RoleBusiness.ROLE_ADMINISTRATOR)); - return this.getUsers(roles); } @@ -757,7 +817,9 @@ public List getUsersFromAdministrator() throws BusinessExce MicroserviceProviderDto providerDto = providerClient.findProviderByAdministrator(userDto.getId()); userDto.setEntity(providerDto); } catch (Exception e) { - log.error("Error consultando el proveedor de insumo por el código de usuario administrador: " + e.getMessage()); + log.warn(String.format( + "Error consultando el proveedor de insumo por el código de usuario administrador %d: %s", + userDto.getId(), e.getMessage())); } try { @@ -768,7 +830,8 @@ public List getUsersFromAdministrator() throws BusinessExce userDto.setEntity(providerDto); } catch (Exception e) { - log.error("Error consultando el proveedor de insumo por el código de usuario: " + e.getMessage()); + log.warn(String.format("Error consultando el proveedor de insumo por el código de usuario %d: %s", + userDto.getId(), e.getMessage())); } listUsersResponse.add(userDto); @@ -793,7 +856,10 @@ public List getUsersFromManager(Long managerCode) throws Business try { usersManagerDto = managerClient.findUsersByManager(managerCode, null); } catch (Exception e) { - log.error("Error consultando usuarios de un gestor: " + e.getMessage()); + String messageError = String.format("Error consultando los usuarios del gestor '%d': %s", managerCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } List users = new ArrayList<>(); @@ -806,7 +872,11 @@ public List getUsersFromManager(Long managerCode) throws Business userDto.setProfilesManager(userManagerDto.getProfiles()); users.add(userDto); } catch (Exception e) { - log.error("Error consultando usuario: " + e.getMessage()); + String messageError = String.format( + "Error consultando el usuario al intentar retornar usuarios gestores'%d': %s", + userManagerDto.getUserCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -820,7 +890,10 @@ public List getUsersFromProvider(Long providerCode) throws Busine try { usersProviderDto = providerClient.findUsersByProviderId(providerCode); } catch (Exception e) { - log.error("Error consultando usuarios de un proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando los usuarios del proveedor '%d': %s", providerCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } List users = new ArrayList<>(); @@ -833,7 +906,11 @@ public List getUsersFromProvider(Long providerCode) throws Busine userDto.setProfilesProvider(userProviderDto.getProfiles()); users.add(userDto); } catch (Exception e) { - log.error("Error consultando usuario: " + e.getMessage()); + String messageError = String.format( + "Error consultando el usuario al intentar retornar usuarios proveedores '%d': %s", + userProviderDto.getUserCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -842,7 +919,10 @@ public List getUsersFromProvider(Long providerCode) throws Busine try { adminsProviderDto = providerClient.findAdministratorsByProviderId(providerCode); } catch (Exception e) { - log.error("Error consultando usuarios (administradores) de un proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando usuarios (administradores) del proveedor '%d': %s", + providerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } for (MicroserviceProviderAdministratorDto userProviderDto : adminsProviderDto) { @@ -857,7 +937,11 @@ public List getUsersFromProvider(Long providerCode) throws Busine userDto.setRolesProvider(userProviderDto.getRoles()); users.add(userDto); } catch (Exception e) { - log.error("Error consultando usuario: " + e.getMessage()); + String messageError = String.format( + "Error consultando el usuario al intentar retornar usuarios proveedores(administradores) '%d': %s", + userProviderDto.getUserCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -871,7 +955,10 @@ public List getUsers(List roles) throws BusinessException { List usersResponse = userClient.findUsersByRoles(roles); return usersResponse.stream().map(CustomUserDto::new).collect(Collectors.toList()); } catch (Exception e) { - throw new BusinessException("Error consultando los usuarios: " + e.getMessage()); + String messageError = String.format("Error consultando los usuarios: %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException(messageError); } } @@ -884,7 +971,10 @@ public CustomUserDto addProfileToUserFromManager(Long userId, Long profileId, Lo try { managerDto = managerClient.findByUserCode(userId); } catch (Exception e) { - log.error("Error consultando gestor por usuario: " + e.getMessage()); + String messageError = String.format("Error consultando el gestor por el usuario '%d' : %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el gestor"); } @@ -906,7 +996,10 @@ public CustomUserDto addProfileToUserFromManager(Long userId, Long profileId, Lo userDto.setProfilesManager(managerUser.getProfiles()); } catch (Exception e) { - log.error("Error agregando perfil a un usuario gestor: " + e.getMessage()); + String messageError = String.format("Error agregando perfil al usuario '%d' del gestor '%d': %s", userId, + managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido agregar el perfil al usuario."); } @@ -922,7 +1015,10 @@ public CustomUserDto addProfileToUserFromProvider(Long userId, Long profileId, L try { providerDto = providerClient.findByUserCode(userId); } catch (Exception e) { - log.error("Error consultando proveedor por usuario: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor por usuario %d : %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el proveedor"); } @@ -942,11 +1038,14 @@ public CustomUserDto addProfileToUserFromProvider(Long userId, Long profileId, L MicroserviceUserDto response = userClient.findById(userId); userDto = new CustomUserDto(response); - usersProvider.stream().filter(u -> u.getUserCode().equals(userId)) - .findAny().ifPresent(userFound -> userDto.setProfilesProvider(userFound.getProfiles())); + usersProvider.stream().filter(u -> u.getUserCode().equals(userId)).findAny() + .ifPresent(userFound -> userDto.setProfilesProvider(userFound.getProfiles())); } catch (Exception e) { - log.error("Error agregando perfil a un usuario proveedor: " + e.getMessage()); + String messageError = String.format("Error agregando perfil al usuario '%d' del proveedor '%d': %s", userId, + providerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido agregar el perfil al usuario."); } @@ -962,7 +1061,10 @@ public CustomUserDto removeProfileToUserFromManager(Long userId, Long profileId, try { managerDto = managerClient.findByUserCode(userId); } catch (Exception e) { - log.error("Error consultando gestor por usuario: " + e.getMessage()); + String messageError = String.format("Error consultando el gestor por el usuario '%d' : %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el gestor"); } @@ -985,7 +1087,10 @@ public CustomUserDto removeProfileToUserFromManager(Long userId, Long profileId, userDto.setProfilesManager(managerUser.getProfiles()); } catch (BusinessException e) { - log.error("Error quitando perfil a un usuario gestor: " + e.getMessage()); + String messageError = String.format("Error quitando perfil al usuario '%d' del gestor '%d': %s", userId, + managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } @@ -1001,7 +1106,10 @@ public CustomUserDto removeProfileToUserFromProvider(Long userId, Long profileId try { providerDto = providerClient.findByUserCode(userId); } catch (Exception e) { - log.error("Error consultando proveedor por usuario: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor por usuario %d : %s", userId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el proveedor"); } @@ -1021,11 +1129,14 @@ public CustomUserDto removeProfileToUserFromProvider(Long userId, Long profileId MicroserviceUserDto response = userClient.findById(userId); userDto = new CustomUserDto(response); - usersProvider.stream().filter(u -> u.getUserCode().equals(userId)) - .findAny().ifPresent(userFound -> userDto.setProfilesProvider(userFound.getProfiles())); + usersProvider.stream().filter(u -> u.getUserCode().equals(userId)).findAny() + .ifPresent(userFound -> userDto.setProfilesProvider(userFound.getProfiles())); } catch (BusinessException e) { - log.error("Error quitando el perfil a un usuario proveedor: " + e.getMessage()); + String messageError = String.format("Error quitando perfil al usuario '%d' del proveedor '%d': %s", userId, + providerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/CadastralAuthorityBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/CadastralAuthorityBusiness.java index bc35f0b..4ba1aac 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/CadastralAuthorityBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/CadastralAuthorityBusiness.java @@ -14,10 +14,13 @@ import com.ai.st.microservice.workspaces.entities.WorkspaceManagerEntity; import com.ai.st.microservice.workspaces.services.MunicipalityService; import com.ai.st.microservice.workspaces.services.WorkspaceService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import com.ai.st.microservice.workspaces.utils.DateTool; import com.ai.st.microservice.workspaces.utils.FileTool; import org.apache.commons.io.FilenameUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; @@ -29,6 +32,8 @@ @Component public class CadastralAuthorityBusiness { + private final Logger log = LoggerFactory.getLogger(CadastralAuthorityBusiness.class); + @Value("${st.filesDirectory}") private String stFilesDirectory; @@ -40,9 +45,9 @@ public class CadastralAuthorityBusiness { private final ReportBusiness reportBusiness; private final ManagerMicroserviceBusiness managerBusiness; - public CadastralAuthorityBusiness(MunicipalityBusiness municipalityBusiness, WorkspaceService workspaceService, FileBusiness fileBusiness, - SupplyBusiness supplyBusiness, MunicipalityService municipalityService, - ReportBusiness reportBusiness, ManagerMicroserviceBusiness managerBusiness) { + public CadastralAuthorityBusiness(MunicipalityBusiness municipalityBusiness, WorkspaceService workspaceService, + FileBusiness fileBusiness, SupplyBusiness supplyBusiness, MunicipalityService municipalityService, + ReportBusiness reportBusiness, ManagerMicroserviceBusiness managerBusiness) { this.municipalityBusiness = municipalityBusiness; this.workspaceService = workspaceService; this.fileBusiness = fileBusiness; @@ -52,8 +57,8 @@ public CadastralAuthorityBusiness(MunicipalityBusiness municipalityBusiness, Wor this.managerBusiness = managerBusiness; } - public CustomSupplyDto createSupplyCadastralAuthority(Long municipalityId, Long managerCode, Long attachmentTypeId, String name, - String observations, String ftp, MultipartFile file, Long userCode) throws BusinessException { + public CustomSupplyDto createSupplyCadastralAuthority(Long municipalityId, Long managerCode, Long attachmentTypeId, + String name, String observations, String ftp, MultipartFile file, Long userCode) throws BusinessException { CustomSupplyDto supplyDto; @@ -70,8 +75,8 @@ public CustomSupplyDto createSupplyCadastralAuthority(Long municipalityId, Long if (workspaceEntity == null) { throw new BusinessException("El municipio no tiene asignado un gestor"); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El gestor no pertenece al municipio"); } @@ -111,9 +116,12 @@ public CustomSupplyDto createSupplyCadastralAuthority(Long municipalityId, Long } try { - supplyDto = supplyBusiness.createSupply(municipalityCode, observations, null, managerCode, attachments, null, - userCode, null, null, userCode, null, SupplyBusiness.SUPPLY_STATE_INACTIVE, name, null); + supplyDto = supplyBusiness.createSupply(municipalityCode, observations, null, managerCode, attachments, + null, userCode, null, null, userCode, null, SupplyBusiness.SUPPLY_STATE_INACTIVE, name, null); } catch (Exception e) { + String messageError = String.format("Error al intentar crear un insumo: %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cargar el insumo."); } @@ -134,9 +142,8 @@ public String generateReport(Long municipalityId, Long managerCode) throws Busin throw new BusinessException("El municipio aún no tiene asignado un gestor"); } - - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El gestor no pertenece al municipio"); } @@ -158,8 +165,8 @@ public String generateReport(Long municipalityId, Long managerCode) throws Busin List suppliesReport = new ArrayList<>(); - List supplies = (List) supplyBusiness - .getSuppliesByMunicipalityAdmin(municipalityId, new ArrayList<>(), null, null, false, workspaceManagerEntity.getManagerCode()); + List supplies = (List) supplyBusiness.getSuppliesByMunicipalityAdmin( + municipalityId, new ArrayList<>(), null, null, false, workspaceManagerEntity.getManagerCode()); for (CustomSupplyDto supply : supplies) { diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/CrytpoBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/CrytpoBusiness.java index a0fc9a1..58864b5 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/CrytpoBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/CrytpoBusiness.java @@ -16,50 +16,50 @@ @Component public class CrytpoBusiness { - private static String factoryInstance = "PBKDF2WithHmacSHA256"; - private static String cipherInstance = "AES/CBC/PKCS5PADDING"; - private static String secretKeyType = "AES"; - private static byte[] ivCode = new byte[16]; + private static String factoryInstance = "PBKDF2WithHmacSHA256"; + private static String cipherInstance = "AES/CBC/PKCS5PADDING"; + private static String secretKeyType = "AES"; + private static byte[] ivCode = new byte[16]; - @Value("${crypto.secretKey}") - private String secretKey; + @Value("${crypto.secretKey}") + private String secretKey; - @Value("${crypto.salt}") - private String salt; + @Value("${crypto.salt}") + private String salt; - public String encrypt(String value) throws Exception { - Cipher cipher = initCipher(secretKey, salt, Cipher.ENCRYPT_MODE); - byte[] encrypted = cipher.doFinal(value.getBytes()); - byte[] cipherWithIv = addIVToCipher(encrypted); - return Base64.encodeBase64String(cipherWithIv); - } + public String encrypt(String value) throws Exception { + Cipher cipher = initCipher(secretKey, salt, Cipher.ENCRYPT_MODE); + byte[] encrypted = cipher.doFinal(value.getBytes()); + byte[] cipherWithIv = addIVToCipher(encrypted); + return Base64.encodeBase64String(cipherWithIv); + } - public String decrypt(String encrypted) throws Exception { - Cipher cipher = initCipher(secretKey, salt, Cipher.DECRYPT_MODE); - byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); - byte[] originalWithoutIv = Arrays.copyOfRange(original, 16, original.length); - return new String(originalWithoutIv); - } + public String decrypt(String encrypted) throws Exception { + Cipher cipher = initCipher(secretKey, salt, Cipher.DECRYPT_MODE); + byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); + byte[] originalWithoutIv = Arrays.copyOfRange(original, 16, original.length); + return new String(originalWithoutIv); + } - private static Cipher initCipher(String secretKey, String salt, int mode) throws Exception { - SecretKeyFactory factory = SecretKeyFactory.getInstance(factoryInstance); - KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256); - SecretKey tmp = factory.generateSecret(spec); - SecretKeySpec skeySpec = new SecretKeySpec(tmp.getEncoded(), secretKeyType); - Cipher cipher = Cipher.getInstance(cipherInstance); - // Generating random IV - SecureRandom random = new SecureRandom(); - random.nextBytes(ivCode); + private static Cipher initCipher(String secretKey, String salt, int mode) throws Exception { + SecretKeyFactory factory = SecretKeyFactory.getInstance(factoryInstance); + KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256); + SecretKey tmp = factory.generateSecret(spec); + SecretKeySpec skeySpec = new SecretKeySpec(tmp.getEncoded(), secretKeyType); + Cipher cipher = Cipher.getInstance(cipherInstance); + // Generating random IV + SecureRandom random = new SecureRandom(); + random.nextBytes(ivCode); - cipher.init(mode, skeySpec, new IvParameterSpec(ivCode)); - return cipher; - } + cipher.init(mode, skeySpec, new IvParameterSpec(ivCode)); + return cipher; + } - private static byte[] addIVToCipher(byte[] encrypted) { - byte[] cipherWithIv = new byte[ivCode.length + encrypted.length]; - System.arraycopy(ivCode, 0, cipherWithIv, 0, ivCode.length); - System.arraycopy(encrypted, 0, cipherWithIv, encrypted.length, encrypted.length); - return cipherWithIv; - } + private static byte[] addIVToCipher(byte[] encrypted) { + byte[] cipherWithIv = new byte[ivCode.length + encrypted.length]; + System.arraycopy(ivCode, 0, cipherWithIv, 0, ivCode.length); + System.arraycopy(encrypted, 0, cipherWithIv, encrypted.length, encrypted.length); + return cipherWithIv; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/DatabaseIntegrationBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/DatabaseIntegrationBusiness.java index a80c191..333c81d 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/DatabaseIntegrationBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/DatabaseIntegrationBusiness.java @@ -2,6 +2,7 @@ import com.ai.st.microservice.common.exceptions.BusinessException; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -51,7 +52,9 @@ public boolean createDatabase(String database, String username, String password) this.createExtensionsToDatabase(database); } catch (Exception e) { - log.error("Error creando base de datos: " + e.getMessage()); + String messageError = String.format("Error creando base de datos %s: %s", database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido generar la base de datos."); } @@ -59,7 +62,7 @@ public boolean createDatabase(String database, String username, String password) } public void protectedDatabase(String host, String port, String database, String schema, String username, - String password) throws BusinessException { + String password) throws BusinessException { try { @@ -125,7 +128,9 @@ public void protectedDatabase(String host, String port, String database, String stmt13.execute(); } catch (Exception e) { - log.error("Error protegiendo base de datos: " + e.getMessage()); + String messageError = String.format("Error protegiendo la base de datos %s: %s", database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido configurar los permisos a la base de datos."); } @@ -145,7 +150,10 @@ private void createExtensionsToDatabase(String database) { stmt2.execute(); } catch (Exception e) { - log.error("Error creando extensiones a la base de datos: " + e.getMessage()); + String messageError = String.format("Error creando las extensiones en la base de datos %s: %s", database, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -173,13 +181,15 @@ public void dropDatabase(String database, String username) throws BusinessExcept stmt4.execute(); } catch (Exception e) { - log.error("Error eliminando base de datos: " + e.getMessage()); + String messageError = String.format("Error eliminando la base de datos %s: %s", database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido eliminar la base de datos"); } } - public void createViewIntegration(String host, String port, String database, String schema, String nameView) + public void createParcelIntegratedView(String host, String port, String database, String schema, String viewName) throws BusinessException { try { @@ -188,20 +198,196 @@ public void createViewIntegration(String host, String port, String database, Str Connection connection = DriverManager.getConnection(url, databaseUsername, databasePassword); - PreparedStatement stmt1 = connection.prepareStatement("CREATE OR REPLACE VIEW " + schema + "." + nameView - + " AS\n" - + " select id, numero_predial, coalesce(c.tipo_emparejamiento,0) as emparejamiento , geometria from\n" - + "(select * from\n" + " (select p.t_id as id, p.numero_predial, t.geometria\n" - + " from " + schema + ".gc_prediocatastro as p\n" + "inner join " + schema - + ".gc_terreno as t\n" + " on t.gc_predio=p.t_id) as a\n" + " left join\n" - + " (select l.t_id as id2, i.tipo_emparejamiento\n" + " from " + schema - + ".ini_predioinsumos as i\n" + " inner join " + schema + ".gc_prediocatastro as l\n" - + " on l.t_id=i.gc_predio_catastro) as b\n" + " on a.id=b.id2\n" + ") as c;"); + PreparedStatement stmt1 = connection.prepareStatement("CREATE OR REPLACE VIEW " + schema + "." + viewName + + " AS SELECT pc.t_id AS id,\n" + " pc.numero_predial,\n" + " CASE\n" + + " WHEN pc.nupre IS NULL THEN 'NA'::character varying\n" + " ELSE pc.nupre\n" + + " END AS nupre,\n" + " pc.circulo_registral,\n" + + " pc.matricula_inmobiliaria_catastro,\n" + " CASE\n" + + " WHEN r.valor IS NULL THEN 'NA'::character varying\n" + " ELSE r.valor\n" + + " END AS direccion,\n" + " pc.tipo_predio,\n" + + " cpt.dispname AS condicion_predio,\n" + " CASE\n" + + " WHEN ep.estado_alerta IS NULL THEN 'NA'::character varying\n" + + " ELSE ep.estado_alerta\n" + " END AS estado_predio,\n" + " t.geometria,\n" + + " t.area_terreno_alfanumerica,\n" + " t.area_terreno_digital,\n" + " CASE\n" + + " WHEN ipi.t_id IS NULL THEN false\n" + " ELSE true\n" + + " END AS cruzo\n" + " FROM " + schema + ".gc_prediocatastro pc\n" + " JOIN " + schema + + ".gc_terreno t ON t.gc_predio = pc.t_id AND t.geometria IS NOT NULL\n" + " LEFT JOIN " + + schema + ".ini_predioinsumos ipi ON ipi.gc_predio_catastro = pc.t_id\n" + " LEFT JOIN " + + schema + ".gc_condicionprediotipo cpt ON cpt.t_id = pc.condicion_predio\n" + " LEFT JOIN " + + schema + ".gc_estadopredio ep ON ep.gc_prediocatastro_estado_predio = pc.t_id\n" + + " LEFT JOIN LATERAL ( SELECT r_1.t_id,\n" + " r_1.t_seq,\n" + + " r_1.valor,\n" + " r_1.principal,\n" + + " r_1.geometria_referencia,\n" + " r_1.gc_prediocatastro_direcciones\n" + + " FROM " + schema + ".gc_direccion r_1\n" + + " WHERE pc.t_id = r_1.gc_prediocatastro_direcciones\n" + " LIMIT 1) r ON true\n" + + " ORDER BY pc.t_id;"); stmt1.execute(); } catch (Exception e) { - log.error("Error creando vista para el proceso de integración: " + e.getMessage()); - throw new BusinessException("No se ha podido configurar la integración."); + String messageError = String.format( + "Error creando la vista de predios integrados en la base de datos %s: %s", database, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido configurar la vista de predios integrados."); + } + + } + + public void createPerimeterView(String host, String port, String database, String schema, String viewName) + throws BusinessException { + + try { + + String url = "jdbc:postgresql://" + host + ":" + port + "/" + database; + + Connection connection = DriverManager.getConnection(url, databaseUsername, databasePassword); + + PreparedStatement stmt1 = connection.prepareStatement("CREATE OR REPLACE VIEW " + schema + "." + viewName + + " AS SELECT\n" + " CASE\n" + + " WHEN p.codigo_departamento IS NULL THEN 'NA'::character varying\n" + + " ELSE p.codigo_departamento\n" + " END AS codigo_departamento,\n" + + " CASE\n" + " WHEN p.codigo_municipio IS NULL THEN 'NA'::character varying\n" + + " ELSE p.codigo_municipio\n" + " END AS codigo_municipio,\n" + " CASE\n" + + " WHEN p.tipo_avaluo IS NULL THEN 'NA'::character varying\n" + + " ELSE p.tipo_avaluo\n" + " END AS tipo_avaluo,\n" + " CASE\n" + + " WHEN p.nombre_geografico IS NULL THEN 'NA'::character varying\n" + + " ELSE p.nombre_geografico\n" + " END AS nombre_geografico,\n" + + " CASE\n" + " WHEN p.codigo_nombre IS NULL THEN 'NA'::character varying\n" + + " ELSE p.codigo_nombre\n" + " END AS codigo_nombre,\n" + " p.geometria\n" + + " FROM " + schema + ".gc_perimetro p\n" + " WHERE p.geometria IS NOT NULL;"); + stmt1.execute(); + + } catch (Exception e) { + String messageError = String.format("Error creando la vista de perímetros en la base de datos %s: %s", + database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido crear la vista de perímetros."); + } + + } + + public void createSidewalkView(String host, String port, String database, String schema, String viewName) + throws BusinessException { + + try { + + String url = "jdbc:postgresql://" + host + ":" + port + "/" + database; + + Connection connection = DriverManager.getConnection(url, databaseUsername, databasePassword); + + PreparedStatement stmt1 = connection.prepareStatement("CREATE OR REPLACE VIEW " + schema + "." + viewName + + " AS SELECT\n" + " CASE\n" + + " WHEN v.codigo IS NULL THEN 'NA'::character varying\n" + " ELSE v.codigo\n" + + " END AS codigo,\n" + " CASE\n" + + " WHEN v.codigo_anterior IS NULL THEN 'NA'::character varying\n" + + " ELSE v.codigo_anterior\n" + " END AS codigo_anterior,\n" + " CASE\n" + + " WHEN v.nombre IS NULL THEN 'NA'::character varying\n" + " ELSE v.nombre\n" + + " END AS nombre,\n" + " CASE\n" + + " WHEN v.codigo_sector IS NULL THEN 'NA'::character varying\n" + + " ELSE v.codigo_sector\n" + " END AS codigo_sector,\n" + " v.geometria\n" + + " FROM " + schema + ".gc_vereda v\n" + " WHERE v.geometria IS NOT NULL;"); + stmt1.execute(); + + } catch (Exception e) { + String messageError = String.format("Error creando la vista de veredas en la base de datos %s: %s", + database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido crear la vista de veredas."); + } + + } + + public void createBuildingView(String host, String port, String database, String schema, String viewName) + throws BusinessException { + + try { + + String url = "jdbc:postgresql://" + host + ":" + port + "/" + database; + + Connection connection = DriverManager.getConnection(url, databaseUsername, databasePassword); + + PreparedStatement stmt1 = connection.prepareStatement("CREATE OR REPLACE VIEW " + schema + "." + viewName + + " AS SELECT c.t_id AS id,\n" + " c.gc_predio AS id_predio,\n" + " CASE\n" + + " WHEN c.etiqueta IS NULL THEN 'NA'::character varying\n" + + " ELSE c.etiqueta\n" + " END AS etiqueta,\n" + + " uct.dispname AS tipo_construccion,\n" + " c.tipo_dominio,\n" + " c.area_construida,\n" + + " c.geometria\n" + " FROM " + schema + ".gc_construccion c\n" + " LEFT JOIN " + schema + + ".gc_unidadconstrucciontipo uct ON uct.t_id = c.tipo_construccion\n" + + " WHERE c.geometria IS NOT NULL;"); + stmt1.execute(); + + } catch (Exception e) { + String messageError = String.format("Error creando la vista de construcciones en la base de datos %s: %s", + database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido crear la vista de construcciones."); + } + + } + + public void createBuildingUnitsView(String host, String port, String database, String schema, String viewName) + throws BusinessException { + + try { + + String url = "jdbc:postgresql://" + host + ":" + port + "/" + database; + + Connection connection = DriverManager.getConnection(url, databaseUsername, databasePassword); + + PreparedStatement stmt1 = connection.prepareStatement( + "CREATE OR REPLACE VIEW " + schema + "." + viewName + " AS SELECT uc.t_id AS id,\n" + + " CASE\n" + " WHEN uc.etiqueta IS NULL THEN 'NA'::character varying\n" + + " ELSE uc.etiqueta\n" + " END AS etiqueta,\n" + " CASE\n" + + " WHEN uc.tipo_dominio IS NULL THEN 'NA'::character varying\n" + + " ELSE uc.tipo_dominio\n" + " END AS tipo_dominio,\n" + + " uct.dispname AS tipo_construccion,\n" + " uc.total_habitaciones,\n" + + " uc.total_banios,\n" + " uc.total_pisos,\n" + " uc.geometria\n" + " FROM " + + schema + ".gc_unidadconstruccion uc\n" + " LEFT JOIN " + schema + + ".gc_unidadconstrucciontipo uct ON uct.t_id = uc.tipo_construccion\n" + + " WHERE uc.geometria IS NOT NULL;"); + stmt1.execute(); + + } catch (Exception e) { + String messageError = String.format( + "Error creando la vista de unidades de construcción en la base de datos %s: %s", database, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido crear la vista de unidades de construcción."); + } + + } + + public void createSquareView(String host, String port, String database, String schema, String viewName) + throws BusinessException { + + try { + + String url = "jdbc:postgresql://" + host + ":" + port + "/" + database; + + Connection connection = DriverManager.getConnection(url, databaseUsername, databasePassword); + + PreparedStatement stmt1 = connection.prepareStatement("CREATE OR REPLACE VIEW " + schema + "." + viewName + + " AS SELECT\n" + " CASE\n" + + " WHEN m.codigo IS NULL THEN 'NA'::character varying\n" + " ELSE m.codigo\n" + + " END AS codigo,\n" + " CASE\n" + + " WHEN m.codigo_anterior IS NULL THEN 'NA'::character varying\n" + + " ELSE m.codigo_anterior\n" + " END AS codigo_anterior,\n" + " CASE\n" + + " WHEN m.codigo_barrio IS NULL THEN 'NA'::character varying\n" + + " ELSE m.codigo_barrio\n" + " END AS codigo_barrio,\n" + " m.geometria\n" + + " FROM " + schema + ".gc_manzana m\n" + " WHERE m.geometria IS NOT NULL;"); + stmt1.execute(); + + } catch (Exception e) { + String messageError = String.format("Error creando la vista de manzanas en la base de datos %s: %s", + database, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido crear la vista de manzanas."); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/FTPBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/FTPBusiness.java deleted file mode 100644 index 6a259d5..0000000 --- a/src/main/java/com/ai/st/microservice/workspaces/business/FTPBusiness.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.ai.st.microservice.workspaces.business; - -import com.ai.st.microservice.workspaces.clients.FTPFeignClient; -import com.ai.st.microservice.workspaces.dto.ftp.MicroserviceCreateUserFTPDto; - -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPReply; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -@Component -public class FTPBusiness { - - private final Logger log = LoggerFactory.getLogger(FTPBusiness.class); - - @Value("${st.ftp.host}") - private String hostFTP; - - @Value("${st.ftp.port}") - private int portFTP; - - @Autowired - private FTPFeignClient ftpFeignClient; - - public boolean createFTPCredentials(String username, String password) { - - boolean result; - - try { - - MicroserviceCreateUserFTPDto data = new MicroserviceCreateUserFTPDto(); - data.setUsername(username); - data.setPassword(password); - - ftpFeignClient.createUserFTP(data); - result = true; - - } catch (Exception e) { - log.error("Error creating user ftp: " + e.getMessage()); - result = false; - } - - return result; - } - - public boolean uploadFileToFTP(String fileUrl, String nameFile, String ftpUser, String ftpPassword) { - - boolean result = false; - - FTPClient ftpClient = new FTPClient(); - - try { - - ftpClient.connect(hostFTP, portFTP); - showServerReply(ftpClient); - - int replyCode = ftpClient.getReplyCode(); - if (!FTPReply.isPositiveCompletion(replyCode)) { - log.error("Operation failed. Server reply code: " + replyCode); - } else { - - boolean success = ftpClient.login(ftpUser, ftpPassword); - showServerReply(ftpClient); - if (!success) { - log.error("Could not login to the server"); - } else { - - ftpClient.enterLocalPassiveMode(); - ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - - File firstLocalFile = new File(fileUrl); - InputStream inputStream = new FileInputStream(firstLocalFile); - - log.info("Start uploading file " + fileUrl); - result = ftpClient.storeFile(nameFile, inputStream); - inputStream.close(); - showServerReply(ftpClient); - if (result) { - log.info("The file is uploaded successfully."); - } - } - } - } catch (IOException ex) { - log.error("Error uploading file to FTP server: " + ex.getMessage()); - result = false; - } finally { - try { - if (ftpClient.isConnected()) { - ftpClient.logout(); - ftpClient.disconnect(); - } - } catch (IOException ex) { - log.error("Error closing connection: " + ex.getMessage()); - result = false; - } - } - - return result; - } - - private void showServerReply(FTPClient ftpClient) { - String[] replies = ftpClient.getReplyStrings(); - if (replies != null && replies.length > 0) { - for (String aReply : replies) { - log.info("SERVER: " + aReply); - } - } - } - -} diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/FileBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/FileBusiness.java index 8ab0075..e3ac626 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/FileBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/FileBusiness.java @@ -1,5 +1,6 @@ package com.ai.st.microservice.workspaces.business; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import com.ai.st.microservice.workspaces.utils.ZipUtil; import org.apache.commons.io.FileUtils; @@ -39,7 +40,10 @@ public String loadFileToSystem(MultipartFile file, String fileName) { FileUtils.writeByteArrayToFile(new File(temporalFile), file.getBytes()); return temporalFile; } catch (IOException e) { - log.error("Error saving file: " + e.getMessage()); + String messageError = String.format("Error guardando el archivo %s en el directorio de temporales: %s", + fileName, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return null; @@ -50,7 +54,9 @@ public void deleteFile(String path) { try { FileUtils.forceDelete(FileUtils.getFile(path)); } catch (Exception e) { - log.error("It has not been possible delete the file: " + e.getMessage()); + String messageError = String.format("Error eliminando el archivo %s: %s", path, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -77,7 +83,10 @@ public String saveFileToSystem(MultipartFile file, String namespace, Boolean zip return pathFile; } catch (IOException e) { - log.error("Error saving file: " + e.getMessage()); + String messageError = String.format("Error guardando el archivo %s en el directorio finales : %s", + namespace, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return null; diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/IliBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/IliBusiness.java index 6465cf4..aba1f33 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/IliBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/IliBusiness.java @@ -4,6 +4,7 @@ import com.ai.st.microservice.common.dto.ili.*; import com.ai.st.microservice.common.exceptions.BusinessException; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.apache.commons.lang.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +34,7 @@ public IliBusiness(IliFeignClient iliClient) { } public void startExport(String hostname, String database, String password, String port, String schema, - String username, Long integrationId, Boolean withStats, String modelVersion, String namespace) + String username, Long integrationId, Boolean withStats, String modelVersion, String namespace) throws BusinessException { try { @@ -56,13 +57,16 @@ public void startExport(String hostname, String database, String password, Strin iliClient.startExport(exportDto); } catch (Exception e) { + String messageError = String.format("Error empezando la exportación a un archivo XTF : %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido iniciar la generación del insumo"); } } public void startIntegration(String pathFileCadastre, String pathFileRegistration, String hostname, String database, - String password, String port, String schema, String username, Long integrationId, String versionModel) + String password, String port, String schema, String username, Long integrationId, String versionModel) throws BusinessException { try { @@ -82,14 +86,17 @@ public void startIntegration(String pathFileCadastre, String pathFileRegistratio iliClient.startIntegrationCadastreRegistration(integrationDto); } catch (Exception e) { + String messageError = String.format("Error empezando la integración : %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido iniciar la integración."); } } - public void startValidation(Long requestId, String observations, String pathFile, - Long supplyRequestedId, Long userCode, String modelVersion, Boolean skipGeometryValidation, - Boolean skipErrors) throws BusinessException { + public void startValidation(Long requestId, String observations, String pathFile, Long supplyRequestedId, + Long userCode, String modelVersion, Boolean skipGeometryValidation, Boolean skipErrors) + throws BusinessException { try { @@ -109,103 +116,12 @@ public void startValidation(Long requestId, String observations, String pathFile iliClient.startValidation(ilivalidatorDto); } catch (Exception e) { + String messageError = String.format("Error empezando la validación de archivo XTF : %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido iniciar la validación."); } } - public void startImport(String pathFile, String hostname, String database, String password, String port, - String schema, String username, String reference, String versionModel, Long conceptId) - throws BusinessException { - - try { - MicroserviceIli2pgImportReferenceDto importDto = new MicroserviceIli2pgImportReferenceDto(); - - importDto.setPathXTF(pathFile); - importDto.setDatabaseHost(hostname); - importDto.setDatabaseName(database); - importDto.setDatabasePassword(password); - importDto.setDatabasePort(port); - importDto.setDatabaseSchema(schema); - importDto.setDatabaseUsername(username); - importDto.setReference(reference); - importDto.setVersionModel(versionModel); - importDto.setConceptId(conceptId); - - iliClient.startImport(importDto); - - } catch (Exception e) { - throw new BusinessException("No se ha podido iniciar la importación."); - } - - } - - public MicroserviceQueryResultRegistralRevisionDto getResultQueryRegistralRevision(String host, String database, - String password, String port, String schema, String username, String versionModel, int page, int limit) { - - MicroserviceQueryResultRegistralRevisionDto resultDto = null; - - try { - resultDto = iliClient.getRecordsFromQueryRegistralRevision(host, database, schema, port, username, password, - versionModel, IliBusiness.ILI_CONCEPT_INTEGRATION, page, limit); - } catch (Exception e) { - log.error("No se ha podido realizar la consulta: " + e.getMessage()); - } - - return resultDto; - } - - public void updateRecordFromRevision(String host, String database, String password, String port, String schema, - String username, String versionModel, Long boundarySpaceId, Long entityId, String namespace, - String urlFile) { - - try { - - MicroserviceExecuteQueryUpdateToRevisionDto data = new MicroserviceExecuteQueryUpdateToRevisionDto(); - data.setBoundarySpaceId(boundarySpaceId); - data.setConceptId(IliBusiness.ILI_CONCEPT_INTEGRATION); - data.setDatabaseHost(host); - data.setDatabaseName(database); - data.setDatabasePassword(password); - data.setDatabasePort(port); - data.setDatabaseSchema(schema); - data.setDatabaseUsername(username); - data.setEntityId(entityId); - data.setNamespace(namespace); - data.setUrlFile(urlFile); - data.setVersionModel(versionModel); - - iliClient.updateRecordFromRevision(data); - } catch (Exception e) { - log.error("No se ha podido realizar la actualización del registro: " + e.getMessage()); - } - } - - public void startExportReference(String pathFile, String hostname, String database, String password, String port, - String schema, String username, String reference, String versionModel, Long conceptId) - throws BusinessException { - - try { - MicroserviceIli2pgExportReferenceDto exportDto = new MicroserviceIli2pgExportReferenceDto(); - - exportDto.setPathFileXTF(pathFile); - exportDto.setDatabaseHost(hostname); - exportDto.setDatabaseName(database); - exportDto.setDatabasePassword(password); - exportDto.setDatabasePort(port); - exportDto.setDatabaseSchema(schema); - exportDto.setDatabaseUsername(username); - exportDto.setReference(reference); - exportDto.setVersionModel(versionModel); - exportDto.setConceptId(conceptId); - - iliClient.startExportReference(exportDto); - - } catch (Exception e) { - log.error("No se ha podido iniciar la exportación de la base de datos: " + e.getMessage()); - throw new BusinessException("No se ha podido iniciar la exportación."); - } - - } - } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationBusiness.java index 2fe1f78..e6c51a4 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationBusiness.java @@ -26,8 +26,10 @@ import com.ai.st.microservice.workspaces.services.IIntegrationStateService; import com.ai.st.microservice.workspaces.services.IWorkspaceService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.*; @@ -35,6 +37,12 @@ @Component public class IntegrationBusiness { + @Value("${integrations.database.username}") + private String databaseUsername; + + @Value("${integrations.database.password}") + private String databasePassword; + private final SupplyFeignClient supplyClient; private final ProviderFeignClient providerClient; private final GeovisorFeignClient geovisorClient; @@ -49,11 +57,12 @@ public class IntegrationBusiness { private final Logger log = LoggerFactory.getLogger(IntegrationBusiness.class); - public IntegrationBusiness(SupplyFeignClient supplyClient, ProviderFeignClient providerClient, GeovisorFeignClient geovisorClient, - IIntegrationService integrationService, IIntegrationStatService integrationStatService, - IIntegrationStateService integrationStateService, IWorkspaceService workspaceService, - SupplyBusiness supplyBusiness, MunicipalityBusiness municipalityBusiness, - DatabaseIntegrationBusiness databaseBusiness, CrytpoBusiness cryptoBusiness) { + public IntegrationBusiness(SupplyFeignClient supplyClient, ProviderFeignClient providerClient, + GeovisorFeignClient geovisorClient, IIntegrationService integrationService, + IIntegrationStatService integrationStatService, IIntegrationStateService integrationStateService, + IWorkspaceService workspaceService, SupplyBusiness supplyBusiness, + MunicipalityBusiness municipalityBusiness, DatabaseIntegrationBusiness databaseBusiness, + CrytpoBusiness cryptoBusiness) { this.supplyClient = supplyClient; this.providerClient = providerClient; this.geovisorClient = geovisorClient; @@ -68,9 +77,9 @@ public IntegrationBusiness(SupplyFeignClient supplyClient, ProviderFeignClient p } public IntegrationDto createIntegration(String hostname, String port, String database, String schema, - String username, String password, Long supplyCadastreId, Long supplySnrId, Long supplyAntId, - WorkspaceEntity workspaceEntity, IntegrationStateEntity stateEntity, Long userCode, Long managerCode, - String user) { + String username, String password, Long supplyCadastreId, Long supplySnrId, Long supplyAntId, + WorkspaceEntity workspaceEntity, IntegrationStateEntity stateEntity, Long userCode, Long managerCode, + String user) { IntegrationEntity integrationEntity = new IntegrationEntity(); integrationEntity.setDatabase(database); @@ -103,7 +112,7 @@ public IntegrationDto createIntegration(String hostname, String port, String dat } public IntegrationDto updateCredentialsIntegration(Long integrationId, String hostname, String port, - String database, String schema, String username, String password) throws BusinessException { + String database, String schema, String username, String password) throws BusinessException { IntegrationEntity integrationEntity = integrationService.getIntegrationById(integrationId); if (integrationEntity == null) { @@ -124,7 +133,7 @@ public IntegrationDto updateCredentialsIntegration(Long integrationId, String ho } public IntegrationDto addStatToIntegration(Long integrationId, Long countSnr, Long countCadastre, Long countAnt, - Long countMatch, Double percentage) throws BusinessException { + Long countMatch, Double percentage) throws BusinessException { IntegrationEntity integrationEntity = integrationService.getIntegrationById(integrationId); if (integrationEntity == null) { @@ -144,8 +153,8 @@ public IntegrationDto addStatToIntegration(Long integrationId, Long countSnr, Lo return this.transformEntityToDto(integrationEntity); } - public IntegrationDto updateStateToIntegration(Long integrationId, Long stateId, String errors, Long userCode, Long managerCode, - String user) throws BusinessException { + public IntegrationDto updateStateToIntegration(Long integrationId, Long stateId, String errors, Long userCode, + Long managerCode, String user) throws BusinessException { IntegrationEntity integrationEntity = integrationService.getIntegrationById(integrationId); if (integrationEntity == null) { @@ -200,8 +209,8 @@ public List getIntegrationsByWorkspace(Long workspaceId, Long ma } } - List listIntegrationsEntity = - integrationService.getIntegrationByWorkspace(workspaceEntity, managerCode); + List listIntegrationsEntity = integrationService.getIntegrationByWorkspace(workspaceEntity, + managerCode); for (IntegrationEntity integrationEntity : listIntegrationsEntity) { listIntegrationsDto.add(this.transformEntityToDto(integrationEntity)); @@ -211,10 +220,12 @@ public List getIntegrationsByWorkspace(Long workspaceId, Long ma try { - MicroserviceSupplyDto responseCadastre = supplyClient.findSupplyById(integrationDto.getSupplyCadastreId()); + MicroserviceSupplyDto responseCadastre = supplyClient + .findSupplyById(integrationDto.getSupplyCadastreId()); CustomSupplyDto supplyCadastreDto = new CustomSupplyDto(responseCadastre); - supplyCadastreDto.setTypeSupply(providerClient.findTypeSuppleById(supplyCadastreDto.getTypeSupplyCode())); + supplyCadastreDto + .setTypeSupply(providerClient.findTypeSuppleById(supplyCadastreDto.getTypeSupplyCode())); integrationDto.setSupplyCadastre(supplyCadastreDto); MicroserviceSupplyDto responseSnr = supplyClient.findSupplyById(integrationDto.getSupplySnrId()); @@ -223,8 +234,11 @@ public List getIntegrationsByWorkspace(Long workspaceId, Long ma supplySnrDto.setTypeSupply(providerClient.findTypeSuppleById(supplySnrDto.getTypeSupplyCode())); integrationDto.setSupplySnr(supplySnrDto); - } catch (Exception ignored) { - + } catch (Exception e) { + String messageError = String.format("Error consultando los insumos de la integración %d : %s", + integrationDto.getId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -242,6 +256,10 @@ public void deleteIntegration(Long integrationId) throws BusinessException { try { integrationService.deleteIntegration(integrationId); } catch (Exception e) { + String messageError = String.format("Error eliminando la integración %d : %s", integrationId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido eliminar la integración."); } @@ -303,13 +321,17 @@ private IntegrationDto transformEntityToDto(IntegrationEntity integrationEntity) } try { - MunicipalityDto municipalityDto = municipalityBusiness - .getMunicipalityByCode(integrationEntity.getWorkspace().getMunicipality().getCode()); + String municipalityCode = integrationEntity.getWorkspace().getMunicipality().getCode(); + MunicipalityDto municipalityDto = municipalityBusiness.getMunicipalityByCode(municipalityCode); if (municipalityDto != null) { integrationDto.setMunicipalityDto(municipalityDto); } } catch (Exception e) { - log.error("Error consultando municipio: " + e.getMessage()); + String messageError = String.format("Error consultando el municipio %s para la integración %d: %s", + integrationEntity.getWorkspace().getMunicipality().getCode(), integrationDto.getId(), + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return integrationDto; @@ -332,15 +354,17 @@ public List getIntegrationsRunning(MicroserviceManagerDto manage try { - CustomSupplyDto supplyCadastreDto = supplyBusiness - .getSupplyById(integrationDto.getSupplyCadastreId()); - integrationDto.setSupplyCadastre(supplyCadastreDto); + CustomSupplyDto supplyCadastralDto = supplyBusiness.getSupplyById(integrationDto.getSupplyCadastreId()); + integrationDto.setSupplyCadastre(supplyCadastralDto); CustomSupplyDto supplySnrDto = supplyBusiness.getSupplyById(integrationDto.getSupplySnrId()); integrationDto.setSupplySnr(supplySnrDto); } catch (Exception e) { - log.error("Error consultando insumo: " + e.getMessage()); + String messageError = String.format("Error consultando los insumos %d (cadastral) %d (registral) : %s", + integrationDto.getSupplyCadastreId(), integrationDto.getSupplySnrId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -375,11 +399,10 @@ public void configureViewIntegration(Long integrationId, Long managerId) throws "No se puede configurar el geovisor porque la integración esta en un estado inválido."); } - WorkspaceManagerEntity workspaceManagerEntity = - integrationEntity.getWorkspace().getManagers().stream().filter(m -> m.getManagerCode().equals(managerId)).findAny().orElse(null); - if (workspaceManagerEntity == null) { - throw new BusinessException("La integración no pertenece al gestor"); - } + integrationEntity.getWorkspace().getManagers().stream().filter(m -> m.getManagerCode().equals(managerId)) + .findAny().orElseThrow(() -> new BusinessException("La integración no pertenece al gestor")); + + String municipalityCode = integrationEntity.getWorkspace().getMunicipality().getCode(); try { @@ -387,31 +410,57 @@ public void configureViewIntegration(Long integrationId, Long managerId) throws String port = cryptoBusiness.decrypt(integrationEntity.getPort()); String database = cryptoBusiness.decrypt(integrationEntity.getDatabase()); String schema = cryptoBusiness.decrypt(integrationEntity.getSchema()); - String username = cryptoBusiness.decrypt(integrationEntity.getUsername()); - String password = cryptoBusiness.decrypt(integrationEntity.getPassword()); - String nameView = "integration_cat_reg"; - databaseBusiness.createViewIntegration(host, port, database, schema, nameView); + String perimeterView = "perimetros"; + String sideWalkView = "veredas"; + String buildingView = "construcciones"; + String buildingUnitsView = "unidades_construcciones"; + String squareView = "manzanas"; + String parcelsIntegratedView = "predios_integrados"; + + databaseBusiness.createPerimeterView(host, port, database, schema, perimeterView); + databaseBusiness.createSidewalkView(host, port, database, schema, sideWalkView); + databaseBusiness.createBuildingView(host, port, database, schema, buildingView); + databaseBusiness.createBuildingUnitsView(host, port, database, schema, buildingUnitsView); + databaseBusiness.createSquareView(host, port, database, schema, squareView); + databaseBusiness.createParcelIntegratedView(host, port, database, schema, parcelsIntegratedView); MicroserviceSetupMapDto data = new MicroserviceSetupMapDto(); - data.setName_conn(nameView); + data.setName_conn(String.format("connection_%s_%d", municipalityCode, integrationId)); + data.setStore(String.format("store_%s_%d", municipalityCode, integrationId)); + data.setWorkspace(String.format("workspace_%s_%d", municipalityCode, integrationId)); data.setDbname(database); data.setHost(host); - data.setPassword(password); - data.setPort(Integer.parseInt(port)); + data.setPassword(databasePassword); + data.setPort(port); data.setSchema(schema); - data.setUser(username); - data.setLayers(new ArrayList<>(Collections.singletonList(nameView))); + data.setUser(databaseUsername); + List layers = new ArrayList<>(); + layers.add(new MicroserviceSetupMapDto.Layer(perimeterView, "perimetro_urbano", "Perímetros")); + layers.add(new MicroserviceSetupMapDto.Layer(sideWalkView, "vereda", "Veredas")); + layers.add(new MicroserviceSetupMapDto.Layer(buildingView, "construccion_Insumo", "Construcción")); + layers.add(new MicroserviceSetupMapDto.Layer(squareView, "manzana", "Manzanas")); + layers.add(new MicroserviceSetupMapDto.Layer(parcelsIntegratedView, "predio", "Predios Integrados")); + data.setLayers(layers); MicroserviceDataMapDto dataResponse = geovisorClient.setupMap(data); + String[] split = dataResponse.getSt_geocreatefastcontext().split("#"); - log.info("URL: " + dataResponse.getData()); - - String url = dataResponse.getData(); + String url = String.format("#%s", split[1]); updateURLMap(integrationEntity.getId(), url); + } catch (BusinessException e) { + String messageError = String.format("Error configurando el mapa (geo-api) de la integración %d : %s", + integrationId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException(e.getMessage()); } catch (Exception e) { + String messageError = String.format("Error configurando el mapa de la integración %d : %s", integrationId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException( "No se ha podido realizar la configuración de la integración para su visualización."); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationStateBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationStateBusiness.java index e80fae9..a7d00be 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationStateBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/IntegrationStateBusiness.java @@ -5,13 +5,13 @@ @Component public class IntegrationStateBusiness { - public static final Long STATE_STARTED_AUTOMATIC = (long) 1; - public static final Long STATE_FINISHED_AUTOMATIC = (long) 2; - public static final Long STATE_STARTED_ASSISTED = (long) 3; - public static final Long STATE_FINISHED_ASSISTED = (long) 4; - public static final Long STATE_GENERATING_PRODUCT = (long) 5; - public static final Long STATE_GENERATED_PRODUCT = (long) 6; - public static final Long STATE_ERROR_INTEGRATION_AUTOMATIC = (long) 7; - public static final Long STATE_ERROR_GENERATING_PRODUCT = (long) 8; + public static final Long STATE_STARTED_AUTOMATIC = (long) 1; + public static final Long STATE_FINISHED_AUTOMATIC = (long) 2; + public static final Long STATE_STARTED_ASSISTED = (long) 3; + public static final Long STATE_FINISHED_ASSISTED = (long) 4; + public static final Long STATE_GENERATING_PRODUCT = (long) 5; + public static final Long STATE_GENERATED_PRODUCT = (long) 6; + public static final Long STATE_ERROR_INTEGRATION_AUTOMATIC = (long) 7; + public static final Long STATE_ERROR_GENERATING_PRODUCT = (long) 8; } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/ManagerMicroserviceBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/ManagerMicroserviceBusiness.java index a2804c1..4a20d86 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/ManagerMicroserviceBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/ManagerMicroserviceBusiness.java @@ -10,6 +10,7 @@ import com.ai.st.microservice.workspaces.entities.WorkspaceOperatorEntity; import com.ai.st.microservice.workspaces.services.IWorkspaceOperatorService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -29,72 +30,66 @@ public class ManagerMicroserviceBusiness { private final IWorkspaceOperatorService workspaceOperatorService; private final OperatorMicroserviceBusiness operatorBusiness; - public ManagerMicroserviceBusiness(ManagerFeignClient managerClient, IWorkspaceOperatorService workspaceOperatorService, - OperatorMicroserviceBusiness operatorBusiness) { + public ManagerMicroserviceBusiness(ManagerFeignClient managerClient, + IWorkspaceOperatorService workspaceOperatorService, OperatorMicroserviceBusiness operatorBusiness) { this.managerClient = managerClient; this.workspaceOperatorService = workspaceOperatorService; this.operatorBusiness = operatorBusiness; } public MicroserviceManagerDto getManagerById(Long managerId) { - MicroserviceManagerDto managerDto = null; - try { - managerDto = managerClient.findById(managerId); - } catch (Exception e) { - log.error("No se ha podido consultar el gestor: " + e.getMessage()); + String messageError = String.format("Error consultando el gestor %d : %s", managerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - return managerDto; } public MicroserviceManagerDto getManagerByUserCode(Long userCode) { - MicroserviceManagerDto managerDto = null; - try { managerDto = managerClient.findByUserCode(userCode); } catch (Exception e) { - log.error("No se ha podido consultar el gestor: " + e.getMessage()); + String messageError = String.format("Error consultando el gestor por el código de usuario %d : %s", + userCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - return managerDto; } - public List getUserByManager(Long managerId, List profiles) { - + public List getUsersByManager(Long managerId, List profiles) { List users = new ArrayList<>(); - try { users = managerClient.findUsersByManager(managerId, profiles); } catch (Exception e) { - log.error("No se ha podido consultar el gestor: " + e.getMessage()); + String messageError = String.format("Error consultando los usuarios del gestor %d : %s", managerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - return users; } public boolean userManagerIsDirector(Long userCode) { - boolean isDirector = false; - try { - List managerProfiles = managerClient.findProfilesByUser(userCode); - MicroserviceManagerProfileDto profileDirector = managerProfiles.stream() .filter(profileDto -> profileDto.getId().equals(RoleBusiness.SUB_ROLE_DIRECTOR_MANAGER)).findAny() .orElse(null); - if (profileDirector != null) { isDirector = true; } - } catch (FeignException e) { - log.error("No se ha podido verificar si el usuario es un director(gestor): " + e.getMessage()); + String messageError = String.format("Error verificando si el usuario %d es un director(gestor) : %s", + userCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return isDirector; @@ -102,8 +97,8 @@ public boolean userManagerIsDirector(Long userCode) { public List getOperatorsByManager(Long managerCode) { - List workspacesOperators = - workspaceOperatorService.getWorkspacesOperatorsByManagerCode(managerCode); + List workspacesOperators = workspaceOperatorService + .getWorkspacesOperatorsByManagerCode(managerCode); List operatorsId = new ArrayList<>(); diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/NotificationBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/NotificationBusiness.java index e0360b5..2dfa925 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/NotificationBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/NotificationBusiness.java @@ -3,6 +3,7 @@ import com.ai.st.microservice.common.clients.NotifierFeignClient; import com.ai.st.microservice.common.dto.notifier.*; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -21,7 +22,7 @@ public NotificationBusiness(NotifierFeignClient notifierClient) { } public void sendNotificationCreationUser(String email, String password, String profile, String user, - Long userCode) { + Long userCode) { try { @@ -30,20 +31,46 @@ public void sendNotificationCreationUser(String email, String password, String p notification.setPassword(password); notification.setProfile(profile); notification.setStatus(0); - notification.setType("success"); + notification.setType("creationUser"); notification.setUser(user); notification.setUserCode(userCode); notifierClient.creationUser(notification); } catch (Exception e) { - log.error("Error enviando la notificación #1: " + e.getMessage()); + String message = String.format("Error enviando la notificación al crear usuario: %s", e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } - public void sendNotificationMunicipalityManagementDto(String email, String department, String municipality, Date startDate, - Long userCode, String supportFile) { + public void sendNotificationCreationSinicUser(String email, String password, String profile, String user, + Long userCode) { + + try { + + MicroserviceNotificationNewUserDto notification = new MicroserviceNotificationNewUserDto(); + notification.setEmail(email); + notification.setPassword(password); + notification.setProfile(profile); + notification.setStatus(0); + notification.setType("creationSinicUser"); + notification.setUser(user); + notification.setUserCode(userCode); + + notifierClient.creationUser(notification); + + } catch (Exception e) { + String message = String.format("Error enviando la notificación al crear usuario sinic: %s", e.getMessage()); + SCMTracing.sendError(message); + log.error(message); + } + + } + + public void sendNotificationMunicipalityManagementDto(String email, String department, String municipality, + Date startDate, Long userCode, String supportFile) { try { @@ -54,20 +81,23 @@ public void sendNotificationMunicipalityManagementDto(String email, String depar notification.setMpio(municipality); notification.setStartDate(startDate); notification.setStatus(0); - notification.setType("success"); + notification.setType("assignManager"); notification.setUserCode(userCode); notification.setSupportFile(supportFile); notifierClient.municipalityManagement(notification); } catch (Exception e) { - log.error("Error enviando la notificación #2: " + e.getMessage()); + String message = String.format("Error enviando la notificación al asignar un municipio al gestor: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } public void sendNotificationAssignmentOperation(String email, Long userCode, String manager, String municipality, - String department, Date requestDateFrom, Date requestDateTo, String supportFile) { + String department, Date requestDateFrom, Date requestDateTo, String supportFile) { try { @@ -76,7 +106,7 @@ public void sendNotificationAssignmentOperation(String email, Long userCode, Str notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("assignOperator"); notification.setManager(manager); notification.setMpio(municipality); notification.setDpto(department); @@ -88,13 +118,16 @@ public void sendNotificationAssignmentOperation(String email, Long userCode, Str notifierClient.assignmentOperation(notification); } catch (Exception e) { - log.error("Error enviando la notificación #3: " + e.getMessage()); + String message = String.format("Error enviando la notificación al asignar un operador al municipio: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } - public void sendNotificationInputRequest(String email, Long userCode, String manager, String municipality, String department, - String requestNumber, Date requestDate) { + public void sendNotificationInputRequest(String email, Long userCode, String manager, String municipality, + String department, String requestNumber, Date requestDate) { try { @@ -103,7 +136,7 @@ public void sendNotificationInputRequest(String email, Long userCode, String man notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("createSuppliesRequest"); notification.setManager(manager); notification.setMpio(municipality); notification.setDpto(department); @@ -113,13 +146,16 @@ public void sendNotificationInputRequest(String email, Long userCode, String man notifierClient.inputRequest(notification); } catch (Exception e) { - log.error("Error enviando la notificación #4: " + e.getMessage()); + String message = String.format("Error enviando la notificación al crear una solicitud de insumos: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } - public void sendNotificationLoadOfInputs(String email, Long userCode, boolean loadStatus, String municipality, String department, - String requestNumber, Date loadDate, String supportFile) { + public void sendNotificationLoadOfInputs(String email, Long userCode, boolean loadStatus, String municipality, + String department, String requestNumber, Date loadDate, String supportFile) { try { @@ -128,7 +164,7 @@ public void sendNotificationLoadOfInputs(String email, Long userCode, boolean lo notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("loadXTFFileInSuppliesModule"); notification.setLoadStatus(loadStatus); notification.setMpio(municipality); notification.setDpto(department); @@ -139,13 +175,17 @@ public void sendNotificationLoadOfInputs(String email, Long userCode, boolean lo notifierClient.loadOfInputs(notification); } catch (Exception e) { - log.error("Error enviando la notificación #5: " + e.getMessage()); + String message = String.format( + "Error enviando la notificación al cargar un archivo XTF en el módulo de insumos: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } - public void sendNotificationInputIntegrations(String email, Long userCode, String integrationStatus, String municipality, - String department, Date integrationDate) { + public void sendNotificationInputIntegrations(String email, Long userCode, String integrationStatus, + String municipality, String department, Date integrationDate) { try { @@ -154,7 +194,7 @@ public void sendNotificationInputIntegrations(String email, Long userCode, Strin notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("resultIntegration"); notification.setIntegrationStatus(integrationStatus); notification.setMpio(municipality); notification.setDpto(department); @@ -163,13 +203,17 @@ public void sendNotificationInputIntegrations(String email, Long userCode, Strin notifierClient.inputIntegration(notification); } catch (Exception e) { - log.error("Error enviando la notificación #6: " + e.getMessage()); + String message = String.format( + "Error enviando la notificación al finalizar una integración catastro-registro: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } - public void sendNotificationTaskAssignment(String email, Long userCode, String task, String municipality, String department, - Date taskDate) { + public void sendNotificationTaskAssignment(String email, Long userCode, String task, String municipality, + String department, Date taskDate) { try { @@ -178,7 +222,7 @@ public void sendNotificationTaskAssignment(String email, Long userCode, String t notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("taskAssignment"); notification.setTask(task); notification.setMpio(municipality); notification.setDpto(department); @@ -187,13 +231,15 @@ public void sendNotificationTaskAssignment(String email, Long userCode, String t notifierClient.taskAssignment(notification); } catch (Exception e) { - log.error("Error enviando la notificación #7: " + e.getMessage()); + String message = String.format("Error enviando la notificación al crear una tarea: %s", e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } public void sendNotificationProductGenerated(String email, Long userCode, String municipality, String department, - Date requestDate) { + Date requestDate) { try { @@ -202,7 +248,7 @@ public void sendNotificationProductGenerated(String email, Long userCode, String notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("productGeneratedFromIntegration"); notification.setMpio(municipality); notification.setDpto(department); notification.setRequestDate(requestDate); @@ -210,13 +256,16 @@ public void sendNotificationProductGenerated(String email, Long userCode, String notifierClient.productGenerated(notification); } catch (Exception e) { - log.error("Error enviando la notificación #8: " + e.getMessage()); + String message = String.format("Error enviando la notificación al generarse un producto: %s", + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } - public void sendNotificationDeliverySupplies(String email, Long userCode, String manager, String municipality, String department, - String supportFile, Date requestDate) { + public void sendNotificationDeliverySupplies(String email, Long userCode, String manager, String municipality, + String department, String supportFile, Date requestDate) { try { @@ -225,7 +274,7 @@ public void sendNotificationDeliverySupplies(String email, Long userCode, String notification.setEmail(email); notification.setUserCode(userCode); notification.setStatus(0); - notification.setType("success"); + notification.setType("deliveryCreatedForOperator"); notification.setManager(manager); notification.setMpio(municipality); notification.setDpto(department); @@ -235,7 +284,9 @@ public void sendNotificationDeliverySupplies(String email, Long userCode, String notifierClient.deliverySupplies(notification); } catch (Exception e) { - log.error("Error enviando la notificación #9: " + e.getMessage()); + String message = String.format("Error enviando la notificación al crear entrega: %s", e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/OperatorMicroserviceBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/OperatorMicroserviceBusiness.java index f003e6f..427a15a 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/OperatorMicroserviceBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/OperatorMicroserviceBusiness.java @@ -18,6 +18,7 @@ import com.ai.st.microservice.workspaces.entities.MunicipalityEntity; import com.ai.st.microservice.workspaces.services.IMunicipalityService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -48,7 +49,7 @@ public class OperatorMicroserviceBusiness { private SupplyBusiness supplyBusiness; public CustomDeliveryDto createDelivery(Long operatorId, Long managerCode, String municipalityCode, - String observations, List supplies) + String observations, List supplies) throws DisconnectedMicroserviceException { try { @@ -63,17 +64,24 @@ public CustomDeliveryDto createDelivery(Long operatorId, Long managerCode, Strin return new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error creando la entrega: " + e.getMessage()); + String messageError = String.format("Error creando la entrega para el operador %d : %s", operatorId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new DisconnectedMicroserviceException("No se ha podido crear la entrega."); } } public List getDeliveriesByOperator(Long operatorId, String municipalityCode) { try { - List response = operatorClient.findDeliveriesByOperator(operatorId, municipalityCode); + List response = operatorClient.findDeliveriesByOperator(operatorId, + municipalityCode); return response.stream().map(CustomDeliveryDto::new).collect(Collectors.toList()); } catch (Exception e) { - log.error("Error consultando las entregas: " + e.getMessage()); + String messageError = String.format("Error consultando las entregas del operador %d y municipio %s : %s", + operatorId, municipalityCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return new ArrayList<>(); } } @@ -84,7 +92,8 @@ public List getDeliveriesActivesByOperator(Long operatorId) t try { - List deliveriesResponse = operatorClient.findDeliveriesActivesByOperator(operatorId, true); + List deliveriesResponse = operatorClient + .findDeliveriesActivesByOperator(operatorId, true); deliveries = deliveriesResponse.stream().map(CustomDeliveryDto::new).collect(Collectors.toList()); @@ -94,7 +103,10 @@ public List getDeliveriesActivesByOperator(Long operatorId) t MicroserviceManagerDto managerDto = managerClient.findById(deliveryDto.getManagerCode()); deliveryDto.setManager(managerDto); } catch (Exception e) { - log.error("Error consultando gestor: " + e.getMessage()); + String messageError = String.format("Error consultando al gestor %d : %s", + deliveryDto.getManagerCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } try { @@ -107,32 +119,40 @@ public List getDeliveriesActivesByOperator(Long operatorId) t municipalityDto.setName(municipalityEntity.getName()); deliveryDto.setMunicipality(municipalityDto); } catch (Exception e) { - log.error("Error consultando municipio: " + e.getMessage()); + String messageError = String.format("Error consultando al municipio %s : %s", + deliveryDto.getMunicipalityCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - List suppliesResponse = deliveryDto.getSupplies(); - List supplyDeliveriesDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List supplyDeliveriesDto = suppliesResponse.stream() + .map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); for (CustomSupplyDeliveryDto supplyDeliveryDto : supplyDeliveriesDto) { try { - CustomSupplyDto supplyDto = supplyBusiness - .getSupplyById(supplyDeliveryDto.getSupplyCode()); + CustomSupplyDto supplyDto = supplyBusiness.getSupplyById(supplyDeliveryDto.getSupplyCode()); supplyDeliveryDto.setSupply(supplyDto); } catch (Exception e) { - log.error("Error consultando insumo: " + e.getMessage()); + String messageError = String.format("Error consultando el insumo %d : %s", + supplyDeliveryDto.getSupplyCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (supplyDeliveryDto.getDownloadedBy() != null) { try { - MicroserviceUserDto userDto = administrationBusiness.getUserById(supplyDeliveryDto.getDownloadedBy()); + MicroserviceUserDto userDto = administrationBusiness + .getUserById(supplyDeliveryDto.getDownloadedBy()); supplyDeliveryDto.setUserDownloaded(userDto); } catch (Exception e) { - log.error("Error consultando usuario: " + e.getMessage()); + String messageError = String.format("Error consultando el usuario %d : %s", + supplyDeliveryDto.getDownloadedBy(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -143,7 +163,10 @@ public List getDeliveriesActivesByOperator(Long operatorId) t } } catch (Exception e) { - log.error("Error consultando las entregas activas: " + e.getMessage()); + String messageError = String.format("Error consultando las entregas activas del operador %d : %s", + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return deliveries; @@ -154,10 +177,14 @@ public CustomDeliveryDto updateSupplyDeliveredDownloaded(Long deliveryId, Long s MicroserviceUpdateDeliveredSupplyDto supplyDelivered = new MicroserviceUpdateDeliveredSupplyDto(); supplyDelivered.setDownloaded(true); supplyDelivered.setDownloadedBy(userCode); - MicroserviceDeliveryDto response = operatorClient.updateSupplyDelivered(deliveryId, supplyId, supplyDelivered); + MicroserviceDeliveryDto response = operatorClient.updateSupplyDelivered(deliveryId, supplyId, + supplyDelivered); return new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error actualizando la fecha de descarga del insumo: " + e.getMessage()); + String messageError = String.format("Error marcando como descargado el insumo %d de la entrega %d : %s", + supplyId, deliveryId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return null; } } @@ -167,7 +194,9 @@ public CustomDeliveryDto disableDelivery(Long deliveryId) { MicroserviceDeliveryDto response = operatorClient.disableDelivery(deliveryId); return new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error desactivando la entrega: " + e.getMessage()); + String messageError = String.format("Error desactivando la entrega %d : %s", deliveryId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return null; } } @@ -177,7 +206,9 @@ public CustomDeliveryDto getDeliveryId(Long deliveryId) { MicroserviceDeliveryDto response = operatorClient.findDeliveryById(deliveryId); return new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error consultando entrega: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega %d : %s", deliveryId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return null; } } @@ -191,43 +222,40 @@ public MicroserviceOperatorDto getOperatorById(Long operatorId) { operatorDto = operatorClient.findById(operatorId); } catch (Exception e) { - log.error("Error consultando operador: " + e.getMessage()); + String messageError = String.format("Error consultando operador %d : %s", operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return operatorDto; } public MicroserviceOperatorDto addUserToOperator(Long operatorId, Long userCode) { - MicroserviceOperatorDto operatorDto = null; - try { - MicroserviceAddUserToOperatorDto requestAddUser = new MicroserviceAddUserToOperatorDto(); requestAddUser.setOperatorId(operatorId); requestAddUser.setUserCode(userCode); - operatorDto = operatorClient.addUserToOperator(requestAddUser); - } catch (Exception e) { - log.error("Error agregando usuario al operador: " + e.getMessage()); + String messageError = String.format("Error agregando el usuario %d al operador %d : %s", userCode, + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - return operatorDto; } public List getUsersByOperator(Long operatorId) { - List users = new ArrayList<>(); - try { - users = operatorClient.getUsersByOperator(operatorId); - } catch (Exception e) { - log.error("Error consultando usuarios por operador: " + e.getMessage()); + String messageError = String.format("Error consultando los usuarios del operador %d : %s", operatorId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - return users; } @@ -235,10 +263,15 @@ public CustomDeliveryDto updateSupplyDeliveredReportURL(Long deliveryId, Long su try { MicroserviceUpdateDeliveredSupplyDto supplyDelivered = new MicroserviceUpdateDeliveredSupplyDto(); supplyDelivered.setReportUrl(reportUrl); - MicroserviceDeliveryDto response = operatorClient.updateSupplyDelivered(deliveryId, supplyId, supplyDelivered); + MicroserviceDeliveryDto response = operatorClient.updateSupplyDelivered(deliveryId, supplyId, + supplyDelivered); return new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error actualizando la url del reporte de descarga del insumo: " + e.getMessage()); + String messageError = String.format( + "Error actualizando la url del reporte de descarga del insumo %d en la entrega %d: %s", supplyId, + deliveryId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return null; } } @@ -250,7 +283,10 @@ public CustomDeliveryDto updateReportDelivery(Long deliveryId, String reportUrl) MicroserviceDeliveryDto response = operatorClient.updateDelivery(deliveryId, data); return new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error actualizando el reporte de descarga de la entrega: " + e.getMessage()); + String messageError = String.format("Error actualizando el reporte de descarga de la entrega %d: %s", + deliveryId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return null; } } @@ -261,31 +297,26 @@ public List getDeliveriesClosedByOperator(Long operatorId, Lo List deliveries = new ArrayList<>(); try { - String municipalityCode = null; - if (municipalityId != null) { - MunicipalityEntity municipalityEntity = municipalityService.getMunicipalityById(municipalityId); if (municipalityEntity == null) { throw new BusinessException("No se ha encontrado el municipio"); } - municipalityCode = municipalityEntity.getCode(); - } - - List response = operatorClient.findDeliveriesByOperator(operatorId, municipalityCode, false); + List response = operatorClient.findDeliveriesByOperator(operatorId, + municipalityCode, false); deliveries = response.stream().map(CustomDeliveryDto::new).collect(Collectors.toList()); - for (CustomDeliveryDto deliveryDto : deliveries) { - deliveryDto = addInformationDelivery(deliveryDto); - } } catch (Exception e) { - log.error("Error consultando las entregas cerradas: " + e.getMessage()); + String messageError = String.format("Error consultando las entregas cerradas del operador %d : %s", + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return deliveries; @@ -296,22 +327,20 @@ public List getDeliveriesByManager(Long managerId) throws Bus List deliveries = new ArrayList<>(); try { - List response = operatorClient.findDeliveriesByManager(managerId); deliveries = response.stream().map(CustomDeliveryDto::new).collect(Collectors.toList()); - for (CustomDeliveryDto deliveryDto : deliveries) { - deliveryDto = addInformationDelivery(deliveryDto); - } } catch (Exception e) { - log.error("Error consultando las entregas: " + e.getMessage()); + String messageError = String.format("Error consultando las entregas para el gestor %d : %s", managerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return deliveries; - } public CustomDeliveryDto getDeliveryIdAndManager(Long deliveryId, Long managerCode) throws BusinessException { @@ -322,7 +351,10 @@ public CustomDeliveryDto getDeliveryIdAndManager(Long deliveryId, Long managerCo MicroserviceDeliveryDto response = operatorClient.findDeliveryById(deliveryId); deliveryDto = new CustomDeliveryDto(response); } catch (Exception e) { - log.error("Error consultando entrega: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega con id %d para el gestor %d : %s", + deliveryId, managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar la entrega"); } @@ -341,7 +373,10 @@ private CustomDeliveryDto addInformationDelivery(CustomDeliveryDto deliveryDto) MicroserviceManagerDto managerDto = managerClient.findById(deliveryDto.getManagerCode()); deliveryDto.setManager(managerDto); } catch (Exception e) { - log.error("Error consultando gestor: " + e.getMessage()); + String messageError = String.format("Error consultando el gestor %d en la entrega %d: %s", + deliveryDto.getManagerCode(), deliveryDto.getId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } try { @@ -360,12 +395,15 @@ private CustomDeliveryDto addInformationDelivery(CustomDeliveryDto deliveryDto) deliveryDto.setMunicipality(municipalityDto); } catch (Exception e) { - log.error("Error consultando municipio: " + e.getMessage()); + String messageError = String.format("Error consultando el municipio %s en la entrega %d: %s", + deliveryDto.getMunicipalityCode(), deliveryDto.getId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } List suppliesResponse = deliveryDto.getSupplies(); - List supplyDeliveriesDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List supplyDeliveriesDto = suppliesResponse.stream().map(CustomSupplyDeliveryDto::new) + .collect(Collectors.toList()); for (CustomSupplyDeliveryDto supplyDeliveryDto : supplyDeliveriesDto) { @@ -375,15 +413,22 @@ private CustomDeliveryDto addInformationDelivery(CustomDeliveryDto deliveryDto) supplyDeliveryDto.setSupply(supplyDto); } catch (Exception e) { - log.error("Error consultando insumo: " + e.getMessage()); + String messageError = String.format("Error consultando el insumo %d en la entrega %d: %s", + supplyDeliveryDto.getSupplyCode(), supplyDeliveryDto.getId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (supplyDeliveryDto.getDownloadedBy() != null) { try { - MicroserviceUserDto userDto = administrationBusiness.getUserById(supplyDeliveryDto.getDownloadedBy()); + MicroserviceUserDto userDto = administrationBusiness + .getUserById(supplyDeliveryDto.getDownloadedBy()); supplyDeliveryDto.setUserDownloaded(userDto); } catch (Exception e) { - log.error("Error consultando usuario: " + e.getMessage()); + String messageError = String.format("Error consultando el usuario %d en la entrega %d: %s", + supplyDeliveryDto.getDownloadedBy(), supplyDeliveryDto.getId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -399,6 +444,10 @@ public MicroserviceOperatorDto getOperatorByUserCode(Long userCode) { try { operatorDto = operatorClient.findByUserCode(userCode); } catch (Exception e) { + String messageError = String.format("Error consultando el operador a partir del código del usuario %d: %s", + userCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return null; } return operatorDto; diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/ProviderBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/ProviderBusiness.java index bc0e365..fe2f3fa 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/ProviderBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/ProviderBusiness.java @@ -3,7 +3,6 @@ import com.ai.st.microservice.common.clients.ProviderFeignClient; import com.ai.st.microservice.common.clients.TaskFeignClient; import com.ai.st.microservice.common.clients.UserFeignClient; -import com.ai.st.microservice.common.dto.ili.MicroserviceQueryResultRegistralRevisionDto; import com.ai.st.microservice.common.dto.managers.MicroserviceManagerDto; import com.ai.st.microservice.common.dto.providers.*; import com.ai.st.microservice.common.dto.administration.MicroserviceUserDto; @@ -25,6 +24,7 @@ import com.ai.st.microservice.workspaces.entities.DepartmentEntity; import com.ai.st.microservice.workspaces.entities.MunicipalityEntity; import com.ai.st.microservice.workspaces.services.IMunicipalityService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import com.ai.st.microservice.workspaces.utils.FileTool; import com.ai.st.microservice.workspaces.utils.ZipUtil; @@ -84,7 +84,7 @@ public class ProviderBusiness { public static final Long REQUEST_STATE_DELIVERED = (long) 2; public static final Long REQUEST_STATE_CANCELLED = (long) 3; - // Petitions States + // Petition States public static final Long PETITION_STATE_PENDING = (long) 1; public static final Long PETITION_STATE_ACCEPT = (long) 2; public static final Long PETITION_STATE_REJECT = (long) 3; @@ -112,15 +112,15 @@ public class ProviderBusiness { private final IMunicipalityService municipalityService; private final DatabaseIntegrationBusiness databaseIntegrationBusiness; private final CrytpoBusiness cryptoBusiness; - private final FTPBusiness ftpBusiness; private final MunicipalityBusiness municipalityBusiness; private final AdministrationBusiness administrationBusiness; - public ProviderBusiness(ProviderFeignClient providerClient, TaskFeignClient taskClient, SupplyBusiness supplyBusiness, - IliBusiness iliBusiness, FileBusiness fileBusiness, UserFeignClient userClient, - ManagerMicroserviceBusiness managerBusiness, IMunicipalityService municipalityService, - DatabaseIntegrationBusiness databaseIntegrationBusiness, CrytpoBusiness cryptoBusiness, FTPBusiness ftpBusiness, - MunicipalityBusiness municipalityBusiness, AdministrationBusiness administrationBusiness) { + public ProviderBusiness(ProviderFeignClient providerClient, TaskFeignClient taskClient, + SupplyBusiness supplyBusiness, IliBusiness iliBusiness, FileBusiness fileBusiness, + UserFeignClient userClient, ManagerMicroserviceBusiness managerBusiness, + IMunicipalityService municipalityService, DatabaseIntegrationBusiness databaseIntegrationBusiness, + CrytpoBusiness cryptoBusiness, MunicipalityBusiness municipalityBusiness, + AdministrationBusiness administrationBusiness) { this.providerClient = providerClient; this.taskClient = taskClient; this.supplyBusiness = supplyBusiness; @@ -131,14 +131,13 @@ public ProviderBusiness(ProviderFeignClient providerClient, TaskFeignClient task this.municipalityService = municipalityService; this.databaseIntegrationBusiness = databaseIntegrationBusiness; this.cryptoBusiness = cryptoBusiness; - this.ftpBusiness = ftpBusiness; this.municipalityBusiness = municipalityBusiness; this.administrationBusiness = administrationBusiness; } public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean skipErrors, String justification, - MultipartFile[] files, MultipartFile extraFile, String url, MicroserviceProviderDto providerDto, Long userCode, String observations) - throws BusinessException { + MultipartFile[] files, MultipartFile extraFile, String url, MicroserviceProviderDto providerDto, + Long userCode, String observations) throws BusinessException { CustomRequestDto requestUpdatedDto; @@ -169,8 +168,8 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean } List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestDto = suppliesResponse.stream().map(CustomSupplyRequestedDto::new) + .collect(Collectors.toList()); CustomSupplyRequestedDto supplyRequested = suppliesRequestDto.stream() .filter(sR -> sR.getTypeSupply().getId().equals(typeSupplyId)).findAny().orElse(null); @@ -196,12 +195,13 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean Collections.singletonList(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)); List responseTasksDto = taskClient.findByStateAndCategory(taskStates, taskCategories); - List tasksDto = responseTasksDto.stream().map(CustomTaskDto::new).collect(Collectors.toList()); + List tasksDto = responseTasksDto.stream().map(CustomTaskDto::new) + .collect(Collectors.toList()); for (CustomTaskDto taskDto : tasksDto) { MicroserviceTaskMetadataDto metadataRequest = taskDto.getMetadata().stream() .filter(meta -> meta.getKey().equalsIgnoreCase("request")).findAny().orElse(null); - if (metadataRequest instanceof MicroserviceTaskMetadataDto) { + if (metadataRequest != null) { MicroserviceTaskMetadataPropertyDto propertyRequest = metadataRequest.getProperties().stream() .filter(p -> p.getKey().equalsIgnoreCase("requestId")).findAny().orElse(null); @@ -217,12 +217,12 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean if (metaRequestId.equals(requestId) && metaTypeSupplyId.equals(typeSupplyId)) { List responseMembers = taskDto.getMembers(); - List membersDto = - responseMembers.stream().map(CustomTaskMemberDto::new).collect(Collectors.toList()); + List membersDto = responseMembers.stream() + .map(CustomTaskMemberDto::new).collect(Collectors.toList()); CustomTaskMemberDto memberDto = membersDto.stream() .filter(m -> m.getMemberCode().equals(userCode)).findAny().orElse(null); - if (!(memberDto instanceof CustomTaskMemberDto)) { + if (memberDto == null) { throw new BusinessException( "No es posible cargar el insumo, la tarea está asignada a otro usuario."); } @@ -232,7 +232,10 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean } } catch (Exception e) { - log.error("No se ha podido consultar si la tarea esta asociada al cargue de insumo: " + e.getMessage()); + String messageError = String.format("Error verificando si la tarea esta asociada al cargue de insumo : %s", + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (supplyRequested.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_VALIDATING)) { @@ -321,7 +324,8 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean if (loadedFileExtension.equalsIgnoreCase("zip")) { if (!isLoadShp && !isLoadGdb) { - List extensionsAllowed = extensionAllowed.stream().map(MicroserviceExtensionDto::getName).collect(Collectors.toList()); + List extensionsAllowed = extensionAllowed.stream() + .map(MicroserviceExtensionDto::getName).collect(Collectors.toList()); fileAllowed = ZipUtil.zipContainsFile(filePathTemporal, extensionsAllowed); loadedFileExtensions = ZipUtil.getExtensionsFromZip(filePathTemporal); @@ -333,7 +337,7 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean MicroserviceExtensionDto extensionDto = extensionAllowed.stream() .filter(ext -> ext.getName().equalsIgnoreCase(loadedFileExtension)).findAny() .orElse(null); - fileAllowed = extensionDto instanceof MicroserviceExtensionDto; + fileAllowed = extensionDto != null; loadedFileExtensions.add(loadedFileExtension); zipFile = true; } @@ -348,7 +352,11 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean try { FileUtils.deleteQuietly(new File(filePathTemporal)); } catch (Exception e) { - log.error("No se ha podido eliminar el archivo temporal: " + e.getMessage()); + String messageError = String.format( + "Error eliminando el archivo temporal %s de la solicitud %d: %s", filePathTemporal, + requestId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } // save file @@ -357,10 +365,10 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean if (!supplyExtension.isEmpty()) { supplyRequestedStateId = ProviderBusiness.SUPPLY_REQUESTED_STATE_VALIDATING; - // validate xtf with ilivalidator + // validate xtf with ili validator iliBusiness.startValidation(requestId, observations, urlDocumentaryRepository, - supplyRequested.getId(), userCode, supplyRequested.getModelVersion(), - false, skipErrors); + supplyRequested.getId(), userCode, supplyRequested.getModelVersion(), false, + skipErrors); updateSupply.setUrl(null); updateSupply.setFtp(null); @@ -395,12 +403,14 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean updateSupply.setJustification(justification); updateSupply.setExtraFile(urlExtraFileSaved); - MicroserviceRequestDto responseRequestDto = providerClient.updateSupplyRequested(requestId, supplyRequested.getId(), updateSupply); + MicroserviceRequestDto responseRequestDto = providerClient.updateSupplyRequested(requestId, + supplyRequested.getId(), updateSupply); requestUpdatedDto = new CustomRequestDto(responseRequestDto); - List suppliesResponseDto = requestUpdatedDto.getSuppliesRequested(); - List suppliesRequestedDto = - suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesResponseDto = requestUpdatedDto + .getSuppliesRequested(); + List suppliesRequestedDto = suppliesResponseDto.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); for (CustomSupplyRequestedDto supply : suppliesRequestedDto) { if (supply.getDeliveredBy() != null) { @@ -408,12 +418,21 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean MicroserviceUserDto userDto = userClient.findById(supply.getDeliveredBy()); supply.setUserDeliveryBy(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + supply.getDeliveredBy(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); supply.setUserDeliveryBy(null); } } } } catch (Exception e) { + String messageError = String.format( + "Error actualizando la información de la solicitud %d por el usuario %d: %s", requestId, userCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido actualizar la información de la solicitud."); } @@ -423,7 +442,6 @@ public CustomRequestDto answerRequest(Long requestId, Long typeSupplyId, Boolean public CustomRequestDto closeRequest(Long requestId, MicroserviceProviderDto providerDto, Long userCode) throws BusinessException { - MicroserviceRequestDto response = providerClient.findRequestById(requestId); CustomRequestDto requestDto = new CustomRequestDto(response); @@ -443,14 +461,14 @@ public CustomRequestDto closeRequest(Long requestId, MicroserviceProviderDto pro } List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestDto = suppliesResponse.stream().map(CustomSupplyRequestedDto::new) + .collect(Collectors.toList()); boolean canClose = false; for (CustomSupplyRequestedDto supplyRequested : suppliesRequestDto) { if (!supplyRequested.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED) && !supplyRequested.getState().getId() - .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_UNDELIVERED)) { + .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_UNDELIVERED)) { throw new BusinessException( "No se puede cerrar la solicitud porque no se han cargado todos los insumos."); } @@ -465,214 +483,154 @@ public CustomRequestDto closeRequest(Long requestId, MicroserviceProviderDto pro "No se puede cerrar la solicitud porque el usuario no es la persona que ha cargado los insumos."); } - boolean sendToReview = false; - CustomSupplyRequestedDto supplyRegistral = null; - if (requestDto.getProvider().getId().equals(ProviderBusiness.PROVIDER_SNR_ID)) { - - List suppliesResponseDto = requestDto.getSuppliesRequested(); - List suppliesRequestedDto = - suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); - - supplyRegistral = suppliesRequestedDto.stream() - .filter(sR -> sR.getTypeSupply().getId().equals(ProviderBusiness.PROVIDER_SNR_SUPPLY_REGISTRAL)) - .findAny().orElse(null); - sendToReview = (supplyRegistral != null); - } - CustomRequestDto requestUpdatedDto; - if (sendToReview) { - - for (CustomSupplyRequestedDto supplyRequested : suppliesRequestDto) { - if (supplyRequested.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_UNDELIVERED)) { - - try { - MicroserviceRequestDto responseUpdateDto = providerClient.closeRequest(requestId, userCode); - return new CustomRequestDto(responseUpdateDto); - } catch (Exception e) { - throw new BusinessException("No se ha podido actualizar la información de la solicitud."); - } - - } - } - - // Update supply requested - try { - - MicroserviceUpdateSupplyRequestedDto updateSupply = new MicroserviceUpdateSupplyRequestedDto(); - updateSupply.setDelivered(null); - updateSupply.setDeliveryBy(null); - updateSupply.setSupplyRequestedStateId(ProviderBusiness.SUPPLY_REQUESTED_STATE_PENDING_REVIEW); - updateSupply.setJustification(null); - - MicroserviceRequestDto updateResponseDto = providerClient.updateSupplyRequested(requestId, supplyRegistral.getId(), updateSupply); - requestUpdatedDto = new CustomRequestDto(updateResponseDto); - - List suppliesUpdateResponse = requestUpdatedDto.getSuppliesRequested(); - List suppliesRequestedUpdateDto = - suppliesUpdateResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); - - for (CustomSupplyRequestedDto supply : suppliesRequestedUpdateDto) { - if (supply.getDeliveredBy() != null) { - try { - MicroserviceUserDto userDto = userClient.findById(supply.getDeliveredBy()); - supply.setUserDeliveryBy(userDto); - } catch (Exception e) { - supply.setUserDeliveryBy(null); - } - } - } - - } catch (Exception e) { - throw new BusinessException("No se ha podido actualizar la información de la solicitud."); - } - - } else { - - try { - - List suppliesResponseDto = requestDto.getSuppliesRequested(); - List suppliesRequestedDto = - suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + try { - for (CustomSupplyRequestedDto supplyRequested : suppliesRequestedDto) { + List suppliesResponseDto = requestDto.getSuppliesRequested(); + List suppliesRequestedDto = suppliesResponseDto.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); - // verify if the supply is assigned to a task - List taskStates = new ArrayList<>( - Arrays.asList(TaskBusiness.TASK_STATE_STARTED, TaskBusiness.TASK_STATE_ASSIGNED)); - List taskCategories = new ArrayList<>( - Collections.singletonList(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)); + for (CustomSupplyRequestedDto supplyRequested : suppliesRequestedDto) { - List responseTasksDto = taskClient.findByStateAndCategory(taskStates, taskCategories); - List tasksDto = responseTasksDto.stream().map(CustomTaskDto::new).collect(Collectors.toList()); + // verify if the supply is assigned to a task + List taskStates = new ArrayList<>( + Arrays.asList(TaskBusiness.TASK_STATE_STARTED, TaskBusiness.TASK_STATE_ASSIGNED)); + List taskCategories = new ArrayList<>( + Collections.singletonList(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)); - for (CustomTaskDto taskDto : tasksDto) { - MicroserviceTaskMetadataDto metadataRequest = taskDto.getMetadata().stream() - .filter(meta -> meta.getKey().equalsIgnoreCase("request")).findAny().orElse(null); - if (metadataRequest != null) { + List responseTasksDto = taskClient.findByStateAndCategory(taskStates, + taskCategories); + List tasksDto = responseTasksDto.stream().map(CustomTaskDto::new) + .collect(Collectors.toList()); - MicroserviceTaskMetadataPropertyDto propertyRequest = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("requestId")).findAny() - .orElse(null); + for (CustomTaskDto taskDto : tasksDto) { + MicroserviceTaskMetadataDto metadataRequest = taskDto.getMetadata().stream() + .filter(meta -> meta.getKey().equalsIgnoreCase("request")).findAny().orElse(null); + if (metadataRequest != null) { - MicroserviceTaskMetadataPropertyDto propertyTypeSupply = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("typeSupplyId")).findAny() - .orElse(null); + MicroserviceTaskMetadataPropertyDto propertyRequest = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("requestId")).findAny().orElse(null); - if (propertyRequest != null && propertyTypeSupply != null) { + MicroserviceTaskMetadataPropertyDto propertyTypeSupply = metadataRequest.getProperties() + .stream().filter(p -> p.getKey().equalsIgnoreCase("typeSupplyId")).findAny() + .orElse(null); - Long taskRequestId = Long.parseLong(propertyRequest.getValue()); - Long taskTypeSupplyId = Long.parseLong(propertyTypeSupply.getValue()); + if (propertyRequest != null && propertyTypeSupply != null) { - if (taskRequestId.equals(requestId) - && taskTypeSupplyId.equals(supplyRequested.getTypeSupply().getId())) { + Long taskRequestId = Long.parseLong(propertyRequest.getValue()); + Long taskTypeSupplyId = Long.parseLong(propertyTypeSupply.getValue()); - Long supplyRequestedState = supplyRequested.getState().getId(); + if (taskRequestId.equals(requestId) + && taskTypeSupplyId.equals(supplyRequested.getTypeSupply().getId())) { - if (supplyRequestedState.equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED)) { - taskClient.closeTask(taskDto.getId()); - } else if (supplyRequestedState - .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_UNDELIVERED)) { - MicroserviceCancelTaskDto cancelTaskDto = new MicroserviceCancelTaskDto(); - cancelTaskDto.setReason("Cancelada por el sistema."); - taskClient.cancelTask(taskDto.getId(), cancelTaskDto); - } + Long supplyRequestedState = supplyRequested.getState().getId(); + if (supplyRequestedState.equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED)) { + taskClient.closeTask(taskDto.getId()); + } else if (supplyRequestedState + .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_UNDELIVERED)) { + MicroserviceCancelTaskDto cancelTaskDto = new MicroserviceCancelTaskDto(); + cancelTaskDto.setReason("Cancelada por el sistema."); + taskClient.cancelTask(taskDto.getId(), cancelTaskDto); } } + } } - } - } catch (Exception e) { - log.error("Ha ocurrido un error intentando cerrar las tareas asociadas a la solicitud"); } - try { - - List suppliesResponseDto = requestDto.getSuppliesRequested(); - List suppliesRequestedDto = - suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + } catch (Exception e) { + String messageError = String.format("Error cerrando las tareas asociadas a la solicitud %d : %s", requestId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + } - for (CustomSupplyRequestedDto supplyRequested : suppliesRequestedDto) { + try { - if (supplyRequested.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED)) { + List suppliesResponseDto = requestDto.getSuppliesRequested(); + List suppliesRequestedDto = suppliesResponseDto.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); - List attachments = new ArrayList<>(); + for (CustomSupplyRequestedDto supplyRequested : suppliesRequestedDto) { + if (supplyRequested.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED)) { - if (supplyRequested.getTypeSupply().getId().equals(ProviderBusiness.PROVIDER_SUPPLY_CADASTRAL)) { - List supplyFiles = new ArrayList<>(Collections.singletonList(new File(supplyRequested.getUrl()))); - if (supplyRequested.getLog() != null) { - supplyFiles.add(new File(supplyRequested.getLog())); - } - if (supplyRequested.getExtraFile() != null) { - supplyFiles.add(new File(supplyRequested.getExtraFile())); - } - String zipName = "insumo_" + RandomStringUtils.random(10, false, true); - String namespace = stFilesDirectory + "/" + requestDto.getMunicipalityCode().replace(" ", "_") - + "/insumos/proveedores/" + providerDto.getName().replace(" ", "_") + "/" - + supplyRequested.getTypeSupply().getName().replace(" ", "_"); + List attachments = new ArrayList<>(); - String pathSupplyFile = ZipUtil.zipping(supplyFiles, zipName, FileTool.removeAccents(namespace)); + if (supplyRequested.getTypeSupply().getId().equals(ProviderBusiness.PROVIDER_SUPPLY_CADASTRAL)) { + List supplyFiles = new ArrayList<>( + Collections.singletonList(new File(supplyRequested.getUrl()))); + if (supplyRequested.getLog() != null) { + supplyFiles.add(new File(supplyRequested.getLog())); + } + if (supplyRequested.getExtraFile() != null) { + supplyFiles.add(new File(supplyRequested.getExtraFile())); + } + String zipName = "insumo_" + RandomStringUtils.random(10, false, true); + String namespace = stFilesDirectory + "/" + requestDto.getMunicipalityCode().replace(" ", "_") + + "/insumos/proveedores/" + providerDto.getName().replace(" ", "_") + "/" + + supplyRequested.getTypeSupply().getName().replace(" ", "_"); - attachments.add(new MicroserviceCreateSupplyAttachmentDto(pathSupplyFile, - SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY)); - } else { + String pathSupplyFile = ZipUtil.zipping(supplyFiles, zipName, + FileTool.removeAccents(namespace)); - if (supplyRequested.getUrl() != null) { - attachments.add(new MicroserviceCreateSupplyAttachmentDto(supplyRequested.getUrl(), - SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY)); - } - if (supplyRequested.getFtp() != null) { - attachments.add(new MicroserviceCreateSupplyAttachmentDto(supplyRequested.getFtp(), - SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_FTP)); - } + attachments.add(new MicroserviceCreateSupplyAttachmentDto(pathSupplyFile, + SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY)); + } else { + if (supplyRequested.getUrl() != null) { + attachments.add(new MicroserviceCreateSupplyAttachmentDto(supplyRequested.getUrl(), + SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY)); + } + if (supplyRequested.getFtp() != null) { + attachments.add(new MicroserviceCreateSupplyAttachmentDto(supplyRequested.getFtp(), + SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_FTP)); } - List emittersResponse = requestDto.getEmitters(); - List emittersDto = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); + } - CustomEmitterDto emitterDto = emittersDto.stream(). - filter(e -> e.getEmitterType().equalsIgnoreCase("ENTITY")).findAny().orElse(null); + List emittersResponse = requestDto.getEmitters(); + List emittersDto = emittersResponse.stream().map(CustomEmitterDto::new) + .collect(Collectors.toList()); - supplyBusiness.createSupply(requestDto.getMunicipalityCode(), supplyRequested.getObservations(), - supplyRequested.getTypeSupply().getId(), emitterDto.getEmitterCode(), attachments, requestId, userCode, - providerDto.getId(), null, null, supplyRequested.getModelVersion(), - SupplyBusiness.SUPPLY_STATE_ACTIVE, supplyRequested.getTypeSupply().getName(), supplyRequested.getValid()); - } + CustomEmitterDto emitterDto = emittersDto.stream() + .filter(e -> e.getEmitterType().equalsIgnoreCase("ENTITY")).findAny().orElse(null); + supplyBusiness.createSupply(requestDto.getMunicipalityCode(), supplyRequested.getObservations(), + supplyRequested.getTypeSupply().getId(), emitterDto.getEmitterCode(), attachments, + requestId, userCode, providerDto.getId(), null, null, supplyRequested.getModelVersion(), + SupplyBusiness.SUPPLY_STATE_ACTIVE, supplyRequested.getTypeSupply().getName(), + supplyRequested.getValid()); } - } catch (Exception e) { - log.error("No se ha podido crear los insumos: " + e.getMessage()); - throw new BusinessException("No se ha podido disponer los insumos al municipio."); - } - - try { - MicroserviceRequestDto responseUpdateDto = providerClient.closeRequest(requestId, userCode); - requestUpdatedDto = new CustomRequestDto(responseUpdateDto); - } catch (Exception e) { - throw new BusinessException("No se ha podido actualizar la información de la solicitud."); } + } catch (Exception e) { + String messageError = String.format( + "Error creando los insumos para el municipio %s al cerrar la solicitud %d : %s", + requestDto.getMunicipalityCode(), requestId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido disponer los insumos al municipio."); } - return requestUpdatedDto; - } - - public CustomRequestDto closeRequest(Long requestId, Long userCode) { try { - MicroserviceRequestDto response = providerClient.closeRequest(requestId, userCode); - return new CustomRequestDto(response); + MicroserviceRequestDto responseUpdateDto = providerClient.closeRequest(requestId, userCode); + requestUpdatedDto = new CustomRequestDto(responseUpdateDto); } catch (Exception e) { - log.error("Error cerrando solicitud: " + e.getMessage()); - return null; + String messageError = String.format("Error cerrando la solicitud %d por el usuario %d : %s", requestId, + userCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido cerrar la solicitud."); } + + return requestUpdatedDto; } public List getUsersByProvider(Long providerId, List profiles) @@ -689,9 +647,11 @@ public List getUsersByProvider(Long providerId, Lis } } catch (BusinessException e) { - String message = "No se han podido obtener los usuarios del proveedor."; - this.log.error(message + ": " + e.getMessage()); - throw new BusinessException(message); + String messageError = String.format("Error consultando los usuarios que pertenecen al proveedor %d : %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + throw new BusinessException("No se ha podido consultar los usuarios que pertenecen al proveedor."); } return usersDto; @@ -702,13 +662,16 @@ public List getRequestsByEmittersManager(Long managerCode) thr List response = providerClient.findRequestsByEmmiters(managerCode, "ENTITY"); return response.stream().map(CustomRequestDto::new).collect(Collectors.toList()); } catch (Exception e) { - log.error("Error consultando solicitudes: " + e.getMessage()); + String messageError = String.format("Error consultando las solicitudes hechas por el gestor %d : %s", + managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); return new ArrayList<>(); } } public MicroserviceRequestPaginatedDto getRequestsByManagerAndMunicipality(int page, Long managerCode, - String municipalityCode) throws BusinessException { + String municipalityCode) throws BusinessException { MicroserviceRequestPaginatedDto data; @@ -724,10 +687,18 @@ public MicroserviceRequestPaginatedDto getRequestsByManagerAndMunicipality(int p } } catch (BusinessException e) { - log.error("Error consultando solicitudes por gestor y municipio: " + e.getMessage()); + String messageError = String.format( + "Error consultando las solicitudes hechas por el gestor %d para el municipio %s : %s", managerCode, + municipalityCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error consultando solicitudes por gestor y municipio: " + e.getMessage()); + String messageError = String.format( + "Error consultando las solicitudes hechas por el gestor %d para el municipio %s : %s", managerCode, + municipalityCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar las solicitudes que el gestor ha realizado."); } @@ -748,7 +719,10 @@ public List getRequestsByPackage(String packageLabel) { } } catch (Exception e) { - log.error("Error consultando solicitudes por paquete: " + e.getMessage()); + String messageError = String.format("Error consultando las solicitudes a partir del paquete/orden %s : %s", + packageLabel, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return requestsDto; @@ -776,10 +750,18 @@ public MicroserviceRequestPaginatedDto getRequestsByManagerAndProvider(int page, data.setItems(all); } catch (BusinessException e) { - log.error("Error consultando solicitudes por gestor y proveedor: " + e.getMessage()); + String messageError = String.format( + "Error consultando las solicitudes hechas por el gestor %d para el proveedor %d : %s", managerCode, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error consultando solicitudes por gestor y proveedor: " + e.getMessage()); + String messageError = String.format( + "Error consultando las solicitudes hechas por el gestor %d para el proveedor %d : %s", managerCode, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar las solicitudes que el gestor ha realizado."); } @@ -822,7 +804,7 @@ public List getRequestsByManagerAndPackage(Long managerCode, RequestPackageDto packageFound = packages.stream() .filter(p -> p.getPackageLabel().equals(packageRequest)).findAny().orElse(null); - if (packageFound instanceof RequestPackageDto) { + if (packageFound != null) { packageFound.getRequests().add(requestDto); } @@ -831,10 +813,17 @@ public List getRequestsByManagerAndPackage(Long managerCode, } } catch (BusinessException e) { - log.error("Error consultando solicitudes por gestor y proveedor: " + e.getMessage()); + String messageError = String.format( + "Error consultando las solicitudes hechas por el gestor %d a partir del paquete %s : %s", + managerCode, packageLabel, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error consultando solicitudes por gestor y proveedor: " + e.getMessage()); + String messageError = String.format( + "Error consultando las solicitudes hechas por el gestor %d a partir del paquete %s : %s", + managerCode, packageLabel, e.getMessage()); + SCMTracing.sendError(messageError); throw new BusinessException("No se ha podido consultar las solicitudes que el gestor ha realizado."); } @@ -846,8 +835,8 @@ public CustomRequestDto completeInformationRequest(CustomRequestDto requestDto) List emittersDto = new ArrayList<>(); List emittersResponse = requestDto.getEmitters(); - List emitterListDto = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); + List emitterListDto = emittersResponse.stream().map(CustomEmitterDto::new) + .collect(Collectors.toList()); for (CustomEmitterDto emitterDto : emitterListDto) { if (emitterDto.getEmitterType().equals("ENTITY")) { @@ -855,6 +844,10 @@ public CustomRequestDto completeInformationRequest(CustomRequestDto requestDto) MicroserviceManagerDto managerDto = managerBusiness.getManagerById(emitterDto.getEmitterCode()); emitterDto.setUser(managerDto); } catch (Exception e) { + String messageError = String.format("Error consultando el gestor %d : %s", + emitterDto.getEmitterCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); emitterDto.setUser(null); } } else { @@ -862,6 +855,10 @@ public CustomRequestDto completeInformationRequest(CustomRequestDto requestDto) MicroserviceUserDto userDto = administrationBusiness.getUserById(emitterDto.getEmitterCode()); emitterDto.setUser(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + emitterDto.getEmitterCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); emitterDto.setUser(null); } } @@ -886,8 +883,8 @@ public CustomRequestDto completeInformationRequest(CustomRequestDto requestDto) } List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestDto = suppliesResponse.stream().map(CustomSupplyRequestedDto::new) + .collect(Collectors.toList()); for (CustomSupplyRequestedDto supply : suppliesRequestDto) { @@ -898,6 +895,10 @@ public CustomRequestDto completeInformationRequest(CustomRequestDto requestDto) MicroserviceUserDto userDto = administrationBusiness.getUserById(supply.getDeliveredBy()); supply.setUserDeliveryBy(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", supply.getDeliveredBy(), + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); supply.setUserDeliveryBy(null); } @@ -915,7 +916,9 @@ public MicroserviceProviderDto getProviderById(Long providerId) { try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("No se podido consultar el proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d : %s", providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return providerDto; @@ -935,10 +938,16 @@ public MicroserviceProviderProfileDto createProfile(Long providerId, String name profileDto = providerClient.createProfile(providerId, createProviderProfileDto); } catch (BusinessException e) { - log.error("Error creando perfil del proveedor: " + e.getMessage()); + String messageError = String.format("Error creando el perfil para el proveedor %d: %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error creando perfil del proveedor: " + e.getMessage()); + String messageError = String.format("Error creando el perfil para el proveedor %d: %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido crear el perfil del proveedor"); } @@ -954,10 +963,16 @@ public List getProfilesByProvider(Long providerI profilesDto = providerClient.getProfilesByProvider(providerId); } catch (BusinessException e) { - log.error("Error consultando perfiles del proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando los perfiles para el proveedor %d: %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error consultando perfiles del proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando los perfiles para el proveedor %d: %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar los perfiles del proveedor"); } @@ -965,7 +980,7 @@ public List getProfilesByProvider(Long providerI } public MicroserviceProviderProfileDto updateProfile(Long providerId, Long profileId, String name, - String description) throws BusinessException { + String description) throws BusinessException { MicroserviceProviderProfileDto profileDto; @@ -978,10 +993,16 @@ public MicroserviceProviderProfileDto updateProfile(Long providerId, Long profil profileDto = providerClient.updateProfile(providerId, profileId, createProviderProfileDto); } catch (BusinessException e) { - log.error("Error editando perfil del proveedor: " + e.getMessage()); + String messageError = String.format("Error editando el perfil %d para el proveedor %d: %s", profileId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error editando perfil del proveedor: " + e.getMessage()); + String messageError = String.format("Error editando el perfil %d para el proveedor %d: %s", profileId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido editar el perfil del proveedor"); } @@ -995,16 +1016,22 @@ public void deleteProfile(Long providerId, Long profileId) throws BusinessExcept providerClient.deleteProfile(providerId, profileId); } catch (BusinessException e) { - log.error("Error eliminando perfil del proveedor: " + e.getMessage()); + String messageError = String.format("Error eliminando el perfil %d para el proveedor %d: %s", profileId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error eliminando perfil del proveedor: " + e.getMessage()); + String messageError = String.format("Error eliminando el perfil %d para el proveedor %d: %s", profileId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido eliminar el perfil del proveedor"); } } public MicroserviceTypeSupplyDto createTypeSupply(Long providerId, String name, String description, - Boolean metadataRequired, Boolean modelRequired, Long profileId, List extensions) + Boolean metadataRequired, Boolean modelRequired, Long profileId, List extensions) throws BusinessException { MicroserviceTypeSupplyDto typeSupplyDto; @@ -1022,10 +1049,16 @@ public MicroserviceTypeSupplyDto createTypeSupply(Long providerId, String name, typeSupplyDto = providerClient.createTypeSupplies(providerId, create); } catch (BusinessException e) { - log.error("Error creando tipo de insumo para el proveedor: " + e.getMessage()); + String messageError = String.format("Error creando el tipo de insumos para el proveedor %d: %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error creando tipo de insumo para el proveedor: " + e.getMessage()); + String messageError = String.format("Error creando el tipo de insumos para el proveedor %d: %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido crear el tipo de insumo para el proveedor"); } @@ -1037,14 +1070,18 @@ public List getTypesSuppliesByProvider(Long providerI List typesSuppliesDto; try { - typesSuppliesDto = providerClient.getTypesSuppliesByProvider(providerId); - } catch (BusinessException e) { - log.error("Error consultando tipos de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando los tipos de insumos para el proveedor %d: %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error consultando tipos de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando los tipos de insumos para el proveedor %d: %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar los tipos de insumo del proveedor"); } @@ -1052,8 +1089,8 @@ public List getTypesSuppliesByProvider(Long providerI } public MicroserviceTypeSupplyDto updateTypeSupply(Long providerId, Long typeSupplyId, String name, - String description, Boolean metadataRequired, Boolean modelRequired, Long profileId, - List extensions) throws BusinessException { + String description, Boolean metadataRequired, Boolean modelRequired, Long profileId, + List extensions) throws BusinessException { MicroserviceTypeSupplyDto typeSupplyDto; @@ -1070,10 +1107,16 @@ public MicroserviceTypeSupplyDto updateTypeSupply(Long providerId, Long typeSupp typeSupplyDto = providerClient.updateTypeSupplies(providerId, typeSupplyId, data); } catch (BusinessException e) { - log.error("Error editando tipo de insumo para el proveedor: " + e.getMessage()); + String messageError = String.format("Error editando el tipo de insumo %d para el proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error editando tipo de insumo para el proveedor: " + e.getMessage()); + String messageError = String.format("Error editando el tipo de insumo %d para el proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido editar el tipo de insumo para el proveedor"); } @@ -1081,30 +1124,34 @@ public MicroserviceTypeSupplyDto updateTypeSupply(Long providerId, Long typeSupp } public void deleteTypeSupply(Long providerId, Long typeSupplyId) throws BusinessException { - try { - providerClient.deleteTypeSupply(providerId, typeSupplyId); - } catch (BusinessException e) { - log.error("Error eliminando tipo de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error eliminando el tipo de insumo %d para el proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error eliminando tipo de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error eliminando el tipo de insumo %d para el proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido eliminar el tipo de insumo del proveedor"); } } public MicroserviceProviderDto getProviderByUserAdministrator(Long userCode) { - MicroserviceProviderDto providerDto = null; - try { providerDto = providerClient.findProviderByAdministrator(userCode); } catch (Exception e) { - log.error("No se ha podido consultar el proveedor: " + e.getMessage()); + String message = String.format( + "No se ha podido consultar el proveedor a partir de usuario (administrador) %d: %s", userCode, + e.getMessage()); + SCMTracing.sendError(message); + log.error(message); } - return providerDto; } @@ -1115,7 +1162,11 @@ public MicroserviceProviderDto getProviderByUserTechnical(Long userCode) { try { providerDto = providerClient.findByUserCode(userCode); } catch (Exception e) { - log.error("No se ha podido consultar el proveedor: " + e.getMessage()); + String messageError = String.format( + "Error consultando el proveedor a partir del usuario (technical) %d : %s", userCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return providerDto; @@ -1150,501 +1201,16 @@ public boolean userProviderIsDirector(Long userCode) { } } catch (Exception e) { - log.error("No se ha podido verificar si el usuario es un director(proveedor): " + e.getMessage()); + String messageError = String.format( + "Error verificando si el usuario %d es un director (proveedor de insumos) : %s", userCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return isDirector; } - public boolean userProviderIsDelegate(Long userCode) { - - boolean isDelegate = false; - - try { - - List providerRoles = providerClient.findRolesByUser(userCode); - - MicroserviceProviderRoleDto roleDirector = providerRoles.stream() - .filter(roleDto -> roleDto.getId().equals(RoleBusiness.SUB_ROLE_DELEGATE_PROVIDER)).findAny() - .orElse(null); - - if (roleDirector != null) { - isDelegate = true; - } - - } catch (Exception e) { - log.error("No se ha podido verificar si el usuario es un delegado(proveedor): " + e.getMessage()); - } - - return isDelegate; - } - - public List getSuppliesToReview(Long providerId) { - - List all = new ArrayList<>(); - - try { - - List suppliesRequestedDto = new ArrayList<>(); - - List states = new ArrayList<>(Arrays.asList(ProviderBusiness.SUPPLY_REQUESTED_STATE_PENDING_REVIEW, - ProviderBusiness.SUPPLY_REQUESTED_STATE_SETTING_REVIEW, - ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW, - ProviderBusiness.SUPPLY_REQUESTED_STATE_CLOSING_REVIEW)); - - List response = providerClient.getSuppliesRequestedToReview(providerId, states); - suppliesRequestedDto = response.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); - - - for (CustomSupplyRequestedDto sR : suppliesRequestedDto) { - - MunicipalityDto municipalityDto = municipalityBusiness - .getMunicipalityByCode(sR.getRequest().getMunicipalityCode()); - - if (sR.getRequest() != null) { - - List emittersResponse = sR.getRequest().getEmitters(); - List emitterDtoList = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); - - CustomEmitterDto emitterDto = emitterDtoList.stream().filter(e -> e.getEmitterType().equalsIgnoreCase("ENTITY")) - .findAny().orElse(null); - if (emitterDto != null) { - MicroserviceManagerDto managerDto = managerBusiness.getManagerById(emitterDto.getEmitterCode()); - emitterDto.setUser(managerDto); - } - - CustomRequestDto r = new CustomRequestDto(sR.getRequest()); - r.setEmitters(new ArrayList<>(Collections.singletonList(emitterDto))); - r.setMunicipality(municipalityDto); - sR.setRequest(r); - } - - all.add(sR); - } - - } catch (Exception e) { - log.error("No se ha podido consultar los insumos pendiente de revisión: " + e.getMessage()); - } - - return all; - } - - public CustomSupplyRequestedDto getSupplyRequestedById(Long supplyRequestedId) { - CustomSupplyRequestedDto supplyRequestedDto = null; - try { - MicroserviceSupplyRequestedDto response = providerClient.getSupplyRequested(supplyRequestedId); - supplyRequestedDto = new CustomSupplyRequestedDto(response); - } catch (Exception e) { - log.error("No se ha podido consultar el insumo solicitado: " + e.getMessage()); - } - return supplyRequestedDto; - } - - public MicroserviceSupplyRevisionDto createSupplyRevision(Long supplyRequestedId, String database, String hostname, - String username, String password, String port, String schema, Long startBy) { - - MicroserviceSupplyRevisionDto supplyRevisionDto = null; - - try { - - MicroserviceCreateSupplyRevisionDto createRevisionDto = new MicroserviceCreateSupplyRevisionDto(); - createRevisionDto.setDatabase(database); - createRevisionDto.setHostname(hostname); - createRevisionDto.setPassword(password); - createRevisionDto.setPort(port); - createRevisionDto.setSchema(schema); - createRevisionDto.setStartBy(startBy); - createRevisionDto.setUsername(username); - - supplyRevisionDto = providerClient.createSupplyRevision(supplyRequestedId, createRevisionDto); - - } catch (Exception e) { - log.error("No se ha podido crear la revisión: " + e.getMessage()); - } - - return supplyRevisionDto; - } - - public CustomRequestDto updateStateToSupplyRequested(Long requestId, Long supplyRequestedId, Long stateId) { - - CustomRequestDto requestDto = null; - - try { - - MicroserviceUpdateSupplyRequestedDto updateSupply = new MicroserviceUpdateSupplyRequestedDto(); - updateSupply.setSupplyRequestedStateId(stateId); - - MicroserviceRequestDto response = providerClient.updateSupplyRequested(requestId, supplyRequestedId, updateSupply); - - requestDto = new CustomRequestDto(response); - } catch (Exception e) { - log.error("No se ha podido actualizar el estado del insumo solicitado: " + e.getMessage()); - } - - return requestDto; - } - - public CustomRequestDto updateSupplyRequested(Long requestId, Long supplyRequestedId, - MicroserviceUpdateSupplyRequestedDto updateSupplyData) { - - CustomRequestDto requestDto = null; - - try { - MicroserviceRequestDto response = providerClient.updateSupplyRequested(requestId, supplyRequestedId, updateSupplyData); - requestDto = new CustomRequestDto(response); - } catch (Exception e) { - log.error("No se ha podido actualizar el insumo solicitado: " + e.getMessage()); - } - - return requestDto; - } - - public void startRevision(Long supplyRequestedId, Long userCode, MicroserviceProviderDto providerDto) - throws BusinessException { - - CustomSupplyRequestedDto supplyRequestedDto = this.getSupplyRequestedById(supplyRequestedId); - if (supplyRequestedDto == null) { - throw new BusinessException("El insumo solicitado no existe"); - } - - if (!supplyRequestedDto.getTypeSupply().getProvider().getId().equals(providerDto.getId())) { - throw new BusinessException("El insumo solicitado no pertenece al proveedor"); - } - - if (!supplyRequestedDto.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_PENDING_REVIEW)) { - throw new BusinessException("El estado en el que se encuentra el insumo no permite iniciar una revisión."); - } - - String randomUsername = RandomStringUtils.random(8, true, false).toLowerCase(); - String randomPassword = RandomStringUtils.random(10, true, true); - - // create FTP credentials - boolean credentialsCreated = ftpBusiness.createFTPCredentials(randomUsername, randomPassword); - if (!credentialsCreated) { - throw new BusinessException("No se ha podido crear el espacio para el almacenamiento de archivos."); - } - - // create database - String randomDatabaseName = RandomStringUtils.random(8, true, false).toLowerCase(); - String schema = "import_snr"; - try { - databaseIntegrationBusiness.createDatabase(randomDatabaseName, randomUsername, randomPassword); - } catch (Exception e) { - throw new BusinessException("No se ha podido iniciar la revisión."); - } - - // create revision - MicroserviceSupplyRevisionDto supplyRevisionDto; - try { - supplyRevisionDto = createSupplyRevision(supplyRequestedId, cryptoBusiness.encrypt(randomDatabaseName), - cryptoBusiness.encrypt(databaseIntegrationHost), cryptoBusiness.encrypt(randomUsername), - cryptoBusiness.encrypt(randomPassword), cryptoBusiness.encrypt(databaseIntegrationPort), - cryptoBusiness.encrypt(schema), userCode); - } catch (Exception e) { - throw new BusinessException("Ha ocurrido un error intentando crear la revisión."); - } - if (supplyRevisionDto == null) { - throw new BusinessException("Ha ocurrido un error intentando crear la revisión."); - } - - // start import - try { - - String reference = "import-" + supplyRequestedDto.getId() + "-" + supplyRequestedDto.getRequest().getId(); - - iliBusiness.startImport(supplyRequestedDto.getUrl(), databaseIntegrationHost, randomDatabaseName, - databaseIntegrationPassword, databaseIntegrationPort, schema, databaseIntegrationUsername, - reference, supplyRequestedDto.getModelVersion().trim(), IliBusiness.ILI_CONCEPT_INTEGRATION); - - } catch (Exception e) { - log.error("No se ha podido iniciar la revisión: " + e.getMessage()); - throw new BusinessException("No se ha podido iniciar la revisión."); - } - - // update state supply requested to Setting Revision - updateStateToSupplyRequested(supplyRequestedDto.getRequest().getId(), supplyRequestedId, - ProviderBusiness.SUPPLY_REQUESTED_STATE_SETTING_REVIEW); - } - - public MicroserviceSupplyRevisionDto getSupplyRevisionFromSupplyRequested(Long supplyRequestedId) { - - MicroserviceSupplyRevisionDto supplyRevisionDto = null; - - try { - - supplyRevisionDto = providerClient.getSupplyRevisionFromSupplyRequested(supplyRequestedId); - - } catch (Exception e) { - log.error("No se ha podido consultar la revisión del insumo solicitado: " + e.getMessage()); - } - - return supplyRevisionDto; - } - - public void deleteSupplyRevision(Long supplyRequestedId, Long supplyRevisionId) { - - try { - - providerClient.deleteSupplyRevision(supplyRequestedId, supplyRevisionId); - - } catch (Exception e) { - log.error("No se ha podido eliminar la revisión del insumo solicitado: " + e.getMessage()); - } - } - - public MicroserviceQueryResultRegistralRevisionDto getRecordsFromRevision(MicroserviceProviderDto providerDto, - Long supplyRequestedId, int page) throws BusinessException { - - if (page <= 0) { - page = 1; - } - - CustomSupplyRequestedDto supplyRequestedDto = this.getSupplyRequestedById(supplyRequestedId); - if (supplyRequestedDto == null) { - throw new BusinessException("El insumo solicitado no existe"); - } - - if (!supplyRequestedDto.getTypeSupply().getProvider().getId().equals(providerDto.getId())) { - throw new BusinessException("El insumo solicitado no pertenece al proveedor"); - } - - if (!supplyRequestedDto.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW)) { - throw new BusinessException("El estado en el que se encuentra el insumo no permite realizar la consulta."); - } - - MicroserviceSupplyRevisionDto supplyRevisionDto = getSupplyRevisionFromSupplyRequested(supplyRequestedId); - if (supplyRevisionDto == null) { - throw new BusinessException("No existe una revisión para el insumo."); - } - - MicroserviceQueryResultRegistralRevisionDto resultDto; - - try { - - String host = cryptoBusiness.decrypt(supplyRevisionDto.getHostname()); - String database = cryptoBusiness.decrypt(supplyRevisionDto.getDatabase()); - String password = databaseIntegrationPassword; - String port = cryptoBusiness.decrypt(supplyRevisionDto.getPort()); - String schema = cryptoBusiness.decrypt(supplyRevisionDto.getSchema()); - String username = databaseIntegrationUsername; - - int limit = 1000; - - resultDto = iliBusiness.getResultQueryRegistralRevision(host, database, password, port, schema, username, - supplyRequestedDto.getModelVersion(), page, limit); - - } catch (Exception e) { - log.error("No se ha podido realizar la consulta: " + e.getMessage()); - throw new BusinessException("No se ha podido realizar la consulta."); - } - - if (resultDto == null) { - throw new BusinessException("No se ha podido realizar la consulta."); - } - - return resultDto; - } - - public void uploadAttachmentToRevision(MicroserviceProviderDto providerDto, MultipartFile fileUploaded, - Long supplyRequestedId, Long boundaryId, Long userCode) throws BusinessException { - - CustomSupplyRequestedDto supplyRequestedDto = this.getSupplyRequestedById(supplyRequestedId); - if (supplyRequestedDto == null) { - throw new BusinessException("El insumo solicitado no existe"); - } - - if (!supplyRequestedDto.getTypeSupply().getProvider().getId().equals(providerDto.getId())) { - throw new BusinessException("El insumo solicitado no pertenece al proveedor"); - } - - if (!supplyRequestedDto.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW)) { - throw new BusinessException( - "El estado en el que se encuentra el insumo no permite actualizar el registro."); - } - - MicroserviceSupplyRevisionDto supplyRevisionDto = getSupplyRevisionFromSupplyRequested(supplyRequestedId); - if (supplyRevisionDto == null) { - throw new BusinessException("No existe una revisión para el insumo."); - } - - // save file - String urlBase = "/anexos/" + supplyRequestedId; - urlBase = FileTool.removeAccents(urlBase); - String urlFile = fileBusiness.saveFileToSystem(fileUploaded, urlBase, true); - - String FTPFileName = boundaryId + ".zip"; - - String usernameFTP = null; - String passwordFTP = null; - try { - usernameFTP = cryptoBusiness.decrypt(supplyRevisionDto.getUsername()); - passwordFTP = cryptoBusiness.decrypt(supplyRevisionDto.getPassword()); - } catch (Exception e) { - log.error("Error consultando datos de conexión al FTP:" + e.getMessage()); - } - - boolean uploadFilToFTPServer = ftpBusiness.uploadFileToFTP(urlFile, FTPFileName, usernameFTP, passwordFTP); - if (!uploadFilToFTPServer) { - throw new BusinessException("No se ha podido cargar el archivo al servidor FTP."); - } - - try { - - String host = cryptoBusiness.decrypt(supplyRevisionDto.getHostname()); - String database = cryptoBusiness.decrypt(supplyRevisionDto.getDatabase()); - String password = databaseIntegrationPassword; - String port = cryptoBusiness.decrypt(supplyRevisionDto.getPort()); - String schema = cryptoBusiness.decrypt(supplyRevisionDto.getSchema()); - String username = databaseIntegrationUsername; - - String namespace = supplyRequestedDto.getTypeSupply().getProvider().getName() + "_FUENTECABIDALINDEROS"; - - iliBusiness.updateRecordFromRevision(host, database, password, port, schema, username, - supplyRequestedDto.getModelVersion(), boundaryId, ProviderBusiness.PROVIDER_SNR_ID, namespace, - FTPFileName); - - } catch (Exception e) { - log.error("No se ha podido realizar la consulta: " + e.getMessage()); - throw new BusinessException("No se ha podido actualizar el registro."); - } - - // delete file - try { - FileUtils.deleteQuietly(new File(urlFile)); - } catch (Exception e) { - log.error("No se ha podido eliminar el archivo temporal: " + e.getMessage()); - } - - } - - public void closeRevision(Long supplyRequestedId, Long userCode, MicroserviceProviderDto providerDto) - throws BusinessException { - - CustomSupplyRequestedDto supplyRequestedDto = this.getSupplyRequestedById(supplyRequestedId); - if (supplyRequestedDto == null) { - throw new BusinessException("El insumo solicitado no existe"); - } - - if (!supplyRequestedDto.getTypeSupply().getProvider().getId().equals(providerDto.getId())) { - throw new BusinessException("El insumo solicitado no pertenece al proveedor"); - } - - if (!supplyRequestedDto.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW)) { - throw new BusinessException("El estado en el que se encuentra el insumo no permite cerrar una revisión."); - } - - MicroserviceSupplyRevisionDto supplyRevisionDto = getSupplyRevisionFromSupplyRequested(supplyRequestedId); - if (supplyRevisionDto == null) { - throw new BusinessException("No existe una revisión para el insumo."); - } - - // start export - try { - - String host = cryptoBusiness.decrypt(supplyRevisionDto.getHostname()); - String database = cryptoBusiness.decrypt(supplyRevisionDto.getDatabase()); - String password = databaseIntegrationPassword; - String port = cryptoBusiness.decrypt(supplyRevisionDto.getPort()); - String schema = cryptoBusiness.decrypt(supplyRevisionDto.getSchema()); - String username = databaseIntegrationUsername; - - String reference = "export-" + supplyRequestedDto.getId() + "-" + supplyRequestedDto.getRequest().getId() - + "-" + userCode; - - String randomFilename = RandomStringUtils.random(20, true, false).toLowerCase(); - String pathFile = stFilesDirectory + "/anexos/" + supplyRequestedId + File.separator + randomFilename + ".xtf"; - - iliBusiness.startExportReference(pathFile, host, database, password, port, schema, username, reference, - supplyRequestedDto.getModelVersion().trim(), IliBusiness.ILI_CONCEPT_INTEGRATION); - - } catch (Exception e) { - log.error("No se ha podido iniciar la exportación: " + e.getMessage()); - throw new BusinessException("No se ha podido iniciar la exportación."); - } - - // update state supply requested to Closing Revision - updateStateToSupplyRequested(supplyRequestedDto.getRequest().getId(), supplyRequestedId, - ProviderBusiness.SUPPLY_REQUESTED_STATE_CLOSING_REVIEW); - - } - - public CustomRequestDto getRequestById(Long requestId) { - - CustomRequestDto requestDto = null; - - try { - MicroserviceRequestDto response = providerClient.findRequestById(requestId); - requestDto = new CustomRequestDto(response); - } catch (Exception e) { - log.error("Error consultando solicitud por id: " + e.getMessage()); - } - - return requestDto; - } - - public MicroserviceSupplyRevisionDto updateSupplyRevision(Long supplyRequestedId, Long supplyRevisionId, - MicroserviceUpdateSupplyRevisionDto updateData) { - - MicroserviceSupplyRevisionDto supplyRevisionDto = null; - - try { - - supplyRevisionDto = providerClient.updateSupplyRevision(supplyRequestedId, supplyRevisionId, updateData); - - } catch (Exception e) { - log.error("No se ha podido actualizar la revisión: " + e.getMessage()); - } - - return supplyRevisionDto; - } - - public void skipRevision(Long supplyRequestedId, Long userCode, MicroserviceProviderDto providerDto) - throws BusinessException { - - CustomSupplyRequestedDto supplyRequestedDto = this.getSupplyRequestedById(supplyRequestedId); - if (supplyRequestedDto == null) { - throw new BusinessException("El insumo solicitado no existe"); - } - - if (!supplyRequestedDto.getTypeSupply().getProvider().getId().equals(providerDto.getId())) { - throw new BusinessException("El insumo solicitado no pertenece al proveedor"); - } - - if (!supplyRequestedDto.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_PENDING_REVIEW)) { - throw new BusinessException("El estado en el que se encuentra el insumo no permite omitir la revisión."); - } - - // create supply - - Long requestId = supplyRequestedDto.getRequest().getId(); - String urlDocumentaryRepository = supplyRequestedDto.getUrl(); - - CustomRequestDto requestDto = this.getRequestById(requestId); - - List attachments = new ArrayList<>(); - - attachments.add(new MicroserviceCreateSupplyAttachmentDto(urlDocumentaryRepository, - SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY)); - - List emittersResponse = requestDto.getEmitters(); - List emittersDto = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); - - CustomEmitterDto emitterDto = emittersDto.stream(). - filter(e -> e.getEmitterType().equalsIgnoreCase("ENTITY")).findAny().orElse(null); - - supplyBusiness.createSupply(requestDto.getMunicipalityCode(), supplyRequestedDto.getObservations(), - supplyRequestedDto.getTypeSupply().getId(), emitterDto.getEmitterCode(), attachments, requestId, userCode, - requestDto.getProvider().getId(), null, null, supplyRequestedDto.getModelVersion(), - SupplyBusiness.SUPPLY_STATE_ACTIVE, supplyRequestedDto.getTypeSupply().getName(), supplyRequestedDto.getValid()); - - updateStateToSupplyRequested(requestId, supplyRequestedId, ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED); - - // close request - closeRequest(requestId, userCode); - } - public CustomPetitionDto createPetition(Long providerId, Long managerId, String description) throws BusinessException { @@ -1655,7 +1221,10 @@ public CustomPetitionDto createPetition(Long providerId, Long managerId, String try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("Error verificando proveedor para crear petición: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d para crear la petición : %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (providerDto == null) { throw new BusinessException("El proveedor de insumo no existe."); @@ -1673,15 +1242,17 @@ public CustomPetitionDto createPetition(Long providerId, Long managerId, String petitionDto = addAdditionalDataToPetition(petitionDto); } catch (Exception e) { - log.error("Error creando petición: " + e.getMessage()); + String messageError = String.format("Error creando la petición para el proveedor %d : %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido crear la petición."); } return petitionDto; } - public List getPetitionsForManager(Long providerId, Long managerId) - throws BusinessException { + public List getPetitionsFromManager(Long providerId, Long managerId) throws BusinessException { List listPetitionsDto; List response; @@ -1690,12 +1261,14 @@ public List getPetitionsForManager(Long providerId, Long mana response = providerClient.getPetitionsByManager(managerId); } else { - // validate provider MicroserviceProviderDto providerDto = null; try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("Error verificando proveedor para crear petición: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d : %s", providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (providerDto == null) { throw new BusinessException("El proveedor de insumo no existe."); @@ -1713,7 +1286,10 @@ public List getPetitionsForManager(Long providerId, Long mana } } catch (Exception e) { - log.error("Error obteniendo las peticiones para el gestor: " + e.getMessage()); + String messageError = String.format("Error obteniendo las peticiones del gestor %d : %s", managerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar las peticiones del gestor."); } @@ -1729,7 +1305,9 @@ public List getPetitionsForProviderOpen(Long providerId) thro try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("Error verificando proveedor para crear petición: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d : %s", providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (providerDto == null) { throw new BusinessException("El proveedor de insumo no existe."); @@ -1747,7 +1325,10 @@ public List getPetitionsForProviderOpen(Long providerId) thro } } catch (Exception e) { - log.error("Error obteniendo las peticiones pendientes para el proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando las peticiones pendientes del proveedor %d : %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar las peticiones del proveedor."); } @@ -1763,7 +1344,9 @@ public List getPetitionsForProviderClose(Long providerId) thr try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("Error verificando proveedor para crear petición: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d : %s", providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (providerDto == null) { throw new BusinessException("El proveedor de insumo no existe."); @@ -1782,7 +1365,10 @@ public List getPetitionsForProviderClose(Long providerId) thr } } catch (Exception e) { - log.error("Error obteniendo las peticiones cerradas para el proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando las peticiones cerradas del proveedor %d : %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar las peticiones del proveedor."); } @@ -1799,7 +1385,9 @@ public CustomPetitionDto acceptPetition(Long providerId, Long petitionId, String try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("Error verificando proveedor para actualizar petición: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d : %s", providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (providerDto == null) { throw new BusinessException("El proveedor de insumo no existe."); @@ -1817,10 +1405,16 @@ public CustomPetitionDto acceptPetition(Long providerId, Long petitionId, String petitionDto = addAdditionalDataToPetition(petitionDto); } catch (BusinessException e) { - log.error("Error aceptando la petición: " + e.getMessage()); + String messageError = String.format("Error rechazando la petición %d por el proveedor %d : %s", petitionId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error aceptando la petición: " + e.getMessage()); + String messageError = String.format("Error aceptando la petición %d por el proveedor %d : %s", petitionId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido aceptar la petición."); } @@ -1837,7 +1431,9 @@ public CustomPetitionDto rejectPetition(Long providerId, Long petitionId, String try { providerDto = providerClient.findById(providerId); } catch (Exception e) { - log.error("Error verificando proveedor para actualizar petición: " + e.getMessage()); + String messageError = String.format("Error consultando el proveedor %d : %s", providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (providerDto == null) { throw new BusinessException("El proveedor de insumo no existe."); @@ -1855,10 +1451,16 @@ public CustomPetitionDto rejectPetition(Long providerId, Long petitionId, String petitionDto = addAdditionalDataToPetition(petitionDto); } catch (BusinessException e) { - log.error("Error rechazando la petición: " + e.getMessage()); + String messageError = String.format("Error rechazando la petición %d por el proveedor %d : %s", petitionId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error rechazando la petición: " + e.getMessage()); + String messageError = String.format("Error rechazando la petición %d por el proveedor %d : %s", petitionId, + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido rechazar la petición."); } @@ -1874,7 +1476,10 @@ private CustomPetitionDto addAdditionalDataToPetition(CustomPetitionDto petition } catch (Exception e) { petitionDto.setManager(null); - log.error("Error agregando información adicional a una petición: " + e.getMessage()); + String messageError = String.format("Error agregando información del gestor %d a la petición %d : %s", + petitionDto.getManagerCode(), petitionDto.getId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return petitionDto; @@ -1895,7 +1500,11 @@ public MicroserviceTypeSupplyDto enableTypeSupply(Long providerId, Long typeSupp } catch (Exception e) { belongToProvider = false; - log.error("Error verificando si el tipo de insumo pertenece al proveedor: " + e.getMessage()); + String messageError = String.format( + "Error verificando si el tipo de insumo %d pertenece al proveedor %d: %s", typeSupplyId, providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (!belongToProvider) { throw new BusinessException("El tipo de insumo no pertenece al proveedor."); @@ -1906,10 +1515,16 @@ public MicroserviceTypeSupplyDto enableTypeSupply(Long providerId, Long typeSupp typeSupplyDto = providerClient.enableTypeSupply(typeSupplyId); } catch (BusinessException e) { - log.error("Error activando tipo de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error activando el tipo de insumo %d del proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error activando tipo de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error activando el tipo de insumo %d del proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido activar el tipo de insumo."); } @@ -1931,7 +1546,11 @@ public MicroserviceTypeSupplyDto disableTypeSupply(Long providerId, Long typeSup } catch (Exception e) { belongToProvider = false; - log.error("Error verificando si el tipo de insumo pertenece al proveedor: " + e.getMessage()); + String messageError = String.format( + "Error verificando si el tipo de insumo %d pertenece al proveedor %d: %s", typeSupplyId, providerId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (!belongToProvider) { throw new BusinessException("El tipo de insumo no pertenece al proveedor."); @@ -1942,10 +1561,16 @@ public MicroserviceTypeSupplyDto disableTypeSupply(Long providerId, Long typeSup typeSupplyDto = providerClient.disableTypeSupply(typeSupplyId); } catch (BusinessException e) { - log.error("Error desactivando tipo de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error desactivando el tipo de insumo %d del proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error desactivando tipo de insumo del proveedor: " + e.getMessage()); + String messageError = String.format("Error desactivando el tipo de insumo %d del proveedor %d: %s", + typeSupplyId, providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido desactivar el tipo de insumo."); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/ReportBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/ReportBusiness.java index 487ff67..9aaa940 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/ReportBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/ReportBusiness.java @@ -4,6 +4,7 @@ import com.ai.st.microservice.common.dto.reports.*; import com.ai.st.microservice.common.exceptions.BusinessException; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @@ -22,9 +23,9 @@ public ReportBusiness(ReportFeignClient reportClient) { } public MicroserviceReportInformationDto generateReportDownloadSupply(String namespace, String dateCreation, - String dateDelivery, String deliveryId, String departmentName, String managerName, String municipalityCode, - String municipalityName, String observations, String operatorName, - List supplies) throws BusinessException { + String dateDelivery, String deliveryId, String departmentName, String managerName, String municipalityCode, + String municipalityName, String observations, String operatorName, + List supplies) throws BusinessException { MicroserviceReportInformationDto informationDto; @@ -45,7 +46,11 @@ public MicroserviceReportInformationDto generateReportDownloadSupply(String name informationDto = reportClient.createReportDownloadSuppliesTotal(data); } catch (Exception e) { - log.error("Error creando reporte (entrega de insumos por parte del gestor al operador): " + e.getMessage()); + String messageError = String.format( + "Error creando reporte (entrega de insumos por parte del gestor %s al operador %s): %s", + managerName, operatorName, e.getMessage()); + SCMTracing.sendError(e.getMessage()); + log.error(messageError); throw new BusinessException("No se ha podido generar el reporte."); } @@ -53,8 +58,8 @@ public MicroserviceReportInformationDto generateReportDownloadSupply(String name } public MicroserviceReportInformationDto generateReportDeliveryAC(String namespace, String createdAt, - String departmentName, String managerName, String municipalityCode, String municipalityName, - List supplies) throws BusinessException { + String departmentName, String managerName, String municipalityCode, String municipalityName, + List supplies) throws BusinessException { MicroserviceReportInformationDto informationDto; @@ -73,8 +78,11 @@ public MicroserviceReportInformationDto generateReportDeliveryAC(String namespac informationDto = reportClient.createReportDeliverySuppliesAC(data); } catch (Exception e) { - log.error("Error creando reporte (entrega de insumos por parte de la autoridad catastral): " - + e.getMessage()); + String messageError = String.format( + "Error creando reporte (entrega de insumos por parte de la autoridad catastral al gestor %s): %s", + managerName, e.getMessage()); + SCMTracing.sendError(e.getMessage()); + log.error(messageError); throw new BusinessException("No se ha podido generar el reporte."); } @@ -83,9 +91,9 @@ public MicroserviceReportInformationDto generateReportDeliveryAC(String namespac } public MicroserviceReportInformationDto generateReportDeliveryManager(String namespace, String dateCreation, - String dateDelivery, String deliveryId, String departmentName, String managerName, String municipalityCode, - String municipalityName, String observations, String operatorName, - List supplies) throws BusinessException { + String dateDelivery, String deliveryId, String departmentName, String managerName, String municipalityCode, + String municipalityName, String observations, String operatorName, + List supplies) throws BusinessException { MicroserviceReportInformationDto informationDto; @@ -106,7 +114,11 @@ public MicroserviceReportInformationDto generateReportDeliveryManager(String nam informationDto = reportClient.createReportDeliveryManager(data); } catch (Exception e) { - log.error("Error creando reporte (entrega de insumos por parte del gestor al operador): " + e.getMessage()); + String messageError = String.format( + "Error creando reporte (entrega de insumos por parte del gestor %s al operador %s): %s", + managerName, operatorName, e.getMessage()); + SCMTracing.sendError(e.getMessage()); + log.error(messageError); throw new BusinessException("No se ha podido generar el reporte."); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/SupplyBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/SupplyBusiness.java index adddaa1..9db917e 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/SupplyBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/SupplyBusiness.java @@ -18,10 +18,12 @@ import com.ai.st.microservice.workspaces.entities.WorkspaceOperatorEntity; import com.ai.st.microservice.workspaces.services.IMunicipalityService; import com.ai.st.microservice.workspaces.services.IWorkspaceService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import com.ai.st.microservice.workspaces.utils.DateTool; import com.ai.st.microservice.workspaces.utils.FileTool; import org.apache.commons.lang.RandomStringUtils; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -41,7 +43,7 @@ public class SupplyBusiness { private final Logger log = LoggerFactory.getLogger(SupplyBusiness.class); - // attachments types + // attachment types public static final Long SUPPLY_ATTACHMENT_TYPE_SUPPLY = (long) 1; public static final Long SUPPLY_ATTACHMENT_TYPE_FTP = (long) 2; public static final Long SUPPLY_ATTACHMENT_TYPE_EXTERNAL_SOURCE = (long) 3; @@ -67,7 +69,7 @@ public class SupplyBusiness { private OperatorMicroserviceBusiness operatorBusiness; public Object getSuppliesByMunicipalityAdmin(Long municipalityId, List extensions, Integer page, - List requests, boolean active, Long managerCode) throws BusinessException { + List requests, boolean active, Long managerCode) throws BusinessException { // validate if the municipality exists MunicipalityEntity municipalityEntity = municipalityService.getMunicipalityById(municipalityId); @@ -75,11 +77,12 @@ public Object getSuppliesByMunicipalityAdmin(Long municipalityId, List e throw new BusinessException("No se ha encontrado el municipio."); } - return this.getSuppliesByMunicipality(municipalityEntity, extensions, page, requests, active, managerCode, null); + return this.getSuppliesByMunicipality(municipalityEntity, extensions, page, requests, active, managerCode, + null); } public Object getSuppliesByMunicipalityManager(Long municipalityId, Long managerCode, List extensions, - Integer page, List requests, boolean active, Long operatorCode) throws BusinessException { + Integer page, List requests, boolean active, Long operatorCode) throws BusinessException { // validate if the municipality exists MunicipalityEntity municipalityEntity = municipalityService.getMunicipalityById(municipalityId); @@ -91,19 +94,22 @@ public Object getSuppliesByMunicipalityManager(Long municipalityId, Long manager WorkspaceEntity workspaceActive = workspaceService.getWorkspaceActiveByMunicipality(municipalityEntity); if (workspaceActive != null) { - WorkspaceManagerEntity workspaceManagerEntity = - workspaceActive.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceActive.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("No tiene acceso al municipio."); } } } - return this.getSuppliesByMunicipality(municipalityEntity, extensions, page, requests, active, managerCode, operatorCode); + return this.getSuppliesByMunicipality(municipalityEntity, extensions, page, requests, active, managerCode, + operatorCode); } private Object getSuppliesByMunicipality(MunicipalityEntity municipality, List extensions, Integer page, - List requests, boolean active, Long managerCode, Long operatorCode) throws BusinessException { + List requests, boolean active, Long managerCode, Long operatorCode) throws BusinessException { + + log.info("Get supplies by municipality started"); List states = new ArrayList<>(); @@ -115,6 +121,10 @@ private Object getSuppliesByMunicipality(MunicipalityEntity municipality, List suppliesDto; @@ -124,22 +134,31 @@ private Object getSuppliesByMunicipality(MunicipalityEntity municipality, List response = dataPaginated.getItems(); suppliesDto = response.stream().map(CustomSupplyDto::new).collect(Collectors.toList()); } else { - List response = supplyClient.getSuppliesByMunicipalityCode(municipality.getCode(), states); + log.info("Get results without pagination"); + + List response = supplyClient + .getSuppliesByMunicipalityCode(municipality.getCode(), states); suppliesDto = response.stream().map(CustomSupplyDto::new).collect(Collectors.toList()); if (managerCode != null) { - suppliesDto = suppliesDto.stream().filter(s -> s.getManagerCode().equals(managerCode)).collect(Collectors.toList()); + suppliesDto = suppliesDto.stream().filter(s -> s.getManagerCode().equals(managerCode)) + .collect(Collectors.toList()); } } + log.info("Result founds: " + suppliesDto.size()); + List all = new ArrayList<>(); for (CustomSupplyDto supplyDto : suppliesDto) { @@ -147,11 +166,17 @@ private Object getSuppliesByMunicipality(MunicipalityEntity municipality, List o.getOperatorCode().equals(operatorCode) - && o.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceEntity workspaceActive = workspaceService + .getWorkspaceActiveByMunicipality(municipality); + WorkspaceOperatorEntity workspaceOperatorEntity = workspaceActive.getOperators().stream() + .filter(o -> o.getOperatorCode().equals(operatorCode) + && o.getManagerCode().equals(managerCode)) + .findAny().orElse(null); if (workspaceOperatorEntity != null) { - List deliveriesDto = operatorBusiness.getDeliveriesByOperator( - operatorCode, municipality.getCode()); + List deliveriesDto = operatorBusiness + .getDeliveriesByOperator(operatorCode, municipality.getCode()); for (CustomDeliveryDto deliveryFoundDto : deliveriesDto) { - List suppliesResponse = deliveryFoundDto.getSupplies(); - List suppliesDeliveryDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesResponse = deliveryFoundDto + .getSupplies(); + List suppliesDeliveryDto = suppliesResponse.stream() + .map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); CustomSupplyDeliveryDto supplyFound = suppliesDeliveryDto.stream() .filter(sDto -> sDto.getSupplyCode().equals(supplyDto.getId())).findAny() @@ -187,14 +215,16 @@ private Object getSuppliesByMunicipality(MunicipalityEntity municipality, List extensionsDto = supplyDto.getTypeSupply().getExtensions(); for (MicroserviceExtensionDto extensionDto : extensionsDto) { - String extensionFound = extensions.stream().filter( - extension -> extensionDto.getName().equalsIgnoreCase(extension)) - .findAny().orElse(null); + String extensionFound = extensions.stream() + .filter(extension -> extensionDto.getName().equalsIgnoreCase(extension)).findAny() + .orElse(null); if (extensionFound != null) { suppliesFinal.add(supplyDto); } @@ -234,14 +269,25 @@ private Object getSuppliesByMunicipality(MunicipalityEntity municipality, List attachments, Long requestId, Long userCode, Long providerCode, - Long managerCode, Long cadastralAuthority, String modelVersion, Long stateSupplyId, String name, - Boolean isValid) - throws BusinessException { + public CustomSupplyDto createSupply(String municipalityCode, String observations, Long typeSupplyCode, + Long toManagerCode, List attachments, Long requestId, Long userCode, + Long providerCode, Long managerCode, Long cadastralAuthority, String modelVersion, Long stateSupplyId, + String name, Boolean isValid) throws BusinessException { + + log.info("Create supply in supplies microservice started"); + + final String attachmentStringId = StringUtils.join(attachments.stream() + .map(MicroserviceCreateSupplyAttachmentDto::getAttachmentTypeId).collect(Collectors.toList()), ","); + + log.info(String.format("params: municipality=%s observations=%s typeSupplyCode=%d toManagerCode=%d " + + "attachments=%s requestId=%d userCode=%d providerCode=%d managerCode=%d cadastralAuthority=%d " + + "modelVersion=%s stateSupplyId=%d name=%s isValid=%s", municipalityCode, observations, typeSupplyCode, + toManagerCode, attachmentStringId, requestId, userCode, providerCode, managerCode, cadastralAuthority, + modelVersion, stateSupplyId, name, isValid)); CustomSupplyDto supplyDto; @@ -270,6 +316,10 @@ public CustomSupplyDto createSupply(String municipalityCode, String observations createSupplyDto.setTypeSupplyCode(typeSupplyCode); } + if (observations == null) { + createSupplyDto.setObservations("N/A"); + } + createSupplyDto.setAttachments(attachments); List owners = new ArrayList<>(); @@ -308,7 +358,10 @@ public CustomSupplyDto createSupply(String municipalityCode, String observations supplyDto = new CustomSupplyDto(response); } catch (Exception e) { - log.error("No se ha podido crear el insumo: " + e.getMessage()); + String messageError = String.format("Error creando el insumo para el municipio %s : %s debido a: %s", + municipalityCode, e.getMessage(), e.getCause()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cargar el insumo"); } @@ -332,22 +385,22 @@ public CustomSupplyDto getSupplyById(Long supplyId) throws BusinessException { } } catch (Exception e) { - log.error("No se ha podido consultar el insumo: " + e.getMessage()); + String messageError = String.format("Error consultando el insumo %d : %s", supplyId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return supplyDto; } public void deleteSupply(Long supplyId) { - try { - supplyClient.deleteSupplyById(supplyId); - } catch (Exception e) { - log.error("No se ha podido eliminar el insumo: " + e.getMessage()); + String messageError = String.format("Error eliminando el insumo %d : %s", supplyId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - } public File generateFTPFile(CustomSupplyDto supplyDto, MunicipalityDto municipalityDto) { @@ -384,8 +437,7 @@ public File generateFTPFile(CustomSupplyDto supplyDto, MunicipalityDto municipal return FileTool.createSimpleFile(content, filename); } - public CustomSupplyDto changeStateSupply(Long supplyId, Long stateId, Long managerCode) - throws BusinessException { + public CustomSupplyDto changeStateSupply(Long supplyId, Long stateId, Long managerCode) throws BusinessException { CustomSupplyDto supplyDto = getSupplyById(supplyId); if (supplyDto == null) { @@ -405,10 +457,16 @@ public CustomSupplyDto changeStateSupply(Long supplyId, Long stateId, Long manag supplyDto = new CustomSupplyDto(response); } catch (BusinessException e) { - log.error("Error actualizando el estado del insumo: " + e.getMessage()); + String messageError = String.format("Error actualizando el estado del insumo %d a %d por el gestor %d: %s", + supplyId, stateId, managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException(e.getMessage()); } catch (Exception e) { - log.error("Error actualizando el estado del insumo: " + e.getMessage()); + String messageError = String.format("Error actualizando el estado del insumo %d a %d por el gestor %d: %s", + supplyId, stateId, managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cambiar el estado del insumo."); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/TaskBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/TaskBusiness.java index 477e7aa..26a7fee 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/TaskBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/TaskBusiness.java @@ -20,6 +20,7 @@ import com.ai.st.microservice.workspaces.entities.WorkspaceEntity; import com.ai.st.microservice.workspaces.services.IIntegrationService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.apache.commons.lang.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -82,9 +83,10 @@ public class TaskBusiness { private final QualityFeignClient qualityClient; public TaskBusiness(TaskFeignClient taskClient, UserFeignClient userClient, SupplyFeignClient supplyClient, - ProviderFeignClient providerClient, IliBusiness iliBusiness, CrytpoBusiness cryptoBusiness, - IntegrationBusiness integrationBusiness, DatabaseIntegrationBusiness databaseIntegrationBusiness, - ProviderBusiness providerBusiness, IIntegrationService integrationService, QualityFeignClient qualityClient) { + ProviderFeignClient providerClient, IliBusiness iliBusiness, CrytpoBusiness cryptoBusiness, + IntegrationBusiness integrationBusiness, DatabaseIntegrationBusiness databaseIntegrationBusiness, + ProviderBusiness providerBusiness, IIntegrationService integrationService, + QualityFeignClient qualityClient) { this.taskClient = taskClient; this.userClient = userClient; this.supplyClient = supplyClient; @@ -103,8 +105,8 @@ public CustomTaskDto extendTask(CustomTaskDto taskDto) { List members = new ArrayList<>(); List response = taskDto.getMembers(); - List tasksMembersDto = - response.stream().map(CustomTaskMemberDto::new).collect(Collectors.toList()); + List tasksMembersDto = response.stream().map(CustomTaskMemberDto::new) + .collect(Collectors.toList()); for (CustomTaskMemberDto member : tasksMembersDto) { try { @@ -141,7 +143,7 @@ public CustomTaskDto extendTask(CustomTaskDto taskDto) { return taskDto; } - public List getPendingTasks(Long userCode) throws BusinessException { + public List getPendingTasksByUser(Long userCode) throws BusinessException { List listTasksDto = new ArrayList<>(); @@ -152,7 +154,8 @@ public List getPendingTasks(Long userCode) throws BusinessExcepti taskStates.add(TaskBusiness.TASK_STATE_STARTED); List response = taskClient.findByUserAndState(userCode, taskStates); - List listResponseTasks = response.stream().map(CustomTaskDto::new).collect(Collectors.toList()); + List listResponseTasks = response.stream().map(CustomTaskDto::new) + .collect(Collectors.toList()); for (CustomTaskDto taskDto : listResponseTasks) { taskDto = this.extendTask(taskDto); @@ -160,6 +163,10 @@ public List getPendingTasks(Long userCode) throws BusinessExcepti } } catch (Exception e) { + String messageError = String.format("Error consultando las tareas pendientes del usuario %d : %s", userCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar las tareas pendientes del usuario."); } @@ -167,8 +174,8 @@ public List getPendingTasks(Long userCode) throws BusinessExcepti } public CustomTaskDto createTask(List categories, String deadline, String description, String name, - List users, List metadata, - List steps) throws BusinessException { + List users, List metadata, + List steps) throws BusinessException { CustomTaskDto taskDto; @@ -187,15 +194,17 @@ public CustomTaskDto createTask(List categories, String deadline, String d taskDto = new CustomTaskDto(response); } catch (Exception e) { - log.error("No se ha podido crear la tarea: " + e.getMessage()); + String messageError = String.format("Error creando tarea : %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido crear la tarea."); } return taskDto; } - public CustomTaskDto createTaskForGenerationSupply(List users, String municipality, String department, Long requestId, - Long typeSupplyId, Date dateDeadline, String modelVersion) throws BusinessException { + public CustomTaskDto createTaskForGenerationSupply(List users, String municipality, String department, + Long requestId, Long typeSupplyId, Date dateDeadline, String modelVersion) throws BusinessException { List taskCategories = new ArrayList<>(); taskCategories.add(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION); @@ -240,6 +249,9 @@ public CustomTaskDto startTask(Long taskId, Long userId) throws BusinessExceptio MicroserviceTaskDto response = taskClient.findTaskById(taskId); taskDto = new CustomTaskDto(response); } catch (Exception e) { + String messageError = String.format("Error consultando la tarea %d: %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado la tarea."); } @@ -250,8 +262,8 @@ public CustomTaskDto startTask(Long taskId, Long userId) throws BusinessExceptio // verify if the user is assigned the task List responseMembers = taskDto.getMembers(); - List membersDto = - responseMembers.stream().map(CustomTaskMemberDto::new).collect(Collectors.toList()); + List membersDto = responseMembers.stream().map(CustomTaskMemberDto::new) + .collect(Collectors.toList()); CustomTaskMemberDto memberFound = membersDto.stream() .filter(memberDto -> memberDto.getMemberCode().equals(userId)).findAny().orElse(null); @@ -263,15 +275,17 @@ public CustomTaskDto startTask(Long taskId, Long userId) throws BusinessExceptio // remove others members try { List responseMembersDto = taskDto.getMembers(); - List membersListDto = - responseMembersDto.stream().map(CustomTaskMemberDto::new).collect(Collectors.toList()); + List membersListDto = responseMembersDto.stream().map(CustomTaskMemberDto::new) + .collect(Collectors.toList()); for (CustomTaskMemberDto memberDto : membersListDto) { if (!memberDto.getMemberCode().equals(userId)) { taskClient.removeMemberFromTask(taskId, memberDto.getMemberCode()); } } } catch (Exception e) { - log.error("No se ha podido desasignar los usuarios de la tarea: " + e.getMessage()); + String messageError = String.format("Error quitando usuarios de la tarea %d: %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } try { @@ -279,7 +293,9 @@ public CustomTaskDto startTask(Long taskId, Long userId) throws BusinessExceptio taskDto = new CustomTaskDto(response); taskDto = this.extendTask(taskDto); } catch (Exception e) { - log.error("No se ha podido iniciar la tarea: " + e.getMessage()); + String messageError = String.format("Error iniciando la tarea %d: %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido iniciar la tarea."); } @@ -294,6 +310,9 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws MicroserviceTaskDto response = taskClient.findTaskById(taskId); taskDto = new CustomTaskDto(response); } catch (Exception e) { + String messageError = String.format("Error consultando la tarea %d: %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado la tarea."); } @@ -304,8 +323,8 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws // verify if the user is assigned the task List responseMembers = taskDto.getMembers(); - List membersDto = - responseMembers.stream().map(CustomTaskMemberDto::new).collect(Collectors.toList()); + List membersDto = responseMembers.stream().map(CustomTaskMemberDto::new) + .collect(Collectors.toList()); CustomTaskMemberDto memberFound = membersDto.stream() .filter(memberDto -> memberDto.getMemberCode().equals(userDto.getId())).findAny().orElse(null); @@ -350,7 +369,8 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws WorkspaceEntity workspaceEntity = integrationEntity.getWorkspace(); // supply cadastre - MicroserviceSupplyDto response = supplyClient.findSupplyById(integrationEntity.getSupplyCadastreId()); + MicroserviceSupplyDto response = supplyClient + .findSupplyById(integrationEntity.getSupplyCadastreId()); CustomSupplyDto supplyCadastreDto = new CustomSupplyDto(response); String urlBase = "/" + workspaceEntity.getMunicipality().getCode().replace(" ", "_") @@ -370,11 +390,15 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws } } catch (Exception e) { - log.error("No se ha podido empezar a generar el producto: " + e.getMessage()); + String messageError = String.format( + "Error generando el producto a partir de la finalización de la tarea de integración %d: %s", taskId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } MicroserviceTaskCategoryDto categoryGenerationFound = taskDto.getCategories().stream().filter( - categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)) + categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)) .findAny().orElse(null); // task for generation of supplies @@ -402,14 +426,15 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws CustomRequestDto requestDto = new CustomRequestDto(response); - List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesResponse = requestDto + .getSuppliesRequested(); + List suppliesRequestDto = suppliesResponse.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); CustomSupplyRequestedDto supplyRequestedDto = suppliesRequestDto.stream() .filter(sR -> sR.getTypeSupply().getId().equals(typeSupplyId)).findAny().orElse(null); - if (supplyRequestedDto instanceof CustomSupplyRequestedDto) { + if (supplyRequestedDto != null) { Long supplyStateId = supplyRequestedDto.getState().getId(); if (supplyStateId.equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_VALIDATING)) { @@ -432,8 +457,8 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws } } - MicroserviceTaskCategoryDto categoryXTFQuality = taskDto.getCategories().stream().filter( - categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_XTF_QUALITY_PROCESS)) + MicroserviceTaskCategoryDto categoryXTFQuality = taskDto.getCategories().stream() + .filter(categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_XTF_QUALITY_PROCESS)) .findAny().orElse(null); if (categoryXTFQuality != null) { @@ -442,23 +467,27 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws .filter(meta -> meta.getKey().equalsIgnoreCase("attachment")).findAny().orElse(null); if (metadataRequest != null) { - BusinessException error = new BusinessException("Ha ocurrido un error finalizando la tarea del proceso de calidad"); + BusinessException error = new BusinessException( + "Ha ocurrido un error finalizando la tarea del proceso de calidad"); - MicroserviceTaskMetadataPropertyDto propertyDeliveryId = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("deliveryId")).findAny().orElseThrow(() -> error); - MicroserviceTaskMetadataPropertyDto propertyDeliveryProductId = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("deliveryProductId")).findAny().orElseThrow(() -> error); - MicroserviceTaskMetadataPropertyDto propertyAttachmentId = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("attachmentId")).findAny().orElseThrow(() -> error); + MicroserviceTaskMetadataPropertyDto propertyDeliveryId = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("deliveryId")).findAny().orElseThrow(() -> error); + MicroserviceTaskMetadataPropertyDto propertyDeliveryProductId = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("deliveryProductId")).findAny() + .orElseThrow(() -> error); + MicroserviceTaskMetadataPropertyDto propertyAttachmentId = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("attachmentId")).findAny().orElseThrow(() -> error); Long deliveryId = Long.parseLong(propertyDeliveryId.getValue()); Long productId = Long.parseLong(propertyDeliveryProductId.getValue()); Long attachmentId = Long.parseLong(propertyAttachmentId.getValue()); - MicroserviceXTFAttachmentDto attachmentDto = qualityClient.findAttachmentById(deliveryId, productId, attachmentId); + MicroserviceXTFAttachmentDto attachmentDto = qualityClient.findAttachmentById(deliveryId, productId, + attachmentId); if (!attachmentDto.getData().isHasReportRevision()) { - throw new BusinessException("No se puede finalizar la tarea porque no se ha cargado el reporte de revisión al archivo XTF"); + throw new BusinessException( + "No se puede finalizar la tarea porque no se ha cargado el reporte de revisión al archivo XTF"); } qualityClient.udpdateXTFStatusToQualityProcessFinished(deliveryId, productId, attachmentId); @@ -471,15 +500,16 @@ public CustomTaskDto finishTask(Long taskId, MicroserviceUserDto userDto) throws taskDto = new CustomTaskDto(response); taskDto = this.extendTask(taskDto); } catch (Exception e) { - log.error("No se ha podido finalizar la tarea: " + e.getMessage()); + String messageError = String.format("Error finalizando la tarea %d: %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido finalizar la tarea."); } return taskDto; } - public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto userDto) - throws BusinessException { + public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto userDto) throws BusinessException { CustomTaskDto taskDto; @@ -487,6 +517,9 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto MicroserviceTaskDto response = taskClient.findTaskById(taskId); taskDto = new CustomTaskDto(response); } catch (Exception e) { + String messageError = String.format("Error consultando la tarea %d: %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado la tarea."); } @@ -498,8 +531,8 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto // verify if the user is assigned the task List responseMembers = taskDto.getMembers(); - List membersDto = - responseMembers.stream().map(CustomTaskMemberDto::new).collect(Collectors.toList()); + List membersDto = responseMembers.stream().map(CustomTaskMemberDto::new) + .collect(Collectors.toList()); CustomTaskMemberDto memberFound = membersDto.stream() .filter(memberDto -> memberDto.getMemberCode().equals(userDto.getId())).findAny().orElse(null); @@ -536,7 +569,11 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto cryptoBusiness.decrypt(integrationEntity.getDatabase()), cryptoBusiness.decrypt(integrationEntity.getUsername())); } catch (Exception e) { - log.error("No se ha podido borrar la base de datos: " + e.getMessage()); + String messageError = String.format( + "Error eliminando la base de datos a partir de la cancelación de la tarea %d: %s", + taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } String randomDatabaseName = RandomStringUtils.random(8, true, false).toLowerCase(); @@ -548,8 +585,11 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto databaseIntegrationBusiness.createDatabase(randomDatabaseName, randomUsername, randomPassword); } catch (Exception e) { - log.error("No se ha podido crear la base de datos para la integración: " - + e.getMessage()); + String messageError = String.format( + "Error creando la base de datos a partir de la cancelación de la tarea %d: %s", + taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } integrationBusiness.updateCredentialsIntegration(integrationId, @@ -562,7 +602,8 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto try { // file cadastre - MicroserviceSupplyDto responseCadastre = supplyClient.findSupplyById(integrationEntity.getSupplyCadastreId()); + MicroserviceSupplyDto responseCadastre = supplyClient + .findSupplyById(integrationEntity.getSupplyCadastreId()); CustomSupplyDto supplyCadastreDto = new CustomSupplyDto(responseCadastre); MicroserviceSupplyAttachmentDto attachmentCadastre = supplyCadastreDto.getAttachments() @@ -572,7 +613,8 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto .findAny().orElse(null); // file register - MicroserviceSupplyDto responseSnr = supplyClient.findSupplyById(integrationEntity.getSupplySnrId()); + MicroserviceSupplyDto responseSnr = supplyClient + .findSupplyById(integrationEntity.getSupplySnrId()); CustomSupplyDto supplyRegisteredDto = new CustomSupplyDto(responseSnr); MicroserviceSupplyAttachmentDto attachmentRegister = supplyRegisteredDto .getAttachments().stream() @@ -588,7 +630,11 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto integrationId, supplyCadastreDto.getModelVersion()); } catch (Exception e) { - log.error("No se ha podido iniciar la integración: " + e.getMessage()); + String messageError = String.format( + "Error iniciando la integración a partir de la cancelación de la tarea %d: %s", + taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } // modify integration state to finish assisted @@ -603,11 +649,14 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto } } catch (Exception e) { - log.error("No se ha podido empezar a generar el producto: " + e.getMessage()); + String messageError = String.format( + "Error al momento de cancelar una tarea correspondiente a una integración : %s", e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } MicroserviceTaskCategoryDto categoryGenerationFound = taskDto.getCategories().stream().filter( - categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)) + categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_CADASTRAL_INPUT_GENERATION)) .findAny().orElse(null); // task for generation of supplies @@ -670,11 +719,13 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto } } catch (Exception e) { - log.error("No se ha podido re-asignar la tarea: " + e.getMessage()); + String messageError = String.format("Error re-asignando la tarea %d : %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } - MicroserviceTaskCategoryDto categoryXTFQuality = taskDto.getCategories().stream().filter( - categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_XTF_QUALITY_PROCESS)) + MicroserviceTaskCategoryDto categoryXTFQuality = taskDto.getCategories().stream() + .filter(categoryDto -> categoryDto.getId().equals(TaskBusiness.TASK_CATEGORY_XTF_QUALITY_PROCESS)) .findAny().orElse(null); if (categoryXTFQuality != null) { @@ -683,14 +734,16 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto .filter(meta -> meta.getKey().equalsIgnoreCase("attachment")).findAny().orElse(null); if (metadataRequest != null) { - BusinessException error = new BusinessException("Ha ocurrido un error cancelando la tarea del proceso de calidad"); + BusinessException error = new BusinessException( + "Ha ocurrido un error cancelando la tarea del proceso de calidad"); - MicroserviceTaskMetadataPropertyDto propertyDeliveryId = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("deliveryId")).findAny().orElseThrow(() -> error); - MicroserviceTaskMetadataPropertyDto propertyDeliveryProductId = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("deliveryProductId")).findAny().orElseThrow(() -> error); - MicroserviceTaskMetadataPropertyDto propertyAttachmentId = metadataRequest.getProperties() - .stream().filter(p -> p.getKey().equalsIgnoreCase("attachmentId")).findAny().orElseThrow(() -> error); + MicroserviceTaskMetadataPropertyDto propertyDeliveryId = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("deliveryId")).findAny().orElseThrow(() -> error); + MicroserviceTaskMetadataPropertyDto propertyDeliveryProductId = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("deliveryProductId")).findAny() + .orElseThrow(() -> error); + MicroserviceTaskMetadataPropertyDto propertyAttachmentId = metadataRequest.getProperties().stream() + .filter(p -> p.getKey().equalsIgnoreCase("attachmentId")).findAny().orElseThrow(() -> error); Long deliveryId = Long.parseLong(propertyDeliveryId.getValue()); Long productId = Long.parseLong(propertyDeliveryProductId.getValue()); @@ -710,6 +763,9 @@ public CustomTaskDto cancelTask(Long taskId, String reason, MicroserviceUserDto taskDto = this.extendTask(taskDto); } catch (Exception e) { + String messageError = String.format("Error cancelando la tarea %d : %s", taskId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cancelar la tarea."); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceBusiness.java index b453f12..a9c67b3 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceBusiness.java @@ -45,6 +45,7 @@ import com.ai.st.microservice.workspaces.entities.WorkspaceManagerEntity; import com.ai.st.microservice.workspaces.entities.WorkspaceOperatorEntity; import com.ai.st.microservice.workspaces.services.*; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import com.ai.st.microservice.workspaces.utils.FileTool; import org.apache.commons.io.FilenameUtils; @@ -105,15 +106,16 @@ public class WorkspaceBusiness { private final IWorkspaceManagerService workspaceManagerService; public WorkspaceBusiness(ManagerFeignClient managerClient, ProviderFeignClient providerClient, - UserFeignClient userClient, SupplyFeignClient supplyClient, IMunicipalityService municipalityService, - IWorkspaceService workspaceService, IIntegrationService integrationService, IIntegrationStateService integrationStateService, - IWorkspaceOperatorService workspaceOperatorService, DatabaseIntegrationBusiness databaseIntegrationBusiness, - CrytpoBusiness cryptoBusiness, IntegrationBusiness integrationBusiness, TaskBusiness taskBusiness, - IliBusiness iliBusiness, ProviderBusiness providerBusiness, FileBusiness fileBusiness, - SupplyBusiness supplyBusiness, OperatorMicroserviceBusiness operatorBusiness, NotificationBusiness notificationBusiness, - ManagerMicroserviceBusiness managerBusiness, WorkspaceManagerBusiness workspaceManagerBusiness, - WorkspaceOperatorBusiness workspaceOperatorBusiness, AdministrationBusiness administrationBusiness, - IWorkspaceManagerService workspaceManagerService) { + UserFeignClient userClient, SupplyFeignClient supplyClient, IMunicipalityService municipalityService, + IWorkspaceService workspaceService, IIntegrationService integrationService, + IIntegrationStateService integrationStateService, IWorkspaceOperatorService workspaceOperatorService, + DatabaseIntegrationBusiness databaseIntegrationBusiness, CrytpoBusiness cryptoBusiness, + IntegrationBusiness integrationBusiness, TaskBusiness taskBusiness, IliBusiness iliBusiness, + ProviderBusiness providerBusiness, FileBusiness fileBusiness, SupplyBusiness supplyBusiness, + OperatorMicroserviceBusiness operatorBusiness, NotificationBusiness notificationBusiness, + ManagerMicroserviceBusiness managerBusiness, WorkspaceManagerBusiness workspaceManagerBusiness, + WorkspaceOperatorBusiness workspaceOperatorBusiness, AdministrationBusiness administrationBusiness, + IWorkspaceManagerService workspaceManagerService) { this.managerClient = managerClient; this.providerClient = providerClient; this.userClient = userClient; @@ -156,9 +158,8 @@ public List getWorkspacesByMunicipality(Long municipalityId, Long WorkspaceEntity workspaceActive = workspaceService.getWorkspaceActiveByMunicipality(municipalityEntity); if (workspaceActive != null) { - - WorkspaceManagerEntity workspaceManagerEntity = - workspaceActive.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceActive.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El gestor no tiene acceso al municipio."); } @@ -178,9 +179,8 @@ public List getWorkspacesByMunicipality(Long municipalityId, Long } public WorkspaceDto assignOperator(Long workspaceId, Date startDate, Date endDate, Long operatorCode, - Long numberParcelsExpected, Double workArea, MultipartFile supportFile, String observations, - Long managerCode) throws BusinessException { - + Long numberParcelsExpected, Double workArea, MultipartFile supportFile, String observations, + Long managerCode) throws BusinessException { // validate if the workspace exists WorkspaceEntity workspaceEntity = workspaceService.getWorkspaceById(workspaceId); @@ -199,7 +199,8 @@ public WorkspaceDto assignOperator(Long workspaceId, Date startDate, Date endDat throw new BusinessException("La fecha de finalización debe ser mayor a la fecha de inicio."); } - WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El usuario no tiene acceso al espacio de trabajo."); } @@ -221,7 +222,10 @@ public WorkspaceDto assignOperator(Long workspaceId, Date startDate, Date endDat urlBase = FileTool.removeAccents(urlBase); urlDocumentaryRepository = fileBusiness.saveFileToSystem(supportFile, urlBase, false); } catch (Exception e) { - log.error("No se ha podido cargar el soporte operador: " + e.getMessage()); + String messageError = String.format("Error guardando el soporte al momento de asignar el operador %d: %s", + operatorCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cargar el soporte."); } @@ -233,8 +237,9 @@ public WorkspaceDto assignOperator(Long workspaceId, Date startDate, Date endDat throw new BusinessException("El operador ya ha sido asignado al municipio."); } - WorkspaceOperatorDto workspaceOperatorDto = workspaceOperatorBusiness.createOperator(startDate, endDate, numberParcelsExpected, workArea, observations, - urlDocumentaryRepository, workspaceId, operatorCode, managerCode); + WorkspaceOperatorDto workspaceOperatorDto = workspaceOperatorBusiness.createOperator(startDate, endDate, + numberParcelsExpected, workArea, observations, urlDocumentaryRepository, workspaceId, operatorCode, + managerCode); // send notification try { @@ -252,7 +257,11 @@ public WorkspaceDto assignOperator(Long workspaceId, Date startDate, Date endDat } } } catch (Exception e) { - log.error("Error enviando notificación al asignar operador: " + e.getMessage()); + String messageError = String.format( + "Error enviando la notificación al asignar operador al espacio de trabajo %d : %s", workspaceId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } WorkspaceDto workspaceDto = entityParseToDto(workspaceEntity); @@ -262,7 +271,7 @@ public WorkspaceDto assignOperator(Long workspaceId, Date startDate, Date endDat } public WorkspaceDto updateManagerFromWorkspace(Long workspaceId, Long managerCode, Date startDate, - String observations) throws BusinessException { + String observations) throws BusinessException { WorkspaceDto workspaceDto; @@ -326,19 +335,20 @@ public List getOperatorsByWorkspaceId(Long workspaceId, Lo // validate access if (managerCode != null) { - WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers() - .stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El usuario no tiene acceso al espacio de trabajo."); } - listOperatorsDto = workspaceEntity.getOperators().stream().filter(o -> o.getManagerCode().equals(managerCode)) + listOperatorsDto = workspaceEntity.getOperators().stream() + .filter(o -> o.getManagerCode().equals(managerCode)) .map(workspaceOperatorBusiness::entityParseToDto).collect(Collectors.toList()); } else { - listOperatorsDto = workspaceEntity.getOperators().stream() - .map(workspaceOperatorBusiness::entityParseToDto).collect(Collectors.toList()); + listOperatorsDto = workspaceEntity.getOperators().stream().map(workspaceOperatorBusiness::entityParseToDto) + .collect(Collectors.toList()); } @@ -363,8 +373,8 @@ public WorkspaceDto getWorkspaceActiveByMunicipality(Long municipalityId, Long m // validate access if (managerCode != null) { - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El usuario no tiene acceso al espacio de trabajo."); } @@ -374,8 +384,8 @@ public WorkspaceDto getWorkspaceActiveByMunicipality(Long municipalityId, Long m return entityParseToDto(workspaceEntity); } - public List createRequest(Date deadline, List supplies, - Long userCode, Long managerCode, Long municipalityId) throws BusinessException { + public List createRequest(Date deadline, List supplies, Long userCode, + Long managerCode, Long municipalityId) throws BusinessException { // validate if the municipality exists MunicipalityEntity municipalityEntity = municipalityService.getMunicipalityById(municipalityId); @@ -386,11 +396,10 @@ public List createRequest(Date deadline, List m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El usuario no tiene acceso al espacio de trabajo."); } @@ -505,26 +514,30 @@ public List createRequest(Date deadline, List p.getId().equals(providerProfileId)).findAny() - .ifPresent(profileFound -> notificationBusiness.sendNotificationInputRequest(userDto.getEmail(), userCode, - managerDto.getName(), municipalityEntity.getName(), - municipalityEntity.getDepartment().getName(), responseRequest.getId().toString(), - new Date())); + providerUser.getProfiles().stream().filter(p -> p.getId().equals(providerProfileId)) + .findAny() + .ifPresent(profileFound -> notificationBusiness.sendNotificationInputRequest( + userDto.getEmail(), userCode, managerDto.getName(), + municipalityEntity.getName(), municipalityEntity.getDepartment().getName(), + responseRequest.getId().toString(), new Date())); } - } } catch (Exception er) { - log.error("Error enviando la notificación por solicitud de insumos: " + er.getMessage()); + String messageError = String.format( + "Error enviando la notificación a los proveedores por solicitud de insumos : %s", + er.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (responseRequest.getProvider().getId().equals(ProviderBusiness.PROVIDER_IGAC_ID)) { - List suppliesResponse = responseRequest.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesResponse = responseRequest + .getSuppliesRequested(); + List suppliesRequestDto = suppliesResponse.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); CustomSupplyRequestedDto supplyRequested = suppliesRequestDto.stream() .filter(sR -> sR.getTypeSupply().getId().equals(ProviderBusiness.PROVIDER_SUPPLY_CADASTRAL)) @@ -545,12 +558,15 @@ public List createRequest(Date deadline, List createRequest(Date deadline, List createRequest(Date deadline, List getPendingRequestByProvider(Long userCode, Long providerId) - throws BusinessException { + public List getPendingRequestByProvider(Long userCode, Long providerId) throws BusinessException { List listPendingRequestsDto = new ArrayList<>(); @@ -580,17 +597,19 @@ public List getPendingRequestByProvider(Long userCode, Long pr throw new BusinessException("El usuario no esta registrado como usuario para el proveedor de insumo."); } - List response = providerClient.getRequestsByProvider(providerId, ProviderBusiness.REQUEST_STATE_REQUESTED); + List response = providerClient.getRequestsByProvider(providerId, + ProviderBusiness.REQUEST_STATE_REQUESTED); - List responseRequestsDto = response.stream().map(CustomRequestDto::new).collect(Collectors.toList()); + List responseRequestsDto = response.stream().map(CustomRequestDto::new) + .collect(Collectors.toList()); for (CustomRequestDto requestDto : responseRequestsDto) { List emittersDto = new ArrayList<>(); List emittersResponse = requestDto.getEmitters(); - List emitterDtoList = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); + List emitterDtoList = emittersResponse.stream().map(CustomEmitterDto::new) + .collect(Collectors.toList()); for (CustomEmitterDto emitterDto : emitterDtoList) { @@ -599,6 +618,10 @@ public List getPendingRequestByProvider(Long userCode, Long pr MicroserviceManagerDto managerDto = managerClient.findById(emitterDto.getEmitterCode()); emitterDto.setUser(managerDto); } catch (Exception e) { + String messageError = String.format("Error consultando el gestor %d : %s", + emitterDto.getEmitterCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); emitterDto.setUser(null); } } else { @@ -606,6 +629,10 @@ public List getPendingRequestByProvider(Long userCode, Long pr MicroserviceUserDto userDto = userClient.findById(emitterDto.getEmitterCode()); emitterDto.setUser(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + emitterDto.getEmitterCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); emitterDto.setUser(null); } } @@ -628,8 +655,8 @@ public List getPendingRequestByProvider(Long userCode, Long pr requestDto.setMunicipality(municipalityDto); List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestDto = suppliesResponse.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); for (CustomSupplyRequestedDto supply : suppliesRequestDto) { @@ -640,6 +667,10 @@ public List getPendingRequestByProvider(Long userCode, Long pr MicroserviceUserDto userDto = userClient.findById(supply.getDeliveredBy()); supply.setUserDeliveryBy(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + supply.getDeliveredBy(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); supply.setUserDeliveryBy(null); } @@ -653,8 +684,8 @@ public List getPendingRequestByProvider(Long userCode, Long pr int countNot = 0; List suppliesResponseDto = requestDto.getSuppliesRequested(); - List suppliesRequestedDto = - suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestedDto = suppliesResponseDto.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); for (CustomSupplyRequestedDto supply : suppliesRequestedDto) { @@ -667,10 +698,10 @@ public List getPendingRequestByProvider(Long userCode, Long pr if (supply.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_PENDING_REVIEW) || supply.getState().getId() - .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_SETTING_REVIEW) + .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_SETTING_REVIEW) || supply.getState().getId().equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW) || supply.getState().getId() - .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_CLOSING_REVIEW)) { + .equals(ProviderBusiness.SUPPLY_REQUESTED_STATE_CLOSING_REVIEW)) { supply.setCanUpload(false); countNot++; @@ -697,29 +728,34 @@ public List getPendingRequestByProvider(Long userCode, Long pr } } catch (Exception e) { - log.error("No se han podido cargar las solicitudes pendientes del proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando las solicitudes pendientes del proveedor %d : %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return listPendingRequestsDto; } - public List getClosedRequestByProvider(Long userCode, Long providerId) - throws BusinessException { + public List getClosedRequestByProvider(Long userCode, Long providerId) throws BusinessException { List listClosedRequestsDto = new ArrayList<>(); try { List response = providerClient.getRequestsByProviderClosed(providerId, userCode); - List responseRequestsDto = response.stream().map(CustomRequestDto::new).collect(Collectors.toList()); + List responseRequestsDto = response.stream().map(CustomRequestDto::new) + .collect(Collectors.toList()); + + log.info("Requests found: " + responseRequestsDto.size()); for (CustomRequestDto requestDto : responseRequestsDto) { List emittersDto = new ArrayList<>(); List emittersResponse = requestDto.getEmitters(); - List emittersRequestDto = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); + List emittersRequestDto = emittersResponse.stream().map(CustomEmitterDto::new) + .collect(Collectors.toList()); for (CustomEmitterDto emitterDto : emittersRequestDto) { if (emitterDto.getEmitterType().equals("ENTITY")) { @@ -727,6 +763,10 @@ public List getClosedRequestByProvider(Long userCode, Long pro MicroserviceManagerDto managerDto = managerClient.findById(emitterDto.getEmitterCode()); emitterDto.setUser(managerDto); } catch (Exception e) { + String messageError = String.format("Error consultando el gestor %d : %s", + emitterDto.getEmitterCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); emitterDto.setUser(null); } } else { @@ -734,6 +774,10 @@ public List getClosedRequestByProvider(Long userCode, Long pro MicroserviceUserDto userDto = userClient.findById(emitterDto.getEmitterCode()); emitterDto.setUser(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + emitterDto.getEmitterCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); emitterDto.setUser(null); } } @@ -761,12 +805,16 @@ public List getClosedRequestByProvider(Long userCode, Long pro requestDto.setUserClosedBy(userDto); } } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + requestDto.getClosedBy(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); requestDto.setUserClosedBy(null); } List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestDto = suppliesResponse.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); for (CustomSupplyRequestedDto supply : suppliesRequestDto) { @@ -777,6 +825,10 @@ public List getClosedRequestByProvider(Long userCode, Long pro MicroserviceUserDto userDto = userClient.findById(supply.getDeliveredBy()); supply.setUserDeliveryBy(userDto); } catch (Exception e) { + String messageError = String.format("Error consultando el usuario %d : %s", + supply.getDeliveredBy(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); supply.setUserDeliveryBy(null); } @@ -789,16 +841,17 @@ public List getClosedRequestByProvider(Long userCode, Long pro } } catch (Exception e) { - log.error("No se han podido cargar las solicitudes cerradas del proveedor: " + e.getMessage()); + String messageError = String.format("Error consultando las solicitudes cerradas del proveedor %d : %s", + providerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return listClosedRequestsDto; } public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, Long supplyIdCadastre, - Long supplyIdRegistration, - MicroserviceManagerDto managerDto, - MicroserviceUserDto userDto) + Long supplyIdRegistration, MicroserviceManagerDto managerDto, MicroserviceUserDto userDto) throws BusinessException { IntegrationDto integrationResponseDto; @@ -814,8 +867,8 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L throw new BusinessException("El municipio no cuenta con un espacio de trabajo activo."); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceActive.getManagers().stream().filter(m -> m.getManagerCode().equals(managerDto.getId())).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceActive.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerDto.getId())).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("No tiene acceso al municipio."); } @@ -827,8 +880,8 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L statesId.add(IntegrationStateBusiness.STATE_STARTED_ASSISTED); statesId.add(IntegrationStateBusiness.STATE_FINISHED_ASSISTED); - List integrationsPending = integrationService - .getPendingIntegrations(workspaceActive.getId(), statesId, managerDto.getId()); + List integrationsPending = integrationService.getPendingIntegrations(workspaceActive.getId(), + statesId, managerDto.getId()); if (integrationsPending.size() > 0) { throw new BusinessException("Existe una integración en curso para el municipio."); @@ -853,6 +906,10 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L pathFileCadastre = attachment.getData(); } catch (Exception e) { + String messageError = String.format("Error consultando el tipo de insumo de catastro %d : %s", + supplyIdCadastre, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar el tipo de insumo."); } if (supplyCadastreDto.getTypeSupply().getProvider().getProviderCategory().getId() != 1) { @@ -881,6 +938,10 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L pathFileRegistration = attachment.getData(); } catch (Exception e) { + String messageError = String.format("Error consultando el tipo de insumo de registro %d : %s", + supplyIdRegistration, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido consultar el tipo de insumo."); } if (supplyRegisteredDto.getTypeSupply().getProvider().getProviderCategory().getId() != 2) { @@ -938,7 +999,10 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L integrationId = integrationResponseDto.getId(); } catch (Exception e) { - log.error("No se ha podido crear la integración: " + e.getMessage()); + String messageError = String.format("Error creando la integración catastro(%d)-registro(%d) : %s", + supplyIdCadastre, supplyIdRegistration, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido crear la integración."); } @@ -951,7 +1015,10 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L } catch (Exception e) { integrationBusiness.updateStateToIntegration(integrationId, IntegrationStateBusiness.STATE_ERROR_INTEGRATION_AUTOMATIC, e.getMessage(), null, null, "SISTEMA"); - log.error("No se ha podido iniciar la integración: " + e.getMessage()); + String messageError = String.format("Error iniciando la integración catastro(%d)-registro(%d) : %s", + supplyIdCadastre, supplyIdRegistration, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido iniciar la integración."); } @@ -959,7 +1026,7 @@ public IntegrationDto makeIntegrationCadastreRegistration(Long municipalityId, L } public IntegrationDto startIntegrationAssisted(Long workspaceId, Long integrationId, - MicroserviceManagerDto managerDto, MicroserviceUserDto userDto) throws BusinessException { + MicroserviceManagerDto managerDto, MicroserviceUserDto userDto) throws BusinessException { IntegrationDto integrationDto; @@ -974,8 +1041,8 @@ public IntegrationDto startIntegrationAssisted(Long workspaceId, Long integratio "No se puede iniciar la integración ya que le espacio de trabajo no es el actual."); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerDto.getId())).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerDto.getId())).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("No tiene acceso al municipio."); } @@ -1000,7 +1067,8 @@ public IntegrationDto startIntegrationAssisted(Long workspaceId, Long integratio String textHistory = userDto.getFirstName() + " " + userDto.getLastName() + " - " + managerDto.getName(); integrationDto = integrationBusiness.updateStateToIntegration(integrationId, - IntegrationStateBusiness.STATE_STARTED_ASSISTED, null, userDto.getId(), managerDto.getId(), textHistory); + IntegrationStateBusiness.STATE_STARTED_ASSISTED, null, userDto.getId(), managerDto.getId(), + textHistory); String host = integrationEntity.getHostname(); String port = integrationEntity.getPort(); @@ -1014,7 +1082,10 @@ public IntegrationDto startIntegrationAssisted(Long workspaceId, Long integratio cryptoBusiness.decrypt(database), cryptoBusiness.decrypt(schema), cryptoBusiness.decrypt(username), cryptoBusiness.decrypt(password)); } catch (Exception e) { - log.error("No se ha podido restringir la base de datos: " + e.getMessage()); + String messageError = String.format("Error configurando la base de datos de la integración %d : %s", + integrationId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } // create task @@ -1077,7 +1148,8 @@ public IntegrationDto startIntegrationAssisted(Long workspaceId, Long integratio for (MicroserviceManagerUserDto managerUserDto : listUsersIntegrators) { - MicroserviceUserDto userIntegratorDto = administrationBusiness.getUserById(managerUserDto.getUserCode()); + MicroserviceUserDto userIntegratorDto = administrationBusiness + .getUserById(managerUserDto.getUserCode()); if (userIntegratorDto != null && userDto.getEnabled()) { notificationBusiness.sendNotificationTaskAssignment(userIntegratorDto.getEmail(), userIntegratorDto.getId(), name, municipalityEntity.getName(), @@ -1087,19 +1159,25 @@ public IntegrationDto startIntegrationAssisted(Long workspaceId, Long integratio } } catch (Exception e) { - log.error("Error enviando notificación a los usuarios que se les ha asignado una tarea de integración: " - + e.getMessage()); + String messageError = String.format( + "Error enviando notificación al usuario ya que se le ha asignado una tarea para la integración %d : %s", + integrationId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } catch (Exception e) { - log.error("No se ha podido crear la tarea de integración: " + e.getMessage()); + String messageError = String.format("Error creando la tarea para la integración %d : %s", integrationId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return integrationDto; } public IntegrationDto exportXtf(Long workspaceId, Long integrationId, MicroserviceManagerDto managerDto, - MicroserviceUserDto userDto) throws BusinessException { + MicroserviceUserDto userDto) throws BusinessException { IntegrationDto integrationDto; @@ -1114,8 +1192,8 @@ public IntegrationDto exportXtf(Long workspaceId, Long integrationId, Microservi "No se puede iniciar la integración ya que le espacio de trabajo no es el actual."); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerDto.getId())).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerDto.getId())).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("No tiene acceso al municipio."); } @@ -1148,8 +1226,8 @@ public IntegrationDto exportXtf(Long workspaceId, Long integrationId, Microservi MicroserviceSupplyDto response = supplyClient.findSupplyById(integrationEntity.getSupplyCadastreId()); CustomSupplyDto supplyCadastreDto = new CustomSupplyDto(response); - String urlBase = "/" + workspaceEntity.getMunicipality().getCode().replace(" ", "_") - + "/insumos/gestores/" + managerDto.getId(); + String urlBase = "/" + workspaceEntity.getMunicipality().getCode().replace(" ", "_") + "/insumos/gestores/" + + managerDto.getId(); iliBusiness.startExport(hostnameDecrypt, databaseDecrypt, databaseIntegrationPassword, portDecrypt, schemaDecrypt, databaseIntegrationUsername, integrationId, false, @@ -1162,7 +1240,10 @@ public IntegrationDto exportXtf(Long workspaceId, Long integrationId, Microservi textHistory); } catch (Exception e) { - log.error("No se ha podido iniciar la generación del insumo: " + e.getMessage()); + String messageError = String.format("Error iniciando la generación del insumo para la integración %d : %s", + integrationId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido iniciar la generación del insumo"); } @@ -1188,9 +1269,10 @@ public void removeIntegrationFromWorkspace(Long workspaceId, Long integrationId, throw new BusinessException("No se ha encontrado la integración."); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode) - && integrationEntity.getManagerCode().equals(m.getManagerCode())).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode) + && integrationEntity.getManagerCode().equals(m.getManagerCode())) + .findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El gestor no tiene acceso al municipio."); } @@ -1212,7 +1294,10 @@ public void removeIntegrationFromWorkspace(Long workspaceId, Long integrationId, integrationBusiness.deleteIntegration(integrationId); } catch (Exception e) { - log.error("Error intentando eliminar la integración: " + e.getMessage()); + String messageError = String.format("Error eliminando la integración %d : %s", integrationId, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido eliminar la integración."); } @@ -1230,8 +1315,8 @@ public boolean managerHasAccessToMunicipality(String municipalityCode, Long mana WorkspaceEntity workspaceActive = workspaceService.getWorkspaceActiveByMunicipality(municipalityEntity); if (workspaceActive != null) { - WorkspaceManagerEntity workspaceManagerEntity = - workspaceActive.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceActive.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity != null) { hasAccess = true; } @@ -1252,13 +1337,17 @@ public void removeSupply(Long workspaceId, Long supplyId, Long managerCode) thro for (MicroserviceSupplyAttachmentDto attachment : supplyDto.getAttachments()) { if (attachment.getAttachmentType().getId().equals(SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY) || attachment.getAttachmentType().getId() - .equals(SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_EXTERNAL_SOURCE)) { + .equals(SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_EXTERNAL_SOURCE)) { pathsFile.add(attachment.getData()); } } } catch (Exception e) { - log.error("No se ha encontrado el insumo para eliminarlo: " + e.getMessage()); + String messageError = String.format( + "Error consultando el insumo %d en el espacio de trabajo %d para eliminarlo : %s", supplyId, + workspaceId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha encontrado el insumo."); } @@ -1274,8 +1363,8 @@ public void removeSupply(Long workspaceId, Long supplyId, Long managerCode) thro throw new BusinessException("El espacio de trabajo no se encuentra activo."); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("No tiene acceso al municipio."); } @@ -1301,7 +1390,7 @@ public void removeSupply(Long workspaceId, Long supplyId, Long managerCode) thro } public CustomDeliveryDto createDelivery(Long workspaceId, Long managerCode, Long operatorCode, String observations, - List suppliesDto) throws BusinessException { + List suppliesDto) throws BusinessException { CustomDeliveryDto deliveryDto; @@ -1316,8 +1405,8 @@ public CustomDeliveryDto createDelivery(Long workspaceId, Long managerCode, Long "No se puede iniciar la integración ya que le espacio de trabajo no es el actual."); } - WorkspaceManagerEntity workspaceManagerEntity = - workspaceEntity.getManagers().stream().filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceManagerEntity workspaceManagerEntity = workspaceEntity.getManagers().stream() + .filter(m -> m.getManagerCode().equals(managerCode)).findAny().orElse(null); if (workspaceManagerEntity == null) { throw new BusinessException("El gestor no tiene acceso al municipio."); } @@ -1327,9 +1416,9 @@ public CustomDeliveryDto createDelivery(Long workspaceId, Long managerCode, Long throw new BusinessException("El municipio no tiene asignado ningún operador."); } - WorkspaceOperatorEntity workspaceOperatorEntity = - operators.stream().filter(o -> o.getOperatorCode().equals(operatorCode) && o.getManagerCode().equals(managerCode)). - findAny().orElse(null); + WorkspaceOperatorEntity workspaceOperatorEntity = operators.stream() + .filter(o -> o.getOperatorCode().equals(operatorCode) && o.getManagerCode().equals(managerCode)) + .findAny().orElse(null); if (workspaceOperatorEntity == null) { throw new BusinessException("El municipio no tiene asignado el operador."); } @@ -1358,8 +1447,8 @@ public CustomDeliveryDto createDelivery(Long workspaceId, Long managerCode, Long for (CustomDeliveryDto deliveryFoundDto : deliveriesDto) { List suppliesResponse = deliveryFoundDto.getSupplies(); - List suppliesDeliveryDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveryDto = suppliesResponse.stream() + .map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); CustomSupplyDeliveryDto supplyFound = suppliesDeliveryDto.stream() .filter(supplyDto -> supplyDto.getSupplyCode().equals(deliverySupplyDto.getSupplyId())) @@ -1367,7 +1456,8 @@ public CustomDeliveryDto createDelivery(Long workspaceId, Long managerCode, Long if (supplyFound != null) { - String nameSupply = (supply.getTypeSupply() != null) ? supply.getTypeSupply().getName() : supply.getObservations(); + String nameSupply = (supply.getTypeSupply() != null) ? supply.getTypeSupply().getName() + : supply.getObservations(); String messageError = String.format("El insumo %s ya ha sido entregado al operador.", nameSupply); throw new BusinessException(messageError); @@ -1398,18 +1488,26 @@ public CustomDeliveryDto createDelivery(Long workspaceId, Long managerCode, Long } } catch (Exception e) { - log.error("Error enviando notificación de entrega de insumos al operador: " + e.getMessage()); + String messageError = String.format( + "Error enviando la notificación de entrega de insumos al operador %d : %s", operatorCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } catch (Exception e) { - log.error("No se ha podido realizar la entrega al operador: " + e.getMessage()); + String messageError = String.format("Error realizando la entrega de insumos al operador %d : %s", + operatorCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido realizar la entrega al operador."); } return deliveryDto; } - public String getManagerSupportURL(Long workspaceId, Long managerCode, Long managerCodeSession) throws BusinessException { + public String getManagerSupportURL(Long workspaceId, Long managerCode, Long managerCodeSession) + throws BusinessException { String supportURL = null; @@ -1620,7 +1718,7 @@ public List validateMunicipalitiesToAssign(List assignManager(Date startDate, Long managerCode, - List municipalities, String observations, MultipartFile supportFile) + List municipalities, String observations, MultipartFile supportFile) throws BusinessException { List workspacesDto = new ArrayList<>(); @@ -1647,7 +1745,6 @@ public List assignManager(Date startDate, Long managerCode, } - for (MunicipalityToAssignDto municipalityToAssign : municipalities) { MunicipalityEntity municipalityEntity = municipalityService @@ -1661,7 +1758,10 @@ public List assignManager(Date startDate, Long managerCode, urlDocumentaryRepository = fileBusiness.saveFileToSystem(supportFile, urlBase, false); } catch (Exception e) { - log.error("No se ha podido cargar el soporte gestor: " + e.getMessage()); + String messageError = String.format("Error guardando el soporte de asignación del gestor %d : %s", + managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cargar el soporte."); } @@ -1689,21 +1789,25 @@ public List assignManager(Date startDate, Long managerCode, // send notification try { - List directors = managerBusiness.getUserByManager(managerDto.getId(), + List directors = managerBusiness.getUsersByManager(managerDto.getId(), new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_DIRECTOR_MANAGER))); for (MicroserviceManagerUserDto directorDto : directors) { MicroserviceUserDto userDto = administrationBusiness.getUserById(directorDto.getUserCode()); if (userDto != null && userDto.getEnabled()) { - notificationBusiness.sendNotificationMunicipalityManagementDto(userDto.getEmail(), municipalityEntity.getDepartment().getName(), - municipalityEntity.getName(), startDate, userDto.getId(), ""); + notificationBusiness.sendNotificationMunicipalityManagementDto(userDto.getEmail(), + municipalityEntity.getDepartment().getName(), municipalityEntity.getName(), startDate, + userDto.getId(), ""); } } } catch (Exception e) { - log.error("Error enviando notificación al asignar gestor: " + e.getMessage()); + String messageError = String.format("Error enviando notificación al asignar el gestor %d : %s", + managerCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } WorkspaceDto workspaceDto = entityParseToDto(workspaceEntity); @@ -1714,8 +1818,9 @@ public List assignManager(Date startDate, Long managerCode, return workspacesDto; } - public WorkspaceDto updateOperatorFromWorkspace(Long workspaceId, Long managerCode, Long operatorCode, Date startDate, Date endDate, String observations, - Long numberParcelsExpected, Double workArea, MultipartFile supportFile) throws BusinessException { + public WorkspaceDto updateOperatorFromWorkspace(Long workspaceId, Long managerCode, Long operatorCode, + Date startDate, Date endDate, String observations, Long numberParcelsExpected, Double workArea, + MultipartFile supportFile) throws BusinessException { WorkspaceDto workspaceDto; @@ -1741,7 +1846,9 @@ public WorkspaceDto updateOperatorFromWorkspace(Long workspaceId, Long managerCo throw new BusinessException("El gestor no pertenece al municipio."); } - WorkspaceOperatorEntity workspaceOperatorFound = workspaceEntity.getOperators().stream().filter(o -> o.getOperatorCode().equals(operatorCode) && o.getManagerCode().equals(managerCode)).findAny().orElse(null); + WorkspaceOperatorEntity workspaceOperatorFound = workspaceEntity.getOperators().stream() + .filter(o -> o.getOperatorCode().equals(operatorCode) && o.getManagerCode().equals(managerCode)) + .findAny().orElse(null); if (workspaceOperatorFound == null) { throw new BusinessException("El gestor no tiene permitido editar el operador."); } @@ -1754,7 +1861,10 @@ public WorkspaceDto updateOperatorFromWorkspace(Long workspaceId, Long managerCo urlBase = FileTool.removeAccents(urlBase); urlDocumentaryRepository = fileBusiness.saveFileToSystem(supportFile, urlBase, false); } catch (Exception e) { - log.error("No se ha podido cargar el soporte operador: " + e.getMessage()); + String messageError = String.format("Error guardando el soporte de asignación del operador %d : %s", + operatorCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido cargar el soporte."); } @@ -1770,7 +1880,8 @@ public WorkspaceDto updateOperatorFromWorkspace(Long workspaceId, Long managerCo return workspaceDto; } - public String getOperatorSupportURL(Long workspaceId, Long operatorCode, Long managerCodeSession) throws BusinessException { + public String getOperatorSupportURL(Long workspaceId, Long operatorCode, Long managerCodeSession) + throws BusinessException { String supportURL; @@ -1806,8 +1917,8 @@ public String getOperatorSupportURL(Long workspaceId, Long operatorCode, Long ma public List getWorkspacesByOperator(Long operatorCode) { - List workspaceOperatorEntities = - workspaceOperatorService.getWorkspacesOperatorsByOperatorCode(operatorCode); + List workspaceOperatorEntities = workspaceOperatorService + .getWorkspacesOperatorsByOperatorCode(operatorCode); List workspacesOperators = new ArrayList<>(); @@ -1819,15 +1930,15 @@ public List getWorkspacesByOperator(Long operatorCode) { return workspacesOperators; } - public WorkspaceManagerDto getWorkspacesByManagerAndMunicipality(Long managerCode, String municipalityCode) throws BusinessException { + public WorkspaceManagerDto getWorkspacesByManagerAndMunicipality(Long managerCode, String municipalityCode) + throws BusinessException { - List workspaceManagerEntities = - workspaceManagerService.getWorkspaceManagerByManager(managerCode); + List workspaceManagerEntities = workspaceManagerService + .getWorkspaceManagerByManager(managerCode); WorkspaceManagerEntity workspaceManagerEntity = workspaceManagerEntities.stream() .filter(wM -> wM.getWorkspace().getMunicipality().getCode().equalsIgnoreCase(municipalityCode)) - .findAny() - .orElseThrow(() -> new BusinessException("")); + .findAny().orElseThrow(() -> new BusinessException("")); return workspaceManagerBusiness.entityParseToDto(workspaceManagerEntity); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceManagerBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceManagerBusiness.java index 70df208..dc797fa 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceManagerBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceManagerBusiness.java @@ -8,6 +8,9 @@ import com.ai.st.microservice.workspaces.services.IWorkspaceManagerService; import com.ai.st.microservice.workspaces.services.IWorkspaceService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Date; @@ -15,19 +18,21 @@ @Component public class WorkspaceManagerBusiness { + private final Logger log = LoggerFactory.getLogger(WorkspaceManagerBusiness.class); + private final IWorkspaceManagerService workspaceManagerService; private final IWorkspaceService workspaceService; private final ManagerMicroserviceBusiness managerBusiness; - public WorkspaceManagerBusiness(IWorkspaceManagerService workspaceManagerService, IWorkspaceService workspaceService, - ManagerMicroserviceBusiness managerBusiness) { + public WorkspaceManagerBusiness(IWorkspaceManagerService workspaceManagerService, + IWorkspaceService workspaceService, ManagerMicroserviceBusiness managerBusiness) { this.workspaceManagerService = workspaceManagerService; this.workspaceService = workspaceService; this.managerBusiness = managerBusiness; } public WorkspaceManagerDto createWorkspaceManager(Long managerCode, String specificObservations, - String generalObservations, Date startDate, String urlSupportFile, Long workspaceId) { + String generalObservations, Date startDate, String urlSupportFile, Long workspaceId) { WorkspaceEntity workspaceEntity = workspaceService.getWorkspaceById(workspaceId); @@ -76,6 +81,10 @@ public WorkspaceManagerDto entityParseToDto(WorkspaceManagerEntity workspaceMana MicroserviceManagerDto managerDto = managerBusiness.getManagerById(workspaceManagerEntity.getManagerCode()); workspaceManagerDto.setManager(managerDto); } catch (Exception e) { + String messageError = String.format("Error consultando el gestor %d : %s", + workspaceManagerEntity.getManagerCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); workspaceManagerDto.setManager(null); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceOperatorBusiness.java b/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceOperatorBusiness.java index 71ac9a9..d88e84b 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceOperatorBusiness.java +++ b/src/main/java/com/ai/st/microservice/workspaces/business/WorkspaceOperatorBusiness.java @@ -22,6 +22,7 @@ import com.ai.st.microservice.workspaces.dto.supplies.CustomSupplyDto; import com.ai.st.microservice.workspaces.entities.WorkspaceOperatorEntity; import com.ai.st.microservice.workspaces.services.IWorkspaceOperatorService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import com.ai.st.microservice.workspaces.utils.DateTool; import org.slf4j.Logger; @@ -49,10 +50,10 @@ public class WorkspaceOperatorBusiness { private final AdministrationBusiness administrationBusiness; public WorkspaceOperatorBusiness(IWorkspaceOperatorService operatorService, IWorkspaceService workspaceService, - IWorkspaceOperatorService workspaceOperatorService, OperatorMicroserviceBusiness operatorBusiness, - ReportBusiness reportBusiness, MunicipalityBusiness municipalityBusiness, - ManagerMicroserviceBusiness managerBusiness, SupplyBusiness supplyBusiness, - AdministrationBusiness administrationBusiness) { + IWorkspaceOperatorService workspaceOperatorService, OperatorMicroserviceBusiness operatorBusiness, + ReportBusiness reportBusiness, MunicipalityBusiness municipalityBusiness, + ManagerMicroserviceBusiness managerBusiness, SupplyBusiness supplyBusiness, + AdministrationBusiness administrationBusiness) { this.operatorService = operatorService; this.workspaceService = workspaceService; this.workspaceOperatorService = workspaceOperatorService; @@ -73,8 +74,8 @@ public CustomDeliveryDto getDeliveryFromSupply(Long operatorCode, Long supplyCod for (CustomDeliveryDto delivery : deliveries) { List suppliesResponse = delivery.getSupplies(); - List suppliesDeliveryDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveryDto = suppliesResponse.stream() + .map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); CustomSupplyDeliveryDto supplyDto = suppliesDeliveryDto.stream() .filter(s -> s.getSupplyCode().equals(supplyCode)).findAny().orElse(null); @@ -86,21 +87,23 @@ public CustomDeliveryDto getDeliveryFromSupply(Long operatorCode, Long supplyCod } } catch (Exception e) { - log.error("Error consultando la entrega por insumo: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega a partir del insumo %d : %s", supplyCode, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido obtener la entrega correspondiente al insumo."); } return null; } - public CustomDeliveryDto registerDownloadSupply(CustomDeliveryDto deliveryDto, Long supplyCode, - Long userCode) { + public CustomDeliveryDto registerDownloadSupply(CustomDeliveryDto deliveryDto, Long supplyCode, Long userCode) { try { List suppliesResponse = deliveryDto.getSupplies(); - List suppliesDeliveryDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveryDto = suppliesResponse.stream() + .map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); CustomSupplyDeliveryDto supplyDto = suppliesDeliveryDto.stream() .filter(s -> s.getSupplyCode().equals(supplyCode)).findAny().orElse(null); @@ -111,7 +114,10 @@ public CustomDeliveryDto registerDownloadSupply(CustomDeliveryDto deliveryDto, L } } catch (Exception e) { - log.error("Error consultando la entrega por insumo: " + e.getMessage()); + String messageError = String.format("Error actualizando la entrega %d y el insumo %d : %s", + deliveryDto.getId(), supplyCode, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return deliveryDto; @@ -124,7 +130,10 @@ public CustomDeliveryDto disableDelivery(Long operatorId, Long deliveryId) throw try { deliveryDto = operatorBusiness.getDeliveryId(deliveryId); } catch (Exception e) { - log.error("Error consultando entrega por id: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega %d del operador %d: %s", deliveryId, + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (deliveryDto == null) { @@ -138,6 +147,10 @@ public CustomDeliveryDto disableDelivery(Long operatorId, Long deliveryId) throw try { deliveryDto = operatorBusiness.disableDelivery(deliveryId); } catch (Exception e) { + String messageError = String.format("Error desactivando la entrega %d del operador %d: %s", deliveryId, + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); throw new BusinessException("No se ha podido desactivar la entrega."); } @@ -153,13 +166,18 @@ public String generateReportDownloadSupplyIndividual(Long operatorId, Long deliv try { deliveryDto = operatorBusiness.getDeliveryId(deliveryId); } catch (Exception e) { - log.error("Error consultando entrega por id: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega %d del operador %d: %s", deliveryId, + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } try { operatorDto = operatorBusiness.getOperatorById(operatorId); } catch (Exception e) { - log.error("Error consultando operador por id: " + e.getMessage()); + String messageError = String.format("Error consultando el operador %d : %s", operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (operatorDto == null) { @@ -179,8 +197,8 @@ public String generateReportDownloadSupplyIndividual(Long operatorId, Long deliv } List suppliesResponse = deliveryDto.getSupplies(); - List suppliesDeliveryDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveryDto = suppliesResponse.stream().map(CustomSupplyDeliveryDto::new) + .collect(Collectors.toList()); CustomSupplyDeliveryDto supplyDeliveryDto = suppliesDeliveryDto.stream() .filter(s -> s.getSupplyCode().equals(supplyId)).findAny().orElse(null); @@ -252,7 +270,8 @@ public String generateReportDownloadSupplyIndividual(Long operatorId, Long deliv } supplies.add(new MicroserviceDownloadedSupplyDto(supplyName, - DateTool.formatDate(supplyDeliveryDto.getDownloadedAt(), format), downloadedBy, providerName.toUpperCase())); + DateTool.formatDate(supplyDeliveryDto.getDownloadedAt(), format), downloadedBy, + providerName.toUpperCase())); MicroserviceReportInformationDto report = reportBusiness.generateReportDownloadSupply(namespace, dateCreation, dateDelivery, deliveryId.toString(), departmentName, managerName, municipalityCode, municipalityName, @@ -272,13 +291,18 @@ public String generateReportDownloadSupplyTotal(Long operatorId, Long deliveryId try { deliveryDto = operatorBusiness.getDeliveryId(deliveryId); } catch (Exception e) { - log.error("Error consultando entrega por id: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega %d del operador %d: %s", deliveryId, + operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } try { operatorDto = operatorBusiness.getOperatorById(operatorId); } catch (Exception e) { - log.error("Error consultando operador por id: " + e.getMessage()); + String messageError = String.format("Error consultando el operador %d : %s", operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (deliveryDto == null) { @@ -294,8 +318,8 @@ public String generateReportDownloadSupplyTotal(Long operatorId, Long deliveryId } List suppliesResponse = deliveryDto.getSupplies(); - List suppliesDeliveryDto = - suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveryDto = suppliesResponse.stream().map(CustomSupplyDeliveryDto::new) + .collect(Collectors.toList()); for (CustomSupplyDeliveryDto supplyDeliveryDto : suppliesDeliveryDto) { if (!supplyDeliveryDto.getDownloaded()) { @@ -334,8 +358,8 @@ public String generateReportDownloadSupplyTotal(Long operatorId, Long deliveryId List supplies = new ArrayList<>(); List response = deliveryDto.getSupplies(); - List suppliesDeliveriesDto = - response.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveriesDto = response.stream().map(CustomSupplyDeliveryDto::new) + .collect(Collectors.toList()); for (CustomSupplyDeliveryDto supplyDeliveryDto : suppliesDeliveriesDto) { String supplyName = ""; @@ -371,7 +395,8 @@ public String generateReportDownloadSupplyTotal(Long operatorId, Long deliveryId } supplies.add(new MicroserviceDownloadedSupplyDto(supplyName, - DateTool.formatDate(supplyDeliveryDto.getDownloadedAt(), format), downloadedBy, providerName.toUpperCase())); + DateTool.formatDate(supplyDeliveryDto.getDownloadedAt(), format), downloadedBy, + providerName.toUpperCase())); } MicroserviceReportInformationDto report = reportBusiness.generateReportDownloadSupply(namespace, dateCreation, @@ -392,24 +417,29 @@ public String generateReportDeliveryManager(Long managerId, Long deliveryId) thr try { deliveryDto = operatorBusiness.getDeliveryId(deliveryId); } catch (Exception e) { - log.error("Error consultando entrega por id: " + e.getMessage()); + String messageError = String.format("Error consultando la entrega %d del gestor %d : %s", deliveryId, + managerId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (deliveryDto == null) { throw new BusinessException("No se ha encontrado la entrega."); } + Long operatorId = deliveryDto.getOperator().getId(); try { - operatorDto = operatorBusiness.getOperatorById(deliveryDto.getOperator().getId()); + operatorDto = operatorBusiness.getOperatorById(operatorId); } catch (Exception e) { - log.error("Error consultando operador por id: " + e.getMessage()); + String messageError = String.format("Error consultando el operator %d : %s", operatorId, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } if (operatorDto == null) { throw new BusinessException("No se ha encontrado el operador."); } - if (!deliveryDto.getManagerCode().equals(managerId)) { throw new BusinessException("La entrega no pertenece al gestor."); } @@ -440,8 +470,8 @@ public String generateReportDeliveryManager(Long managerId, Long deliveryId) thr List supplies = new ArrayList<>(); List response = deliveryDto.getSupplies(); - List suppliesDeliveriesDto = - response.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList()); + List suppliesDeliveriesDto = response.stream().map(CustomSupplyDeliveryDto::new) + .collect(Collectors.toList()); for (CustomSupplyDeliveryDto supplyDeliveryDto : suppliesDeliveriesDto) { String supplyName = ""; @@ -484,8 +514,9 @@ public void deleteWorkspaceOperatorById(Long workspaceOperatorId) { operatorService.deleteWorkspaceOperatorById(workspaceOperatorId); } - public WorkspaceOperatorDto createOperator(Date startDate, Date endDate, Long numberParcelsExpected, Double workArea, String observations, - String supportFileURL, Long workspaceId, Long operatorCode, Long managerCode) { + public WorkspaceOperatorDto createOperator(Date startDate, Date endDate, Long numberParcelsExpected, + Double workArea, String observations, String supportFileURL, Long workspaceId, Long operatorCode, + Long managerCode) { WorkspaceEntity workspaceEntity = workspaceService.getWorkspaceById(workspaceId); @@ -509,7 +540,7 @@ public WorkspaceOperatorDto createOperator(Date startDate, Date endDate, Long nu } public WorkspaceOperatorDto updateWorkspaceOperator(Long workspaceManagerId, Date startDate, Date endDate, - String observations, Long parcelsExpected, Double workArea, String supportFile) { + String observations, Long parcelsExpected, Double workArea, String supportFile) { WorkspaceOperatorEntity workspaceOperatorEntity = workspaceOperatorService .getWorkspaceOperatorById(workspaceManagerId); @@ -550,7 +581,8 @@ public WorkspaceOperatorDto entityParseToDto(WorkspaceOperatorEntity workspaceOp municipalityDto.setId(municipalityEntity.getId()); municipalityDto.setName(municipalityEntity.getName()); municipalityDto.setCode(municipalityEntity.getCode()); - municipalityDto.setDepartment(new DepartmentDto(departmentEntity.getId(), departmentEntity.getName(), departmentEntity.getCode())); + municipalityDto.setDepartment( + new DepartmentDto(departmentEntity.getId(), departmentEntity.getName(), departmentEntity.getCode())); workspaceOperatorDto.setMunicipality(municipalityDto); try { @@ -558,6 +590,10 @@ public WorkspaceOperatorDto entityParseToDto(WorkspaceOperatorEntity workspaceOp .getManagerById(workspaceOperatorEntity.getManagerCode()); workspaceOperatorDto.setManager(managerDto); } catch (Exception e) { + String messageError = String.format("Error consultando el gestor %d : %s", + workspaceOperatorEntity.getManagerCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); workspaceOperatorDto.setManager(null); } @@ -566,6 +602,10 @@ public WorkspaceOperatorDto entityParseToDto(WorkspaceOperatorEntity workspaceOp .getOperatorById(workspaceOperatorEntity.getOperatorCode()); workspaceOperatorDto.setOperator(operatorDto); } catch (Exception e) { + String messageError = String.format("Error consultando el operador %d : %s", + workspaceOperatorEntity.getOperatorCode(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); workspaceOperatorDto.setOperator(null); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/clients/CustomErrorDecoder.java b/src/main/java/com/ai/st/microservice/workspaces/clients/CustomErrorDecoder.java new file mode 100644 index 0000000..c4bb763 --- /dev/null +++ b/src/main/java/com/ai/st/microservice/workspaces/clients/CustomErrorDecoder.java @@ -0,0 +1,31 @@ +package com.ai.st.microservice.workspaces.clients; + +import com.ai.st.microservice.common.exceptions.BusinessException; +import com.ai.st.microservice.workspaces.controllers.v1.IntegrationV1Controller; +import feign.Response; +import feign.codec.ErrorDecoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public final class CustomErrorDecoder implements ErrorDecoder { + + private final Logger log = LoggerFactory.getLogger(IntegrationV1Controller.class); + + @Override + public Exception decode(String methodKey, Response response) { + + switch (response.status()) { + case 400: + log.error("Error request (400): " + response.request().toString()); + log.error("Error request body (400): " + response.body().toString()); + return new BusinessException("Error 400 en la comunicación con el microservicio"); + case 500: + default: + log.error("Error request (500): " + response.request().toString()); + log.error("Error request body (500): " + response.body().toString()); + return new BusinessException("Error 500 en la comunicación con el microservicio"); + } + + } + +} diff --git a/src/main/java/com/ai/st/microservice/workspaces/clients/FTPFeignClient.java b/src/main/java/com/ai/st/microservice/workspaces/clients/FTPFeignClient.java deleted file mode 100644 index ec734a5..0000000 --- a/src/main/java/com/ai/st/microservice/workspaces/clients/FTPFeignClient.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ai.st.microservice.workspaces.clients; - -import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; - -import org.springframework.beans.factory.ObjectFactory; -import org.springframework.boot.autoconfigure.http.HttpMessageConverters; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.cloud.openfeign.support.SpringEncoder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Scope; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.ai.st.microservice.workspaces.dto.ftp.MicroserviceCreateUserFTPDto; - -import feign.Feign; -import feign.codec.Encoder; -import feign.form.spring.SpringFormEncoder; - -@FeignClient(name = "st-microservice-ftp", configuration = FTPFeignClient.Configuration.class) -public interface FTPFeignClient { - - @RequestMapping(method = RequestMethod.POST, value = "/api/managers/v1/ftp/add-user", consumes = APPLICATION_JSON_VALUE) - void createUserFTP(@RequestBody MicroserviceCreateUserFTPDto data); - - class Configuration { - - @Bean - Encoder feignFormEncoder(ObjectFactory converters) { - return new SpringFormEncoder(new SpringEncoder(converters)); - } - - @Bean - @Scope("prototype") - public Feign.Builder feignBuilder() { - return Feign.builder(); - } - - } - -} diff --git a/src/main/java/com/ai/st/microservice/workspaces/clients/GeovisorFeignClient.java b/src/main/java/com/ai/st/microservice/workspaces/clients/GeovisorFeignClient.java index 9e812a9..72bae68 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/clients/GeovisorFeignClient.java +++ b/src/main/java/com/ai/st/microservice/workspaces/clients/GeovisorFeignClient.java @@ -2,15 +2,15 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; +import feign.codec.ErrorDecoder; import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Scope; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import com.ai.st.microservice.workspaces.dto.geovisor.MicroserviceDataMapDto; import com.ai.st.microservice.workspaces.dto.geovisor.MicroserviceSetupMapDto; @@ -19,10 +19,10 @@ import feign.codec.Encoder; import feign.form.spring.SpringFormEncoder; -@FeignClient(name = "data", configuration = GeovisorFeignClient.Configuration.class, url = "pending") +@FeignClient(value = "geovisor", configuration = GeovisorFeignClient.Configuration.class, url = "${geoapi.url}") public interface GeovisorFeignClient { - @RequestMapping(method = RequestMethod.POST, value = "/users/test", consumes = APPLICATION_JSON_VALUE) + @PostMapping(value = "/st_geocreatefastcontext", consumes = APPLICATION_JSON_VALUE) MicroserviceDataMapDto setupMap(@RequestBody MicroserviceSetupMapDto data); class Configuration { @@ -32,6 +32,11 @@ Encoder feignFormEncoder(ObjectFactory converters) { return new SpringFormEncoder(new SpringEncoder(converters)); } + @Bean + public ErrorDecoder errorDecoder() { + return new CustomErrorDecoder(); + } + @Bean @Scope("prototype") public Feign.Builder feignBuilder() { @@ -40,4 +45,4 @@ public Feign.Builder feignBuilder() { } -} +} \ No newline at end of file diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/AdministrationV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/AdministrationV1Controller.java index aa4065c..12856b2 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/AdministrationV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/AdministrationV1Controller.java @@ -5,8 +5,10 @@ import com.ai.st.microservice.common.dto.general.BasicResponseDto; import com.ai.st.microservice.common.dto.managers.MicroserviceManagerDto; import com.ai.st.microservice.common.dto.providers.MicroserviceProviderDto; -import com.ai.st.microservice.common.exceptions.*; +import com.ai.st.microservice.common.exceptions.BusinessException; +import com.ai.st.microservice.common.exceptions.DisconnectedMicroserviceException; +import com.ai.st.microservice.common.exceptions.InputValidationException; import com.ai.st.microservice.workspaces.business.AdministratorMicroserviceBusiness; import com.ai.st.microservice.workspaces.business.ManagerMicroserviceBusiness; import com.ai.st.microservice.workspaces.business.ProviderBusiness; @@ -15,6 +17,8 @@ import com.ai.st.microservice.workspaces.dto.CreateUserDto; import com.ai.st.microservice.workspaces.dto.UpdateUserDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -27,10 +31,10 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Manage Users-Roles", tags = {"Administration"}) +@Api(value = "Manage Users-Roles", tags = { "Administration" }) @RestController @RequestMapping("api/workspaces/v1/administration") -public class AdministrationV1Controller { +public final class AdministrationV1Controller { private final Logger log = LoggerFactory.getLogger(AdministrationV1Controller.class); @@ -40,8 +44,8 @@ public class AdministrationV1Controller { private final AdministrationBusiness administrationBusiness; public AdministrationV1Controller(AdministratorMicroserviceBusiness administrationBusiness, - ManagerMicroserviceBusiness managerBusiness, ProviderBusiness providerBusiness, - AdministrationBusiness administrationBusiness1) { + ManagerMicroserviceBusiness managerBusiness, ProviderBusiness providerBusiness, + AdministrationBusiness administrationBusiness1) { this.administrationMicroserviceBusiness = administrationBusiness; this.managerBusiness = managerBusiness; this.providerBusiness = providerBusiness; @@ -50,45 +54,50 @@ public AdministrationV1Controller(AdministratorMicroserviceBusiness administrati @PostMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create user") - @ApiResponses(value = {@ApiResponse(code = 201, message = "Create user", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Create user", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity createUser(@RequestBody CreateUserDto requestCreateUser, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity createUser(@RequestBody CreateUserDto requestCreateUser, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("createUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isSuperAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_SUPER_ADMIN, true); responseDto = administrationMicroserviceBusiness.createUser(requestCreateUser.getFirstName(), requestCreateUser.getLastName(), requestCreateUser.getEmail(), requestCreateUser.getUsername(), - requestCreateUser.getPassword(), true, null, requestCreateUser.getRoleAdministrator(), null, null); + requestCreateUser.getPassword(), true, null, requestCreateUser.getRoleAdministrator(), null, + null); } if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); if (requestCreateUser.getRoleProvider() != null) { requestCreateUser.getRoleProvider().setFromAdministrator(true); } - - responseDto = administrationMicroserviceBusiness.createUserFromAdministrator(requestCreateUser.getFirstName(), - requestCreateUser.getLastName(), requestCreateUser.getEmail(), requestCreateUser.getUsername(), - requestCreateUser.getPassword(), requestCreateUser.getRoleProvider(), - requestCreateUser.getRoleAdministrator(), requestCreateUser.getRoleManager(), - requestCreateUser.getRoleOperator()); + responseDto = administrationMicroserviceBusiness.createUserFromAdministrator( + requestCreateUser.getFirstName(), requestCreateUser.getLastName(), requestCreateUser.getEmail(), + requestCreateUser.getUsername(), requestCreateUser.getPassword(), + requestCreateUser.getRoleProvider(), requestCreateUser.getRoleAdministrator(), + requestCreateUser.getRoleManager(), requestCreateUser.getRoleOperator()); } if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -96,20 +105,19 @@ public ResponseEntity createUser(@RequestBody CreateUserDto requestCreat if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para crear usuarios."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); requestCreateUser.getRoleManager().setManagerId(managerDto.getId()); - responseDto = administrationMicroserviceBusiness.createUserFromManager(requestCreateUser.getFirstName(), requestCreateUser.getLastName(), requestCreateUser.getEmail(), requestCreateUser.getUsername(), requestCreateUser.getPassword(), requestCreateUser.getRoleManager()); - } if (administrationBusiness.isProvider(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); requestCreateUser.getRoleProvider().setFromAdministrator(false); - - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } @@ -117,24 +125,29 @@ public ResponseEntity createUser(@RequestBody CreateUserDto requestCreat throw new InputValidationException("El usuario no tiene permisos para crear usuarios."); } - requestCreateUser.getRoleProvider().setProviderId(providerDto.getId()); - - responseDto = administrationMicroserviceBusiness.createUserFromProvider(requestCreateUser.getFirstName(), - requestCreateUser.getLastName(), requestCreateUser.getEmail(), requestCreateUser.getUsername(), - requestCreateUser.getPassword(), requestCreateUser.getRoleProvider()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); + requestCreateUser.getRoleProvider().setProviderId(providerDto.getId()); + responseDto = administrationMicroserviceBusiness.createUserFromProvider( + requestCreateUser.getFirstName(), requestCreateUser.getLastName(), requestCreateUser.getEmail(), + requestCreateUser.getUsername(), requestCreateUser.getPassword(), + requestCreateUser.getRoleProvider()); } + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, requestCreateUser.toString()); httpStatus = HttpStatus.CREATED; } catch (BusinessException e) { log.error("Error AdministrationV1Controller@createUser#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@createUser#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -142,22 +155,27 @@ public ResponseEntity createUser(@RequestBody CreateUserDto requestCreat @PostMapping(value = "/users/reset-password", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Change password user") - @ApiResponses(value = {@ApiResponse(code = 201, message = "Create user", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Create user", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity resetUserPassword(@RequestBody ChangePasswordDto requestChangePassword, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity resetUserPassword(@RequestBody ChangePasswordDto requestChangePassword, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("changeUserPassword"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); responseDto = administrationMicroserviceBusiness.changeUserPassword(userDtoSession.getId(), requestChangePassword.getPassword()); @@ -166,15 +184,18 @@ public ResponseEntity resetUserPassword(@RequestBody ChangePasswordDto r } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@resetUserPassword#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@resetUserPassword#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@resetUserPassword#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -182,37 +203,44 @@ public ResponseEntity resetUserPassword(@RequestBody ChangePasswordDto r @PutMapping(value = "/users/{userId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Update user") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Update user", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Update user", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity updateUser(@PathVariable Long userId, - @RequestBody UpdateUserDto requestUpdateUser, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity updateUser(@PathVariable Long userId, @RequestBody UpdateUserDto requestUpdateUser, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("updateUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isSuperAdministrator(userDtoSession)) { - responseDto = administrationMicroserviceBusiness.updateUserFromSuperAdmin(userId, requestUpdateUser.getFirstName(), - requestUpdateUser.getLastName(), requestUpdateUser.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.IS_SUPER_ADMIN, true); + responseDto = administrationMicroserviceBusiness.updateUserFromSuperAdmin(userId, + requestUpdateUser.getFirstName(), requestUpdateUser.getLastName(), + requestUpdateUser.getEmail()); } if (administrationBusiness.isAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = administrationMicroserviceBusiness.updateUserFromAdministrator(userId, - requestUpdateUser.getFirstName(), requestUpdateUser.getLastName(), requestUpdateUser.getEmail()); + requestUpdateUser.getFirstName(), requestUpdateUser.getLastName(), + requestUpdateUser.getEmail()); } if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -220,26 +248,29 @@ public ResponseEntity updateUser(@PathVariable Long userId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para editar usuarios."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); - responseDto = administrationMicroserviceBusiness.updateUserFromManager(userId, requestUpdateUser.getFirstName(), - requestUpdateUser.getLastName(), requestUpdateUser.getEmail(), managerDto.getId()); - + responseDto = administrationMicroserviceBusiness.updateUserFromManager(userId, + requestUpdateUser.getFirstName(), requestUpdateUser.getLastName(), requestUpdateUser.getEmail(), + managerDto.getId()); } if (administrationBusiness.isProvider(userDtoSession)) { - - // get providers - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para editar usuarios."); } - - responseDto = administrationMicroserviceBusiness.updateUserFromProvider(userId, requestUpdateUser.getFirstName(), - requestUpdateUser.getLastName(), requestUpdateUser.getEmail(), providerDto.getId()); - + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); + responseDto = administrationMicroserviceBusiness.updateUserFromProvider(userId, + requestUpdateUser.getFirstName(), requestUpdateUser.getLastName(), requestUpdateUser.getEmail(), + providerDto.getId()); } httpStatus = HttpStatus.OK; @@ -247,19 +278,23 @@ public ResponseEntity updateUser(@PathVariable Long userId, } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@updateUser#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error AdministrationV1Controller@updateUser#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.UNAUTHORIZED; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@updateUser#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@updateUser#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -267,33 +302,40 @@ public ResponseEntity updateUser(@PathVariable Long userId, @PutMapping(value = "/users/{userId}/disable", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Disable user") - @ApiResponses(value = {@ApiResponse(code = 200, message = "User disabled", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "User disabled", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity disableUser(@PathVariable Long userId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity disableUser(@PathVariable Long userId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("disableUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isSuperAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_SUPER_ADMIN, true); responseDto = administrationMicroserviceBusiness.changeStatusUserFromSuperAdmin(userId, false); } if (administrationBusiness.isAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = administrationMicroserviceBusiness.changeStatusUserFromAdministrator(userId, false); } if (administrationBusiness.isManager(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -301,23 +343,28 @@ public ResponseEntity disableUser(@PathVariable Long userId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para deshabilitar el soporte."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); - responseDto = administrationMicroserviceBusiness.changeStatusUserFromManager(userId, false, managerDto.getId()); + responseDto = administrationMicroserviceBusiness.changeStatusUserFromManager(userId, false, + managerDto.getId()); } if (administrationBusiness.isProvider(userDtoSession)) { - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para deshabilitar usuarios."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); - responseDto = administrationMicroserviceBusiness.changeStatusUserFromProvider(userId, false, providerDto.getId()); - + responseDto = administrationMicroserviceBusiness.changeStatusUserFromProvider(userId, false, + providerDto.getId()); } httpStatus = HttpStatus.OK; @@ -325,19 +372,23 @@ public ResponseEntity disableUser(@PathVariable Long userId, } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@disableUser#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error AdministrationV1Controller@disableUser#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.UNAUTHORIZED; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@disableUser#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@disableUser#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -345,34 +396,40 @@ public ResponseEntity disableUser(@PathVariable Long userId, @PutMapping(value = "/users/{userId}/enable", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Enable user") - @ApiResponses(value = {@ApiResponse(code = 200, message = "User enabled", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "User enabled", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity enableUser(@PathVariable Long userId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity enableUser(@PathVariable Long userId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("enableUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isSuperAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_SUPER_ADMIN, true); responseDto = administrationMicroserviceBusiness.changeStatusUserFromSuperAdmin(userId, true); } if (administrationBusiness.isAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = administrationMicroserviceBusiness.changeStatusUserFromAdministrator(userId, true); } if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -380,22 +437,28 @@ public ResponseEntity enableUser(@PathVariable Long userId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para habilitar usuarios."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); - responseDto = administrationMicroserviceBusiness.changeStatusUserFromManager(userId, true, managerDto.getId()); + responseDto = administrationMicroserviceBusiness.changeStatusUserFromManager(userId, true, + managerDto.getId()); } if (administrationBusiness.isProvider(userDtoSession)) { - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para habilitar usuarios."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); - responseDto = administrationMicroserviceBusiness.changeStatusUserFromProvider(userId, true, providerDto.getId()); + responseDto = administrationMicroserviceBusiness.changeStatusUserFromProvider(userId, true, + providerDto.getId()); } @@ -404,19 +467,23 @@ public ResponseEntity enableUser(@PathVariable Long userId, } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@enableUser#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error AdministrationV1Controller@enableUser#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.UNAUTHORIZED; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@enableUser#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@enableUser#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -424,8 +491,8 @@ public ResponseEntity enableUser(@PathVariable Long userId, @GetMapping(value = "/users", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get users") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Get users", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Get users", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getUsers(@RequestHeader("authorization") String headerAuthorization) { @@ -434,23 +501,29 @@ public ResponseEntity getUsers(@RequestHeader("authorization") String he try { - // user session + SCMTracing.setTransactionName("getUsers"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isSuperAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_SUPER_ADMIN, true); responseDto = administrationMicroserviceBusiness.getUsersFromSuperAdmin(); } if (administrationBusiness.isAdministrator(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = administrationMicroserviceBusiness.getUsersFromAdministrator(); } if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -458,22 +531,23 @@ public ResponseEntity getUsers(@RequestHeader("authorization") String he if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para consultar usuarios."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = administrationMicroserviceBusiness.getUsersFromManager(managerDto.getId()); - } if (administrationBusiness.isProvider(userDtoSession)) { - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para consultar usuarios."); } - + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = administrationMicroserviceBusiness.getUsersFromProvider(providerDto.getId()); } @@ -483,19 +557,23 @@ public ResponseEntity getUsers(@RequestHeader("authorization") String he } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@getUsers#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error AdministrationV1Controller@getUsers#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.UNAUTHORIZED; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@getUsers#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@getUsers#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -503,53 +581,60 @@ public ResponseEntity getUsers(@RequestHeader("authorization") String he @PostMapping(value = "/users/{userId}/profiles", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Add profile to user") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Profile Added", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Profile Added", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity addProfileToUser(@RequestHeader("authorization") String headerAuthorization, - @RequestBody AddProfileToUserDto addProfileUser, @PathVariable Long userId) { + public ResponseEntity addProfileToUser(@RequestHeader("authorization") String headerAuthorization, + @RequestBody AddProfileToUserDto addProfileUser, @PathVariable Long userId) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("addProfileToUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, addProfileUser.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { - throw new InputValidationException("El usuario no tiene permisos para agregar perfiles a los usuarios."); + throw new InputValidationException( + "El usuario no tiene permisos para agregar perfiles a los usuarios."); } - - responseDto = administrationMicroserviceBusiness.addProfileToUserFromManager(userId, addProfileUser.getProfileId(), - managerDto.getId()); - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); + responseDto = administrationMicroserviceBusiness.addProfileToUserFromManager(userId, + addProfileUser.getProfileId(), managerDto.getId()); } if (administrationBusiness.isProvider(userDtoSession)) { - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { - throw new InputValidationException("El usuario no tiene permisos para agregar perfiles a los usuarios."); + throw new InputValidationException( + "El usuario no tiene permisos para agregar perfiles a los usuarios."); } - - responseDto = administrationMicroserviceBusiness.addProfileToUserFromProvider(userId, addProfileUser.getProfileId(), - providerDto.getId()); - + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); + responseDto = administrationMicroserviceBusiness.addProfileToUserFromProvider(userId, + addProfileUser.getProfileId(), providerDto.getId()); } httpStatus = HttpStatus.OK; @@ -557,19 +642,23 @@ public ResponseEntity addProfileToUser(@RequestHeader("authorization") S } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@addProfileToUser#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error AdministrationV1Controller@addProfileToUser#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.UNAUTHORIZED; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@addProfileToUser#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@addProfileToUser#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -577,53 +666,60 @@ public ResponseEntity addProfileToUser(@RequestHeader("authorization") S @DeleteMapping(value = "/users/{userId}/profiles", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Remove profile to user") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Profile Added", response = MicroserviceUserDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Profile Added", response = MicroserviceUserDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity removeProfileToUser(@RequestHeader("authorization") String headerAuthorization, - @RequestBody AddProfileToUserDto addProfileUser, @PathVariable Long userId) { + public ResponseEntity removeProfileToUser(@RequestHeader("authorization") String headerAuthorization, + @RequestBody AddProfileToUserDto removeProfileUser, @PathVariable Long userId) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("removeProfileToUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, removeProfileUser.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { - throw new InputValidationException("El usuario no tiene permisos para remover perfiles a los usuarios."); + throw new InputValidationException( + "El usuario no tiene permisos para remover perfiles a los usuarios."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = administrationMicroserviceBusiness.removeProfileToUserFromManager(userId, - addProfileUser.getProfileId(), managerDto.getId()); - + removeProfileUser.getProfileId(), managerDto.getId()); } if (administrationBusiness.isProvider(userDtoSession)) { - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.IS_PROVIDER, true); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { - throw new InputValidationException("El usuario no tiene permisos para remover perfiles a los usuarios."); + throw new InputValidationException( + "El usuario no tiene permisos para remover perfiles a los usuarios."); } - + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = administrationMicroserviceBusiness.removeProfileToUserFromProvider(userId, - addProfileUser.getProfileId(), providerDto.getId()); - + removeProfileUser.getProfileId(), providerDto.getId()); } httpStatus = HttpStatus.OK; @@ -631,19 +727,23 @@ public ResponseEntity removeProfileToUser(@RequestHeader("authorization" } catch (DisconnectedMicroserviceException e) { log.error("Error AdministrationV1Controller@removeProfileToUser#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error AdministrationV1Controller@removeProfileToUser#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.UNAUTHORIZED; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error AdministrationV1Controller@removeProfileToUser#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error AdministrationV1Controller@removeProfileToUser#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/CadastralAuthorityV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/CadastralAuthorityV1Controller.java index 66ad278..9484f51 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/CadastralAuthorityV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/CadastralAuthorityV1Controller.java @@ -16,6 +16,8 @@ import javax.servlet.ServletContext; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import com.google.common.io.Files; import org.slf4j.Logger; @@ -33,7 +35,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Manage Cadastral Authority Processes ", tags = {"Cadastral Authority"}) +@Api(value = "Manage Cadastral Authority Processes ", tags = { "Cadastral Authority" }) @RestController @RequestMapping("api/workspaces/v1/cadastral-authority") public class CadastralAuthorityV1Controller { @@ -44,8 +46,8 @@ public class CadastralAuthorityV1Controller { private final ServletContext servletContext; private final AdministrationBusiness administrationBusiness; - public CadastralAuthorityV1Controller(CadastralAuthorityBusiness cadastralAuthorityBusiness, ServletContext servletContext, - AdministrationBusiness administrationBusiness) { + public CadastralAuthorityV1Controller(CadastralAuthorityBusiness cadastralAuthorityBusiness, + ServletContext servletContext, AdministrationBusiness administrationBusiness) { this.cadastralAuthorityBusiness = cadastralAuthorityBusiness; this.servletContext = servletContext; this.administrationBusiness = administrationBusiness; @@ -53,27 +55,31 @@ public CadastralAuthorityV1Controller(CadastralAuthorityBusiness cadastralAuthor @PostMapping(value = "/supplies/{municipalityId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create supply (cadastral authority)") - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Supply created", response = CustomSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Supply created", response = CustomSupplyDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity createSupply(@PathVariable Long municipalityId, - @RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "file", required = false) MultipartFile file, - @ModelAttribute CreateSupplyCadastralAuthorityDto supplyCadastralAuthorityDto) { + @RequestHeader("authorization") String headerAuthorization, + @RequestParam(name = "file", required = false) MultipartFile file, + @ModelAttribute CreateSupplyCadastralAuthorityDto supplyCadastralAuthorityDto) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("createSupplyAsCadastralAuthority"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, supplyCadastralAuthorityDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // validation manager Long managerCode = supplyCadastralAuthorityDto.getManagerCode(); if (managerCode == null || managerCode <= 0) { throw new InputValidationException("El gestor es requerido."); @@ -97,26 +103,31 @@ public ResponseEntity createSupply(@PathVariable Long municipalityId, throw new InputValidationException("Las observaciones son requeridas."); } - responseDto = cadastralAuthorityBusiness.createSupplyCadastralAuthority(municipalityId, managerCode, attachmentTypeId, - name, observations, supplyCadastralAuthorityDto.getFtp(), file, userDtoSession.getId()); + responseDto = cadastralAuthorityBusiness.createSupplyCadastralAuthority(municipalityId, managerCode, + attachmentTypeId, name, observations, supplyCadastralAuthorityDto.getFtp(), file, + userDtoSession.getId()); httpStatus = HttpStatus.CREATED; } catch (DisconnectedMicroserviceException e) { log.error("Error CadastralAuthorityV1Controller@createSupply#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error CadastralAuthorityV1Controller@createSupply#Validation ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error CadastralAuthorityV1Controller@createSupply#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error CadastralAuthorityV1Controller@createSupply#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -124,12 +135,11 @@ public ResponseEntity createSupply(@PathVariable Long municipalityId, @GetMapping(value = "/report/{municipalityId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create report (cadastral authority)") - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Supply created", response = CustomSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Supply created", response = CustomSupplyDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity downloadReport(@PathVariable Long municipalityId, - @RequestParam(name = "manager") Long managerCode) { + @RequestParam(name = "manager") Long managerCode) { MediaType mediaType; File file; @@ -137,6 +147,8 @@ public ResponseEntity downloadReport(@PathVariable Long municipalityId, try { + SCMTracing.setTransactionName("downloadReportCadastralAuthority"); + String pathFile = cadastralAuthorityBusiness.generateReport(municipalityId, managerCode); Path path = Paths.get(pathFile); @@ -154,17 +166,18 @@ public ResponseEntity downloadReport(@PathVariable Long municipalityId, resource = new InputStreamResource(new FileInputStream(file)); } catch (BusinessException e) { + SCMTracing.sendError(e.getMessage()); log.error("Error CadastralAuthorityV1Controller@downloadReport#Business ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 2), HttpStatus.UNPROCESSABLE_ENTITY); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY); } catch (Exception e) { + SCMTracing.sendError(e.getMessage()); log.error("Error CadastralAuthorityV1Controller@downloadReport#General ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 3), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) .contentType(mediaType).contentLength(file.length()) .header("extension", Files.getFileExtension(file.getName())).body(resource); - } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/DepartmentV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/DepartmentV1Controller.java index 4b8dede..ec1ac61 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/DepartmentV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/DepartmentV1Controller.java @@ -9,6 +9,8 @@ import com.ai.st.microservice.workspaces.dto.DepartmentDto; import com.ai.st.microservice.workspaces.dto.MunicipalityDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -24,7 +26,7 @@ import java.util.ArrayList; import java.util.List; -@Api(value = "Manage Departments", tags = {"Departments"}) +@Api(value = "Manage Departments", tags = { "Departments" }) @RestController @RequestMapping("api/workspaces/v1/departments") public class DepartmentV1Controller { @@ -37,7 +39,7 @@ public class DepartmentV1Controller { private final AdministrationBusiness administrationBusiness; public DepartmentV1Controller(DepartmentBusiness departmentBusiness, MunicipalityBusiness municipalityBusiness, - ManagerMicroserviceBusiness managerBusiness, AdministrationBusiness administrationBusiness) { + ManagerMicroserviceBusiness managerBusiness, AdministrationBusiness administrationBusiness) { this.departmentBusiness = departmentBusiness; this.municipalityBusiness = municipalityBusiness; this.managerBusiness = managerBusiness; @@ -48,7 +50,8 @@ public DepartmentV1Controller(DepartmentBusiness departmentBusiness, Municipalit @ApiOperation(value = "Get departments") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get departments", response = DepartmentDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 422, message = "Error getting departments", response = String.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity> getDepartments( @RequestHeader("authorization") String headerAuthorization) { @@ -58,36 +61,47 @@ public ResponseEntity> getDepartments( try { + SCMTracing.setTransactionName("getDepartments"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - if (administrationBusiness.isAdministrator(userDtoSession) || administrationBusiness.isProvider(userDtoSession)) { + if (administrationBusiness.isAdministrator(userDtoSession) + || administrationBusiness.isProvider(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); listDepartments = departmentBusiness.getDepartments(); } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } - + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); listDepartments = departmentBusiness.getDepartmentsByManagerCode(managerDto.getId()); } - httpStatus = HttpStatus.OK; + } catch (DisconnectedMicroserviceException e) { log.error("Error DepartmentV1Controller@getDepartments#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { listDepartments = null; log.error("Error DepartmentV1Controller@getDepartments#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { listDepartments = null; log.error("Error DepartmentV1Controller@getDepartments#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(listDepartments, httpStatus); @@ -97,31 +111,40 @@ public ResponseEntity> getDepartments( @ApiOperation(value = "Get municipalities by department") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get municipalities by department", response = MunicipalityDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 422, message = "Error getting municipalities", response = String.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity> getMunicipalitiesById(@PathVariable Long departmentId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; List listMunicipalities = new ArrayList<>(); try { - // user session + SCMTracing.setTransactionName("getMunicipalitiesByDepartment"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - if (administrationBusiness.isAdministrator(userDtoSession) || administrationBusiness.isProvider(userDtoSession)) { + if (administrationBusiness.isAdministrator(userDtoSession) + || administrationBusiness.isProvider(userDtoSession)) { + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); listMunicipalities = municipalityBusiness.getMunicipalitiesByDepartmentId(departmentId); } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); listMunicipalities = municipalityBusiness.getMunicipalitiesByDepartmentIdAndManager(departmentId, managerDto.getId()); @@ -131,14 +154,17 @@ public ResponseEntity> getMunicipalitiesById(@PathVariable } catch (DisconnectedMicroserviceException e) { log.error("Error DepartmentV1Controller@getMunicipalitiesById#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { listMunicipalities = null; log.error("Error DepartmentV1Controller@getMunicipalitiesById#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { listMunicipalities = null; log.error("Error DepartmentV1Controller@getMunicipalitiesById#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(listMunicipalities, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/IntegrationV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/IntegrationV1Controller.java index 8e05fbe..f88cef5 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/IntegrationV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/IntegrationV1Controller.java @@ -9,8 +9,9 @@ import com.ai.st.microservice.workspaces.business.IntegrationBusiness; import com.ai.st.microservice.workspaces.business.ManagerMicroserviceBusiness; import com.ai.st.microservice.workspaces.dto.IntegrationDto; -import com.ai.st.microservice.workspaces.dto.PossibleIntegrationDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -23,7 +24,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Manage Integrations", tags = {"Integrations"}) +@Api(value = "Manage Integrations", tags = { "Integrations" }) @RestController @RequestMapping("api/workspaces/v1/integrations") public class IntegrationV1Controller { @@ -35,7 +36,7 @@ public class IntegrationV1Controller { private final AdministrationBusiness administrationBusiness; public IntegrationV1Controller(ManagerMicroserviceBusiness managerBusiness, IntegrationBusiness integrationBusiness, - AdministrationBusiness administrationBusiness) { + AdministrationBusiness administrationBusiness) { this.managerBusiness = managerBusiness; this.integrationBusiness = integrationBusiness; this.administrationBusiness = administrationBusiness; @@ -45,22 +46,26 @@ public IntegrationV1Controller(ManagerMicroserviceBusiness managerBusiness, Inte @ApiOperation(value = "Get integrations") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get integrations", response = IntegrationDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getIntegrationsRunning(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getIntegrationsRunning(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getIntegrationsRunning"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -70,46 +75,56 @@ public ResponseEntity getIntegrationsRunning(@RequestHeader("authorizati throw new InputValidationException("El usuario no tiene permisos para consultar las integraciones."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); + responseDto = integrationBusiness.getIntegrationsRunning(managerDto); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { log.error("Error IntegrationV1Controller@getIntegrationsRunning#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error IntegrationV1Controller@getIntegrationsRunning#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error IntegrationV1Controller@getIntegrationsRunning#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); } @PutMapping(value = "{integrationId}/configure-view", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Get integrations") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Get integrations", response = PossibleIntegrationDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiOperation(value = "Configure map") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Map configured", response = String.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity configureViewIntegration(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long integrationId) { + public ResponseEntity configureViewIntegration(@RequestHeader("authorization") String headerAuthorization, + @PathVariable Long integrationId) { + HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("configureViewIntegration"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -119,22 +134,28 @@ public ResponseEntity configureViewIntegration(@RequestHeader("authoriza throw new InputValidationException("El usuario no tiene permisos para configurar las integraciones."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); + integrationBusiness.configureViewIntegration(integrationId, managerDto.getId()); - responseDto = new BasicResponseDto("Se ha configurado ", 7); + responseDto = new BasicResponseDto("Se ha configurado la vista del mapa", 7); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { log.error("Error IntegrationV1Controller@configureViewIntegration#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 1); + httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error IntegrationV1Controller@configureViewIntegration#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error IntegrationV1Controller@configureViewIntegration#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ManagerV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ManagerV1Controller.java index db45e22..b2d9022 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ManagerV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ManagerV1Controller.java @@ -11,6 +11,8 @@ import com.ai.st.microservice.workspaces.business.OperatorMicroserviceBusiness; import com.ai.st.microservice.workspaces.dto.operators.CustomDeliveryDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -23,7 +25,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Managers ", tags = {"Managers"}) +@Api(value = "Managers ", tags = { "Managers" }) @RestController @RequestMapping("api/workspaces/v1/managers") public class ManagerV1Controller { @@ -34,8 +36,8 @@ public class ManagerV1Controller { private final OperatorMicroserviceBusiness operatorBusiness; private final AdministrationBusiness administrationBusiness; - public ManagerV1Controller(ManagerMicroserviceBusiness managerBusiness, OperatorMicroserviceBusiness operatorBusiness, - AdministrationBusiness administrationBusiness) { + public ManagerV1Controller(ManagerMicroserviceBusiness managerBusiness, + OperatorMicroserviceBusiness operatorBusiness, AdministrationBusiness administrationBusiness) { this.managerBusiness = managerBusiness; this.operatorBusiness = operatorBusiness; this.administrationBusiness = administrationBusiness; @@ -45,7 +47,7 @@ public ManagerV1Controller(ManagerMicroserviceBusiness managerBusiness, Operator @ApiOperation(value = "Get deliveries by manager") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get deliveries by manager", response = CustomDeliveryDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getDeliveriesByManager(@RequestHeader("authorization") String headerAuthorization) { @@ -54,13 +56,17 @@ public ResponseEntity getDeliveriesByManager(@RequestHeader("authorization") try { - // user session + SCMTracing.setTransactionName("getDeliveriesForManagerFromOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -69,22 +75,27 @@ public ResponseEntity getDeliveriesByManager(@RequestHeader("authorization") if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para consultar entregas."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = operatorBusiness.getDeliveriesByManager(managerDto.getId()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { log.error("Error ManagerV1Controller@getDeliveriesByManager#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ManagerV1Controller@getDeliveriesByManager#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ManagerV1Controller@getDeliveriesByManager#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -94,23 +105,27 @@ public ResponseEntity getDeliveriesByManager(@RequestHeader("authorization") @ApiOperation(value = "Get delivery by id") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get deliveries by manager", response = CustomDeliveryDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getDeliveriesById(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long deliveryId) { + public ResponseEntity getDeliveryById(@RequestHeader("authorization") String headerAuthorization, + @PathVariable Long deliveryId) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getDeliveryByIdForManagerFromOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -119,22 +134,27 @@ public ResponseEntity getDeliveriesById(@RequestHeader("authorization") Strin if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para consultar entregas."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = operatorBusiness.getDeliveryIdAndManager(deliveryId, managerDto.getId()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error ManagerV1Controller@getDeliveriesById#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + log.error("Error ManagerV1Controller@getDeliveryById#Microservice ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ManagerV1Controller@getDeliveriesById#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + log.error("Error ManagerV1Controller@getDeliveryById#Business ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ManagerV1Controller@getDeliveriesById#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + log.error("Error ManagerV1Controller@getDeliveryById#General ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -144,7 +164,7 @@ public ResponseEntity getDeliveriesById(@RequestHeader("authorization") Strin @ApiOperation(value = "Get operators by manager session") @ApiResponses(value = { @ApiResponse(code = 200, message = "Operators got", response = MicroserviceOperatorDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getOperatorsByManager(@RequestHeader("authorization") String headerAuthorization) { @@ -153,17 +173,23 @@ public ResponseEntity getOperatorsByManager(@RequestHeader("authorization") S try { - // user session + SCMTracing.setTransactionName("getOperatorsByManager"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = managerBusiness.getOperatorsByManager(managerDto.getId()); httpStatus = HttpStatus.OK; @@ -171,7 +197,8 @@ public ResponseEntity getOperatorsByManager(@RequestHeader("authorization") S } catch (Exception e) { log.error("Error ManagerV1Controller@getOperatorsByManager#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/MunicipalityV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/MunicipalityV1Controller.java index 4244c8c..4a31ef4 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/MunicipalityV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/MunicipalityV1Controller.java @@ -6,6 +6,7 @@ import com.ai.st.microservice.workspaces.business.MunicipalityBusiness; import com.ai.st.microservice.workspaces.dto.MunicipalityDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -18,7 +19,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Manage Municipalities", tags = {"Municipalities"}) +@Api(value = "Manage Municipalities", tags = { "Municipalities" }) @RestController @RequestMapping("api/workspaces/v1/municipalities") public class MunicipalityV1Controller { @@ -35,7 +36,7 @@ public MunicipalityV1Controller(MunicipalityBusiness municipalityBusiness) { @ApiOperation(value = "Get municipalities by manager") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get municipalities by manager", response = MunicipalityDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getMunicipalitiesByManager(@PathVariable Long managerId) { @@ -44,17 +45,21 @@ public ResponseEntity getMunicipalitiesByManager(@PathVariable Long managerId try { + SCMTracing.setTransactionName("getMunicipalitiesByManager"); + responseDto = municipalityBusiness.getMunicipalitiesByManager(managerId); httpStatus = HttpStatus.OK; } catch (BusinessException e) { - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); log.error("Error MunicipalityV1Controller@getMunicipalitiesByManager#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); log.error("Error MunicipalityV1Controller@getMunicipalitiesByManager#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -64,7 +69,7 @@ public ResponseEntity getMunicipalitiesByManager(@PathVariable Long managerId @ApiOperation(value = "Get municipalities by department") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get municipalities not workspaces", response = MunicipalityDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getMunicipalitiesNotWorkspaceByDepartment(@PathVariable Long departmentId) { @@ -73,19 +78,23 @@ public ResponseEntity getMunicipalitiesNotWorkspaceByDepartment(@PathVariable try { + SCMTracing.setTransactionName("getMunicipalitiesNotWorkspaceByDepartment"); + responseDto = municipalityBusiness.getMunicipalitiesNotWorkspaceByDepartment(departmentId); httpStatus = HttpStatus.OK; } catch (BusinessException e) { - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); log.error("Error MunicipalityV1Controller@getMunicipalitiesNotWorkspaceByDepartment#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); log.error("Error MunicipalityV1Controller@getMunicipalitiesNotWorkspaceByDepartment#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -93,9 +102,8 @@ public ResponseEntity getMunicipalitiesNotWorkspaceByDepartment(@PathVariable @GetMapping(value = "/code/{municipalityCode}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get municipality by code") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Municipality got", response = MunicipalityDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Municipality gotten", response = MunicipalityDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getMunicipalityByCode(@PathVariable String municipalityCode) { @@ -104,13 +112,17 @@ public ResponseEntity getMunicipalityByCode(@PathVariable String municipality try { + SCMTracing.setTransactionName("getMunicipalityByCode"); + responseDto = municipalityBusiness.getMunicipalityByCode(municipalityCode); httpStatus = HttpStatus.OK; } catch (Exception e) { - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); log.error("Error MunicipalityV1Controller@getMunicipalityByCode#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); + } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/OperatorV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/OperatorV1Controller.java index 2f2b8a4..eaf2e1a 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/OperatorV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/OperatorV1Controller.java @@ -10,6 +10,8 @@ import com.ai.st.microservice.workspaces.business.WorkspaceOperatorBusiness; import com.ai.st.microservice.workspaces.dto.operators.CustomDeliveryDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.InputStreamResource; @@ -33,7 +35,7 @@ import java.nio.file.Path; import java.nio.file.Paths; -@Api(value = "Manage Operators", tags = {"Operators"}) +@Api(value = "Manage Operators", tags = { "Operators" }) @RestController @RequestMapping("api/workspaces/v1/operators") public class OperatorV1Controller { @@ -46,7 +48,7 @@ public class OperatorV1Controller { private final AdministrationBusiness administrationBusiness; public OperatorV1Controller(WorkspaceOperatorBusiness workspaceOperatorBusiness, ServletContext servletContext, - OperatorMicroserviceBusiness operatorBusiness, AdministrationBusiness administrationBusiness) { + OperatorMicroserviceBusiness operatorBusiness, AdministrationBusiness administrationBusiness) { this.workspaceOperatorBusiness = workspaceOperatorBusiness; this.servletContext = servletContext; this.operatorBusiness = operatorBusiness; @@ -55,29 +57,34 @@ public OperatorV1Controller(WorkspaceOperatorBusiness workspaceOperatorBusiness, @PutMapping(value = "/deliveries/{deliveryId}/disable", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Disable delivery") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Delivery disabled", response = CustomDeliveryDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Delivery disabled", response = CustomDeliveryDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity disableDelivery(@PathVariable Long deliveryId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("disableDeliveryFromOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get operator MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); if (operatorDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el operador."); } + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); responseDto = workspaceOperatorBusiness.disableDelivery(operatorDto.getId(), deliveryId); httpStatus = HttpStatus.OK; @@ -85,15 +92,18 @@ public ResponseEntity disableDelivery(@PathVariable Long deliveryId, } catch (DisconnectedMicroserviceException e) { log.error("Error OperatorV1Controller@disableDelivery#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error OperatorV1Controller@disableDelivery#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error OperatorV1Controller@disableDelivery#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -101,11 +111,11 @@ public ResponseEntity disableDelivery(@PathVariable Long deliveryId, @GetMapping(value = "/deliveries/{deliveryId}/reports-individual/{supplyId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Download report individual") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Download report individual"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Download report individual"), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity reportDownloadSupplyIndividual(@PathVariable Long deliveryId, @PathVariable Long supplyId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { MediaType mediaType; File file; @@ -113,17 +123,23 @@ public ResponseEntity reportDownloadSupplyIndividual(@PathVariable Long deliv try { - // user session + SCMTracing.setTransactionName("downloadReportIndividualForOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get operator MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); if (operatorDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el operador."); } + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); String pathFile = workspaceOperatorBusiness.generateReportDownloadSupplyIndividual(operatorDto.getId(), deliveryId, supplyId); @@ -144,13 +160,16 @@ public ResponseEntity reportDownloadSupplyIndividual(@PathVariable Long deliv } catch (DisconnectedMicroserviceException e) { log.error("Error OperatorV1Controller@reportDownloadSupplyIndividual#Microservice ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 4), HttpStatus.INTERNAL_SERVER_ERROR); + SCMTracing.sendError(e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } catch (BusinessException e) { log.error("Error OperatorV1Controller@reportDownloadSupplyIndividual#Business ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 2), HttpStatus.UNPROCESSABLE_ENTITY); + SCMTracing.sendError(e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY); } catch (Exception e) { log.error("Error OperatorV1Controller@reportDownloadSupplyIndividual#General ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 3), HttpStatus.INTERNAL_SERVER_ERROR); + SCMTracing.sendError(e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) @@ -160,11 +179,11 @@ public ResponseEntity reportDownloadSupplyIndividual(@PathVariable Long deliv @GetMapping(value = "/deliveries/{deliveryId}/reports-total", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Download report total") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Download report total"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Download report total"), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity reportDownloadSupplyTotal(@PathVariable Long deliveryId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { MediaType mediaType; File file; @@ -172,17 +191,23 @@ public ResponseEntity reportDownloadSupplyTotal(@PathVariable Long deliveryId try { - // user session + SCMTracing.setTransactionName("downloadReportCompleteForOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get operator MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); if (operatorDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el operador."); } + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); String pathFile = workspaceOperatorBusiness.generateReportDownloadSupplyTotal(operatorDto.getId(), deliveryId); @@ -203,13 +228,16 @@ public ResponseEntity reportDownloadSupplyTotal(@PathVariable Long deliveryId } catch (DisconnectedMicroserviceException e) { log.error("Error OperatorV1Controller@reportDownloadSupplyTotal#Microservice ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 4), HttpStatus.INTERNAL_SERVER_ERROR); + SCMTracing.sendError(e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } catch (BusinessException e) { log.error("Error OperatorV1Controller@reportDownloadSupplyTotal#Business ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 2), HttpStatus.UNPROCESSABLE_ENTITY); + SCMTracing.sendError(e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY); } catch (Exception e) { log.error("Error OperatorV1Controller@reportDownloadSupplyTotal#General ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 3), HttpStatus.INTERNAL_SERVER_ERROR); + SCMTracing.sendError(e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/PetitionV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/PetitionV1Controller.java index ed17e22..829155d 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/PetitionV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/PetitionV1Controller.java @@ -13,6 +13,8 @@ import com.ai.st.microservice.workspaces.dto.UpdatePetitionDto; import com.ai.st.microservice.workspaces.dto.providers.CustomPetitionDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -25,7 +27,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Manage Petitions", tags = {"Petitions"}) +@Api(value = "Manage Petitions", tags = { "Petitions" }) @RestController @RequestMapping("api/workspaces/v1/petitions") public class PetitionV1Controller { @@ -37,7 +39,7 @@ public class PetitionV1Controller { private final AdministrationBusiness administrationBusiness; public PetitionV1Controller(ManagerMicroserviceBusiness managerBusiness, ProviderBusiness providerBusiness, - AdministrationBusiness administrationBusiness) { + AdministrationBusiness administrationBusiness) { this.managerBusiness = managerBusiness; this.providerBusiness = providerBusiness; this.administrationBusiness = administrationBusiness; @@ -45,25 +47,29 @@ public PetitionV1Controller(ManagerMicroserviceBusiness managerBusiness, Provide @PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create petition") - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Petition created", response = CustomPetitionDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Petition created", response = CustomPetitionDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity createPetition(@RequestBody CreatePetitionDto requestCreatePetition, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity createPetition(@RequestBody CreatePetitionDto requestCreatePetition, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("createPetition"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, requestCreatePetition.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -72,6 +78,8 @@ public ResponseEntity createPetition(@RequestBody CreatePetitionDto requ if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para crear peticiones."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); // validate description if (requestCreatePetition.getDescription() == null || requestCreatePetition.getDescription().isEmpty()) { @@ -90,19 +98,23 @@ public ResponseEntity createPetition(@RequestBody CreatePetitionDto requ } catch (DisconnectedMicroserviceException e) { log.error("Error PetitionV1Controller@createPetition#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error PetitionV1Controller@createPetition#Validator ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error PetitionV1Controller@createPetition#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error PetitionV1Controller@createPetition#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -112,23 +124,27 @@ public ResponseEntity createPetition(@RequestBody CreatePetitionDto requ @ApiOperation(value = "Get petitions for manager") @ApiResponses(value = { @ApiResponse(code = 200, message = "Petitions got", response = CustomPetitionDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getPetitionsForManager(@RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "provider", required = false) Long providerId) { + public ResponseEntity getPetitionsFromManager(@RequestHeader("authorization") String headerAuthorization, + @RequestParam(name = "provider", required = false) Long providerId) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getPetitionsFromManager"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -137,22 +153,27 @@ public ResponseEntity getPetitionsForManager(@RequestHeader("authorizati if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para crear peticiones."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); - responseDto = providerBusiness.getPetitionsForManager(providerId, managerDto.getId()); + responseDto = providerBusiness.getPetitionsFromManager(providerId, managerDto.getId()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error PetitionV1Controller@getPetitionsForManager#Microservice ---> " + e.getMessage()); + log.error("Error PetitionV1Controller@getPetitionsFromManager#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error PetitionV1Controller@getPetitionsForManager#Business ---> " + e.getMessage()); + log.error("Error PetitionV1Controller@getPetitionsFromManager#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error PetitionV1Controller@getPetitionsForManager#General ---> " + e.getMessage()); + log.error("Error PetitionV1Controller@getPetitionsFromManager#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -162,29 +183,36 @@ public ResponseEntity getPetitionsForManager(@RequestHeader("authorizati @ApiOperation(value = "Get petitions for provider (open)") @ApiResponses(value = { @ApiResponse(code = 200, message = "Petitions got", response = CustomPetitionDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getPetitionsForProviderOpen(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getPetitionsForProviderOpen(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getPetitionsForProviderOpen"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para consultar esta información."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.getPetitionsForProviderOpen(providerDto.getId()); httpStatus = HttpStatus.OK; @@ -192,15 +220,18 @@ public ResponseEntity getPetitionsForProviderOpen(@RequestHeader("author } catch (DisconnectedMicroserviceException e) { log.error("Error PetitionV1Controller@getPetitionsForProviderOpen#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error PetitionV1Controller@getPetitionsForProviderOpen#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error PetitionV1Controller@getPetitionsForProviderOpen#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -210,23 +241,26 @@ public ResponseEntity getPetitionsForProviderOpen(@RequestHeader("author @ApiOperation(value = "Get petitions for provider (close)") @ApiResponses(value = { @ApiResponse(code = 200, message = "Petitions got", response = CustomPetitionDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getPetitionsForProviderClose( - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getPetitionsForProviderClose(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getPetitionsForProviderClose"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider MicroserviceProviderDto providerDto = providerBusiness .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { @@ -235,6 +269,8 @@ public ResponseEntity getPetitionsForProviderClose( if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para consultar esta información."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.getPetitionsForProviderClose(providerDto.getId()); httpStatus = HttpStatus.OK; @@ -242,51 +278,62 @@ public ResponseEntity getPetitionsForProviderClose( } catch (DisconnectedMicroserviceException e) { log.error("Error PetitionV1Controller@getPetitionsForProviderClose#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error PetitionV1Controller@getPetitionsForProviderClose#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error PetitionV1Controller@getPetitionsForProviderClose#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); } @PutMapping(value = "/{petitionId}/accept", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Update petition") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Petition updated", response = CustomPetitionDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiOperation(value = "Accept petition") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Petition accepted", response = CustomPetitionDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity acceptPetition(@RequestBody UpdatePetitionDto requestUpdatePetition, - @PathVariable Long petitionId, @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity acceptPetition(@RequestBody UpdatePetitionDto requestUpdatePetition, + @PathVariable Long petitionId, @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("acceptPetition"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, requestUpdatePetition.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para realizar cambios en la petición."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); // validate description - if (requestUpdatePetition.getJustification() == null || requestUpdatePetition.getJustification().isEmpty()) { + if (requestUpdatePetition.getJustification() == null + || requestUpdatePetition.getJustification().isEmpty()) { throw new InputValidationException("La justificación es requerida"); } @@ -297,55 +344,67 @@ public ResponseEntity acceptPetition(@RequestBody UpdatePetitionDto requ } catch (DisconnectedMicroserviceException e) { log.error("Error PetitionV1Controller@acceptPetition#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error PetitionV1Controller@acceptPetition#Validator ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error PetitionV1Controller@acceptPetition#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error PetitionV1Controller@acceptPetition#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); } @PutMapping(value = "/{petitionId}/reject", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Update petition") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Petition updated", response = CustomPetitionDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiOperation(value = "Reject petition") + @ApiResponses(value = { @ApiResponse(code = 200, message = "Petition rejected", response = CustomPetitionDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity rejectPetition(@RequestBody UpdatePetitionDto requestUpdatePetition, - @PathVariable Long petitionId, @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity rejectPetition(@RequestBody UpdatePetitionDto requestUpdatePetition, + @PathVariable Long petitionId, @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("rejectPetition"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, requestUpdatePetition.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para realizar cambios en la petición."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); // validate description - if (requestUpdatePetition.getJustification() == null || requestUpdatePetition.getJustification().isEmpty()) { + if (requestUpdatePetition.getJustification() == null + || requestUpdatePetition.getJustification().isEmpty()) { throw new InputValidationException("La justificación es requerida"); } @@ -356,19 +415,23 @@ public ResponseEntity rejectPetition(@RequestBody UpdatePetitionDto requ } catch (DisconnectedMicroserviceException e) { log.error("Error PetitionV1Controller@rejectPetition#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error PetitionV1Controller@rejectPetition#Validator ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error PetitionV1Controller@rejectPetition#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error PetitionV1Controller@rejectPetition#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ProviderV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ProviderV1Controller.java index 0d64ea0..3f6cffb 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ProviderV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/ProviderV1Controller.java @@ -3,7 +3,6 @@ import com.ai.st.microservice.common.business.AdministrationBusiness; import com.ai.st.microservice.common.dto.administration.MicroserviceUserDto; import com.ai.st.microservice.common.dto.general.BasicResponseDto; -import com.ai.st.microservice.common.dto.ili.MicroserviceQueryResultRegistralRevisionDto; import com.ai.st.microservice.common.dto.managers.MicroserviceManagerDto; import com.ai.st.microservice.common.dto.providers.MicroserviceProviderDto; import com.ai.st.microservice.common.dto.providers.MicroserviceProviderProfileDto; @@ -17,8 +16,9 @@ import com.ai.st.microservice.workspaces.dto.CreateTypeSupplyDto; import com.ai.st.microservice.workspaces.dto.TypeSupplyRequestedDto; import com.ai.st.microservice.workspaces.dto.providers.CustomRequestDto; -import com.ai.st.microservice.workspaces.dto.providers.CustomSupplyRequestedDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -37,7 +37,7 @@ import java.util.Date; import java.util.List; -@Api(value = "Manage Providers", tags = {"Providers"}) +@Api(value = "Manage Providers", tags = { "Providers" }) @RestController @RequestMapping("api/workspaces/v1/providers") public class ProviderV1Controller { @@ -50,7 +50,7 @@ public class ProviderV1Controller { private final AdministrationBusiness administrationBusiness; public ProviderV1Controller(WorkspaceBusiness workspaceBusiness, ProviderBusiness providerBusiness, - ManagerMicroserviceBusiness managerBusiness, AdministrationBusiness administrationBusiness) { + ManagerMicroserviceBusiness managerBusiness, AdministrationBusiness administrationBusiness) { this.workspaceBusiness = workspaceBusiness; this.providerBusiness = providerBusiness; this.managerBusiness = managerBusiness; @@ -59,12 +59,11 @@ public ProviderV1Controller(WorkspaceBusiness workspaceBusiness, ProviderBusines @PostMapping(value = "/municipalities/{municipalityId}/requests", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create request") - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Create request", response = CustomRequestDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Create request", response = CustomRequestDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity createRequest(@RequestBody CreateRequestDto createRequestDto, - @RequestHeader("authorization") String headerAuthorization, @PathVariable Long municipalityId) { + public ResponseEntity createRequest(@RequestBody CreateRequestDto createRequestDto, + @RequestHeader("authorization") String headerAuthorization, @PathVariable Long municipalityId) { HttpStatus httpStatus; List listRequests = new ArrayList<>(); @@ -72,13 +71,18 @@ public ResponseEntity createRequest(@RequestBody CreateRequestDto create try { - // user session + SCMTracing.setTransactionName("createSuppliesRequest"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, createRequestDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -86,6 +90,8 @@ public ResponseEntity createRequest(@RequestBody CreateRequestDto create if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para actualizar el soporte."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); // validation deadline String deadlineString = createRequestDto.getDeadline(); @@ -113,7 +119,8 @@ public ResponseEntity createRequest(@RequestBody CreateRequestDto create } } } else { - throw new InputValidationException("La solicitud debe contener al menos un tipo de insumo a solicitar."); + throw new InputValidationException( + "La solicitud debe contener al menos un tipo de insumo a solicitar."); } listRequests = workspaceBusiness.createRequest(deadline, supplies, userDtoSession.getId(), @@ -123,19 +130,23 @@ public ResponseEntity createRequest(@RequestBody CreateRequestDto create } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@createRequest#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error ProviderV1Controller@createRequest#Validation ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@createRequest#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@createRequest#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return (responseDto != null) ? new ResponseEntity<>(responseDto, httpStatus) @@ -146,9 +157,9 @@ public ResponseEntity createRequest(@RequestBody CreateRequestDto create @ApiOperation(value = "Get pending requests by provider") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get pending requests by provider", response = CustomRequestDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getRequestsPendingByProveedor(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getRequestsPendingByProveedor(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; List listRequests = new ArrayList<>(); @@ -156,17 +167,23 @@ public ResponseEntity getRequestsPendingByProveedor(@RequestHeader("auth try { - // user session + SCMTracing.setTransactionName("getRequestsPendingByProveedor"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserTechnical(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); listRequests = workspaceBusiness.getPendingRequestByProvider(userDtoSession.getId(), providerDto.getId()); httpStatus = HttpStatus.OK; @@ -174,15 +191,18 @@ public ResponseEntity getRequestsPendingByProveedor(@RequestHeader("auth } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@getRequestsPendingByProveedor#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@getRequestsPendingByProveedor#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@getRequestsPendingByProveedor#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return (responseDto != null) ? new ResponseEntity<>(responseDto, httpStatus) @@ -193,9 +213,9 @@ public ResponseEntity getRequestsPendingByProveedor(@RequestHeader("auth @ApiOperation(value = "Get closed-requests") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get closed requests by provider", response = CustomRequestDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getRequestsClosedByProveedor(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getRequestsClosedByProveedor(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; List listRequests = new ArrayList<>(); @@ -203,17 +223,24 @@ public ResponseEntity getRequestsClosedByProveedor(@RequestHeader("autho try { - // user session + SCMTracing.setTransactionName("getRequestsClosedByProveedor"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserTechnicalOrAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserTechnicalOrAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); listRequests = workspaceBusiness.getClosedRequestByProvider(userDtoSession.getId(), providerDto.getId()); httpStatus = HttpStatus.OK; @@ -221,15 +248,18 @@ public ResponseEntity getRequestsClosedByProveedor(@RequestHeader("autho } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@getRequestsClosedByProveedor#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@getRequestsClosedByProveedor#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@getRequestsClosedByProveedor#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return (responseDto != null) ? new ResponseEntity<>(responseDto, httpStatus) @@ -238,32 +268,38 @@ public ResponseEntity getRequestsClosedByProveedor(@RequestHeader("autho @PutMapping(value = "/requests/{requestId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Answer request") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Answer request", response = CustomRequestDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Answer request", response = CustomRequestDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity answerRequest(@PathVariable Long requestId, - @RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "files[]", required = false) MultipartFile[] files, - @RequestParam(name = "extra", required = false) MultipartFile extraFile, - @ModelAttribute AnswerRequestDto answerRequest) { + public ResponseEntity answerRequest(@PathVariable Long requestId, + @RequestHeader("authorization") String headerAuthorization, + @RequestParam(name = "files[]", required = false) MultipartFile[] files, + @RequestParam(name = "extra", required = false) MultipartFile extraFile, + @ModelAttribute AnswerRequestDto answerRequest) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("answerSuppliesRequest"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, answerRequest.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserTechnical(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); // validation type supply Long typeSupplyId = answerRequest.getTypeSupplyId(); @@ -271,27 +307,31 @@ public ResponseEntity answerRequest(@PathVariable Long requestId, throw new InputValidationException("El tipo de insumo es inválido."); } - responseDto = providerBusiness.answerRequest(requestId, typeSupplyId, answerRequest.getSkipErrors(), answerRequest.getJustification(), - files, extraFile, answerRequest.getUrl(), providerDto, userDtoSession.getId(), - answerRequest.getObservations()); + responseDto = providerBusiness.answerRequest(requestId, typeSupplyId, answerRequest.getSkipErrors(), + answerRequest.getJustification(), files, extraFile, answerRequest.getUrl(), providerDto, + userDtoSession.getId(), answerRequest.getObservations()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@answerRequest#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error ProviderV1Controller@answerRequest#Validation ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@answerRequest#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@answerRequest#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -299,29 +339,34 @@ public ResponseEntity answerRequest(@PathVariable Long requestId, @PutMapping(value = "/requests/{requestId}/close", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Close request") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Close request", response = CustomRequestDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Close request", response = CustomRequestDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity closeRequest(@PathVariable Long requestId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity closeRequest(@PathVariable Long requestId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("closeRequest"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserTechnical(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.closeRequest(requestId, providerDto, userDtoSession.getId()); httpStatus = HttpStatus.OK; @@ -329,15 +374,18 @@ public ResponseEntity closeRequest(@PathVariable Long requestId, } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@closeRequest#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@closeRequest#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@closeRequest#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -345,28 +393,33 @@ public ResponseEntity closeRequest(@PathVariable Long requestId, @GetMapping(value = "/requests/emmiters", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Close request") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Close request", response = CustomRequestDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Close request", response = CustomRequestDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getRequestsByEmitters(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getRequestsByEmitters(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getRequestsByEmitters"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = providerBusiness.getRequestsByEmittersManager(managerDto.getId()); httpStatus = HttpStatus.OK; @@ -374,15 +427,18 @@ public ResponseEntity getRequestsByEmitters(@RequestHeader("authorizatio } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@getRequestsByEmmiters#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@getRequestsByEmmiters#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@getRequestsByEmmiters#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -392,30 +448,38 @@ public ResponseEntity getRequestsByEmitters(@RequestHeader("authorizatio @ApiOperation(value = "Create type supply") @ApiResponses(value = { @ApiResponse(code = 201, message = "Create type supply", response = MicroserviceTypeSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity createTypeSupply(@RequestBody CreateTypeSupplyDto createTypeSupplyDto, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("createTypeSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, createTypeSupplyDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para crear insumos."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.createTypeSupply(providerDto.getId(), createTypeSupplyDto.getName(), createTypeSupplyDto.getDescription(), createTypeSupplyDto.getMetadataRequired(), @@ -426,15 +490,18 @@ public ResponseEntity createTypeSupply(@RequestBody CreateTypeSupplyDto } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@createTypeSupply#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@createTypeSupply#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@createTypeSupply#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -444,29 +511,36 @@ public ResponseEntity createTypeSupply(@RequestBody CreateTypeSupplyDto @ApiOperation(value = "Get types supplies") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get types supplies", response = MicroserviceTypeSupplyDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getTypeSupplies(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getTypeSupplies(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getTypeSupplies"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para consultar insumos."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.getTypesSuppliesByProvider(providerDto.getId()); httpStatus = HttpStatus.OK; @@ -474,15 +548,18 @@ public ResponseEntity getTypeSupplies(@RequestHeader("authorization") St } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@getTypeSupplies#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@getTypeSupplies#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@getTypeSupplies#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -492,50 +569,61 @@ public ResponseEntity getTypeSupplies(@RequestHeader("authorization") St @ApiOperation(value = "Update type supply") @ApiResponses(value = { @ApiResponse(code = 200, message = "Update type supply", response = MicroserviceTypeSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity updateTypeSupply(@PathVariable Long typeSupplyId, - @RequestBody CreateTypeSupplyDto createTypeSupplyDto, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity updateTypeSupply(@PathVariable Long typeSupplyId, + @RequestBody CreateTypeSupplyDto updateTypeSupplyDto, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("updateTypeSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, updateTypeSupplyDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para modificar insumos."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.updateTypeSupply(providerDto.getId(), typeSupplyId, - createTypeSupplyDto.getName(), createTypeSupplyDto.getDescription(), - createTypeSupplyDto.getMetadataRequired(), createTypeSupplyDto.getModelRequired(), - createTypeSupplyDto.getProviderProfileId(), createTypeSupplyDto.getExtensions()); + updateTypeSupplyDto.getName(), updateTypeSupplyDto.getDescription(), + updateTypeSupplyDto.getMetadataRequired(), updateTypeSupplyDto.getModelRequired(), + updateTypeSupplyDto.getProviderProfileId(), updateTypeSupplyDto.getExtensions()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@updateTypeSupply#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@updateTypeSupply#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@updateTypeSupply #General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -545,30 +633,37 @@ public ResponseEntity updateTypeSupply(@PathVariable Long typeSupplyId, @ApiOperation(value = "Enable type supply") @ApiResponses(value = { @ApiResponse(code = 200, message = "Type supply enabled", response = MicroserviceTypeSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity enableTypeSupply(@PathVariable Long typeSupplyId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity enableTypeSupply(@PathVariable Long typeSupplyId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("enableTypeSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para modificar el tipo de insumo."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.enableTypeSupply(providerDto.getId(), typeSupplyId); httpStatus = HttpStatus.OK; @@ -576,15 +671,18 @@ public ResponseEntity enableTypeSupply(@PathVariable Long typeSupplyId, } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@enableTypeSupply#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@enableTypeSupply#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@enableTypeSupply #General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -594,30 +692,37 @@ public ResponseEntity enableTypeSupply(@PathVariable Long typeSupplyId, @ApiOperation(value = "Disable type supply") @ApiResponses(value = { @ApiResponse(code = 200, message = "Type supply disabled", response = MicroserviceTypeSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity disableTypeSupply(@PathVariable Long typeSupplyId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity disableTypeSupply(@PathVariable Long typeSupplyId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("disableTypeSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para modificar el tipo de insumo."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.disableTypeSupply(providerDto.getId(), typeSupplyId); httpStatus = HttpStatus.OK; @@ -625,15 +730,18 @@ public ResponseEntity disableTypeSupply(@PathVariable Long typeSupplyId, } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@disableTypeSupply#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@disableTypeSupply#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@disableTypeSupply #General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -641,31 +749,38 @@ public ResponseEntity disableTypeSupply(@PathVariable Long typeSupplyId, @DeleteMapping(value = "/types-supplies/{typeSupplyId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Delete type supply") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Delete type supply"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Delete type supply"), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity deleteTypeSupply(@PathVariable Long typeSupplyId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity deleteTypeSupply(@PathVariable Long typeSupplyId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("deleteTypeSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para eliminar insumos."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); providerBusiness.deleteTypeSupply(providerDto.getId(), typeSupplyId); httpStatus = HttpStatus.NO_CONTENT; @@ -673,15 +788,18 @@ public ResponseEntity deleteTypeSupply(@PathVariable Long typeSupplyId, } catch (DisconnectedMicroserviceException e) { log.error("Error ProviderV1Controller@deleteTypeSupply#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error ProviderV1Controller@deleteTypeSupply#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error ProviderV1Controller@deleteTypeSupply #General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -690,31 +808,39 @@ public ResponseEntity deleteTypeSupply(@PathVariable Long typeSupplyId, @PostMapping(value = "/profiles", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create profile") @ApiResponses(value = { - @ApiResponse(code = 201, message = "Create profile", response = MicroserviceProviderProfileDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 201, message = "Profile created", response = MicroserviceProviderProfileDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity createProfile(@RequestBody CreateProviderProfileDto createProfileDto, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity createProviderProfile(@RequestBody CreateProviderProfileDto createProfileDto, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("createProviderProfile"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, createProfileDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para crear perfiles."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.createProfile(providerDto.getId(), createProfileDto.getName(), createProfileDto.getDescription()); @@ -722,17 +848,20 @@ public ResponseEntity createProfile(@RequestBody CreateProviderProfileDt httpStatus = HttpStatus.CREATED; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@createProfile#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@createProviderProfile#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@createProfile#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@createProviderProfile#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@createProfile#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@createProviderProfile#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -742,45 +871,55 @@ public ResponseEntity createProfile(@RequestBody CreateProviderProfileDt @ApiOperation(value = "Get profiles") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get profiles", response = MicroserviceProviderProfileDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getProfiles(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getProviderProfiles(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getProviderProfiles"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para consultar perfiles."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.getProfilesByProvider(providerDto.getId()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@getProfiles#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getProviderProfiles#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@getProfiles#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getProviderProfiles#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@getProfiles#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getProviderProfiles#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -790,48 +929,59 @@ public ResponseEntity getProfiles(@RequestHeader("authorization") String @ApiOperation(value = "Update profile") @ApiResponses(value = { @ApiResponse(code = 200, message = "Update profile", response = MicroserviceProviderProfileDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity updateProfile(@PathVariable Long profileId, - @RequestHeader("authorization") String headerAuthorization, - @RequestBody CreateProviderProfileDto updateProfileDto) { + public ResponseEntity updateProviderProfile(@PathVariable Long profileId, + @RequestHeader("authorization") String headerAuthorization, + @RequestBody CreateProviderProfileDto updateProfileDto) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("updateProviderProfile"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, updateProfileDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para modificar perfiles."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); responseDto = providerBusiness.updateProfile(providerDto.getId(), profileId, updateProfileDto.getName(), updateProfileDto.getDescription()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@updateProfile#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@updateProviderProfile#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@updateProfile#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@updateProviderProfile#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@updateProfile#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@updateProviderProfile#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -839,47 +989,57 @@ public ResponseEntity updateProfile(@PathVariable Long profileId, @DeleteMapping(value = "/profiles/{profileId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Delete profile") - @ApiResponses(value = {@ApiResponse(code = 204, message = "Delete profile"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Delete profile"), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity deleteProfile(@PathVariable Long profileId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity deleteProviderProfile(@PathVariable Long profileId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("deleteProviderProfile"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); + MicroserviceProviderDto providerDto = providerBusiness + .getProviderByUserAdministrator(userDtoSession.getId()); if (providerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); } if (!providerBusiness.userProviderIsDirector(userDtoSession.getId())) { throw new BusinessException("No tiene permiso para remover perfiles."); } + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_ID, providerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.PROVIDER_NAME, providerDto.getName()); providerBusiness.deleteProfile(providerDto.getId(), profileId); httpStatus = HttpStatus.NO_CONTENT; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@deleteProfile#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@deleteProviderProfile#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@deleteProfile#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@deleteProviderProfile#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@deleteProfile#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@deleteProviderProfile#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -888,29 +1048,35 @@ public ResponseEntity deleteProfile(@PathVariable Long profileId, @GetMapping(value = "/requests/municipality", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get requests by municipality") @ApiResponses(value = { - @ApiResponse(code = 200, message = "Get requests", response = CustomRequestDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 200, message = "Requests got", response = CustomRequestDto.class, responseContainer = "List"), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getRequestsByMunicipality(@RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "page") Integer page, - @RequestParam(name = "municipality") String municipalityCode) { + public ResponseEntity getRequestsByMunicipalityForManager( + @RequestHeader("authorization") String headerAuthorization, @RequestParam(name = "page") Integer page, + @RequestParam(name = "municipality") String municipalityCode) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getRequestsByMunicipalityForManager"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = providerBusiness.getRequestsByManagerAndMunicipality(page, managerDto.getId(), municipalityCode); @@ -918,17 +1084,21 @@ public ResponseEntity getRequestsByMunicipality(@RequestHeader("authoriz httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@getRequestsByMunicipality#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByMunicipalityForManager#Microservice ---> " + + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@getRequestsByMunicipality#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByMunicipalityForManager#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@getRequestsByMunicipality#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByMunicipalityForManager#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -938,44 +1108,52 @@ public ResponseEntity getRequestsByMunicipality(@RequestHeader("authoriz @ApiOperation(value = "Get requests by provider") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get requests", response = CustomRequestDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getRequestsByProvider(@RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "page") Integer page, - @RequestParam(name = "provider") Long providerId) { + public ResponseEntity getRequestsByProviderForManager(@RequestHeader("authorization") String headerAuthorization, + @RequestParam(name = "page") Integer page, @RequestParam(name = "provider") Long providerId) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getRequestsByProviderForManager"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = providerBusiness.getRequestsByManagerAndProvider(page, managerDto.getId(), providerId); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@getRequestsByProvider#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByProviderForManager#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@getRequestsByProvider#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByProviderForManager#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@getRequestsByProvider#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByProviderForManager#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -985,340 +1163,52 @@ public ResponseEntity getRequestsByProvider(@RequestHeader("authorizatio @ApiOperation(value = "Get requests by package") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get requests", response = CustomRequestDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getRequestsByPackage(@RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "package", required = false) String packageLabel) { + public ResponseEntity getRequestsByPackageForManager(@RequestHeader("authorization") String headerAuthorization, + @RequestParam(name = "package", required = false) String packageLabel) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getRequestsByPackageForManager"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = providerBusiness.getRequestsByManagerAndPackage(managerDto.getId(), packageLabel); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@getRequestsByPackage#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); - } catch (BusinessException e) { - log.error("Error ProviderV1Controller@getRequestsByPackage#Business ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); - } catch (Exception e) { - log.error("Error ProviderV1Controller@getRequestsByPackage#General ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); - } - - return new ResponseEntity<>(responseDto, httpStatus); - } - - @GetMapping(value = "/supplies-review", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Get supplies requested to review") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Get supplies requested to review", response = CustomSupplyRequestedDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) - @ResponseBody - public ResponseEntity getSuppliesRequestedToReview(@RequestHeader("authorization") String headerAuthorization) { - - HttpStatus httpStatus; - Object responseDto; - - try { - - // user session - MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); - if (userDtoSession == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); - } - - // get provider - MicroserviceProviderDto providerDto = providerBusiness - .getProviderByUserAdministrator(userDtoSession.getId()); - if (providerDto == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); - } - if (!providerBusiness.userProviderIsDelegate(userDtoSession.getId())) { - throw new BusinessException("No tiene permiso para consultar insumos pendientes de revisión."); - } - - responseDto = providerBusiness.getSuppliesToReview(providerDto.getId()); - httpStatus = HttpStatus.OK; - - } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@getSuppliesRequestedToReview#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); - } catch (BusinessException e) { - log.error("Error ProviderV1Controller@getSuppliesRequestedToReview#Business ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); - } catch (Exception e) { - log.error("Error ProviderV1Controller@getSuppliesRequestedToReview#General ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); - } - - return new ResponseEntity<>(responseDto, httpStatus); - } - - @PostMapping(value = "/supplies-review/{supplyRequestedId}/start", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Start revision") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Start revision", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) - @ResponseBody - public ResponseEntity startRevision(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long supplyRequestedId) { - - HttpStatus httpStatus; - Object responseDto; - - try { - - // user session - MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); - if (userDtoSession == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); - } - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); - if (providerDto == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); - } - if (!providerBusiness.userProviderIsDelegate(userDtoSession.getId())) { - throw new BusinessException("No tiene permiso para iniciar la revisión."); - } - - providerBusiness.startRevision(supplyRequestedId, userDtoSession.getId(), providerDto); - responseDto = new BasicResponseDto("Revisión iniciada", 7); - httpStatus = HttpStatus.OK; - - } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@startRevision#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); - } catch (BusinessException e) { - log.error("Error ProviderV1Controller@startRevision#Business ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); - } catch (Exception e) { - log.error("Error ProviderV1Controller@startRevision#General ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); - } - - return new ResponseEntity<>(responseDto, httpStatus); - } - - @GetMapping(value = "/supplies-review/{supplyRequestedId}/records", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Start revision") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Start revision", response = MicroserviceQueryResultRegistralRevisionDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) - @ResponseBody - public ResponseEntity getRecordsFromRevision(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long supplyRequestedId, @RequestParam(name = "page") int page) { - - HttpStatus httpStatus; - Object responseDto; - - try { - - // user session - MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); - if (userDtoSession == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); - } - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); - if (providerDto == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); - } - if (!providerBusiness.userProviderIsDelegate(userDtoSession.getId())) { - throw new BusinessException("No tiene permiso para consultar esta información."); - } - - responseDto = providerBusiness.getRecordsFromRevision(providerDto, supplyRequestedId, page); - httpStatus = HttpStatus.OK; - - } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@startRevision#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); - } catch (BusinessException e) { - log.error("Error ProviderV1Controller@startRevision#Business ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); - } catch (Exception e) { - log.error("Error ProviderV1Controller@startRevision#General ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); - } - - return new ResponseEntity<>(responseDto, httpStatus); - } - - @PostMapping(value = "/supplies-review/{supplyRequestedId}/update/{boundarySpaceId}", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Start revision") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Start revision", response = MicroserviceQueryResultRegistralRevisionDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) - @ResponseBody - public ResponseEntity updateRecordBoundarySpace(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long supplyRequestedId, @PathVariable Long boundarySpaceId, - @RequestParam(name = "file") MultipartFile file) { - - HttpStatus httpStatus; - Object responseDto; - - try { - - // user session - MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); - if (userDtoSession == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); - } - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); - if (providerDto == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); - } - if (!providerBusiness.userProviderIsDelegate(userDtoSession.getId())) { - throw new BusinessException("No tiene permiso para actualizar la información."); - } - - providerBusiness.uploadAttachmentToRevision(providerDto, file, supplyRequestedId, boundarySpaceId, - userDtoSession.getId()); - responseDto = new BasicResponseDto("Registro actualizado", 7); - httpStatus = HttpStatus.OK; - - } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@updateRecordBoundarySpace#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); - } catch (BusinessException e) { - log.error("Error ProviderV1Controller@updateRecordBoundarySpace#Business ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); - } catch (Exception e) { - log.error("Error ProviderV1Controller@updateRecordBoundarySpace#General ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); - } - - return new ResponseEntity<>(responseDto, httpStatus); - } - - @PostMapping(value = "/supplies-review/{supplyRequestedId}/close", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Start revision") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Start revision", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) - @ResponseBody - public ResponseEntity closeRevision(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long supplyRequestedId) { - - HttpStatus httpStatus; - Object responseDto; - - try { - - // user session - MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); - if (userDtoSession == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); - } - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); - if (providerDto == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); - } - if (!providerBusiness.userProviderIsDelegate(userDtoSession.getId())) { - throw new BusinessException("No tiene permiso para cerrar la revisión."); - } - - providerBusiness.closeRevision(supplyRequestedId, userDtoSession.getId(), providerDto); - responseDto = new BasicResponseDto("El proceso de cerrar revisión ha iniciado", 7); - httpStatus = HttpStatus.OK; - - } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@startRevision#Microservice ---> " + e.getMessage()); - httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); - } catch (BusinessException e) { - log.error("Error ProviderV1Controller@startRevision#Business ---> " + e.getMessage()); - httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); - } catch (Exception e) { - log.error("Error ProviderV1Controller@startRevision#General ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); - } - - return new ResponseEntity<>(responseDto, httpStatus); - } - - @PostMapping(value = "/supplies-review/{supplyRequestedId}/skip", produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(value = "Start revision") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Start revision", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) - @ResponseBody - public ResponseEntity skipRevision(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long supplyRequestedId) { - - HttpStatus httpStatus; - Object responseDto; - - try { - - // user session - MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); - if (userDtoSession == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); - } - - // get provider - MicroserviceProviderDto providerDto = providerBusiness.getProviderByUserAdministrator(userDtoSession.getId()); - if (providerDto == null) { - throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el proveedor."); - } - if (!providerBusiness.userProviderIsDelegate(userDtoSession.getId())) { - throw new BusinessException("No tiene permiso para omitir la revisión."); - } - - providerBusiness.skipRevision(supplyRequestedId, userDtoSession.getId(), providerDto); - responseDto = new BasicResponseDto("Revisión omitida", 7); - httpStatus = HttpStatus.OK; - - } catch (DisconnectedMicroserviceException e) { - log.error("Error ProviderV1Controller@skipRevision#Microservice ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByPackageForManager#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error ProviderV1Controller@skipRevision#Business ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByPackageForManager#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error ProviderV1Controller@skipRevision#General ---> " + e.getMessage()); + log.error("Error ProviderV1Controller@getRequestsByPackageForManager#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/SupplyV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/SupplyV1Controller.java index a4729ff..8b97ae0 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/SupplyV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/SupplyV1Controller.java @@ -10,6 +10,8 @@ import com.ai.st.microservice.workspaces.business.SupplyBusiness; import com.ai.st.microservice.workspaces.dto.supplies.CustomSupplyDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -24,7 +26,7 @@ import java.util.List; -@Api(value = "Manage Supplies", tags = {"Supplies"}) +@Api(value = "Manage Supplies", tags = { "Supplies" }) @RestController @RequestMapping("api/workspaces/v1/supplies") public class SupplyV1Controller { @@ -36,7 +38,7 @@ public class SupplyV1Controller { private final AdministrationBusiness administrationBusiness; public SupplyV1Controller(SupplyBusiness supplyBusiness, ManagerMicroserviceBusiness managerBusiness, - AdministrationBusiness administrationBusiness) { + AdministrationBusiness administrationBusiness) { this.supplyBusiness = supplyBusiness; this.managerBusiness = managerBusiness; this.administrationBusiness = administrationBusiness; @@ -46,40 +48,46 @@ public SupplyV1Controller(SupplyBusiness supplyBusiness, ManagerMicroserviceBusi @ApiOperation(value = "Get supplies by municipality") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get supplies", response = CustomSupplyDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getSuppliesByMunicipality(@PathVariable Long municipalityId, - @RequestParam(name = "extensions", required = false) List extensions, - @RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "page", required = false) Integer page, - @RequestParam(name = "manager", required = false) Long managerCode, - @RequestParam(name = "operator", required = false) Long operatorCode, - @RequestParam(name = "active", defaultValue = "true") boolean active, - @RequestParam(name = "requests", required = false) List requests) { + @RequestParam(name = "extensions", required = false) List extensions, + @RequestHeader("authorization") String headerAuthorization, + @RequestParam(name = "page", required = false) Integer page, + @RequestParam(name = "manager", required = false) Long managerCode, + @RequestParam(name = "operator", required = false) Long operatorCode, + @RequestParam(name = "active", defaultValue = "true") boolean active, + @RequestParam(name = "requests", required = false) List requests) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("getSuppliesByMunicipality"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = supplyBusiness.getSuppliesByMunicipalityAdmin(municipalityId, extensions, page, requests, active, managerCode); } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = supplyBusiness.getSuppliesByMunicipalityManager(municipalityId, managerDto.getId(), extensions, page, requests, active, operatorCode); @@ -90,12 +98,15 @@ public ResponseEntity getSuppliesByMunicipality(@PathVariable Long municipali } catch (DisconnectedMicroserviceException e) { log.error("Error SupplyV1Controller@getSuppliesByMunicipality#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error SupplyV1Controller@getSuppliesByMunicipality#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error SupplyV1Controller@getSuppliesByMunicipality#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -103,25 +114,28 @@ public ResponseEntity getSuppliesByMunicipality(@PathVariable Long municipali @PutMapping(value = "/{supplyId}/active", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Active supply") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Supply updated", response = CustomSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Supply activated", response = CustomSupplyDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity activeSupply(@PathVariable Long supplyId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("activeSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -129,6 +143,8 @@ public ResponseEntity activeSupply(@PathVariable Long supplyId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para activar insumos."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = supplyBusiness.changeStateSupply(supplyId, SupplyBusiness.SUPPLY_STATE_ACTIVE, managerDto.getId()); @@ -136,16 +152,19 @@ public ResponseEntity activeSupply(@PathVariable Long supplyId, } catch (DisconnectedMicroserviceException e) { log.error("Error SupplyV1Controller@activeSupply#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error SupplyV1Controller@activeSupply#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error SupplyV1Controller@activeSupply#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -153,25 +172,28 @@ public ResponseEntity activeSupply(@PathVariable Long supplyId, @PutMapping(value = "/{supplyId}/inactive", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Inactive supply") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Supply updated", response = CustomSupplyDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Supply inactivated", response = CustomSupplyDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity inactiveSupply(@PathVariable Long supplyId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("inactiveSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -179,6 +201,8 @@ public ResponseEntity inactiveSupply(@PathVariable Long supplyId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para activar insumos."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = supplyBusiness.changeStateSupply(supplyId, SupplyBusiness.SUPPLY_STATE_INACTIVE, managerDto.getId()); @@ -186,16 +210,19 @@ public ResponseEntity inactiveSupply(@PathVariable Long supplyId, } catch (DisconnectedMicroserviceException e) { log.error("Error SupplyV1Controller@inactiveSupply#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 5); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error SupplyV1Controller@inactiveSupply#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error SupplyV1Controller@inactiveSupply#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/TaskV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/TaskV1Controller.java index f4b56d8..9f734be 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/TaskV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/TaskV1Controller.java @@ -9,6 +9,8 @@ import com.ai.st.microservice.workspaces.dto.CancelTaskDto; import com.ai.st.microservice.workspaces.dto.tasks.CustomTaskDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -24,7 +26,7 @@ import java.util.ArrayList; import java.util.List; -@Api(value = "Manage Tasks", tags = {"Tasks"}) +@Api(value = "Manage Tasks", tags = { "Tasks" }) @RestController @RequestMapping("api/workspaces/v1/tasks") public class TaskV1Controller { @@ -43,9 +45,9 @@ public TaskV1Controller(TaskBusiness taskBusiness, AdministrationBusiness admini @ApiOperation(value = "Get pending tasks") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get pending tasks", response = CustomTaskDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getPendingTasks(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getPendingTasksForUser(@RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; List listTasks = new ArrayList<>(); @@ -53,27 +55,35 @@ public ResponseEntity getPendingTasks(@RequestHeader("authorization") St try { - // user session + SCMTracing.setTransactionName("getPendingTasksForUser"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - listTasks = taskBusiness.getPendingTasks(userDtoSession.getId()); + listTasks = taskBusiness.getPendingTasksByUser(userDtoSession.getId()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error TaskV1Controller@createRequest#getPendingTasks ---> " + e.getMessage()); + log.error("Error TaskV1Controller@getPendingTasksForUser#getPendingTasks ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error TaskV1Controller@createRequest#getPendingTasks ---> " + e.getMessage()); + log.error("Error TaskV1Controller@getPendingTasksForUser#getPendingTasks ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error TaskV1Controller@createRequest#getPendingTasks ---> " + e.getMessage()); + log.error("Error TaskV1Controller@getPendingTasksForUser#getPendingTasks ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return (responseDto != null) ? new ResponseEntity<>(responseDto, httpStatus) @@ -84,21 +94,26 @@ public ResponseEntity getPendingTasks(@RequestHeader("authorization") St @ApiOperation(value = "Start task") @ApiResponses(value = { @ApiResponse(code = 200, message = "Task started", response = CustomTaskDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity startTask(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long taskId) { + @PathVariable Long taskId) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("startTask"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); responseDto = taskBusiness.startTask(taskId, userDtoSession.getId()); httpStatus = HttpStatus.OK; @@ -106,15 +121,18 @@ public ResponseEntity startTask(@RequestHeader("authorization") String header } catch (DisconnectedMicroserviceException e) { log.error("Error TaskV1Controller@startTask#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error TaskV1Controller@startTask#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error TaskV1Controller@startTask#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -124,21 +142,26 @@ public ResponseEntity startTask(@RequestHeader("authorization") String header @ApiOperation(value = "Finish task") @ApiResponses(value = { @ApiResponse(code = 200, message = "Task finished", response = CustomTaskDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity finishTask(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long taskId) { + @PathVariable Long taskId) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("finishTask"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); responseDto = taskBusiness.finishTask(taskId, userDtoSession); httpStatus = HttpStatus.OK; @@ -146,15 +169,18 @@ public ResponseEntity finishTask(@RequestHeader("authorization") String heade } catch (DisconnectedMicroserviceException e) { log.error("Error TaskV1Controller@finishTask#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error TaskV1Controller@finishTask#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error TaskV1Controller@finishTask#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -164,22 +190,26 @@ public ResponseEntity finishTask(@RequestHeader("authorization") String heade @ApiOperation(value = "Cancel task") @ApiResponses(value = { @ApiResponse(code = 200, message = "Task cancelled", response = CustomTaskDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity cancelTask(@RequestHeader("authorization") String headerAuthorization, - @PathVariable Long taskId, - @RequestBody CancelTaskDto cancelTaskRequest) { + @PathVariable Long taskId, @RequestBody CancelTaskDto cancelTaskRequest) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("cancelTask"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); String reason = cancelTaskRequest.getReason(); if (reason == null || reason.isEmpty()) { @@ -192,19 +222,23 @@ public ResponseEntity cancelTask(@RequestHeader("authorization") String heade } catch (DisconnectedMicroserviceException e) { log.error("Error TaskV1Controller@cancelTask#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error TaskV1Controller@cancelTask#Validation ---> " + e.getMessage()); - httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + httpStatus = HttpStatus.BAD_REQUEST; + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error TaskV1Controller@cancelTask#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error TaskV1Controller@cancelTask#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/WorkspaceV1Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/WorkspaceV1Controller.java index d0773b4..76ad200 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/WorkspaceV1Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v1/WorkspaceV1Controller.java @@ -15,7 +15,7 @@ import com.ai.st.microservice.workspaces.business.SupplyBusiness; import com.ai.st.microservice.workspaces.business.WorkspaceBusiness; import com.ai.st.microservice.workspaces.business.WorkspaceOperatorBusiness; -import com.ai.st.microservice.workspaces.dto.AssignOperatorWorkpaceDto; +import com.ai.st.microservice.workspaces.dto.AssignOperatorWorkspaceDto; import com.ai.st.microservice.workspaces.dto.IntegrationDto; import com.ai.st.microservice.workspaces.dto.CreateDeliveryDto; import com.ai.st.microservice.workspaces.dto.CreateSupplyDeliveryDto; @@ -25,6 +25,8 @@ import com.ai.st.microservice.workspaces.dto.WorkspaceOperatorDto; import com.ai.st.microservice.workspaces.dto.operators.CustomDeliveryDto; import com.ai.st.microservice.workspaces.dto.supplies.CustomSupplyDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import com.ai.st.microservice.workspaces.utils.ZipUtil; import org.apache.commons.lang.RandomStringUtils; @@ -55,7 +57,7 @@ import javax.servlet.ServletContext; -@Api(value = "Manage Workspaces", tags = {"Workspaces"}) +@Api(value = "Manage Workspaces", tags = { "Workspaces" }) @RestController @RequestMapping("api/workspaces/v1/workspaces") public class WorkspaceV1Controller { @@ -76,10 +78,10 @@ public class WorkspaceV1Controller { private final AdministrationBusiness administrationBusiness; public WorkspaceV1Controller(WorkspaceBusiness workspaceBusiness, IntegrationBusiness integrationBusiness, - SupplyBusiness supplyBusiness, OperatorMicroserviceBusiness operatorBusiness, - ManagerMicroserviceBusiness managerBusiness, MunicipalityBusiness municipalityBusiness, - WorkspaceOperatorBusiness workspaceOperatorBusiness, ServletContext servletContext, - AdministrationBusiness administrationBusiness) { + SupplyBusiness supplyBusiness, OperatorMicroserviceBusiness operatorBusiness, + ManagerMicroserviceBusiness managerBusiness, MunicipalityBusiness municipalityBusiness, + WorkspaceOperatorBusiness workspaceOperatorBusiness, ServletContext servletContext, + AdministrationBusiness administrationBusiness) { this.workspaceBusiness = workspaceBusiness; this.integrationBusiness = integrationBusiness; this.supplyBusiness = supplyBusiness; @@ -95,34 +97,38 @@ public WorkspaceV1Controller(WorkspaceBusiness workspaceBusiness, IntegrationBus @ApiOperation(value = "Get workspaces by municipality") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get workspaces by municipality", response = WorkspaceDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity> getWorkspacesByMunicipality(@PathVariable Long municipalityId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; List listWorkspaces = new ArrayList<>(); try { - // user session + SCMTracing.setTransactionName("getWorkspacesByMunicipality"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); listWorkspaces = workspaceBusiness.getWorkspacesByMunicipality(municipalityId, null); - } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); listWorkspaces = workspaceBusiness.getWorkspacesByMunicipality(municipalityId, managerDto.getId()); } @@ -131,14 +137,17 @@ public ResponseEntity> getWorkspacesByMunicipality(@PathVaria listWorkspaces = null; log.error("Error WorkspaceV1Controller@getWorkspacesByMunicipality#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { listWorkspaces = null; log.error("Error WorkspaceV1Controller@getWorkspacesByMunicipality#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { listWorkspaces = null; log.error("Error WorkspaceV1Controller@getWorkspacesByMunicipality#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(listWorkspaces, httpStatus); @@ -148,24 +157,29 @@ public ResponseEntity> getWorkspacesByMunicipality(@PathVaria @ApiOperation(value = "Assign operator to workspace (municipality)") @ApiResponses(value = { @ApiResponse(code = 200, message = "Assign operator to workspace", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity assignOperator(@PathVariable Long workspaceId, - @ModelAttribute AssignOperatorWorkpaceDto requestAssignOperator, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity assignOperator(@PathVariable Long workspaceId, + @ModelAttribute AssignOperatorWorkspaceDto requestAssignOperator, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("assignOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, requestAssignOperator.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -173,6 +187,8 @@ public ResponseEntity assignOperator(@PathVariable Long workspaceId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para descargar el soporte."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); // validation start date String startDateString = requestAssignOperator.getStartDate(); @@ -237,19 +253,23 @@ public ResponseEntity assignOperator(@PathVariable Long workspaceId, } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@assignOperator#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { log.error("Error WorkspaceV1Controller@assignOperator#Validation ---> " + e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; - responseDto = new BasicResponseDto(e.getMessage(), 1); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@assignOperator#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@assignOperator#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -257,35 +277,40 @@ public ResponseEntity assignOperator(@PathVariable Long workspaceId, @GetMapping(value = "/{workspaceId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get workspace by id") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Get workspace by id", response = WorkspaceDto.class), + @ApiResponses(value = { @ApiResponse(code = 200, message = "Get workspace by id", response = WorkspaceDto.class), @ApiResponse(code = 404, message = "Workspace not found", response = String.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getWorkspaceById(@PathVariable Long workspaceId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getWorkspaceById(@PathVariable Long workspaceId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("getWorkspaceById"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = workspaceBusiness.getWorkspaceById(workspaceId, null); - } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = workspaceBusiness.getWorkspaceById(workspaceId, managerDto.getId()); } @@ -295,15 +320,18 @@ public ResponseEntity getWorkspaceById(@PathVariable Long workspaceId, } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@getWorkspaceById#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@getWorkspaceById#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@getWorkspaceById#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -313,10 +341,10 @@ public ResponseEntity getWorkspaceById(@PathVariable Long workspaceId, @ApiOperation(value = "Get operators by workspace") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get operators by workspace", response = WorkspaceDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getOperatorsByWorkspace(@PathVariable Long workspaceId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; List listOperators = new ArrayList<>(); @@ -324,24 +352,28 @@ public ResponseEntity getOperatorsByWorkspace(@PathVariable Long workspaceId, try { - // user session + SCMTracing.setTransactionName("getOperatorsByWorkspace"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); listOperators = workspaceBusiness.getOperatorsByWorkspaceId(workspaceId, null); - } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); listOperators = workspaceBusiness.getOperatorsByWorkspaceId(workspaceId, managerDto.getId()); } @@ -350,15 +382,18 @@ public ResponseEntity getOperatorsByWorkspace(@PathVariable Long workspaceId, } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@getOperatorsByWorkspace#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@getOperatorsByWorkspace#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@getOperatorsByWorkspace#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return (responseDto != null) ? new ResponseEntity<>(responseDto, httpStatus) @@ -369,55 +404,63 @@ public ResponseEntity getOperatorsByWorkspace(@PathVariable Long workspaceId, @ApiOperation(value = "Get workspace active by municipality") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get workspace active by municipality", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getWorkspaceActiveByMunicipality(@PathVariable Long municipalityId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getWorkspaceActiveByMunicipality(@PathVariable Long municipalityId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("getWorkspaceActiveByMunicipality"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = workspaceBusiness.getWorkspaceActiveByMunicipality(municipalityId, null); - } else if (administrationBusiness.isManager(userDtoSession)) { - - // verify that you have access to the municipality + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } - if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { - throw new InputValidationException("El usuario no tiene permisos para consultar el espacio de trabajo."); + throw new InputValidationException( + "El usuario no tiene permisos para consultar el espacio de trabajo."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = workspaceBusiness.getWorkspaceActiveByMunicipality(municipalityId, managerDto.getId()); } httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@getWorkspaceActiveByMunicipality#Microservice ---> " + e.getMessage()); + log.error( + "Error WorkspaceV1Controller@getWorkspaceActiveByMunicipality#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@getWorkspaceActiveByMunicipality#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@getWorkspaceActiveByMunicipality#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -425,25 +468,30 @@ public ResponseEntity getWorkspaceActiveByMunicipality(@PathVariable Lon @PostMapping(value = "/integration/{municipalityId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Make integration") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Integration done", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Integration done", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity makeIntegrationAutomatic(@PathVariable Long municipalityId, - @RequestBody MakeIntegrationDto requestMakeIntegration, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity makeAutomaticIntegration(@PathVariable Long municipalityId, + @RequestBody MakeIntegrationDto requestMakeIntegration, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("makeAutomaticIntegration"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, requestMakeIntegration.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -451,6 +499,8 @@ public ResponseEntity makeIntegrationAutomatic(@PathVariable Long municipalit if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para realizar la integración."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); // validation supply cadastre Long supplyCadastre = requestMakeIntegration.getSupplyCadastre(); @@ -470,17 +520,20 @@ public ResponseEntity makeIntegrationAutomatic(@PathVariable Long municipalit httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@makeIntegration#Microservice ---> " + e.getMessage()); + log.error("Error WorkspaceV1Controller@makeAutomaticIntegration#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error WorkspaceV1Controller@makeIntegration#Business ---> " + e.getMessage()); + log.error("Error WorkspaceV1Controller@makeAutomaticIntegration#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV1Controller@makeIntegration#General ---> " + e.getMessage()); + log.error("Error WorkspaceV1Controller@makeAutomaticIntegration#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -490,34 +543,38 @@ public ResponseEntity makeIntegrationAutomatic(@PathVariable Long municipalit @ApiOperation(value = "Get integrations by workspace") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get integrations", response = IntegrationDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getIntegrationsByWorkspace(@PathVariable Long workspaceId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("getIntegrationsByWorkspace"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = integrationBusiness.getIntegrationsByWorkspace(workspaceId, null); - } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = integrationBusiness.getIntegrationsByWorkspace(workspaceId, managerDto.getId()); } @@ -526,15 +583,18 @@ public ResponseEntity getIntegrationsByWorkspace(@PathVariable Long workspace } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@getIntegrationsByWorkspace#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@getIntegrationsByWorkspace#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@getIntegrationsByWorkspace#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -542,31 +602,38 @@ public ResponseEntity getIntegrationsByWorkspace(@PathVariable Long workspace @PostMapping(value = "{workspaceId}/integrations/{integrationId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Start integration assisted") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Get integrations", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Get integrations", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity startIntegrationAssisted(@PathVariable Long workspaceId, @PathVariable Long integrationId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("startIntegrationAssisted"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { - throw new InputValidationException("El usuario no tiene permisos para realizar la integración asistida."); + throw new InputValidationException( + "El usuario no tiene permisos para realizar la integración asistida."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = workspaceBusiness.startIntegrationAssisted(workspaceId, integrationId, managerDto, userDtoSession); @@ -575,15 +642,18 @@ public ResponseEntity startIntegrationAssisted(@PathVariable Long workspaceId } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@startIntegrationAssisted#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@startIntegrationAssisted#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@startIntegrationAssisted#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -591,24 +661,28 @@ public ResponseEntity startIntegrationAssisted(@PathVariable Long workspaceId @PostMapping(value = "{workspaceId}/integrations/{integrationId}/export", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Generate supply from integration") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Supply generated", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Supply generated", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity generateSupply(@PathVariable Long workspaceId, @PathVariable Long integrationId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity generateSupplyFromIntegration(@PathVariable Long workspaceId, + @PathVariable Long integrationId, @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("generateSupplyFromIntegration"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -616,22 +690,27 @@ public ResponseEntity generateSupply(@PathVariable Long workspaceId, @PathVar if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para actualizar el soporte."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); responseDto = workspaceBusiness.exportXtf(workspaceId, integrationId, managerDto, userDtoSession); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@generateSupply#Microservice ---> " + e.getMessage()); + log.error("Error WorkspaceV1Controller@generateSupplyFromIntegration#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error WorkspaceV1Controller@generateSupply#Business ---> " + e.getMessage()); + log.error("Error WorkspaceV1Controller@generateSupplyFromIntegration#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV1Controller@generateSupply#General ---> " + e.getMessage()); + log.error("Error WorkspaceV1Controller@generateSupplyFromIntegration#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -641,24 +720,27 @@ public ResponseEntity generateSupply(@PathVariable Long workspaceId, @PathVar @ApiOperation(value = "Remove integration from workspace") @ApiResponses(value = { @ApiResponse(code = 200, message = "Integration deleted", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity removeIntegrationFromWorkspace(@PathVariable Long workspaceId, - @PathVariable Long integrationId, - @RequestHeader("authorization") String headerAuthorization) { + @PathVariable Long integrationId, @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("removeIntegrationFromWorkspace"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -666,6 +748,8 @@ public ResponseEntity removeIntegrationFromWorkspace(@PathVariable Long works if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para actualizar el soporte."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); workspaceBusiness.removeIntegrationFromWorkspace(workspaceId, integrationId, managerDto.getId()); responseDto = new BasicResponseDto("Se ha borrado la integración", 7); @@ -674,15 +758,18 @@ public ResponseEntity removeIntegrationFromWorkspace(@PathVariable Long works } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@removeIntegrationFromWorkspace#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 4); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@removeIntegrationFromWorkspace#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@removeIntegrationFromWorkspace#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -690,11 +777,11 @@ public ResponseEntity removeIntegrationFromWorkspace(@PathVariable Long works @GetMapping(value = "download-supply/{supplyId}") @ApiOperation(value = "Download file") - @ApiResponses(value = {@ApiResponse(code = 200, message = "File downloaded", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "File downloaded", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity downloadSupply(@PathVariable Long supplyId, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { MediaType mediaType; File file; @@ -703,11 +790,16 @@ public ResponseEntity downloadSupply(@PathVariable Long supplyId, try { - // user session + SCMTracing.setTransactionName("downloadSupply"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); supplyDto = supplyBusiness.getSupplyById(supplyId); if (supplyDto == null) { @@ -715,8 +807,7 @@ public ResponseEntity downloadSupply(@PathVariable Long supplyId, } if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -724,27 +815,27 @@ public ResponseEntity downloadSupply(@PathVariable Long supplyId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para actualizar el soporte."); } - - if (!workspaceBusiness.managerHasAccessToMunicipality(supplyDto.getMunicipalityCode(), managerDto.getId())) { + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); + if (!workspaceBusiness.managerHasAccessToMunicipality(supplyDto.getMunicipalityCode(), + managerDto.getId())) { throw new InputValidationException("El gestor no tiene acceso al insumo."); } - if (!supplyDto.getManagerCode().equals(managerDto.getId())) { throw new BusinessException("No tiene acceso al insumo"); } - } else if (administrationBusiness.isOperator(userDtoSession)) { - - // get operator + SCMTracing.addCustomParameter(TracingKeyword.IS_OPERATOR, true); MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); - - CustomDeliveryDto deliveryDto = workspaceOperatorBusiness.getDeliveryFromSupply(operatorDto.getId(), supplyDto.getId()); + CustomDeliveryDto deliveryDto = workspaceOperatorBusiness.getDeliveryFromSupply(operatorDto.getId(), + supplyDto.getId()); if (deliveryDto == null) { throw new InputValidationException("El operador no tiene acceso al insumo."); } - - workspaceOperatorBusiness.registerDownloadSupply(deliveryDto, supplyDto.getId(), userDtoSession.getId()); - + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); + workspaceOperatorBusiness.registerDownloadSupply(deliveryDto, supplyDto.getId(), + userDtoSession.getId()); } String pathFile; @@ -758,7 +849,8 @@ public ResponseEntity downloadSupply(@PathVariable Long supplyId, .getAttachmentType().getId().equals(SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_EXTERNAL_SOURCE)) .findAny().orElse(null); - MunicipalityDto municipalityDto = municipalityBusiness.getMunicipalityByCode(supplyDto.getMunicipalityCode()); + MunicipalityDto municipalityDto = municipalityBusiness + .getMunicipalityByCode(supplyDto.getMunicipalityCode()); // the supply has FTP if (attachmentFtp != null && attachmentSupply == null) { @@ -766,10 +858,11 @@ public ResponseEntity downloadSupply(@PathVariable Long supplyId, File fileFTP = supplyBusiness.generateFTPFile(supplyDto, municipalityDto); String randomCode = RandomStringUtils.random(10, false, true); - pathFile = ZipUtil.zipping(new ArrayList<>(Collections.singletonList(fileFTP)), "insumo_" + randomCode, stTemporalDirectory); + pathFile = ZipUtil.zipping(new ArrayList<>(Collections.singletonList(fileFTP)), "insumo_" + randomCode, + stTemporalDirectory); } - // the supply has file to download + // the supply has a file to download else if (attachmentFtp == null && attachmentSupply != null) { pathFile = attachmentSupply.getData(); } else { // the supply has both attachments types (file and FTP) @@ -778,8 +871,8 @@ else if (attachmentFtp == null && attachmentSupply != null) { File fileSupply = new File(attachmentSupply.getData()); String randomCode = RandomStringUtils.random(10, false, true); - pathFile = ZipUtil.zipping(new ArrayList<>(Arrays.asList(fileFTP, fileSupply)), - "insumo_" + randomCode, stTemporalDirectory); + pathFile = ZipUtil.zipping(new ArrayList<>(Arrays.asList(fileFTP, fileSupply)), "insumo_" + randomCode, + stTemporalDirectory); } @@ -798,14 +891,17 @@ else if (attachmentFtp == null && attachmentSupply != null) { resource = new InputStreamResource(new FileInputStream(file)); } catch (DisconnectedMicroserviceException e) { + SCMTracing.sendError(e.getMessage()); log.error("Error WorkspaceV1Controller@downloadSupply#Microservice ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 4), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } catch (BusinessException e) { + SCMTracing.sendError(e.getMessage()); log.error("Error WorkspaceV1Controller@downloadSupply#Business ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 2), HttpStatus.UNPROCESSABLE_ENTITY); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY); } catch (Exception e) { + SCMTracing.sendError(e.getMessage()); log.error("Error WorkspaceV1Controller@downloadSupply#General ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 3), HttpStatus.INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return ResponseEntity.ok() @@ -821,30 +917,33 @@ else if (attachmentFtp == null && attachmentSupply != null) { @DeleteMapping(value = "{workspaceId}/supplies/{supplyId}") @ApiOperation(value = "Delete supply") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Supply Deleted", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Supply Deleted", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity removeSupply(@PathVariable Long workspaceId, @PathVariable Long supplyId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity removeSupplyFromMunicipality(@PathVariable Long workspaceId, @PathVariable Long supplyId, + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("removeSupplyFromMunicipality"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); workspaceBusiness.removeSupply(workspaceId, supplyId, null); - } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -852,7 +951,8 @@ public ResponseEntity removeSupply(@PathVariable Long workspaceId, @PathVaria if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para activar insumos."); } - + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); workspaceBusiness.removeSupply(workspaceId, supplyId, managerDto.getId()); } @@ -860,17 +960,20 @@ public ResponseEntity removeSupply(@PathVariable Long workspaceId, @PathVaria httpStatus = HttpStatus.NO_CONTENT; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@removeSupply#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + log.error("Error WorkspaceV1Controller@removeSupplyFromMunicipality#Microservice ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error WorkspaceV1Controller@removeSupply#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + log.error("Error WorkspaceV1Controller@removeSupplyFromMunicipality#Business ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV1Controller@removeSupply#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + log.error("Error WorkspaceV1Controller@removeSupplyFromMunicipality#General ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -878,25 +981,30 @@ public ResponseEntity removeSupply(@PathVariable Long workspaceId, @PathVaria @PostMapping(value = "{workspaceId}/operators/deliveries") @ApiOperation(value = "Create delivery") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Delivery created", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Delivery created", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity createDelivery(@PathVariable Long workspaceId, - @RequestHeader("authorization") String headerAuthorization, - @RequestBody CreateDeliveryDto createDeliveryDto) { + public ResponseEntity createDeliveryForOperator(@PathVariable Long workspaceId, + @RequestHeader("authorization") String headerAuthorization, + @RequestBody CreateDeliveryDto createDeliveryDto) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("createDeliveryForOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + SCMTracing.addCustomParameter(TracingKeyword.BODY_REQUEST, createDeliveryDto.toString()); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -904,6 +1012,8 @@ public ResponseEntity createDelivery(@PathVariable Long workspaceId, if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para actualizar el soporte."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); // validation observations String observations = createDeliveryDto.getObservations(); @@ -929,25 +1039,30 @@ public ResponseEntity createDelivery(@PathVariable Long workspaceId, throw new InputValidationException("Es necesario definir a cuál operador se le realizará la entrega."); } - responseDto = workspaceBusiness.createDelivery(workspaceId, managerDto.getId(), operatorCode, observations, supplies); + responseDto = workspaceBusiness.createDelivery(workspaceId, managerDto.getId(), operatorCode, observations, + supplies); httpStatus = HttpStatus.CREATED; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@createDelivery#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + log.error("Error WorkspaceV1Controller@createDeliveryForOperator#Microservice ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (InputValidationException e) { - log.error("Error WorkspaceV1Controller@createDelivery#Validation ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + log.error("Error WorkspaceV1Controller@createDeliveryForOperator#Validation ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.BAD_REQUEST; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error WorkspaceV1Controller@createDelivery#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + log.error("Error WorkspaceV1Controller@createDeliveryForOperator#Business ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV1Controller@createDelivery#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + log.error("Error WorkspaceV1Controller@createDeliveryForOperator#General ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -955,43 +1070,53 @@ public ResponseEntity createDelivery(@PathVariable Long workspaceId, @GetMapping(value = "operators/deliveries") @ApiOperation(value = "Get deliveries") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Get deliveries", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Get deliveries", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getSuppliesOperator(@RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity getActiveDeliveriesForOperator( + @RequestHeader("authorization") String headerAuthorization) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getActiveDeliveriesForOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get operator MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); if (operatorDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el operador."); } + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); responseDto = operatorBusiness.getDeliveriesActivesByOperator(operatorDto.getId()); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@getSuppliesOperator#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + log.error("Error WorkspaceV1Controller@getActiveDeliveriesForOperator#Microservice ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error WorkspaceV1Controller@getSuppliesOperator#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + log.error("Error WorkspaceV1Controller@getActiveDeliveriesForOperator#Business ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV1Controller@getSuppliesOperator#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + log.error("Error WorkspaceV1Controller@getActiveDeliveriesForOperator#General ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -1001,43 +1126,52 @@ public ResponseEntity getSuppliesOperator(@RequestHeader("authorization") Str @ApiOperation(value = "Get deliveries closed") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get deliveries closed", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity getDeliveriesClosed(@RequestHeader("authorization") String headerAuthorization, - @RequestParam(required = false, name = "municipality") Long municipalityId) { + public ResponseEntity getClosedDeliveriesForOperator(@RequestHeader("authorization") String headerAuthorization, + @RequestParam(required = false, name = "municipality") Long municipalityId) { HttpStatus httpStatus; Object responseDto; try { - // user session + SCMTracing.setTransactionName("getClosedDeliveriesForOperator"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get operator MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); if (operatorDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el operador."); } + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); responseDto = operatorBusiness.getDeliveriesClosedByOperator(operatorDto.getId(), municipalityId); httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { - log.error("Error WorkspaceV1Controller@getDeliveriesClosed#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 4); + log.error("Error WorkspaceV1Controller@getClosedDeliveriesForOperator#Microservice ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { - log.error("Error WorkspaceV1Controller@getDeliveriesClosed#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + log.error("Error WorkspaceV1Controller@getClosedDeliveriesForOperator#Business ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV1Controller@getDeliveriesClosed#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + log.error("Error WorkspaceV1Controller@getClosedDeliveriesForOperator#General ---> " + e.getMessage()); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -1045,54 +1179,62 @@ public ResponseEntity getDeliveriesClosed(@RequestHeader("authorization") Str @GetMapping(value = "/location") @ApiOperation(value = "Get workspaces by location") - @ApiResponses(value = { - @ApiResponse(code = 200, message = "Get workspaces", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Get workspaces", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getWorkspacesByLocation(@RequestHeader("authorization") String headerAuthorization, - @RequestParam(name = "department") Long departmentId, - @RequestParam(required = false, name = "municipality") Long municipalityId) { + @RequestParam(name = "department") Long departmentId, + @RequestParam(required = false, name = "municipality") Long municipalityId) { HttpStatus httpStatus; Object responseDto = null; try { - // user session + SCMTracing.setTransactionName("getWorkspacesByLocation"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); if (administrationBusiness.isAdministrator(userDtoSession)) { - + SCMTracing.addCustomParameter(TracingKeyword.IS_ADMIN, true); responseDto = workspaceBusiness.getWorkspacesByLocation(departmentId, municipalityId, null); } else if (administrationBusiness.isManager(userDtoSession)) { - - // get manager + SCMTracing.addCustomParameter(TracingKeyword.IS_MANAGER, true); MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); } - - responseDto = workspaceBusiness.getWorkspacesByLocation(departmentId, municipalityId, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); + responseDto = workspaceBusiness.getWorkspacesByLocation(departmentId, municipalityId, + managerDto.getId()); } httpStatus = HttpStatus.OK; } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@getWorkspacesByLocation#Microservice ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@getWorkspacesByLocation#Business ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@getWorkspacesByLocation#General ---> " + e.getMessage()); - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -1100,11 +1242,11 @@ public ResponseEntity getWorkspacesByLocation(@RequestHeader("authorization") @GetMapping(value = "/report-delivery/{deliveryId}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Download report delivery") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Download report delivery"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Download report delivery"), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody - public ResponseEntity reportDownloadDeliveryManager(@PathVariable Long deliveryId, - @RequestHeader("authorization") String headerAuthorization) { + public ResponseEntity downloadReportDeliveryAsManager(@PathVariable Long deliveryId, + @RequestHeader("authorization") String headerAuthorization) { MediaType mediaType; File file; @@ -1112,13 +1254,17 @@ public ResponseEntity reportDownloadDeliveryManager(@PathVariable Long delive try { - // user session + SCMTracing.setTransactionName("downloadReportDeliveryAsManager"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get manager MicroserviceManagerDto managerDto = managerBusiness.getManagerByUserCode(userDtoSession.getId()); if (managerDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el gestor."); @@ -1126,6 +1272,8 @@ public ResponseEntity reportDownloadDeliveryManager(@PathVariable Long delive if (!managerBusiness.userManagerIsDirector(userDtoSession.getId())) { throw new InputValidationException("El usuario no tiene permisos para crear peticiones."); } + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_ID, managerDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.MANAGER_NAME, managerDto.getName()); String pathFile = workspaceOperatorBusiness.generateReportDeliveryManager(managerDto.getId(), deliveryId); @@ -1144,14 +1292,18 @@ public ResponseEntity reportDownloadDeliveryManager(@PathVariable Long delive resource = new InputStreamResource(new FileInputStream(file)); } catch (DisconnectedMicroserviceException e) { - log.error("Error OperatorV1Controller@reportDownloadDeliveryManager#Microservice ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 4), HttpStatus.INTERNAL_SERVER_ERROR); + SCMTracing.sendError(e.getMessage()); + log.error( + "Error WorkspaceV1Controller@downloadReportDeliveryAsManager#Microservice ---> " + e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } catch (BusinessException e) { - log.error("Error OperatorV1Controller@reportDownloadDeliveryManager#Business ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 2), HttpStatus.UNPROCESSABLE_ENTITY); + SCMTracing.sendError(e.getMessage()); + log.error("Error WorkspaceV1Controller@downloadReportDeliveryAsManager#Business ---> " + e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.UNPROCESSABLE_ENTITY); } catch (Exception e) { - log.error("Error OperatorV1Controller@reportDownloadDeliveryManager#General ---> " + e.getMessage()); - return new ResponseEntity<>(new BasicResponseDto(e.getMessage(), 3), HttpStatus.INTERNAL_SERVER_ERROR); + SCMTracing.sendError(e.getMessage()); + log.error("Error WorkspaceV1Controller@downloadReportDeliveryAsManager#General ---> " + e.getMessage()); + return new ResponseEntity<>(new BasicResponseDto(e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR); } return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName()) @@ -1162,29 +1314,33 @@ public ResponseEntity reportDownloadDeliveryManager(@PathVariable Long delive @DeleteMapping(value = "/unassign/{municipalityId}/managers/{managerCode}") @ApiOperation(value = "Unassigned manager from municipality") - @ApiResponses(value = {@ApiResponse(code = 204, message = "Unassigned manager", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 204, message = "Unassigned manager", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity unassignedManagerFromMunicipality(@PathVariable Long municipalityId, - @PathVariable Long managerCode) { + @PathVariable Long managerCode) { HttpStatus httpStatus; Object responseDto; try { + SCMTracing.setTransactionName("unassignedManagerFromMunicipality"); + workspaceBusiness.unassignedManagerFromMunicipality(municipalityId, managerCode); - responseDto = new BasicResponseDto("Se ha desasignado el gestor del municipio", 7); + responseDto = new BasicResponseDto("Se ha des-asignado el gestor del municipio"); httpStatus = HttpStatus.NO_CONTENT; } catch (BusinessException e) { log.error("Error WorkspaceV1Controller@unassignManagerFromMunicipality#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@unassignManagerFromMunicipality#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -1192,8 +1348,8 @@ public ResponseEntity unassignedManagerFromMunicipality(@PathVariable Long mu @GetMapping(value = "/operators", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get workspaces by operator") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Obtained workspaces", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Obtained workspaces", response = WorkspaceDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getWorkspacesByOperator(@RequestHeader("authorization") String headerAuthorization) { @@ -1202,17 +1358,23 @@ public ResponseEntity getWorkspacesByOperator(@RequestHeader("authorization") try { - // user session + SCMTracing.setTransactionName("getWorkspacesByOperatorSession"); + SCMTracing.addCustomParameter(TracingKeyword.AUTHORIZATION_HEADER, headerAuthorization); + MicroserviceUserDto userDtoSession = administrationBusiness.getUserByToken(headerAuthorization); if (userDtoSession == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el usuario"); } + SCMTracing.addCustomParameter(TracingKeyword.USER_ID, userDtoSession.getId()); + SCMTracing.addCustomParameter(TracingKeyword.USER_EMAIL, userDtoSession.getEmail()); + SCMTracing.addCustomParameter(TracingKeyword.USER_NAME, userDtoSession.getUsername()); - // get operator MicroserviceOperatorDto operatorDto = operatorBusiness.getOperatorByUserCode(userDtoSession.getId()); if (operatorDto == null) { throw new DisconnectedMicroserviceException("Ha ocurrido un error consultando el operador."); } + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_ID, operatorDto.getId()); + SCMTracing.addCustomParameter(TracingKeyword.OPERATOR_NAME, operatorDto.getName()); responseDto = workspaceBusiness.getWorkspacesByOperator(operatorDto.getId()); httpStatus = HttpStatus.OK; @@ -1220,11 +1382,13 @@ public ResponseEntity getWorkspacesByOperator(@RequestHeader("authorization") } catch (DisconnectedMicroserviceException e) { log.error("Error WorkspaceV1Controller@getWorkspacesByOperator#Microservice ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { log.error("Error WorkspaceV1Controller@getWorkspacesByOperator#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -1232,8 +1396,8 @@ public ResponseEntity getWorkspacesByOperator(@RequestHeader("authorization") @GetMapping(value = "/operators/{operatorCode}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get workspaces by operator") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Obtained workspaces", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Obtained workspaces", response = WorkspaceDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getWorkspacesByOperator(@PathVariable Long operatorCode) { @@ -1242,13 +1406,16 @@ public ResponseEntity getWorkspacesByOperator(@PathVariable Long operatorCode try { + SCMTracing.setTransactionName("getWorkspacesByOperator"); + responseDto = workspaceBusiness.getWorkspacesByOperator(operatorCode); httpStatus = HttpStatus.OK; } catch (Exception e) { log.error("Error WorkspaceV1Controller@getWorkspacesByOperator#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -1256,24 +1423,28 @@ public ResponseEntity getWorkspacesByOperator(@PathVariable Long operatorCode @GetMapping(value = "/managers/{managerCode}/municipalities/{municipalityCode}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get workspaces by manager") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Obtained workspaces", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Obtained workspaces", response = WorkspaceDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getWorkspaceByManagerAndMunicipality(@PathVariable Long managerCode, - @PathVariable String municipalityCode) { + @PathVariable String municipalityCode) { HttpStatus httpStatus; Object responseDto; try { + SCMTracing.setTransactionName("getWorkspaceByManagerAndMunicipality"); + responseDto = workspaceBusiness.getWorkspacesByManagerAndMunicipality(managerCode, municipalityCode); httpStatus = HttpStatus.OK; } catch (Exception e) { - log.error("Error WorkspaceV1Controller@getWorkspaceByManagerAndMunicipality#General ---> " + e.getMessage()); + log.error( + "Error WorkspaceV1Controller@getWorkspaceByManagerAndMunicipality#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/MunicipalityV2Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/MunicipalityV2Controller.java index f666d63..c382a58 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/MunicipalityV2Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/MunicipalityV2Controller.java @@ -6,6 +6,7 @@ import com.ai.st.microservice.workspaces.business.MunicipalityBusiness; import com.ai.st.microservice.workspaces.dto.MunicipalityDto; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -18,7 +19,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -@Api(value = "Manage Municipalities", tags = {"Municipalities"}) +@Api(value = "Manage Municipalities", tags = { "Municipalities" }) @RestController @RequestMapping("api/workspaces/v2/municipalities") public class MunicipalityV2Controller { @@ -35,27 +36,33 @@ public MunicipalityV2Controller(MunicipalityBusiness municipalityBusiness) { @ApiOperation(value = "Get municipalities where manager does not belong in") @ApiResponses(value = { @ApiResponse(code = 200, message = "Get municipalities", response = MunicipalityDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity getMunicipalitiesWhereManagerDoesNotBelongIn(@PathVariable Long managerCode, - @PathVariable Long departmentId) { + @PathVariable Long departmentId) { HttpStatus httpStatus; Object responseDto; try { + SCMTracing.setTransactionName("getMunicipalitiesWhereManagerDoesNotBelongIn"); + responseDto = municipalityBusiness.getMunicipalitiesWhereManagerDoesNotBelong(managerCode, departmentId); httpStatus = HttpStatus.OK; } catch (BusinessException e) { - log.error("Error MunicipalityV2Controller@getMunicipalitiesWhereManagerDoesntBelongIn#Business ---> " + e.getMessage()); + log.error("Error MunicipalityV2Controller@getMunicipalitiesWhereManagerDoesntBelongIn#Business ---> " + + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error MunicipalityV2Controller@getMunicipalitiesWhereManagerDoesntBelongIn#General ---> " + e.getMessage()); + log.error("Error MunicipalityV2Controller@getMunicipalitiesWhereManagerDoesntBelongIn#General ---> " + + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); diff --git a/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/WorkspaceV2Controller.java b/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/WorkspaceV2Controller.java index 2ec8d19..44032ff 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/WorkspaceV2Controller.java +++ b/src/main/java/com/ai/st/microservice/workspaces/controllers/v2/WorkspaceV2Controller.java @@ -9,7 +9,8 @@ import com.ai.st.microservice.workspaces.dto.*; import com.ai.st.microservice.workspaces.business.ManagerMicroserviceBusiness; import com.ai.st.microservice.workspaces.business.WorkspaceBusiness; - +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; +import com.ai.st.microservice.workspaces.services.tracing.TracingKeyword; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.InputStreamResource; @@ -37,7 +38,7 @@ import javax.servlet.ServletContext; -@Api(value = "Manage Workspaces", tags = {"Workspaces"}) +@Api(value = "Manage Workspaces", tags = { "Workspaces" }) @RestController @RequestMapping("api/workspaces/v2/workspaces") public class WorkspaceV2Controller { @@ -50,7 +51,7 @@ public class WorkspaceV2Controller { private final AdministrationBusiness administrationBusiness; public WorkspaceV2Controller(WorkspaceBusiness workspaceBusiness, ManagerMicroserviceBusiness managerBusiness, - ServletContext servletContext, AdministrationBusiness administrationBusiness) { + ServletContext servletContext, AdministrationBusiness administrationBusiness) { this.workspaceBusiness = workspaceBusiness; this.managerBusiness = managerBusiness; this.servletContext = servletContext; @@ -61,7 +62,7 @@ public WorkspaceV2Controller(WorkspaceBusiness workspaceBusiness, ManagerMicrose @ApiOperation(value = "Get municipalities where manager does not belong in") @ApiResponses(value = { @ApiResponse(code = 200, message = "Municipalities validated", response = ValidationMunicipalitiesDto.class, responseContainer = "List"), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity validateMunicipalitiesBeforeAssigned( @RequestParam(name = "municipalities") List municipalities) { @@ -71,17 +72,23 @@ public ResponseEntity validateMunicipalitiesBeforeAssigned( try { + SCMTracing.setTransactionName("validateMunicipalitiesBeforeAssigned"); + responseDto = workspaceBusiness.validateMunicipalitiesToAssign(municipalities); httpStatus = HttpStatus.OK; } catch (BusinessException e) { - log.error("Error WorkspaceV2Controller@validateMunicipalitiesBeforeAssigned#Business ---> " + e.getMessage()); + log.error( + "Error WorkspaceV2Controller@validateMunicipalitiesBeforeAssigned#Business ---> " + e.getMessage()); httpStatus = HttpStatus.UNPROCESSABLE_ENTITY; - responseDto = new BasicResponseDto(e.getMessage(), 2); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } catch (Exception e) { - log.error("Error WorkspaceV2Controller@validateMunicipalitiesBeforeAssigned#General ---> " + e.getMessage()); + log.error( + "Error WorkspaceV2Controller@validateMunicipalitiesBeforeAssigned#General ---> " + e.getMessage()); httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; - responseDto = new BasicResponseDto(e.getMessage(), 3); + responseDto = new BasicResponseDto(e.getMessage()); + SCMTracing.sendError(e.getMessage()); } return new ResponseEntity<>(responseDto, httpStatus); @@ -89,11 +96,10 @@ public ResponseEntity validateMunicipalitiesBeforeAssigned( @PostMapping(value = "/assign-manager", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Assign manager") - @ApiResponses(value = {@ApiResponse(code = 201, message = "Manager assigned", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 201, message = "Manager assigned", response = WorkspaceDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity assignManager(@ModelAttribute AssignManagerDto assignManagerDto) { - HttpStatus httpStatus; Object responseDto; @@ -160,11 +166,11 @@ public ResponseEntity assignManager(@ModelAttribute AssignManagerDto ass @GetMapping(value = "{workspaceId}/download-support-manager/{managerCode}") @ApiOperation(value = "Download file") - @ApiResponses(value = {@ApiResponse(code = 200, message = "File downloaded", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "File downloaded", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity downloadSupportManager(@PathVariable Long workspaceId, @PathVariable Long managerCode, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { MediaType mediaType; File file; @@ -229,8 +235,8 @@ public ResponseEntity downloadSupportManager(@PathVariable Long workspaceId, @PutMapping(value = "/{workspaceId}/managers/{managerCode}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Update manager from workspace") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Manager updated", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Manager updated", response = WorkspaceDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity updateManagerFromWorkspace( @RequestBody UpdateManagerFromWorkspaceDto requestUpdateWorkspace, @PathVariable Long workspaceId, @@ -284,8 +290,8 @@ public ResponseEntity updateManagerFromWorkspace( @PutMapping(value = "/{workspaceId}/operators/{operatorCode}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Update operator from workspace") - @ApiResponses(value = {@ApiResponse(code = 200, message = "Operator updated", response = WorkspaceDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Operator updated", response = WorkspaceDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity updateOperatorFromWorkspace( @ModelAttribute UpdateOperatorFromWorkspaceDto updateOperatorWorkspace, @PathVariable Long workspaceId, @@ -361,8 +367,9 @@ public ResponseEntity updateOperatorFromWorkspace( } } - responseDto = workspaceBusiness.updateOperatorFromWorkspace(workspaceId, managerDto.getId(), operatorCode, startDate, endDate, - observations, parcelsNumber, workArea, updateOperatorWorkspace.getSupportFile()); + responseDto = workspaceBusiness.updateOperatorFromWorkspace(workspaceId, managerDto.getId(), operatorCode, + startDate, endDate, observations, parcelsNumber, workArea, + updateOperatorWorkspace.getSupportFile()); httpStatus = HttpStatus.OK; } catch (InputValidationException e) { @@ -384,11 +391,11 @@ public ResponseEntity updateOperatorFromWorkspace( @GetMapping(value = "{workspaceId}/download-support-operator/{operatorCode}") @ApiOperation(value = "Download file") - @ApiResponses(value = {@ApiResponse(code = 200, message = "File downloaded", response = BasicResponseDto.class), - @ApiResponse(code = 500, message = "Error Server", response = String.class)}) + @ApiResponses(value = { @ApiResponse(code = 200, message = "File downloaded", response = BasicResponseDto.class), + @ApiResponse(code = 500, message = "Error Server", response = String.class) }) @ResponseBody public ResponseEntity downloadSupportOperator(@PathVariable Long workspaceId, @PathVariable Long operatorCode, - @RequestHeader("authorization") String headerAuthorization) { + @RequestHeader("authorization") String headerAuthorization) { MediaType mediaType; File file; diff --git a/src/main/java/com/ai/st/microservice/workspaces/drivers/PostgresDriver.java b/src/main/java/com/ai/st/microservice/workspaces/drivers/PostgresDriver.java index a81d8bc..7d1a9e1 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/drivers/PostgresDriver.java +++ b/src/main/java/com/ai/st/microservice/workspaces/drivers/PostgresDriver.java @@ -11,104 +11,104 @@ public class PostgresDriver { - private Connection c = null; - private Statement stmt = null; + private Connection c = null; + private Statement stmt = null; - public ResultSet query(String sql) { - ResultSet response = null; - try { - this.stmt = this.c.createStatement(); - response = this.stmt.executeQuery(sql); - response.next(); - return response; - } catch (SQLException ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - } - return response; - } + public ResultSet query(String sql) { + ResultSet response = null; + try { + this.stmt = this.c.createStatement(); + response = this.stmt.executeQuery(sql); + response.next(); + return response; + } catch (SQLException ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + } + return response; + } - public String queryToString(String sql) { - String response = ""; - try { - this.stmt = this.c.createStatement(); - ResultSet rs = stmt.executeQuery(sql); - rs.next(); - response = rs.getString(1); - stmt.close(); - c.commit(); - return response; - } catch (SQLException ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - } - return response; - } + public String queryToString(String sql) { + String response = ""; + try { + this.stmt = this.c.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + rs.next(); + response = rs.getString(1); + stmt.close(); + c.commit(); + return response; + } catch (SQLException ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + } + return response; + } - public boolean connect(String connectionString, String connectionUser, String connectionPassword, - String classForName) { - this.disconnect(); - try { - Class.forName(classForName); - c = DriverManager.getConnection(connectionString, connectionUser, connectionPassword); - c.setAutoCommit(false); - return true; - } catch (Exception ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - this.disconnect(); - } - return false; - } + public boolean connect(String connectionString, String connectionUser, String connectionPassword, + String classForName) { + this.disconnect(); + try { + Class.forName(classForName); + c = DriverManager.getConnection(connectionString, connectionUser, connectionPassword); + c.setAutoCommit(false); + return true; + } catch (Exception ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + this.disconnect(); + } + return false; + } - public void disconnect() { - if (this.c != null) { - try { - this.stmt.close(); - this.c.close(); - } catch (SQLException ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - } - } - this.c = null; - } + public void disconnect() { + if (this.c != null) { + try { + this.stmt.close(); + this.c.close(); + } catch (SQLException ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + } + } + this.c = null; + } - public ResultSet getResultSetFromSql(String sql) { - ResultSet response = null; - try { - this.stmt = this.c.createStatement(); - response = this.stmt.executeQuery(sql); - return response; - } catch (SQLException ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - } - return response; - } + public ResultSet getResultSetFromSql(String sql) { + ResultSet response = null; + try { + this.stmt = this.c.createStatement(); + response = this.stmt.executeQuery(sql); + return response; + } catch (SQLException ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + } + return response; + } - public long insert(String sql) { - try { - PreparedStatement pstmt = this.c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); - long affectedRows = pstmt.executeUpdate(); - c.commit(); - return affectedRows; - } catch (SQLException ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - } - return 0; - } + public long insert(String sql) { + try { + PreparedStatement pstmt = this.c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); + long affectedRows = pstmt.executeUpdate(); + c.commit(); + return affectedRows; + } catch (SQLException ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + } + return 0; + } - public long count(String sql) { + public long count(String sql) { - long count = 0; + long count = 0; - try { + try { - this.stmt = this.c.createStatement(); - ResultSet rs = stmt.executeQuery(sql); - rs.next(); - count = rs.getInt(1); - } catch (SQLException ex) { - Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); - } + this.stmt = this.c.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + rs.next(); + count = rs.getInt(1); + } catch (SQLException ex) { + Logger.getLogger(PostgresDriver.class.getName()).log(Level.SEVERE, null, ex); + } - return count; - } + return count; + } } \ No newline at end of file diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/AddProfileToUserDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/AddProfileToUserDto.java index 0584a41..92a14bf 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/AddProfileToUserDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/AddProfileToUserDto.java @@ -8,21 +8,25 @@ @ApiModel(value = "AddProfileToUserDto", description = "Add Profile To User Dto") public class AddProfileToUserDto implements Serializable { - private static final long serialVersionUID = 9169071345697135149L; + private static final long serialVersionUID = 9169071345697135149L; - @ApiModelProperty(required = true, notes = "Profile ID") - private Long profileId; + @ApiModelProperty(required = true, notes = "Profile ID") + private Long profileId; - public AddProfileToUserDto() { + public AddProfileToUserDto() { - } + } - public Long getProfileId() { - return profileId; - } + public Long getProfileId() { + return profileId; + } - public void setProfileId(Long profileId) { - this.profileId = profileId; - } + public void setProfileId(Long profileId) { + this.profileId = profileId; + } + @Override + public String toString() { + return "AddProfileToUserDto{" + "profileId=" + profileId + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/AnswerRequestDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/AnswerRequestDto.java index 99f1be6..1acf43c 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/AnswerRequestDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/AnswerRequestDto.java @@ -68,4 +68,11 @@ public Boolean getSkipErrors() { public void setSkipErrors(Boolean skipErrors) { this.skipErrors = skipErrors; } + + @Override + public String toString() { + return "AnswerRequestDto{" + "typeSupplyId=" + typeSupplyId + ", justification='" + justification + '\'' + + ", url='" + url + '\'' + ", observations='" + observations + '\'' + ", skipErrors=" + skipErrors + + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/AssignManagerDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/AssignManagerDto.java index 01e04e3..afa09bb 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/AssignManagerDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/AssignManagerDto.java @@ -12,64 +12,64 @@ @ApiModel(value = "AssignManagerDto") public class AssignManagerDto implements Serializable { - private static final long serialVersionUID = 678643285561859459L; + private static final long serialVersionUID = 678643285561859459L; - @ApiModelProperty(required = true, notes = "Start date") - private String startDate; + @ApiModelProperty(required = true, notes = "Start date") + private String startDate; - @ApiModelProperty(required = true, notes = "Manager Code") - private Long managerCode; + @ApiModelProperty(required = true, notes = "Manager Code") + private Long managerCode; - @ApiModelProperty(required = true, notes = "Observations") - private String observations; + @ApiModelProperty(required = true, notes = "Observations") + private String observations; - @ApiModelProperty(required = true, notes = "Support file") - private MultipartFile supportFile; + @ApiModelProperty(required = true, notes = "Support file") + private MultipartFile supportFile; - private List municipalities; + private List municipalities; - public AssignManagerDto() { - this.municipalities = new ArrayList(); - } + public AssignManagerDto() { + this.municipalities = new ArrayList(); + } - public String getStartDate() { - return startDate; - } + public String getStartDate() { + return startDate; + } - public void setStartDate(String startDate) { - this.startDate = startDate; - } + public void setStartDate(String startDate) { + this.startDate = startDate; + } - public Long getManagerCode() { - return managerCode; - } + public Long getManagerCode() { + return managerCode; + } - public void setManagerCode(Long managerCode) { - this.managerCode = managerCode; - } + public void setManagerCode(Long managerCode) { + this.managerCode = managerCode; + } - public String getObservations() { - return observations; - } + public String getObservations() { + return observations; + } - public void setObservations(String observations) { - this.observations = observations; - } + public void setObservations(String observations) { + this.observations = observations; + } - public MultipartFile getSupportFile() { - return supportFile; - } + public MultipartFile getSupportFile() { + return supportFile; + } - public void setSupportFile(MultipartFile supportFile) { - this.supportFile = supportFile; - } + public void setSupportFile(MultipartFile supportFile) { + this.supportFile = supportFile; + } - public List getMunicipalities() { - return municipalities; - } + public List getMunicipalities() { + return municipalities; + } - public void setMunicipalities(List municipalities) { - this.municipalities = municipalities; - } + public void setMunicipalities(List municipalities) { + this.municipalities = municipalities; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/AssignOperatorWorkpaceDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/AssignOperatorWorkpaceDto.java deleted file mode 100644 index d7440e6..0000000 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/AssignOperatorWorkpaceDto.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.ai.st.microservice.workspaces.dto; - -import java.io.Serializable; - -import org.springframework.web.multipart.MultipartFile; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -@ApiModel(value = "AssignOperatorWorkpaceDto") -public class AssignOperatorWorkpaceDto implements Serializable { - - private static final long serialVersionUID = -4217826518362864745L; - - @ApiModelProperty(required = true, notes = "Start date") - private String startDate; - - @ApiModelProperty(required = true, notes = "End date") - private String endDate; - - @ApiModelProperty(required = true, notes = "Operator Code") - private Long operatorCode; - - @ApiModelProperty(required = false, notes = "Observations") - private String observations; - - @ApiModelProperty(required = true, notes = "Support file") - private MultipartFile supportFile; - - @ApiModelProperty(required = false, notes = "Number parcels expected") - private Long numberParcelsExpected; - - @ApiModelProperty(required = false, notes = "Work area") - private Double workArea; - - public AssignOperatorWorkpaceDto() { - - } - - public String getStartDate() { - return startDate; - } - - public void setStartDate(String startDate) { - this.startDate = startDate; - } - - public String getEndDate() { - return endDate; - } - - public void setEndDate(String endDate) { - this.endDate = endDate; - } - - public Long getOperatorCode() { - return operatorCode; - } - - public void setOperatorCode(Long operatorCode) { - this.operatorCode = operatorCode; - } - - public MultipartFile getSupportFile() { - return supportFile; - } - - public void setSupportFile(MultipartFile supportFile) { - this.supportFile = supportFile; - } - - public String getObservations() { - return observations; - } - - public void setObservations(String observations) { - this.observations = observations; - } - - public Long getNumberParcelsExpected() { - return numberParcelsExpected; - } - - public void setNumberParcelsExpected(Long numberParcelsExpected) { - this.numberParcelsExpected = numberParcelsExpected; - } - - public Double getWorkArea() { - return workArea; - } - - public void setWorkArea(Double workArea) { - this.workArea = workArea; - } - -} diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/AssignOperatorWorkspaceDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/AssignOperatorWorkspaceDto.java new file mode 100644 index 0000000..40fcaf5 --- /dev/null +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/AssignOperatorWorkspaceDto.java @@ -0,0 +1,102 @@ +package com.ai.st.microservice.workspaces.dto; + +import java.io.Serializable; + +import org.springframework.web.multipart.MultipartFile; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "AssignOperatorWorkspaceDto") +public class AssignOperatorWorkspaceDto implements Serializable { + + private static final long serialVersionUID = -4217826518362864745L; + + @ApiModelProperty(required = true, notes = "Start date") + private String startDate; + + @ApiModelProperty(required = true, notes = "End date") + private String endDate; + + @ApiModelProperty(required = true, notes = "Operator Code") + private Long operatorCode; + + @ApiModelProperty(required = false, notes = "Observations") + private String observations; + + @ApiModelProperty(required = true, notes = "Support file") + private MultipartFile supportFile; + + @ApiModelProperty(required = false, notes = "Number parcels expected") + private Long numberParcelsExpected; + + @ApiModelProperty(required = false, notes = "Work area") + private Double workArea; + + public AssignOperatorWorkspaceDto() { + + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getEndDate() { + return endDate; + } + + public void setEndDate(String endDate) { + this.endDate = endDate; + } + + public Long getOperatorCode() { + return operatorCode; + } + + public void setOperatorCode(Long operatorCode) { + this.operatorCode = operatorCode; + } + + public MultipartFile getSupportFile() { + return supportFile; + } + + public void setSupportFile(MultipartFile supportFile) { + this.supportFile = supportFile; + } + + public String getObservations() { + return observations; + } + + public void setObservations(String observations) { + this.observations = observations; + } + + public Long getNumberParcelsExpected() { + return numberParcelsExpected; + } + + public void setNumberParcelsExpected(Long numberParcelsExpected) { + this.numberParcelsExpected = numberParcelsExpected; + } + + public Double getWorkArea() { + return workArea; + } + + public void setWorkArea(Double workArea) { + this.workArea = workArea; + } + + @Override + public String toString() { + return "AssignOperatorWorkspaceDto{" + "startDate='" + startDate + '\'' + ", endDate='" + endDate + '\'' + + ", operatorCode=" + operatorCode + ", observations='" + observations + '\'' + + ", numberParcelsExpected=" + numberParcelsExpected + ", workArea=" + workArea + '}'; + } +} diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CancelTaskDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CancelTaskDto.java index b5689e4..baa0247 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CancelTaskDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CancelTaskDto.java @@ -4,20 +4,20 @@ public class CancelTaskDto implements Serializable { - private static final long serialVersionUID = -3519926277652676501L; + private static final long serialVersionUID = -3519926277652676501L; - private String reason; + private String reason; - public CancelTaskDto() { + public CancelTaskDto() { - } + } - public String getReason() { - return reason; - } + public String getReason() { + return reason; + } - public void setReason(String reason) { - this.reason = reason; - } + public void setReason(String reason) { + this.reason = reason; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/ChangePasswordDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/ChangePasswordDto.java index a4a570b..1adae70 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/ChangePasswordDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/ChangePasswordDto.java @@ -8,21 +8,21 @@ @ApiModel(value = "ChangePasswordDto", description = "Change Password Dto") public class ChangePasswordDto implements Serializable { - private static final long serialVersionUID = -2819572836734055387L; + private static final long serialVersionUID = -2819572836734055387L; - @ApiModelProperty(required = true, notes = "Password") - private String password; + @ApiModelProperty(required = true, notes = "Password") + private String password; - public ChangePasswordDto() { + public ChangePasswordDto() { - } + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateDeliveryDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateDeliveryDto.java index 17aaa8f..1c95508 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateDeliveryDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateDeliveryDto.java @@ -48,4 +48,10 @@ public Long getOperatorCode() { public void setOperatorCode(Long operatorCode) { this.operatorCode = operatorCode; } + + @Override + public String toString() { + return "CreateDeliveryDto{" + "observations='" + observations + '\'' + ", operatorCode=" + operatorCode + + ", supplies=" + supplies + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreatePetitionDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreatePetitionDto.java index 528f6c5..bc84025 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreatePetitionDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreatePetitionDto.java @@ -8,32 +8,36 @@ @ApiModel(value = "CreatePetitionDto") public class CreatePetitionDto implements Serializable { - private static final long serialVersionUID = -4366303440135678188L; - - @ApiModelProperty(required = true, notes = "Provider ID") - private Long providerId; - - @ApiModelProperty(required = true, notes = "Description") - private String description; - - public CreatePetitionDto() { - - } - - public Long getProviderId() { - return providerId; - } - - public void setProviderId(Long providerId) { - this.providerId = providerId; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } + private static final long serialVersionUID = -4366303440135678188L; + @ApiModelProperty(required = true, notes = "Provider ID") + private Long providerId; + + @ApiModelProperty(required = true, notes = "Description") + private String description; + + public CreatePetitionDto() { + + } + + public Long getProviderId() { + return providerId; + } + + public void setProviderId(Long providerId) { + this.providerId = providerId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "CreatePetitionDto{" + "providerId=" + providerId + ", description='" + description + '\'' + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateProviderProfileDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateProviderProfileDto.java index ac20a6d..b4ac0c5 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateProviderProfileDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateProviderProfileDto.java @@ -8,32 +8,36 @@ @ApiModel(value = "CreateProviderProfileDto", description = "Create Provider Profile Dto") public class CreateProviderProfileDto implements Serializable { - private static final long serialVersionUID = -7565386071265746501L; + private static final long serialVersionUID = -7565386071265746501L; - @ApiModelProperty(required = true, notes = "Name") - private String name; + @ApiModelProperty(required = true, notes = "Name") + private String name; - @ApiModelProperty(required = true, notes = "Description") - private String description; + @ApiModelProperty(required = true, notes = "Description") + private String description; - public CreateProviderProfileDto() { + public CreateProviderProfileDto() { - } + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } + @Override + public String toString() { + return "CreateProviderProfileDto{" + "name='" + name + '\'' + ", description='" + description + '\'' + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateRequestDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateRequestDto.java index eca9953..ea7bb92 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateRequestDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateRequestDto.java @@ -10,32 +10,36 @@ @ApiModel(value = "CreateRequestDto", description = "Create Request Dto") public class CreateRequestDto implements Serializable { - private static final long serialVersionUID = 1848871808401415553L; + private static final long serialVersionUID = 1848871808401415553L; - @ApiModelProperty(required = true, notes = "Deadline") - private String deadline; + @ApiModelProperty(required = true, notes = "Deadline") + private String deadline; - @ApiModelProperty(required = true, notes = "Supplies requested") - private List supplies; + @ApiModelProperty(required = true, notes = "Supplies requested") + private List supplies; - public CreateRequestDto() { - supplies = new ArrayList(); - } + public CreateRequestDto() { + supplies = new ArrayList(); + } - public String getDeadline() { - return deadline; - } + public String getDeadline() { + return deadline; + } - public void setDeadline(String deadline) { - this.deadline = deadline; - } + public void setDeadline(String deadline) { + this.deadline = deadline; + } - public List getSupplies() { - return supplies; - } + public List getSupplies() { + return supplies; + } - public void setSupplies(List supplies) { - this.supplies = supplies; - } + public void setSupplies(List supplies) { + this.supplies = supplies; + } + @Override + public String toString() { + return "CreateRequestDto{" + "deadline='" + deadline + '\'' + ", supplies=" + supplies + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyCadastralAuthorityDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyCadastralAuthorityDto.java index a0a3dfb..75fbd5a 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyCadastralAuthorityDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyCadastralAuthorityDto.java @@ -13,7 +13,7 @@ public class CreateSupplyCadastralAuthorityDto implements Serializable { @ApiModelProperty(required = true, notes = "Attachment Type ID") private Long attachmentTypeId; - @ApiModelProperty(required = false, notes = "FTP") + @ApiModelProperty(notes = "FTP") private String ftp; @ApiModelProperty(required = true, notes = "Observations") @@ -68,4 +68,11 @@ public Long getManagerCode() { public void setManagerCode(Long managerCode) { this.managerCode = managerCode; } + + @Override + public String toString() { + return "CreateSupplyCadastralAuthorityDto{" + "attachmentTypeId=" + attachmentTypeId + ", ftp='" + ftp + '\'' + + ", observations='" + observations + '\'' + ", name='" + name + '\'' + ", managerCode=" + managerCode + + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyDeliveryDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyDeliveryDto.java index 941bb70..608f9b8 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyDeliveryDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateSupplyDeliveryDto.java @@ -36,4 +36,8 @@ public void setSupplyId(Long supplyId) { this.supplyId = supplyId; } + @Override + public String toString() { + return "CreateSupplyDeliveryDto{" + "observations='" + observations + '\'' + ", supplyId=" + supplyId + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateTypeSupplyDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateTypeSupplyDto.java index 12762b1..fa6e10e 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateTypeSupplyDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateTypeSupplyDto.java @@ -10,76 +10,82 @@ @ApiModel(value = "CreateTypeSupplyDto", description = "Create Type Supply Dto") public class CreateTypeSupplyDto implements Serializable { - private static final long serialVersionUID = 6515735489433109152L; + private static final long serialVersionUID = 6515735489433109152L; - @ApiModelProperty(required = true, notes = "Description") - private String description; + @ApiModelProperty(required = true, notes = "Description") + private String description; - @ApiModelProperty(required = true, notes = "Metadata is required ?") - private Boolean metadataRequired; + @ApiModelProperty(required = true, notes = "Metadata is required ?") + private Boolean metadataRequired; - @ApiModelProperty(required = true, notes = "Model is required ?") - private Boolean modelRequired; + @ApiModelProperty(required = true, notes = "Model is required ?") + private Boolean modelRequired; - @ApiModelProperty(required = true, notes = "Type supply name") - private String name; + @ApiModelProperty(required = true, notes = "Type supply name") + private String name; - @ApiModelProperty(required = true, notes = "Provider profile") - private Long providerProfileId; + @ApiModelProperty(required = true, notes = "Provider profile") + private Long providerProfileId; - @ApiModelProperty(required = true, notes = "Provider profile") - private List extensions; + @ApiModelProperty(required = true, notes = "Provider profile") + private List extensions; - public List getExtensions() { - return extensions; - } + public List getExtensions() { + return extensions; + } - public void setExtensions(List extensions) { - this.extensions = extensions; - } + public void setExtensions(List extensions) { + this.extensions = extensions; + } - public Boolean getModelRequired() { - return modelRequired; - } + public Boolean getModelRequired() { + return modelRequired; + } - public void setModelRequired(Boolean modelRequired) { - this.modelRequired = modelRequired; - } + public void setModelRequired(Boolean modelRequired) { + this.modelRequired = modelRequired; + } - public CreateTypeSupplyDto() { - this.extensions = new ArrayList<>(); - } + public CreateTypeSupplyDto() { + this.extensions = new ArrayList<>(); + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public Long getProviderProfileId() { - return providerProfileId; - } + public Long getProviderProfileId() { + return providerProfileId; + } - public void setProviderProfileId(Long providerProfileId) { - this.providerProfileId = providerProfileId; - } + public void setProviderProfileId(Long providerProfileId) { + this.providerProfileId = providerProfileId; + } - public Boolean getMetadataRequired() { - return metadataRequired; - } + public Boolean getMetadataRequired() { + return metadataRequired; + } - public void setMetadataRequired(Boolean metadataRequired) { - this.metadataRequired = metadataRequired; - } + public void setMetadataRequired(Boolean metadataRequired) { + this.metadataRequired = metadataRequired; + } + @Override + public String toString() { + return "CreateTypeSupplyDto{" + "description='" + description + '\'' + ", metadataRequired=" + metadataRequired + + ", modelRequired=" + modelRequired + ", name='" + name + '\'' + ", providerProfileId=" + + providerProfileId + ", extensions=" + extensions + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserDto.java index 5f58d0b..a5d9331 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserDto.java @@ -8,109 +8,116 @@ @ApiModel(value = "CreateUserDto", description = "Create User Dto") public class CreateUserDto implements Serializable { - private static final long serialVersionUID = -2041172889834251468L; + private static final long serialVersionUID = -2041172889834251468L; - @ApiModelProperty(required = true, notes = "First name") - private String firstName; + @ApiModelProperty(required = true, notes = "First name") + private String firstName; - @ApiModelProperty(required = true, notes = "Last name") - private String lastName; + @ApiModelProperty(required = true, notes = "Last name") + private String lastName; - @ApiModelProperty(required = true, notes = "Username") - private String username; + @ApiModelProperty(required = true, notes = "Username") + private String username; - @ApiModelProperty(required = true, notes = "Email") - private String email; + @ApiModelProperty(required = true, notes = "Email") + private String email; - @ApiModelProperty(required = true, notes = "Password") - private String password; + @ApiModelProperty(required = true, notes = "Password") + private String password; - @ApiModelProperty(notes = "Role Provider Supply") - private CreateUserRoleProviderDto roleProvider; + @ApiModelProperty(notes = "Role Provider Supply") + private CreateUserRoleProviderDto roleProvider; - @ApiModelProperty(notes = "Role Administrator") - private CreateUserRoleAdministratorDto roleAdministrator; + @ApiModelProperty(notes = "Role Administrator") + private CreateUserRoleAdministratorDto roleAdministrator; - @ApiModelProperty(notes = "Role Manager") - private CreateUserRoleManagerDto roleManager; + @ApiModelProperty(notes = "Role Manager") + private CreateUserRoleManagerDto roleManager; - @ApiModelProperty(notes = "Operator Manager") - private CreateUserRoleOperatorDto roleOperator; + @ApiModelProperty(notes = "Operator Manager") + private CreateUserRoleOperatorDto roleOperator; - public CreateUserDto() { + public CreateUserDto() { - } + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getEmail() { - return email; - } + public String getEmail() { + return email; + } - public void setEmail(String email) { - this.email = email; - } + public void setEmail(String email) { + this.email = email; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - public CreateUserRoleProviderDto getRoleProvider() { - return roleProvider; - } + public CreateUserRoleProviderDto getRoleProvider() { + return roleProvider; + } - public void setRoleProvider(CreateUserRoleProviderDto roleProvider) { - this.roleProvider = roleProvider; - } + public void setRoleProvider(CreateUserRoleProviderDto roleProvider) { + this.roleProvider = roleProvider; + } - public CreateUserRoleAdministratorDto getRoleAdministrator() { - return roleAdministrator; - } + public CreateUserRoleAdministratorDto getRoleAdministrator() { + return roleAdministrator; + } - public void setRoleAdministrator(CreateUserRoleAdministratorDto roleAdministrator) { - this.roleAdministrator = roleAdministrator; - } + public void setRoleAdministrator(CreateUserRoleAdministratorDto roleAdministrator) { + this.roleAdministrator = roleAdministrator; + } - public CreateUserRoleManagerDto getRoleManager() { - return roleManager; - } + public CreateUserRoleManagerDto getRoleManager() { + return roleManager; + } - public void setRoleManager(CreateUserRoleManagerDto roleManager) { - this.roleManager = roleManager; - } + public void setRoleManager(CreateUserRoleManagerDto roleManager) { + this.roleManager = roleManager; + } - public CreateUserRoleOperatorDto getRoleOperator() { - return roleOperator; - } + public CreateUserRoleOperatorDto getRoleOperator() { + return roleOperator; + } - public void setRoleOperator(CreateUserRoleOperatorDto roleOperator) { - this.roleOperator = roleOperator; - } + public void setRoleOperator(CreateUserRoleOperatorDto roleOperator) { + this.roleOperator = roleOperator; + } + @Override + public String toString() { + return "CreateUserDto{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", username='" + + username + '\'' + ", email='" + email + '\'' + ", roleProvider=" + roleProvider + + ", roleAdministrator=" + roleAdministrator + ", roleManager=" + roleManager + ", roleOperator=" + + roleOperator + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleAdministratorDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleAdministratorDto.java index cb47573..184d5e3 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleAdministratorDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleAdministratorDto.java @@ -8,21 +8,25 @@ @ApiModel(value = "CreateUserRoleAdministratorDto", description = "Create User Role Administrator Dto") public class CreateUserRoleAdministratorDto implements Serializable { - private static final long serialVersionUID = -6386496439475467133L; + private static final long serialVersionUID = -6386496439475467133L; - @ApiModelProperty(required = true, notes = "Role ID") - private Long roleId; + @ApiModelProperty(required = true, notes = "Role ID") + private Long roleId; - public CreateUserRoleAdministratorDto() { + public CreateUserRoleAdministratorDto() { - } + } - public Long getRoleId() { - return roleId; - } + public Long getRoleId() { + return roleId; + } - public void setRoleId(Long roleId) { - this.roleId = roleId; - } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + @Override + public String toString() { + return "CreateUserRoleAdministratorDto{" + "roleId=" + roleId + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleManagerDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleManagerDto.java index 1622934..0aaf15e 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleManagerDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleManagerDto.java @@ -10,62 +10,67 @@ @ApiModel(value = "CreateUserRoleManagerDto", description = "Create User Role Manager Dto") public class CreateUserRoleManagerDto implements Serializable { - private static final long serialVersionUID = 4040750533290642970L; + private static final long serialVersionUID = 4040750533290642970L; - @ApiModelProperty(required = true, notes = "Role ID") - private Long roleId; + @ApiModelProperty(required = true, notes = "Role ID") + private Long roleId; - @ApiModelProperty(required = true, notes = "Manager ID") - private Long managerId; + @ApiModelProperty(required = true, notes = "Manager ID") + private Long managerId; - @ApiModelProperty(required = true, notes = "Profiles ID") - private List profiles; - - private Boolean isManager; - private Boolean isDirector; + @ApiModelProperty(required = true, notes = "Profiles ID") + private List profiles; - public CreateUserRoleManagerDto() { - this.profiles = new ArrayList(); - } + private Boolean isManager; + private Boolean isDirector; - public Long getRoleId() { - return roleId; - } + public CreateUserRoleManagerDto() { + this.profiles = new ArrayList(); + } - public void setRoleId(Long roleId) { - this.roleId = roleId; - } + public Long getRoleId() { + return roleId; + } - public Long getManagerId() { - return managerId; - } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } - public void setManagerId(Long managerId) { - this.managerId = managerId; - } + public Long getManagerId() { + return managerId; + } - public List getProfiles() { - return profiles; - } + public void setManagerId(Long managerId) { + this.managerId = managerId; + } - public void setProfiles(List profiles) { - this.profiles = profiles; - } + public List getProfiles() { + return profiles; + } - public Boolean getIsManager() { - return isManager; - } + public void setProfiles(List profiles) { + this.profiles = profiles; + } - public void setIsManager(Boolean isManager) { - this.isManager = isManager; - } + public Boolean getIsManager() { + return isManager; + } - public Boolean getIsDirector() { - return isDirector; - } + public void setIsManager(Boolean isManager) { + this.isManager = isManager; + } - public void setIsDirector(Boolean isDirector) { - this.isDirector = isDirector; - } + public Boolean getIsDirector() { + return isDirector; + } + public void setIsDirector(Boolean isDirector) { + this.isDirector = isDirector; + } + + @Override + public String toString() { + return "CreateUserRoleManagerDto{" + "roleId=" + roleId + ", managerId=" + managerId + ", profiles=" + profiles + + ", isManager=" + isManager + ", isDirector=" + isDirector + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleOperatorDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleOperatorDto.java index 36a48de..1378e24 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleOperatorDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleOperatorDto.java @@ -8,32 +8,36 @@ @ApiModel(value = "CreateUserRoleOperatorDto", description = "Create User Role Operator Dto") public class CreateUserRoleOperatorDto implements Serializable { - private static final long serialVersionUID = -8970830341208681180L; + private static final long serialVersionUID = -8970830341208681180L; - @ApiModelProperty(required = true, notes = "Role ID") - private Long roleId; + @ApiModelProperty(required = true, notes = "Role ID") + private Long roleId; - @ApiModelProperty(required = true, notes = "Operator ID") - private Long operatorId; + @ApiModelProperty(required = true, notes = "Operator ID") + private Long operatorId; - public CreateUserRoleOperatorDto() { + public CreateUserRoleOperatorDto() { - } + } - public Long getRoleId() { - return roleId; - } + public Long getRoleId() { + return roleId; + } - public void setRoleId(Long roleId) { - this.roleId = roleId; - } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } - public Long getOperatorId() { - return operatorId; - } + public Long getOperatorId() { + return operatorId; + } - public void setOperatorId(Long operatorId) { - this.operatorId = operatorId; - } + public void setOperatorId(Long operatorId) { + this.operatorId = operatorId; + } + @Override + public String toString() { + return "CreateUserRoleOperatorDto{" + "roleId=" + roleId + ", operatorId=" + operatorId + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleProviderDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleProviderDto.java index 607f2b3..a3dbdd0 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleProviderDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/CreateUserRoleProviderDto.java @@ -10,65 +10,70 @@ @ApiModel(value = "CreateUserRoleProviderDto", description = "Create User Role Provider Dto") public class CreateUserRoleProviderDto implements Serializable { - private static final long serialVersionUID = -6386496439475467133L; + private static final long serialVersionUID = -6386496439475467133L; - @ApiModelProperty(required = true, notes = "Role ID") - private Long roleId; + @ApiModelProperty(required = true, notes = "Role ID") + private Long roleId; - @ApiModelProperty(required = true, notes = "Provider ID") - private Long providerId; + @ApiModelProperty(required = true, notes = "Provider ID") + private Long providerId; - @ApiModelProperty(required = true, notes = "Profiles ID") - private List profiles; + @ApiModelProperty(required = true, notes = "Profiles ID") + private List profiles; - @ApiModelProperty(required = true, notes = "Is technical?") - private Boolean isTechnical; + @ApiModelProperty(required = true, notes = "Is technical?") + private Boolean isTechnical; - private Boolean fromAdministrator; + private Boolean fromAdministrator; - public CreateUserRoleProviderDto() { - this.profiles = new ArrayList(); - this.isTechnical = false; - } + public CreateUserRoleProviderDto() { + this.profiles = new ArrayList(); + this.isTechnical = false; + } - public Long getRoleId() { - return roleId; - } + public Long getRoleId() { + return roleId; + } - public void setRoleId(Long roleId) { - this.roleId = roleId; - } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } - public Long getProviderId() { - return providerId; - } + public Long getProviderId() { + return providerId; + } - public void setProviderId(Long providerId) { - this.providerId = providerId; - } + public void setProviderId(Long providerId) { + this.providerId = providerId; + } - public List getProfiles() { - return profiles; - } + public List getProfiles() { + return profiles; + } - public void setProfiles(List profiles) { - this.profiles = profiles; - } + public void setProfiles(List profiles) { + this.profiles = profiles; + } - public Boolean getFromAdministrator() { - return fromAdministrator; - } + public Boolean getFromAdministrator() { + return fromAdministrator; + } - public void setFromAdministrator(Boolean fromAdministrator) { - this.fromAdministrator = fromAdministrator; - } + public void setFromAdministrator(Boolean fromAdministrator) { + this.fromAdministrator = fromAdministrator; + } - public Boolean getIsTechnical() { - return isTechnical; - } + public Boolean getIsTechnical() { + return isTechnical; + } - public void setIsTechnical(Boolean isTechnical) { - this.isTechnical = isTechnical; - } + public void setIsTechnical(Boolean isTechnical) { + this.isTechnical = isTechnical; + } + @Override + public String toString() { + return "CreateUserRoleProviderDto{" + "roleId=" + roleId + ", providerId=" + providerId + ", profiles=" + + profiles + ", isTechnical=" + isTechnical + ", fromAdministrator=" + fromAdministrator + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/DepartmentDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/DepartmentDto.java index 8498f69..e7eb9b1 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/DepartmentDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/DepartmentDto.java @@ -8,50 +8,50 @@ @ApiModel(value = "DepartmentDto", description = "Department Dto") public class DepartmentDto implements Serializable { - private static final long serialVersionUID = -4872570330522596800L; + private static final long serialVersionUID = -4872570330522596800L; - @ApiModelProperty(required = true, notes = "Department ID") - private Long id; + @ApiModelProperty(required = true, notes = "Department ID") + private Long id; - @ApiModelProperty(required = true, notes = "Department name") - private String name; + @ApiModelProperty(required = true, notes = "Department name") + private String name; - @ApiModelProperty(required = true, notes = "Department code") - private String code; + @ApiModelProperty(required = true, notes = "Department code") + private String code; - public DepartmentDto() { + public DepartmentDto() { - } + } - public DepartmentDto(Long id, String name, String code) { - super(); - this.id = id; - this.name = name; - this.code = code; - } + public DepartmentDto(Long id, String name, String code) { + super(); + this.id = id; + this.name = name; + this.code = code; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationHistoryDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationHistoryDto.java index 26f1431..e24d3c8 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationHistoryDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationHistoryDto.java @@ -9,54 +9,54 @@ @ApiModel(value = "IntegrationHistoryDto", description = "Integration History Dto") public class IntegrationHistoryDto implements Serializable { - private static final long serialVersionUID = -6132580187596130900L; + private static final long serialVersionUID = -6132580187596130900L; - @ApiModelProperty(required = true, notes = "Integration ID") - private Long id; + @ApiModelProperty(required = true, notes = "Integration ID") + private Long id; - @ApiModelProperty(required = true, notes = "Created at") - private Date createdAt; + @ApiModelProperty(required = true, notes = "Created at") + private Date createdAt; - @ApiModelProperty(required = true, notes = "State") - private IntegrationStateDto state; + @ApiModelProperty(required = true, notes = "State") + private IntegrationStateDto state; - @ApiModelProperty(required = true, notes = "User name") - private String userName; + @ApiModelProperty(required = true, notes = "User name") + private String userName; - public IntegrationHistoryDto() { + public IntegrationHistoryDto() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public IntegrationStateDto getState() { - return state; - } + public IntegrationStateDto getState() { + return state; + } - public void setState(IntegrationStateDto state) { - this.state = state; - } + public void setState(IntegrationStateDto state) { + this.state = state; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } - public void setUserName(String userName) { - this.userName = userName; - } + public void setUserName(String userName) { + this.userName = userName; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStatDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStatDto.java index 1201164..cdb6837 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStatDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStatDto.java @@ -9,87 +9,87 @@ @ApiModel(value = "IntegrationStatDto", description = "Integration Stat Dto") public class IntegrationStatDto implements Serializable { - private static final long serialVersionUID = 8551544715165376269L; + private static final long serialVersionUID = 8551544715165376269L; - @ApiModelProperty(required = true, notes = "Integration Stat ID") - private Long id; + @ApiModelProperty(required = true, notes = "Integration Stat ID") + private Long id; - @ApiModelProperty(required = true, notes = "ANT records number") - private Long antRecordsNumber; + @ApiModelProperty(required = true, notes = "ANT records number") + private Long antRecordsNumber; - @ApiModelProperty(required = true, notes = "Cadastre records number") - private Long cadastreRecordsNumber; + @ApiModelProperty(required = true, notes = "Cadastre records number") + private Long cadastreRecordsNumber; - @ApiModelProperty(required = true, notes = "SNR records number") - private Long snrRecordsNumber; + @ApiModelProperty(required = true, notes = "SNR records number") + private Long snrRecordsNumber; - @ApiModelProperty(required = true, notes = "Percentage (Match)") - private Double percentage; + @ApiModelProperty(required = true, notes = "Percentage (Match)") + private Double percentage; - @ApiModelProperty(required = true, notes = "Match number") - private Long matchNumber; + @ApiModelProperty(required = true, notes = "Match number") + private Long matchNumber; - @ApiModelProperty(required = true, notes = "Created at") - private Date createdAt; + @ApiModelProperty(required = true, notes = "Created at") + private Date createdAt; - public IntegrationStatDto() { + public IntegrationStatDto() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getAntRecordsNumber() { - return antRecordsNumber; - } + public Long getAntRecordsNumber() { + return antRecordsNumber; + } - public void setAntRecordsNumber(Long antRecordsNumber) { - this.antRecordsNumber = antRecordsNumber; - } + public void setAntRecordsNumber(Long antRecordsNumber) { + this.antRecordsNumber = antRecordsNumber; + } - public Long getCadastreRecordsNumber() { - return cadastreRecordsNumber; - } + public Long getCadastreRecordsNumber() { + return cadastreRecordsNumber; + } - public void setCadastreRecordsNumber(Long cadastreRecordsNumber) { - this.cadastreRecordsNumber = cadastreRecordsNumber; - } + public void setCadastreRecordsNumber(Long cadastreRecordsNumber) { + this.cadastreRecordsNumber = cadastreRecordsNumber; + } - public Long getSnrRecordsNumber() { - return snrRecordsNumber; - } + public Long getSnrRecordsNumber() { + return snrRecordsNumber; + } - public void setSnrRecordsNumber(Long snrRecordsNumber) { - this.snrRecordsNumber = snrRecordsNumber; - } + public void setSnrRecordsNumber(Long snrRecordsNumber) { + this.snrRecordsNumber = snrRecordsNumber; + } - public Double getPercentage() { - return percentage; - } + public Double getPercentage() { + return percentage; + } - public void setPercentage(Double percentage) { - this.percentage = percentage; - } + public void setPercentage(Double percentage) { + this.percentage = percentage; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public Long getMatchNumber() { - return matchNumber; - } + public Long getMatchNumber() { + return matchNumber; + } - public void setMatchNumber(Long matchNumber) { - this.matchNumber = matchNumber; - } + public void setMatchNumber(Long matchNumber) { + this.matchNumber = matchNumber; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStateDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStateDto.java index ef0bbb1..a533f13 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStateDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/IntegrationStateDto.java @@ -8,50 +8,50 @@ @ApiModel(value = "IntegrationStateDto", description = "Integration State Dto") public class IntegrationStateDto implements Serializable { - private static final long serialVersionUID = 4121667515330552261L; + private static final long serialVersionUID = 4121667515330552261L; - @ApiModelProperty(required = true, notes = "Integration State ID") - private Long id; + @ApiModelProperty(required = true, notes = "Integration State ID") + private Long id; - @ApiModelProperty(required = true, notes = "Name") - private String name; + @ApiModelProperty(required = true, notes = "Name") + private String name; - @ApiModelProperty(required = true, notes = "Description") - private String description; + @ApiModelProperty(required = true, notes = "Description") + private String description; - public IntegrationStateDto() { + public IntegrationStateDto() { - } + } - public IntegrationStateDto(Long id, String name, String description) { - super(); - this.id = id; - this.name = name; - this.description = description; - } + public IntegrationStateDto(Long id, String name, String description) { + super(); + this.id = id; + this.name = name; + this.description = description; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/MakeIntegrationDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/MakeIntegrationDto.java index d18d347..e967007 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/MakeIntegrationDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/MakeIntegrationDto.java @@ -8,32 +8,37 @@ @ApiModel(value = "MakeIntegrationDto", description = "Make Integration Dto") public class MakeIntegrationDto implements Serializable { - private static final long serialVersionUID = -126620994344892312L; + private static final long serialVersionUID = -126620994344892312L; - @ApiModelProperty(required = true, notes = "Supply ID (cadastre)") - private Long supplyCadastre; + @ApiModelProperty(required = true, notes = "Supply ID (cadastre)") + private Long supplyCadastre; - @ApiModelProperty(required = true, notes = "Supply ID (registration)") - private Long supplyRegistration; + @ApiModelProperty(required = true, notes = "Supply ID (registration)") + private Long supplyRegistration; - public MakeIntegrationDto() { + public MakeIntegrationDto() { - } + } - public Long getSupplyCadastre() { - return supplyCadastre; - } + public Long getSupplyCadastre() { + return supplyCadastre; + } - public void setSupplyCadastre(Long supplyCadastre) { - this.supplyCadastre = supplyCadastre; - } + public void setSupplyCadastre(Long supplyCadastre) { + this.supplyCadastre = supplyCadastre; + } - public Long getSupplyRegistration() { - return supplyRegistration; - } + public Long getSupplyRegistration() { + return supplyRegistration; + } - public void setSupplyRegistration(Long supplyRegistration) { - this.supplyRegistration = supplyRegistration; - } + public void setSupplyRegistration(Long supplyRegistration) { + this.supplyRegistration = supplyRegistration; + } + @Override + public String toString() { + return "MakeIntegrationDto{" + "supplyCadastre=" + supplyCadastre + ", supplyRegistration=" + supplyRegistration + + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityDto.java index baf1dbc..b07b6ef 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityDto.java @@ -8,54 +8,54 @@ @ApiModel(value = "MunicipalityDto", description = "Municipality Dto") public class MunicipalityDto implements Serializable { - private static final long serialVersionUID = 5342779101170022387L; + private static final long serialVersionUID = 5342779101170022387L; - @ApiModelProperty(required = true, notes = "Municipality ID") - private Long id; + @ApiModelProperty(required = true, notes = "Municipality ID") + private Long id; - @ApiModelProperty(required = true, notes = "Municipality name") - private String name; + @ApiModelProperty(required = true, notes = "Municipality name") + private String name; - @ApiModelProperty(required = true, notes = "Municipality code") - private String code; + @ApiModelProperty(required = true, notes = "Municipality code") + private String code; - @ApiModelProperty(required = true, notes = "Department") - private DepartmentDto department; + @ApiModelProperty(required = true, notes = "Department") + private DepartmentDto department; - public MunicipalityDto() { + public MunicipalityDto() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public DepartmentDto getDepartment() { - return department; - } + public DepartmentDto getDepartment() { + return department; + } - public void setDepartment(DepartmentDto department) { - this.department = department; - } + public void setDepartment(DepartmentDto department) { + this.department = department; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityToAssignDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityToAssignDto.java index 5a21cfb..1d71814 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityToAssignDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/MunicipalityToAssignDto.java @@ -6,26 +6,26 @@ @ApiModel(value = "MunicipalityToAssignDto") public class MunicipalityToAssignDto { - @ApiModelProperty(required = true, notes = "Municipality ID") - private Long municipalityId; + @ApiModelProperty(required = true, notes = "Municipality ID") + private Long municipalityId; - @ApiModelProperty(required = true, notes = "Observations") - private String observations; + @ApiModelProperty(required = true, notes = "Observations") + private String observations; - public Long getMunicipalityId() { - return municipalityId; - } + public Long getMunicipalityId() { + return municipalityId; + } - public void setMunicipalityId(Long municipalityId) { - this.municipalityId = municipalityId; - } + public void setMunicipalityId(Long municipalityId) { + this.municipalityId = municipalityId; + } - public String getObservations() { - return observations; - } + public String getObservations() { + return observations; + } - public void setObservations(String observations) { - this.observations = observations; - } + public void setObservations(String observations) { + this.observations = observations; + } } \ No newline at end of file diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/PossibleIntegrationDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/PossibleIntegrationDto.java index f6f6786..535e68f 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/PossibleIntegrationDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/PossibleIntegrationDto.java @@ -8,25 +8,25 @@ @ApiModel(value = "PossibleIntegrationDto") public class PossibleIntegrationDto implements Serializable { - private static final long serialVersionUID = 9161755714691932192L; + private static final long serialVersionUID = 9161755714691932192L; - @ApiModelProperty(required = true, notes = "Municipality") - private MunicipalityDto municipality; + @ApiModelProperty(required = true, notes = "Municipality") + private MunicipalityDto municipality; - public PossibleIntegrationDto() { + public PossibleIntegrationDto() { - } + } - public PossibleIntegrationDto(MunicipalityDto municipality) { - this.municipality = municipality; - } + public PossibleIntegrationDto(MunicipalityDto municipality) { + this.municipality = municipality; + } - public MunicipalityDto getMunicipality() { - return municipality; - } + public MunicipalityDto getMunicipality() { + return municipality; + } - public void setMunicipality(MunicipalityDto municipality) { - this.municipality = municipality; - } + public void setMunicipality(MunicipalityDto municipality) { + this.municipality = municipality; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/TypeSupplyRequestedDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/TypeSupplyRequestedDto.java index b348c6c..f85aa38 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/TypeSupplyRequestedDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/TypeSupplyRequestedDto.java @@ -8,54 +8,59 @@ @ApiModel(value = "TypeSupplyRequestDto", description = "Type Supply Requested Dto") public class TypeSupplyRequestedDto implements Serializable { - private static final long serialVersionUID = -5598899972451538583L; + private static final long serialVersionUID = -5598899972451538583L; - @ApiModelProperty(required = true, notes = "Deadline") - private Long typeSupplyId; + @ApiModelProperty(required = true, notes = "Deadline") + private Long typeSupplyId; - @ApiModelProperty(required = false, notes = "Observation") - private String observation; + @ApiModelProperty(notes = "Observation") + private String observation; - @ApiModelProperty(required = true, notes = "Provider ID") - private Long providerId; + @ApiModelProperty(required = true, notes = "Provider ID") + private Long providerId; - @ApiModelProperty(required = false, notes = "Model version") - private String modelVersion; + @ApiModelProperty(notes = "Model version") + private String modelVersion; - public TypeSupplyRequestedDto() { + public TypeSupplyRequestedDto() { - } + } - public Long getTypeSupplyId() { - return typeSupplyId; - } + public Long getTypeSupplyId() { + return typeSupplyId; + } - public void setTypeSupplyId(Long typeSupplyId) { - this.typeSupplyId = typeSupplyId; - } + public void setTypeSupplyId(Long typeSupplyId) { + this.typeSupplyId = typeSupplyId; + } - public String getObservation() { - return observation; - } + public String getObservation() { + return observation; + } - public void setObservation(String observation) { - this.observation = observation; - } + public void setObservation(String observation) { + this.observation = observation; + } - public Long getProviderId() { - return providerId; - } + public Long getProviderId() { + return providerId; + } - public void setProviderId(Long providerId) { - this.providerId = providerId; - } + public void setProviderId(Long providerId) { + this.providerId = providerId; + } - public String getModelVersion() { - return modelVersion; - } + public String getModelVersion() { + return modelVersion; + } - public void setModelVersion(String modelVersion) { - this.modelVersion = modelVersion; - } + public void setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + } + @Override + public String toString() { + return "TypeSupplyRequestedDto{" + "typeSupplyId=" + typeSupplyId + ", observation='" + observation + '\'' + + ", providerId=" + providerId + ", modelVersion='" + modelVersion + '\'' + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/UpdatePetitionDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/UpdatePetitionDto.java index 8f50e31..e05adaf 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/UpdatePetitionDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/UpdatePetitionDto.java @@ -8,21 +8,25 @@ @ApiModel(value = "UpdatePetitionDto") public class UpdatePetitionDto implements Serializable { - private static final long serialVersionUID = -5543133839868782615L; + private static final long serialVersionUID = -5543133839868782615L; - @ApiModelProperty(required = true, notes = "Justification") - private String justification; + @ApiModelProperty(required = true, notes = "Justification") + private String justification; - public UpdatePetitionDto() { + public UpdatePetitionDto() { - } + } - public String getJustification() { - return justification; - } + public String getJustification() { + return justification; + } - public void setJustification(String justification) { - this.justification = justification; - } + public void setJustification(String justification) { + this.justification = justification; + } + @Override + public String toString() { + return "UpdatePetitionDto{" + "justification='" + justification + '\'' + '}'; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/ValidationMunicipalitiesDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/ValidationMunicipalitiesDto.java index 763a8c0..2932cea 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/ValidationMunicipalitiesDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/ValidationMunicipalitiesDto.java @@ -10,74 +10,74 @@ @ApiModel(value = "ValidationMunicipalitiesDto") public class ValidationMunicipalitiesDto implements Serializable { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - @ApiModelProperty(required = true, notes = "Municipality ID") - private Long municipalityId; + @ApiModelProperty(required = true, notes = "Municipality ID") + private Long municipalityId; - @ApiModelProperty(required = true, notes = "Municipality Name") - private String municipalityName; + @ApiModelProperty(required = true, notes = "Municipality Name") + private String municipalityName; - @ApiModelProperty(required = true, notes = "Municipality Code (DIVIPOLA)") - private String municipalityCode; + @ApiModelProperty(required = true, notes = "Municipality Code (DIVIPOLA)") + private String municipalityCode; - @ApiModelProperty(required = true, notes = "Does municipality have a conflict?") - private Boolean conflict; + @ApiModelProperty(required = true, notes = "Does municipality have a conflict?") + private Boolean conflict; - @ApiModelProperty(required = true, notes = "Does municipality have a conflict?") - private List managers; + @ApiModelProperty(required = true, notes = "Does municipality have a conflict?") + private List managers; - public ValidationMunicipalitiesDto() { - this.managers = new ArrayList<>(); - } + public ValidationMunicipalitiesDto() { + this.managers = new ArrayList<>(); + } - public ValidationMunicipalitiesDto(Long municipalityId, String municipalityName, String municipalityCode) { - super(); - this.municipalityId = municipalityId; - this.municipalityName = municipalityName; - this.municipalityCode = municipalityCode; - this.conflict = false; - this.managers = new ArrayList<>(); - } + public ValidationMunicipalitiesDto(Long municipalityId, String municipalityName, String municipalityCode) { + super(); + this.municipalityId = municipalityId; + this.municipalityName = municipalityName; + this.municipalityCode = municipalityCode; + this.conflict = false; + this.managers = new ArrayList<>(); + } - public Long getMunicipalityId() { - return municipalityId; - } + public Long getMunicipalityId() { + return municipalityId; + } - public void setMunicipalityId(Long municipalityId) { - this.municipalityId = municipalityId; - } + public void setMunicipalityId(Long municipalityId) { + this.municipalityId = municipalityId; + } - public Boolean getConflict() { - return conflict; - } + public Boolean getConflict() { + return conflict; + } - public void setConflict(Boolean conflict) { - this.conflict = conflict; - } + public void setConflict(Boolean conflict) { + this.conflict = conflict; + } - public String getMunicipalityName() { - return municipalityName; - } + public String getMunicipalityName() { + return municipalityName; + } - public void setMunicipalityName(String municipalityName) { - this.municipalityName = municipalityName; - } + public void setMunicipalityName(String municipalityName) { + this.municipalityName = municipalityName; + } - public String getMunicipalityCode() { - return municipalityCode; - } + public String getMunicipalityCode() { + return municipalityCode; + } - public void setMunicipalityCode(String municipalityCode) { - this.municipalityCode = municipalityCode; - } + public void setMunicipalityCode(String municipalityCode) { + this.municipalityCode = municipalityCode; + } - public List getManagers() { - return managers; - } + public List getManagers() { + return managers; + } - public void setManagers(List managers) { - this.managers = managers; - } + public void setManagers(List managers) { + this.managers = managers; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/WorkspaceDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/WorkspaceDto.java index e949100..db62a83 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/WorkspaceDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/WorkspaceDto.java @@ -11,88 +11,88 @@ @ApiModel(value = "WorkspaceDto", description = "Workspace Dto") public class WorkspaceDto implements Serializable { - private static final long serialVersionUID = 3626653639569669214L; + private static final long serialVersionUID = 3626653639569669214L; - @ApiModelProperty(required = true, notes = "Workspace ID") - private Long id; + @ApiModelProperty(required = true, notes = "Workspace ID") + private Long id; - @ApiModelProperty(required = true, notes = "Is active?") - private Boolean isActive; + @ApiModelProperty(required = true, notes = "Is active?") + private Boolean isActive; - @ApiModelProperty(required = true, notes = "Date creation") - private Date createdAt; + @ApiModelProperty(required = true, notes = "Date creation") + private Date createdAt; - @ApiModelProperty(required = false, notes = "Date update") - private Date updatedAt; + @ApiModelProperty(required = false, notes = "Date update") + private Date updatedAt; - @ApiModelProperty(required = false, notes = "Operators") - private List operators; + @ApiModelProperty(required = false, notes = "Operators") + private List operators; - @ApiModelProperty(required = false, notes = "Managers") - private List managers; + @ApiModelProperty(required = false, notes = "Managers") + private List managers; - @ApiModelProperty(required = false, notes = "Municipality") - private MunicipalityDto municipality; + @ApiModelProperty(required = false, notes = "Municipality") + private MunicipalityDto municipality; - public WorkspaceDto() { - operators = new ArrayList(); - managers = new ArrayList(); - } + public WorkspaceDto() { + operators = new ArrayList(); + managers = new ArrayList(); + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Boolean getIsActive() { - return isActive; - } + public Boolean getIsActive() { + return isActive; + } - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } + public void setIsActive(Boolean isActive) { + this.isActive = isActive; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public List getOperators() { - return operators; - } + public List getOperators() { + return operators; + } - public void setOperators(List operators) { - this.operators = operators; - } + public void setOperators(List operators) { + this.operators = operators; + } - public Date getUpdatedAt() { - return updatedAt; - } + public Date getUpdatedAt() { + return updatedAt; + } - public void setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - } + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } - public MunicipalityDto getMunicipality() { - return municipality; - } + public MunicipalityDto getMunicipality() { + return municipality; + } - public void setMunicipality(MunicipalityDto municipality) { - this.municipality = municipality; - } + public void setMunicipality(MunicipalityDto municipality) { + this.municipality = municipality; + } - public List getManagers() { - return managers; - } + public List getManagers() { + return managers; + } - public void setManagers(List managers) { - this.managers = managers; - } + public void setManagers(List managers) { + this.managers = managers; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/administration/CustomUserDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/administration/CustomUserDto.java index 776b8c4..9a58683 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/administration/CustomUserDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/administration/CustomUserDto.java @@ -25,7 +25,7 @@ public CustomUserDto() { } public CustomUserDto(Long id, String firstName, String lastName, String email, String username, String password, - Boolean enabled, Date createdAt, Date updatedAt, List roles) { + Boolean enabled, Date createdAt, Date updatedAt, List roles) { super(); this.setId(id); this.setFirstName(firstName); diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/ftp/MicroserviceCreateUserFTPDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/ftp/MicroserviceCreateUserFTPDto.java index 338eec0..803fabc 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/ftp/MicroserviceCreateUserFTPDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/ftp/MicroserviceCreateUserFTPDto.java @@ -8,32 +8,32 @@ @ApiModel(value = "CreateUserDto") public class MicroserviceCreateUserFTPDto implements Serializable { - private static final long serialVersionUID = 7642358068586739264L; + private static final long serialVersionUID = 7642358068586739264L; - @ApiModelProperty(required = true, notes = "Username") - private String username; + @ApiModelProperty(required = true, notes = "Username") + private String username; - @ApiModelProperty(required = true, notes = "Password") - private String password; + @ApiModelProperty(required = true, notes = "Password") + private String password; - public MicroserviceCreateUserFTPDto() { + public MicroserviceCreateUserFTPDto() { - } + } - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceDataMapDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceDataMapDto.java index fa0ff88..81afb5b 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceDataMapDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceDataMapDto.java @@ -4,20 +4,20 @@ public class MicroserviceDataMapDto implements Serializable { - private static final long serialVersionUID = 7795987778570923080L; + private static final long serialVersionUID = 7795987778570923080L; - private String data; + private String st_geocreatefastcontext; - public MicroserviceDataMapDto() { + public MicroserviceDataMapDto() { - } + } - public String getData() { - return data; - } + public String getSt_geocreatefastcontext() { + return st_geocreatefastcontext; + } - public void setData(String data) { - this.data = data; - } + public void setSt_geocreatefastcontext(String st_geocreatefastcontext) { + this.st_geocreatefastcontext = st_geocreatefastcontext; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceSetupMapDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceSetupMapDto.java index 4a3e514..359699f 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceSetupMapDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/geovisor/MicroserviceSetupMapDto.java @@ -6,83 +6,142 @@ public class MicroserviceSetupMapDto implements Serializable { - private static final long serialVersionUID = 2755366603547812603L; - - private String name_conn; - private String dbname; - private String host; - private int port; - private String user; - private String password; - private String schema; - private List layers; - - public MicroserviceSetupMapDto() { - this.layers = new ArrayList(); - } - - public String getName_conn() { - return name_conn; - } - - public void setName_conn(String name_conn) { - this.name_conn = name_conn; - } - - public String getDbname() { - return dbname; - } - - public void setDbname(String dbname) { - this.dbname = dbname; - } - - public String getHost() { - return host; - } - - public void setHost(String host) { - this.host = host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public String getSchema() { - return schema; - } - - public void setSchema(String schema) { - this.schema = schema; - } - - public List getLayers() { - return layers; - } - - public void setLayers(List layers) { - this.layers = layers; - } + private static final long serialVersionUID = 2755366603547812603L; + + private String name_conn; + private String store; + private String workspace; + private String dbname; + private String host; + private String port; + private String user; + private String password; + private String schema; + private List layers; + + public MicroserviceSetupMapDto() { + this.layers = new ArrayList<>(); + } + + public String getName_conn() { + return name_conn; + } + + public void setName_conn(String name_conn) { + this.name_conn = name_conn; + } + + public String getDbname() { + return dbname; + } + + public void setDbname(String dbname) { + this.dbname = dbname; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getSchema() { + return schema; + } + + public void setSchema(String schema) { + this.schema = schema; + } + + public List getLayers() { + return layers; + } + + public void setLayers(List layers) { + this.layers = layers; + } + + public String getStore() { + return store; + } + + public void setStore(String store) { + this.store = store; + } + + public String getWorkspace() { + return workspace; + } + + public void setWorkspace(String workspace) { + this.workspace = workspace; + } + + public static class Layer { + + private String tablename; + private String style; + private String title; + + public Layer() { + + } + + public Layer(String tableName, String style, String title) { + this.tablename = tableName; + this.style = style; + this.title = title; + } + + public String getTablename() { + return tablename; + } + + public void setTablename(String tablename) { + this.tablename = tablename; + } + + public String getStyle() { + return style; + } + + public void setStyle(String style) { + this.style = style; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/operators/CustomSupplyDeliveryDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/operators/CustomSupplyDeliveryDto.java index b250303..4bcc6fa 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/operators/CustomSupplyDeliveryDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/operators/CustomSupplyDeliveryDto.java @@ -26,7 +26,6 @@ public CustomSupplyDeliveryDto(MicroserviceSupplyDeliveryDto response) { this.setDownloadReportUrl(response.getDownloadReportUrl()); } - public CustomSupplyDto getSupply() { return supply; } diff --git a/src/main/java/com/ai/st/microservice/workspaces/dto/providers/RequestPackageDto.java b/src/main/java/com/ai/st/microservice/workspaces/dto/providers/RequestPackageDto.java index d0d0958..f61084a 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/dto/providers/RequestPackageDto.java +++ b/src/main/java/com/ai/st/microservice/workspaces/dto/providers/RequestPackageDto.java @@ -6,29 +6,29 @@ public class RequestPackageDto implements Serializable { - private static final long serialVersionUID = -181941292488270615L; + private static final long serialVersionUID = -181941292488270615L; - private String packageLabel; - private List requests; + private String packageLabel; + private List requests; - public RequestPackageDto() { - this.requests = new ArrayList<>(); - } + public RequestPackageDto() { + this.requests = new ArrayList<>(); + } - public List getRequests() { - return requests; - } + public List getRequests() { + return requests; + } - public void setRequests(List requests) { - this.requests = requests; - } + public void setRequests(List requests) { + this.requests = requests; + } - public String getPackageLabel() { - return packageLabel; - } + public String getPackageLabel() { + return packageLabel; + } - public void setPackageLabel(String packageLabel) { - this.packageLabel = packageLabel; - } + public void setPackageLabel(String packageLabel) { + this.packageLabel = packageLabel; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/DepartmentEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/DepartmentEntity.java index 19b173f..f2c26ad 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/DepartmentEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/DepartmentEntity.java @@ -11,43 +11,43 @@ @Table(name = "departments", schema = "workspaces") public class DepartmentEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; - - @Column(name = "name", nullable = false) - private String name; - - @Column(name = "code", nullable = false) - private String code; - - public DepartmentEntity() { - - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; + + @Column(name = "name", nullable = false) + private String name; + + @Column(name = "code", nullable = false) + private String code; + + public DepartmentEntity() { + + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationHistoryEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationHistoryEntity.java index 15650c9..64dfaf8 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationHistoryEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationHistoryEntity.java @@ -18,90 +18,90 @@ @Table(name = "integrations_histories", schema = "workspaces") public class IntegrationHistoryEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "integration_id", referencedColumnName = "id", nullable = false) - private IntegrationEntity integration; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "integration_id", referencedColumnName = "id", nullable = false) + private IntegrationEntity integration; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "integration_state_id", referencedColumnName = "id", nullable = false) - private IntegrationStateEntity state; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "integration_state_id", referencedColumnName = "id", nullable = false) + private IntegrationStateEntity state; - @Column(name = "created_at", nullable = false) - @Temporal(TemporalType.TIMESTAMP) - private Date createdAt; + @Column(name = "created_at", nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date createdAt; - @Column(name = "user_name", nullable = false, length = 300) - private String userName; + @Column(name = "user_name", nullable = false, length = 300) + private String userName; - @Column(name = "user_code") - private Long userCode; + @Column(name = "user_code") + private Long userCode; - @Column(name = "manager_code") - private Long managerCode; + @Column(name = "manager_code") + private Long managerCode; - public IntegrationHistoryEntity() { + public IntegrationHistoryEntity() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public IntegrationEntity getIntegration() { - return integration; - } + public IntegrationEntity getIntegration() { + return integration; + } - public void setIntegration(IntegrationEntity integration) { - this.integration = integration; - } + public void setIntegration(IntegrationEntity integration) { + this.integration = integration; + } - public IntegrationStateEntity getState() { - return state; - } + public IntegrationStateEntity getState() { + return state; + } - public void setState(IntegrationStateEntity state) { - this.state = state; - } + public void setState(IntegrationStateEntity state) { + this.state = state; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } - public void setUserName(String userName) { - this.userName = userName; - } + public void setUserName(String userName) { + this.userName = userName; + } - public Long getUserCode() { - return userCode; - } + public Long getUserCode() { + return userCode; + } - public void setUserCode(Long userCode) { - this.userCode = userCode; - } + public void setUserCode(Long userCode) { + this.userCode = userCode; + } - public Long getManagerCode() { - return managerCode; - } + public Long getManagerCode() { + return managerCode; + } - public void setManagerCode(Long managerCode) { - this.managerCode = managerCode; - } + public void setManagerCode(Long managerCode) { + this.managerCode = managerCode; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStatEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStatEntity.java index 5822189..a13e618 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStatEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStatEntity.java @@ -18,100 +18,100 @@ @Table(name = "integrations_stats", schema = "workspaces") public class IntegrationStatEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "integration_id", referencedColumnName = "id", nullable = false) - private IntegrationEntity integration; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "integration_id", referencedColumnName = "id", nullable = false) + private IntegrationEntity integration; - @Column(name = "snr_records_number", nullable = false) - private Long snrRecordsNumber; + @Column(name = "snr_records_number", nullable = false) + private Long snrRecordsNumber; - @Column(name = "cadastre_records_number", nullable = false) - private Long cadastreRecordsNumber; + @Column(name = "cadastre_records_number", nullable = false) + private Long cadastreRecordsNumber; - @Column(name = "ant_records_number") - private Long antRecordsNumber; + @Column(name = "ant_records_number") + private Long antRecordsNumber; - @Column(name = "match_number", nullable = false) - private Long matchNumber; + @Column(name = "match_number", nullable = false) + private Long matchNumber; - @Column(name = "percentage", precision = 10, scale = 2, nullable = false) - private Double percentage; + @Column(name = "percentage", precision = 10, scale = 2, nullable = false) + private Double percentage; - @Column(name = "created_at", nullable = false) - @Temporal(TemporalType.TIMESTAMP) - private Date createdAt; + @Column(name = "created_at", nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date createdAt; - public IntegrationStatEntity() { + public IntegrationStatEntity() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public IntegrationEntity getIntegration() { - return integration; - } + public IntegrationEntity getIntegration() { + return integration; + } - public void setIntegration(IntegrationEntity integration) { - this.integration = integration; - } + public void setIntegration(IntegrationEntity integration) { + this.integration = integration; + } - public Long getSnrRecordsNumber() { - return snrRecordsNumber; - } + public Long getSnrRecordsNumber() { + return snrRecordsNumber; + } - public void setSnrRecordsNumber(Long snrRecordsNumber) { - this.snrRecordsNumber = snrRecordsNumber; - } + public void setSnrRecordsNumber(Long snrRecordsNumber) { + this.snrRecordsNumber = snrRecordsNumber; + } - public Long getCadastreRecordsNumber() { - return cadastreRecordsNumber; - } + public Long getCadastreRecordsNumber() { + return cadastreRecordsNumber; + } - public void setCadastreRecordsNumber(Long cadastreRecordsNumber) { - this.cadastreRecordsNumber = cadastreRecordsNumber; - } + public void setCadastreRecordsNumber(Long cadastreRecordsNumber) { + this.cadastreRecordsNumber = cadastreRecordsNumber; + } - public Long getAntRecordsNumber() { - return antRecordsNumber; - } + public Long getAntRecordsNumber() { + return antRecordsNumber; + } - public void setAntRecordsNumber(Long antRecordsNumber) { - this.antRecordsNumber = antRecordsNumber; - } + public void setAntRecordsNumber(Long antRecordsNumber) { + this.antRecordsNumber = antRecordsNumber; + } - public Double getPercentage() { - return percentage; - } + public Double getPercentage() { + return percentage; + } - public void setPercentage(Double percentage) { - this.percentage = percentage; - } + public void setPercentage(Double percentage) { + this.percentage = percentage; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public Long getMatchNumber() { - return matchNumber; - } + public Long getMatchNumber() { + return matchNumber; + } - public void setMatchNumber(Long matchNumber) { - this.matchNumber = matchNumber; - } + public void setMatchNumber(Long matchNumber) { + this.matchNumber = matchNumber; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStateEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStateEntity.java index 5569bb3..7d95515 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStateEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/IntegrationStateEntity.java @@ -13,43 +13,43 @@ @Transactional public class IntegrationStateEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; - @Column(name = "name", nullable = false) - private String name; + @Column(name = "name", nullable = false) + private String name; - @Column(name = "description") - private String description; + @Column(name = "description") + private String description; - public IntegrationStateEntity() { + public IntegrationStateEntity() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/MunicipalityEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/MunicipalityEntity.java index 17eb2fc..fab7133 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/MunicipalityEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/MunicipalityEntity.java @@ -14,55 +14,55 @@ @Table(name = "municipalities", schema = "workspaces") public class MunicipalityEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; - @Column(name = "name", nullable = false) - private String name; + @Column(name = "name", nullable = false) + private String name; - @Column(name = "code", nullable = false) - private String code; + @Column(name = "code", nullable = false) + private String code; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "department_id", referencedColumnName = "id", nullable = false) - private DepartmentEntity department; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "department_id", referencedColumnName = "id", nullable = false) + private DepartmentEntity department; - public MunicipalityEntity() { + public MunicipalityEntity() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getCode() { - return code; - } + public String getCode() { + return code; + } - public void setCode(String code) { - this.code = code; - } + public void setCode(String code) { + this.code = code; + } - public DepartmentEntity getDepartment() { - return department; - } + public DepartmentEntity getDepartment() { + return department; + } - public void setDepartment(DepartmentEntity department) { - this.department = department; - } + public void setDepartment(DepartmentEntity department) { + this.department = department; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceEntity.java index 76e1f18..03c198e 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceEntity.java @@ -21,102 +21,102 @@ @Table(name = "workspaces", schema = "workspaces") public class WorkspaceEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; - @Column(name = "is_active") - private Boolean isActive; + @Column(name = "is_active") + private Boolean isActive; - @Column(name = "created_at", nullable = false) - @Temporal(TemporalType.TIMESTAMP) - private Date createdAt; + @Column(name = "created_at", nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date createdAt; - @Column(name = "updated_at") - @Temporal(TemporalType.TIMESTAMP) - private Date updatedAt; + @Column(name = "updated_at") + @Temporal(TemporalType.TIMESTAMP) + private Date updatedAt; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "municipality_id", referencedColumnName = "id", nullable = false) - private MunicipalityEntity municipality; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "municipality_id", referencedColumnName = "id", nullable = false) + private MunicipalityEntity municipality; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "workspace_id", referencedColumnName = "id") - private WorkspaceEntity workspace; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "workspace_id", referencedColumnName = "id") + private WorkspaceEntity workspace; - @OneToMany(mappedBy = "workspace", fetch = FetchType.LAZY) - private List operators = new ArrayList<>(); + @OneToMany(mappedBy = "workspace", fetch = FetchType.LAZY) + private List operators = new ArrayList<>(); - @OneToMany(mappedBy = "workspace", fetch = FetchType.LAZY) - private List managers = new ArrayList<>(); + @OneToMany(mappedBy = "workspace", fetch = FetchType.LAZY) + private List managers = new ArrayList<>(); - public WorkspaceEntity() { + public WorkspaceEntity() { - } + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Boolean getIsActive() { - return isActive; - } + public Boolean getIsActive() { + return isActive; + } - public void setIsActive(Boolean isActive) { - this.isActive = isActive; - } + public void setIsActive(Boolean isActive) { + this.isActive = isActive; + } - public Date getCreatedAt() { - return createdAt; - } + public Date getCreatedAt() { + return createdAt; + } - public void setCreatedAt(Date createdAt) { - this.createdAt = createdAt; - } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } - public MunicipalityEntity getMunicipality() { - return municipality; - } + public MunicipalityEntity getMunicipality() { + return municipality; + } - public void setMunicipality(MunicipalityEntity municipality) { - this.municipality = municipality; - } + public void setMunicipality(MunicipalityEntity municipality) { + this.municipality = municipality; + } - public List getOperators() { - return operators; - } + public List getOperators() { + return operators; + } - public void setOperators(List operators) { - this.operators = operators; - } + public void setOperators(List operators) { + this.operators = operators; + } - public Date getUpdatedAt() { - return updatedAt; - } + public Date getUpdatedAt() { + return updatedAt; + } - public void setUpdatedAt(Date updatedAt) { - this.updatedAt = updatedAt; - } + public void setUpdatedAt(Date updatedAt) { + this.updatedAt = updatedAt; + } - public WorkspaceEntity getWorkspace() { - return workspace; - } + public WorkspaceEntity getWorkspace() { + return workspace; + } - public void setWorkspace(WorkspaceEntity workspace) { - this.workspace = workspace; - } + public void setWorkspace(WorkspaceEntity workspace) { + this.workspace = workspace; + } - public List getManagers() { - return managers; - } + public List getManagers() { + return managers; + } - public void setManagers(List managers) { - this.managers = managers; - } + public void setManagers(List managers) { + this.managers = managers; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceManagerEntity.java b/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceManagerEntity.java index dc2f1e9..9fa760e 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceManagerEntity.java +++ b/src/main/java/com/ai/st/microservice/workspaces/entities/WorkspaceManagerEntity.java @@ -18,74 +18,74 @@ @Table(name = "workspace_managers", schema = "workspaces") public class WorkspaceManagerEntity { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - private Long id; + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Long id; - @Column(name = "manager_code", nullable = false) - private Long managerCode; + @Column(name = "manager_code", nullable = false) + private Long managerCode; - @Column(name = "observations", nullable = false, length = 500) - private String observations; + @Column(name = "observations", nullable = false, length = 500) + private String observations; - @Column(name = "start_date", nullable = false) - @Temporal(TemporalType.DATE) - private Date startDate; + @Column(name = "start_date", nullable = false) + @Temporal(TemporalType.DATE) + private Date startDate; - @Column(name = "support", nullable = false, length = 1000) - private String supportFile; + @Column(name = "support", nullable = false, length = 1000) + private String supportFile; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "workspace_id", referencedColumnName = "id", nullable = false) - private WorkspaceEntity workspace; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "workspace_id", referencedColumnName = "id", nullable = false) + private WorkspaceEntity workspace; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getManagerCode() { - return managerCode; - } + public Long getManagerCode() { + return managerCode; + } - public void setManagerCode(Long managerCode) { - this.managerCode = managerCode; - } + public void setManagerCode(Long managerCode) { + this.managerCode = managerCode; + } - public String getObservations() { - return observations; - } + public String getObservations() { + return observations; + } - public void setObservations(String observations) { - this.observations = observations; - } + public void setObservations(String observations) { + this.observations = observations; + } - public Date getStartDate() { - return startDate; - } + public Date getStartDate() { + return startDate; + } - public void setStartDate(Date startDate) { - this.startDate = startDate; - } + public void setStartDate(Date startDate) { + this.startDate = startDate; + } - public WorkspaceEntity getWorkspace() { - return workspace; - } + public WorkspaceEntity getWorkspace() { + return workspace; + } - public void setWorkspace(WorkspaceEntity workspace) { - this.workspace = workspace; - } + public void setWorkspace(WorkspaceEntity workspace) { + this.workspace = workspace; + } - public String getSupportFile() { - return supportFile; - } + public String getSupportFile() { + return supportFile; + } - public void setSupportFile(String supportFile) { - this.supportFile = supportFile; - } + public void setSupportFile(String supportFile) { + this.supportFile = supportFile; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/RabbitMQConfig.java b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/RabbitMQConfig.java index d9e65f5..6445540 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/RabbitMQConfig.java +++ b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/RabbitMQConfig.java @@ -17,142 +17,142 @@ @Configuration public class RabbitMQConfig { - @Value("${st.rabbitmq.queueUpdateIntegration.queue}") - public String queueUpdateIntegrationsName; + @Value("${st.rabbitmq.queueUpdateIntegration.queue}") + public String queueUpdateIntegrationsName; - @Value("${st.rabbitmq.queueUpdateIntegration.exchange}") - public String exchangeUpdateIntegrationsName; + @Value("${st.rabbitmq.queueUpdateIntegration.exchange}") + public String exchangeUpdateIntegrationsName; - @Value("${st.rabbitmq.queueUpdateIntegration.routingkey}") - public String routingkeyUpdateIntegrationsName; + @Value("${st.rabbitmq.queueUpdateIntegration.routingkey}") + public String routingkeyUpdateIntegrationsName; - @Value("${st.rabbitmq.queueUpdateExport.queue}") - public String queueUpdateExportName; + @Value("${st.rabbitmq.queueUpdateExport.queue}") + public String queueUpdateExportName; - @Value("${st.rabbitmq.queueUpdateExport.exchange}") - public String exchangeUpdateExportName; + @Value("${st.rabbitmq.queueUpdateExport.exchange}") + public String exchangeUpdateExportName; - @Value("${st.rabbitmq.queueUpdateExport.routingkey}") - public String routingkeyUpdateExportName; + @Value("${st.rabbitmq.queueUpdateExport.routingkey}") + public String routingkeyUpdateExportName; - @Value("${st.rabbitmq.queueUpdateStateSupply.queue}") - public String queueUpdateStateSupplyName; + @Value("${st.rabbitmq.queueUpdateStateSupply.queue}") + public String queueUpdateStateSupplyName; - @Value("${st.rabbitmq.queueUpdateStateSupply.exchange}") - public String exchangeUpdateStateSupplyName; + @Value("${st.rabbitmq.queueUpdateStateSupply.exchange}") + public String exchangeUpdateStateSupplyName; - @Value("${st.rabbitmq.queueUpdateStateSupply.routingkey}") - public String routingkeyUpdateStateSupplyName; + @Value("${st.rabbitmq.queueUpdateStateSupply.routingkey}") + public String routingkeyUpdateStateSupplyName; - @Value("${st.rabbitmq.queueResultImport.queue}") - public String queueResultImportName; + @Value("${st.rabbitmq.queueResultImport.queue}") + public String queueResultImportName; - @Value("${st.rabbitmq.queueResultImport.exchange}") - public String exchangeResultImportName; + @Value("${st.rabbitmq.queueResultImport.exchange}") + public String exchangeResultImportName; - @Value("${st.rabbitmq.queueResultImport.routingkey}") - public String routingkeyResultImportName; - - @Value("${st.rabbitmq.queueResultExport.queue}") - public String queueResultExportName; - - @Value("${st.rabbitmq.queueResultExport.exchange}") - public String exchangeResultExportName; - - @Value("${st.rabbitmq.queueResultExport.routingkey}") - public String routingkeyResultExportName; - - @Bean - public Queue queueUpdateIntegrations() { - return new Queue(queueUpdateIntegrationsName, false); - } - - @Bean - public DirectExchange exchangeUpdateIntegrations() { - return new DirectExchange(exchangeUpdateIntegrationsName); - } - - @Bean - public Binding bindingQueueUpdateIntegrations() { - return BindingBuilder.bind(queueUpdateIntegrations()).to(exchangeUpdateIntegrations()) - .with(routingkeyUpdateIntegrationsName); - } - - @Bean - public Queue queueUpdateExports() { - return new Queue(queueUpdateExportName, false); - } - - @Bean - public DirectExchange exchangeUpdateExports() { - return new DirectExchange(exchangeUpdateExportName); - } - - @Bean - public Binding bindingQueueUpdateExports() { - return BindingBuilder.bind(queueUpdateExports()).to(exchangeUpdateExports()).with(routingkeyUpdateExportName); - } - - @Bean - public Queue queueUpdateStateSupply() { - return new Queue(queueUpdateStateSupplyName, false); - } - - @Bean - public DirectExchange exchangeUpdateStateSupply() { - return new DirectExchange(exchangeUpdateStateSupplyName); - } - - @Bean - public Binding bindingQueueUpdateStateSupply() { - return BindingBuilder.bind(queueUpdateStateSupply()).to(exchangeUpdateStateSupply()) - .with(routingkeyUpdateStateSupplyName); - } - - // queue result imports reference - - @Bean - public Queue queueResultImport() { - return new Queue(queueResultImportName, false); - } - - @Bean - public DirectExchange exchangeResultImport() { - return new DirectExchange(exchangeResultImportName); - } - - @Bean - public Binding bindingQueueResultImport() { - return BindingBuilder.bind(queueResultImport()).to(exchangeResultImport()).with(routingkeyResultImportName); - } - - // queue result exports reference - - @Bean - public Queue queueResultExport() { - return new Queue(queueResultExportName, false); - } - - @Bean - public DirectExchange exchangeResultExport() { - return new DirectExchange(exchangeResultExportName); - } - - @Bean - public Binding bindingQueueResultExport() { - return BindingBuilder.bind(queueResultExport()).to(exchangeResultExport()).with(routingkeyResultExportName); - } - - @Bean - public Jackson2JsonMessageConverter jsonMessageConverter() { - return new Jackson2JsonMessageConverter(); - } - - @Bean - public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) { - final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); - rabbitTemplate.setMessageConverter(jsonMessageConverter()); - return rabbitTemplate; - } + @Value("${st.rabbitmq.queueResultImport.routingkey}") + public String routingkeyResultImportName; + + @Value("${st.rabbitmq.queueResultExport.queue}") + public String queueResultExportName; + + @Value("${st.rabbitmq.queueResultExport.exchange}") + public String exchangeResultExportName; + + @Value("${st.rabbitmq.queueResultExport.routingkey}") + public String routingkeyResultExportName; + + @Bean + public Queue queueUpdateIntegrations() { + return new Queue(queueUpdateIntegrationsName, false); + } + + @Bean + public DirectExchange exchangeUpdateIntegrations() { + return new DirectExchange(exchangeUpdateIntegrationsName); + } + + @Bean + public Binding bindingQueueUpdateIntegrations() { + return BindingBuilder.bind(queueUpdateIntegrations()).to(exchangeUpdateIntegrations()) + .with(routingkeyUpdateIntegrationsName); + } + + @Bean + public Queue queueUpdateExports() { + return new Queue(queueUpdateExportName, false); + } + + @Bean + public DirectExchange exchangeUpdateExports() { + return new DirectExchange(exchangeUpdateExportName); + } + + @Bean + public Binding bindingQueueUpdateExports() { + return BindingBuilder.bind(queueUpdateExports()).to(exchangeUpdateExports()).with(routingkeyUpdateExportName); + } + + @Bean + public Queue queueUpdateStateSupply() { + return new Queue(queueUpdateStateSupplyName, false); + } + + @Bean + public DirectExchange exchangeUpdateStateSupply() { + return new DirectExchange(exchangeUpdateStateSupplyName); + } + + @Bean + public Binding bindingQueueUpdateStateSupply() { + return BindingBuilder.bind(queueUpdateStateSupply()).to(exchangeUpdateStateSupply()) + .with(routingkeyUpdateStateSupplyName); + } + + // queue result imports reference + + @Bean + public Queue queueResultImport() { + return new Queue(queueResultImportName, false); + } + + @Bean + public DirectExchange exchangeResultImport() { + return new DirectExchange(exchangeResultImportName); + } + + @Bean + public Binding bindingQueueResultImport() { + return BindingBuilder.bind(queueResultImport()).to(exchangeResultImport()).with(routingkeyResultImportName); + } + + // queue result exports reference + + @Bean + public Queue queueResultExport() { + return new Queue(queueResultExportName, false); + } + + @Bean + public DirectExchange exchangeResultExport() { + return new DirectExchange(exchangeResultExportName); + } + + @Bean + public Binding bindingQueueResultExport() { + return BindingBuilder.bind(queueResultExport()).to(exchangeResultExport()).with(routingkeyResultExportName); + } + + @Bean + public Jackson2JsonMessageConverter jsonMessageConverter() { + return new Jackson2JsonMessageConverter(); + } + + @Bean + public AmqpTemplate rabbitTemplate(ConnectionFactory connectionFactory) { + final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); + rabbitTemplate.setMessageConverter(jsonMessageConverter()); + return rabbitTemplate; + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultExportListener.java b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultExportListener.java index 1868eca..f506cba 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultExportListener.java +++ b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultExportListener.java @@ -1,156 +1,37 @@ package com.ai.st.microservice.workspaces.rabbitmq.listeners; import com.ai.st.microservice.common.dto.ili.MicroserviceResultExportDto; -import com.ai.st.microservice.common.dto.providers.*; -import com.ai.st.microservice.common.dto.supplies.MicroserviceCreateSupplyAttachmentDto; - -import com.ai.st.microservice.workspaces.dto.providers.*; -import com.ai.st.microservice.workspaces.business.CrytpoBusiness; -import com.ai.st.microservice.workspaces.business.DatabaseIntegrationBusiness; -import com.ai.st.microservice.workspaces.business.ProviderBusiness; -import com.ai.st.microservice.workspaces.business.SupplyBusiness; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - @Component public class RabbitMQResultExportListener { - @Value("${st.filesDirectory}") - private String stFilesDirectory; - - @Value("${st.ftp.host}") - private String hostFTP; - - @Value("${st.ftp.port}") - private int portFTP; - private final Logger log = LoggerFactory.getLogger(this.getClass()); - private final ProviderBusiness providerBusiness; - private final DatabaseIntegrationBusiness databaseIntegration; - private final CrytpoBusiness cryptoBusiness; - private final SupplyBusiness supplyBusiness; - - public RabbitMQResultExportListener(ProviderBusiness providerBusiness, DatabaseIntegrationBusiness databaseIntegration, - CrytpoBusiness cryptoBusiness, SupplyBusiness supplyBusiness) { - this.providerBusiness = providerBusiness; - this.databaseIntegration = databaseIntegration; - this.cryptoBusiness = cryptoBusiness; - this.supplyBusiness = supplyBusiness; - } - @RabbitListener(queues = "${st.rabbitmq.queueResultExport.queue}", concurrency = "${st.rabbitmq.queueResultExport.concurrency}") - public void updateIntegration(MicroserviceResultExportDto resultDto) { + public void updateResultExport(MicroserviceResultExportDto resultDto) { log.info("procesando resultado de la exportación ... " + resultDto.getReference()); try { String[] reference = resultDto.getReference().split("-"); - String typeResult = reference[0]; if (typeResult.equalsIgnoreCase("export")) { - Long supplyRequestedId = Long.parseLong(reference[1]); - Long requestId = Long.parseLong(reference[2]); - Long userId = Long.parseLong(reference[3]); - - MicroserviceSupplyRevisionDto supplyRevisionDto = providerBusiness - .getSupplyRevisionFromSupplyRequested(supplyRequestedId); - - if (resultDto.getResult()) { - - // save zip file - - CustomRequestDto requestDto = providerBusiness.getRequestById(requestId); - - List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); - - CustomSupplyRequestedDto supplyRequestedDto = suppliesRequestDto.stream() - .filter(sR -> sR.getId().equals(supplyRequestedId)).findAny().orElse(null); - - String urlDocumentaryRepository = resultDto.getPathFile(); - - log.info("url file (snr export): " + urlDocumentaryRepository); - - // update state and URL from supply requested - - MicroserviceUpdateSupplyRequestedDto updateSupplyData = new MicroserviceUpdateSupplyRequestedDto(); - updateSupplyData.setSupplyRequestedStateId(ProviderBusiness.SUPPLY_REQUESTED_STATE_ACCEPTED); - updateSupplyData.setUrl(urlDocumentaryRepository); - providerBusiness.updateSupplyRequested(requestId, supplyRequestedId, updateSupplyData); - - MicroserviceUpdateSupplyRevisionDto updateRevisionData = new MicroserviceUpdateSupplyRevisionDto(); - updateRevisionData.setFinishedBy(userId); - providerBusiness.updateSupplyRevision(supplyRequestedId, supplyRevisionDto.getId(), - updateRevisionData); - - // close request - providerBusiness.closeRequest(requestId, userId); - - // create supply - - List attachments = new ArrayList<>(); - - attachments.add(new MicroserviceCreateSupplyAttachmentDto(urlDocumentaryRepository, - SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_SUPPLY)); - - String ftpData = null; - try { - ftpData = "Servidor: " + hostFTP + " Puerto: " + portFTP + " Usuario: " - + cryptoBusiness.decrypt(supplyRevisionDto.getUsername()) + " Contraseña: " - + cryptoBusiness.decrypt(supplyRevisionDto.getPassword()); - } catch (Exception e) { - log.error("Error creando información FTP: " + e.getMessage()); - } - - attachments.add(new MicroserviceCreateSupplyAttachmentDto(ftpData, - SupplyBusiness.SUPPLY_ATTACHMENT_TYPE_FTP)); - - List emittersResponse = requestDto.getEmitters(); - List emittersRequestDto = - emittersResponse.stream().map(CustomEmitterDto::new).collect(Collectors.toList()); - - CustomEmitterDto emitterDto = emittersRequestDto.stream(). - filter(e -> e.getEmitterType().equalsIgnoreCase("ENTITY")).findAny().orElse(null); - - supplyBusiness.createSupply(requestDto.getMunicipalityCode(), supplyRequestedDto.getObservations(), - supplyRequestedDto.getTypeSupply().getId(), emitterDto.getEmitterCode(), attachments, requestId, userId, - requestDto.getProvider().getId(), null, null, supplyRequestedDto.getModelVersion(), - SupplyBusiness.SUPPLY_STATE_ACTIVE, supplyRequestedDto.getTypeSupply().getName(), supplyRequestedDto.getValid()); - - // delete database - try { - databaseIntegration.dropDatabase(cryptoBusiness.decrypt(supplyRevisionDto.getDatabase()), - cryptoBusiness.decrypt(supplyRevisionDto.getUsername())); - } catch (Exception e) { - log.error("No se ha podido borrar la base de datos: " + e.getMessage()); - } - - } else { - - providerBusiness.updateStateToSupplyRequested(requestId, supplyRequestedId, - ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW); - - } - - log.info("se realizaron los procesos del resultado: " + resultDto.getResult()); - } } catch (Exception e) { - log.error("Ha ocurrido un error actualizando el resultado de la exportación: " + e.getMessage()); + String messageError = String.format( + "Error procesando el resultado de la exportación con referencia %s : %s", resultDto.getReference(), + e.getMessage()); + SCMTracing.sendError(messageError); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultImportListener.java b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultImportListener.java index 3ef9e49..bda2654 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultImportListener.java +++ b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQResultImportListener.java @@ -1,10 +1,8 @@ package com.ai.st.microservice.workspaces.rabbitmq.listeners; import com.ai.st.microservice.common.dto.ili.MicroserviceResultImportDto; -import com.ai.st.microservice.common.dto.providers.MicroserviceSupplyRevisionDto; - -import com.ai.st.microservice.workspaces.business.ProviderBusiness; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; @@ -15,14 +13,8 @@ public class RabbitMQResultImportListener { private final Logger log = LoggerFactory.getLogger(this.getClass()); - private final ProviderBusiness providerBusiness; - - public RabbitMQResultImportListener(ProviderBusiness providerBusiness) { - this.providerBusiness = providerBusiness; - } - @RabbitListener(queues = "${st.rabbitmq.queueResultImport.queue}", concurrency = "${st.rabbitmq.queueResultImport.concurrency}") - public void updateIntegration(MicroserviceResultImportDto resultDto) { + public void resultImportProcess(MicroserviceResultImportDto resultDto) { log.info("procesando resultado de la importación ... " + resultDto.getReference()); @@ -34,34 +26,14 @@ public void updateIntegration(MicroserviceResultImportDto resultDto) { if (typeResult.equalsIgnoreCase("import")) { - Long supplyRequestedId = Long.parseLong(reference[1]); - Long requestId = Long.parseLong(reference[2]); - - MicroserviceSupplyRevisionDto supplyRevisionDto = providerBusiness - .getSupplyRevisionFromSupplyRequested(supplyRequestedId); - - if (supplyRevisionDto == null || !resultDto.getResult()) { - providerBusiness.updateStateToSupplyRequested(requestId, supplyRequestedId, - ProviderBusiness.SUPPLY_REQUESTED_STATE_PENDING_REVIEW); - } - - if (resultDto.getResult()) { - - providerBusiness.updateStateToSupplyRequested(requestId, supplyRequestedId, - ProviderBusiness.SUPPLY_REQUESTED_STATE_IN_REVIEW); - - } else { - - providerBusiness.deleteSupplyRevision(supplyRequestedId, supplyRevisionDto.getId()); - - } - - log.info("se realizaron los procesos del resultado: " + resultDto.getResult()); - } } catch (Exception e) { - log.error("Ha ocurrido un error actualizando el resultado de la importación: " + e.getMessage()); + String messageError = String.format( + "Error procesando el resultado de la importación con referencia %s : %s", resultDto.getReference(), + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateExportIntegrationListener.java b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateExportIntegrationListener.java index 51dcf33..28ca34d 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateExportIntegrationListener.java +++ b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateExportIntegrationListener.java @@ -21,6 +21,7 @@ import com.ai.st.microservice.workspaces.entities.WorkspaceEntity; import com.ai.st.microservice.workspaces.services.IntegrationService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; @@ -46,10 +47,11 @@ public class RabbitMQUpdateExportIntegrationListener { private final IntegrationService integrationService; private final AdministrationBusiness administrationBusiness; - public RabbitMQUpdateExportIntegrationListener(IntegrationBusiness integrationBusiness, ManagerMicroserviceBusiness managerBusiness, - NotificationBusiness notificationBusiness, DatabaseIntegrationBusiness databaseIntegration, - CrytpoBusiness cryptoBusiness, SupplyBusiness supplyBusiness, IntegrationService integrationService, - AdministrationBusiness administrationBusiness) { + public RabbitMQUpdateExportIntegrationListener(IntegrationBusiness integrationBusiness, + ManagerMicroserviceBusiness managerBusiness, NotificationBusiness notificationBusiness, + DatabaseIntegrationBusiness databaseIntegration, CrytpoBusiness cryptoBusiness, + SupplyBusiness supplyBusiness, IntegrationService integrationService, + AdministrationBusiness administrationBusiness) { this.integrationBusiness = integrationBusiness; this.managerBusiness = managerBusiness; this.notificationBusiness = notificationBusiness; @@ -99,29 +101,34 @@ public void updateExport(MicroserviceIliExportResultDto resultExportDto) { // load supply to municipality String observations = "Archivo XTF generado para el modelo de insumos"; - CustomSupplyDto supplyCadastralDto = supplyBusiness.getSupplyById(integrationEntity.getSupplyCadastreId()); - CustomSupplyDto supplyRegistralDto = supplyBusiness.getSupplyById(integrationEntity.getSupplySnrId()); + CustomSupplyDto supplyCadastralDto = supplyBusiness + .getSupplyById(integrationEntity.getSupplyCadastreId()); + CustomSupplyDto supplyRegistralDto = supplyBusiness + .getSupplyById(integrationEntity.getSupplySnrId()); boolean isValid = supplyCadastralDto.getValid() && supplyRegistralDto.getValid(); - supplyBusiness.createSupply(municipalityCode, observations, null, integrationEntity.getManagerCode(), attachments, null, - null, null, integrationEntity.getManagerCode(), null, resultExportDto.getModelVersion(), - SupplyBusiness.SUPPLY_STATE_ACTIVE, "Datos en modelo de insumos para el Municipio", isValid); + supplyBusiness.createSupply(municipalityCode, observations, null, + integrationEntity.getManagerCode(), attachments, null, null, null, + integrationEntity.getManagerCode(), null, resultExportDto.getModelVersion(), + SupplyBusiness.SUPPLY_STATE_ACTIVE, "Datos en modelo de insumos para el Municipio", + isValid); /* * try { // delete database - * databaseIntegration.dropDatabase(cryptoBusiness.decrypt(integrationEntity. - * getDatabase()), cryptoBusiness.decrypt(integrationEntity.getUsername())); } - * catch (Exception e) { log.error("No se ha podido borrar la base de datos: " + - * e.getMessage()); } + * databaseIntegration.dropDatabase(cryptoBusiness.decrypt(integrationEntity. getDatabase()), + * cryptoBusiness.decrypt(integrationEntity.getUsername())); } catch (Exception e) { + * log.error("No se ha podido borrar la base de datos: " + e.getMessage()); } */ - // integrationBusiness.configureViewIntegration(integrationEntity.getId(), integrationEntity.getManagerCode()); + // integrationBusiness.configureViewIntegration(integrationEntity.getId(), + // integrationEntity.getManagerCode()); // send notification try { - List directors = managerBusiness.getUserByManager(integrationEntity.getManagerCode(), + List directors = managerBusiness.getUsersByManager( + integrationEntity.getManagerCode(), new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_DIRECTOR_MANAGER))); for (MicroserviceManagerUserDto directorDto : directors) { @@ -136,13 +143,15 @@ public void updateExport(MicroserviceIliExportResultDto resultExportDto) { } } catch (Exception e) { - log.error("Error enviando notificación de producto generado: " + e.getMessage()); + String messageError = String.format("Error enviando notificación de producto generado : %s", + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } else { - stateId = IntegrationStateBusiness.STATE_ERROR_GENERATING_PRODUCT; - log.error("Export finished with errors"); + log.warn("Export finished with errors"); } String logErrors = null; @@ -154,18 +163,26 @@ public void updateExport(MicroserviceIliExportResultDto resultExportDto) { logErrors = errors.toString(); } - integrationBusiness.updateStateToIntegration(resultExportDto.getIntegrationId(), stateId, logErrors, null, null, "SISTEMA"); + integrationBusiness.updateStateToIntegration(resultExportDto.getIntegrationId(), stateId, logErrors, + null, null, "SISTEMA"); } } catch (Exception e) { - log.info("Error update export integration: " + e.getMessage()); + String messageError = String.format("Error actualizando la exportación de la integración %d : %s", + resultExportDto.getIntegrationId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); Long stateId = IntegrationStateBusiness.STATE_ERROR_GENERATING_PRODUCT; try { - integrationBusiness.updateStateToIntegration(resultExportDto.getIntegrationId(), stateId, e.getMessage(), null, null, "SISTEMA"); + integrationBusiness.updateStateToIntegration(resultExportDto.getIntegrationId(), stateId, + e.getMessage(), null, null, "SISTEMA"); } catch (BusinessException e1) { - log.error("Error actualizando el estado de la integración por error: " + e.getMessage()); + String messageErrorII = String.format("Error actualizando el estado de la integración %d : %s", + resultExportDto.getIntegrationId(), e.getMessage()); + SCMTracing.sendError(messageErrorII); + log.error(messageErrorII); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateIntegrationListener.java b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateIntegrationListener.java index a10d2ec..cac3364 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateIntegrationListener.java +++ b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateIntegrationListener.java @@ -17,6 +17,7 @@ import com.ai.st.microservice.workspaces.services.IIntegrationService; import com.ai.st.microservice.workspaces.services.IIntegrationStateService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; @@ -38,9 +39,10 @@ public class RabbitMQUpdateIntegrationListener { private final IIntegrationStateService integrationStateService; private final AdministrationBusiness administrationBusiness; - public RabbitMQUpdateIntegrationListener(IntegrationBusiness integrationBusiness, NotificationBusiness notificationBusiness, - ManagerMicroserviceBusiness managerBusiness, IIntegrationService integrationService, - IIntegrationStateService integrationStateService, AdministrationBusiness administrationBusiness) { + public RabbitMQUpdateIntegrationListener(IntegrationBusiness integrationBusiness, + NotificationBusiness notificationBusiness, ManagerMicroserviceBusiness managerBusiness, + IIntegrationService integrationService, IIntegrationStateService integrationStateService, + AdministrationBusiness administrationBusiness) { this.integrationBusiness = integrationBusiness; this.notificationBusiness = notificationBusiness; this.managerBusiness = managerBusiness; @@ -64,7 +66,7 @@ public void updateIntegration(MicroserviceIntegrationStatDto integrationStats) { log.info("Integration automatic finished successful"); } else { stateId = IntegrationStateBusiness.STATE_ERROR_INTEGRATION_AUTOMATIC; - log.info("Integration automatic finished with errors"); + log.warn("Integration automatic finished with errors"); } // send notification @@ -78,7 +80,8 @@ public void updateIntegration(MicroserviceIntegrationStatDto integrationStats) { WorkspaceEntity workspaceEntity = integrationEntity.getWorkspace(); MunicipalityEntity municipalityEntity = workspaceEntity.getMunicipality(); - List directors = managerBusiness.getUserByManager(integrationEntity.getManagerCode(), + List directors = managerBusiness.getUsersByManager( + integrationEntity.getManagerCode(), new ArrayList<>(Collections.singletonList(RoleBusiness.SUB_ROLE_DIRECTOR_MANAGER))); for (MicroserviceManagerUserDto directorDto : directors) { @@ -93,8 +96,11 @@ public void updateIntegration(MicroserviceIntegrationStatDto integrationStats) { } } catch (Exception e) { - log.error("Error enviando notificación informando estado de la integración automática: " - + e.getMessage()); + String messageError = String.format( + "Error enviando notificación informando el estado de la integración automática %d : %s", + integrationStats.getIntegrationId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } String logErrors = null; @@ -106,11 +112,14 @@ public void updateIntegration(MicroserviceIntegrationStatDto integrationStats) { logErrors = errors.toString(); } - integrationBusiness.updateStateToIntegration(integrationStats.getIntegrationId(), stateId, logErrors, null, null, - "SISTEMA"); + integrationBusiness.updateStateToIntegration(integrationStats.getIntegrationId(), stateId, logErrors, null, + null, "SISTEMA"); } catch (Exception e) { - log.error("Error RabbitMQUpdateIntegrationListener@updateIntegration#Business ---> " + e.getMessage()); + String messageError = String.format("Error procesando el resultado de la integración automática %d : %s", + integrationStats.getIntegrationId(), e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateStateSupplyListener.java b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateStateSupplyListener.java index 8c29970..af8e8eb 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateStateSupplyListener.java +++ b/src/main/java/com/ai/st/microservice/workspaces/rabbitmq/listeners/RabbitMQUpdateStateSupplyListener.java @@ -15,6 +15,7 @@ import com.ai.st.microservice.workspaces.entities.MunicipalityEntity; import com.ai.st.microservice.workspaces.services.IMunicipalityService; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,8 +37,9 @@ public class RabbitMQUpdateStateSupplyListener { private final IMunicipalityService municipalityService; private final AdministrationBusiness administrationBusiness; - public RabbitMQUpdateStateSupplyListener(ProviderFeignClient providerClient, NotificationBusiness notificationBusiness, - IMunicipalityService municipalityService, AdministrationBusiness administrationBusiness) { + public RabbitMQUpdateStateSupplyListener(ProviderFeignClient providerClient, + NotificationBusiness notificationBusiness, IMunicipalityService municipalityService, + AdministrationBusiness administrationBusiness) { this.providerClient = providerClient; this.notificationBusiness = notificationBusiness; this.municipalityService = municipalityService; @@ -70,7 +72,10 @@ public void updateIntegration(MicroserviceValidationDto validationDto) { try { FileUtils.deleteQuietly(new File(validationDto.getFilenameTemporal())); } catch (Exception e) { - log.error("No se ha podido eliminar el insumo rechazado: " + e.getMessage()); + String messageError = String.format("Error eliminando el insumo físico rechazado : %s", + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -80,8 +85,8 @@ public void updateIntegration(MicroserviceValidationDto validationDto) { try { List suppliesResponse = requestDto.getSuppliesRequested(); - List suppliesRequestDto = - suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); + List suppliesRequestDto = suppliesResponse.stream() + .map(CustomSupplyRequestedDto::new).collect(Collectors.toList()); CustomSupplyRequestedDto supplyRequestedDto = suppliesRequestDto.stream() .filter(supply -> supply.getId().equals(validationDto.getSupplyRequestedId())).findAny() @@ -92,14 +97,17 @@ public void updateIntegration(MicroserviceValidationDto validationDto) { MicroserviceUserDto userDto = administrationBusiness.getUserById(supplyRequestedDto.getDeliveredBy()); if (userDto != null && userDto.getEnabled()) { - notificationBusiness.sendNotificationLoadOfInputs(userDto.getEmail(), userDto.getId(), - xtfAccept, municipalityEntity.getName(), - municipalityEntity.getDepartment().getName(), validationDto.getRequestId().toString(), - new Date(), ""); + notificationBusiness.sendNotificationLoadOfInputs(userDto.getEmail(), userDto.getId(), xtfAccept, + municipalityEntity.getName(), municipalityEntity.getDepartment().getName(), + validationDto.getRequestId().toString(), new Date(), ""); } } catch (Exception e) { - log.error("Error enviando notificación para informar de la carga del insumo: " + e.getMessage()); + String messageError = String.format( + "Error enviando notificación para informar de la carga del archivo XTF en el módulo de insumos : %s", + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } // update request @@ -125,6 +133,11 @@ public void updateIntegration(MicroserviceValidationDto validationDto) { } catch (Exception e) { log.error("Ha ocurrido un error actualizando el estado del insumo: " + e.getMessage()); + String messageError = String.format( + "Error procesando el resultado de la carga de un archivo XTF en el módulo de insumos : %s", + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/repositories/DepartmentRepository.java b/src/main/java/com/ai/st/microservice/workspaces/repositories/DepartmentRepository.java index b25af44..cac5160 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/repositories/DepartmentRepository.java +++ b/src/main/java/com/ai/st/microservice/workspaces/repositories/DepartmentRepository.java @@ -10,12 +10,12 @@ public interface DepartmentRepository extends CrudRepository { - @Override - List findAll(); + @Override + List findAll(); - @Query(nativeQuery = true, value = "select\n" + " distinct d.*\n" + "from\n" + " workspaces.departments d,\n" - + " workspaces.municipalities m,\n" + " workspaces.workspaces w,\n" + " workspaces.workspace_managers wm\n" - + "where\n" + " w.municipality_id = m.id\n" + " and m.department_id = d.id\n" - + " and wm.workspace_id = w.id \n" + " and wm.manager_code = :managerCode \n" + " and w.is_active = true") - List getDepartmentsByManagerCode(@Param("managerCode") Long managerCode); + @Query(nativeQuery = true, value = "select\n" + " distinct d.*\n" + "from\n" + " workspaces.departments d,\n" + + " workspaces.municipalities m,\n" + " workspaces.workspaces w,\n" + " workspaces.workspace_managers wm\n" + + "where\n" + " w.municipality_id = m.id\n" + " and m.department_id = d.id\n" + + " and wm.workspace_id = w.id \n" + " and wm.manager_code = :managerCode \n" + " and w.is_active = true") + List getDepartmentsByManagerCode(@Param("managerCode") Long managerCode); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/repositories/IntegrationRepository.java b/src/main/java/com/ai/st/microservice/workspaces/repositories/IntegrationRepository.java index 2ace84e..196ad2d 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/repositories/IntegrationRepository.java +++ b/src/main/java/com/ai/st/microservice/workspaces/repositories/IntegrationRepository.java @@ -16,25 +16,19 @@ public interface IntegrationRepository extends CrudRepository findIntegrationsByWorkspaceAndStates(@Param("workspaceId") Long workspaceId, - @Param("statesId") List statesId); + @Param("statesId") List statesId); List findByWorkspaceAndManagerCode(WorkspaceEntity workspace, Long managerCode); - IntegrationEntity findBySupplyCadastreIdAndSupplySnrIdAndStateAndManagerCode(Long supplyCadastreId, Long supplySnrId, - IntegrationStateEntity state, Long managerCode); + IntegrationEntity findBySupplyCadastreIdAndSupplySnrIdAndStateAndManagerCode(Long supplyCadastreId, + Long supplySnrId, IntegrationStateEntity state, Long managerCode); List findByWorkspaceInAndManagerCode(List workspaces, Long managerCode); - @Query(nativeQuery = true, value = "select\n" + - "\ti.*\n" + - "from\n" + - "\tworkspaces.integrations i\n" + - "where\n" + - "\ti.integration_state_id in (:statesId)\n" + - "\tand i.workspace_id = :workspaceId\n" + - "\tand i.manager_code = :managerCode") + @Query(nativeQuery = true, value = "select\n" + "\ti.*\n" + "from\n" + "\tworkspaces.integrations i\n" + "where\n" + + "\ti.integration_state_id in (:statesId)\n" + "\tand i.workspace_id = :workspaceId\n" + + "\tand i.manager_code = :managerCode") List findIntegrationsPending(@Param("workspaceId") Long workspaceId, - @Param("statesId") List statesId, - @Param("managerCode") Long managerCode); + @Param("statesId") List statesId, @Param("managerCode") Long managerCode); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/repositories/MunicipalityRepository.java b/src/main/java/com/ai/st/microservice/workspaces/repositories/MunicipalityRepository.java index 9cc0a07..4299987 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/repositories/MunicipalityRepository.java +++ b/src/main/java/com/ai/st/microservice/workspaces/repositories/MunicipalityRepository.java @@ -10,38 +10,38 @@ public interface MunicipalityRepository extends CrudRepository { - @Query("SELECT m FROM MunicipalityEntity m WHERE m.department.id = :departmentId") - List getMunicipalitiesByDepartmentId(@Param("departmentId") Long departmentId); - - @Query(nativeQuery = true, value = "select\n" + " m.*\n" + "from\n" + " workspaces.municipalities m,\n" - + " workspaces.workspaces w,\n" + " workspaces.workspace_managers wm \n" + "where\n" - + " w.municipality_id = m.id\n" + " and wm.workspace_id = w.id \n" - + " and wm.manager_code = :managerCode \n" + " and m.department_id = :departmentId \n" - + " and w.is_active = true") - List getMunicipalitiesByDepartmentIdAndManagerCode(@Param("departmentId") Long departmentId, - @Param("managerCode") Long managerCode); - - MunicipalityEntity findByCode(String code); - - @Query(nativeQuery = true, value = "select\n" + " m.* \n" + "from\n" + " workspaces.municipalities m,\n" - + " workspaces.workspaces w,\n" + " workspaces.workspace_managers wm \n" + "where\n" - + " m.id = w.municipality_id\n" + " and w.id = wm.workspace_id\n" + " and wm.manager_code = :managerCode") - List getMunicipalitiesByManagerCode(@Param("managerCode") Long managerCode); - - @Query(nativeQuery = true, value = "select\n" + " m.*\n" + "from\n" - + " workspaces.municipalities m, workspaces.departments d\n" + "where\n" + " d.id = m.department_id \n" - + " and d.id = :departmentId \n" + " and m.id not in (\n" + " select\n" + " m2.id\n" - + " from\n" + " workspaces.municipalities m2 , workspaces.workspaces w\n" + " where\n" - + " w.municipality_id = m2.id)") - List getMunicipalitiesNotWorkspaceInDepartment(@Param("departmentId") Long departmentId); - - @Query(nativeQuery = true, value = "select\n" + " m.*\n" + "from\n" + " workspaces.municipalities m,\n" - + " workspaces.departments d\n" + "where\n" + " d.id = m.department_id\n" + " and d.id = :departmentId \n" - + " and m.id not in (\n" + " select\n" + " m2.id\n" + " from\n" - + " workspaces.municipalities m2 ,\n" + " workspaces.workspaces w,\n" - + " workspaces.workspace_managers wm\n" + " where\n" - + " w.municipality_id = m2.id and wm.manager_code = :managerCode and wm.workspace_id = w.id)") - List getMunicipalitiesWhereManagerDoesNotBelongIn(@Param("managerCode") Long managerCode, - @Param("departmentId") Long departmentId); + @Query("SELECT m FROM MunicipalityEntity m WHERE m.department.id = :departmentId") + List getMunicipalitiesByDepartmentId(@Param("departmentId") Long departmentId); + + @Query(nativeQuery = true, value = "select\n" + " m.*\n" + "from\n" + " workspaces.municipalities m,\n" + + " workspaces.workspaces w,\n" + " workspaces.workspace_managers wm \n" + "where\n" + + " w.municipality_id = m.id\n" + " and wm.workspace_id = w.id \n" + + " and wm.manager_code = :managerCode \n" + " and m.department_id = :departmentId \n" + + " and w.is_active = true") + List getMunicipalitiesByDepartmentIdAndManagerCode(@Param("departmentId") Long departmentId, + @Param("managerCode") Long managerCode); + + MunicipalityEntity findByCode(String code); + + @Query(nativeQuery = true, value = "select\n" + " m.* \n" + "from\n" + " workspaces.municipalities m,\n" + + " workspaces.workspaces w,\n" + " workspaces.workspace_managers wm \n" + "where\n" + + " m.id = w.municipality_id\n" + " and w.id = wm.workspace_id\n" + " and wm.manager_code = :managerCode") + List getMunicipalitiesByManagerCode(@Param("managerCode") Long managerCode); + + @Query(nativeQuery = true, value = "select\n" + " m.*\n" + "from\n" + + " workspaces.municipalities m, workspaces.departments d\n" + "where\n" + " d.id = m.department_id \n" + + " and d.id = :departmentId \n" + " and m.id not in (\n" + " select\n" + " m2.id\n" + + " from\n" + " workspaces.municipalities m2 , workspaces.workspaces w\n" + " where\n" + + " w.municipality_id = m2.id)") + List getMunicipalitiesNotWorkspaceInDepartment(@Param("departmentId") Long departmentId); + + @Query(nativeQuery = true, value = "select\n" + " m.*\n" + "from\n" + " workspaces.municipalities m,\n" + + " workspaces.departments d\n" + "where\n" + " d.id = m.department_id\n" + " and d.id = :departmentId \n" + + " and m.id not in (\n" + " select\n" + " m2.id\n" + " from\n" + + " workspaces.municipalities m2 ,\n" + " workspaces.workspaces w,\n" + + " workspaces.workspace_managers wm\n" + " where\n" + + " w.municipality_id = m2.id and wm.manager_code = :managerCode and wm.workspace_id = w.id)") + List getMunicipalitiesWhereManagerDoesNotBelongIn(@Param("managerCode") Long managerCode, + @Param("departmentId") Long departmentId); } diff --git a/src/main/java/com/ai/st/microservice/workspaces/repositories/WorkspaceRepository.java b/src/main/java/com/ai/st/microservice/workspaces/repositories/WorkspaceRepository.java index 24b811e..a375148 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/repositories/WorkspaceRepository.java +++ b/src/main/java/com/ai/st/microservice/workspaces/repositories/WorkspaceRepository.java @@ -17,15 +17,9 @@ public interface WorkspaceRepository extends CrudRepository findByManagerCode(@Param("managerCode") Long departmentId); @Query(nativeQuery = true, value = "select\n" + " w.*\n" + "from\n" + " workspaces.workspaces w,\n" diff --git a/src/main/java/com/ai/st/microservice/workspaces/services/IIntegrationService.java b/src/main/java/com/ai/st/microservice/workspaces/services/IIntegrationService.java index 2ec1fae..9988d57 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/services/IIntegrationService.java +++ b/src/main/java/com/ai/st/microservice/workspaces/services/IIntegrationService.java @@ -20,8 +20,8 @@ public interface IIntegrationService { List getIntegrationByWorkspace(WorkspaceEntity workspaceEntity, Long managerCode); - IntegrationEntity getIntegrationByCadastreAndSnrAndState(Long cadastreId, Long snrId, - IntegrationStateEntity state, Long managerCode); + IntegrationEntity getIntegrationByCadastreAndSnrAndState(Long cadastreId, Long snrId, IntegrationStateEntity state, + Long managerCode); void deleteIntegration(Long id); diff --git a/src/main/java/com/ai/st/microservice/workspaces/services/IntegrationService.java b/src/main/java/com/ai/st/microservice/workspaces/services/IntegrationService.java index 155f6d8..c1bb8f2 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/services/IntegrationService.java +++ b/src/main/java/com/ai/st/microservice/workspaces/services/IntegrationService.java @@ -28,7 +28,7 @@ public IntegrationEntity createIntegration(IntegrationEntity integrationEntity) @Override public IntegrationEntity getIntegrationByWorkspaceAndState(WorkspaceEntity workspace, - IntegrationStateEntity state) { + IntegrationStateEntity state) { return integrationRepository.findByWorkspaceAndState(workspace, state); } @@ -55,8 +55,9 @@ public List getIntegrationByWorkspace(WorkspaceEntity workspa @Override public IntegrationEntity getIntegrationByCadastreAndSnrAndState(Long cadastreId, Long snrId, - IntegrationStateEntity state, Long managerCode) { - return integrationRepository.findBySupplyCadastreIdAndSupplySnrIdAndStateAndManagerCode(cadastreId, snrId, state, managerCode); + IntegrationStateEntity state, Long managerCode) { + return integrationRepository.findBySupplyCadastreIdAndSupplySnrIdAndStateAndManagerCode(cadastreId, snrId, + state, managerCode); } @Override diff --git a/src/main/java/com/ai/st/microservice/workspaces/services/tracing/SCMTracing.java b/src/main/java/com/ai/st/microservice/workspaces/services/tracing/SCMTracing.java new file mode 100644 index 0000000..765201b --- /dev/null +++ b/src/main/java/com/ai/st/microservice/workspaces/services/tracing/SCMTracing.java @@ -0,0 +1,39 @@ +package com.ai.st.microservice.workspaces.services.tracing; + +import com.newrelic.api.agent.NewRelic; + +public class SCMTracing { + + public static void setTransactionName(String transactionName) { + NewRelic.setTransactionName("SCM", transactionName); + } + + public static void sendError(String message) { + NewRelic.noticeError(message); + } + + public static void addCustomParameter(TracingKeyword key, Number value) { + NewRelic.addCustomParameter(key.getValue(), value); + } + + public static void addCustomParameter(TracingKeyword key, String value) { + NewRelic.addCustomParameter(key.getValue(), value); + } + + public static void addCustomParameter(TracingKeyword key, boolean value) { + NewRelic.addCustomParameter(key.getValue(), value); + } + + public static void addCustomParameter(String key, String value) { + NewRelic.addCustomParameter(key, value); + } + + public static void addCustomParameter(String key, Number value) { + NewRelic.addCustomParameter(key, value); + } + + public static void addCustomParameter(String key, boolean value) { + NewRelic.addCustomParameter(key, value); + } + +} diff --git a/src/main/java/com/ai/st/microservice/workspaces/services/tracing/TracingKeyword.java b/src/main/java/com/ai/st/microservice/workspaces/services/tracing/TracingKeyword.java new file mode 100644 index 0000000..4528ef9 --- /dev/null +++ b/src/main/java/com/ai/st/microservice/workspaces/services/tracing/TracingKeyword.java @@ -0,0 +1,20 @@ +package com.ai.st.microservice.workspaces.services.tracing; + +public enum TracingKeyword { + USER_ID("userId"), USER_NAME("username"), USER_EMAIL("userEmail"), MANAGER_ID("managerId"), + MANAGER_NAME("managerName"), AUTHORIZATION_HEADER("authorizationHeader"), DEPARTMENT_ID("departmentId"), + IS_SUPER_ADMIN("isSuperAdmin"), IS_ADMIN("isAdmin"), IS_MANAGER("isManager"), IS_PROVIDER("isProvider"), + IS_OPERATOR("isOperator"), BODY_REQUEST("bodyRequest"), PROVIDER_ID("providerId"), PROVIDER_NAME("providerName"), + OPERATOR_ID("operatorId"), OPERATOR_NAME("operatorName"); + + private final String value; + + TracingKeyword(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + +} diff --git a/src/main/java/com/ai/st/microservice/workspaces/swagger/SwaggerConfig.java b/src/main/java/com/ai/st/microservice/workspaces/swagger/SwaggerConfig.java index 58446d4..c218f0c 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/swagger/SwaggerConfig.java +++ b/src/main/java/com/ai/st/microservice/workspaces/swagger/SwaggerConfig.java @@ -18,19 +18,19 @@ @Configuration public class SwaggerConfig { - @Bean - public Docket usersApi() { - return new Docket(DocumentationType.SWAGGER_2).apiInfo(usersApiInfo()).select().paths(userPaths()) - .apis(RequestHandlerSelectors.any()).build().useDefaultResponseMessages(false); - } - - private ApiInfo usersApiInfo() { - return new ApiInfoBuilder().title("Microservice Workspaces").version("1.0") - .license("GNU AFFERO GENERAL PUBLIC LICENSE - Version 3").build(); - } - - private Predicate userPaths() { - return regex("/api.*"); - } + @Bean + public Docket usersApi() { + return new Docket(DocumentationType.SWAGGER_2).apiInfo(usersApiInfo()).select().paths(userPaths()) + .apis(RequestHandlerSelectors.any()).build().useDefaultResponseMessages(false); + } + + private ApiInfo usersApiInfo() { + return new ApiInfoBuilder().title("Microservice Workspaces").version("1.0") + .license("GNU AFFERO GENERAL PUBLIC LICENSE - Version 3").build(); + } + + private Predicate userPaths() { + return regex("/api.*"); + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/utils/FileTool.java b/src/main/java/com/ai/st/microservice/workspaces/utils/FileTool.java index fd7779f..6d46911 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/utils/FileTool.java +++ b/src/main/java/com/ai/st/microservice/workspaces/utils/FileTool.java @@ -6,42 +6,45 @@ import java.io.IOException; import java.io.Writer; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileTool { - private final static Logger log = LoggerFactory.getLogger(FileTool.class); + private final static Logger log = LoggerFactory.getLogger(FileTool.class); - public static File createSimpleFile(String content, String filename) { + public static File createSimpleFile(String content, String filename) { - File file = new File(filename); + File file = new File(filename); - try (Writer writer = new BufferedWriter(new FileWriter(file))) { - writer.write(content); - } catch (IOException e) { - log.error("Error creando archivo: " + e.getMessage()); - } + try (Writer writer = new BufferedWriter(new FileWriter(file))) { + writer.write(content); + } catch (IOException e) { + String messageError = String.format("Error creando archivo : %s", filename, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); + } - return file; - } + return file; + } - public static String removeAccents(String str) { + public static String removeAccents(String str) { - final String original = "ÁáÉéÍíÓóÚúÑñÜü"; - final String replace = "AaEeIiOoUuNnUu"; + final String original = "ÁáÉéÍíÓóÚúÑñÜü"; + final String replace = "AaEeIiOoUuNnUu"; - if (str == null) { - return null; - } - char[] array = str.toCharArray(); - for (int index = 0; index < array.length; index++) { - int pos = original.indexOf(array[index]); - if (pos > -1) { - array[index] = replace.charAt(pos); - } - } - return new String(array); - } + if (str == null) { + return null; + } + char[] array = str.toCharArray(); + for (int index = 0; index < array.length; index++) { + int pos = original.indexOf(array[index]); + if (pos > -1) { + array[index] = replace.charAt(pos); + } + } + return new String(array); + } } diff --git a/src/main/java/com/ai/st/microservice/workspaces/utils/ZipUtil.java b/src/main/java/com/ai/st/microservice/workspaces/utils/ZipUtil.java index b958cc7..1c23038 100644 --- a/src/main/java/com/ai/st/microservice/workspaces/utils/ZipUtil.java +++ b/src/main/java/com/ai/st/microservice/workspaces/utils/ZipUtil.java @@ -1,7 +1,6 @@ package com.ai.st.microservice.workspaces.utils; import java.io.*; -import java.nio.file.Files; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; @@ -9,6 +8,7 @@ import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; +import com.ai.st.microservice.workspaces.services.tracing.SCMTracing; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,7 +46,10 @@ public static boolean zipContainsFile(String filePathZip, List extension zipFile.close(); } catch (IOException e) { fileFound = false; - log.error("Error unzipping archive: " + e.getMessage()); + String messageError = String.format("Error descomprimiendo el archivo %s : %s", filePathZip, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return fileFound; @@ -68,48 +71,16 @@ public static List getExtensionsFromZip(String filePathZip) { zipFile.close(); } catch (IOException e) { - log.error("Error unzipping archive: " + e.getMessage()); + String messageError = String.format("Error descomprimiendo el archivo %s : %s", filePathZip, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return extensions; } - public static boolean unzipping(String filePathZip) { - - try { - - ZipFile zipFile = new ZipFile(filePathZip); - - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - InputStream stream = zipFile.getInputStream(entry); - - String fileEntryOutName = FilenameUtils.getFullPath(filePathZip) + entry.getName(); - FileOutputStream outputStream = new FileOutputStream(new File(fileEntryOutName)); - - int read = 0; - byte[] bytes = new byte[1024]; - - while ((read = stream.read(bytes)) != -1) { - outputStream.write(bytes, 0, read); - } - stream.close(); - outputStream.close(); - - } - - zipFile.close(); - - return true; - } catch (IOException e) { - log.error("Error unzipping archive: " + e.getMessage()); - } - - return false; - } - public static boolean zipMustContains(String filePathZip, List extensionsToSearch) { ZipFile zipFile = null; try { @@ -136,12 +107,17 @@ public static boolean zipMustContains(String filePathZip, List extension } } catch (IOException e) { - log.error("Error unzipping archive: " + e.getMessage()); + String messageError = String.format("Error descomprimiendo el archivo %s : %s", filePathZip, + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } finally { try { zipFile.close(); } catch (IOException e) { - e.printStackTrace(); + String messageError = String.format("Error cerrando archivo zip %s : %s", filePathZip, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } } @@ -170,7 +146,9 @@ public static String zipping(MultipartFile file, String zipName, String fileName return path; } catch (IOException e) { - log.error("Error zipping archive: " + e.getMessage()); + String messageError = String.format("Error comprimiendo el archivo %s : %s", zipName, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return null; @@ -210,10 +188,10 @@ public static String zipping(List files, String zipName, String namespace) return path; - } catch (IOException e) { - log.error("Error zipping archive (I): " + e.getMessage()); } catch (Exception e) { - log.error("Error zipping archive (II): " + e.getMessage()); + String messageError = String.format("Error comprimiendo el archivo %s : %s", zipName, e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return null; @@ -227,7 +205,6 @@ public static boolean hasGDBDatabase(String filePathZip) { ZipFile zipFile = new ZipFile(filePathZip); - Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); @@ -238,11 +215,13 @@ public static boolean hasGDBDatabase(String filePathZip) { } } - zipFile.close(); } catch (IOException e) { fileFound = false; - log.error("Error hasGDBDatabase: " + e.getMessage()); + String messageError = String.format("Error comprobando si el archivo zip tiene un archivo GDB : %s", + e.getMessage()); + SCMTracing.sendError(messageError); + log.error(messageError); } return fileFound; diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index e1f00bb..e2d2876 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -22,13 +22,16 @@ eureka: defaultZone: http://localhost:8761/eureka server: - port: 8964 - - + port: 8964 + +logging: + level: + org: + hibernate: + SQL: debug + feign: client: config: default: - connectTimeout: 160000000 - readTimeout: 160000000 - + loggerLevel: full \ No newline at end of file diff --git a/src/main/resources/db/migration/V1_0_0__database_definition.sql b/src/main/resources/db/migration/V1_0_0__database_definition.sql new file mode 100644 index 0000000..8c7c17b --- /dev/null +++ b/src/main/resources/db/migration/V1_0_0__database_definition.sql @@ -0,0 +1,1419 @@ +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + +CREATE SCHEMA IF NOT EXISTS workspaces; + +SET default_tablespace = ''; + +CREATE TABLE workspaces.departments ( + id bigint NOT NULL, + code character varying(255) NOT NULL, + name character varying(255) NOT NULL +); + +ALTER TABLE workspaces.departments ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.departments_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.integrations ( + id bigint NOT NULL, + database character varying(255) NOT NULL, + errors character varying(1000), + finished_at timestamp without time zone, + hostname character varying(255) NOT NULL, + manager_code bigint NOT NULL, + password character varying(255) NOT NULL, + port character varying(255) NOT NULL, + schema character varying(255) NOT NULL, + started_at timestamp without time zone NOT NULL, + supply_ant_id bigint, + supply_cadastre_id bigint NOT NULL, + supply_snr_id bigint NOT NULL, + url_map character varying(255), + username character varying(255) NOT NULL, + integration_state_id bigint NOT NULL, + workspace_id bigint NOT NULL +); + +CREATE TABLE workspaces.integrations_histories ( + id bigint NOT NULL, + created_at timestamp without time zone NOT NULL, + manager_code bigint, + user_code bigint, + user_name character varying(300) NOT NULL, + integration_id bigint NOT NULL, + integration_state_id bigint NOT NULL +); + +ALTER TABLE workspaces.integrations_histories ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.integrations_histories_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +ALTER TABLE workspaces.integrations ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.integrations_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.integrations_states ( + id bigint NOT NULL, + description character varying(255), + name character varying(255) NOT NULL +); + +ALTER TABLE workspaces.integrations_states ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.integrations_states_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.integrations_stats ( + id bigint NOT NULL, + ant_records_number bigint, + cadastre_records_number bigint NOT NULL, + created_at timestamp without time zone NOT NULL, + match_number bigint NOT NULL, + percentage double precision NOT NULL, + snr_records_number bigint NOT NULL, + integration_id bigint NOT NULL +); + +ALTER TABLE workspaces.integrations_stats ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.integrations_stats_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.municipalities ( + id bigint NOT NULL, + code character varying(255) NOT NULL, + name character varying(255) NOT NULL, + department_id bigint NOT NULL +); + +ALTER TABLE workspaces.municipalities ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.municipalities_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.workspace_managers ( + id bigint NOT NULL, + manager_code bigint NOT NULL, + observations character varying(500) NOT NULL, + start_date date NOT NULL, + support character varying(1000) NOT NULL, + workspace_id bigint NOT NULL +); + +ALTER TABLE workspaces.workspace_managers ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.workspace_managers_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.workspace_operators ( + id bigint NOT NULL, + created_at timestamp without time zone NOT NULL, + end_date timestamp without time zone, + manager_code bigint NOT NULL, + number_parcels_expected bigint, + observations character varying(500), + operator_code bigint NOT NULL, + start_date timestamp without time zone, + support character varying(1000) NOT NULL, + work_area double precision, + workspace_id bigint NOT NULL +); + +ALTER TABLE workspaces.workspace_operators ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.workspace_operators_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +CREATE TABLE workspaces.workspaces ( + id bigint NOT NULL, + created_at timestamp without time zone NOT NULL, + is_active boolean, + updated_at timestamp without time zone, + municipality_id bigint NOT NULL, + workspace_id bigint +); + +ALTER TABLE workspaces.workspaces ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY ( + SEQUENCE NAME workspaces.workspaces_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1 +); + +INSERT INTO workspaces.departments VALUES (5, '05', 'ANTIOQUIA'); +INSERT INTO workspaces.departments VALUES (6, '08', 'ATLÁNTICO'); +INSERT INTO workspaces.departments VALUES (7, '11', 'BOGOTÁ, D.C.'); +INSERT INTO workspaces.departments VALUES (8, '13', 'BOLÍVAR'); +INSERT INTO workspaces.departments VALUES (9, '15', 'BOYACÁ'); +INSERT INTO workspaces.departments VALUES (10, '17', 'CALDAS'); +INSERT INTO workspaces.departments VALUES (11, '18', 'CAQUETÁ'); +INSERT INTO workspaces.departments VALUES (12, '19', 'CAUCA'); +INSERT INTO workspaces.departments VALUES (13, '20', 'CESAR'); +INSERT INTO workspaces.departments VALUES (14, '23', 'CÓRDOBA'); +INSERT INTO workspaces.departments VALUES (15, '25', 'CUNDINAMARCA'); +INSERT INTO workspaces.departments VALUES (16, '27', 'CHOCÓ'); +INSERT INTO workspaces.departments VALUES (17, '41', 'HUILA'); +INSERT INTO workspaces.departments VALUES (18, '44', 'LA GUAJIRA'); +INSERT INTO workspaces.departments VALUES (19, '47', 'MAGDALENA'); +INSERT INTO workspaces.departments VALUES (20, '50', 'META'); +INSERT INTO workspaces.departments VALUES (21, '52', 'NARIÑO'); +INSERT INTO workspaces.departments VALUES (22, '54', 'NORTE DE SANTANDER'); +INSERT INTO workspaces.departments VALUES (23, '63', 'QUINDÍO'); +INSERT INTO workspaces.departments VALUES (24, '66', 'RISARALDA'); +INSERT INTO workspaces.departments VALUES (25, '68', 'SANTANDER'); +INSERT INTO workspaces.departments VALUES (26, '70', 'SUCRE'); +INSERT INTO workspaces.departments VALUES (27, '73', 'TOLIMA'); +INSERT INTO workspaces.departments VALUES (28, '76', 'VALLE DEL CAUCA'); +INSERT INTO workspaces.departments VALUES (29, '81', 'ARAUCA'); +INSERT INTO workspaces.departments VALUES (30, '85', 'CASANARE'); +INSERT INTO workspaces.departments VALUES (31, '86', 'PUTUMAYO'); +INSERT INTO workspaces.departments VALUES (32, '88', 'ARCHIPIÉLAGO DE SAN ANDRÉS, PROVIDENCIA Y SANTA CATALINA'); +INSERT INTO workspaces.departments VALUES (33, '91', 'AMAZONAS'); +INSERT INTO workspaces.departments VALUES (34, '94', 'GUAINÍA'); +INSERT INTO workspaces.departments VALUES (35, '95', 'GUAVIARE'); +INSERT INTO workspaces.departments VALUES (36, '97', 'VAUPÉS'); +INSERT INTO workspaces.departments VALUES (37, '99', 'VICHADA'); + +INSERT INTO workspaces.integrations_states VALUES (1, 'La integración ha iniciado de forma automática.', 'INICIADA AUTOMÁTICA'); +INSERT INTO workspaces.integrations_states VALUES (2, 'La integración ha finalizado de forma automática.', 'FINALIZADA AUTOMÁTICA'); +INSERT INTO workspaces.integrations_states VALUES (3, 'La integración ha iniciado de forma asistida.', 'INICIADA ASISTIDA'); +INSERT INTO workspaces.integrations_states VALUES (4, 'La integración ha finalizado de forma asistida.', 'FINALIZADA ASISTIDA'); +INSERT INTO workspaces.integrations_states VALUES (5, 'Se esta generando un producto.', 'GENERANDO PRODUCTO'); +INSERT INTO workspaces.integrations_states VALUES (6, 'Se ha generado ya un producto.', 'PRODUCTO GENERADO'); +INSERT INTO workspaces.integrations_states VALUES (7, 'Ha ocurrido un error realizando la integración.', 'ERROR REALIZANDO INTEGRACIÓN AUTOMÁTICA'); +INSERT INTO workspaces.integrations_states VALUES (8, 'Ha ocurrido un error realizando la integración.', 'ERROR GENERANDO PRODUCTO'); + +INSERT INTO workspaces.municipalities VALUES (11, '05001', 'MEDELLÍN', 5); +INSERT INTO workspaces.municipalities VALUES (12, '05002', 'ABEJORRAL', 5); +INSERT INTO workspaces.municipalities VALUES (13, '05004', 'ABRIAQUÍ', 5); +INSERT INTO workspaces.municipalities VALUES (14, '05021', 'ALEJANDRÍA', 5); +INSERT INTO workspaces.municipalities VALUES (15, '05030', 'AMAGÁ', 5); +INSERT INTO workspaces.municipalities VALUES (16, '05031', 'AMALFI', 5); +INSERT INTO workspaces.municipalities VALUES (17, '05034', 'ANDES', 5); +INSERT INTO workspaces.municipalities VALUES (18, '05036', 'ANGELÓPOLIS', 5); +INSERT INTO workspaces.municipalities VALUES (19, '05038', 'ANGOSTURA', 5); +INSERT INTO workspaces.municipalities VALUES (20, '05040', 'ANORÍ', 5); +INSERT INTO workspaces.municipalities VALUES (21, '05042', 'SANTA FÉ DE ANTIOQUIA', 5); +INSERT INTO workspaces.municipalities VALUES (22, '05044', 'ANZÁ', 5); +INSERT INTO workspaces.municipalities VALUES (23, '05045', 'APARTADÓ', 5); +INSERT INTO workspaces.municipalities VALUES (24, '05051', 'ARBOLETES', 5); +INSERT INTO workspaces.municipalities VALUES (25, '05055', 'ARGELIA', 5); +INSERT INTO workspaces.municipalities VALUES (26, '05059', 'ARMENIA', 5); +INSERT INTO workspaces.municipalities VALUES (27, '05079', 'BARBOSA', 5); +INSERT INTO workspaces.municipalities VALUES (28, '05086', 'BELMIRA', 5); +INSERT INTO workspaces.municipalities VALUES (29, '05088', 'BELLO', 5); +INSERT INTO workspaces.municipalities VALUES (30, '05091', 'BETANIA', 5); +INSERT INTO workspaces.municipalities VALUES (31, '05093', 'BETULIA', 5); +INSERT INTO workspaces.municipalities VALUES (32, '05101', 'CIUDAD BOLÍVAR', 5); +INSERT INTO workspaces.municipalities VALUES (33, '05107', 'BRICEÑO', 5); +INSERT INTO workspaces.municipalities VALUES (34, '05113', 'BURITICÁ', 5); +INSERT INTO workspaces.municipalities VALUES (35, '05120', 'CÁCERES', 5); +INSERT INTO workspaces.municipalities VALUES (36, '05125', 'CAICEDO', 5); +INSERT INTO workspaces.municipalities VALUES (37, '05129', 'CALDAS', 5); +INSERT INTO workspaces.municipalities VALUES (38, '05134', 'CAMPAMENTO', 5); +INSERT INTO workspaces.municipalities VALUES (39, '05138', 'CAÑASGORDAS', 5); +INSERT INTO workspaces.municipalities VALUES (40, '05142', 'CARACOLÍ', 5); +INSERT INTO workspaces.municipalities VALUES (41, '05145', 'CARAMANTA', 5); +INSERT INTO workspaces.municipalities VALUES (42, '05147', 'CAREPA', 5); +INSERT INTO workspaces.municipalities VALUES (43, '05148', 'EL CARMEN DE VIBORAL', 5); +INSERT INTO workspaces.municipalities VALUES (44, '05150', 'CAROLINA', 5); +INSERT INTO workspaces.municipalities VALUES (45, '05154', 'CAUCASIA', 5); +INSERT INTO workspaces.municipalities VALUES (46, '05172', 'CHIGORODÓ', 5); +INSERT INTO workspaces.municipalities VALUES (47, '05190', 'CISNEROS', 5); +INSERT INTO workspaces.municipalities VALUES (48, '05197', 'COCORNÁ', 5); +INSERT INTO workspaces.municipalities VALUES (49, '05206', 'CONCEPCIÓN', 5); +INSERT INTO workspaces.municipalities VALUES (50, '05209', 'CONCORDIA', 5); +INSERT INTO workspaces.municipalities VALUES (51, '05212', 'COPACABANA', 5); +INSERT INTO workspaces.municipalities VALUES (52, '05234', 'DABEIBA', 5); +INSERT INTO workspaces.municipalities VALUES (53, '05237', 'DONMATÍAS', 5); +INSERT INTO workspaces.municipalities VALUES (54, '05240', 'EBÉJICO', 5); +INSERT INTO workspaces.municipalities VALUES (55, '05250', 'EL BAGRE', 5); +INSERT INTO workspaces.municipalities VALUES (56, '05264', 'ENTRERRÍOS', 5); +INSERT INTO workspaces.municipalities VALUES (57, '05266', 'ENVIGADO', 5); +INSERT INTO workspaces.municipalities VALUES (58, '05282', 'FREDONIA', 5); +INSERT INTO workspaces.municipalities VALUES (59, '05284', 'FRONTINO', 5); +INSERT INTO workspaces.municipalities VALUES (60, '05306', 'GIRALDO', 5); +INSERT INTO workspaces.municipalities VALUES (61, '05308', 'GIRARDOTA', 5); +INSERT INTO workspaces.municipalities VALUES (62, '05310', 'GÓMEZ PLATA', 5); +INSERT INTO workspaces.municipalities VALUES (63, '05313', 'GRANADA', 5); +INSERT INTO workspaces.municipalities VALUES (64, '05315', 'GUADALUPE', 5); +INSERT INTO workspaces.municipalities VALUES (65, '05318', 'GUARNE', 5); +INSERT INTO workspaces.municipalities VALUES (66, '05321', 'GUATAPÉ', 5); +INSERT INTO workspaces.municipalities VALUES (67, '05347', 'HELICONIA', 5); +INSERT INTO workspaces.municipalities VALUES (68, '05353', 'HISPANIA', 5); +INSERT INTO workspaces.municipalities VALUES (69, '05360', 'ITAGÜÍ', 5); +INSERT INTO workspaces.municipalities VALUES (70, '05361', 'ITUANGO', 5); +INSERT INTO workspaces.municipalities VALUES (71, '05364', 'JARDÍN', 5); +INSERT INTO workspaces.municipalities VALUES (72, '05368', 'JERICÓ', 5); +INSERT INTO workspaces.municipalities VALUES (73, '05376', 'LA CEJA', 5); +INSERT INTO workspaces.municipalities VALUES (74, '05380', 'LA ESTRELLA', 5); +INSERT INTO workspaces.municipalities VALUES (75, '05390', 'LA PINTADA', 5); +INSERT INTO workspaces.municipalities VALUES (76, '05400', 'LA UNIÓN', 5); +INSERT INTO workspaces.municipalities VALUES (77, '05411', 'LIBORINA', 5); +INSERT INTO workspaces.municipalities VALUES (78, '05425', 'MACEO', 5); +INSERT INTO workspaces.municipalities VALUES (79, '05440', 'MARINILLA', 5); +INSERT INTO workspaces.municipalities VALUES (80, '05467', 'MONTEBELLO', 5); +INSERT INTO workspaces.municipalities VALUES (81, '05475', 'MURINDÓ', 5); +INSERT INTO workspaces.municipalities VALUES (82, '05480', 'MUTATÁ', 5); +INSERT INTO workspaces.municipalities VALUES (83, '05483', 'NARIÑO', 5); +INSERT INTO workspaces.municipalities VALUES (84, '05490', 'NECOCLÍ', 5); +INSERT INTO workspaces.municipalities VALUES (85, '05495', 'NECHÍ', 5); +INSERT INTO workspaces.municipalities VALUES (86, '05501', 'OLAYA', 5); +INSERT INTO workspaces.municipalities VALUES (87, '05541', 'PEÑOL', 5); +INSERT INTO workspaces.municipalities VALUES (88, '05543', 'PEQUE', 5); +INSERT INTO workspaces.municipalities VALUES (89, '05576', 'PUEBLORRICO', 5); +INSERT INTO workspaces.municipalities VALUES (90, '05579', 'PUERTO BERRÍO', 5); +INSERT INTO workspaces.municipalities VALUES (91, '05585', 'PUERTO NARE', 5); +INSERT INTO workspaces.municipalities VALUES (92, '05591', 'PUERTO TRIUNFO', 5); +INSERT INTO workspaces.municipalities VALUES (93, '05604', 'REMEDIOS', 5); +INSERT INTO workspaces.municipalities VALUES (94, '05607', 'RETIRO', 5); +INSERT INTO workspaces.municipalities VALUES (95, '05615', 'RIONEGRO', 5); +INSERT INTO workspaces.municipalities VALUES (96, '05628', 'SABANALARGA', 5); +INSERT INTO workspaces.municipalities VALUES (97, '05631', 'SABANETA', 5); +INSERT INTO workspaces.municipalities VALUES (98, '05642', 'SALGAR', 5); +INSERT INTO workspaces.municipalities VALUES (99, '05647', 'SAN ANDRÉS DE CUERQUÍA', 5); +INSERT INTO workspaces.municipalities VALUES (100, '05649', 'SAN CARLOS', 5); +INSERT INTO workspaces.municipalities VALUES (101, '05652', 'SAN FRANCISCO', 5); +INSERT INTO workspaces.municipalities VALUES (102, '05656', 'SAN JERÓNIMO', 5); +INSERT INTO workspaces.municipalities VALUES (103, '05658', 'SAN JOSÉ DE LA MONTAÑA', 5); +INSERT INTO workspaces.municipalities VALUES (104, '05659', 'SAN JUAN DE URABÁ', 5); +INSERT INTO workspaces.municipalities VALUES (105, '05660', 'SAN LUIS', 5); +INSERT INTO workspaces.municipalities VALUES (106, '05664', 'SAN PEDRO DE LOS MILAGROS', 5); +INSERT INTO workspaces.municipalities VALUES (107, '05665', 'SAN PEDRO DE URABÁ', 5); +INSERT INTO workspaces.municipalities VALUES (108, '05667', 'SAN RAFAEL', 5); +INSERT INTO workspaces.municipalities VALUES (109, '05670', 'SAN ROQUE', 5); +INSERT INTO workspaces.municipalities VALUES (110, '05674', 'SAN VICENTE FERRER', 5); +INSERT INTO workspaces.municipalities VALUES (111, '05679', 'SANTA BÁRBARA', 5); +INSERT INTO workspaces.municipalities VALUES (112, '05686', 'SANTA ROSA DE OSOS', 5); +INSERT INTO workspaces.municipalities VALUES (113, '05690', 'SANTO DOMINGO', 5); +INSERT INTO workspaces.municipalities VALUES (114, '05697', 'EL SANTUARIO', 5); +INSERT INTO workspaces.municipalities VALUES (115, '05736', 'SEGOVIA', 5); +INSERT INTO workspaces.municipalities VALUES (116, '05756', 'SONSÓN', 5); +INSERT INTO workspaces.municipalities VALUES (117, '05761', 'SOPETRÁN', 5); +INSERT INTO workspaces.municipalities VALUES (118, '05789', 'TÁMESIS', 5); +INSERT INTO workspaces.municipalities VALUES (119, '05790', 'TARAZÁ', 5); +INSERT INTO workspaces.municipalities VALUES (120, '05792', 'TARSO', 5); +INSERT INTO workspaces.municipalities VALUES (121, '05809', 'TITIRIBÍ', 5); +INSERT INTO workspaces.municipalities VALUES (122, '05819', 'TOLEDO', 5); +INSERT INTO workspaces.municipalities VALUES (123, '05837', 'TURBO', 5); +INSERT INTO workspaces.municipalities VALUES (124, '05842', 'URAMITA', 5); +INSERT INTO workspaces.municipalities VALUES (125, '05847', 'URRAO', 5); +INSERT INTO workspaces.municipalities VALUES (126, '05854', 'VALDIVIA', 5); +INSERT INTO workspaces.municipalities VALUES (127, '05856', 'VALPARAÍSO', 5); +INSERT INTO workspaces.municipalities VALUES (128, '05858', 'VEGACHÍ', 5); +INSERT INTO workspaces.municipalities VALUES (129, '05861', 'VENECIA', 5); +INSERT INTO workspaces.municipalities VALUES (130, '05873', 'VIGÍA DEL FUERTE', 5); +INSERT INTO workspaces.municipalities VALUES (131, '05885', 'YALÍ', 5); +INSERT INTO workspaces.municipalities VALUES (132, '05887', 'YARUMAL', 5); +INSERT INTO workspaces.municipalities VALUES (133, '05890', 'YOLOMBÓ', 5); +INSERT INTO workspaces.municipalities VALUES (134, '05893', 'YONDÓ', 5); +INSERT INTO workspaces.municipalities VALUES (135, '05895', 'ZARAGOZA', 5); +INSERT INTO workspaces.municipalities VALUES (136, '08001', 'BARRANQUILLA', 6); +INSERT INTO workspaces.municipalities VALUES (137, '08078', 'BARANOA', 6); +INSERT INTO workspaces.municipalities VALUES (138, '08137', 'CAMPO DE LA CRUZ', 6); +INSERT INTO workspaces.municipalities VALUES (139, '08141', 'CANDELARIA', 6); +INSERT INTO workspaces.municipalities VALUES (140, '08296', 'GALAPA', 6); +INSERT INTO workspaces.municipalities VALUES (141, '08372', 'JUAN DE ACOSTA', 6); +INSERT INTO workspaces.municipalities VALUES (142, '08421', 'LURUACO', 6); +INSERT INTO workspaces.municipalities VALUES (143, '08433', 'MALAMBO', 6); +INSERT INTO workspaces.municipalities VALUES (144, '08436', 'MANATÍ', 6); +INSERT INTO workspaces.municipalities VALUES (145, '08520', 'PALMAR DE VARELA', 6); +INSERT INTO workspaces.municipalities VALUES (146, '08549', 'PIOJÓ', 6); +INSERT INTO workspaces.municipalities VALUES (147, '08558', 'POLONUEVO', 6); +INSERT INTO workspaces.municipalities VALUES (148, '08560', 'PONEDERA', 6); +INSERT INTO workspaces.municipalities VALUES (149, '08573', 'PUERTO COLOMBIA', 6); +INSERT INTO workspaces.municipalities VALUES (150, '08606', 'REPELÓN', 6); +INSERT INTO workspaces.municipalities VALUES (151, '08634', 'SABANAGRANDE', 6); +INSERT INTO workspaces.municipalities VALUES (152, '08638', 'SABANALARGA', 6); +INSERT INTO workspaces.municipalities VALUES (153, '08675', 'SANTA LUCÍA', 6); +INSERT INTO workspaces.municipalities VALUES (154, '08685', 'SANTO TOMÁS', 6); +INSERT INTO workspaces.municipalities VALUES (155, '08758', 'SOLEDAD', 6); +INSERT INTO workspaces.municipalities VALUES (156, '08770', 'SUAN', 6); +INSERT INTO workspaces.municipalities VALUES (157, '08832', 'TUBARÁ', 6); +INSERT INTO workspaces.municipalities VALUES (158, '08849', 'USIACURÍ', 6); +INSERT INTO workspaces.municipalities VALUES (159, '11001', 'BOGOTÁ, D.C.', 7); +INSERT INTO workspaces.municipalities VALUES (160, '13001', 'CARTAGENA DE INDIAS', 8); +INSERT INTO workspaces.municipalities VALUES (161, '13006', 'ACHÍ', 8); +INSERT INTO workspaces.municipalities VALUES (162, '13030', 'ALTOS DEL ROSARIO', 8); +INSERT INTO workspaces.municipalities VALUES (163, '13042', 'ARENAL', 8); +INSERT INTO workspaces.municipalities VALUES (164, '13052', 'ARJONA', 8); +INSERT INTO workspaces.municipalities VALUES (165, '13062', 'ARROYOHONDO', 8); +INSERT INTO workspaces.municipalities VALUES (166, '13074', 'BARRANCO DE LOBA', 8); +INSERT INTO workspaces.municipalities VALUES (167, '13140', 'CALAMAR', 8); +INSERT INTO workspaces.municipalities VALUES (168, '13160', 'CANTAGALLO', 8); +INSERT INTO workspaces.municipalities VALUES (169, '13188', 'CICUCO', 8); +INSERT INTO workspaces.municipalities VALUES (170, '13212', 'CÓRDOBA', 8); +INSERT INTO workspaces.municipalities VALUES (171, '13222', 'CLEMENCIA', 8); +INSERT INTO workspaces.municipalities VALUES (172, '13244', 'EL CARMEN DE BOLÍVAR', 8); +INSERT INTO workspaces.municipalities VALUES (173, '13248', 'EL GUAMO', 8); +INSERT INTO workspaces.municipalities VALUES (174, '13268', 'EL PEÑÓN', 8); +INSERT INTO workspaces.municipalities VALUES (175, '13300', 'HATILLO DE LOBA', 8); +INSERT INTO workspaces.municipalities VALUES (176, '13430', 'MAGANGUÉ', 8); +INSERT INTO workspaces.municipalities VALUES (177, '13433', 'MAHATES', 8); +INSERT INTO workspaces.municipalities VALUES (178, '13440', 'MARGARITA', 8); +INSERT INTO workspaces.municipalities VALUES (179, '13442', 'MARÍA LA BAJA', 8); +INSERT INTO workspaces.municipalities VALUES (180, '13458', 'MONTECRISTO', 8); +INSERT INTO workspaces.municipalities VALUES (181, '13468', 'MOMPÓS', 8); +INSERT INTO workspaces.municipalities VALUES (182, '13473', 'MORALES', 8); +INSERT INTO workspaces.municipalities VALUES (183, '13490', 'NOROSÍ', 8); +INSERT INTO workspaces.municipalities VALUES (184, '13549', 'PINILLOS', 8); +INSERT INTO workspaces.municipalities VALUES (185, '13580', 'REGIDOR', 8); +INSERT INTO workspaces.municipalities VALUES (186, '13600', 'RÍO VIEJO', 8); +INSERT INTO workspaces.municipalities VALUES (187, '13620', 'SAN CRISTÓBAL', 8); +INSERT INTO workspaces.municipalities VALUES (188, '13647', 'SAN ESTANISLAO', 8); +INSERT INTO workspaces.municipalities VALUES (189, '13650', 'SAN FERNANDO', 8); +INSERT INTO workspaces.municipalities VALUES (190, '13654', 'SAN JACINTO', 8); +INSERT INTO workspaces.municipalities VALUES (191, '13655', 'SAN JACINTO DEL CAUCA', 8); +INSERT INTO workspaces.municipalities VALUES (192, '13657', 'SAN JUAN NEPOMUCENO', 8); +INSERT INTO workspaces.municipalities VALUES (193, '13667', 'SAN MARTÍN DE LOBA', 8); +INSERT INTO workspaces.municipalities VALUES (194, '13670', 'SAN PABLO', 8); +INSERT INTO workspaces.municipalities VALUES (195, '13673', 'SANTA CATALINA', 8); +INSERT INTO workspaces.municipalities VALUES (196, '13683', 'SANTA ROSA', 8); +INSERT INTO workspaces.municipalities VALUES (197, '13688', 'SANTA ROSA DEL SUR', 8); +INSERT INTO workspaces.municipalities VALUES (198, '13744', 'SIMITÍ', 8); +INSERT INTO workspaces.municipalities VALUES (199, '13760', 'SOPLAVIENTO', 8); +INSERT INTO workspaces.municipalities VALUES (200, '13780', 'TALAIGUA NUEVO', 8); +INSERT INTO workspaces.municipalities VALUES (201, '13810', 'TIQUISIO', 8); +INSERT INTO workspaces.municipalities VALUES (202, '13836', 'TURBACO', 8); +INSERT INTO workspaces.municipalities VALUES (203, '13838', 'TURBANÁ', 8); +INSERT INTO workspaces.municipalities VALUES (204, '13873', 'VILLANUEVA', 8); +INSERT INTO workspaces.municipalities VALUES (205, '13894', 'ZAMBRANO', 8); +INSERT INTO workspaces.municipalities VALUES (206, '15001', 'TUNJA', 9); +INSERT INTO workspaces.municipalities VALUES (207, '15022', 'ALMEIDA', 9); +INSERT INTO workspaces.municipalities VALUES (208, '15047', 'AQUITANIA', 9); +INSERT INTO workspaces.municipalities VALUES (209, '15051', 'ARCABUCO', 9); +INSERT INTO workspaces.municipalities VALUES (210, '15087', 'BELÉN', 9); +INSERT INTO workspaces.municipalities VALUES (211, '15090', 'BERBEO', 9); +INSERT INTO workspaces.municipalities VALUES (212, '15092', 'BETÉITIVA', 9); +INSERT INTO workspaces.municipalities VALUES (213, '15097', 'BOAVITA', 9); +INSERT INTO workspaces.municipalities VALUES (214, '15104', 'BOYACÁ', 9); +INSERT INTO workspaces.municipalities VALUES (215, '15106', 'BRICEÑO', 9); +INSERT INTO workspaces.municipalities VALUES (216, '15109', 'BUENAVISTA', 9); +INSERT INTO workspaces.municipalities VALUES (217, '15114', 'BUSBANZÁ', 9); +INSERT INTO workspaces.municipalities VALUES (218, '15131', 'CALDAS', 9); +INSERT INTO workspaces.municipalities VALUES (219, '15135', 'CAMPOHERMOSO', 9); +INSERT INTO workspaces.municipalities VALUES (220, '15162', 'CERINZA', 9); +INSERT INTO workspaces.municipalities VALUES (221, '15172', 'CHINAVITA', 9); +INSERT INTO workspaces.municipalities VALUES (222, '15176', 'CHIQUINQUIRÁ', 9); +INSERT INTO workspaces.municipalities VALUES (223, '15180', 'CHISCAS', 9); +INSERT INTO workspaces.municipalities VALUES (224, '15183', 'CHITA', 9); +INSERT INTO workspaces.municipalities VALUES (225, '15185', 'CHITARAQUE', 9); +INSERT INTO workspaces.municipalities VALUES (226, '15187', 'CHIVATÁ', 9); +INSERT INTO workspaces.municipalities VALUES (227, '15189', 'CIÉNEGA', 9); +INSERT INTO workspaces.municipalities VALUES (228, '15204', 'CÓMBITA', 9); +INSERT INTO workspaces.municipalities VALUES (229, '15212', 'COPER', 9); +INSERT INTO workspaces.municipalities VALUES (230, '15215', 'CORRALES', 9); +INSERT INTO workspaces.municipalities VALUES (231, '15218', 'COVARACHÍA', 9); +INSERT INTO workspaces.municipalities VALUES (232, '15223', 'CUBARÁ', 9); +INSERT INTO workspaces.municipalities VALUES (233, '15224', 'CUCAITA', 9); +INSERT INTO workspaces.municipalities VALUES (234, '15226', 'CUÍTIVA', 9); +INSERT INTO workspaces.municipalities VALUES (235, '15232', 'CHÍQUIZA', 9); +INSERT INTO workspaces.municipalities VALUES (236, '15236', 'CHIVOR', 9); +INSERT INTO workspaces.municipalities VALUES (237, '15238', 'DUITAMA', 9); +INSERT INTO workspaces.municipalities VALUES (238, '15244', 'EL COCUY', 9); +INSERT INTO workspaces.municipalities VALUES (239, '15248', 'EL ESPINO', 9); +INSERT INTO workspaces.municipalities VALUES (240, '15272', 'FIRAVITOBA', 9); +INSERT INTO workspaces.municipalities VALUES (241, '15276', 'FLORESTA', 9); +INSERT INTO workspaces.municipalities VALUES (242, '15293', 'GACHANTIVÁ', 9); +INSERT INTO workspaces.municipalities VALUES (243, '15296', 'GÁMEZA', 9); +INSERT INTO workspaces.municipalities VALUES (244, '15299', 'GARAGOA', 9); +INSERT INTO workspaces.municipalities VALUES (245, '15317', 'GUACAMAYAS', 9); +INSERT INTO workspaces.municipalities VALUES (246, '15322', 'GUATEQUE', 9); +INSERT INTO workspaces.municipalities VALUES (247, '15325', 'GUAYATÁ', 9); +INSERT INTO workspaces.municipalities VALUES (248, '15332', 'GÜICÁN DE LA SIERRA', 9); +INSERT INTO workspaces.municipalities VALUES (249, '15362', 'IZA', 9); +INSERT INTO workspaces.municipalities VALUES (250, '15367', 'JENESANO', 9); +INSERT INTO workspaces.municipalities VALUES (251, '15368', 'JERICÓ', 9); +INSERT INTO workspaces.municipalities VALUES (252, '15377', 'LABRANZAGRANDE', 9); +INSERT INTO workspaces.municipalities VALUES (253, '15380', 'LA CAPILLA', 9); +INSERT INTO workspaces.municipalities VALUES (254, '15401', 'LA VICTORIA', 9); +INSERT INTO workspaces.municipalities VALUES (255, '15403', 'LA UVITA', 9); +INSERT INTO workspaces.municipalities VALUES (256, '15407', 'VILLA DE LEYVA', 9); +INSERT INTO workspaces.municipalities VALUES (257, '15425', 'MACANAL', 9); +INSERT INTO workspaces.municipalities VALUES (258, '15442', 'MARIPÍ', 9); +INSERT INTO workspaces.municipalities VALUES (259, '15455', 'MIRAFLORES', 9); +INSERT INTO workspaces.municipalities VALUES (260, '15464', 'MONGUA', 9); +INSERT INTO workspaces.municipalities VALUES (261, '15466', 'MONGUÍ', 9); +INSERT INTO workspaces.municipalities VALUES (262, '15469', 'MONIQUIRÁ', 9); +INSERT INTO workspaces.municipalities VALUES (263, '15476', 'MOTAVITA', 9); +INSERT INTO workspaces.municipalities VALUES (264, '15480', 'MUZO', 9); +INSERT INTO workspaces.municipalities VALUES (265, '15491', 'NOBSA', 9); +INSERT INTO workspaces.municipalities VALUES (266, '15494', 'NUEVO COLÓN', 9); +INSERT INTO workspaces.municipalities VALUES (267, '15500', 'OICATÁ', 9); +INSERT INTO workspaces.municipalities VALUES (268, '15507', 'OTANCHE', 9); +INSERT INTO workspaces.municipalities VALUES (269, '15511', 'PACHAVITA', 9); +INSERT INTO workspaces.municipalities VALUES (270, '15514', 'PÁEZ', 9); +INSERT INTO workspaces.municipalities VALUES (271, '15516', 'PAIPA', 9); +INSERT INTO workspaces.municipalities VALUES (272, '15518', 'PAJARITO', 9); +INSERT INTO workspaces.municipalities VALUES (273, '15522', 'PANQUEBA', 9); +INSERT INTO workspaces.municipalities VALUES (274, '15531', 'PAUNA', 9); +INSERT INTO workspaces.municipalities VALUES (275, '15533', 'PAYA', 9); +INSERT INTO workspaces.municipalities VALUES (276, '15537', 'PAZ DE RÍO', 9); +INSERT INTO workspaces.municipalities VALUES (277, '15542', 'PESCA', 9); +INSERT INTO workspaces.municipalities VALUES (278, '15550', 'PISBA', 9); +INSERT INTO workspaces.municipalities VALUES (279, '15572', 'PUERTO BOYACÁ', 9); +INSERT INTO workspaces.municipalities VALUES (280, '15580', 'QUÍPAMA', 9); +INSERT INTO workspaces.municipalities VALUES (281, '15599', 'RAMIRIQUÍ', 9); +INSERT INTO workspaces.municipalities VALUES (282, '15600', 'RÁQUIRA', 9); +INSERT INTO workspaces.municipalities VALUES (283, '15621', 'RONDÓN', 9); +INSERT INTO workspaces.municipalities VALUES (284, '15632', 'SABOYÁ', 9); +INSERT INTO workspaces.municipalities VALUES (285, '15638', 'SÁCHICA', 9); +INSERT INTO workspaces.municipalities VALUES (286, '15646', 'SAMACÁ', 9); +INSERT INTO workspaces.municipalities VALUES (287, '15660', 'SAN EDUARDO', 9); +INSERT INTO workspaces.municipalities VALUES (288, '15664', 'SAN JOSÉ DE PARE', 9); +INSERT INTO workspaces.municipalities VALUES (289, '15667', 'SAN LUIS DE GACENO', 9); +INSERT INTO workspaces.municipalities VALUES (290, '15673', 'SAN MATEO', 9); +INSERT INTO workspaces.municipalities VALUES (291, '15676', 'SAN MIGUEL DE SEMA', 9); +INSERT INTO workspaces.municipalities VALUES (292, '15681', 'SAN PABLO DE BORBUR', 9); +INSERT INTO workspaces.municipalities VALUES (293, '15686', 'SANTANA', 9); +INSERT INTO workspaces.municipalities VALUES (294, '15690', 'SANTA MARÍA', 9); +INSERT INTO workspaces.municipalities VALUES (295, '15693', 'SANTA ROSA DE VITERBO', 9); +INSERT INTO workspaces.municipalities VALUES (296, '15696', 'SANTA SOFÍA', 9); +INSERT INTO workspaces.municipalities VALUES (297, '15720', 'SATIVANORTE', 9); +INSERT INTO workspaces.municipalities VALUES (298, '15723', 'SATIVASUR', 9); +INSERT INTO workspaces.municipalities VALUES (299, '15740', 'SIACHOQUE', 9); +INSERT INTO workspaces.municipalities VALUES (300, '15753', 'SOATÁ', 9); +INSERT INTO workspaces.municipalities VALUES (301, '15755', 'SOCOTÁ', 9); +INSERT INTO workspaces.municipalities VALUES (302, '15757', 'SOCHA', 9); +INSERT INTO workspaces.municipalities VALUES (303, '15759', 'SOGAMOSO', 9); +INSERT INTO workspaces.municipalities VALUES (304, '15761', 'SOMONDOCO', 9); +INSERT INTO workspaces.municipalities VALUES (305, '15762', 'SORA', 9); +INSERT INTO workspaces.municipalities VALUES (306, '15763', 'SOTAQUIRÁ', 9); +INSERT INTO workspaces.municipalities VALUES (307, '15764', 'SORACÁ', 9); +INSERT INTO workspaces.municipalities VALUES (308, '15774', 'SUSACÓN', 9); +INSERT INTO workspaces.municipalities VALUES (309, '15776', 'SUTAMARCHÁN', 9); +INSERT INTO workspaces.municipalities VALUES (310, '15778', 'SUTATENZA', 9); +INSERT INTO workspaces.municipalities VALUES (311, '15790', 'TASCO', 9); +INSERT INTO workspaces.municipalities VALUES (312, '15798', 'TENZA', 9); +INSERT INTO workspaces.municipalities VALUES (313, '15804', 'TIBANÁ', 9); +INSERT INTO workspaces.municipalities VALUES (314, '15806', 'TIBASOSA', 9); +INSERT INTO workspaces.municipalities VALUES (315, '15808', 'TINJACÁ', 9); +INSERT INTO workspaces.municipalities VALUES (316, '15810', 'TIPACOQUE', 9); +INSERT INTO workspaces.municipalities VALUES (317, '15814', 'TOCA', 9); +INSERT INTO workspaces.municipalities VALUES (318, '15816', 'TOGÜÍ', 9); +INSERT INTO workspaces.municipalities VALUES (319, '15820', 'TÓPAGA', 9); +INSERT INTO workspaces.municipalities VALUES (320, '15822', 'TOTA', 9); +INSERT INTO workspaces.municipalities VALUES (321, '15832', 'TUNUNGUÁ', 9); +INSERT INTO workspaces.municipalities VALUES (322, '15835', 'TURMEQUÉ', 9); +INSERT INTO workspaces.municipalities VALUES (323, '15837', 'TUTA', 9); +INSERT INTO workspaces.municipalities VALUES (324, '15839', 'TUTAZÁ', 9); +INSERT INTO workspaces.municipalities VALUES (325, '15842', 'ÚMBITA', 9); +INSERT INTO workspaces.municipalities VALUES (326, '15861', 'VENTAQUEMADA', 9); +INSERT INTO workspaces.municipalities VALUES (327, '15879', 'VIRACACHÁ', 9); +INSERT INTO workspaces.municipalities VALUES (328, '15897', 'ZETAQUIRA', 9); +INSERT INTO workspaces.municipalities VALUES (329, '17001', 'MANIZALES', 10); +INSERT INTO workspaces.municipalities VALUES (330, '17013', 'AGUADAS', 10); +INSERT INTO workspaces.municipalities VALUES (331, '17042', 'ANSERMA', 10); +INSERT INTO workspaces.municipalities VALUES (332, '17050', 'ARANZAZU', 10); +INSERT INTO workspaces.municipalities VALUES (333, '17088', 'BELALCÁZAR', 10); +INSERT INTO workspaces.municipalities VALUES (334, '17174', 'CHINCHINÁ', 10); +INSERT INTO workspaces.municipalities VALUES (335, '17272', 'FILADELFIA', 10); +INSERT INTO workspaces.municipalities VALUES (336, '17380', 'LA DORADA', 10); +INSERT INTO workspaces.municipalities VALUES (337, '17388', 'LA MERCED', 10); +INSERT INTO workspaces.municipalities VALUES (338, '17433', 'MANZANARES', 10); +INSERT INTO workspaces.municipalities VALUES (339, '17442', 'MARMATO', 10); +INSERT INTO workspaces.municipalities VALUES (340, '17444', 'MARQUETALIA', 10); +INSERT INTO workspaces.municipalities VALUES (341, '17446', 'MARULANDA', 10); +INSERT INTO workspaces.municipalities VALUES (342, '17486', 'NEIRA', 10); +INSERT INTO workspaces.municipalities VALUES (343, '17495', 'NORCASIA', 10); +INSERT INTO workspaces.municipalities VALUES (344, '17513', 'PÁCORA', 10); +INSERT INTO workspaces.municipalities VALUES (345, '17524', 'PALESTINA', 10); +INSERT INTO workspaces.municipalities VALUES (346, '17541', 'PENSILVANIA', 10); +INSERT INTO workspaces.municipalities VALUES (347, '17614', 'RIOSUCIO', 10); +INSERT INTO workspaces.municipalities VALUES (348, '17616', 'RISARALDA', 10); +INSERT INTO workspaces.municipalities VALUES (349, '17653', 'SALAMINA', 10); +INSERT INTO workspaces.municipalities VALUES (350, '17662', 'SAMANÁ', 10); +INSERT INTO workspaces.municipalities VALUES (351, '17665', 'SAN JOSÉ', 10); +INSERT INTO workspaces.municipalities VALUES (352, '17777', 'SUPÍA', 10); +INSERT INTO workspaces.municipalities VALUES (353, '17867', 'VICTORIA', 10); +INSERT INTO workspaces.municipalities VALUES (354, '17873', 'VILLAMARÍA', 10); +INSERT INTO workspaces.municipalities VALUES (355, '17877', 'VITERBO', 10); +INSERT INTO workspaces.municipalities VALUES (356, '18001', 'FLORENCIA', 11); +INSERT INTO workspaces.municipalities VALUES (357, '18029', 'ALBANIA', 11); +INSERT INTO workspaces.municipalities VALUES (358, '18094', 'BELÉN DE LOS ANDAQUÍES', 11); +INSERT INTO workspaces.municipalities VALUES (359, '18150', 'CARTAGENA DEL CHAIRÁ', 11); +INSERT INTO workspaces.municipalities VALUES (360, '18205', 'CURILLO', 11); +INSERT INTO workspaces.municipalities VALUES (361, '18247', 'EL DONCELLO', 11); +INSERT INTO workspaces.municipalities VALUES (362, '18256', 'EL PAUJÍL', 11); +INSERT INTO workspaces.municipalities VALUES (363, '18410', 'LA MONTAÑITA', 11); +INSERT INTO workspaces.municipalities VALUES (364, '18460', 'MILÁN', 11); +INSERT INTO workspaces.municipalities VALUES (365, '18479', 'MORELIA', 11); +INSERT INTO workspaces.municipalities VALUES (366, '18592', 'PUERTO RICO', 11); +INSERT INTO workspaces.municipalities VALUES (367, '18610', 'SAN JOSÉ DEL FRAGUA', 11); +INSERT INTO workspaces.municipalities VALUES (368, '18753', 'SAN VICENTE DEL CAGUÁN', 11); +INSERT INTO workspaces.municipalities VALUES (369, '18756', 'SOLANO', 11); +INSERT INTO workspaces.municipalities VALUES (370, '18785', 'SOLITA', 11); +INSERT INTO workspaces.municipalities VALUES (371, '18860', 'VALPARAÍSO', 11); +INSERT INTO workspaces.municipalities VALUES (372, '19001', 'POPAYÁN', 12); +INSERT INTO workspaces.municipalities VALUES (373, '19022', 'ALMAGUER', 12); +INSERT INTO workspaces.municipalities VALUES (374, '19050', 'ARGELIA', 12); +INSERT INTO workspaces.municipalities VALUES (375, '19075', 'BALBOA', 12); +INSERT INTO workspaces.municipalities VALUES (376, '19100', 'BOLÍVAR', 12); +INSERT INTO workspaces.municipalities VALUES (377, '19110', 'BUENOS AIRES', 12); +INSERT INTO workspaces.municipalities VALUES (378, '19130', 'CAJIBÍO', 12); +INSERT INTO workspaces.municipalities VALUES (379, '19137', 'CALDONO', 12); +INSERT INTO workspaces.municipalities VALUES (380, '19142', 'CALOTO', 12); +INSERT INTO workspaces.municipalities VALUES (381, '19212', 'CORINTO', 12); +INSERT INTO workspaces.municipalities VALUES (382, '19256', 'EL TAMBO', 12); +INSERT INTO workspaces.municipalities VALUES (383, '19290', 'FLORENCIA', 12); +INSERT INTO workspaces.municipalities VALUES (384, '19300', 'GUACHENÉ', 12); +INSERT INTO workspaces.municipalities VALUES (385, '19318', 'GUAPI', 12); +INSERT INTO workspaces.municipalities VALUES (386, '19355', 'INZÁ', 12); +INSERT INTO workspaces.municipalities VALUES (387, '19364', 'JAMBALÓ', 12); +INSERT INTO workspaces.municipalities VALUES (388, '19392', 'LA SIERRA', 12); +INSERT INTO workspaces.municipalities VALUES (389, '19397', 'LA VEGA', 12); +INSERT INTO workspaces.municipalities VALUES (390, '19418', 'LÓPEZ DE MICAY', 12); +INSERT INTO workspaces.municipalities VALUES (391, '19450', 'MERCADERES', 12); +INSERT INTO workspaces.municipalities VALUES (392, '19455', 'MIRANDA', 12); +INSERT INTO workspaces.municipalities VALUES (393, '19473', 'MORALES', 12); +INSERT INTO workspaces.municipalities VALUES (394, '19513', 'PADILLA', 12); +INSERT INTO workspaces.municipalities VALUES (395, '19517', 'PÁEZ', 12); +INSERT INTO workspaces.municipalities VALUES (396, '19532', 'PATÍA', 12); +INSERT INTO workspaces.municipalities VALUES (397, '19533', 'PIAMONTE', 12); +INSERT INTO workspaces.municipalities VALUES (398, '19548', 'PIENDAMÓ - TUNÍA', 12); +INSERT INTO workspaces.municipalities VALUES (399, '19573', 'PUERTO TEJADA', 12); +INSERT INTO workspaces.municipalities VALUES (400, '19585', 'PURACÉ', 12); +INSERT INTO workspaces.municipalities VALUES (401, '19622', 'ROSAS', 12); +INSERT INTO workspaces.municipalities VALUES (402, '19693', 'SAN SEBASTIÁN', 12); +INSERT INTO workspaces.municipalities VALUES (403, '19698', 'SANTANDER DE QUILICHAO', 12); +INSERT INTO workspaces.municipalities VALUES (404, '19701', 'SANTA ROSA', 12); +INSERT INTO workspaces.municipalities VALUES (405, '19743', 'SILVIA', 12); +INSERT INTO workspaces.municipalities VALUES (406, '19760', 'SOTARÁ PAISPAMBA', 12); +INSERT INTO workspaces.municipalities VALUES (407, '19780', 'SUÁREZ', 12); +INSERT INTO workspaces.municipalities VALUES (408, '19785', 'SUCRE', 12); +INSERT INTO workspaces.municipalities VALUES (409, '19807', 'TIMBÍO', 12); +INSERT INTO workspaces.municipalities VALUES (410, '19809', 'TIMBIQUÍ', 12); +INSERT INTO workspaces.municipalities VALUES (411, '19821', 'TORIBÍO', 12); +INSERT INTO workspaces.municipalities VALUES (412, '19824', 'TOTORÓ', 12); +INSERT INTO workspaces.municipalities VALUES (413, '19845', 'VILLA RICA', 12); +INSERT INTO workspaces.municipalities VALUES (414, '20001', 'VALLEDUPAR', 13); +INSERT INTO workspaces.municipalities VALUES (415, '20011', 'AGUACHICA', 13); +INSERT INTO workspaces.municipalities VALUES (416, '20013', 'AGUSTÍN CODAZZI', 13); +INSERT INTO workspaces.municipalities VALUES (417, '20032', 'ASTREA', 13); +INSERT INTO workspaces.municipalities VALUES (418, '20045', 'BECERRIL', 13); +INSERT INTO workspaces.municipalities VALUES (419, '20060', 'BOSCONIA', 13); +INSERT INTO workspaces.municipalities VALUES (420, '20175', 'CHIMICHAGUA', 13); +INSERT INTO workspaces.municipalities VALUES (421, '20178', 'CHIRIGUANÁ', 13); +INSERT INTO workspaces.municipalities VALUES (422, '20228', 'CURUMANÍ', 13); +INSERT INTO workspaces.municipalities VALUES (423, '20238', 'EL COPEY', 13); +INSERT INTO workspaces.municipalities VALUES (424, '20250', 'EL PASO', 13); +INSERT INTO workspaces.municipalities VALUES (425, '20295', 'GAMARRA', 13); +INSERT INTO workspaces.municipalities VALUES (426, '20310', 'GONZÁLEZ', 13); +INSERT INTO workspaces.municipalities VALUES (427, '20383', 'LA GLORIA', 13); +INSERT INTO workspaces.municipalities VALUES (428, '20400', 'LA JAGUA DE IBIRICO', 13); +INSERT INTO workspaces.municipalities VALUES (429, '20443', 'MANAURE BALCÓN DEL CESAR', 13); +INSERT INTO workspaces.municipalities VALUES (430, '20517', 'PAILITAS', 13); +INSERT INTO workspaces.municipalities VALUES (431, '20550', 'PELAYA', 13); +INSERT INTO workspaces.municipalities VALUES (432, '20570', 'PUEBLO BELLO', 13); +INSERT INTO workspaces.municipalities VALUES (433, '20614', 'RÍO DE ORO', 13); +INSERT INTO workspaces.municipalities VALUES (434, '20621', 'LA PAZ', 13); +INSERT INTO workspaces.municipalities VALUES (435, '20710', 'SAN ALBERTO', 13); +INSERT INTO workspaces.municipalities VALUES (436, '20750', 'SAN DIEGO', 13); +INSERT INTO workspaces.municipalities VALUES (437, '20770', 'SAN MARTÍN', 13); +INSERT INTO workspaces.municipalities VALUES (438, '20787', 'TAMALAMEQUE', 13); +INSERT INTO workspaces.municipalities VALUES (439, '23001', 'MONTERÍA', 14); +INSERT INTO workspaces.municipalities VALUES (440, '23068', 'AYAPEL', 14); +INSERT INTO workspaces.municipalities VALUES (441, '23079', 'BUENAVISTA', 14); +INSERT INTO workspaces.municipalities VALUES (442, '23090', 'CANALETE', 14); +INSERT INTO workspaces.municipalities VALUES (443, '23162', 'CERETÉ', 14); +INSERT INTO workspaces.municipalities VALUES (444, '23168', 'CHIMÁ', 14); +INSERT INTO workspaces.municipalities VALUES (445, '23182', 'CHINÚ', 14); +INSERT INTO workspaces.municipalities VALUES (446, '23189', 'CIÉNAGA DE ORO', 14); +INSERT INTO workspaces.municipalities VALUES (447, '23300', 'COTORRA', 14); +INSERT INTO workspaces.municipalities VALUES (448, '23350', 'LA APARTADA', 14); +INSERT INTO workspaces.municipalities VALUES (449, '23417', 'LORICA', 14); +INSERT INTO workspaces.municipalities VALUES (450, '23419', 'LOS CÓRDOBAS', 14); +INSERT INTO workspaces.municipalities VALUES (451, '23464', 'MOMIL', 14); +INSERT INTO workspaces.municipalities VALUES (452, '23466', 'MONTELÍBANO', 14); +INSERT INTO workspaces.municipalities VALUES (453, '23500', 'MOÑITOS', 14); +INSERT INTO workspaces.municipalities VALUES (454, '23555', 'PLANETA RICA', 14); +INSERT INTO workspaces.municipalities VALUES (455, '23570', 'PUEBLO NUEVO', 14); +INSERT INTO workspaces.municipalities VALUES (456, '23574', 'PUERTO ESCONDIDO', 14); +INSERT INTO workspaces.municipalities VALUES (457, '23580', 'PUERTO LIBERTADOR', 14); +INSERT INTO workspaces.municipalities VALUES (458, '23586', 'PURÍSIMA DE LA CONCEPCIÓN', 14); +INSERT INTO workspaces.municipalities VALUES (459, '23660', 'SAHAGÚN', 14); +INSERT INTO workspaces.municipalities VALUES (460, '23670', 'SAN ANDRÉS DE SOTAVENTO', 14); +INSERT INTO workspaces.municipalities VALUES (461, '23672', 'SAN ANTERO', 14); +INSERT INTO workspaces.municipalities VALUES (462, '23675', 'SAN BERNARDO DEL VIENTO', 14); +INSERT INTO workspaces.municipalities VALUES (463, '23678', 'SAN CARLOS', 14); +INSERT INTO workspaces.municipalities VALUES (464, '23682', 'SAN JOSÉ DE URÉ', 14); +INSERT INTO workspaces.municipalities VALUES (465, '23686', 'SAN PELAYO', 14); +INSERT INTO workspaces.municipalities VALUES (466, '23807', 'TIERRALTA', 14); +INSERT INTO workspaces.municipalities VALUES (467, '23815', 'TUCHÍN', 14); +INSERT INTO workspaces.municipalities VALUES (468, '23855', 'VALENCIA', 14); +INSERT INTO workspaces.municipalities VALUES (469, '25001', 'AGUA DE DIOS', 15); +INSERT INTO workspaces.municipalities VALUES (470, '25019', 'ALBÁN', 15); +INSERT INTO workspaces.municipalities VALUES (471, '25035', 'ANAPOIMA', 15); +INSERT INTO workspaces.municipalities VALUES (472, '25040', 'ANOLAIMA', 15); +INSERT INTO workspaces.municipalities VALUES (473, '25053', 'ARBELÁEZ', 15); +INSERT INTO workspaces.municipalities VALUES (474, '25086', 'BELTRÁN', 15); +INSERT INTO workspaces.municipalities VALUES (475, '25095', 'BITUIMA', 15); +INSERT INTO workspaces.municipalities VALUES (476, '25099', 'BOJACÁ', 15); +INSERT INTO workspaces.municipalities VALUES (477, '25120', 'CABRERA', 15); +INSERT INTO workspaces.municipalities VALUES (478, '25123', 'CACHIPAY', 15); +INSERT INTO workspaces.municipalities VALUES (479, '25126', 'CAJICÁ', 15); +INSERT INTO workspaces.municipalities VALUES (480, '25148', 'CAPARRAPÍ', 15); +INSERT INTO workspaces.municipalities VALUES (481, '25151', 'CÁQUEZA', 15); +INSERT INTO workspaces.municipalities VALUES (482, '25154', 'CARMEN DE CARUPA', 15); +INSERT INTO workspaces.municipalities VALUES (483, '25168', 'CHAGUANÍ', 15); +INSERT INTO workspaces.municipalities VALUES (484, '25175', 'CHÍA', 15); +INSERT INTO workspaces.municipalities VALUES (485, '25178', 'CHIPAQUE', 15); +INSERT INTO workspaces.municipalities VALUES (486, '25181', 'CHOACHÍ', 15); +INSERT INTO workspaces.municipalities VALUES (487, '25183', 'CHOCONTÁ', 15); +INSERT INTO workspaces.municipalities VALUES (488, '25200', 'COGUA', 15); +INSERT INTO workspaces.municipalities VALUES (489, '25214', 'COTA', 15); +INSERT INTO workspaces.municipalities VALUES (490, '25224', 'CUCUNUBÁ', 15); +INSERT INTO workspaces.municipalities VALUES (491, '25245', 'EL COLEGIO', 15); +INSERT INTO workspaces.municipalities VALUES (492, '25258', 'EL PEÑÓN', 15); +INSERT INTO workspaces.municipalities VALUES (493, '25260', 'EL ROSAL', 15); +INSERT INTO workspaces.municipalities VALUES (494, '25269', 'FACATATIVÁ', 15); +INSERT INTO workspaces.municipalities VALUES (495, '25279', 'FÓMEQUE', 15); +INSERT INTO workspaces.municipalities VALUES (496, '25281', 'FOSCA', 15); +INSERT INTO workspaces.municipalities VALUES (497, '25286', 'FUNZA', 15); +INSERT INTO workspaces.municipalities VALUES (498, '25288', 'FÚQUENE', 15); +INSERT INTO workspaces.municipalities VALUES (499, '25290', 'FUSAGASUGÁ', 15); +INSERT INTO workspaces.municipalities VALUES (500, '25293', 'GACHALÁ', 15); +INSERT INTO workspaces.municipalities VALUES (501, '25295', 'GACHANCIPÁ', 15); +INSERT INTO workspaces.municipalities VALUES (502, '25297', 'GACHETÁ', 15); +INSERT INTO workspaces.municipalities VALUES (503, '25299', 'GAMA', 15); +INSERT INTO workspaces.municipalities VALUES (504, '25307', 'GIRARDOT', 15); +INSERT INTO workspaces.municipalities VALUES (505, '25312', 'GRANADA', 15); +INSERT INTO workspaces.municipalities VALUES (506, '25317', 'GUACHETÁ', 15); +INSERT INTO workspaces.municipalities VALUES (507, '25320', 'GUADUAS', 15); +INSERT INTO workspaces.municipalities VALUES (508, '25322', 'GUASCA', 15); +INSERT INTO workspaces.municipalities VALUES (509, '25324', 'GUATAQUÍ', 15); +INSERT INTO workspaces.municipalities VALUES (510, '25326', 'GUATAVITA', 15); +INSERT INTO workspaces.municipalities VALUES (511, '25328', 'GUAYABAL DE SÍQUIMA', 15); +INSERT INTO workspaces.municipalities VALUES (512, '25335', 'GUAYABETAL', 15); +INSERT INTO workspaces.municipalities VALUES (513, '25339', 'GUTIÉRREZ', 15); +INSERT INTO workspaces.municipalities VALUES (514, '25368', 'JERUSALÉN', 15); +INSERT INTO workspaces.municipalities VALUES (515, '25372', 'JUNÍN', 15); +INSERT INTO workspaces.municipalities VALUES (516, '25377', 'LA CALERA', 15); +INSERT INTO workspaces.municipalities VALUES (517, '25386', 'LA MESA', 15); +INSERT INTO workspaces.municipalities VALUES (518, '25394', 'LA PALMA', 15); +INSERT INTO workspaces.municipalities VALUES (519, '25398', 'LA PEÑA', 15); +INSERT INTO workspaces.municipalities VALUES (520, '25402', 'LA VEGA', 15); +INSERT INTO workspaces.municipalities VALUES (521, '25407', 'LENGUAZAQUE', 15); +INSERT INTO workspaces.municipalities VALUES (522, '25426', 'MACHETÁ', 15); +INSERT INTO workspaces.municipalities VALUES (523, '25430', 'MADRID', 15); +INSERT INTO workspaces.municipalities VALUES (524, '25436', 'MANTA', 15); +INSERT INTO workspaces.municipalities VALUES (525, '25438', 'MEDINA', 15); +INSERT INTO workspaces.municipalities VALUES (526, '25473', 'MOSQUERA', 15); +INSERT INTO workspaces.municipalities VALUES (527, '25483', 'NARIÑO', 15); +INSERT INTO workspaces.municipalities VALUES (528, '25486', 'NEMOCÓN', 15); +INSERT INTO workspaces.municipalities VALUES (529, '25488', 'NILO', 15); +INSERT INTO workspaces.municipalities VALUES (530, '25489', 'NIMAIMA', 15); +INSERT INTO workspaces.municipalities VALUES (531, '25491', 'NOCAIMA', 15); +INSERT INTO workspaces.municipalities VALUES (532, '25506', 'VENECIA', 15); +INSERT INTO workspaces.municipalities VALUES (533, '25513', 'PACHO', 15); +INSERT INTO workspaces.municipalities VALUES (534, '25518', 'PAIME', 15); +INSERT INTO workspaces.municipalities VALUES (535, '25524', 'PANDI', 15); +INSERT INTO workspaces.municipalities VALUES (536, '25530', 'PARATEBUENO', 15); +INSERT INTO workspaces.municipalities VALUES (537, '25535', 'PASCA', 15); +INSERT INTO workspaces.municipalities VALUES (538, '25572', 'PUERTO SALGAR', 15); +INSERT INTO workspaces.municipalities VALUES (539, '25580', 'PULÍ', 15); +INSERT INTO workspaces.municipalities VALUES (540, '25592', 'QUEBRADANEGRA', 15); +INSERT INTO workspaces.municipalities VALUES (541, '25594', 'QUETAME', 15); +INSERT INTO workspaces.municipalities VALUES (542, '25596', 'QUIPILE', 15); +INSERT INTO workspaces.municipalities VALUES (543, '25599', 'APULO', 15); +INSERT INTO workspaces.municipalities VALUES (544, '25612', 'RICAURTE', 15); +INSERT INTO workspaces.municipalities VALUES (545, '25645', 'SAN ANTONIO DEL TEQUENDAMA', 15); +INSERT INTO workspaces.municipalities VALUES (546, '25649', 'SAN BERNARDO', 15); +INSERT INTO workspaces.municipalities VALUES (547, '25653', 'SAN CAYETANO', 15); +INSERT INTO workspaces.municipalities VALUES (548, '25658', 'SAN FRANCISCO', 15); +INSERT INTO workspaces.municipalities VALUES (549, '25662', 'SAN JUAN DE RIOSECO', 15); +INSERT INTO workspaces.municipalities VALUES (550, '25718', 'SASAIMA', 15); +INSERT INTO workspaces.municipalities VALUES (551, '25736', 'SESQUILÉ', 15); +INSERT INTO workspaces.municipalities VALUES (552, '25740', 'SIBATÉ', 15); +INSERT INTO workspaces.municipalities VALUES (553, '25743', 'SILVANIA', 15); +INSERT INTO workspaces.municipalities VALUES (554, '25745', 'SIMIJACA', 15); +INSERT INTO workspaces.municipalities VALUES (555, '25754', 'SOACHA', 15); +INSERT INTO workspaces.municipalities VALUES (556, '25758', 'SOPÓ', 15); +INSERT INTO workspaces.municipalities VALUES (557, '25769', 'SUBACHOQUE', 15); +INSERT INTO workspaces.municipalities VALUES (558, '25772', 'SUESCA', 15); +INSERT INTO workspaces.municipalities VALUES (559, '25777', 'SUPATÁ', 15); +INSERT INTO workspaces.municipalities VALUES (560, '25779', 'SUSA', 15); +INSERT INTO workspaces.municipalities VALUES (561, '25781', 'SUTATAUSA', 15); +INSERT INTO workspaces.municipalities VALUES (562, '25785', 'TABIO', 15); +INSERT INTO workspaces.municipalities VALUES (563, '25793', 'TAUSA', 15); +INSERT INTO workspaces.municipalities VALUES (564, '25797', 'TENA', 15); +INSERT INTO workspaces.municipalities VALUES (565, '25799', 'TENJO', 15); +INSERT INTO workspaces.municipalities VALUES (566, '25805', 'TIBACUY', 15); +INSERT INTO workspaces.municipalities VALUES (567, '25807', 'TIBIRITA', 15); +INSERT INTO workspaces.municipalities VALUES (568, '25815', 'TOCAIMA', 15); +INSERT INTO workspaces.municipalities VALUES (569, '25817', 'TOCANCIPÁ', 15); +INSERT INTO workspaces.municipalities VALUES (570, '25823', 'TOPAIPÍ', 15); +INSERT INTO workspaces.municipalities VALUES (571, '25839', 'UBALÁ', 15); +INSERT INTO workspaces.municipalities VALUES (572, '25841', 'UBAQUE', 15); +INSERT INTO workspaces.municipalities VALUES (573, '25843', 'VILLA DE SAN DIEGO DE UBATÉ', 15); +INSERT INTO workspaces.municipalities VALUES (574, '25845', 'UNE', 15); +INSERT INTO workspaces.municipalities VALUES (575, '25851', 'ÚTICA', 15); +INSERT INTO workspaces.municipalities VALUES (576, '25862', 'VERGARA', 15); +INSERT INTO workspaces.municipalities VALUES (577, '25867', 'VIANÍ', 15); +INSERT INTO workspaces.municipalities VALUES (578, '25871', 'VILLAGÓMEZ', 15); +INSERT INTO workspaces.municipalities VALUES (579, '25873', 'VILLAPINZÓN', 15); +INSERT INTO workspaces.municipalities VALUES (580, '25875', 'VILLETA', 15); +INSERT INTO workspaces.municipalities VALUES (581, '25878', 'VIOTÁ', 15); +INSERT INTO workspaces.municipalities VALUES (582, '25885', 'YACOPÍ', 15); +INSERT INTO workspaces.municipalities VALUES (583, '25898', 'ZIPACÓN', 15); +INSERT INTO workspaces.municipalities VALUES (584, '25899', 'ZIPAQUIRÁ', 15); +INSERT INTO workspaces.municipalities VALUES (585, '27001', 'QUIBDÓ', 16); +INSERT INTO workspaces.municipalities VALUES (586, '27006', 'ACANDÍ', 16); +INSERT INTO workspaces.municipalities VALUES (587, '27025', 'ALTO BAUDÓ', 16); +INSERT INTO workspaces.municipalities VALUES (588, '27050', 'ATRATO', 16); +INSERT INTO workspaces.municipalities VALUES (589, '27073', 'BAGADÓ', 16); +INSERT INTO workspaces.municipalities VALUES (590, '27075', 'BAHÍA SOLANO', 16); +INSERT INTO workspaces.municipalities VALUES (591, '27077', 'BAJO BAUDÓ', 16); +INSERT INTO workspaces.municipalities VALUES (592, '27099', 'BOJAYÁ', 16); +INSERT INTO workspaces.municipalities VALUES (593, '27135', 'EL CANTÓN DEL SAN PABLO', 16); +INSERT INTO workspaces.municipalities VALUES (594, '27150', 'CARMEN DEL DARIÉN', 16); +INSERT INTO workspaces.municipalities VALUES (595, '27160', 'CÉRTEGUI', 16); +INSERT INTO workspaces.municipalities VALUES (596, '27205', 'CONDOTO', 16); +INSERT INTO workspaces.municipalities VALUES (597, '27245', 'EL CARMEN DE ATRATO', 16); +INSERT INTO workspaces.municipalities VALUES (598, '27250', 'EL LITORAL DEL SAN JUAN', 16); +INSERT INTO workspaces.municipalities VALUES (599, '27361', 'ISTMINA', 16); +INSERT INTO workspaces.municipalities VALUES (600, '27372', 'JURADÓ', 16); +INSERT INTO workspaces.municipalities VALUES (601, '27413', 'LLORÓ', 16); +INSERT INTO workspaces.municipalities VALUES (602, '27425', 'MEDIO ATRATO', 16); +INSERT INTO workspaces.municipalities VALUES (603, '27430', 'MEDIO BAUDÓ', 16); +INSERT INTO workspaces.municipalities VALUES (604, '27450', 'MEDIO SAN JUAN', 16); +INSERT INTO workspaces.municipalities VALUES (605, '27491', 'NÓVITA', 16); +INSERT INTO workspaces.municipalities VALUES (606, '27495', 'NUQUÍ', 16); +INSERT INTO workspaces.municipalities VALUES (607, '27580', 'RÍO IRÓ', 16); +INSERT INTO workspaces.municipalities VALUES (608, '27600', 'RÍO QUITO', 16); +INSERT INTO workspaces.municipalities VALUES (609, '27615', 'RIOSUCIO', 16); +INSERT INTO workspaces.municipalities VALUES (610, '27660', 'SAN JOSÉ DEL PALMAR', 16); +INSERT INTO workspaces.municipalities VALUES (611, '27745', 'SIPÍ', 16); +INSERT INTO workspaces.municipalities VALUES (612, '27787', 'TADÓ', 16); +INSERT INTO workspaces.municipalities VALUES (613, '27800', 'UNGUÍA', 16); +INSERT INTO workspaces.municipalities VALUES (614, '27810', 'UNIÓN PANAMERICANA', 16); +INSERT INTO workspaces.municipalities VALUES (615, '41001', 'NEIVA', 17); +INSERT INTO workspaces.municipalities VALUES (616, '41006', 'ACEVEDO', 17); +INSERT INTO workspaces.municipalities VALUES (617, '41013', 'AGRADO', 17); +INSERT INTO workspaces.municipalities VALUES (618, '41016', 'AIPE', 17); +INSERT INTO workspaces.municipalities VALUES (619, '41020', 'ALGECIRAS', 17); +INSERT INTO workspaces.municipalities VALUES (620, '41026', 'ALTAMIRA', 17); +INSERT INTO workspaces.municipalities VALUES (621, '41078', 'BARAYA', 17); +INSERT INTO workspaces.municipalities VALUES (622, '41132', 'CAMPOALEGRE', 17); +INSERT INTO workspaces.municipalities VALUES (623, '41206', 'COLOMBIA', 17); +INSERT INTO workspaces.municipalities VALUES (624, '41244', 'ELÍAS', 17); +INSERT INTO workspaces.municipalities VALUES (625, '41298', 'GARZÓN', 17); +INSERT INTO workspaces.municipalities VALUES (626, '41306', 'GIGANTE', 17); +INSERT INTO workspaces.municipalities VALUES (627, '41319', 'GUADALUPE', 17); +INSERT INTO workspaces.municipalities VALUES (628, '41349', 'HOBO', 17); +INSERT INTO workspaces.municipalities VALUES (629, '41357', 'ÍQUIRA', 17); +INSERT INTO workspaces.municipalities VALUES (630, '41359', 'ISNOS', 17); +INSERT INTO workspaces.municipalities VALUES (631, '41378', 'LA ARGENTINA', 17); +INSERT INTO workspaces.municipalities VALUES (632, '41396', 'LA PLATA', 17); +INSERT INTO workspaces.municipalities VALUES (633, '41483', 'NÁTAGA', 17); +INSERT INTO workspaces.municipalities VALUES (634, '41503', 'OPORAPA', 17); +INSERT INTO workspaces.municipalities VALUES (635, '41518', 'PAICOL', 17); +INSERT INTO workspaces.municipalities VALUES (636, '41524', 'PALERMO', 17); +INSERT INTO workspaces.municipalities VALUES (637, '41530', 'PALESTINA', 17); +INSERT INTO workspaces.municipalities VALUES (638, '41548', 'PITAL', 17); +INSERT INTO workspaces.municipalities VALUES (639, '41551', 'PITALITO', 17); +INSERT INTO workspaces.municipalities VALUES (640, '41615', 'RIVERA', 17); +INSERT INTO workspaces.municipalities VALUES (641, '41660', 'SALADOBLANCO', 17); +INSERT INTO workspaces.municipalities VALUES (642, '41668', 'SAN AGUSTÍN', 17); +INSERT INTO workspaces.municipalities VALUES (643, '41676', 'SANTA MARÍA', 17); +INSERT INTO workspaces.municipalities VALUES (644, '41770', 'SUAZA', 17); +INSERT INTO workspaces.municipalities VALUES (645, '41791', 'TARQUI', 17); +INSERT INTO workspaces.municipalities VALUES (646, '41797', 'TESALIA', 17); +INSERT INTO workspaces.municipalities VALUES (647, '41799', 'TELLO', 17); +INSERT INTO workspaces.municipalities VALUES (648, '41801', 'TERUEL', 17); +INSERT INTO workspaces.municipalities VALUES (649, '41807', 'TIMANÁ', 17); +INSERT INTO workspaces.municipalities VALUES (650, '41872', 'VILLAVIEJA', 17); +INSERT INTO workspaces.municipalities VALUES (651, '41885', 'YAGUARÁ', 17); +INSERT INTO workspaces.municipalities VALUES (652, '44001', 'RIOHACHA', 18); +INSERT INTO workspaces.municipalities VALUES (653, '44035', 'ALBANIA', 18); +INSERT INTO workspaces.municipalities VALUES (654, '44078', 'BARRANCAS', 18); +INSERT INTO workspaces.municipalities VALUES (655, '44090', 'DIBULLA', 18); +INSERT INTO workspaces.municipalities VALUES (656, '44098', 'DISTRACCIÓN', 18); +INSERT INTO workspaces.municipalities VALUES (657, '44110', 'EL MOLINO', 18); +INSERT INTO workspaces.municipalities VALUES (658, '44279', 'FONSECA', 18); +INSERT INTO workspaces.municipalities VALUES (659, '44378', 'HATONUEVO', 18); +INSERT INTO workspaces.municipalities VALUES (660, '44420', 'LA JAGUA DEL PILAR', 18); +INSERT INTO workspaces.municipalities VALUES (661, '44430', 'MAICAO', 18); +INSERT INTO workspaces.municipalities VALUES (662, '44560', 'MANAURE', 18); +INSERT INTO workspaces.municipalities VALUES (663, '44650', 'SAN JUAN DEL CESAR', 18); +INSERT INTO workspaces.municipalities VALUES (664, '44847', 'URIBIA', 18); +INSERT INTO workspaces.municipalities VALUES (665, '44855', 'URUMITA', 18); +INSERT INTO workspaces.municipalities VALUES (666, '44874', 'VILLANUEVA', 18); +INSERT INTO workspaces.municipalities VALUES (667, '47001', 'SANTA MARTA', 19); +INSERT INTO workspaces.municipalities VALUES (668, '47030', 'ALGARROBO', 19); +INSERT INTO workspaces.municipalities VALUES (669, '47053', 'ARACATACA', 19); +INSERT INTO workspaces.municipalities VALUES (670, '47058', 'ARIGUANÍ', 19); +INSERT INTO workspaces.municipalities VALUES (671, '47161', 'CERRO DE SAN ANTONIO', 19); +INSERT INTO workspaces.municipalities VALUES (672, '47170', 'CHIVOLO', 19); +INSERT INTO workspaces.municipalities VALUES (673, '47189', 'CIÉNAGA', 19); +INSERT INTO workspaces.municipalities VALUES (674, '47205', 'CONCORDIA', 19); +INSERT INTO workspaces.municipalities VALUES (675, '47245', 'EL BANCO', 19); +INSERT INTO workspaces.municipalities VALUES (676, '47258', 'EL PIÑÓN', 19); +INSERT INTO workspaces.municipalities VALUES (677, '47268', 'EL RETÉN', 19); +INSERT INTO workspaces.municipalities VALUES (678, '47288', 'FUNDACIÓN', 19); +INSERT INTO workspaces.municipalities VALUES (679, '47318', 'GUAMAL', 19); +INSERT INTO workspaces.municipalities VALUES (680, '47460', 'NUEVA GRANADA', 19); +INSERT INTO workspaces.municipalities VALUES (681, '47541', 'PEDRAZA', 19); +INSERT INTO workspaces.municipalities VALUES (682, '47545', 'PIJIÑO DEL CARMEN', 19); +INSERT INTO workspaces.municipalities VALUES (683, '47551', 'PIVIJAY', 19); +INSERT INTO workspaces.municipalities VALUES (684, '47555', 'PLATO', 19); +INSERT INTO workspaces.municipalities VALUES (685, '47570', 'PUEBLOVIEJO', 19); +INSERT INTO workspaces.municipalities VALUES (686, '47605', 'REMOLINO', 19); +INSERT INTO workspaces.municipalities VALUES (687, '47660', 'SABANAS DE SAN ÁNGEL', 19); +INSERT INTO workspaces.municipalities VALUES (688, '47675', 'SALAMINA', 19); +INSERT INTO workspaces.municipalities VALUES (689, '47692', 'SAN SEBASTIÁN DE BUENAVISTA', 19); +INSERT INTO workspaces.municipalities VALUES (690, '47703', 'SAN ZENÓN', 19); +INSERT INTO workspaces.municipalities VALUES (691, '47707', 'SANTA ANA', 19); +INSERT INTO workspaces.municipalities VALUES (692, '47720', 'SANTA BÁRBARA DE PINTO', 19); +INSERT INTO workspaces.municipalities VALUES (693, '47745', 'SITIONUEVO', 19); +INSERT INTO workspaces.municipalities VALUES (694, '47798', 'TENERIFE', 19); +INSERT INTO workspaces.municipalities VALUES (695, '47960', 'ZAPAYÁN', 19); +INSERT INTO workspaces.municipalities VALUES (696, '47980', 'ZONA BANANERA', 19); +INSERT INTO workspaces.municipalities VALUES (697, '50001', 'VILLAVICENCIO', 20); +INSERT INTO workspaces.municipalities VALUES (698, '50006', 'ACACÍAS', 20); +INSERT INTO workspaces.municipalities VALUES (699, '50110', 'BARRANCA DE UPÍA', 20); +INSERT INTO workspaces.municipalities VALUES (700, '50124', 'CABUYARO', 20); +INSERT INTO workspaces.municipalities VALUES (701, '50150', 'CASTILLA LA NUEVA', 20); +INSERT INTO workspaces.municipalities VALUES (702, '50223', 'CUBARRAL', 20); +INSERT INTO workspaces.municipalities VALUES (703, '50226', 'CUMARAL', 20); +INSERT INTO workspaces.municipalities VALUES (704, '50245', 'EL CALVARIO', 20); +INSERT INTO workspaces.municipalities VALUES (705, '50251', 'EL CASTILLO', 20); +INSERT INTO workspaces.municipalities VALUES (706, '50270', 'EL DORADO', 20); +INSERT INTO workspaces.municipalities VALUES (707, '50287', 'FUENTE DE ORO', 20); +INSERT INTO workspaces.municipalities VALUES (708, '50313', 'GRANADA', 20); +INSERT INTO workspaces.municipalities VALUES (709, '50318', 'GUAMAL', 20); +INSERT INTO workspaces.municipalities VALUES (710, '50325', 'MAPIRIPÁN', 20); +INSERT INTO workspaces.municipalities VALUES (711, '50330', 'MESETAS', 20); +INSERT INTO workspaces.municipalities VALUES (712, '50350', 'LA MACARENA', 20); +INSERT INTO workspaces.municipalities VALUES (713, '50370', 'URIBE', 20); +INSERT INTO workspaces.municipalities VALUES (714, '50400', 'LEJANÍAS', 20); +INSERT INTO workspaces.municipalities VALUES (715, '50450', 'PUERTO CONCORDIA', 20); +INSERT INTO workspaces.municipalities VALUES (716, '50568', 'PUERTO GAITÁN', 20); +INSERT INTO workspaces.municipalities VALUES (717, '50573', 'PUERTO LÓPEZ', 20); +INSERT INTO workspaces.municipalities VALUES (718, '50577', 'PUERTO LLERAS', 20); +INSERT INTO workspaces.municipalities VALUES (719, '50590', 'PUERTO RICO', 20); +INSERT INTO workspaces.municipalities VALUES (720, '50606', 'RESTREPO', 20); +INSERT INTO workspaces.municipalities VALUES (721, '50680', 'SAN CARLOS DE GUAROA', 20); +INSERT INTO workspaces.municipalities VALUES (722, '50683', 'SAN JUAN DE ARAMA', 20); +INSERT INTO workspaces.municipalities VALUES (723, '50686', 'SAN JUANITO', 20); +INSERT INTO workspaces.municipalities VALUES (724, '50689', 'SAN MARTÍN', 20); +INSERT INTO workspaces.municipalities VALUES (725, '50711', 'VISTAHERMOSA', 20); +INSERT INTO workspaces.municipalities VALUES (726, '52001', 'PASTO', 21); +INSERT INTO workspaces.municipalities VALUES (727, '52019', 'ALBÁN', 21); +INSERT INTO workspaces.municipalities VALUES (728, '52022', 'ALDANA', 21); +INSERT INTO workspaces.municipalities VALUES (729, '52036', 'ANCUYA', 21); +INSERT INTO workspaces.municipalities VALUES (730, '52051', 'ARBOLEDA', 21); +INSERT INTO workspaces.municipalities VALUES (731, '52079', 'BARBACOAS', 21); +INSERT INTO workspaces.municipalities VALUES (732, '52083', 'BELÉN', 21); +INSERT INTO workspaces.municipalities VALUES (733, '52110', 'BUESACO', 21); +INSERT INTO workspaces.municipalities VALUES (734, '52203', 'COLÓN', 21); +INSERT INTO workspaces.municipalities VALUES (735, '52207', 'CONSACÁ', 21); +INSERT INTO workspaces.municipalities VALUES (736, '52210', 'CONTADERO', 21); +INSERT INTO workspaces.municipalities VALUES (737, '52215', 'CÓRDOBA', 21); +INSERT INTO workspaces.municipalities VALUES (738, '52224', 'CUASPUD CARLOSAMA', 21); +INSERT INTO workspaces.municipalities VALUES (739, '52227', 'CUMBAL', 21); +INSERT INTO workspaces.municipalities VALUES (740, '52233', 'CUMBITARA', 21); +INSERT INTO workspaces.municipalities VALUES (741, '52240', 'CHACHAGÜÍ', 21); +INSERT INTO workspaces.municipalities VALUES (742, '52250', 'EL CHARCO', 21); +INSERT INTO workspaces.municipalities VALUES (743, '52254', 'EL PEÑOL', 21); +INSERT INTO workspaces.municipalities VALUES (744, '52256', 'EL ROSARIO', 21); +INSERT INTO workspaces.municipalities VALUES (745, '52258', 'EL TABLÓN DE GÓMEZ', 21); +INSERT INTO workspaces.municipalities VALUES (746, '52260', 'EL TAMBO', 21); +INSERT INTO workspaces.municipalities VALUES (747, '52287', 'FUNES', 21); +INSERT INTO workspaces.municipalities VALUES (748, '52317', 'GUACHUCAL', 21); +INSERT INTO workspaces.municipalities VALUES (749, '52320', 'GUAITARILLA', 21); +INSERT INTO workspaces.municipalities VALUES (750, '52323', 'GUALMATÁN', 21); +INSERT INTO workspaces.municipalities VALUES (751, '52352', 'ILES', 21); +INSERT INTO workspaces.municipalities VALUES (752, '52354', 'IMUÉS', 21); +INSERT INTO workspaces.municipalities VALUES (753, '52356', 'IPIALES', 21); +INSERT INTO workspaces.municipalities VALUES (754, '52378', 'LA CRUZ', 21); +INSERT INTO workspaces.municipalities VALUES (755, '52381', 'LA FLORIDA', 21); +INSERT INTO workspaces.municipalities VALUES (756, '52385', 'LA LLANADA', 21); +INSERT INTO workspaces.municipalities VALUES (757, '52390', 'LA TOLA', 21); +INSERT INTO workspaces.municipalities VALUES (758, '52399', 'LA UNIÓN', 21); +INSERT INTO workspaces.municipalities VALUES (759, '52405', 'LEIVA', 21); +INSERT INTO workspaces.municipalities VALUES (760, '52411', 'LINARES', 21); +INSERT INTO workspaces.municipalities VALUES (761, '52418', 'LOS ANDES', 21); +INSERT INTO workspaces.municipalities VALUES (762, '52427', 'MAGÜÍ', 21); +INSERT INTO workspaces.municipalities VALUES (763, '52435', 'MALLAMA', 21); +INSERT INTO workspaces.municipalities VALUES (764, '52473', 'MOSQUERA', 21); +INSERT INTO workspaces.municipalities VALUES (765, '52480', 'NARIÑO', 21); +INSERT INTO workspaces.municipalities VALUES (766, '52490', 'OLAYA HERRERA', 21); +INSERT INTO workspaces.municipalities VALUES (767, '52506', 'OSPINA', 21); +INSERT INTO workspaces.municipalities VALUES (768, '52520', 'FRANCISCO PIZARRO', 21); +INSERT INTO workspaces.municipalities VALUES (769, '52540', 'POLICARPA', 21); +INSERT INTO workspaces.municipalities VALUES (770, '52560', 'POTOSÍ', 21); +INSERT INTO workspaces.municipalities VALUES (771, '52565', 'PROVIDENCIA', 21); +INSERT INTO workspaces.municipalities VALUES (772, '52573', 'PUERRES', 21); +INSERT INTO workspaces.municipalities VALUES (773, '52585', 'PUPIALES', 21); +INSERT INTO workspaces.municipalities VALUES (774, '52612', 'RICAURTE', 21); +INSERT INTO workspaces.municipalities VALUES (775, '52621', 'ROBERTO PAYÁN', 21); +INSERT INTO workspaces.municipalities VALUES (776, '52678', 'SAMANIEGO', 21); +INSERT INTO workspaces.municipalities VALUES (777, '52683', 'SANDONÁ', 21); +INSERT INTO workspaces.municipalities VALUES (778, '52685', 'SAN BERNARDO', 21); +INSERT INTO workspaces.municipalities VALUES (779, '52687', 'SAN LORENZO', 21); +INSERT INTO workspaces.municipalities VALUES (780, '52693', 'SAN PABLO', 21); +INSERT INTO workspaces.municipalities VALUES (781, '52694', 'SAN PEDRO DE CARTAGO', 21); +INSERT INTO workspaces.municipalities VALUES (782, '52696', 'SANTA BÁRBARA', 21); +INSERT INTO workspaces.municipalities VALUES (783, '52699', 'SANTACRUZ', 21); +INSERT INTO workspaces.municipalities VALUES (784, '52720', 'SAPUYES', 21); +INSERT INTO workspaces.municipalities VALUES (785, '52786', 'TAMINANGO', 21); +INSERT INTO workspaces.municipalities VALUES (786, '52788', 'TANGUA', 21); +INSERT INTO workspaces.municipalities VALUES (787, '52835', 'SAN ANDRÉS DE TUMACO', 21); +INSERT INTO workspaces.municipalities VALUES (788, '52838', 'TÚQUERRES', 21); +INSERT INTO workspaces.municipalities VALUES (789, '52885', 'YACUANQUER', 21); +INSERT INTO workspaces.municipalities VALUES (790, '54001', 'SAN JOSÉ DE CÚCUTA', 22); +INSERT INTO workspaces.municipalities VALUES (791, '54003', 'ÁBREGO', 22); +INSERT INTO workspaces.municipalities VALUES (792, '54051', 'ARBOLEDAS', 22); +INSERT INTO workspaces.municipalities VALUES (793, '54099', 'BOCHALEMA', 22); +INSERT INTO workspaces.municipalities VALUES (794, '54109', 'BUCARASICA', 22); +INSERT INTO workspaces.municipalities VALUES (795, '54125', 'CÁCOTA', 22); +INSERT INTO workspaces.municipalities VALUES (796, '54128', 'CÁCHIRA', 22); +INSERT INTO workspaces.municipalities VALUES (797, '54172', 'CHINÁCOTA', 22); +INSERT INTO workspaces.municipalities VALUES (798, '54174', 'CHITAGÁ', 22); +INSERT INTO workspaces.municipalities VALUES (799, '54206', 'CONVENCIÓN', 22); +INSERT INTO workspaces.municipalities VALUES (800, '54223', 'CUCUTILLA', 22); +INSERT INTO workspaces.municipalities VALUES (801, '54239', 'DURANIA', 22); +INSERT INTO workspaces.municipalities VALUES (802, '54245', 'EL CARMEN', 22); +INSERT INTO workspaces.municipalities VALUES (803, '54250', 'EL TARRA', 22); +INSERT INTO workspaces.municipalities VALUES (804, '54261', 'EL ZULIA', 22); +INSERT INTO workspaces.municipalities VALUES (805, '54313', 'GRAMALOTE', 22); +INSERT INTO workspaces.municipalities VALUES (806, '54344', 'HACARÍ', 22); +INSERT INTO workspaces.municipalities VALUES (807, '54347', 'HERRÁN', 22); +INSERT INTO workspaces.municipalities VALUES (808, '54377', 'LABATECA', 22); +INSERT INTO workspaces.municipalities VALUES (809, '54385', 'LA ESPERANZA', 22); +INSERT INTO workspaces.municipalities VALUES (810, '54398', 'LA PLAYA', 22); +INSERT INTO workspaces.municipalities VALUES (811, '54405', 'LOS PATIOS', 22); +INSERT INTO workspaces.municipalities VALUES (812, '54418', 'LOURDES', 22); +INSERT INTO workspaces.municipalities VALUES (813, '54480', 'MUTISCUA', 22); +INSERT INTO workspaces.municipalities VALUES (814, '54498', 'OCAÑA', 22); +INSERT INTO workspaces.municipalities VALUES (815, '54518', 'PAMPLONA', 22); +INSERT INTO workspaces.municipalities VALUES (816, '54520', 'PAMPLONITA', 22); +INSERT INTO workspaces.municipalities VALUES (817, '54553', 'PUERTO SANTANDER', 22); +INSERT INTO workspaces.municipalities VALUES (818, '54599', 'RAGONVALIA', 22); +INSERT INTO workspaces.municipalities VALUES (819, '54660', 'SALAZAR', 22); +INSERT INTO workspaces.municipalities VALUES (820, '54670', 'SAN CALIXTO', 22); +INSERT INTO workspaces.municipalities VALUES (821, '54673', 'SAN CAYETANO', 22); +INSERT INTO workspaces.municipalities VALUES (822, '54680', 'SANTIAGO', 22); +INSERT INTO workspaces.municipalities VALUES (823, '54720', 'SARDINATA', 22); +INSERT INTO workspaces.municipalities VALUES (824, '54743', 'SILOS', 22); +INSERT INTO workspaces.municipalities VALUES (825, '54800', 'TEORAMA', 22); +INSERT INTO workspaces.municipalities VALUES (826, '54810', 'TIBÚ', 22); +INSERT INTO workspaces.municipalities VALUES (827, '54820', 'TOLEDO', 22); +INSERT INTO workspaces.municipalities VALUES (828, '54871', 'VILLA CARO', 22); +INSERT INTO workspaces.municipalities VALUES (829, '54874', 'VILLA DEL ROSARIO', 22); +INSERT INTO workspaces.municipalities VALUES (830, '63001', 'ARMENIA', 23); +INSERT INTO workspaces.municipalities VALUES (831, '63111', 'BUENAVISTA', 23); +INSERT INTO workspaces.municipalities VALUES (832, '63130', 'CALARCÁ', 23); +INSERT INTO workspaces.municipalities VALUES (833, '63190', 'CIRCASIA', 23); +INSERT INTO workspaces.municipalities VALUES (834, '63212', 'CÓRDOBA', 23); +INSERT INTO workspaces.municipalities VALUES (835, '63272', 'FILANDIA', 23); +INSERT INTO workspaces.municipalities VALUES (836, '63302', 'GÉNOVA', 23); +INSERT INTO workspaces.municipalities VALUES (837, '63401', 'LA TEBAIDA', 23); +INSERT INTO workspaces.municipalities VALUES (838, '63470', 'MONTENEGRO', 23); +INSERT INTO workspaces.municipalities VALUES (839, '63548', 'PIJAO', 23); +INSERT INTO workspaces.municipalities VALUES (840, '63594', 'QUIMBAYA', 23); +INSERT INTO workspaces.municipalities VALUES (841, '63690', 'SALENTO', 23); +INSERT INTO workspaces.municipalities VALUES (842, '66001', 'PEREIRA', 24); +INSERT INTO workspaces.municipalities VALUES (843, '66045', 'APÍA', 24); +INSERT INTO workspaces.municipalities VALUES (844, '66075', 'BALBOA', 24); +INSERT INTO workspaces.municipalities VALUES (845, '66088', 'BELÉN DE UMBRÍA', 24); +INSERT INTO workspaces.municipalities VALUES (846, '66170', 'DOSQUEBRADAS', 24); +INSERT INTO workspaces.municipalities VALUES (847, '66318', 'GUÁTICA', 24); +INSERT INTO workspaces.municipalities VALUES (848, '66383', 'LA CELIA', 24); +INSERT INTO workspaces.municipalities VALUES (849, '66400', 'LA VIRGINIA', 24); +INSERT INTO workspaces.municipalities VALUES (850, '66440', 'MARSELLA', 24); +INSERT INTO workspaces.municipalities VALUES (851, '66456', 'MISTRATÓ', 24); +INSERT INTO workspaces.municipalities VALUES (852, '66572', 'PUEBLO RICO', 24); +INSERT INTO workspaces.municipalities VALUES (853, '66594', 'QUINCHÍA', 24); +INSERT INTO workspaces.municipalities VALUES (854, '66682', 'SANTA ROSA DE CABAL', 24); +INSERT INTO workspaces.municipalities VALUES (855, '66687', 'SANTUARIO', 24); +INSERT INTO workspaces.municipalities VALUES (856, '68001', 'BUCARAMANGA', 25); +INSERT INTO workspaces.municipalities VALUES (857, '68013', 'AGUADA', 25); +INSERT INTO workspaces.municipalities VALUES (858, '68020', 'ALBANIA', 25); +INSERT INTO workspaces.municipalities VALUES (859, '68051', 'ARATOCA', 25); +INSERT INTO workspaces.municipalities VALUES (860, '68077', 'BARBOSA', 25); +INSERT INTO workspaces.municipalities VALUES (861, '68079', 'BARICHARA', 25); +INSERT INTO workspaces.municipalities VALUES (862, '68081', 'BARRANCABERMEJA', 25); +INSERT INTO workspaces.municipalities VALUES (863, '68092', 'BETULIA', 25); +INSERT INTO workspaces.municipalities VALUES (864, '68101', 'BOLÍVAR', 25); +INSERT INTO workspaces.municipalities VALUES (865, '68121', 'CABRERA', 25); +INSERT INTO workspaces.municipalities VALUES (866, '68132', 'CALIFORNIA', 25); +INSERT INTO workspaces.municipalities VALUES (867, '68147', 'CAPITANEJO', 25); +INSERT INTO workspaces.municipalities VALUES (868, '68152', 'CARCASÍ', 25); +INSERT INTO workspaces.municipalities VALUES (869, '68160', 'CEPITÁ', 25); +INSERT INTO workspaces.municipalities VALUES (870, '68162', 'CERRITO', 25); +INSERT INTO workspaces.municipalities VALUES (871, '68167', 'CHARALÁ', 25); +INSERT INTO workspaces.municipalities VALUES (872, '68169', 'CHARTA', 25); +INSERT INTO workspaces.municipalities VALUES (873, '68176', 'CHIMA', 25); +INSERT INTO workspaces.municipalities VALUES (874, '68179', 'CHIPATÁ', 25); +INSERT INTO workspaces.municipalities VALUES (875, '68190', 'CIMITARRA', 25); +INSERT INTO workspaces.municipalities VALUES (876, '68207', 'CONCEPCIÓN', 25); +INSERT INTO workspaces.municipalities VALUES (877, '68209', 'CONFINES', 25); +INSERT INTO workspaces.municipalities VALUES (878, '68211', 'CONTRATACIÓN', 25); +INSERT INTO workspaces.municipalities VALUES (879, '68217', 'COROMORO', 25); +INSERT INTO workspaces.municipalities VALUES (880, '68229', 'CURITÍ', 25); +INSERT INTO workspaces.municipalities VALUES (881, '68235', 'EL CARMEN DE CHUCURI', 25); +INSERT INTO workspaces.municipalities VALUES (882, '68245', 'EL GUACAMAYO', 25); +INSERT INTO workspaces.municipalities VALUES (883, '68250', 'EL PEÑÓN', 25); +INSERT INTO workspaces.municipalities VALUES (884, '68255', 'EL PLAYÓN', 25); +INSERT INTO workspaces.municipalities VALUES (885, '68264', 'ENCINO', 25); +INSERT INTO workspaces.municipalities VALUES (886, '68266', 'ENCISO', 25); +INSERT INTO workspaces.municipalities VALUES (887, '68271', 'FLORIÁN', 25); +INSERT INTO workspaces.municipalities VALUES (888, '68276', 'FLORIDABLANCA', 25); +INSERT INTO workspaces.municipalities VALUES (889, '68296', 'GALÁN', 25); +INSERT INTO workspaces.municipalities VALUES (890, '68298', 'GÁMBITA', 25); +INSERT INTO workspaces.municipalities VALUES (891, '68307', 'GIRÓN', 25); +INSERT INTO workspaces.municipalities VALUES (892, '68318', 'GUACA', 25); +INSERT INTO workspaces.municipalities VALUES (893, '68320', 'GUADALUPE', 25); +INSERT INTO workspaces.municipalities VALUES (894, '68322', 'GUAPOTÁ', 25); +INSERT INTO workspaces.municipalities VALUES (895, '68324', 'GUAVATÁ', 25); +INSERT INTO workspaces.municipalities VALUES (896, '68327', 'GÜEPSA', 25); +INSERT INTO workspaces.municipalities VALUES (897, '68344', 'HATO', 25); +INSERT INTO workspaces.municipalities VALUES (898, '68368', 'JESÚS MARÍA', 25); +INSERT INTO workspaces.municipalities VALUES (899, '68370', 'JORDÁN', 25); +INSERT INTO workspaces.municipalities VALUES (900, '68377', 'LA BELLEZA', 25); +INSERT INTO workspaces.municipalities VALUES (901, '68385', 'LANDÁZURI', 25); +INSERT INTO workspaces.municipalities VALUES (902, '68397', 'LA PAZ', 25); +INSERT INTO workspaces.municipalities VALUES (903, '68406', 'LEBRIJA', 25); +INSERT INTO workspaces.municipalities VALUES (904, '68418', 'LOS SANTOS', 25); +INSERT INTO workspaces.municipalities VALUES (905, '68425', 'MACARAVITA', 25); +INSERT INTO workspaces.municipalities VALUES (906, '68432', 'MÁLAGA', 25); +INSERT INTO workspaces.municipalities VALUES (907, '68444', 'MATANZA', 25); +INSERT INTO workspaces.municipalities VALUES (908, '68464', 'MOGOTES', 25); +INSERT INTO workspaces.municipalities VALUES (909, '68468', 'MOLAGAVITA', 25); +INSERT INTO workspaces.municipalities VALUES (910, '68498', 'OCAMONTE', 25); +INSERT INTO workspaces.municipalities VALUES (911, '68500', 'OIBA', 25); +INSERT INTO workspaces.municipalities VALUES (912, '68502', 'ONZAGA', 25); +INSERT INTO workspaces.municipalities VALUES (913, '68522', 'PALMAR', 25); +INSERT INTO workspaces.municipalities VALUES (914, '68524', 'PALMAS DEL SOCORRO', 25); +INSERT INTO workspaces.municipalities VALUES (915, '68533', 'PÁRAMO', 25); +INSERT INTO workspaces.municipalities VALUES (916, '68547', 'PIEDECUESTA', 25); +INSERT INTO workspaces.municipalities VALUES (917, '68549', 'PINCHOTE', 25); +INSERT INTO workspaces.municipalities VALUES (918, '68572', 'PUENTE NACIONAL', 25); +INSERT INTO workspaces.municipalities VALUES (919, '68573', 'PUERTO PARRA', 25); +INSERT INTO workspaces.municipalities VALUES (920, '68575', 'PUERTO WILCHES', 25); +INSERT INTO workspaces.municipalities VALUES (921, '68615', 'RIONEGRO', 25); +INSERT INTO workspaces.municipalities VALUES (922, '68655', 'SABANA DE TORRES', 25); +INSERT INTO workspaces.municipalities VALUES (923, '68669', 'SAN ANDRÉS', 25); +INSERT INTO workspaces.municipalities VALUES (924, '68673', 'SAN BENITO', 25); +INSERT INTO workspaces.municipalities VALUES (925, '68679', 'SAN GIL', 25); +INSERT INTO workspaces.municipalities VALUES (926, '68682', 'SAN JOAQUÍN', 25); +INSERT INTO workspaces.municipalities VALUES (927, '68684', 'SAN JOSÉ DE MIRANDA', 25); +INSERT INTO workspaces.municipalities VALUES (928, '68686', 'SAN MIGUEL', 25); +INSERT INTO workspaces.municipalities VALUES (929, '68689', 'SAN VICENTE DE CHUCURÍ', 25); +INSERT INTO workspaces.municipalities VALUES (930, '68705', 'SANTA BÁRBARA', 25); +INSERT INTO workspaces.municipalities VALUES (931, '68720', 'SANTA HELENA DEL OPÓN', 25); +INSERT INTO workspaces.municipalities VALUES (932, '68745', 'SIMACOTA', 25); +INSERT INTO workspaces.municipalities VALUES (933, '68755', 'SOCORRO', 25); +INSERT INTO workspaces.municipalities VALUES (934, '68770', 'SUAITA', 25); +INSERT INTO workspaces.municipalities VALUES (935, '68773', 'SUCRE', 25); +INSERT INTO workspaces.municipalities VALUES (936, '68780', 'SURATÁ', 25); +INSERT INTO workspaces.municipalities VALUES (937, '68820', 'TONA', 25); +INSERT INTO workspaces.municipalities VALUES (938, '68855', 'VALLE DE SAN JOSÉ', 25); +INSERT INTO workspaces.municipalities VALUES (939, '68861', 'VÉLEZ', 25); +INSERT INTO workspaces.municipalities VALUES (940, '68867', 'VETAS', 25); +INSERT INTO workspaces.municipalities VALUES (941, '68872', 'VILLANUEVA', 25); +INSERT INTO workspaces.municipalities VALUES (942, '68895', 'ZAPATOCA', 25); +INSERT INTO workspaces.municipalities VALUES (943, '70001', 'SINCELEJO', 26); +INSERT INTO workspaces.municipalities VALUES (944, '70110', 'BUENAVISTA', 26); +INSERT INTO workspaces.municipalities VALUES (945, '70124', 'CAIMITO', 26); +INSERT INTO workspaces.municipalities VALUES (946, '70204', 'COLOSÓ', 26); +INSERT INTO workspaces.municipalities VALUES (947, '70215', 'COROZAL', 26); +INSERT INTO workspaces.municipalities VALUES (948, '70221', 'COVEÑAS', 26); +INSERT INTO workspaces.municipalities VALUES (949, '70230', 'CHALÁN', 26); +INSERT INTO workspaces.municipalities VALUES (950, '70233', 'EL ROBLE', 26); +INSERT INTO workspaces.municipalities VALUES (951, '70235', 'GALERAS', 26); +INSERT INTO workspaces.municipalities VALUES (952, '70265', 'GUARANDA', 26); +INSERT INTO workspaces.municipalities VALUES (953, '70400', 'LA UNIÓN', 26); +INSERT INTO workspaces.municipalities VALUES (954, '70418', 'LOS PALMITOS', 26); +INSERT INTO workspaces.municipalities VALUES (955, '70429', 'MAJAGUAL', 26); +INSERT INTO workspaces.municipalities VALUES (956, '70473', 'MORROA', 26); +INSERT INTO workspaces.municipalities VALUES (957, '70508', 'OVEJAS', 26); +INSERT INTO workspaces.municipalities VALUES (958, '70523', 'PALMITO', 26); +INSERT INTO workspaces.municipalities VALUES (959, '70670', 'SAMPUÉS', 26); +INSERT INTO workspaces.municipalities VALUES (960, '70678', 'SAN BENITO ABAD', 26); +INSERT INTO workspaces.municipalities VALUES (961, '70702', 'SAN JUAN DE BETULIA', 26); +INSERT INTO workspaces.municipalities VALUES (962, '70708', 'SAN MARCOS', 26); +INSERT INTO workspaces.municipalities VALUES (963, '70713', 'SAN ONOFRE', 26); +INSERT INTO workspaces.municipalities VALUES (964, '70717', 'SAN PEDRO', 26); +INSERT INTO workspaces.municipalities VALUES (965, '70742', 'SAN LUIS DE SINCÉ', 26); +INSERT INTO workspaces.municipalities VALUES (966, '70771', 'SUCRE', 26); +INSERT INTO workspaces.municipalities VALUES (967, '70820', 'SANTIAGO DE TOLÚ', 26); +INSERT INTO workspaces.municipalities VALUES (968, '70823', 'SAN JOSÉ DE TOLUVIEJO', 26); +INSERT INTO workspaces.municipalities VALUES (969, '73001', 'IBAGUÉ', 27); +INSERT INTO workspaces.municipalities VALUES (970, '73024', 'ALPUJARRA', 27); +INSERT INTO workspaces.municipalities VALUES (971, '73026', 'ALVARADO', 27); +INSERT INTO workspaces.municipalities VALUES (972, '73030', 'AMBALEMA', 27); +INSERT INTO workspaces.municipalities VALUES (973, '73043', 'ANZOÁTEGUI', 27); +INSERT INTO workspaces.municipalities VALUES (974, '73055', 'ARMERO', 27); +INSERT INTO workspaces.municipalities VALUES (975, '73067', 'ATACO', 27); +INSERT INTO workspaces.municipalities VALUES (976, '73124', 'CAJAMARCA', 27); +INSERT INTO workspaces.municipalities VALUES (977, '73148', 'CARMEN DE APICALÁ', 27); +INSERT INTO workspaces.municipalities VALUES (978, '73152', 'CASABIANCA', 27); +INSERT INTO workspaces.municipalities VALUES (979, '73168', 'CHAPARRAL', 27); +INSERT INTO workspaces.municipalities VALUES (980, '73200', 'COELLO', 27); +INSERT INTO workspaces.municipalities VALUES (981, '73217', 'COYAIMA', 27); +INSERT INTO workspaces.municipalities VALUES (982, '73226', 'CUNDAY', 27); +INSERT INTO workspaces.municipalities VALUES (983, '73236', 'DOLORES', 27); +INSERT INTO workspaces.municipalities VALUES (984, '73268', 'ESPINAL', 27); +INSERT INTO workspaces.municipalities VALUES (985, '73270', 'FALAN', 27); +INSERT INTO workspaces.municipalities VALUES (986, '73275', 'FLANDES', 27); +INSERT INTO workspaces.municipalities VALUES (987, '73283', 'FRESNO', 27); +INSERT INTO workspaces.municipalities VALUES (988, '73319', 'GUAMO', 27); +INSERT INTO workspaces.municipalities VALUES (989, '73347', 'HERVEO', 27); +INSERT INTO workspaces.municipalities VALUES (990, '73349', 'HONDA', 27); +INSERT INTO workspaces.municipalities VALUES (991, '73352', 'ICONONZO', 27); +INSERT INTO workspaces.municipalities VALUES (992, '73408', 'LÉRIDA', 27); +INSERT INTO workspaces.municipalities VALUES (993, '73411', 'LÍBANO', 27); +INSERT INTO workspaces.municipalities VALUES (994, '73443', 'SAN SEBASTIÁN DE MARIQUITA', 27); +INSERT INTO workspaces.municipalities VALUES (995, '73449', 'MELGAR', 27); +INSERT INTO workspaces.municipalities VALUES (996, '73461', 'MURILLO', 27); +INSERT INTO workspaces.municipalities VALUES (997, '73483', 'NATAGAIMA', 27); +INSERT INTO workspaces.municipalities VALUES (998, '73504', 'ORTEGA', 27); +INSERT INTO workspaces.municipalities VALUES (999, '73520', 'PALOCABILDO', 27); +INSERT INTO workspaces.municipalities VALUES (1000, '73547', 'PIEDRAS', 27); +INSERT INTO workspaces.municipalities VALUES (1001, '73555', 'PLANADAS', 27); +INSERT INTO workspaces.municipalities VALUES (1002, '73563', 'PRADO', 27); +INSERT INTO workspaces.municipalities VALUES (1003, '73585', 'PURIFICACIÓN', 27); +INSERT INTO workspaces.municipalities VALUES (1004, '73616', 'RIOBLANCO', 27); +INSERT INTO workspaces.municipalities VALUES (1005, '73622', 'RONCESVALLES', 27); +INSERT INTO workspaces.municipalities VALUES (1006, '73624', 'ROVIRA', 27); +INSERT INTO workspaces.municipalities VALUES (1007, '73671', 'SALDAÑA', 27); +INSERT INTO workspaces.municipalities VALUES (1008, '73675', 'SAN ANTONIO', 27); +INSERT INTO workspaces.municipalities VALUES (1009, '73678', 'SAN LUIS', 27); +INSERT INTO workspaces.municipalities VALUES (1010, '73686', 'SANTA ISABEL', 27); +INSERT INTO workspaces.municipalities VALUES (1011, '73770', 'SUÁREZ', 27); +INSERT INTO workspaces.municipalities VALUES (1012, '73854', 'VALLE DE SAN JUAN', 27); +INSERT INTO workspaces.municipalities VALUES (1013, '73861', 'VENADILLO', 27); +INSERT INTO workspaces.municipalities VALUES (1014, '73870', 'VILLAHERMOSA', 27); +INSERT INTO workspaces.municipalities VALUES (1015, '73873', 'VILLARRICA', 27); +INSERT INTO workspaces.municipalities VALUES (1016, '76001', 'CALI', 28); +INSERT INTO workspaces.municipalities VALUES (1017, '76020', 'ALCALÁ', 28); +INSERT INTO workspaces.municipalities VALUES (1018, '76036', 'ANDALUCÍA', 28); +INSERT INTO workspaces.municipalities VALUES (1019, '76041', 'ANSERMANUEVO', 28); +INSERT INTO workspaces.municipalities VALUES (1020, '76054', 'ARGELIA', 28); +INSERT INTO workspaces.municipalities VALUES (1021, '76100', 'BOLÍVAR', 28); +INSERT INTO workspaces.municipalities VALUES (1022, '76109', 'BUENAVENTURA', 28); +INSERT INTO workspaces.municipalities VALUES (1023, '76111', 'GUADALAJARA DE BUGA', 28); +INSERT INTO workspaces.municipalities VALUES (1024, '76113', 'BUGALAGRANDE', 28); +INSERT INTO workspaces.municipalities VALUES (1025, '76122', 'CAICEDONIA', 28); +INSERT INTO workspaces.municipalities VALUES (1026, '76126', 'CALIMA', 28); +INSERT INTO workspaces.municipalities VALUES (1027, '76130', 'CANDELARIA', 28); +INSERT INTO workspaces.municipalities VALUES (1028, '76147', 'CARTAGO', 28); +INSERT INTO workspaces.municipalities VALUES (1029, '76233', 'DAGUA', 28); +INSERT INTO workspaces.municipalities VALUES (1030, '76243', 'EL ÁGUILA', 28); +INSERT INTO workspaces.municipalities VALUES (1031, '76246', 'EL CAIRO', 28); +INSERT INTO workspaces.municipalities VALUES (1032, '76248', 'EL CERRITO', 28); +INSERT INTO workspaces.municipalities VALUES (1033, '76250', 'EL DOVIO', 28); +INSERT INTO workspaces.municipalities VALUES (1034, '76275', 'FLORIDA', 28); +INSERT INTO workspaces.municipalities VALUES (1035, '76306', 'GINEBRA', 28); +INSERT INTO workspaces.municipalities VALUES (1036, '76318', 'GUACARÍ', 28); +INSERT INTO workspaces.municipalities VALUES (1037, '76364', 'JAMUNDÍ', 28); +INSERT INTO workspaces.municipalities VALUES (1038, '76377', 'LA CUMBRE', 28); +INSERT INTO workspaces.municipalities VALUES (1039, '76400', 'LA UNIÓN', 28); +INSERT INTO workspaces.municipalities VALUES (1040, '76403', 'LA VICTORIA', 28); +INSERT INTO workspaces.municipalities VALUES (1041, '76497', 'OBANDO', 28); +INSERT INTO workspaces.municipalities VALUES (1042, '76520', 'PALMIRA', 28); +INSERT INTO workspaces.municipalities VALUES (1043, '76563', 'PRADERA', 28); +INSERT INTO workspaces.municipalities VALUES (1044, '76606', 'RESTREPO', 28); +INSERT INTO workspaces.municipalities VALUES (1045, '76616', 'RIOFRÍO', 28); +INSERT INTO workspaces.municipalities VALUES (1046, '76622', 'ROLDANILLO', 28); +INSERT INTO workspaces.municipalities VALUES (1047, '76670', 'SAN PEDRO', 28); +INSERT INTO workspaces.municipalities VALUES (1048, '76736', 'SEVILLA', 28); +INSERT INTO workspaces.municipalities VALUES (1049, '76823', 'TORO', 28); +INSERT INTO workspaces.municipalities VALUES (1050, '76828', 'TRUJILLO', 28); +INSERT INTO workspaces.municipalities VALUES (1051, '76834', 'TULUÁ', 28); +INSERT INTO workspaces.municipalities VALUES (1052, '76845', 'ULLOA', 28); +INSERT INTO workspaces.municipalities VALUES (1053, '76863', 'VERSALLES', 28); +INSERT INTO workspaces.municipalities VALUES (1054, '76869', 'VIJES', 28); +INSERT INTO workspaces.municipalities VALUES (1055, '76890', 'YOTOCO', 28); +INSERT INTO workspaces.municipalities VALUES (1056, '76892', 'YUMBO', 28); +INSERT INTO workspaces.municipalities VALUES (1057, '76895', 'ZARZAL', 28); +INSERT INTO workspaces.municipalities VALUES (1058, '81001', 'ARAUCA', 29); +INSERT INTO workspaces.municipalities VALUES (1059, '81065', 'ARAUQUITA', 29); +INSERT INTO workspaces.municipalities VALUES (1060, '81220', 'CRAVO NORTE', 29); +INSERT INTO workspaces.municipalities VALUES (1061, '81300', 'FORTUL', 29); +INSERT INTO workspaces.municipalities VALUES (1062, '81591', 'PUERTO RONDÓN', 29); +INSERT INTO workspaces.municipalities VALUES (1063, '81736', 'SARAVENA', 29); +INSERT INTO workspaces.municipalities VALUES (1064, '81794', 'TAME', 29); +INSERT INTO workspaces.municipalities VALUES (1065, '85001', 'YOPAL', 30); +INSERT INTO workspaces.municipalities VALUES (1066, '85010', 'AGUAZUL', 30); +INSERT INTO workspaces.municipalities VALUES (1067, '85015', 'CHÁMEZA', 30); +INSERT INTO workspaces.municipalities VALUES (1068, '85125', 'HATO COROZAL', 30); +INSERT INTO workspaces.municipalities VALUES (1069, '85136', 'LA SALINA', 30); +INSERT INTO workspaces.municipalities VALUES (1070, '85139', 'MANÍ', 30); +INSERT INTO workspaces.municipalities VALUES (1071, '85162', 'MONTERREY', 30); +INSERT INTO workspaces.municipalities VALUES (1072, '85225', 'NUNCHÍA', 30); +INSERT INTO workspaces.municipalities VALUES (1073, '85230', 'OROCUÉ', 30); +INSERT INTO workspaces.municipalities VALUES (1074, '85250', 'PAZ DE ARIPORO', 30); +INSERT INTO workspaces.municipalities VALUES (1075, '85263', 'PORE', 30); +INSERT INTO workspaces.municipalities VALUES (1076, '85279', 'RECETOR', 30); +INSERT INTO workspaces.municipalities VALUES (1077, '85300', 'SABANALARGA', 30); +INSERT INTO workspaces.municipalities VALUES (1078, '85315', 'SÁCAMA', 30); +INSERT INTO workspaces.municipalities VALUES (1079, '85325', 'SAN LUIS DE PALENQUE', 30); +INSERT INTO workspaces.municipalities VALUES (1080, '85400', 'TÁMARA', 30); +INSERT INTO workspaces.municipalities VALUES (1081, '85410', 'TAURAMENA', 30); +INSERT INTO workspaces.municipalities VALUES (1082, '85430', 'TRINIDAD', 30); +INSERT INTO workspaces.municipalities VALUES (1083, '85440', 'VILLANUEVA', 30); +INSERT INTO workspaces.municipalities VALUES (1084, '86001', 'MOCOA', 31); +INSERT INTO workspaces.municipalities VALUES (1085, '86219', 'COLÓN', 31); +INSERT INTO workspaces.municipalities VALUES (1086, '86320', 'ORITO', 31); +INSERT INTO workspaces.municipalities VALUES (1087, '86568', 'PUERTO ASÍS', 31); +INSERT INTO workspaces.municipalities VALUES (1088, '86569', 'PUERTO CAICEDO', 31); +INSERT INTO workspaces.municipalities VALUES (1089, '86571', 'PUERTO GUZMÁN', 31); +INSERT INTO workspaces.municipalities VALUES (1090, '86573', 'PUERTO LEGUÍZAMO', 31); +INSERT INTO workspaces.municipalities VALUES (1091, '86749', 'SIBUNDOY', 31); +INSERT INTO workspaces.municipalities VALUES (1092, '86755', 'SAN FRANCISCO', 31); +INSERT INTO workspaces.municipalities VALUES (1093, '86757', 'SAN MIGUEL', 31); +INSERT INTO workspaces.municipalities VALUES (1094, '86760', 'SANTIAGO', 31); +INSERT INTO workspaces.municipalities VALUES (1095, '86865', 'VALLE DEL GUAMUEZ', 31); +INSERT INTO workspaces.municipalities VALUES (1096, '86885', 'VILLAGARZÓN', 31); +INSERT INTO workspaces.municipalities VALUES (1097, '88001', 'SAN ANDRÉS', 32); +INSERT INTO workspaces.municipalities VALUES (1098, '88564', 'PROVIDENCIA', 32); +INSERT INTO workspaces.municipalities VALUES (1099, '91001', 'LETICIA', 33); +INSERT INTO workspaces.municipalities VALUES (1100, '91263', 'EL ENCANTO', 33); +INSERT INTO workspaces.municipalities VALUES (1101, '91405', 'LA CHORRERA', 33); +INSERT INTO workspaces.municipalities VALUES (1102, '91407', 'LA PEDRERA', 33); +INSERT INTO workspaces.municipalities VALUES (1103, '91430', 'LA VICTORIA', 33); +INSERT INTO workspaces.municipalities VALUES (1104, '91460', 'MIRITÍ - PARANÁ', 33); +INSERT INTO workspaces.municipalities VALUES (1105, '91530', 'PUERTO ALEGRÍA', 33); +INSERT INTO workspaces.municipalities VALUES (1106, '91536', 'PUERTO ARICA', 33); +INSERT INTO workspaces.municipalities VALUES (1107, '91540', 'PUERTO NARIÑO', 33); +INSERT INTO workspaces.municipalities VALUES (1108, '91669', 'PUERTO SANTANDER', 33); +INSERT INTO workspaces.municipalities VALUES (1109, '91798', 'TARAPACÁ', 33); +INSERT INTO workspaces.municipalities VALUES (1110, '94001', 'INÍRIDA', 34); +INSERT INTO workspaces.municipalities VALUES (1111, '94343', 'BARRANCOMINAS', 34); +INSERT INTO workspaces.municipalities VALUES (1112, '94883', 'SAN FELIPE', 34); +INSERT INTO workspaces.municipalities VALUES (1113, '94884', 'PUERTO COLOMBIA', 34); +INSERT INTO workspaces.municipalities VALUES (1114, '94885', 'LA GUADALUPE', 34); +INSERT INTO workspaces.municipalities VALUES (1115, '94886', 'CACAHUAL', 34); +INSERT INTO workspaces.municipalities VALUES (1116, '94887', 'PANA PANA', 34); +INSERT INTO workspaces.municipalities VALUES (1117, '94888', 'MORICHAL', 34); +INSERT INTO workspaces.municipalities VALUES (1118, '95001', 'SAN JOSÉ DEL GUAVIARE', 35); +INSERT INTO workspaces.municipalities VALUES (1119, '95015', 'CALAMAR', 35); +INSERT INTO workspaces.municipalities VALUES (1120, '95025', 'EL RETORNO', 35); +INSERT INTO workspaces.municipalities VALUES (1121, '95200', 'MIRAFLORES', 35); +INSERT INTO workspaces.municipalities VALUES (1122, '97001', 'MITÚ', 36); +INSERT INTO workspaces.municipalities VALUES (1123, '97161', 'CARURÚ', 36); +INSERT INTO workspaces.municipalities VALUES (1124, '97511', 'PACOA', 36); +INSERT INTO workspaces.municipalities VALUES (1125, '97666', 'TARAIRA', 36); +INSERT INTO workspaces.municipalities VALUES (1126, '97777', 'PAPUNAHUA', 36); +INSERT INTO workspaces.municipalities VALUES (1127, '97889', 'YAVARATÉ', 36); +INSERT INTO workspaces.municipalities VALUES (1128, '99001', 'PUERTO CARREÑO', 37); +INSERT INTO workspaces.municipalities VALUES (1129, '99524', 'LA PRIMAVERA', 37); +INSERT INTO workspaces.municipalities VALUES (1130, '99624', 'SANTA ROSALÍA', 37); +INSERT INTO workspaces.municipalities VALUES (1131, '99773', 'CUMARIBO', 37); + +SELECT pg_catalog.setval('workspaces.departments_id_seq', 38, true); +SELECT pg_catalog.setval('workspaces.integrations_histories_id_seq', 1, false); +SELECT pg_catalog.setval('workspaces.integrations_id_seq', 1, false); +SELECT pg_catalog.setval('workspaces.integrations_states_id_seq', 8, true); +SELECT pg_catalog.setval('workspaces.integrations_stats_id_seq', 1, false); +SELECT pg_catalog.setval('workspaces.municipalities_id_seq', 1131, true); +SELECT pg_catalog.setval('workspaces.workspace_managers_id_seq', 1, false); +SELECT pg_catalog.setval('workspaces.workspace_operators_id_seq', 1, false); +SELECT pg_catalog.setval('workspaces.workspaces_id_seq', 1, false); + +ALTER TABLE ONLY workspaces.departments + ADD CONSTRAINT departments_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.integrations_histories + ADD CONSTRAINT integrations_histories_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.integrations + ADD CONSTRAINT integrations_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.integrations_states + ADD CONSTRAINT integrations_states_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.integrations_stats + ADD CONSTRAINT integrations_stats_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.municipalities + ADD CONSTRAINT municipalities_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.workspace_managers + ADD CONSTRAINT workspace_managers_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.workspace_operators + ADD CONSTRAINT workspace_operators_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.workspaces + ADD CONSTRAINT workspaces_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY workspaces.integrations_histories + ADD CONSTRAINT fk22lcf7sk847shkiqemx9mmheo FOREIGN KEY (integration_state_id) REFERENCES workspaces.integrations_states(id); + +ALTER TABLE ONLY workspaces.workspace_managers + ADD CONSTRAINT fk3v94oq02hsfq0rrm0nr8rkcxx FOREIGN KEY (workspace_id) REFERENCES workspaces.workspaces(id); + +ALTER TABLE ONLY workspaces.integrations + ADD CONSTRAINT fk9upl96ljkw91e5kgxptp2usfw FOREIGN KEY (integration_state_id) REFERENCES workspaces.integrations_states(id); + +ALTER TABLE ONLY workspaces.workspaces + ADD CONSTRAINT fkb8odxsgj7w7odd35pdm21v9ag FOREIGN KEY (workspace_id) REFERENCES workspaces.workspaces(id); + +ALTER TABLE ONLY workspaces.integrations + ADD CONSTRAINT fkbrb65h3gd37lif5f9nyvrtwuv FOREIGN KEY (workspace_id) REFERENCES workspaces.workspaces(id); + +ALTER TABLE ONLY workspaces.municipalities + ADD CONSTRAINT fkbv7fvmtec7tpmhxb6ojlhgm6m FOREIGN KEY (department_id) REFERENCES workspaces.departments(id); + +ALTER TABLE ONLY workspaces.integrations_stats + ADD CONSTRAINT fkfi59r439mkqwqa2aimpix6u7e FOREIGN KEY (integration_id) REFERENCES workspaces.integrations(id); + +ALTER TABLE ONLY workspaces.workspace_operators + ADD CONSTRAINT fkklakxhmuhmf6ekqu4m2g2r747 FOREIGN KEY (workspace_id) REFERENCES workspaces.workspaces(id); + +ALTER TABLE ONLY workspaces.workspaces + ADD CONSTRAINT fkmo4nentxq08qcfy4uwxh7v5ud FOREIGN KEY (municipality_id) REFERENCES workspaces.municipalities(id); + +ALTER TABLE ONLY workspaces.integrations_histories + ADD CONSTRAINT fktowme6te1tg8yup02jcyh38xo FOREIGN KEY (integration_id) REFERENCES workspaces.integrations(id); \ No newline at end of file diff --git a/src/test/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationTests.java b/src/test/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationTests.java index 925a32b..a2bf5bb 100644 --- a/src/test/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationTests.java +++ b/src/test/java/com/ai/st/microservice/workspaces/StMicroserviceWorkspacesApplicationTests.java @@ -6,8 +6,8 @@ @SpringBootTest class StMicroserviceWorkspacesApplicationTests { - @Test - void contextLoads() { - } + @Test + void contextLoads() { + } }