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 extends MicroserviceSupplyDeliveryDto> 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 extends MicroserviceSupplyDeliveryDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceTaskMemberDto> 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 extends MicroserviceSupplyRequestedDto> suppliesResponseDto = requestUpdatedDto.getSuppliesRequested();
- List suppliesRequestedDto =
- suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList());
+ List extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> suppliesResponseDto = requestDto.getSuppliesRequested();
- List suppliesRequestedDto =
- suppliesResponseDto.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList());
+ try {
- for (CustomSupplyRequestedDto supplyRequested : suppliesRequestedDto) {
+ List extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceEmitterDto> 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 extends MicroserviceEmitterDto> 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 extends MicroserviceEmitterDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceEmitterDto> 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 extends MicroserviceEmitterDto> 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 extends MicroserviceSupplyDeliveryDto> suppliesResponse = deliveryFoundDto.getSupplies();
- List suppliesDeliveryDto =
- suppliesResponse.stream().map(CustomSupplyDeliveryDto::new).collect(Collectors.toList());
+ List extends MicroserviceSupplyDeliveryDto> 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 extends MicroserviceTaskMemberDto> 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 extends MicroserviceTaskMemberDto> 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 extends MicroserviceTaskMemberDto> 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 extends MicroserviceTaskMemberDto> 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 extends MicroserviceSupplyRequestedDto> suppliesResponse = requestDto.getSuppliesRequested();
- List suppliesRequestDto =
- suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList());
+ List extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceTaskMemberDto> 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 extends MicroserviceSupplyRequestedDto> suppliesResponse = responseRequest.getSuppliesRequested();
- List suppliesRequestDto =
- suppliesResponse.stream().map(CustomSupplyRequestedDto::new).collect(Collectors.toList());
+ List extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceEmitterDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceSupplyRequestedDto> 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 extends MicroserviceEmitterDto> 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