diff --git a/pom.xml b/pom.xml
index 1e6d394a..b443ec18 100644
--- a/pom.xml
+++ b/pom.xml
@@ -212,6 +212,13 @@
8.0.5
+
+ io.springfox
+ springfox-boot-starter
+ 3.0.0
+
+
+
diff --git a/src/main/java/net/gepafin/tendermanagement/config/SamlConfig.java b/src/main/java/net/gepafin/tendermanagement/config/SamlConfig.java
index c66e26f1..c69b7316 100644
--- a/src/main/java/net/gepafin/tendermanagement/config/SamlConfig.java
+++ b/src/main/java/net/gepafin/tendermanagement/config/SamlConfig.java
@@ -29,6 +29,7 @@ import org.opensaml.xmlsec.signature.support.SignatureConstants;
import org.opensaml.xmlsec.signature.support.Signer;
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.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -41,6 +42,13 @@ import org.springframework.security.saml2.provider.service.web.DefaultRelyingPar
import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver;
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
import org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import jakarta.servlet.http.HttpServletRequest;
+import net.gepafin.tendermanagement.entities.SamlResponseEntity;
+import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
+import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
@Configuration
public class SamlConfig {
@@ -55,6 +63,9 @@ public class SamlConfig {
@Value("${active.profile.folder}")
String activeProfileFolder;
+
+ @Autowired
+ private SamlResponseRepository samlResponseRepository;
@Bean
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
@@ -123,44 +134,56 @@ public class SamlConfig {
return authnRequest;
}
-@Bean
-public Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingPartyRegistrationRepository registrations) {
- RelyingPartyRegistrationResolver registrationResolver = new DefaultRelyingPartyRegistrationResolver(registrations);
- OpenSaml4AuthenticationRequestResolver authenticationRequestResolver = new OpenSaml4AuthenticationRequestResolver(registrationResolver);
+ @Bean
+ public Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingPartyRegistrationRepository registrations) {
+ RelyingPartyRegistrationResolver registrationResolver = new DefaultRelyingPartyRegistrationResolver(registrations);
+ OpenSaml4AuthenticationRequestResolver authenticationRequestResolver = new OpenSaml4AuthenticationRequestResolver(registrationResolver);
- authenticationRequestResolver.setAuthnRequestCustomizer((context) -> {
- // Set the required attributes
- AuthnRequest authnRequest = context.getAuthnRequest();
- authnRequest.setID("_" + UUID.randomUUID().toString()); // Add a unique ID
- authnRequest.setVersion(SAMLVersion.VERSION_20); // Ensure version is 2.0
- authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI); // HTTP-POST
+ authenticationRequestResolver.setAuthnRequestCustomizer((context) -> {
- // Set Authentication Context
- authnRequest.setRequestedAuthnContext(buildRequestedAuthnContext());
+ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
+ String hubUuid = (String) request.getAttribute("hubId");
- // Log the SAML AuthnRequest after setting context
- String samlRequest = SamlRequestLogger.convertSAMLObjectToString(authnRequest);
- logger.info("SAML AuthnRequest after setting context: " + samlRequest);
- });
+ logger.info("Hub id " + hubUuid);
+ String inResponseTo = "_" + UUID.randomUUID().toString();
+
+ // Continue with normal AuthnRequest configuration
+ AuthnRequest authnRequest = context.getAuthnRequest();
+ authnRequest.setID(inResponseTo);
+ authnRequest.setVersion(SAMLVersion.VERSION_20);
+ authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
+ authnRequest.setRequestedAuthnContext(buildRequestedAuthnContext());
+
+
+ SamlResponseEntity samlResponse = new SamlResponseEntity();
+ samlResponse.setHubUuid(hubUuid);
+ samlResponse.setInResponseTo(inResponseTo);
+ samlResponse.setStatus(SamlResponseStatusEnum.INITIATED.getValue());
+ samlResponseRepository.save(samlResponse);
+ // Log the SAML AuthnRequest after setting context
+ String samlRequest = SamlRequestLogger.convertSAMLObjectToString(authnRequest);
+ logger.info("SAML AuthnRequest after setting context: " + samlRequest);
+ });
- return authenticationRequestResolver;
-}
+ return authenticationRequestResolver;
+ }
-private RequestedAuthnContext buildRequestedAuthnContext() {
- AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
- AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
- SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX
- );
- // Set the SPID Level 2 authentication context
- authnContextClassRef.setURI("urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword");
- RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
- RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
- requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
- requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
-
- return requestedAuthnContext;
-}
+ private RequestedAuthnContext buildRequestedAuthnContext() {
+ AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
+ AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
+ SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX
+ );
+ // Set the SPID Level 2 authentication context
+ authnContextClassRef.setURI("urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword");
+
+ RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
+ RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
+ requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
+ requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
+
+ return requestedAuthnContext;
+ }
public PrivateKey readPrivateKey() throws Exception {
// Path to your private key PEM file
diff --git a/src/main/java/net/gepafin/tendermanagement/config/SamlFailureHandler.java b/src/main/java/net/gepafin/tendermanagement/config/SamlFailureHandler.java
index 171b7e12..d2337ee9 100644
--- a/src/main/java/net/gepafin/tendermanagement/config/SamlFailureHandler.java
+++ b/src/main/java/net/gepafin/tendermanagement/config/SamlFailureHandler.java
@@ -1,9 +1,13 @@
package net.gepafin.tendermanagement.config;
import java.io.IOException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.commons.lang3.StringUtils;
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.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
@@ -11,6 +15,12 @@ import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
+import net.gepafin.tendermanagement.constants.GepafinConstant;
+import net.gepafin.tendermanagement.entities.SamlResponseEntity;
+import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
+import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
+import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
+import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@Component
public class SamlFailureHandler implements AuthenticationFailureHandler {
@@ -20,16 +30,40 @@ public class SamlFailureHandler implements AuthenticationFailureHandler {
@Value("${fe.base.url}")
private String feBaseUrl;
+ @Autowired
+ private SamlResponseRepository samlResponseRepository;
+
@Override
- public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
- AuthenticationException exception) throws IOException {
- try {
- logger.error("SAML login failed: " + exception.getMessage());
-
+ public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
+ AuthenticationException exception) throws IOException {
+ try {
+ logger.error("SAML login failed: " + exception.getMessage());
+ String inResponseTo = extractInResponseTo(feBaseUrl);
+ if (Boolean.FALSE.equals(StringUtils.isEmpty(inResponseTo))) {
+ SamlResponseEntity samlResponseLogEntity = samlResponseRepository
+ .findByInResponseToAndStatus(inResponseTo, SamlResponseStatusEnum.INITIATED.getValue())
+ .orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST,
+ Translator.toLocale(GepafinConstant.INVALID_REQUEST)));
+ samlResponseLogEntity.setStatus(SamlResponseStatusEnum.FAILED.getValue());
+ samlResponseRepository.save(samlResponseLogEntity);
+ }
response.sendRedirect(feBaseUrl + "/login");
- } catch (Exception e) {
- logger.error("Error processing SAML failure handler", e);
- }
- }
+ } catch (Exception e) {
+ logger.error("Error processing SAML failure handler", e);
+ }
+ }
+
+ public static String extractInResponseTo(String message) {
+ String regex = "InResponseTo attribute \\[([a-zA-Z0-9\\-]+)\\]";
+
+ Pattern pattern = Pattern.compile(regex);
+ Matcher matcher = pattern.matcher(message);
+
+ if (matcher.find()) {
+ return matcher.group(1);
+ } else {
+ return null;
+ }
+ }
}
diff --git a/src/main/java/net/gepafin/tendermanagement/config/SamlRequestFilter.java b/src/main/java/net/gepafin/tendermanagement/config/SamlRequestFilter.java
new file mode 100644
index 00000000..a7b3a664
--- /dev/null
+++ b/src/main/java/net/gepafin/tendermanagement/config/SamlRequestFilter.java
@@ -0,0 +1,24 @@
+package net.gepafin.tendermanagement.config;
+
+import java.io.IOException;
+
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import jakarta.servlet.FilterChain;
+import jakarta.servlet.ServletException;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+@Component
+public class SamlRequestFilter extends OncePerRequestFilter {
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException {
+ String hub = request.getParameter("hubId");
+ if (hub != null) {
+ request.setAttribute("hubId", hub); // Store the hub ID as an attribute
+ }
+ filterChain.doFilter(request, response);
+ }
+}
diff --git a/src/main/java/net/gepafin/tendermanagement/config/SamlSuccessHandler.java b/src/main/java/net/gepafin/tendermanagement/config/SamlSuccessHandler.java
index 868b0eae..14f2b1bf 100644
--- a/src/main/java/net/gepafin/tendermanagement/config/SamlSuccessHandler.java
+++ b/src/main/java/net/gepafin/tendermanagement/config/SamlSuccessHandler.java
@@ -1,9 +1,14 @@
package net.gepafin.tendermanagement.config;
+import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -13,16 +18,21 @@ import org.springframework.security.saml2.provider.service.authentication.Saml2A
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.constants.GepafinConstant;
+import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
+import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.repositories.UserRepository;
+import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -40,6 +50,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
@Value("${fe.base.url}")
private String feBaseUrl;
+
+ @Autowired
+ private HubService hubService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
@@ -52,21 +65,52 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
Map> userAttributes = principal.getAttributes();
String token = Utils.generateSecureToken();
logger.info("SAML User Attributes: " + userAttributes);
+
+ // Extracting raw SAML response
+ String samlResponse = samlAuth.getSaml2Response();
+ logger.info("Raw SAML Response: " + samlResponse);
+
+ // If samlResponse is already in XML format, do not Base64 decode it
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ Document document = builder.parse(new ByteArrayInputStream(samlResponse.getBytes())); // Remove the Base64 decoding
- SamlResponseEntity samlResponseLogEntity = new SamlResponseEntity();
- samlResponseLogEntity.setAuthenticationObject(authentication.toString());
+ // Extracting ID, InResponseTo, and IssueInstant from the Response element
+ Element responseElement = (Element) document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "Response").item(0);
+ String responseId = responseElement.getAttribute("ID");
+ String inResponseTo = responseElement.getAttribute("InResponseTo");
+ String issueInstant = responseElement.getAttribute("IssueInstant");
+ logger.info("SAML Response ID: " + responseId);
+ logger.info("InResponseTo: " + inResponseTo);
+ logger.info("IssueInstant: " + issueInstant);
+
+ SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository
+ .findByInResponseToAndStatus(inResponseTo, SamlResponseStatusEnum.INITIATED.getValue())
+ .orElseThrow(() -> new CustomValidationException(Status.BAD_REQUEST,
+ Translator.toLocale(GepafinConstant.INVALID_REQUEST)));
ObjectMapper objectMapper = new ObjectMapper();
String userAttributesJson = objectMapper.writeValueAsString(userAttributes);
+
samlResponseLogEntity.setAuthenticationObject(userAttributesJson);
samlResponseLogEntity.setToken(token);
+ samlResponseLogEntity.setStatus(SamlResponseStatusEnum.SUCCESS.getValue());
+ samlResponseLogEntity.setInResponseTo(inResponseTo);
+ samlResponseLogEntity.setSamlId(responseId);
+ samlResponseLogEntity.setIssueInstant(issueInstant);
samlResponseLogRepository.save(samlResponseLogEntity);
-
+
+ HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
+
String redirectUrl = feBaseUrl;
+ if (Boolean.FALSE.equals(StringUtils.isEmpty(hub.getDomainName()))) {
+ redirectUrl = hub.getDomainName();
+ }
logger.info("SAML login successful for user: " + principal.getName());
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
- UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf).orElse(null);
+ UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscaleAndHubId(cf, hub.getId()).orElse(null);
if (userEntity == null) {
redirectUrl += "/registration?temp_token=" + token;
} else {
@@ -79,9 +123,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
}
}
- public void validateToken(String token, String codiceFiscale) {
+ public void validateToken(String token, String codiceFiscale, String hubUuid) {
SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository.findByToken(token);
- if (samlResponseLogEntity == null) {
+ if (samlResponseLogEntity == null || Boolean.FALSE.equals(hubUuid.equals(samlResponseLogEntity.getHubUuid()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
@@ -92,7 +136,6 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
}
- samlResponseLogRepository.delete(samlResponseLogEntity);
}
}
diff --git a/src/main/java/net/gepafin/tendermanagement/config/SecurityConfig.java b/src/main/java/net/gepafin/tendermanagement/config/SecurityConfig.java
index 90c278d4..090f3688 100644
--- a/src/main/java/net/gepafin/tendermanagement/config/SecurityConfig.java
+++ b/src/main/java/net/gepafin/tendermanagement/config/SecurityConfig.java
@@ -15,6 +15,7 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHt
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.saml2.provider.service.web.Saml2WebSsoAuthenticationRequestFilter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
@@ -106,24 +107,22 @@ public class SecurityConfig {
.requestMatchers("/saml2/**").permitAll() // SAML login initiation
.requestMatchers("/swagger-ui/**").permitAll() // Swagger docs
.requestMatchers("/v1/api-docs/**").permitAll() // API docs
+ .requestMatchers("/v1/user/reset-password/initiate").permitAll()
+ .requestMatchers("/v1/user/reset-password").permitAll()
.anyRequest().authenticated())
- .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
- .exceptionHandling(exceptionHandling -> exceptionHandling
- .authenticationEntryPoint((request, response, authException) -> {
- // Send 403 Forbidden when there is no JWT token provided
- response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden: Authentication token is missing or invalid");
- })
- )
- .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
- .addFilterBefore(new JWTFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
- // Add SAML2 login configuration (for BENEFICIARI)
- /*
- * .saml2Login(saml -> saml.loginPage("/saml/login") // Entry point for SAML
- * login .defaultSuccessUrl("/") // Redirect after successful SAML login );
- */
- .saml2Login(saml -> saml.defaultSuccessUrl("/").successHandler(samlSuccessHandler)
- .failureHandler(samlFailureHandler));
-
+ .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED))
+ .exceptionHandling(exceptionHandling -> exceptionHandling
+ .authenticationEntryPoint((request, response, authException) -> {
+ // Send 403 Forbidden when there is no JWT token provided
+ response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden: Authentication token is missing or invalid");
+ })
+ )
+ .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
+ .addFilterBefore(new JWTFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
+ .addFilterBefore(new SamlRequestFilter(), Saml2WebSsoAuthenticationRequestFilter.class) // Add the custom SAML filter
+ .saml2Login(saml -> saml.defaultSuccessUrl("/")
+ .successHandler(samlSuccessHandler)
+ .failureHandler(samlFailureHandler));
return http.build();
}
diff --git a/src/main/java/net/gepafin/tendermanagement/config/jwt/TokenProvider.java b/src/main/java/net/gepafin/tendermanagement/config/jwt/TokenProvider.java
index d299b6ff..884c848f 100644
--- a/src/main/java/net/gepafin/tendermanagement/config/jwt/TokenProvider.java
+++ b/src/main/java/net/gepafin/tendermanagement/config/jwt/TokenProvider.java
@@ -104,6 +104,10 @@ public class TokenProvider {
if(user != null) {
payload += ":"+user.getId();
}
+
+ if(user != null) {
+ payload += ":"+user.getHub().getId();
+ }
String token = Jwts.builder()
.setSubject(payload)
diff --git a/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java b/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java
index d59010ea..c5b18460 100644
--- a/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java
+++ b/src/main/java/net/gepafin/tendermanagement/constants/GepafinConstant.java
@@ -225,9 +225,31 @@ public class GepafinConstant {
public static final String DD_MM_YYYY = "dd/MM/yyyy";
public static final String DASHBOARD_WIDGET_FETCHED_SUCCESSFULLY="dashboard.widget.fetched.successfully";
+ public static final Integer DEFAULT_PAGE_LIMIT = 1000;
+ public static final Integer DEFAULT_PAGE = 1;
+ public static final String ATTEMPT_DATE = "attemptDate";
+ public static final String LOGIN_ATTEMPTED_CREATED_SUCCESSFULLY="login_attempt_successfully_created";
+ public static final String GET_LOGIN_ATTEMPT_MSG="get_login_attempt_se_msg";
+ public static final String CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT = "application.in.submit.status.cannot.delete.company";
+ public static final String GET_USERS_SUCCESS_MSG = "get.users.success.msg";
+ public static final String CANNOT_CREATE_BENEFICIARY_USER="cannot.create.beneficiary.user";
- public static final String GET_ERROR_S3 = "get.error.s3";
-
+ public static final String APPLICATION_ASSIGNED= "application.assigned.success.msg";
+ public static final String APPLICATION_ALREADY_ASSIGNED = "application.already.assigned.msg";
+ public static final String ASSIGNED_APPLICATION_NOT_FOUND_MSG="aasigned.application.not.found";
+ public static final String DELETE_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.deleted.success";
+ public static final String GET_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.get.success";
+ public static final String ASSIGNED_APPLICATION_UPDATE_SUCCESSFULLY_MSG = "assigned.application.update.successfully";
+ public static final String HUB_CREATE_SUCCESS = "hub_create_success";
+ public static final String HUB_UPDATE_SUCCESS = "hub_update_success";
+ public static final String HUB_GET_SUCCESS = "hub_get_success";
+ public static final String HUB_GET_ALL_SUCCESS = "hub_get_all_success";
+ public static final String HUB_DELETE_SUCCESS = "hub_delete_success";
+ public static final String HUB_NOT_FOUND = "hub_not_found";
+ public static final String EVALUATIONCRITERIA_INVALID = "evaluationCriteria.invalid";
+ public static final String APPLICATION_NOT_IN_DRAFT_STATUS="application.not.in.draft.status";
+ public static final String GET_ERROR_S3 = "get.error.s3";
+ public static final String INVALID_APPLICATION_STATUS = "invalid.application.status";
}
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java
index ad2ac4a2..c68d3f2e 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/ApplicationDao.java
@@ -20,6 +20,7 @@ import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.DocumentService;
import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
+import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.MailUtil;
@@ -119,19 +120,26 @@ public class ApplicationDao {
@Value("${aws.s3.url.folder.signed.document}")
private String signedDocumentS3Folder;
+
+ @Value("${default.hub.uuid}")
+ private String defaultHubUuid;
+
+ @Autowired
+ private UserService userService;
- public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId, Long applicationId) {
+ public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId);
// callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId);
- if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
- throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED));
+ validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
+ if(Boolean.FALSE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.DRAFT.getValue()))) {
+ throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
}
formService.validateFormField(applicationRequestBean.getFormFields(),applicationEntity,formEntity);
ApplicationFormEntity applicationFormEntity = getApplicationFormOrCreate(formEntity, applicationEntity);
- createOrUpdateMultipleFormFields(applicationRequestBean.getFormFields(), applicationFormEntity,formEntity);
+ createOrUpdateMultipleFormFields(applicationRequestBean.getFormFields(), applicationFormEntity, formEntity);
return getApplicationById(applicationEntity.getId(),formEntity.getId());
}
public void validateDelegation(UserEntity user, CompanyEntity company) {
@@ -167,6 +175,7 @@ public class ApplicationDao {
entity.setUserId(user.getId());
entity.setCompany(companyEntity);
entity.setCall(call);
+ entity.setHubId(call.getHub().getId());
entity.setIsDeleted(false);
entity.setStatus(ApplicationStatusTypeEnum.DRAFT.getValue());
return entity;
@@ -229,10 +238,11 @@ public class ApplicationDao {
return applicationFormFieldResponseBeans;
}
- public void deleteById(Long id) {
+ public void deleteById(HttpServletRequest request, Long id) {
log.info("Deleting application with ID: {}", id);
ApplicationEntity applicationEntity= validateApplication(id);
+ validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
applicationEntity.setIsDeleted(true);
applicationEntity=saveApplicationEntity(applicationEntity);
log.info("Application deleted with ID: {}", id);
@@ -274,11 +284,11 @@ public class ApplicationDao {
// return applicationResponses;
// }
- public List getAllApplications(UserEntity userEntity, Long callId, Long companyId) {
+ public List getAllApplications(UserEntity userEntity, Long callId, Long companyId,String status) {
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
- Specification spec = search(userEntity.getId(), callId, companyId);
+ Specification spec = search(userEntity, callId, companyId,status);
List applicationEntities = applicationRepository.findAll(spec);
@@ -288,12 +298,12 @@ public class ApplicationDao {
}
- private Specification search(Long userId, Long callId, Long companyId) {
+ private Specification search(UserEntity userEntity, Long callId, Long companyId,String status) {
return (root, query, builder) -> {
Boolean isBeneficiary = validator.checkIsBeneficiary();
Predicate predicate = builder.isFalse(root.get("isDeleted"));
if (isBeneficiary) {
- predicate = builder.and(predicate, builder.equal(root.get("userId"), userId));
+ predicate = builder.and(predicate, builder.equal(root.get("userId"), userEntity.getId()));
}
if (callId != null) {
predicate = builder.and(predicate, builder.equal(root.get("call").get("id"), callId));
@@ -301,6 +311,10 @@ public class ApplicationDao {
if (companyId != null) {
predicate = builder.and(predicate, builder.equal(root.get("company").get("id"), companyId));
}
+ if (status != null) {
+ predicate = builder.and(predicate, builder.equal(root.get("status"), status));
+ }
+ predicate = builder.and(predicate, builder.equal(root.get("hubId"), userEntity.getHub().getId()));
return predicate;
};
}
@@ -467,9 +481,10 @@ public class ApplicationDao {
return applicationEntity;
}
- public ApplicationGetResponseBean getApplicationByFormId( Long applicationId, Long formId, UserEntity userEntity) {
+ public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId, Long formId) {
List formApplicationResponses = new ArrayList<>();
List formEntities = new ArrayList<>();
+ UserEntity userEntity = validator.validateUser(request);
boolean isBeneficiary = isBeneficiary(userEntity);
ApplicationEntity applicationEntity = isBeneficiary
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
@@ -574,8 +589,10 @@ public class ApplicationDao {
}
}
- public ApplicationResponse updateApplicationStatus(UserEntity userEntity, Long applicationId, ApplicationStatusTypeEnum status) {
+ public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
ApplicationEntity applicationEntity = validateApplication(applicationId);
+ UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
+ validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
}
@@ -583,41 +600,32 @@ public class ApplicationDao {
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(status.getValue()))){
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_IN_PREVIOUS_STATUS));
}
- if (status.equals(ApplicationStatusTypeEnum.SUBMIT)) {
- callService.validatePublishedCall(applicationEntity.getCall().getId());
-// CallEntity callEntity = applicationEntity.getCall();
-// Long initialFormId = callEntity.getInitialForm();
-// Long finalFormId = callEntity.getFinalForm();
-//// if (initialFormId == null || finalFormId == null) {
-//// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
-//// }
-// ApplicationFormEntity initialApplicationForm = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), initialFormId);
-// ApplicationFormEntity finalApplicationForm = applicationFormRepository.findByApplicationIdAndFormId(applicationEntity.getId(), finalFormId);
-// if (initialApplicationForm == null || finalApplicationForm == null) {
-// throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
-// }
- List flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
- Long totalSteps=flowFormDao.calculateTotalSteps(flowEdgesList);
- Integer completedSteps=flowFormDao.getCompletedSteps(applicationEntity);
- if (totalSteps.intValue() != completedSteps) {
- throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
- }
- Integer maxProtocolNumber=protocolRepository.findMaxProtocolNumber();
- Integer protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 1;
- ProtocolEntity protocolEntity=createProtocolEntity(applicationEntity,protocolNumber);
+ if (status.equals(ApplicationStatusTypeEnum.SUBMIT) && Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.READY.getValue()))) {
+ callService.validatePublishedCall(applicationEntity.getCall().getId(), userEntity.getHub().getId());
+ Long protocolNumber = getProtocolNumber(userEntity.getHub());
+ ProtocolEntity protocolEntity = createProtocolEntity(applicationEntity,protocolNumber, userEntity.getHub().getId());
applicationEntity.setProtocol(protocolEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
+ applicationEntity = saveApplicationEntity(applicationEntity);
sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
- } else {
applicationEntity.setStatus(status.getValue());
+ applicationEntity = saveApplicationEntity(applicationEntity);
}
- applicationEntity = saveApplicationEntity(applicationEntity);
+
return getApplicationResponse(applicationEntity);
}
+ private Long getProtocolNumber(HubEntity hubEntity) {
+ Long maxProtocolNumber = protocolRepository.findMaxProtocolNumberAndHubId(hubEntity.getId());
+ Long startNumber = 10000001L;
+ if(Boolean.FALSE.equals(defaultHubUuid.equals(hubEntity.getUniqueUuid()))) {
+ startNumber = 20000001L;
+ }
+ return (maxProtocolNumber != null) ? maxProtocolNumber + 1 : startNumber;
+ }
public Integer calculateProgress(Long totalSteps, Long completedSteps) {
if (FieldValidator.isNullOrZero(totalSteps)) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.TOTAL_STEPS_NOT_BE_ZERO));
@@ -691,14 +699,15 @@ public class ApplicationDao {
}
}
- public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Integer protocolNumber){
+ public ProtocolEntity createProtocolEntity(ApplicationEntity applicationEntity,Long protocolNumber, Long hubId){
ProtocolEntity protocolEntity=new ProtocolEntity();
protocolEntity.setCall(applicationEntity.getCall().getId());
LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
protocolEntity.setYear(utcDateTime.getYear());
- protocolEntity.setProtocolNumber(Long.valueOf(protocolNumber));
+ protocolEntity.setProtocolNumber(protocolNumber);
protocolEntity.setTime(LocalTime.now());
protocolEntity.setApplicationId(applicationEntity.getId());
+ protocolEntity.setHubId(hubId);
protocolRepository.save(protocolEntity);
return protocolEntity;
}
@@ -763,7 +772,9 @@ public class ApplicationDao {
mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
- mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
+ if(validator.isProductionProfileActivated()) {
+ mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
+ }
}
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,
@@ -774,8 +785,9 @@ public class ApplicationDao {
ApplicationSignedDocumentEntity applicationSignedDocument = applicationSignedDocumentRepository
.findByApplicationIdAndStatus(applicationId, ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
if (applicationSignedDocument != null) {
- applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
- applicationSignedDocumentRepository.save(applicationSignedDocument);
+ throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_ASSIGNED));
+// applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
+// applicationSignedDocumentRepository.save(applicationSignedDocument);
}
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = amazonS3Service.uploadFileOnAmazonS3(signedDocumentS3Folder,
file);
@@ -785,6 +797,8 @@ public class ApplicationDao {
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
+ applicationEntity.setStatus(ApplicationStatusTypeEnum.READY.getValue());
+ applicationRepository.save(applicationEntity);
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
}
@@ -841,4 +855,24 @@ public class ApplicationDao {
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.INACTIVE.getValue());
applicationSignedDocumentRepository.save(applicationSignedDocument);
}
+
+ public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId) {
+ ApplicationEntity applicationEntity = validateApplication(applicationId);
+ UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
+ validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
+ if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.DRAFT.getValue().equals(applicationEntity.getStatus()))) {
+ throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_NOT_IN_DRAFT_STATUS));
+ }
+ List flowEdgesList = flowEdgesRepository.findByCallId(applicationEntity.getCall().getId());
+ Long totalSteps=flowFormDao.calculateTotalSteps(flowEdgesList);
+ Integer completedSteps=flowFormDao.getCompletedSteps(applicationEntity);
+ if (totalSteps.intValue() != completedSteps) {
+ throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
+ }
+
+ applicationEntity.setStatus(ApplicationStatusTypeEnum.AWAITING.getValue());
+ applicationEntity = saveApplicationEntity(applicationEntity);
+ return getApplicationResponse(applicationEntity);
+ }
+
}
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/AssignedApplicationsDao.java b/src/main/java/net/gepafin/tendermanagement/dao/AssignedApplicationsDao.java
new file mode 100644
index 00000000..f04b5e98
--- /dev/null
+++ b/src/main/java/net/gepafin/tendermanagement/dao/AssignedApplicationsDao.java
@@ -0,0 +1,207 @@
+package net.gepafin.tendermanagement.dao;
+import jakarta.persistence.criteria.Predicate;
+import jakarta.servlet.http.HttpServletRequest;
+import net.gepafin.tendermanagement.config.Translator;
+import net.gepafin.tendermanagement.constants.GepafinConstant;
+import net.gepafin.tendermanagement.entities.ApplicationEntity;
+import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
+import net.gepafin.tendermanagement.entities.UserEntity;
+import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
+import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
+import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
+import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
+import net.gepafin.tendermanagement.repositories.ApplicationRepository;
+import net.gepafin.tendermanagement.repositories.AssignedApplicationsRepository;
+import net.gepafin.tendermanagement.service.ApplicationService;
+import net.gepafin.tendermanagement.service.UserService;
+import net.gepafin.tendermanagement.util.DateTimeUtil;
+import net.gepafin.tendermanagement.util.Validator;
+import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
+import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
+import net.gepafin.tendermanagement.web.rest.api.errors.Status;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Component;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static net.gepafin.tendermanagement.util.Utils.log;
+import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
+
+@Component
+public class AssignedApplicationsDao {
+
+ @Autowired
+ private ApplicationService applicationService;
+
+ @Autowired
+ private ApplicationRepository applicationRepository;
+
+ @Autowired
+ private AssignedApplicationsRepository assignedApplicationsRepository;
+
+ @Autowired
+ private UserService userService;
+
+ @Autowired
+ private Validator validator;
+
+ public AssignedApplicationsResponse createAssignedApplications(Long applicationId, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest){
+ log.info("Assigning application to pre-Instructor with details: {}", applicationId,userId);
+
+ AssignedApplicationsEntity assignedApplications = assignedApplicationsRepository.findByApplicationIdAndIsDeletedFalse(applicationId).orElse(null);
+ if(assignedApplications!=null){
+ throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_ASSIGNED));
+ }
+ ApplicationEntity application = applicationService.validateApplication(applicationId);
+
+
+ if (Boolean.FALSE.equals(ApplicationStatusTypeEnum.SUBMIT.getValue().equals(application.getStatus()))) {
+ throw new CustomValidationException(
+ Status.BAD_REQUEST,
+ Translator.toLocale(GepafinConstant.INVALID_APPLICATION_STATUS)
+ );
+ }
+ application.setStatus(ApplicationStatusTypeEnum.EVALUATION.getValue());
+ applicationRepository.save(application);
+ UserEntity user = userService.validateUser(userId);
+ AssignedApplicationsEntity assignment = createAssignmentEntity(application, user.getId(), assignedByUser, assignedApplicationsRequest);
+ AssignedApplicationsResponse assignApplicationToInstructorResponse = convertEntityToResponse(assignment);
+
+ log.info("Application assigned succesfully {}", assignApplicationToInstructorResponse);
+ return assignApplicationToInstructorResponse;
+ }
+
+ public AssignedApplicationsEntity createAssignmentEntity(ApplicationEntity application, Long userId, UserEntity assignedByUser, AssignedApplicationsRequest assignedApplicationsRequest){
+ AssignedApplicationsEntity assignApplication= new AssignedApplicationsEntity();
+ assignApplication.setApplication(application);
+ assignApplication.setAssignedBy(assignedByUser.getId());
+ assignApplication.setUserId(userId);
+ assignApplication.setStatus(AssignedApplicationEnum.ASSIGNED.getValue());
+ if(assignedApplicationsRequest.getStatus() != null) {
+ assignApplication.setStatus(assignedApplicationsRequest.getStatus().getValue());
+ }
+ assignApplication.setNote(assignedApplicationsRequest.getNote());
+ assignApplication.setIsDeleted(false);
+ assignApplication.setAssignedAt(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
+ AssignedApplicationsEntity assignedApplicationsEntity = saveAssignedApplication(assignApplication);
+ return assignedApplicationsEntity;
+
+ }
+ public AssignedApplicationsEntity saveAssignedApplication(AssignedApplicationsEntity assignedApplicationsEntity){
+ AssignedApplicationsEntity assignedApplication= assignedApplicationsRepository.save(assignedApplicationsEntity);
+ return assignedApplication;
+ }
+
+ public AssignedApplicationsResponse convertEntityToResponse(AssignedApplicationsEntity assignedApplications){
+ AssignedApplicationsResponse assignedApplicationsResponse = new AssignedApplicationsResponse();
+ assignedApplicationsResponse.setId(assignedApplications.getId());
+ assignedApplicationsResponse.setApplicationId(assignedApplications.getApplication().getId());
+
+ ApplicationEntity application = applicationService.validateApplication(assignedApplications.getApplication().getId());
+ String callName = application.getCall() != null ? application.getCall().getName() : "";
+ LocalDateTime callEndDate = application.getCall().getEndDate();
+ LocalDateTime callStartDate = application.getCall().getStartDate();
+
+ Long protocolNumber = (application.getProtocol() != null && application.getProtocol().getProtocolNumber() != null)
+ ? application.getProtocol().getProtocolNumber()
+ : 0;
+ LocalDateTime submissionDate = application.getSubmissionDate();
+ UserEntity userEntity = userService.validateUser(application.getUserId());
+
+ String firstName = userEntity.getBeneficiary() != null ? userEntity.getBeneficiary().getFirstName() : null;
+ String lastName = userEntity.getBeneficiary() != null ? userEntity.getBeneficiary().getLastName() : null;
+
+ String beneficiaryName = (firstName != null && !firstName.isBlank() ? firstName : "") +
+ (lastName != null && !lastName.isBlank() ? " " + lastName : "");
+
+ beneficiaryName = beneficiaryName.isBlank() ? "" : beneficiaryName;
+
+ assignedApplicationsResponse.setAssignedBy(assignedApplications.getAssignedBy());
+ assignedApplicationsResponse.setUserId(assignedApplications.getUserId());
+ assignedApplicationsResponse.setCreatedDate(assignedApplications.getCreatedDate());
+ assignedApplicationsResponse.setUpdatedDate(assignedApplications.getUpdatedDate());
+ assignedApplicationsResponse.setNote(assignedApplications.getNote());
+ assignedApplicationsResponse.setStatus(AssignedApplicationEnum.valueOf(assignedApplications.getStatus()));
+ assignedApplicationsResponse.setAssignedAt(assignedApplications.getAssignedAt());
+ assignedApplicationsResponse.setProtocolNumber(protocolNumber);
+ assignedApplicationsResponse.setCallName(callName);
+ assignedApplicationsResponse.setBeneficiaryName(beneficiaryName);
+ assignedApplicationsResponse.setSubmissionDate(submissionDate);
+ assignedApplicationsResponse.setCallEndDate(callEndDate);
+ assignedApplicationsResponse.setCallStartDate(callStartDate);
+
+ return assignedApplicationsResponse;
+ }
+
+ public AssignedApplicationsEntity validateAssignedApplication(Long id){
+ AssignedApplicationsEntity assignedApplication = assignedApplicationsRepository.findByIdAndIsDeletedFalse(id).orElseThrow(()->
+ new ResourceNotFoundException(Status.NOT_FOUND,Translator.toLocale(GepafinConstant.ASSIGNED_APPLICATION_NOT_FOUND_MSG)));
+ return assignedApplication;
+ }
+
+ public void deleteById(HttpServletRequest request, Long id) {
+ log.info("Deleting assigned application with ID: {}", id);
+ AssignedApplicationsEntity assignedApplicationsEntity= validateAssignedApplication(id);
+ validator.validatePreInstructor(request, assignedApplicationsEntity.getUserId());
+ assignedApplicationsEntity.setIsDeleted(true);
+ assignedApplicationsEntity= saveAssignedApplication(assignedApplicationsEntity);
+ log.info("Assigned Application deleted with ID: {}", id);
+ }
+
+ public List getAllAssignedApplications(HttpServletRequest request, Long userId) {
+ UserEntity user = validator.validateUser(request);
+ if(validator.checkIsPreInstructor() && userId == null) {
+ throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.USER_ID_NOT_NULL_MSG));
+ }
+ if(userId != null) {
+ validator.validatePreInstructor(request, userId);
+ }
+ Specification spec = search(user.getHub().getId() ,userId);
+ List assignedApplicationsEntityList = assignedApplicationsRepository.findAll(spec);
+ return assignedApplicationsEntityList.stream()
+ .map(entity -> convertEntityToResponse(entity))
+ .collect(Collectors.toList());
+ }
+ private Specification search(Long hubId, Long userId) {
+ return (root, query, builder) -> {
+ Predicate predicate = builder.isFalse(root.get("isDeleted"));
+ if (userId != null) {
+ predicate = builder.and(predicate, builder.equal(root.get("userId"), userId));
+ }
+ predicate = builder.and(predicate, builder.equal(root.get("application").get("hubId"), hubId));
+ return predicate;
+ };
+ }
+
+
+ public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request,
+ Long id, AssignedApplicationsRequest updateRequest) {
+ UserEntity updatedByUser = validator.validateUser(request);
+ log.info("Updating assigned application with ID: {}", id);
+ AssignedApplicationsEntity existingAssignment = validateAssignedApplication(id);
+ validator.validatePreInstructor(request, existingAssignment.getUserId());
+ setIfUpdated(existingAssignment::getNote, existingAssignment::setNote, updateRequest.getNote());
+ setIfUpdated(existingAssignment::getStatus, existingAssignment::setStatus, updateRequest.getStatus().name());
+ setIfUpdated(existingAssignment::getAssignedBy, existingAssignment::setAssignedBy, updatedByUser.getId());
+
+ existingAssignment.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
+
+ AssignedApplicationsEntity updatedAssignment = saveAssignedApplication(existingAssignment);
+ AssignedApplicationsResponse response = convertEntityToResponse(updatedAssignment);
+ log.info("Assigned application updated successfully: {}", response);
+ return response;
+ }
+
+ public AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id) {
+ log.info("Fetching assigned application with ID: {}", id);
+ AssignedApplicationsEntity assignedApplication = validateAssignedApplication(id);
+ validator.validatePreInstructor(request, assignedApplication.getUserId());
+ AssignedApplicationsResponse response = convertEntityToResponse(assignedApplication);
+ log.info("Assigned application fetched successfully: {}", response);
+ return response;
+ }
+
+}
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/BeneficiaryPreferredCallDao.java b/src/main/java/net/gepafin/tendermanagement/dao/BeneficiaryPreferredCallDao.java
index 13b0f719..285702f1 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/BeneficiaryPreferredCallDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/BeneficiaryPreferredCallDao.java
@@ -5,13 +5,11 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryPreferredCallEntity;
import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.BeneficiaryCallStatus;
-import net.gepafin.tendermanagement.enums.RoleStatusEnum;
-import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.BeneficiaryPreferredCallReq;
import net.gepafin.tendermanagement.model.response.BeneficiaryPreferredCallResponseBean;
import net.gepafin.tendermanagement.repositories.BeneficiaryPreferredCallRepository;
-import net.gepafin.tendermanagement.service.UserService;
+import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.slf4j.Logger;
@@ -19,10 +17,11 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
+import jakarta.servlet.http.HttpServletRequest;
+
import java.util.List;
import java.util.stream.Collectors;
-import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@Component
public class BeneficiaryPreferredCallDao {
@@ -31,11 +30,14 @@ public class BeneficiaryPreferredCallDao {
@Autowired
private BeneficiaryPreferredCallRepository beneficiaryPreferredCallRepository;
+
@Autowired
- private UserService userService;
+ private Validator validator;
- public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(BeneficiaryPreferredCallReq request,UserEntity user) {
+
+ public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(HttpServletRequest httpServletRequest, BeneficiaryPreferredCallReq request,UserEntity user) {
log.info("Creating new beneficiary preferred call with details: {}", request);
+ validator.validateUserWithCompany(httpServletRequest, request.getCompanyId());
BeneficiaryPreferredCallEntity entity = convertRequestToEntity(request,user);
entity = beneficiaryPreferredCallRepository.save(entity);
log.info("Beneficiary preferred call created with ID: {}", entity.getId());
@@ -44,9 +46,8 @@ public class BeneficiaryPreferredCallDao {
private BeneficiaryPreferredCallEntity convertRequestToEntity(BeneficiaryPreferredCallReq request,UserEntity userEntity) {
BeneficiaryPreferredCallEntity entity = new BeneficiaryPreferredCallEntity();
- UserEntity user= userService.validateUser(userEntity.getId());
- if (user.getBeneficiary()!=null) {
- entity.setBeneficiaryId(user.getBeneficiary().getId());
+ if (userEntity.getBeneficiary()!=null) {
+ entity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
entity.setStatus(BeneficiaryCallStatus.ENABLED.getValue());
entity.setCallId(request.getCallId());
@@ -55,9 +56,10 @@ public class BeneficiaryPreferredCallDao {
return entity;
}
- public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(Long id) {
+ public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(HttpServletRequest request, Long id) {
log.info("Fetching beneficiary preferred call with ID: {}", id);
BeneficiaryPreferredCallEntity entity = validateBeneficiaryPreferredCall(id);
+ validator.validateUserId(request, entity.getUserId());
log.info("Beneficiary preferred call found: {}", entity);
return convertEntityToResponse(entity);
}
@@ -74,20 +76,18 @@ public class BeneficiaryPreferredCallDao {
// return convertEntityToResponse(existingEntity);
// }
- private boolean isUserABeneficiary(Long userId) {
- UserEntity user=userService.validateUser(userId);
- return RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(user.getRoleEntity().getRoleType());
- }
- public void deleteBeneficiaryPreferredCallById(Long id) {
+ public void deleteBeneficiaryPreferredCallById(HttpServletRequest request, Long id) {
log.info("Deleting beneficiary preferred call with ID: {}", id);
- validateBeneficiaryPreferredCall(id);
+ BeneficiaryPreferredCallEntity entity = validateBeneficiaryPreferredCall(id);
+ validator.validateUserId(request, entity.getUserId());
beneficiaryPreferredCallRepository.deleteById(id);
log.info("Beneficiary preferred call deleted with ID: {}", id);
}
- public List getAllBeneficiaryPreferredCalls() {
+ public List getAllBeneficiaryPreferredCalls(HttpServletRequest request) {
+ UserEntity userEntity = validator.validateUser(request);
log.info("Fetching all beneficiary preferred calls");
- List calls = beneficiaryPreferredCallRepository.findAll()
+ List calls = beneficiaryPreferredCallRepository.findByUserId(userEntity.getId())
.stream()
.map(this::convertEntityToResponse)
.collect(Collectors.toList());
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/CallDao.java b/src/main/java/net/gepafin/tendermanagement/dao/CallDao.java
index e7b303d2..b52aa97b 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/CallDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/CallDao.java
@@ -1,6 +1,5 @@
package net.gepafin.tendermanagement.dao;
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -23,10 +22,6 @@ import net.gepafin.tendermanagement.util.Utils;
import org.h2.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
@@ -34,6 +29,7 @@ import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CallTargetAudienceChecklistEntity;
+import net.gepafin.tendermanagement.entities.CriteriaFormFieldEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity;
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
import net.gepafin.tendermanagement.entities.FaqEntity;
@@ -52,6 +48,7 @@ import net.gepafin.tendermanagement.model.request.LookUpDataReq;
import net.gepafin.tendermanagement.model.request.UpdateCallRequestStep1;
import net.gepafin.tendermanagement.repositories.CallRepository;
import net.gepafin.tendermanagement.repositories.CallTargetAudienceChecklistRepository;
+import net.gepafin.tendermanagement.repositories.CriteriaFormFieldRepository;
import net.gepafin.tendermanagement.repositories.DocumentRepository;
import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository;
import net.gepafin.tendermanagement.repositories.FaqRepository;
@@ -88,24 +85,27 @@ public class CallDao {
@Autowired
private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository;
- @Autowired
- private UserService userService;
-
@Autowired
private FaqService faqService;
+
@Autowired
private FlowDao flowDao;
+
@Autowired
private FormDao formDao;
+
@Value("${aws.s3.url.folder}")
private String s3Folder;
+
@Autowired
private AmazonS3Service amazonS3Service;
+
+ @Autowired
+ private CriteriaFormFieldRepository criteriaFormFieldRepository;
- public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) {
- UserEntity userEntity = userService.validateUser(userId);
+ public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
- CallEntity callEntity = convertToCallEntity(createCallRequest);
+ CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ);
@@ -148,7 +148,7 @@ public class CallDao {
- public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest) {
+ public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
CallEntity callEntity = new CallEntity();
// validateCallEntity(createCallRequest);
RegionEntity region = regionRepository.findById(createCallRequest.getRegionId())
@@ -184,6 +184,7 @@ public class CallDao {
callEntity.setPhoneNumber(createCallRequest.getPhoneNumber());
callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime()));
callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime()));
+ callEntity.setHub(userEntity.getHub());
callEntity = callRepository.save(callEntity);
return callEntity;
}
@@ -209,6 +210,12 @@ public class CallDao {
private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) {
evaluationCriteriaEntity.setIsDeleted(true);
evaluationCriteriaRepository.save(evaluationCriteriaEntity);
+ List list = criteriaFormFieldRepository
+ .findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaEntity.getId())
+ .stream()
+ .peek(data -> data.setIsDeleted(Boolean.TRUE))
+ .toList();
+ criteriaFormFieldRepository.saveAll(list);
}
private EvaluationCriteriaEntity convertToEvaluationCriteriaEntity(EvaluationCriteriaReq criteriaReq,
@@ -257,6 +264,7 @@ public class CallDao {
private void softDeleteDocument(DocumentEntity documentEntity) {
documentEntity.setIsDeleted(true);
documentRepository.save(documentEntity);
+
}
private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) {
@@ -424,13 +432,11 @@ public class CallDao {
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)));
}
- public CallResponse getCallById(Long callId) {
- CallEntity callEntity = validateCall(callId);
+ public CallResponse getCallById(CallEntity callEntity) {
return getCallResponseBean(callEntity);
}
- public CallResponse createCallStep2(Long callId, CreateCallRequestStep2 createCallRequest, Long userId) {
- CallEntity callEntity = validateCall(callId);
+ public CallResponse createCallStep2(CallEntity callEntity, CreateCallRequestStep2 createCallRequest, UserEntity user) {
validateUpdate(callEntity);
setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold());
callRepository.save(callEntity);
@@ -490,8 +496,7 @@ public class CallDao {
}
}
- public CallResponse updateCallStep1(Long callId, UpdateCallRequestStep1 updateCallRequest, Long userId) {
- CallEntity callEntity = validateCall(callId);
+ public CallResponse updateCallStep1(CallEntity callEntity, UpdateCallRequestStep1 updateCallRequest, UserEntity userEntity) {
if(Boolean.TRUE.equals(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue()))) {
try {
Utils.retainOnlySpecificFields(updateCallRequest, Collections.singletonList("faq"));
@@ -499,7 +504,6 @@ public class CallDao {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FAILED_RETAIN_FIELD));
}
}
- UserEntity userEntity = userService.validateUser(userId);
isValidDateRange(updateCallRequest, callEntity);
setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName());
setIfUpdated(callEntity::getDescriptionShort, callEntity::setDescriptionShort,
@@ -553,9 +557,9 @@ public class CallDao {
}
List existingChecklist = callTargetAudienceChecklistRepository
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), type.getValue());
- List incomingIds = lookupDataReqList.stream().map(LookUpDataReq::getLookUpDataId)
+ List incomingIds = lookupDataReqList.stream().map(LookUpDataReq::getId)
.filter(id -> id != null && id > 0).collect(Collectors.toList());
- existingChecklist.stream().filter(checklist -> !incomingIds.contains(checklist.getLookupData().getId()))
+ existingChecklist.stream().filter(checklist -> !incomingIds.contains(checklist.getId()))
.forEach(this::softDeleteCallTargetAudienceChecklist);
lookupDataReqList
.forEach(lookUpDataReq -> createOrUpdateCallTargetAudienceChecklist(lookUpDataReq, callEntity, type));
@@ -650,7 +654,7 @@ public class CallDao {
if (Boolean.FALSE.equals(ROLE_SUPER_ADMIN.getValue().equals(type))) {
callStatusList = List.of(CallStatusEnum.PUBLISH.getValue());
}
- List calls = callRepository.findByStatusIn(callStatusList);
+ List calls = callRepository.findByStatusInAndHubId(callStatusList, user.getHub().getId());
return calls.stream()
.map(this::convertToCallDetailsResponseBean)
.collect(Collectors.toList());
@@ -660,7 +664,7 @@ public class CallDao {
validateUpdate(callEntity);
CallResponse callResponseBean = getCallResponseBean(callEntity);
FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId());
- List formResponseBean = formDao.getFormsByCallId(callEntity.getId());
+ List formResponseBean = formDao.getFormsByCallId(callEntity);
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean);
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
callRepository.save(callEntity);
@@ -668,16 +672,15 @@ public class CallDao {
callResponseBean.setStatus(CallStatusEnum.valueOf(callEntity.getStatus()));
return callResponseBean;
}
- public CallEntity getCallEntityById(Long id){
- CallEntity callEntity=callRepository.findByIdAndStatusNotIn(id,List.of(CallStatusEnum.PUBLISH.getValue()));
- if(callEntity==null){
- throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
- }
- return callEntity;
- }
+// public CallEntity getCallEntityById(Long id){
+// CallEntity callEntity=callRepository.findByIdAndStatusNotInAndHubId(id, List.of(CallStatusEnum.PUBLISH.getValue()));
+// if(callEntity==null){
+// throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
+// }
+// return callEntity;
+// }
- public CallResponse updateCallStatus(Long callId, CallStatusEnum statusReq) {
- CallEntity callEntity = validateCall(callId);
+ public CallResponse updateCallStatus(CallEntity callEntity, CallStatusEnum statusReq) {
CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus());
validateStatusChange(currentStatus, statusReq);
callEntity.setStatus(statusReq.getValue());
@@ -715,9 +718,9 @@ public class CallDao {
}
}
- public CallEntity validatePublishedCall(Long callId) {
+ public CallEntity validatePublishedCall(Long callId, Long hubId) {
CallEntity callEntity= callRepository
- .findByIdAndStatus(callId, CallStatusEnum.PUBLISH.getValue());
+ .findByIdAndStatusAndHubId(callId, CallStatusEnum.PUBLISH.getValue(), hubId);
if(callEntity==null){
throw new ResourceNotFoundException(
Status.NOT_FOUND,
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/CompanyDao.java b/src/main/java/net/gepafin/tendermanagement/dao/CompanyDao.java
index 3a9b92ad..84b01021 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/CompanyDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/CompanyDao.java
@@ -2,25 +2,23 @@ package net.gepafin.tendermanagement.dao;
import java.util.List;
+import net.gepafin.tendermanagement.entities.*;
+import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
+import net.gepafin.tendermanagement.repositories.ApplicationRepository;
+import net.gepafin.tendermanagement.repositories.FaqRepository;
+import net.gepafin.tendermanagement.web.rest.api.errors.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
-import net.gepafin.tendermanagement.entities.CompanyEntity;
-import net.gepafin.tendermanagement.entities.UserEntity;
-import net.gepafin.tendermanagement.entities.UserWithCompanyEntity;
import net.gepafin.tendermanagement.model.request.CompanyRequest;
import net.gepafin.tendermanagement.model.response.CompanyResponse;
import net.gepafin.tendermanagement.repositories.CompanyRepository;
import net.gepafin.tendermanagement.repositories.UserWithCompanyRepository;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.Utils;
-import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
-import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
-import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
-import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@@ -35,13 +33,17 @@ public class CompanyDao {
@Autowired
private UserWithCompanyRepository userWithCompanyRepository;
+ @Autowired
+ private ApplicationRepository applicationRepository;
+ @Autowired
+ private FaqRepository faqRepository;
public CompanyResponse createCompany(UserEntity userEntity, CompanyRequest companyRequest) {
- CompanyEntity existingCompany = companyRepository.findByVatNumber(companyRequest.getVatNumber());
+ CompanyEntity existingCompany = companyRepository.findByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId());
UserWithCompanyEntity userWithCompanyEntity = null;
if (existingCompany != null) {
- UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyId(userEntity.getId(), existingCompany.getId())
+ UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), existingCompany.getId())
.orElse(null);
if (existingRelation == null) {
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, existingCompany, companyRequest.getIsLegalRepresentant());
@@ -51,8 +53,8 @@ public class CompanyDao {
}
return convertCompanyEntityToCompanyResponse(existingCompany, userWithCompanyEntity);
} else {
- validateCompany(companyRequest);
- CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(companyRequest);
+ validateCompany(userEntity, companyRequest);
+ CompanyEntity companyEntity = convertCompanyRequestToCompanyEntity(userEntity, companyRequest);
companyRepository.save(companyEntity);
userWithCompanyEntity = createUserWithCompanyRelation(userEntity, companyEntity, companyRequest.getIsLegalRepresentant());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
@@ -60,7 +62,7 @@ public class CompanyDao {
}
- private void validateCompany(CompanyRequest companyRequest) {
+ private void validateCompany(UserEntity userEntity, CompanyRequest companyRequest) {
if (Boolean.FALSE.equals(StringUtils.isEmpty(companyRequest.getEmail()))
&& Boolean.FALSE.equals(Utils.isValidEmail(companyRequest.getEmail()))) {
@@ -71,7 +73,7 @@ public class CompanyDao {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_MANDATORY));
}
- if (companyRepository.existsByVatNumber(companyRequest.getVatNumber())) {
+ if (companyRepository.existsByVatNumberAndHubId(companyRequest.getVatNumber(), userEntity.getHub().getId())) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VATNUMBER_ALREADY_EXISTS));
}
@@ -82,13 +84,14 @@ public class CompanyDao {
if (userEntity.getBeneficiary() != null) {
userWithCompanyEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
}
+ userWithCompanyEntity.setIsDeleted(Boolean.FALSE);
userWithCompanyEntity.setCompanyId(companyEntity.getId());
userWithCompanyEntity.setUserId(userEntity.getId());
userWithCompanyEntity.setIsLegalRepresentant(isLegalRepresentant);
return userWithCompanyRepository.save(userWithCompanyEntity);
}
- private CompanyEntity convertCompanyRequestToCompanyEntity(CompanyRequest request) {
+ private CompanyEntity convertCompanyRequestToCompanyEntity(UserEntity userEntity, CompanyRequest request) {
CompanyEntity entity = new CompanyEntity();
entity.setCompanyName(request.getCompanyName());
entity.setVatNumber(request.getVatNumber());
@@ -105,6 +108,7 @@ public class CompanyDao {
entity.setAnnualRevenue(request.getAnnualRevenue());
entity.setContactName(request.getContactName());
entity.setContactEmail(request.getContactEmail());
+ entity.setHub(userEntity.getHub());
return entity;
}
@@ -177,27 +181,49 @@ public class CompanyDao {
public void deleteCompany(UserEntity userEntity, Long companyId) {
CompanyEntity companyEntity = validateCompany(companyId);
companyRepository.delete(companyEntity);
- userWithCompanyRepository.deleteByCompanyId(companyId);
+ userWithCompanyRepository.deleteByCompanyIdAndIsDeletedFalse(companyId);
}
public List getCompanyByUserId(Long userId) {
UserEntity userEntity = userService.validateUser(userId);
- List companyIds = userWithCompanyRepository.findCompanyIdByUserId(userEntity.getId());
- List list = companyRepository.findByIdIn(companyIds);
- return list.stream().map(companyEntity->{
+ List activeCompanyIds = userWithCompanyRepository.findActiveCompanyIdsByUserId(userEntity.getId());
+ List companies = companyRepository.findByIdInAndHubId(activeCompanyIds, userEntity.getHub().getId());
+ return companies.stream().map(companyEntity -> {
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyEntity.getId());
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
}).toList();
}
public UserWithCompanyEntity validateUserWithCompny(Long userId, Long companyId) {
- return userWithCompanyRepository.findByUserIdAndCompanyId(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
+ return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, companyId).orElseThrow(() -> new ForbiddenAccessException(Status.FORBIDDEN,
Translator.toLocale(GepafinConstant.PERMISSION_DENIED)));
}
public UserWithCompanyEntity getUserWithCompany(Long userId, Long compnayId) {
- return userWithCompanyRepository.findByUserIdAndCompanyId(userId, compnayId).orElseThrow(
+ return userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userId, compnayId).orElseThrow(
() -> new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_COMPANY_RELATION_NOT_FOUND)));
}
+ public void removeCompanyFromList(UserEntity userEntity, Long companyId) {
+ CompanyEntity companyEntity = validateCompany(companyId);
+ UserWithCompanyEntity existingRelation = userWithCompanyRepository.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), companyEntity.getId())
+ .orElseThrow(() -> new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.USER_ALREADY_CONNECTED_TO_COMPANY)));
+ List userApplications = applicationRepository.findByCompanyIdAndUserIdAndIsDeletedFalse(companyEntity.getId(), userEntity.getId());
+ List faqs = faqRepository.findByCompanyIdAndUserIdAndIsDeletedFalse(companyEntity.getId(), userEntity.getId());
+ for (ApplicationEntity application : userApplications) {
+ if(Boolean.TRUE.equals(application.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
+ throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT));
+ }
+ if(Boolean.TRUE.equals(application.getStatus().equals(ApplicationStatusTypeEnum.DRAFT.getValue()))) {
+ application.setIsDeleted(Boolean.TRUE);
+ applicationRepository.save(application);
+ }
+ }
+ for(FaqEntity faq:faqs) {
+ faq.setIsDeleted(Boolean.TRUE);
+ faqRepository.save(faq);
+ }
+ existingRelation.setIsDeleted(Boolean.TRUE);
+ userWithCompanyRepository.save(existingRelation);
+ }
}
diff --git a/src/main/java/net/gepafin/tendermanagement/dao/DashboardDao.java b/src/main/java/net/gepafin/tendermanagement/dao/DashboardDao.java
index 0f917535..c76d14c9 100644
--- a/src/main/java/net/gepafin/tendermanagement/dao/DashboardDao.java
+++ b/src/main/java/net/gepafin/tendermanagement/dao/DashboardDao.java
@@ -32,23 +32,23 @@ public class DashboardDao {
@Autowired
private CompanyRepository companyRepository;
- public SuperAdminWidgetResponseBean getDashboardWidget() {
+ public SuperAdminWidgetResponseBean getDashboardWidget(UserEntity requestedUserEntity) {
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
- widgetResponseBean.setWidget1(createWidget1());
+ widgetResponseBean.setWidget1(createWidget1(requestedUserEntity));
// List