Conflict Resolved
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<String, List<Object>> 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -109,23 +110,19 @@ public class SecurityConfig {
|
||||
.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();
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -241,5 +241,32 @@ public class GepafinConstant {
|
||||
public static final String APPLICATION_EVALUATION_NOT_FOUND = "application.evaluation.not.found";
|
||||
public static final String APPLICATION_EVALUATION_STATUS_UPDATED_SUCCESSFULLY = "application.evaluation.status.updated.successfully";
|
||||
|
||||
|
||||
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 ADDED_S3_PATH_STRUCTURE ="added.s3.path.structure";
|
||||
public static final String S3_PATH_STRUCTURE_BY_TYPE ="fetched.s3.path.structure.by.type.successfully";
|
||||
public static final String S3_PATH_STRUCTURE_NOT_FOUND_BY_TYPE_MSG ="s3.path.not.found.by.type";
|
||||
public static final String S3_PATH_STRUCTURE_NOT_FOUND_BY_ID_MSG ="s3.path.not.found.by.id";
|
||||
public static final String S3_PATH_DELETE_MSG ="s3.path.config.delete.successfully";
|
||||
public static final String S3_PATH_CONFIG_UPDATE_MSG ="s3.path.config.updated.successfully";
|
||||
public static final String S3_PATH_CONFIG_DUPLICATE_TYPE_ALREADY_EXIST ="s3.path.config.already.exist.";
|
||||
public static final String S3_PATH_GENERATION_ERROR_MSG ="s3.path.config.already.exist.";
|
||||
public static final String INVALID_APPLICATION_STATUS = "invalid.application.status";
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.entities.SystemEmailTemplatesEntity.SystemEmailTemplatesEntityTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationSignedDocumentStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.ApplicationStatusTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.DocOtherSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
|
||||
@@ -20,6 +21,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 +121,29 @@ public class ApplicationDao {
|
||||
|
||||
@Value("${aws.s3.url.folder.signed.document}")
|
||||
private String signedDocumentS3Folder;
|
||||
|
||||
@Value("${default.hub.uuid}")
|
||||
private String defaultHubUuid;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
S3PathConfig s3ConfigBean;
|
||||
|
||||
|
||||
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 +179,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 +242,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 +288,11 @@ public class ApplicationDao {
|
||||
// return applicationResponses;
|
||||
// }
|
||||
|
||||
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId) {
|
||||
public List<ApplicationResponse> getAllApplications(UserEntity userEntity, Long callId, Long companyId,String status) {
|
||||
|
||||
log.info("Fetching applications for RoleType: {}", userEntity.getRoleEntity().getRoleType());
|
||||
|
||||
Specification<ApplicationEntity> spec = search(userEntity.getId(), callId, companyId);
|
||||
Specification<ApplicationEntity> spec = search(userEntity, callId, companyId,status);
|
||||
|
||||
List<ApplicationEntity> applicationEntities = applicationRepository.findAll(spec);
|
||||
|
||||
@@ -288,12 +302,12 @@ public class ApplicationDao {
|
||||
}
|
||||
|
||||
|
||||
private Specification<ApplicationEntity> search(Long userId, Long callId, Long companyId) {
|
||||
private Specification<ApplicationEntity> 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 +315,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 +485,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<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
|
||||
List<FormEntity> formEntities = new ArrayList<>();
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
boolean isBeneficiary = isBeneficiary(userEntity);
|
||||
ApplicationEntity applicationEntity = isBeneficiary
|
||||
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
|
||||
@@ -574,8 +593,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 +604,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<FlowEdgesEntity> 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 +703,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 +776,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,20 +789,38 @@ 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);
|
||||
applicationSignedDocument = new ApplicationSignedDocumentEntity();
|
||||
UploadFileOnAmazonS3Response uploadFileOnAmazonS3 = uploadFileOnAmazonS3ForUserSignedDocument(file,
|
||||
applicationEntity.getCall().getId(), applicationId);
|
||||
applicationSignedDocument = new ApplicationSignedDocumentEntity();
|
||||
applicationSignedDocument.setApplication(applicationEntity);
|
||||
applicationSignedDocument.setFileName(uploadFileOnAmazonS3.getFileName());
|
||||
applicationSignedDocument.setFilePath(uploadFileOnAmazonS3.getFilePath());
|
||||
applicationSignedDocument.setStatus(ApplicationSignedDocumentStatusEnum.ACTIVE.getValue());
|
||||
applicationSignedDocumentRepository.save(applicationSignedDocument);
|
||||
applicationEntity.setStatus(ApplicationStatusTypeEnum.READY.getValue());
|
||||
applicationRepository.save(applicationEntity);
|
||||
return convertApplicationSignedDocumentToApplicationSignedDocumentResponse(applicationSignedDocument);
|
||||
}
|
||||
|
||||
private UploadFileOnAmazonS3Response uploadFileOnAmazonS3ForUserSignedDocument(MultipartFile file, Long callId, Long applicationId) {
|
||||
try {
|
||||
String s3Path = generateS3PathForDelegation(callId, applicationId);
|
||||
log.info("S3 Path {}", s3Path);
|
||||
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
|
||||
} catch (Exception e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
|
||||
}
|
||||
}
|
||||
private String generateS3PathForDelegation(Long callId, Long applicationId) {
|
||||
try {
|
||||
return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT, callId, applicationId);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
|
||||
}
|
||||
}
|
||||
private ApplicationSignedDocumentResponse convertApplicationSignedDocumentToApplicationSignedDocumentResponse(
|
||||
ApplicationSignedDocumentEntity applicationSignedDocument) {
|
||||
ApplicationSignedDocumentResponse applicationSignedDocumentResponse = new ApplicationSignedDocumentResponse();
|
||||
@@ -841,4 +874,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<FlowEdgesEntity> 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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<AssignedApplicationsResponse> 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<AssignedApplicationsEntity> spec = search(user.getHub().getId() ,userId);
|
||||
List<AssignedApplicationsEntity> assignedApplicationsEntityList = assignedApplicationsRepository.findAll(spec);
|
||||
return assignedApplicationsEntityList.stream()
|
||||
.map(entity -> convertEntityToResponse(entity))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
private Specification<AssignedApplicationsEntity> 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls() {
|
||||
public List<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls(HttpServletRequest request) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
log.info("Fetching all beneficiary preferred calls");
|
||||
List<BeneficiaryPreferredCallResponseBean> calls = beneficiaryPreferredCallRepository.findAll()
|
||||
List<BeneficiaryPreferredCallResponseBean> calls = beneficiaryPreferredCallRepository.findByUserId(userEntity.getId())
|
||||
.stream()
|
||||
.map(this::convertEntityToResponse)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -127,8 +127,9 @@ public class CallDao {
|
||||
ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
|
||||
for (DocumentEntity document : documents) {
|
||||
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFileName())) {
|
||||
ZipEntry zipEntry = new ZipEntry(document.getFileName());
|
||||
try (InputStream fileInputStream = amazonS3Service.getFile(s3Folder, document.getFilePath())) {
|
||||
String fileName = Utils.extractFileName(document.getFilePath());
|
||||
ZipEntry zipEntry = new ZipEntry(fileName);
|
||||
zos.putNextEntry(zipEntry);
|
||||
IOUtils.copy(fileInputStream, zos);
|
||||
zos.closeEntry();
|
||||
@@ -147,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())
|
||||
@@ -183,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;
|
||||
}
|
||||
@@ -208,6 +210,12 @@ public class CallDao {
|
||||
private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) {
|
||||
evaluationCriteriaEntity.setIsDeleted(true);
|
||||
evaluationCriteriaRepository.save(evaluationCriteriaEntity);
|
||||
List<CriteriaFormFieldEntity> list = criteriaFormFieldRepository
|
||||
.findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaEntity.getId())
|
||||
.stream()
|
||||
.peek(data -> data.setIsDeleted(Boolean.TRUE))
|
||||
.toList();
|
||||
criteriaFormFieldRepository.saveAll(list);
|
||||
}
|
||||
|
||||
private EvaluationCriteriaEntity convertToEvaluationCriteriaEntity(EvaluationCriteriaReq criteriaReq,
|
||||
@@ -222,6 +230,7 @@ public class CallDao {
|
||||
criteriaEntity = new EvaluationCriteriaEntity();
|
||||
criteriaEntity.setCall(callEntity);
|
||||
criteriaEntity.setLookupData(lookupDataEntity);
|
||||
criteriaEntity.setScore(0L);
|
||||
criteriaEntity.setIsDeleted(false);
|
||||
}
|
||||
setIfUpdated(criteriaEntity::getScore, criteriaEntity::setScore, criteriaReq.getScore());
|
||||
@@ -239,7 +248,7 @@ public class CallDao {
|
||||
}
|
||||
|
||||
List<DocumentEntity> existingDocuments = documentRepository
|
||||
.findBySourceIdAndTypeAndIsDeletedFalse(sourceId, documentType.getValue());
|
||||
.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(sourceId, DocumentSourceTypeEnum.CALL.getValue(), documentType.getValue());
|
||||
|
||||
List<Long> incomingIds = documentReqList.stream().map(DocumentReq::getId).filter(id -> id != null && id > 0)
|
||||
.collect(Collectors.toList());
|
||||
@@ -255,11 +264,12 @@ public class CallDao {
|
||||
private void softDeleteDocument(DocumentEntity documentEntity) {
|
||||
documentEntity.setIsDeleted(true);
|
||||
documentRepository.save(documentEntity);
|
||||
|
||||
}
|
||||
|
||||
private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) {
|
||||
validateDocumentEntity(documentReq.getId());
|
||||
DocumentEntity documentEntity = documentRepository.findByIdAndSourceIdAndIsDeletedFalse(documentReq.getId(),sourceId)
|
||||
DocumentEntity documentEntity = documentRepository.findByIdAndSourceIdAndSourceAndIsDeletedFalse(documentReq.getId(),sourceId, DocumentSourceTypeEnum.CALL.getValue())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.DOCUMENT_NOT_FOUND)));
|
||||
return documentEntity;
|
||||
@@ -422,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);
|
||||
@@ -488,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"));
|
||||
@@ -497,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,
|
||||
@@ -596,6 +602,7 @@ public class CallDao {
|
||||
dates.add(callEntity.getStartDate());
|
||||
dates.add(callEntity.getEndDate());
|
||||
callDetailsResponseBean.setDates(dates);
|
||||
callDetailsResponseBean.setConfidi(callEntity.getConfidi());
|
||||
callDetailsResponseBean.setDescriptionShort(callEntity.getDescriptionShort());
|
||||
callDetailsResponseBean.setDescriptionLong(callEntity.getDescriptionLong());
|
||||
callDetailsResponseBean.setStatus(CallStatusEnum.valueOf(callEntity.getStatus()));
|
||||
@@ -614,14 +621,15 @@ public class CallDao {
|
||||
callDetailsResponseBean.setPhoneNumber(callEntity.getPhoneNumber());
|
||||
callDetailsResponseBean.setCreatedDate(callEntity.getCreatedDate());
|
||||
callDetailsResponseBean.setUpdatedDate(callEntity.getUpdatedDate());
|
||||
|
||||
return callDetailsResponseBean;
|
||||
}
|
||||
|
||||
private CallResponse getCallResponseBean(CallEntity callEntity) {
|
||||
List<DocumentEntity> documentEntities = documentRepository.findBySourceIdAndTypeAndIsDeletedFalse(callEntity.getId(),
|
||||
DocumentTypeEnum.DOCUMENT.getValue());
|
||||
List<DocumentEntity> imageEntities = documentRepository.findBySourceIdAndTypeAndIsDeletedFalse(callEntity.getId(),
|
||||
DocumentTypeEnum.IMAGES.getValue());
|
||||
List<DocumentEntity> documentEntities = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callEntity.getId(),DocumentSourceTypeEnum.CALL.getValue()
|
||||
, DocumentTypeEnum.DOCUMENT.getValue());
|
||||
List<DocumentEntity> imageEntities = documentRepository.findBySourceIdAndSourceAndTypeAndIsDeletedFalse(callEntity.getId(), DocumentSourceTypeEnum.CALL.getValue()
|
||||
, DocumentTypeEnum.IMAGES.getValue());
|
||||
List<LookUpDataResponse> amiedTo = callTargetAudienceChecklistRepository
|
||||
.findByCallIdAndLookupDataTypeAndIsDeletedFalse(callEntity.getId(), LookUpDataTypeEnum.AIMED_TO.getValue()).stream()
|
||||
.map(this::convertToLookUpDataResponseBean).toList();
|
||||
@@ -646,7 +654,7 @@ public class CallDao {
|
||||
if (Boolean.FALSE.equals(ROLE_SUPER_ADMIN.getValue().equals(type))) {
|
||||
callStatusList = List.of(CallStatusEnum.PUBLISH.getValue());
|
||||
}
|
||||
List<CallEntity> calls = callRepository.findByStatusIn(callStatusList);
|
||||
List<CallEntity> calls = callRepository.findByStatusInAndHubId(callStatusList, user.getHub().getId());
|
||||
return calls.stream()
|
||||
.map(this::convertToCallDetailsResponseBean)
|
||||
.collect(Collectors.toList());
|
||||
@@ -656,7 +664,7 @@ public class CallDao {
|
||||
validateUpdate(callEntity);
|
||||
CallResponse callResponseBean = getCallResponseBean(callEntity);
|
||||
FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId());
|
||||
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity.getId());
|
||||
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity);
|
||||
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean);
|
||||
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
|
||||
callRepository.save(callEntity);
|
||||
@@ -664,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());
|
||||
@@ -711,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,
|
||||
|
||||
@@ -40,7 +40,7 @@ public class CompanyDao {
|
||||
|
||||
|
||||
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.findByUserIdAndCompanyIdAndIsDeletedFalse(userEntity.getId(), existingCompany.getId())
|
||||
@@ -53,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);
|
||||
@@ -62,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()))) {
|
||||
@@ -73,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));
|
||||
}
|
||||
@@ -91,7 +91,7 @@ public class CompanyDao {
|
||||
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());
|
||||
@@ -108,6 +108,7 @@ public class CompanyDao {
|
||||
entity.setAnnualRevenue(request.getAnnualRevenue());
|
||||
entity.setContactName(request.getContactName());
|
||||
entity.setContactEmail(request.getContactEmail());
|
||||
entity.setHub(userEntity.getHub());
|
||||
return entity;
|
||||
}
|
||||
|
||||
@@ -186,7 +187,7 @@ public class CompanyDao {
|
||||
public List<CompanyResponse> getCompanyByUserId(Long userId) {
|
||||
UserEntity userEntity = userService.validateUser(userId);
|
||||
List<Long> activeCompanyIds = userWithCompanyRepository.findActiveCompanyIdsByUserId(userEntity.getId());
|
||||
List<CompanyEntity> companies = companyRepository.findByIdIn(activeCompanyIds);
|
||||
List<CompanyEntity> companies = companyRepository.findByIdInAndHubId(activeCompanyIds, userEntity.getHub().getId());
|
||||
return companies.stream().map(companyEntity -> {
|
||||
UserWithCompanyEntity userWithCompanyEntity = getUserWithCompany(userEntity.getId(), companyEntity.getId());
|
||||
return convertCompanyEntityToCompanyResponse(companyEntity, userWithCompanyEntity);
|
||||
|
||||
@@ -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<Object[]> widgetBars = callRepository.findApplicationsPerCall();
|
||||
// widgetResponseBean.setWidgetBars(widgetBars);
|
||||
return widgetResponseBean;
|
||||
}
|
||||
|
||||
private Widget1 createWidget1() {
|
||||
private Widget1 createWidget1(UserEntity requestedUserEntity) {
|
||||
Widget1 widget1 = initializeWidget1();
|
||||
|
||||
setActiveCalls(widget1);
|
||||
setRegisteredUsers(widget1);
|
||||
setTotalActiveFinancing(widget1);
|
||||
setSubmittedApplications(widget1);
|
||||
setDraftApplications(widget1);
|
||||
setNumberOfCompanies(widget1);
|
||||
setActiveCalls(widget1, requestedUserEntity);
|
||||
setRegisteredUsers(widget1, requestedUserEntity);
|
||||
setTotalActiveFinancing(widget1, requestedUserEntity);
|
||||
setSubmittedApplications(widget1, requestedUserEntity);
|
||||
setDraftApplications(widget1, requestedUserEntity);
|
||||
setNumberOfCompanies(widget1, requestedUserEntity);
|
||||
|
||||
return widget1;
|
||||
}
|
||||
@@ -59,42 +59,42 @@ public class DashboardDao {
|
||||
.build();
|
||||
}
|
||||
|
||||
private void setActiveCalls(Widget1 widget1) {
|
||||
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
|
||||
private void setActiveCalls(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
Long activeCalls = callRepository.countByStatusAndHubId(CallStatusEnum.PUBLISH.getValue(), requestedUserEntity.getHub().getId());
|
||||
if (activeCalls != null) {
|
||||
widget1.setNumberOfActiveCalls(activeCalls);
|
||||
}
|
||||
}
|
||||
|
||||
private void setRegisteredUsers(Widget1 widget1) {
|
||||
Long activeUsers = userRepository.countByStatusAndRoleEntity_RoleType(UserStatusEnum.ACTIVE.getValue(),
|
||||
RoleStatusEnum.ROLE_BENEFICIARY.getValue());
|
||||
private void setRegisteredUsers(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
Long activeUsers = userRepository.countByStatusAndRoleEntityRoleTypeAndHubId(UserStatusEnum.ACTIVE.getValue(),
|
||||
RoleStatusEnum.ROLE_BENEFICIARY.getValue(), requestedUserEntity.getHub().getId());
|
||||
if (activeUsers != null) {
|
||||
widget1.setNumberOfResgisteredUsers(activeUsers);
|
||||
}
|
||||
}
|
||||
|
||||
private void setTotalActiveFinancing(Widget1 widget1) {
|
||||
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCalls();
|
||||
private void setTotalActiveFinancing(Widget1 widget1, UserEntity requestedUser) {
|
||||
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCallsAndHubId(requestedUser.getHub().getId());
|
||||
widget1.setTotalActiveFinancing(totalActiveFinancing);
|
||||
}
|
||||
|
||||
private void setSubmittedApplications(Widget1 widget1) {
|
||||
Long submittedApplications = applicationRepository.countSubmittedApplications();
|
||||
private void setSubmittedApplications(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
Long submittedApplications = applicationRepository.countSubmittedApplicationsByHubId(requestedUserEntity.getHub().getId());
|
||||
if (submittedApplications != null) {
|
||||
widget1.setNumberOfSubmittedApplications(submittedApplications);
|
||||
}
|
||||
}
|
||||
|
||||
private void setDraftApplications(Widget1 widget1) {
|
||||
Long draftApplications = applicationRepository.countDraftApplications();
|
||||
private void setDraftApplications(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
Long draftApplications = applicationRepository.countDraftApplicationsByHubId(requestedUserEntity.getHub().getId());
|
||||
if (draftApplications != null) {
|
||||
widget1.setNumberOfDraftApplications(draftApplications);
|
||||
}
|
||||
}
|
||||
|
||||
private void setNumberOfCompanies(Widget1 widget1) {
|
||||
Long numberOfCompanies = companyRepository.countTotalCompanies();
|
||||
private void setNumberOfCompanies(Widget1 widget1, UserEntity requestedUserEntity) {
|
||||
Long numberOfCompanies = companyRepository.countTotalCompaniesByHubId(requestedUserEntity.getHub().getId());
|
||||
if (numberOfCompanies != null) {
|
||||
widget1.setNumberOfCompany(numberOfCompanies);
|
||||
}
|
||||
@@ -104,7 +104,7 @@ public class DashboardDao {
|
||||
CompanyEntity company) {
|
||||
BeneficiaryWidgetResponseBean beneficiaryWidgetResponseBean = BeneficiaryWidgetResponseBean.builder()
|
||||
.numberOfApplications(0L).numberOfCalls(0L).numberOfIntegratedDocuments(0L).build();
|
||||
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
|
||||
Long activeCalls = callRepository.countByStatusAndHubId(CallStatusEnum.PUBLISH.getValue(), userEntity.getHub().getId());
|
||||
if (activeCalls != null) {
|
||||
beneficiaryWidgetResponseBean.setNumberOfCalls(activeCalls);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import net.gepafin.tendermanagement.enums.DocOtherSourceTypeEnum;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFDocument;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -15,6 +15,7 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
@@ -24,6 +25,7 @@ import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.UserCompanyDelegationStatusEnum;
|
||||
import net.gepafin.tendermanagement.model.request.CompanyDelegationRequest;
|
||||
import net.gepafin.tendermanagement.model.response.CompanyDelegationResponse;
|
||||
import net.gepafin.tendermanagement.model.response.UploadFileOnAmazonS3Response;
|
||||
import net.gepafin.tendermanagement.model.response.UserResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserCompanyDelegationRepository;
|
||||
@@ -31,6 +33,7 @@ import net.gepafin.tendermanagement.service.AmazonS3Service;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
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;
|
||||
@@ -38,7 +41,7 @@ import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
@Component
|
||||
public class DelegationDao {
|
||||
|
||||
private static final String DEFAULT_PLACEHOLDER = "____________________";
|
||||
// private static final String DEFAULT_PLACEHOLDER = "____________________";
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@@ -51,12 +54,18 @@ public class DelegationDao {
|
||||
|
||||
@Autowired
|
||||
private DocumentRepository documentRepository;
|
||||
|
||||
@Autowired
|
||||
private S3PathConfig s3ConfigBean;
|
||||
|
||||
@Value("${aws.s3.url.folder.delegation}")
|
||||
private String s3Folder;
|
||||
|
||||
@Autowired
|
||||
private UserCompanyDelegationRepository userCompanyDelegationRepository;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
|
||||
public ByteArrayOutputStream generateDocument(Map<String, String> placeholders, String templateName) {
|
||||
@@ -89,14 +98,15 @@ public class DelegationDao {
|
||||
return new XWPFDocument(templateStream);
|
||||
}
|
||||
|
||||
public ByteArrayOutputStream downloadCompanyDelegation(UserEntity userEntity, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
|
||||
public ByteArrayOutputStream downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
|
||||
Map<String, String> placeholders = getDefaultPlaceholders();
|
||||
UserResponseBean user = userService.getUserById(userEntity.getId());
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
UserResponseBean user = userService.getUserById(request, userEntity.getId());
|
||||
CompanyEntity companyEntity = companyDao.validateCompany(companyId);
|
||||
companyDao.getUserWithCompany(userEntity.getId(), companyId);
|
||||
updatePlaceholdersForDelegation(user, companyEntity, placeholders, companyDelegationRequest);
|
||||
DocumentEntity documentEntity = documentRepository.findBySource(GepafinConstant.DELEGATION_TEMPLATE).get(0);
|
||||
return generateDocument(placeholders, documentEntity.getFileName());
|
||||
return generateDocument(placeholders, documentEntity.getFilePath());
|
||||
}
|
||||
|
||||
private Map<String, String> updatePlaceholdersForDelegation(UserResponseBean user, CompanyEntity companyEntity,
|
||||
@@ -179,7 +189,7 @@ public class DelegationDao {
|
||||
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.INACTIVE.getValue());
|
||||
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
|
||||
}
|
||||
UploadFileOnAmazonS3 uploadFileOnAmazonS3 = uploadFileOnAmazonS3(file);
|
||||
UploadFileOnAmazonS3Response uploadFileOnAmazonS3Response = uploadFileOnAmazonS3ForCompanyDelegation(file);
|
||||
userCompanyDelegationEntity = new UserCompanyDelegationEntity();
|
||||
userCompanyDelegationEntity.setCompanyId(companyId);
|
||||
userCompanyDelegationEntity.setUserId(userEntity.getId());
|
||||
@@ -187,35 +197,30 @@ public class DelegationDao {
|
||||
userCompanyDelegationEntity.setBeneficiaryId(userEntity.getBeneficiary().getId());
|
||||
}
|
||||
userCompanyDelegationEntity.setStatus(UserCompanyDelegationStatusEnum.ACTIVE.getValue());
|
||||
userCompanyDelegationEntity.setFileName(uploadFileOnAmazonS3.fileName());
|
||||
userCompanyDelegationEntity.setFilePath(uploadFileOnAmazonS3.filepath());
|
||||
userCompanyDelegationEntity.setFileName(uploadFileOnAmazonS3Response.getFileName());
|
||||
userCompanyDelegationEntity.setFilePath(uploadFileOnAmazonS3Response.getFilePath());
|
||||
userCompanyDelegationRepository.save(userCompanyDelegationEntity);
|
||||
return convertUserCompanyDelegationToCompanyDelegationResponse(userCompanyDelegationEntity);
|
||||
}
|
||||
|
||||
private UploadFileOnAmazonS3Response uploadFileOnAmazonS3ForCompanyDelegation(MultipartFile file) {
|
||||
try {
|
||||
String s3Path = generateS3PathForDelegation();
|
||||
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
|
||||
} catch (Exception e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
|
||||
}
|
||||
}
|
||||
private String generateS3PathForDelegation() {
|
||||
try {
|
||||
return s3ConfigBean.generateDocumentPathForDelegationAndSignedDocument(DocOtherSourceTypeEnum.USER_DELEGATION);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
|
||||
}
|
||||
}
|
||||
private CompanyDelegationResponse convertUserCompanyDelegationToCompanyDelegationResponse(
|
||||
UserCompanyDelegationEntity userCompanyDelegationEntity) {
|
||||
return Utils.convertSourceObjectToDestinationObject(userCompanyDelegationEntity, CompanyDelegationResponse.class);
|
||||
}
|
||||
|
||||
private UploadFileOnAmazonS3 uploadFileOnAmazonS3(MultipartFile file){
|
||||
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
|
||||
String fileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
|
||||
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||
firstNameContain+=Utils.randomKey(5);
|
||||
fileName = (firstNameContain + "." + extension);
|
||||
try {
|
||||
String filepath = amazonS3Service.upload(fileName, s3Folder, file);
|
||||
return new UploadFileOnAmazonS3(fileName, filepath);
|
||||
} catch (Exception e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private record UploadFileOnAmazonS3(String fileName, String filepath) {
|
||||
}
|
||||
|
||||
private void validateFileType(MultipartFile file) {
|
||||
if (file.isEmpty()) {
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
@@ -17,16 +17,17 @@ import net.gepafin.tendermanagement.entities.CallEntity;
|
||||
import net.gepafin.tendermanagement.entities.DocumentEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocumentTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.response.DocumentResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.UploadFileOnAmazonS3Response;
|
||||
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
||||
import net.gepafin.tendermanagement.service.AmazonS3Service;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DocumentDao {
|
||||
|
||||
@@ -41,6 +42,12 @@ public class DocumentDao {
|
||||
|
||||
@Autowired
|
||||
private CallService callService;
|
||||
|
||||
@Autowired
|
||||
private S3PathConfig s3ConfigBean;
|
||||
|
||||
@Autowired
|
||||
private ApplicationRepository applicationFormRepository;
|
||||
|
||||
@Value("${aws.s3.url.folder}")
|
||||
private String s3Folder;
|
||||
@@ -49,24 +56,45 @@ public class DocumentDao {
|
||||
List<DocumentEntity> documentEntities = new ArrayList<>();
|
||||
Long source = resolveSourceId(sourceId, sourceType);
|
||||
for (MultipartFile file : files) {
|
||||
try {
|
||||
uploadFileOnAmazonS3 result = uploadFileOnAmazonS3(file);
|
||||
if (result != null) {
|
||||
DocumentEntity documentEntity = new DocumentEntity();
|
||||
documentEntity.setFileName(result.fileName());
|
||||
documentEntity.setSource(sourceType.getValue());
|
||||
documentEntity.setSourceId(source);
|
||||
documentEntity.setType(fileType.getValue());
|
||||
documentEntity.setFilePath(result.filepath());
|
||||
documentEntity.setIsDeleted(false);
|
||||
documentEntities.add(documentEntity);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
UploadFileOnAmazonS3Response uploadFileOnAmazonS3Response = uploadFileOnAmazonS3(file, sourceType, sourceId);
|
||||
if (uploadFileOnAmazonS3Response != null) {
|
||||
DocumentEntity documentEntity = new DocumentEntity();
|
||||
documentEntity.setFileName(uploadFileOnAmazonS3Response.getFileName());
|
||||
documentEntity.setSource(sourceType.getValue());
|
||||
documentEntity.setSourceId(source);
|
||||
documentEntity.setType(fileType.getValue());
|
||||
documentEntity.setFilePath(uploadFileOnAmazonS3Response.getFilePath());
|
||||
documentEntity.setIsDeleted(false);
|
||||
documentEntities.add(documentEntity);
|
||||
}
|
||||
}
|
||||
documentRepository.saveAll(documentEntities);
|
||||
return documentEntities.stream().map(callDao::convertToDocumentResponseBean).collect(Collectors.toList());
|
||||
}
|
||||
private UploadFileOnAmazonS3Response uploadFileOnAmazonS3(MultipartFile file, DocumentSourceTypeEnum type, Long sourceId) {
|
||||
|
||||
Long applicationId = 0L;
|
||||
Long callId = sourceId;
|
||||
if (type == DocumentSourceTypeEnum.APPLICATION) {
|
||||
applicationId = sourceId;
|
||||
callId = applicationFormRepository.findCallIdById(applicationId);
|
||||
}
|
||||
try {
|
||||
String s3Path = generateS3Path(type, callId, applicationId);
|
||||
log.info("Generated S3 path {}", s3Path);
|
||||
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
|
||||
} catch (Exception e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
|
||||
}
|
||||
}
|
||||
public String generateS3Path(DocumentSourceTypeEnum typeOfDocument, Long callId, Long applicationId) {
|
||||
|
||||
try {
|
||||
return s3ConfigBean.generateDocumentPath(typeOfDocument, callId, applicationId);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.S3_PATH_GENERATION_ERROR_MSG));
|
||||
}
|
||||
}
|
||||
private Long resolveSourceId(Long sourceId, DocumentSourceTypeEnum sourceType) {
|
||||
if (sourceType == DocumentSourceTypeEnum.CALL) {
|
||||
CallEntity callEntity = callService.validateCall(sourceId);
|
||||
@@ -80,19 +108,6 @@ public class DocumentDao {
|
||||
return sourceId;
|
||||
}
|
||||
|
||||
private uploadFileOnAmazonS3 uploadFileOnAmazonS3(MultipartFile file) throws IOException {
|
||||
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
|
||||
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
|
||||
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||
fileName = (firstNameContain + "." + extension);
|
||||
String filepath = amazonS3Service.upload(fileName, s3Folder, file);
|
||||
uploadFileOnAmazonS3 result = new uploadFileOnAmazonS3(fileName, filepath);
|
||||
return result;
|
||||
}
|
||||
|
||||
private record uploadFileOnAmazonS3(String fileName, String filepath) {
|
||||
}
|
||||
|
||||
public void deleteFile(Long documentId) {
|
||||
DocumentEntity documentEntity = validateDocument(documentId);
|
||||
// String fileName= Utils.extractFileName(documentEntity.getFilePath());
|
||||
@@ -101,13 +116,6 @@ public class DocumentDao {
|
||||
documentRepository.save(documentEntity);
|
||||
}
|
||||
|
||||
private DocumentEntity deleteFileOnAmazonS3(String fileName) {
|
||||
try {
|
||||
amazonS3Service.delete(s3Folder, fileName);
|
||||
} catch (Exception e) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public DocumentEntity validateDocument(Long id) {
|
||||
return documentRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
@@ -116,16 +124,11 @@ public class DocumentDao {
|
||||
|
||||
public DocumentResponseBean updateDocument(Long documentId, MultipartFile file, DocumentTypeEnum documentTypeEnum) {
|
||||
DocumentEntity documentEntity = validateDocument(documentId);
|
||||
String fileName = Utils.extractFileName(documentEntity.getFilePath());
|
||||
deleteFileOnAmazonS3(fileName);
|
||||
uploadFileOnAmazonS3 result = null;
|
||||
try {
|
||||
result = uploadFileOnAmazonS3(file);
|
||||
} catch (IOException e) {
|
||||
}
|
||||
if (result != null) {
|
||||
documentEntity.setFilePath(result.filepath);
|
||||
documentEntity.setFileName(result.fileName);
|
||||
String type = documentEntity.getSource();
|
||||
UploadFileOnAmazonS3Response uploadFileOnAmazonS3Response = updateFileOnAmazonS3(file, DocumentSourceTypeEnum.valueOf(type), documentEntity.getSourceId());
|
||||
if (uploadFileOnAmazonS3Response != null) {
|
||||
documentEntity.setFileName(uploadFileOnAmazonS3Response.getFileName());
|
||||
documentEntity.setFilePath(uploadFileOnAmazonS3Response.getFilePath());
|
||||
documentEntity.setType(documentTypeEnum.getValue());
|
||||
documentEntity.setSource(documentEntity.getSource());
|
||||
documentEntity.setSourceId(documentEntity.getSourceId());
|
||||
@@ -133,7 +136,25 @@ public class DocumentDao {
|
||||
}
|
||||
return callDao.convertToDocumentResponseBean(documentEntity);
|
||||
}
|
||||
private UploadFileOnAmazonS3Response updateFileOnAmazonS3(MultipartFile file, DocumentSourceTypeEnum type, Long id) {
|
||||
|
||||
try {
|
||||
Long callId;
|
||||
Long applicationId;
|
||||
if(type.equals("APPLICATION")){
|
||||
callId = applicationFormRepository.findCallIdById(id);
|
||||
applicationId = id;
|
||||
}else{
|
||||
callId = id;
|
||||
applicationId = 0L;
|
||||
}
|
||||
String s3Path = generateS3Path(type, callId, applicationId);
|
||||
log.info("Generated S3 path {}", s3Path);
|
||||
return amazonS3Service.uploadFileOnAmazonS3(s3Path, file);
|
||||
} catch (Exception e) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
|
||||
}
|
||||
}
|
||||
public DocumentResponseBean getDocument(Long documentId) {
|
||||
DocumentEntity documentEntity = validateDocument(documentId);
|
||||
return callDao.convertToDocumentResponseBean(documentEntity);
|
||||
|
||||
@@ -3,17 +3,21 @@ package net.gepafin.tendermanagement.dao;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.CallEntity;
|
||||
import net.gepafin.tendermanagement.entities.CriteriaFormFieldEntity;
|
||||
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
|
||||
import net.gepafin.tendermanagement.entities.LookUpDataEntity;
|
||||
import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest;
|
||||
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.CriteriaFormFieldRepository;
|
||||
import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.service.LookUpDataService;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@@ -27,6 +31,9 @@ public class EvaluationCriteriaDao {
|
||||
|
||||
@Autowired
|
||||
private LookUpDataService lookUpDataService;
|
||||
|
||||
@Autowired
|
||||
private CriteriaFormFieldRepository criteriaFormFieldRepository;
|
||||
|
||||
public EvaluationCriteriaResponseBean createEvaluationCriteria(
|
||||
EvaluationCriteriaRequest evaluationCriteriaRequest) {
|
||||
@@ -43,7 +50,10 @@ public class EvaluationCriteriaDao {
|
||||
.validateLookUpData(evaluationCriteriaRequest.getLookUpDataId());
|
||||
entity.setCall(callEntity);
|
||||
entity.setLookupData(looDataEntity);
|
||||
entity.setScore(evaluationCriteriaRequest.getScore());
|
||||
entity.setScore(0L);
|
||||
if (evaluationCriteriaRequest.getScore() != null) {
|
||||
entity.setScore(evaluationCriteriaRequest.getScore());
|
||||
}
|
||||
entity = evaluationCriteriaRepository.save(entity);
|
||||
return entity;
|
||||
}
|
||||
@@ -54,6 +64,12 @@ public class EvaluationCriteriaDao {
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_NOT_FOUND)));
|
||||
}
|
||||
|
||||
public EvaluationCriteriaEntity validateEvaluationCriteria(Long id) {
|
||||
return evaluationCriteriaRepository.findById(id)
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_NOT_FOUND)));
|
||||
}
|
||||
|
||||
public EvaluationCriteriaResponseBean updateEvaluationCriteria(Long id, EvaluationCriteriaRequest request) {
|
||||
EvaluationCriteriaEntity entity = evaluationCriteriaRepository.findById(id)
|
||||
@@ -64,12 +80,15 @@ public class EvaluationCriteriaDao {
|
||||
}
|
||||
|
||||
public void deleteEvaluationCriteria(Long id) {
|
||||
try {
|
||||
evaluationCriteriaRepository.deleteById(id);
|
||||
} catch (EmptyResultDataAccessException e) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_NOT_FOUND));
|
||||
}
|
||||
EvaluationCriteriaEntity evaluationCriteriaEntity = validateEvaluationCriteria(id);
|
||||
evaluationCriteriaEntity.setIsDeleted(Boolean.TRUE);
|
||||
evaluationCriteriaRepository.save(evaluationCriteriaEntity);
|
||||
List<CriteriaFormFieldEntity> list = criteriaFormFieldRepository.findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaEntity.getId())
|
||||
.stream()
|
||||
.peek(data -> data.setIsDeleted(Boolean.TRUE))
|
||||
.toList();;
|
||||
criteriaFormFieldRepository.saveAll(list);
|
||||
}
|
||||
|
||||
private EvaluationCriteriaResponseBean convertEvaluationCriteriaEntityEvaluationCriteriaToResponseBean(
|
||||
|
||||
@@ -6,25 +6,27 @@ import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.model.request.*;
|
||||
import net.gepafin.tendermanagement.model.response.ContentResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.FormResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.VatNumberResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.*;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.service.EvaluationCriteriaService;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.FieldValidator;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
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.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.text.MessageFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
@@ -33,9 +35,6 @@ public class FormDao {
|
||||
@Autowired
|
||||
private FormRepository formRepository;
|
||||
|
||||
@Autowired
|
||||
private CallService callService;
|
||||
|
||||
@Autowired
|
||||
private ApplicationFormRepository applicationFormRepository;
|
||||
|
||||
@@ -53,35 +52,55 @@ public class FormDao {
|
||||
|
||||
@Autowired
|
||||
private CallRepository callRepository;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Autowired
|
||||
private CriteriaFormFieldRepository criteriaFormFieldRepository;
|
||||
|
||||
@Autowired
|
||||
private EvaluationCriteriaService evaluationCriteriaService;
|
||||
|
||||
public FormEntity saveFormEntity(FormEntity formEntity){
|
||||
formEntity=formRepository.save(formEntity);
|
||||
return formEntity;
|
||||
}
|
||||
|
||||
public FormEntity convertFormRequestToFormEntity(Long callId,FormRequest formRequest){
|
||||
public FormEntity convertFormRequestToFormEntity(CallEntity callEntity, FormRequest formRequest){
|
||||
FormEntity formEntity=new FormEntity();
|
||||
CallEntity callEntity=callService.getCallEntityById(callId);
|
||||
formEntity.setCall(callEntity);
|
||||
formEntity.setLabel(formRequest.getLabel());
|
||||
formEntity.setContent(setContentResponseBean(formRequest.getContent()));
|
||||
formEntity=saveFormEntity(formEntity);
|
||||
return formEntity;
|
||||
}
|
||||
public FormResponseBean convertFormEntityToFormResponseBean(FormEntity formEntity){
|
||||
public FormResponseBean convertFormEntityToFormResponseBean(FormEntity formEntity) {
|
||||
FormResponseBean formResponseBean=new FormResponseBean();
|
||||
formResponseBean.setId(formEntity.getId());
|
||||
formResponseBean.setContent(Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class));
|
||||
formResponseBean.setContent(setContent(formEntity));
|
||||
formResponseBean.setLabel(formEntity.getLabel());
|
||||
formResponseBean.setCallId(formEntity.getCall().getId());
|
||||
formResponseBean.setCallStatus(formEntity.getCall().getStatus());
|
||||
return formResponseBean;
|
||||
}
|
||||
public FormResponseBean createForm(Long callId,FormRequest formRequest){
|
||||
|
||||
private List<ContentResponseBean> setContent(FormEntity formEntity) {
|
||||
List<ContentResponseBean> contentList = Utils.convertJsonStringToList(formEntity.getContent(),
|
||||
ContentResponseBean.class);
|
||||
contentList.forEach(data -> {
|
||||
List<Long> criteriaIds = criteriaFormFieldRepository
|
||||
.findByCallIdAndFormIdAndFormFieldIdAndIsDeletedFalse(formEntity.getCall().getId(), formEntity.getId(), data.getId())
|
||||
.stream().map(CriteriaFormFieldEntity::getEvaluationCriteriaId).toList();
|
||||
data.setCriteria(criteriaIds);
|
||||
});
|
||||
return contentList;
|
||||
}
|
||||
|
||||
public FormResponseBean createForm(CallEntity callEntity,FormRequest formRequest){
|
||||
validateForm(formRequest);
|
||||
CallEntity callEntity=callService.validateCall(callId);
|
||||
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callId);
|
||||
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callId);
|
||||
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callEntity.getId());
|
||||
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callEntity.getId());
|
||||
if(Boolean.FALSE.equals(flowDataEntities.isEmpty() || flowDataEntities==null ) || Boolean.FALSE.equals(flowEdgesEntities.isEmpty() || flowEdgesEntities==null) ){
|
||||
flowDataRepository.deleteAll(flowDataEntities);
|
||||
flowEdgesRepository.deleteAll(flowEdgesEntities);
|
||||
@@ -89,19 +108,72 @@ public class FormDao {
|
||||
callEntity.setFinalForm(null);
|
||||
callRepository.save(callEntity);
|
||||
}
|
||||
FormEntity formEntity=convertFormRequestToFormEntity(callId,formRequest);
|
||||
FormEntity formEntity=convertFormRequestToFormEntity(callEntity, formRequest);
|
||||
validateAndSaveCriteriaFormField(callEntity, formEntity, formRequest.getContent());
|
||||
return convertFormEntityToFormResponseBean(formEntity);
|
||||
}
|
||||
public void validateForm(FormRequest formRequest){
|
||||
|
||||
private void validateAndSaveCriteriaFormField(CallEntity callEntity, FormEntity formEntity,
|
||||
List<ContentRequestBean> contentResponseBeans) {
|
||||
|
||||
contentResponseBeans.forEach(content -> {
|
||||
// Fetch existing records from the repository based on the call, form, and field ID
|
||||
List<CriteriaFormFieldEntity> existingCriteriaFields = criteriaFormFieldRepository
|
||||
.findByCallIdAndFormIdAndFormFieldIdAndIsDeletedFalse(callEntity.getId(), formEntity.getId(), content.getId());
|
||||
|
||||
// Extract existing evaluation criteria IDs into a set for quick lookup
|
||||
Set<Long> existingEvaluationCriteriaIds = existingCriteriaFields.stream()
|
||||
.map(CriteriaFormFieldEntity::getEvaluationCriteriaId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Get the criteria list (handling null as an empty list for uniformity)
|
||||
List<Long> criteriaList = Optional.ofNullable(content.getCriteria()).orElse(Collections.emptyList());
|
||||
|
||||
// Filter and create new entries for criteria that are not already present
|
||||
criteriaList.stream()
|
||||
.filter(criteriaId -> !existingEvaluationCriteriaIds.contains(criteriaId))
|
||||
.forEach(criteriaId -> createCriteriaFormField(callEntity, formEntity, content.getId(), criteriaId));
|
||||
|
||||
List<CriteriaFormFieldEntity> toBeDeleted = existingCriteriaFields.stream()
|
||||
.filter(criteriaFormField -> !criteriaList.contains(criteriaFormField.getEvaluationCriteriaId()))
|
||||
.peek(data->data.setIsDeleted(Boolean.TRUE))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (!toBeDeleted.isEmpty()) {
|
||||
criteriaFormFieldRepository.saveAll(toBeDeleted);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void createCriteriaFormField(CallEntity callEntity, FormEntity formEntity,
|
||||
String formFieldId,Long evaluationCriteriaId) {
|
||||
EvaluationCriteriaEntity evaluationCriteria = evaluationCriteriaService.validateEvaluationCriteria(evaluationCriteriaId);
|
||||
if (Boolean.FALSE.equals(evaluationCriteria.getCall().getId().equals(callEntity.getId()))) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.EVALUATIONCRITERIA_INVALID));
|
||||
}
|
||||
CriteriaFormFieldEntity criteriaFormField = new CriteriaFormFieldEntity();
|
||||
criteriaFormField.setCallId(callEntity.getId());
|
||||
criteriaFormField.setFormId(formEntity.getId());
|
||||
criteriaFormField.setFormFieldId(formFieldId);
|
||||
criteriaFormField.setIsDeleted(Boolean.FALSE);
|
||||
criteriaFormField.setEvaluationCriteriaId(evaluationCriteriaId);
|
||||
criteriaFormFieldRepository.save(criteriaFormField);
|
||||
|
||||
}
|
||||
|
||||
public void validateForm(FormRequest formRequest){
|
||||
if(formRequest.getContent()==null || formRequest.getLabel()==null ){
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.REQUIRED_PARAMETER_NOT_FOUND_FOR_FORM));
|
||||
}
|
||||
}
|
||||
public FormResponseBean updateForm(Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
|
||||
}
|
||||
public FormResponseBean updateForm(UserEntity user, Long formId, FormRequest formRequest,Boolean forceDeleteFlow){
|
||||
ContentRequestBean contentRequestBean2=null;
|
||||
String choosenField=null;
|
||||
FormEntity formEntity = validateForm(formId);
|
||||
callDao.validateUpdate(formEntity.getCall());
|
||||
validator.validateUserWithCall(user, formEntity.getCall().getId());
|
||||
callDao.validateUpdate(formEntity.getCall());
|
||||
List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(), ContentRequestBean.class);
|
||||
for (ContentRequestBean contentRequestBean1 : contentRequestBean) {
|
||||
FlowDataEntity flowDataEntity = flowDataRepository.findByFormIdAndChoosenField(formEntity.getId(), contentRequestBean1.getId());
|
||||
@@ -160,6 +232,7 @@ public class FormDao {
|
||||
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
|
||||
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
|
||||
formEntity = saveFormEntity(formEntity);
|
||||
validateAndSaveCriteriaFormField(formEntity.getCall(), formEntity, formRequest.getContent());
|
||||
return convertFormEntityToFormResponseBean(formEntity);
|
||||
}
|
||||
return convertFormEntityToFormResponseBean(formEntity);
|
||||
@@ -171,12 +244,14 @@ public class FormDao {
|
||||
return formEntity;
|
||||
}
|
||||
|
||||
public FormResponseBean getFormEntityById(Long formId) {
|
||||
public FormResponseBean getFormEntityById(UserEntity user, Long formId) {
|
||||
FormEntity formEntity = validateForm(formId);
|
||||
validator.validateUserWithCall(user, formEntity.getCall().getId());
|
||||
return convertFormEntityToFormResponseBean(formEntity);
|
||||
}
|
||||
public void deleteFormById(Long formId){
|
||||
public void deleteFormById(UserEntity user, Long formId){
|
||||
FormEntity formEntity = validateForm(formId);
|
||||
validator.validateUserWithCall(user, formEntity.getCall().getId());
|
||||
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(formEntity.getCall().getId());
|
||||
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(formEntity.getCall().getId());
|
||||
flowDataRepository.deleteAll(flowDataEntities);
|
||||
@@ -187,20 +262,22 @@ public class FormDao {
|
||||
callRepository.save(callEntity);
|
||||
formRepository.delete(formEntity);
|
||||
}
|
||||
public List<FormResponseBean> getFormsByCallId(Long callId){
|
||||
CallEntity callEntity=callService.validateCall(callId);
|
||||
public List<FormResponseBean> getFormsByCallId(CallEntity callEntity){
|
||||
if(callEntity== null){
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
|
||||
}
|
||||
List<FormEntity> formEntities=formRepository.findByCallId(callId);
|
||||
List<FormEntity> formEntities=formRepository.findByCallId(callEntity.getId());
|
||||
List<FormResponseBean> formResponseBeanList = formEntities.stream()
|
||||
.map(req -> convertFormEntityToFormResponseBean(req))
|
||||
.collect(Collectors.toList());
|
||||
return formResponseBeanList;
|
||||
}
|
||||
public String setContentResponseBean(List<ContentRequestBean> contentRequestBeans){
|
||||
return Utils.convertListToJsonString(contentRequestBeans);
|
||||
String stringContentRequest = Utils.convertListToJsonString(contentRequestBeans);
|
||||
List<ContentRequestBean> cloneContentRequestBeans = Utils.convertJsonStringToList(stringContentRequest, ContentRequestBean.class);
|
||||
cloneContentRequestBeans.forEach(data->data.setCriteria(null));
|
||||
return Utils.convertListToJsonString(cloneContentRequestBeans);
|
||||
}
|
||||
|
||||
public void validateFormField(List<ApplicationFormFieldRequestBean> applicationFormFieldRequestList, ApplicationEntity applicationEntity, FormEntity formEntity) {
|
||||
@@ -295,12 +372,13 @@ public class FormDao {
|
||||
String error=null;
|
||||
|
||||
if (value!=null && value.matches("^\\d{1,11}$")) {
|
||||
Map<String, Object> customData=null;
|
||||
// Map<String, Object> customData=null;
|
||||
try {
|
||||
Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
|
||||
if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
|
||||
customData = vatCheckResponse;
|
||||
}
|
||||
// Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
|
||||
vatCheckDao.checkVatNumberApi(value);
|
||||
// if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
|
||||
// customData = vatCheckResponse;
|
||||
// }
|
||||
} catch (Exception e) {
|
||||
error=(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_VALID_PIVA), fieldId));
|
||||
}
|
||||
|
||||
100
src/main/java/net/gepafin/tendermanagement/dao/HubDao.java
Normal file
100
src/main/java/net/gepafin/tendermanagement/dao/HubDao.java
Normal file
@@ -0,0 +1,100 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
import net.gepafin.tendermanagement.model.request.HubReq;
|
||||
import net.gepafin.tendermanagement.model.response.HubResponseBean;
|
||||
import net.gepafin.tendermanagement.model.util.NanoIdUtils;
|
||||
import net.gepafin.tendermanagement.repositories.HubRepository;
|
||||
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.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Component
|
||||
public class HubDao {
|
||||
|
||||
@Autowired
|
||||
private HubRepository hubRepository;
|
||||
|
||||
public HubResponseBean createHub(HubReq hubReq) {
|
||||
HubEntity hubEntity = createOrUpdateHubEntity(new HubEntity(), hubReq);
|
||||
hubRepository.save(hubEntity);
|
||||
return convertToHubResponseBean(hubEntity);
|
||||
}
|
||||
|
||||
public HubResponseBean updateHub(Long hubId, HubReq hubReq) {
|
||||
HubEntity hubEntity = validateHub(hubId);
|
||||
createOrUpdateHubEntity(hubEntity, hubReq);
|
||||
return convertToHubResponseBean(hubEntity);
|
||||
}
|
||||
|
||||
public HubResponseBean getHubById(Long hubId) {
|
||||
return convertToHubResponseBean(validateHub(hubId));
|
||||
}
|
||||
|
||||
public List<HubResponseBean> getAllHubs() {
|
||||
List<HubEntity> hubs = hubRepository.findAll();
|
||||
return hubs.stream().map(this::convertToHubResponseBean).toList();
|
||||
}
|
||||
|
||||
public void deleteHub(Long hubId) {
|
||||
HubEntity hubEntity = validateHub(hubId);
|
||||
hubRepository.deleteById(hubId);
|
||||
hubRepository.save(hubEntity);
|
||||
}
|
||||
|
||||
private HubEntity validateHub(Long hubId) {
|
||||
return hubRepository.findById(hubId)
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.HUB_NOT_FOUND)));
|
||||
}
|
||||
|
||||
private HubEntity createOrUpdateHubEntity(HubEntity hubEntity, HubReq hubReq) {
|
||||
hubEntity.setCompanyName(hubReq.getCompanyName());
|
||||
hubEntity.setFirstName(hubReq.getFirstName());
|
||||
hubEntity.setLastName(hubReq.getLastName());
|
||||
hubEntity.setEmail(hubReq.getEmail());
|
||||
hubEntity.setCity(hubReq.getCity());
|
||||
hubEntity.setCountry(hubReq.getCountry());
|
||||
hubEntity.setVatNumber(hubReq.getVatNumber());
|
||||
hubEntity.setUniqueUuid(NanoIdUtils.randomNanoId());
|
||||
hubEntity.setDomainName(hubReq.getDomainName());
|
||||
hubEntity.setAppConfig(hubReq.getAppConfig() != null ? hubReq.getAppConfig().toString() : null);
|
||||
hubEntity.setCreatedDate(hubEntity.getCreatedDate() == null ? LocalDateTime.now() : hubEntity.getCreatedDate());
|
||||
hubEntity.setUpdatedDate(LocalDateTime.now());
|
||||
return hubEntity;
|
||||
}
|
||||
|
||||
private HubResponseBean convertToHubResponseBean(HubEntity hubEntity) {
|
||||
HubResponseBean responseBean = new HubResponseBean();
|
||||
responseBean.setId(hubEntity.getId());
|
||||
responseBean.setCompanyName(hubEntity.getCompanyName());
|
||||
responseBean.setFirstName(hubEntity.getFirstName());
|
||||
responseBean.setLastName(hubEntity.getLastName());
|
||||
responseBean.setEmail(hubEntity.getEmail());
|
||||
responseBean.setCity(hubEntity.getCity());
|
||||
responseBean.setCountry(hubEntity.getCountry());
|
||||
responseBean.setVatNumber(hubEntity.getVatNumber());
|
||||
responseBean.setUniqueUuid(hubEntity.getUniqueUuid());
|
||||
responseBean.setDomainName(hubEntity.getDomainName());
|
||||
responseBean.setAppConfig(hubEntity.getAppConfig());
|
||||
responseBean.setCreatedDate(hubEntity.getCreatedDate());
|
||||
responseBean.setUpdatedDate(hubEntity.getUpdatedDate());
|
||||
return responseBean;
|
||||
}
|
||||
|
||||
public HubEntity getHubByUuid(String hubUuid) {
|
||||
return hubRepository.findByUniqueUuid(hubUuid).orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.HUB_NOT_FOUND)));
|
||||
}
|
||||
|
||||
public HubResponseBean getHubByHubUuid(String uuid) {
|
||||
return convertToHubResponseBean(getHubByUuid(uuid));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package net.gepafin.tendermanagement.dao;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.model.response.LoginAttemptPageableResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.LoginAttemptRepository;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
@@ -29,7 +30,7 @@ public class LoginAttemptDao {
|
||||
loginAttemptRepository.save(loginAttemptEntity);
|
||||
}
|
||||
|
||||
public LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(Integer pageNo, Integer pageLimit) {
|
||||
public LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(UserEntity userEntity, Integer pageNo, Integer pageLimit) {
|
||||
if (pageLimit == null || pageLimit <= 0) {
|
||||
pageLimit = GepafinConstant.DEFAULT_PAGE_LIMIT;
|
||||
}
|
||||
@@ -38,7 +39,7 @@ public class LoginAttemptDao {
|
||||
pageNo = GepafinConstant.DEFAULT_PAGE;
|
||||
}
|
||||
|
||||
Page<LoginAttemptEntity> page = loginAttemptRepository.findAll(PageRequest.of(pageNo - 1, pageLimit, Sort.by(GepafinConstant.ATTEMPT_DATE).descending()));
|
||||
Page<LoginAttemptEntity> page = loginAttemptRepository.findByHubId(userEntity.getHub().getId(), PageRequest.of(pageNo - 1, pageLimit, Sort.by(GepafinConstant.ATTEMPT_DATE).descending()));
|
||||
List<LoginAttemptEntity> list = new ArrayList<>();
|
||||
for (LoginAttemptEntity loginAttemptEntity : page.getContent()) {
|
||||
list.add(loginAttemptEntity);
|
||||
|
||||
@@ -2,12 +2,6 @@ package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.itextpdf.kernel.colors.ColorConstants;
|
||||
import com.itextpdf.kernel.colors.DeviceRgb;
|
||||
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
|
||||
import com.itextpdf.layout.properties.UnitValue;
|
||||
import com.itextpdf.layout.renderer.CellRenderer;
|
||||
import com.itextpdf.layout.renderer.DrawContext;
|
||||
import com.itextpdf.text.*;
|
||||
import com.itextpdf.text.Element;
|
||||
import com.itextpdf.text.Font;
|
||||
@@ -16,28 +10,21 @@ import com.itextpdf.text.Rectangle;
|
||||
import com.itextpdf.text.pdf.*;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.entities.*;
|
||||
import net.gepafin.tendermanagement.model.request.CustomPageEvent;
|
||||
import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest;
|
||||
import net.gepafin.tendermanagement.model.response.*;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
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;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.itextpdf.layout.element.Table;
|
||||
import com.itextpdf.layout.element.Cell;
|
||||
//import com.itextpdf.layout.element.
|
||||
|
||||
|
||||
import java.awt.*;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -54,6 +41,7 @@ public class PdfDao {
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
public static final Logger log = LoggerFactory.getLogger(PdfDao.class);
|
||||
|
||||
public byte[] generatePdf(HttpServletRequest request,Long applicationId) {
|
||||
try {
|
||||
@@ -92,56 +80,11 @@ public class PdfDao {
|
||||
addColoredLines(writer,document,greyColor);
|
||||
document.add(new Paragraph(" "));
|
||||
|
||||
// Application ID section (Centered)
|
||||
// pageEvent.setTotalPages(writer.getPageNumber());
|
||||
String protocolNumber="XX00";
|
||||
if(applicationEntity.getProtocol()!=null) {
|
||||
protocolNumber= String.valueOf(applicationEntity.getProtocol().getProtocolNumber());
|
||||
}
|
||||
Paragraph appId = new Paragraph("ID domanda :" +protocolNumber);
|
||||
appId.setAlignment(Element.ALIGN_RIGHT);
|
||||
document.add(appId);
|
||||
|
||||
document.add(new Paragraph(" "));
|
||||
|
||||
addColoredLines(writer,document,greenColor);
|
||||
document.add(new Paragraph(" "));
|
||||
document.add(new Paragraph("\n")); // Add line break
|
||||
// String companyName= companyEntity.getCompanyName();
|
||||
// String vatNumber=companyEntity.getVatNumber();
|
||||
// String address=companyEntity.getAddress();
|
||||
// // Section: Dati Anagrafici Azienda
|
||||
// document.add(new Paragraph("Dati Anagrafici Azienda", sectionFont));
|
||||
// addLabelValuePair(document, "Codice ATECO", "SEZIONE C “ATTIVITÀ MANUFATTURIERE”", regularFont);
|
||||
// addLabelValuePair(document, "Ragione Sociale", companyName, regularFont);
|
||||
// addLabelValuePair(document, "Partita IVA", vatNumber, regularFont);
|
||||
// addLabelValuePair(document, "Indirizzo sede Legale", address, regularFont);
|
||||
//
|
||||
// document.add(new Paragraph("\n")); // Add line break
|
||||
//
|
||||
// // Section: Domanda presentata da
|
||||
// document.add(new Paragraph("Domanda presentata da:", sectionFont));
|
||||
// addLabelValuePair(document, "Nome e cognome", userEntity.getBeneficiary().getFirstName()+" "+userEntity.getBeneficiary().getLastName(), regularFont);
|
||||
// addLabelValuePair(document, "Codice fiscale", userEntity.getBeneficiary().getCodiceFiscale(), regularFont);
|
||||
// addLabelValuePair(document, "Telefono", userEntity.getBeneficiary().getPhoneNumber(), regularFont);
|
||||
// addLabelValuePair(document, "Email", userEntity.getBeneficiary().getEmail(), regularFont);
|
||||
// addLabelValuePair(document, "Con il titolo di", "Rappresentante legale", regularFont);
|
||||
document.add(new Paragraph(" "));
|
||||
|
||||
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(applicationId,null, userEntity);
|
||||
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(request, applicationId, null);
|
||||
for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) {
|
||||
document.add(new Paragraph(formApplicationResponse.getLabel(),sectionFont));
|
||||
document.add(new Paragraph(" ")); // Add line break
|
||||
List<FieldLabelValuePairRequest> fieldLabelValuePairRequests = getFormFieldsToLabels(formApplicationResponse);
|
||||
for (FieldLabelValuePairRequest pair : fieldLabelValuePairRequests) {
|
||||
String label = pair.getLabel();
|
||||
Object value = pair.getValue();
|
||||
Integer pages=0;
|
||||
pages=addLabelValuePair(writer,document, label, value, labelFont,valueFont,call.getName(),pages);
|
||||
if(pages !=0 ){
|
||||
// pageEvent.setTotalPages(writer.getPageNumber());
|
||||
}
|
||||
}
|
||||
List<FieldLabelValuePairRequest> fieldLabelValuePairRequests = getFormFieldsToLabels(formApplicationResponse,writer,document);
|
||||
addColoredLines(writer,document,greenColor);
|
||||
document.add(new Paragraph(" ")); // Add line break
|
||||
}
|
||||
@@ -217,15 +160,6 @@ public class PdfDao {
|
||||
|
||||
addColoredLines(writer,document,greenColor);
|
||||
|
||||
// System.out.println(writer.getPageSize());
|
||||
// System.out.println(document.getPageSize());
|
||||
// System.out.println(document.getPageNumber());
|
||||
// System.out.println(writer.getPageNumber());
|
||||
// document.setPageCount(100);
|
||||
// document.setPageCount(writer.getPageNumber());
|
||||
// System.out.println(document.getPageNumber());
|
||||
|
||||
// Close the document
|
||||
document.close();
|
||||
|
||||
// Convert to byte array for response
|
||||
@@ -238,12 +172,13 @@ public class PdfDao {
|
||||
return null;
|
||||
}
|
||||
|
||||
private Integer addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,String title,Integer totalPages) throws DocumentException {
|
||||
private void addLabelValuePair(PdfWriter writer,Document document, String label, Object value, Font labelFont,Font valueFont,ContentResponseBean contentResponseBean) throws DocumentException {
|
||||
// Add label
|
||||
Map<String, Boolean> stateFieldMap= new HashMap<>();
|
||||
|
||||
Paragraph labelParagraph = new Paragraph(label, labelFont);
|
||||
document.add(labelParagraph);
|
||||
float leftMargin = 20f;
|
||||
|
||||
PdfContentByte canvas = writer.getDirectContent();
|
||||
|
||||
// Setting the color and width of the line
|
||||
@@ -257,8 +192,6 @@ public class PdfDao {
|
||||
|
||||
if (yPos <= 140) {
|
||||
// If xEnd is less than or equal to 200, generate a new page
|
||||
|
||||
totalPages++;
|
||||
document.newPage();
|
||||
} // Add a gap between the label and value
|
||||
document.add(new Paragraph(" ")); // Adding an empty paragraph for spacing
|
||||
@@ -288,44 +221,13 @@ public class PdfDao {
|
||||
|
||||
// Finally, add the table to the document
|
||||
document.add(valueTable);
|
||||
} else {
|
||||
boolean containsThreeValues = false; // Variable to track if any map contains three keys
|
||||
List<Map<String, Object>> dataList = (List<Map<String, Object>>) value; // Cast Object to List of Maps
|
||||
for (Map<String, Object> entry : dataList) {
|
||||
if (entry.size() == 3) { // Check if the current map has three keys
|
||||
containsThreeValues = true; // If found, set the variable to true
|
||||
break; // No need to check further, exit loop
|
||||
}
|
||||
}
|
||||
List<Map<String, String>> extractedData = new ArrayList<>(); // To hold extracted data
|
||||
for (Map<String, Object> entry : dataList) {
|
||||
Map<String, String> extractedMap = new HashMap<>(); // To hold the current extracted row of data
|
||||
}
|
||||
else if (!list.isEmpty() && list.get(0) instanceof Map<?, ?>) {
|
||||
Object object = value;
|
||||
String stringvalue = Utils.convertToString(object);
|
||||
List<Map<String, Object>> fieldValueList = Utils.convertJsonStringIntoJsonList(stringvalue);
|
||||
|
||||
List<String> keys = new ArrayList<>(entry.keySet()); // Get all keys in the current map
|
||||
|
||||
// Handle based on the number of keys in the map
|
||||
if (Boolean.FALSE.equals(containsThreeValues) && keys.size() == 2) {
|
||||
// Treat the first key as the "key" and second key as the "value"
|
||||
String heading = (String) entry.get(keys.get(0)); // Get value of first key
|
||||
String value1 = (String) entry.get(keys.get(1)); // Get value of second key
|
||||
extractedMap.put(heading,value1); // Store the first key's value as "heading"
|
||||
} if (Boolean.TRUE.equals(containsThreeValues) ) {
|
||||
String amount="";
|
||||
// Treat the first as number, second as description, third as amount
|
||||
if(keys.size()==3){
|
||||
amount = (String) entry.get(keys.get(2)); // Third key's value
|
||||
}
|
||||
String number = (String) entry.get(keys.get(0)); // First key's value
|
||||
String description = (String) entry.get(keys.get(1)); // Second key's value
|
||||
|
||||
// Store the combined result as a value in the map, with a suitable key
|
||||
String combinedValue = number + "; " + description + "; " + amount; // Concatenate them as a single value
|
||||
extractedMap.put("combined", combinedValue); // Store as a single entry, key as "combined"
|
||||
}
|
||||
|
||||
extractedData.add(extractedMap); // Add each extracted map to the list
|
||||
}
|
||||
document=createPdfTable(extractedData,document);
|
||||
document = createPdfTable(fieldValueList, document, contentResponseBean);
|
||||
}
|
||||
}
|
||||
else {
|
||||
@@ -342,150 +244,89 @@ public class PdfDao {
|
||||
}
|
||||
|
||||
document.add(new Paragraph("\n")); // Add line break after each value
|
||||
return totalPages;
|
||||
}
|
||||
|
||||
private Document createPdfTable(List<Map<String, String>> extractedData,Document document) throws DocumentException {
|
||||
// Create a PdfPTable with 2 columns
|
||||
PdfPTable table = new PdfPTable(2); // Initial assumption for 2 columns
|
||||
private Document createPdfTable(List<Map<String, Object>> extractedData, Document document, ContentResponseBean contentResponseBean) throws DocumentException {
|
||||
// Create a PdfPTable with dynamic column count based on stateFieldMap size
|
||||
Map<String, String> stateFieldMap = new HashMap<>();
|
||||
|
||||
// Populate stateFieldMap from contentResponseBean settings
|
||||
contentResponseBean.getSettings().stream()
|
||||
.filter(setting -> "table_columns".equals(setting.getName())) // Check for "table_columns"
|
||||
.map(SettingResponseBean::getValue)
|
||||
.filter(Objects::nonNull) // Ensure value is not null
|
||||
.filter(settingValue -> settingValue instanceof Map) // Ensure value is a Map
|
||||
.map(settingValue -> (Map<String, Object>) settingValue) // Cast to Map
|
||||
.map(valueMap -> (List<Map<String, Object>>) valueMap.get("stateFieldData")) // Extract stateFieldData list
|
||||
.filter(Objects::nonNull) // Ensure stateFieldData is not null
|
||||
.flatMap(List::stream) // Flatten the list of field data maps
|
||||
.forEach(fieldData -> {
|
||||
String fieldName = (String) fieldData.get("name"); // Get the name field
|
||||
String fieldDataValue = (String) fieldData.get("label"); // Get the predefined field
|
||||
|
||||
if (fieldName != null && fieldDataValue != null) {
|
||||
stateFieldMap.put(fieldName, fieldDataValue);
|
||||
}
|
||||
});
|
||||
|
||||
PdfPTable table = new PdfPTable(stateFieldMap.size()); // Number of columns equals the number of map entries
|
||||
table.setWidthPercentage(100); // Set table width to 100%
|
||||
table.setTableEvent(new RoundedBorderEvent());
|
||||
|
||||
Font textFont = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new BaseColor(105, 105, 105)); // Gray text
|
||||
boolean combinedHeaderAdded = false; // Flag to track if headers for combined have been added
|
||||
float rowHeight = 50f; // Example row height, adjust as necessary
|
||||
float rowHeight = 20f; // Example row height
|
||||
float maxTableHeight = 700f; // Maximum height of the table before a page break
|
||||
float[] columnWidths = {0.7f, 0.3f};
|
||||
table.setWidths(columnWidths);
|
||||
boolean headersAdded = false; // Flag to check if headers have been added
|
||||
|
||||
// Iterate through extracted data to populate the table
|
||||
for (Map<String, Object> row : extractedData) {
|
||||
// Add headers once
|
||||
if (!headersAdded) {
|
||||
for (Map.Entry<String, String> stateField : stateFieldMap.entrySet()) {
|
||||
String headerValue = stateField.getValue(); // Header text
|
||||
|
||||
// Add table header
|
||||
// Populate the table with extracted data and style rows
|
||||
for (Map<String, String> row : extractedData) {
|
||||
for (Map.Entry<String, String> entry : row.entrySet()) {
|
||||
String key = entry.getKey(); // This will give you the key
|
||||
String value = entry.getValue(); // This will give you the value
|
||||
PdfPCell headerCell = new PdfPCell(new Phrase(headerValue)); // Create a new PdfPCell for the header
|
||||
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
||||
headerCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
||||
headerCell.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
||||
|
||||
// Check if the current entry is for the combined section
|
||||
if ("combined".equals(key)) {
|
||||
// Ensure the combined header is added only once
|
||||
if (!combinedHeaderAdded) {
|
||||
// Create a new table for combined entries
|
||||
table = new PdfPTable(3); // 3 columns for combined entries
|
||||
|
||||
PdfPCell headerCell1 = new PdfPCell(new Phrase("Number"));
|
||||
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
||||
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
||||
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
||||
table.addCell(headerCell1);
|
||||
|
||||
PdfPCell headerCell2 = new PdfPCell(new Phrase("Details"));
|
||||
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
||||
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
||||
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
||||
table.addCell(headerCell2);
|
||||
|
||||
PdfPCell headerCell3 = new PdfPCell(new Phrase("Amount"));
|
||||
headerCell3.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
||||
headerCell3.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
||||
headerCell3.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
||||
table.addCell(headerCell3);
|
||||
|
||||
combinedHeaderAdded = true; // Mark header as added
|
||||
}
|
||||
|
||||
// Split the value for "combined" into separate parts
|
||||
String[] combinedValues = value.split("; ");
|
||||
|
||||
// Check if we have 3 parts (number, description, amount)
|
||||
String number = combinedValues[0]; // 1st part (number)
|
||||
String description = combinedValues[1]; // 2nd part (description)
|
||||
String amount = "";
|
||||
if (combinedValues.length == 3) {
|
||||
amount = combinedValues[2]; // 3rd part (amount)
|
||||
}
|
||||
|
||||
// Create PDF cells using the split values
|
||||
PdfPCell cellNumber = new PdfPCell(new Phrase(number, textFont)); // Cell for number
|
||||
PdfPCell cellDescription = new PdfPCell(new Phrase(description, textFont)); // Cell for description
|
||||
PdfPCell cellAmount = new PdfPCell(new Phrase(amount, textFont)); // Cell for amount
|
||||
|
||||
// Set row background color for combined values
|
||||
cellNumber.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for combined rows
|
||||
cellDescription.setBackgroundColor(new BaseColor(239, 243, 248));
|
||||
cellAmount.setBackgroundColor(new BaseColor(239, 243, 248));
|
||||
|
||||
// Set cell height and add rounded borders
|
||||
// cellNumber.setFixedHeight(rowHeight);
|
||||
// cellDescription.setFixedHeight(rowHeight);
|
||||
// cellAmount.setFixedHeight(rowHeight);
|
||||
|
||||
cellNumber.setMinimumHeight(20f); // Set minimum height for better appearance
|
||||
cellDescription.setMinimumHeight(20f); // Set minimum height for better appearance
|
||||
cellAmount.setMinimumHeight(20f); // Set minimum height for better appearance
|
||||
|
||||
cellNumber.setPadding(7f);
|
||||
cellDescription.setPadding(7f);
|
||||
cellAmount.setPadding(7f);
|
||||
|
||||
// Add the cells to the table only once
|
||||
table.addCell(cellNumber);
|
||||
table.addCell(cellDescription);
|
||||
table.addCell(cellAmount);
|
||||
|
||||
|
||||
} else {
|
||||
if (!combinedHeaderAdded) {
|
||||
// Create a new table for combined entries
|
||||
table= new PdfPTable(2); // 3 columns for combined entries
|
||||
table.setWidthPercentage(100);
|
||||
|
||||
PdfPCell headerCell1 = new PdfPCell(new Phrase("Details"));
|
||||
headerCell1.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
||||
headerCell1.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
||||
headerCell1.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
||||
table.addCell(headerCell1);
|
||||
|
||||
PdfPCell headerCell2 = new PdfPCell(new Phrase("Amount"));
|
||||
headerCell2.setHorizontalAlignment(Element.ALIGN_CENTER); // Center align
|
||||
headerCell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
|
||||
headerCell2.setBackgroundColor(new BaseColor(178, 190, 181)); // Light gray background for header
|
||||
table.addCell(headerCell2);
|
||||
combinedHeaderAdded=true;
|
||||
}
|
||||
// Add cells for regular key-value pairs without headers
|
||||
PdfPCell cellKey = new PdfPCell(new Phrase(key, textFont));
|
||||
PdfPCell cellValue = new PdfPCell(new Phrase(value, textFont));
|
||||
|
||||
// Set background color for both cells
|
||||
cellKey.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for other rows
|
||||
cellValue.setBackgroundColor(new BaseColor(239, 243, 248));
|
||||
|
||||
cellKey.setPadding(7f);
|
||||
cellValue.setPadding(7f);
|
||||
// Set cell height and add rounded borders
|
||||
cellKey.setFixedHeight(rowHeight);
|
||||
cellValue.setFixedHeight(rowHeight);
|
||||
|
||||
// Add the cells to the table
|
||||
table.addCell(cellKey);
|
||||
table.addCell(cellValue);
|
||||
table.addCell(headerCell); // Add the header cell to the table
|
||||
}
|
||||
if (table.getTotalHeight() + rowHeight > maxTableHeight) {
|
||||
// Start a new page if needed
|
||||
document.add(table);
|
||||
table = new PdfPTable(2); // Reset table for new page
|
||||
table.setWidthPercentage(100); // Reset width percentage
|
||||
combinedHeaderAdded = false; // Reset header flag
|
||||
headersAdded = true; // Prevent headers from being added again
|
||||
}
|
||||
|
||||
// Add data rows matching stateFieldMap keys
|
||||
for (Map.Entry<String, String> stateField : stateFieldMap.entrySet()) {
|
||||
String stateKey = stateField.getKey(); // Get the key from stateFieldMap
|
||||
if (row.containsKey(stateKey)) { // If row contains the stateKey
|
||||
Object value = row.get(stateKey); // Get the value from the row map
|
||||
|
||||
PdfPCell dynamicCell = new PdfPCell(new Phrase(value != null ? value.toString() : "", textFont));
|
||||
dynamicCell.setBackgroundColor(new BaseColor(239, 243, 248)); // Light blue for the cell
|
||||
dynamicCell.setMinimumHeight(rowHeight);
|
||||
dynamicCell.setPadding(7f);
|
||||
|
||||
table.addCell(dynamicCell); // Add the dynamically created cell to the table
|
||||
}
|
||||
}
|
||||
|
||||
// Check if adding another row would exceed max height
|
||||
if (table.getTotalHeight() + rowHeight > maxTableHeight) {
|
||||
document.add(table); // Add the table to the document
|
||||
document.newPage(); // Start a new page
|
||||
table = new PdfPTable(stateFieldMap.size()); // Create a new table for the new page
|
||||
table.setWidthPercentage(100); // Reset table width
|
||||
|
||||
headersAdded = false; // Reset the header flag for the new page
|
||||
}
|
||||
}
|
||||
document.add(table); // Add the last table before returning
|
||||
|
||||
// Add the last table to the document
|
||||
document.add(table);
|
||||
|
||||
// Check if adding a new row would exceed the maximum height
|
||||
// Return the populated table
|
||||
return document;
|
||||
}
|
||||
|
||||
public static class RoundedBorderEvent implements PdfPTableEvent {
|
||||
@Override
|
||||
public void tableLayout(PdfPTable table, float[][] widths, float[] heights,
|
||||
@@ -506,82 +347,98 @@ public class PdfDao {
|
||||
canvas.stroke();
|
||||
}
|
||||
}
|
||||
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean) {
|
||||
public List<FieldLabelValuePairRequest> getFormFieldsToLabels(FormApplicationResponse responseBean,PdfWriter writer,Document document) {
|
||||
List<FieldLabelValuePairRequest> labelValuePairs = new ArrayList<>();
|
||||
|
||||
// Iterate through each form in the application response
|
||||
|
||||
List<ApplicationFormFieldResponseBean> formFields = responseBean.getFormFields();
|
||||
List<ContentResponseBean> contents = responseBean.getContent();
|
||||
|
||||
// Iterate through each formField in the current form
|
||||
for (ApplicationFormFieldResponseBean formField : formFields) {
|
||||
String fieldId = formField.getFieldId();
|
||||
Object fieldValue = formField.getFieldValue();
|
||||
|
||||
// Find the content in the form that matches the fieldId
|
||||
Optional<ContentResponseBean> matchingContent = contents.stream()
|
||||
.filter(content -> content.getId().equals(fieldId))
|
||||
.findFirst();
|
||||
Font labelFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12,new BaseColor(113,121,126)); // Light grey);
|
||||
Font valueFont=FontFactory.getFont(FontFactory.HELVETICA_BOLD,10,new BaseColor(178, 190, 181));
|
||||
|
||||
|
||||
// If the content with the matching fieldId is found, create a label-value pair
|
||||
if (matchingContent.isPresent()) {
|
||||
String name = matchingContent.get().getName();
|
||||
if (name.equals("fileupload")) {
|
||||
// Get form fields and contents from the response
|
||||
List<ApplicationFormFieldResponseBean> formFields = responseBean.getFormFields();
|
||||
List<ContentResponseBean> contents = responseBean.getContent();
|
||||
|
||||
// Step 1: Check if fieldValue is an instance of List<DocumentResponseBean>
|
||||
if (fieldValue instanceof List<?> && ((List<?>) fieldValue).stream().allMatch(item -> item instanceof DocumentResponseBean)) {
|
||||
// Step 2: Safely cast to List<DocumentResponseBean>
|
||||
List<DocumentResponseBean> documentList = (List<DocumentResponseBean>) fieldValue;
|
||||
// Iterate through each content in the response
|
||||
for (ContentResponseBean content : contents) {
|
||||
String contentId = content.getId(); // Content ID
|
||||
String label = content.getLabel(); // Content label
|
||||
String name = content.getName(); // Content name
|
||||
Object fieldValue = null;
|
||||
|
||||
// Step 3: Extract names from the document list
|
||||
List<String> names = documentList.stream()
|
||||
.map(DocumentResponseBean::getName) // Extract the name from each DocumentResponseBean
|
||||
.collect(Collectors.toList());
|
||||
String contentLabel = content.getSettings().stream()
|
||||
.filter(setting -> "label".equals(setting.getName())) // Filter settings by name
|
||||
.map(SettingResponseBean::getValue) // Extract the value from the matching setting
|
||||
.map(Object::toString) // Convert the value to a string
|
||||
.findFirst() // Get the first matching value
|
||||
.orElse(null); // If no match is found, set label to null
|
||||
// Find the form field in the response that matches the contentId
|
||||
Optional<ApplicationFormFieldResponseBean> matchingFormField = formFields.stream()
|
||||
.filter(formField -> formField.getFieldId().equals(contentId))
|
||||
.findFirst();
|
||||
|
||||
fieldValue=names;
|
||||
}
|
||||
// If a matching form field is found, process its value
|
||||
if (matchingFormField.isPresent()) {
|
||||
ApplicationFormFieldResponseBean formField = matchingFormField.get();
|
||||
fieldValue = formField.getFieldValue();
|
||||
|
||||
// If fieldValue is null, set it to an empty string
|
||||
if (fieldValue == null) {
|
||||
fieldValue = "";
|
||||
}
|
||||
|
||||
// Process 'fileupload' and 'checkboxes' cases as in the original logic
|
||||
if (name.equals("fileupload")) {
|
||||
if (fieldValue instanceof List<?> && ((List<?>) fieldValue).stream().allMatch(item -> item instanceof DocumentResponseBean)) {
|
||||
List<DocumentResponseBean> documentList = (List<DocumentResponseBean>) fieldValue;
|
||||
List<String> names = documentList.stream()
|
||||
.map(DocumentResponseBean::getName)
|
||||
.collect(Collectors.toList());
|
||||
fieldValue = names;
|
||||
}
|
||||
if(name.equals("checkboxes")) {
|
||||
List<String> check = (List<String>) fieldValue;
|
||||
List<SettingResponseBean> settingResponseBeans = matchingContent.get().getSettings();
|
||||
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
|
||||
// Initialize a list to hold matched labels for each SettingResponseBean
|
||||
List<String> matchedLabels = new ArrayList<>();
|
||||
if (settingResponseBean.getValue() instanceof List<?>) {
|
||||
} else if (name.equals("checkboxes")) {
|
||||
List<String> check = (List<String>) fieldValue;
|
||||
List<SettingResponseBean> settingResponseBeans = content.getSettings();
|
||||
List<String> matchedLabels = new ArrayList<>();
|
||||
|
||||
List<?> valueList = (List<?>) settingResponseBean.getValue();
|
||||
if (!valueList.isEmpty() && valueList.get(0) instanceof Map<?, ?>) {
|
||||
// Cast to List<Map<String, String>>
|
||||
List<Map<String, String>> options = (List<Map<String, String>>) valueList;
|
||||
for (Map<String, String> field : options) {
|
||||
for (String val : check) {
|
||||
String name1=field.get("name");
|
||||
if (val.equals(name1)) { // Check if the key exists in the current field map
|
||||
String label = field.get("label"); // Extract the label
|
||||
if (field != null) { // Check if the value is not null
|
||||
matchedLabels.add(label); // Add the value to the matchedValues list
|
||||
}
|
||||
}
|
||||
for (SettingResponseBean settingResponseBean : settingResponseBeans) {
|
||||
if (settingResponseBean.getValue() instanceof List<?>) {
|
||||
List<Map<String, String>> options = (List<Map<String, String>>) settingResponseBean.getValue();
|
||||
|
||||
for (Map<String, String> field : options) {
|
||||
for (String val : check) {
|
||||
String name1 = field.get("name");
|
||||
if (val.equals(name1)) {
|
||||
String labelVal = field.get("label");
|
||||
if (labelVal != null) {
|
||||
matchedLabels.add(labelVal);
|
||||
}
|
||||
}
|
||||
fieldValue = matchedLabels;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
String label = matchingContent.get().getLabel();
|
||||
// Add the label-value pair to the list
|
||||
if (fieldValue != null && !fieldValue.toString().trim().isEmpty()) {
|
||||
fieldValue = findLabelInOptions(matchingContent.get().getSettings(), fieldValue);
|
||||
labelValuePairs.add(new FieldLabelValuePairRequest(label, fieldValue));
|
||||
}
|
||||
fieldValue = matchedLabels;
|
||||
}
|
||||
|
||||
// Further processing of field value (e.g., finding labels in options)
|
||||
fieldValue = findLabelInOptions(content.getSettings(), fieldValue);
|
||||
} else {
|
||||
// If no matching form field is found, store contentId with an empty string
|
||||
fieldValue = "";
|
||||
}
|
||||
|
||||
try {
|
||||
addLabelValuePair(writer,document, contentLabel, fieldValue, labelFont,valueFont,content);
|
||||
} catch (DocumentException e) {
|
||||
log.error("Error checking object: " + e.getMessage(), e);
|
||||
|
||||
}
|
||||
// } labelValuePairs.add(new FieldLabelValuePairRequest(contentLabel, fieldValue));
|
||||
}
|
||||
|
||||
return labelValuePairs;
|
||||
}
|
||||
|
||||
|
||||
public static Object findLabelInOptions(List<SettingResponseBean> settings, Object valueToFind) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
104
src/main/java/net/gepafin/tendermanagement/dao/S3ConfigDao.java
Normal file
104
src/main/java/net/gepafin/tendermanagement/dao/S3ConfigDao.java
Normal file
@@ -0,0 +1,104 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.S3ConfigEntity;
|
||||
import net.gepafin.tendermanagement.model.request.S3ConfigReq;
|
||||
import net.gepafin.tendermanagement.model.response.S3ConfigBean;
|
||||
import net.gepafin.tendermanagement.repositories.S3ConfigRepository;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
|
||||
|
||||
@Component
|
||||
public class S3ConfigDao {
|
||||
private static final Logger log = LoggerFactory.getLogger(S3ConfigDao.class);
|
||||
|
||||
@Autowired
|
||||
S3ConfigRepository s3ConfigRepository;
|
||||
|
||||
public S3ConfigBean addS3Path(S3ConfigReq s3PathConfigurationReq) {
|
||||
|
||||
log.info("Adding s3 s3PathConfigurationReq structure with it's type..");
|
||||
S3ConfigEntity s3PathConfigurationEntity = convertToS3pathEntity(s3PathConfigurationReq);
|
||||
s3PathConfigurationEntity = s3ConfigRepository.save(s3PathConfigurationEntity);
|
||||
log.info("Added s3 path config details {} to DB.", s3PathConfigurationEntity);
|
||||
return convertToS3pathBean(s3PathConfigurationEntity);
|
||||
}
|
||||
private S3ConfigEntity convertToS3pathEntity(S3ConfigReq s3PathConfigReq) {
|
||||
|
||||
S3ConfigEntity s3PathConfigEntity = new S3ConfigEntity();
|
||||
s3PathConfigEntity.setPath(s3PathConfigReq.getPath());
|
||||
s3PathConfigEntity.setType(s3PathConfigReq.getType());
|
||||
s3PathConfigEntity.setBucketName(s3PathConfigReq.getBucketName());
|
||||
return s3PathConfigEntity;
|
||||
}
|
||||
private S3ConfigBean convertToS3pathBean(S3ConfigEntity s3PathConfigReq) {
|
||||
|
||||
S3ConfigBean s3PathConfigBean = new S3ConfigBean();
|
||||
s3PathConfigBean.setPath(s3PathConfigReq.getPath());
|
||||
s3PathConfigBean.setType(s3PathConfigReq.getType());
|
||||
s3PathConfigBean.setBucketName(s3PathConfigReq.getBucketName());
|
||||
return s3PathConfigBean;
|
||||
}
|
||||
|
||||
public Optional<S3ConfigEntity> getS3PathByType(String type) {
|
||||
|
||||
log.info("Fetching S3-Path structure by type: {}", type);
|
||||
Optional<S3ConfigEntity> s3PathData = s3ConfigRepository.getPathByType(type);
|
||||
if (s3PathData == null) {
|
||||
log.error("No S3-Path found for type: {}", type);
|
||||
throw new CustomValidationException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.S3_PATH_STRUCTURE_NOT_FOUND_BY_TYPE_MSG));
|
||||
}
|
||||
log.info("Fetched S3-Path: {} for type: {}", s3PathData, type);
|
||||
return s3PathData;
|
||||
}
|
||||
|
||||
public S3ConfigEntity deleteS3PathConfigById(Long id) {
|
||||
|
||||
log.info("Checking s3-path associated with this id {} to delete....", id);
|
||||
S3ConfigEntity s3PathConfigData = s3ConfigRepository.findS3PathConfigurationById(id);
|
||||
if (s3PathConfigData == null) {
|
||||
log.error("No S3-Path found for id: {}", id);
|
||||
throw new CustomValidationException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.S3_PATH_STRUCTURE_NOT_FOUND_BY_ID_MSG));
|
||||
} else {
|
||||
log.info("Found s3-path associated with this id {} to delete.", id);
|
||||
s3ConfigRepository.deleteById(id);
|
||||
log.error("Deleted s3-path configuration successfully for id: {}", id);
|
||||
return s3PathConfigData;
|
||||
}
|
||||
}
|
||||
public S3ConfigBean updateS3PathConfiguration(S3ConfigReq s3PathConfigurationReq, Long id) {
|
||||
|
||||
log.info("Updating S3-path Configuration.");
|
||||
S3ConfigEntity s3PathConfigDataExists = s3ConfigRepository.findS3PathConfigurationById(id);
|
||||
if (s3PathConfigDataExists == null) {
|
||||
log.error("No S3-Path found for id: {}", id);
|
||||
throw new CustomValidationException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.S3_PATH_STRUCTURE_NOT_FOUND_BY_ID_MSG));
|
||||
} else {
|
||||
Optional<S3ConfigEntity> s3PathData = s3ConfigRepository.getPathByType(s3PathConfigurationReq.getType());
|
||||
if(s3PathData != null){
|
||||
log.error("S3-Path type already exist. {}", s3PathData);
|
||||
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.S3_PATH_CONFIG_DUPLICATE_TYPE_ALREADY_EXIST));
|
||||
}
|
||||
S3ConfigEntity s3PathConfigurationEntity = convertToS3pathEntity(s3PathConfigurationReq);
|
||||
setIfUpdated(s3PathConfigurationEntity::getPath, s3PathConfigurationEntity::setPath, s3PathConfigurationReq.getPath());
|
||||
setIfUpdated(s3PathConfigurationEntity::getBucketName, s3PathConfigurationEntity::setBucketName, s3PathConfigurationReq.getBucketName());
|
||||
setIfUpdated(s3PathConfigurationEntity::getType, s3PathConfigurationEntity::setType, s3PathConfigurationReq.getType());
|
||||
// s3PathConfigurationEntity.setType(s3PathConfigurationReq.getType());
|
||||
// s3PathConfigurationEntity.setPath(s3PathConfigurationReq.getPath());
|
||||
// s3PathConfigurationEntity.setBucketName(s3PathConfigurationReq.getBucketName());
|
||||
s3ConfigRepository.save(s3PathConfigurationEntity);
|
||||
log.info("Updated S3-path-configuration successfully.");
|
||||
return convertToS3pathBean(s3PathConfigurationEntity);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.S3ConfigEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocOtherSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.repositories.S3ConfigRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class S3PathConfig {
|
||||
|
||||
@Autowired
|
||||
S3ConfigRepository s3ConfigRepository;
|
||||
|
||||
public String generateDocumentPath(DocumentSourceTypeEnum type, Long callId, Long applicationId) {
|
||||
|
||||
S3ConfigEntity config = getDocumentPath(type);
|
||||
return config.getParentFolder() + "/" + buildS3Path(config.getPath(), callId, applicationId);
|
||||
}
|
||||
public String generateDocumentPathForOther(DocOtherSourceTypeEnum type, Long callId, Long applicationId) {
|
||||
|
||||
S3ConfigEntity config = getDocumentPathForOther(type);
|
||||
return config.getParentFolder() + "/" + buildS3Path(config.getPath(), callId, applicationId);
|
||||
}
|
||||
private String buildS3Path(String pathTemplate, Long callId, Long applicationId) {
|
||||
|
||||
return pathTemplate.replace("{call_id}", callId != null && callId != 0L ? "call_" + callId : "").replace("{application_id}", applicationId != null && applicationId != 0L ? "application_" + applicationId : "");
|
||||
}
|
||||
public String generateDocumentPathForDelegationAndSignedDocument(DocOtherSourceTypeEnum type) {
|
||||
|
||||
S3ConfigEntity config = getDocumentPathForOther(type);
|
||||
return config.getParentFolder() + "/" + config.getPath();
|
||||
}
|
||||
private S3ConfigEntity getDocumentPath(DocumentSourceTypeEnum type) {
|
||||
|
||||
return s3ConfigRepository.getPathByType(type.name()).orElseThrow(() -> new IllegalArgumentException("No path configuration found for type: " + type));
|
||||
}
|
||||
private S3ConfigEntity getDocumentPathForOther(DocOtherSourceTypeEnum type) {
|
||||
|
||||
return s3ConfigRepository.getPathByType(type.name()).orElseThrow(() -> new IllegalArgumentException("No path configuration found for type: " + type));
|
||||
}
|
||||
public String getBucketNameForOtherType(DocOtherSourceTypeEnum type){
|
||||
return s3ConfigRepository.getBucketNameByType(type);
|
||||
}
|
||||
public String getBucketNameForCallAppType(DocumentSourceTypeEnum type){
|
||||
return s3ConfigRepository.getBucketNameByType(type);
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package net.gepafin.tendermanagement.dao;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
import net.gepafin.tendermanagement.entities.RoleEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
@@ -17,10 +19,11 @@ import net.gepafin.tendermanagement.model.response.UserResponseBean;
|
||||
import net.gepafin.tendermanagement.model.util.JWTToken;
|
||||
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import net.gepafin.tendermanagement.service.HubService;
|
||||
import net.gepafin.tendermanagement.service.RoleService;
|
||||
import net.gepafin.tendermanagement.service.impl.AuthenticationService;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
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;
|
||||
@@ -29,11 +32,12 @@ 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.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
|
||||
@@ -45,36 +49,53 @@ public class UserDao {
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private CompanyDao companyDao;
|
||||
|
||||
@Autowired
|
||||
private AuthenticationService authService;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
|
||||
@Autowired
|
||||
private RoleDao roleDao;
|
||||
|
||||
@Autowired
|
||||
private BeneficiaryRepository beneficiaryRepository;
|
||||
|
||||
@Autowired
|
||||
private RoleService roleService;
|
||||
|
||||
@Value("${default.hub.uuid}")
|
||||
private String defaultHubUuid;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Autowired
|
||||
private SamlSuccessHandler samlSuccessHandler;
|
||||
|
||||
@Autowired
|
||||
private HubService hubService;
|
||||
|
||||
|
||||
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
|
||||
|
||||
validateUserRequest(tempToken, userReq);
|
||||
if(StringUtils.isEmpty(userReq.getHubUuid())) {
|
||||
userReq.setHubUuid(defaultHubUuid);
|
||||
}
|
||||
HubEntity hub = hubService.getHubByUuid(userReq.getHubUuid());
|
||||
validateUserRequest(request, tempToken, userReq, hub);
|
||||
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
|
||||
|
||||
RoleEntity roleEntity = getRoleEntity(userReq.getRoleId());
|
||||
BeneficiaryEntity beneficiary = createBeneficiary(roleEntity, userReq);
|
||||
UserEntity userEntity = convertUserRequestToUserEntity(beneficiary, roleEntity, userReq);
|
||||
BeneficiaryEntity beneficiary = createBeneficiary(roleEntity, userReq, hub);
|
||||
UserEntity userEntity = convertUserRequestToUserEntity(beneficiary, roleEntity, userReq, hub);
|
||||
log.info("User created with ID: {}", userEntity.getId());
|
||||
return authService.getJWTTokenBean(userEntity, Boolean.TRUE);
|
||||
}
|
||||
|
||||
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq) {
|
||||
private BeneficiaryEntity createBeneficiary(RoleEntity roleEntity, UserReq userReq, HubEntity hub) {
|
||||
BeneficiaryEntity beneficiaryEntity = null;
|
||||
if (RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType())) {
|
||||
beneficiaryEntity = new BeneficiaryEntity();
|
||||
@@ -94,25 +115,34 @@ public class UserDao {
|
||||
beneficiaryEntity.setMarketing(userReq.getMarketing());
|
||||
beneficiaryEntity.setThirdParty(userReq.getThirdParty());
|
||||
beneficiaryEntity.setEmailPec(userReq.getEmailPec());
|
||||
beneficiaryEntity.setHubId(hub.getId());
|
||||
beneficiaryEntity =beneficiaryRepository.save(beneficiaryEntity);
|
||||
}
|
||||
return beneficiaryEntity;
|
||||
}
|
||||
|
||||
private void validateUserRequest(String tempToken, UserReq userReq) {
|
||||
RoleEntity role = roleService.validateRole(userReq.getRoleId());
|
||||
private void validateUserRequest(HttpServletRequest request, String tempToken, UserReq userReq, HubEntity hub) {
|
||||
|
||||
if (tempToken == null) {
|
||||
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
userReq.setHubUuid(userEntity.getHub().getUniqueUuid());
|
||||
}else {
|
||||
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale(), userReq.getHubUuid());
|
||||
}
|
||||
|
||||
if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
|
||||
}
|
||||
log.info("Creating user with email: {}", userReq.getEmail());
|
||||
if (userRepository.existsByEmailIgnoreCase(userReq.getEmail())) {
|
||||
if (userRepository.existsByEmailIgnoreCaseAndHubUniqueUuid(userReq.getEmail(), userReq.getHubUuid())) {
|
||||
log.error("User creation failed: Email {} already exists", userReq.getEmail());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
|
||||
}
|
||||
if (Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getCodiceFiscale()))
|
||||
&& userRepository.existsByBeneficiaryCodiceFiscale(userReq.getCodiceFiscale())) {
|
||||
&& userRepository.existsByBeneficiaryCodiceFiscaleAndHubId(userReq.getCodiceFiscale(), hub.getId())) {
|
||||
log.error("User creation failed: CodiceFiscale {} already exists", userReq.getCodiceFiscale());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.CODICE_FISCALE_EXISTS));
|
||||
@@ -124,10 +154,14 @@ public class UserDao {
|
||||
if (tempToken != null) {
|
||||
userReq.setRoleId(null);
|
||||
}
|
||||
if(tempToken == null && Boolean.TRUE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(role.getRoleType()))){
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.CANNOT_CREATE_BENEFICIARY_USER));
|
||||
}
|
||||
|
||||
if (tempToken == null) {
|
||||
RoleEntity role = roleService.validateRole(userReq.getRoleId());
|
||||
if (Boolean.TRUE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(role.getRoleType()))) {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.CANNOT_CREATE_BENEFICIARY_USER));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validatePassword(String password, String confirmPassword, String tempToken) {
|
||||
@@ -179,7 +213,7 @@ public class UserDao {
|
||||
return convertUserEntityToUserResponse(userEntity);
|
||||
}
|
||||
|
||||
private UserEntity convertUserRequestToUserEntity(BeneficiaryEntity beneficiary, RoleEntity roleEntity, UserReq userReq) {
|
||||
private UserEntity convertUserRequestToUserEntity(BeneficiaryEntity beneficiary, RoleEntity roleEntity, UserReq userReq, HubEntity hub) {
|
||||
UserEntity userEntity = new UserEntity();
|
||||
if(Boolean.FALSE.equals(StringUtils.isEmpty(userReq.getPassword()))) {
|
||||
userEntity.setPassword(passwordEncoder.encode(userReq.getPassword()));
|
||||
@@ -188,8 +222,8 @@ public class UserDao {
|
||||
userEntity.setEmail(userReq.getEmail());
|
||||
userEntity.setStatus(UserStatusEnum.ACTIVE.getValue());
|
||||
userEntity.setBeneficiary(beneficiary);
|
||||
userEntity.setHub(hub);
|
||||
if (Boolean.FALSE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType()))) {
|
||||
|
||||
userEntity.setFirstName(userReq.getFirstName());
|
||||
userEntity.setLastName(userReq.getLastName());
|
||||
userEntity.setOrganization(userReq.getOrganization());
|
||||
@@ -269,6 +303,9 @@ public class UserDao {
|
||||
|
||||
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
|
||||
log.info("User login attempt for email: {}", loginReq.getEmail());
|
||||
if(StringUtils.isEmpty(loginReq.getHubUuid())) {
|
||||
loginReq.setHubUuid(defaultHubUuid);
|
||||
}
|
||||
JWTToken jwtToken = authService.login(loginReq,request);
|
||||
log.info("Login successful for email: {}", loginReq.getEmail());
|
||||
return jwtToken;
|
||||
@@ -289,11 +326,11 @@ public class UserDao {
|
||||
}
|
||||
|
||||
public String initiatePasswordReset(InitiatePasswordResetReq resetReq) {
|
||||
UserEntity user = userRepository.findByEmail(resetReq.getEmail());
|
||||
if (user == null) {
|
||||
log.info("Password reset attempt for non-existent user: {}", resetReq.getEmail());
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
|
||||
}
|
||||
UserEntity user = userRepository
|
||||
.findByEmailIgnoreCaseAndHubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
|
||||
String token = Utils.generateSecureToken();
|
||||
user.setResetPasswordToken(token);
|
||||
userRepository.save(user);
|
||||
@@ -302,11 +339,11 @@ public class UserDao {
|
||||
}
|
||||
|
||||
public Boolean resetPassword(ResetPasswordReq resetPasswordReq) {
|
||||
UserEntity user = userRepository.findByEmail(resetPasswordReq.getEmail());
|
||||
if (user == null) {
|
||||
log.info("Password reset attempt for non-existent user: {}", resetPasswordReq.getEmail());
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
|
||||
}
|
||||
UserEntity user = userRepository
|
||||
.findByEmailIgnoreCaseAndHubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
|
||||
if (!resetPasswordReq.getNewPassword().equals(resetPasswordReq.getConfirmPassword())) {
|
||||
log.info("User creation failed: Passwords do not match for email {}", user.getEmail());
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
|
||||
@@ -325,12 +362,12 @@ public class UserDao {
|
||||
return true;
|
||||
}
|
||||
|
||||
public Boolean changePassword(ChangePasswordRequest request) {
|
||||
UserEntity user = userRepository.findByEmail(request.getEmail());
|
||||
if (user == null) {
|
||||
log.info("Password reset attempt for non-existent user: {}", request.getEmail());
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG));
|
||||
}
|
||||
public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest request) {
|
||||
UserEntity user = userRepository
|
||||
.findByEmailIgnoreCaseAndHubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
|
||||
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CURRENT_PASSWORD_INCORRECT));
|
||||
}
|
||||
@@ -355,6 +392,16 @@ public class UserDao {
|
||||
log.info("User status updated to {} for user ID: {}", statusReq, userId);
|
||||
return convertUserEntityToUserResponse(userEntity);
|
||||
}
|
||||
public List<UserResponseBean> getUserByHubId(String hubId) {
|
||||
// log.info("Fetching users for hub ID: {}", hubId);
|
||||
// List<UserHubEntity> userHubMappings = userHubRepository.findByHubId(hubId);
|
||||
List<UserResponseBean> userResponseBeans = new ArrayList<>();
|
||||
// for (UserHubEntity mapping : userHubMappings) {
|
||||
// UserEntity userEntity = validateUser(mapping.getUserId());
|
||||
// userResponseBeans.add(convertUserEntityToUserResponse(userEntity));
|
||||
// }
|
||||
return userResponseBeans;
|
||||
}
|
||||
|
||||
public JWTToken validateExistingUserToken(String token) {
|
||||
return authService.validateExistingUserToken(token);
|
||||
@@ -364,15 +411,15 @@ public class UserDao {
|
||||
return authService.validateNewUserToken(token);
|
||||
}
|
||||
|
||||
public List<UserResponseBean> getAllUsers(Long roleId) {
|
||||
public List<UserResponseBean> getAllUsers(UserEntity user, Long roleId) {
|
||||
List<UserEntity> users;
|
||||
if (roleId != null) {
|
||||
log.info("Fetching users by role ID: {}", roleId);
|
||||
RoleEntity roleEntity=roleService.validateRole(roleId);
|
||||
users = userRepository.findByRoleEntityId(roleEntity.getId());
|
||||
users = userRepository.findByRoleEntityIdAndHubId(roleEntity.getId(), user.getHub().getId());
|
||||
} else {
|
||||
log.info("Fetching all users");
|
||||
users = userRepository.findAll();
|
||||
users = userRepository.findByHubId(user.getHub().getId());
|
||||
}
|
||||
List<UserResponseBean> userResponseBeans = users.stream()
|
||||
.map(this::convertUserEntityToUserResponse)
|
||||
|
||||
@@ -39,4 +39,7 @@ public class ApplicationEntity extends BaseEntity {
|
||||
@OneToOne
|
||||
@JoinColumn(name = "PROTOCOL_NUMBER")
|
||||
private ProtocolEntity protocol;
|
||||
|
||||
@Column(name = "HUB_ID")
|
||||
private Long hubId;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Data
|
||||
@Table(name = "assigned_applications")
|
||||
|
||||
public class AssignedApplicationsEntity extends BaseEntity{
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "APPLICATION_ID")
|
||||
private ApplicationEntity application;
|
||||
|
||||
@Column(name = "USER_ID")
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "ASSIGNED_BY")
|
||||
private Long assignedBy;
|
||||
|
||||
@Column(name = "STATUS")
|
||||
private String status;
|
||||
|
||||
@Column(name = "NOTE")
|
||||
private String note;
|
||||
|
||||
@Column(name="IS_DELETED")
|
||||
private Boolean isDeleted=false;
|
||||
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime assignedAt;
|
||||
}
|
||||
@@ -61,4 +61,7 @@ public class BeneficiaryEntity extends BaseEntity {
|
||||
|
||||
@Column(name = "EMAIL_PEC")
|
||||
private String emailPec;
|
||||
|
||||
@Column(name = "HUB_ID")
|
||||
private Long hubId;
|
||||
}
|
||||
|
||||
@@ -84,5 +84,9 @@ public class CallEntity extends BaseEntity {
|
||||
|
||||
@Column(name = "END_TIME")
|
||||
private LocalTime endTime;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "HUB_ID")
|
||||
private HubEntity hub;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ import java.math.BigDecimal;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Data;
|
||||
|
||||
@@ -56,4 +58,9 @@ public class CompanyEntity extends BaseEntity{
|
||||
|
||||
@Column(name = "CONTACT_EMAIL")
|
||||
private String contactEmail;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "HUB_ID")
|
||||
private HubEntity hub;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Data;
|
||||
|
||||
@Entity
|
||||
@Table(name = "criteria_form_field")
|
||||
@Data
|
||||
public class CriteriaFormFieldEntity extends BaseEntity {
|
||||
|
||||
private Long callId;
|
||||
|
||||
private Long formId;
|
||||
|
||||
private String formFieldId;
|
||||
|
||||
private Long evaluationCriteriaId;
|
||||
|
||||
@Column(name ="IS_DELETED", nullable = false)
|
||||
private Boolean isDeleted = false;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
|
||||
@Entity
|
||||
@Table(name="hub")
|
||||
@Setter
|
||||
@Getter
|
||||
public class HubEntity extends BaseEntity{
|
||||
|
||||
@Column(name = "COMPANY_NAME")
|
||||
private String companyName;
|
||||
|
||||
@Column(name = "FIRST_NAME")
|
||||
private String firstName;
|
||||
|
||||
@Column(name = "LAST_NAME")
|
||||
private String lastName;
|
||||
|
||||
@Column(name = "EMAIL")
|
||||
private String email;
|
||||
|
||||
@Column(name = "CITY")
|
||||
private String city;
|
||||
|
||||
@Column(name = "COUNTRY")
|
||||
private String country;
|
||||
|
||||
@Size(min=5,max=15)
|
||||
@Column(name = "VAT_NUMBER")
|
||||
private String vatNumber;
|
||||
|
||||
@Column(name = "DOMAIN_NAME")
|
||||
private String domainName;
|
||||
|
||||
@Column(name = "APP_CONFIG")
|
||||
private String appConfig;
|
||||
|
||||
@Column(name = "UNIQUE_UUID")
|
||||
private String uniqueUuid;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "hub_user")
|
||||
@Getter
|
||||
@Setter
|
||||
public class HubUserEntity extends BaseEntity{
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "hub_id", nullable = false)
|
||||
private HubEntity hub;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
|
||||
}
|
||||
@@ -24,5 +24,8 @@ public class ProtocolEntity extends BaseEntity {
|
||||
|
||||
@Column(name="APPLICATION_ID")
|
||||
private Long applicationId;
|
||||
|
||||
@Column(name="HUB_ID")
|
||||
private Long hubId;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package net.gepafin.tendermanagement.entities;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Data;
|
||||
|
||||
@Entity
|
||||
@Table(name = "s3_path_configuration")
|
||||
@Data
|
||||
public class S3ConfigEntity extends BaseEntity {
|
||||
|
||||
@Column(name = "TYPE")
|
||||
private String type;
|
||||
|
||||
@Column(name = "PATH")
|
||||
private String path;
|
||||
|
||||
@Column(name = "BUCKET_NAME")
|
||||
private String bucketName;
|
||||
|
||||
@Column(name = "PARENT_FOLDER")
|
||||
private String parentFolder;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,21 @@ public class SamlResponseEntity extends BaseEntity{
|
||||
@Column(name = "AUTHENTICATION_OBJECT")
|
||||
private String authenticationObject;
|
||||
|
||||
@Column(name = "IN_RESPONSE_TO")
|
||||
private String inResponseTo;
|
||||
|
||||
@Column(name = "ISSUE_INSTANT")
|
||||
private String issueInstant;
|
||||
|
||||
@Column(name = "SAML_ID")
|
||||
private String samlId;
|
||||
|
||||
@Column(name = "HUB_UUID")
|
||||
private String hubUuid;
|
||||
|
||||
@Column(name = "STATUS")
|
||||
private String status;
|
||||
|
||||
@Column(name = "TOKEN")
|
||||
private String token;
|
||||
|
||||
|
||||
@@ -65,4 +65,8 @@ public class UserEntity extends BaseEntity {
|
||||
@OneToOne
|
||||
@JoinColumn(name = "BENEFICIARY_ID")
|
||||
private BeneficiaryEntity beneficiary;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "HUB_ID")
|
||||
private HubEntity hub;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ public enum ApplicationStatusTypeEnum {
|
||||
|
||||
DRAFT("DRAFT"),
|
||||
SUBMIT("SUBMIT"),
|
||||
DISCARD("DISCARD");
|
||||
AWAITING("AWAITING"),
|
||||
READY("READY"),
|
||||
DISCARD("DISCARD"),
|
||||
EVALUATION("EVALUATION");
|
||||
|
||||
private String value;
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package net.gepafin.tendermanagement.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum AssignedApplicationEnum {
|
||||
ASSIGNED("ASSIGNED"),
|
||||
APPROVED("APPROVED"),
|
||||
REJECTED("REJECTED");
|
||||
|
||||
|
||||
private final String value;
|
||||
|
||||
AssignedApplicationEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.gepafin.tendermanagement.enums;
|
||||
|
||||
public enum DocOtherSourceTypeEnum {
|
||||
USER_SIGNED_DOCUMENT("USER_SIGNED_DOCUMENT"),
|
||||
USER_DELEGATION("USER_DELEGATION"),
|
||||
TEMPLATE("TEMPLATE");
|
||||
|
||||
private String value;
|
||||
|
||||
DocOtherSourceTypeEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package net.gepafin.tendermanagement.enums;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum SamlResponseStatusEnum {
|
||||
|
||||
SUCCESS("SUCCESS"),
|
||||
FAILED("FAILED"),
|
||||
INITIATED("INITIATED");
|
||||
|
||||
private String value;
|
||||
|
||||
SamlResponseStatusEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
|
||||
|
||||
@Data
|
||||
public class AssignedApplicationsRequest {
|
||||
private String note;
|
||||
private AssignedApplicationEnum status;
|
||||
}
|
||||
@@ -13,6 +13,8 @@ public class ContentRequestBean {
|
||||
private String label;
|
||||
private List<SettingRequestBean> settings;
|
||||
private Map<String,Object> validators;
|
||||
private List<Long> criteria;
|
||||
private String dynamicData;
|
||||
private Integer dbId;
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class HubReq {
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
private String companyName;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String email;
|
||||
|
||||
private String city;
|
||||
|
||||
private String country;
|
||||
|
||||
private String vatNumber;
|
||||
|
||||
private String domainName;
|
||||
|
||||
private Map<String, Object> appConfig;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private String uniqueUuid;
|
||||
}
|
||||
@@ -5,4 +5,5 @@ import lombok.Data;
|
||||
@Data
|
||||
public class InitiatePasswordResetReq {
|
||||
private String email;
|
||||
private String hubUuid;
|
||||
}
|
||||
|
||||
@@ -14,5 +14,6 @@ public class LoginReq {
|
||||
private String email;
|
||||
@NotEmpty
|
||||
private String password;
|
||||
private String hubUuid;
|
||||
private Boolean rememberMe;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,6 @@ public class ResetPasswordReq {
|
||||
private String token;
|
||||
private String newPassword;
|
||||
private String confirmPassword;
|
||||
|
||||
private String hubUuid;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.gepafin.tendermanagement.model.request;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Data
|
||||
public class S3ConfigReq {
|
||||
@NotNull
|
||||
private String path;
|
||||
|
||||
@NotNull
|
||||
private String type;
|
||||
|
||||
@NotNull
|
||||
private String bucketName;
|
||||
|
||||
@NotNull
|
||||
private String parentFolder;
|
||||
}
|
||||
@@ -39,4 +39,8 @@ public class UserReq {
|
||||
private Boolean thirdParty;
|
||||
|
||||
private String emailPec;
|
||||
|
||||
private String hubUuid;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.enums.AssignedApplicationEnum;
|
||||
import net.gepafin.tendermanagement.model.BaseBean;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class AssignedApplicationsResponse extends BaseBean {
|
||||
private Long applicationId;
|
||||
private Long userId;
|
||||
private Long assignedBy;
|
||||
private AssignedApplicationEnum status;
|
||||
private String note;
|
||||
private LocalDateTime assignedAt;
|
||||
private Long protocolNumber;
|
||||
private String callName;
|
||||
private String beneficiaryName;
|
||||
private LocalDateTime submissionDate;
|
||||
private LocalDateTime callStartDate;
|
||||
private LocalDateTime callEndDate;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ public class CallDetailsResponseBean {
|
||||
|
||||
private List<LocalDateTime> dates;
|
||||
|
||||
private Boolean confidi;
|
||||
|
||||
private CallStatusEnum status;
|
||||
|
||||
private Long regionId;
|
||||
|
||||
@@ -5,8 +5,10 @@ import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import lombok.Data;
|
||||
import net.gepafin.tendermanagement.enums.CallStatusEnum;
|
||||
import net.gepafin.tendermanagement.util.DynamicLocalTimeSerializer;
|
||||
|
||||
@Data
|
||||
public class CallResponse {
|
||||
@@ -47,8 +49,10 @@ public class CallResponse {
|
||||
|
||||
private String phoneNumber;
|
||||
|
||||
@JsonSerialize(using = DynamicLocalTimeSerializer.class)
|
||||
private LocalTime startTime;
|
||||
|
||||
@JsonSerialize(using = DynamicLocalTimeSerializer.class)
|
||||
private LocalTime endTime;
|
||||
|
||||
private LocalDateTime createdDate;
|
||||
|
||||
@@ -13,5 +13,7 @@ public class ContentResponseBean {
|
||||
private String label;
|
||||
private List<SettingResponseBean> settings;
|
||||
private Map<String,Object> validators;
|
||||
private List<Long> criteria;
|
||||
private String dynamicData;
|
||||
private Integer dbId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import net.gepafin.tendermanagement.model.BaseBean;
|
||||
|
||||
import java.util.Map;
|
||||
@Getter
|
||||
@Setter
|
||||
public class HubResponseBean extends BaseBean {
|
||||
|
||||
private String companyName;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String email;
|
||||
|
||||
private String city;
|
||||
|
||||
private String country;
|
||||
|
||||
private String vatNumber;
|
||||
|
||||
private String appConfig;
|
||||
|
||||
private String domainName;
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private String uniqueUuid;
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package net.gepafin.tendermanagement.model.response;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class S3ConfigBean {
|
||||
private String path;
|
||||
private String type;
|
||||
private String bucketName;
|
||||
private String parentFolder;
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* Copyright (c) 2017 The JNanoID Authors
|
||||
* Copyright (c) 2017 Aventrix LLC
|
||||
* Copyright (c) 2017 Andrey Sitnik
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
package net.gepafin.tendermanagement.model.util;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
|
||||
|
||||
public final class NanoIdUtils {
|
||||
|
||||
/**
|
||||
* <code>NanoIdUtils</code> instances should NOT be constructed in standard programming.
|
||||
* Instead, the class should be used as <code>NanoIdUtils.randomNanoId();</code>.
|
||||
*/
|
||||
private NanoIdUtils() {
|
||||
//Do Nothing
|
||||
}
|
||||
|
||||
/**
|
||||
* The default random number generator used by this class.
|
||||
* Creates cryptographically strong NanoId Strings.
|
||||
*/
|
||||
public static final SecureRandom DEFAULT_NUMBER_GENERATOR = new SecureRandom();
|
||||
|
||||
/**
|
||||
* The default alphabet used by this class.
|
||||
* Creates url-friendly NanoId Strings using 64 unique symbols.
|
||||
*/
|
||||
public static final char[] DEFAULT_ALPHABET =
|
||||
"_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
|
||||
|
||||
/**
|
||||
* The default size used by this class.
|
||||
* Creates NanoId Strings with slightly more unique values than UUID v4.
|
||||
*/
|
||||
public static final int DEFAULT_SIZE = 21;
|
||||
|
||||
/**
|
||||
* Static factory to retrieve a url-friendly, pseudo randomly generated, NanoId String.
|
||||
*
|
||||
* The generated NanoId String will have 21 symbols.
|
||||
*
|
||||
* The NanoId String is generated using a cryptographically strong pseudo random number
|
||||
* generator.
|
||||
*
|
||||
* @return A randomly generated NanoId String.
|
||||
*/
|
||||
public static String randomNanoId() {
|
||||
return randomNanoId(DEFAULT_NUMBER_GENERATOR, DEFAULT_ALPHABET, DEFAULT_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Static factory to retrieve a NanoId String.
|
||||
*
|
||||
* The string is generated using the given random number generator.
|
||||
*
|
||||
* @param random The random number generator.
|
||||
* @param alphabet The symbols used in the NanoId String.
|
||||
* @param size The number of symbols in the NanoId String.
|
||||
* @return A randomly generated NanoId String.
|
||||
*/
|
||||
public static String randomNanoId(final Random random, final char[] alphabet, final int size) {
|
||||
|
||||
if (random == null) {
|
||||
throw new IllegalArgumentException("random cannot be null.");
|
||||
}
|
||||
|
||||
if (alphabet == null) {
|
||||
throw new IllegalArgumentException("alphabet cannot be null.");
|
||||
}
|
||||
|
||||
if (alphabet.length == 0 || alphabet.length >= 256) {
|
||||
throw new IllegalArgumentException("alphabet must contain between 1 and 255 symbols.");
|
||||
}
|
||||
|
||||
if (size <= 0) {
|
||||
throw new IllegalArgumentException("size must be greater than zero.");
|
||||
}
|
||||
|
||||
double value = (double) (alphabet.length - 1);
|
||||
|
||||
final int mask = (2 << (int) Math.floor(Math.log(value) / Math.log(2))) - 1;
|
||||
final int step = (int) Math.ceil(1.6 * mask * size / alphabet.length);
|
||||
|
||||
final StringBuilder idBuilder = new StringBuilder();
|
||||
|
||||
while (true) {
|
||||
|
||||
final byte[] bytes = new byte[step];
|
||||
random.nextBytes(bytes);
|
||||
|
||||
for (int i = 0; i < step; i++) {
|
||||
|
||||
final int alphabetIndex = bytes[i] & mask;
|
||||
|
||||
if (alphabetIndex < alphabet.length) {
|
||||
idBuilder.append(alphabet[alphabetIndex]);
|
||||
if (idBuilder.length() == size) {
|
||||
return idBuilder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -32,13 +32,14 @@ public interface ApplicationRepository extends JpaRepository<ApplicationEntity,
|
||||
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.userId = :userId AND a.company.id = :companyId AND a.status = 'SUBMIT' ")
|
||||
Long countSubmittedApplicationsByUserId(@Param("userId") Long userId, @Param("companyId") Long companyId);
|
||||
|
||||
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'SUBMIT'")
|
||||
Long countSubmittedApplications();
|
||||
|
||||
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'DRAFT'")
|
||||
Long countDraftApplications();
|
||||
|
||||
List<ApplicationEntity> findByCompanyIdAndUserIdAndIsDeletedFalse(Long companyId,Long userId);
|
||||
|
||||
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'SUBMIT' And a.hubId = :hubId")
|
||||
public Long countSubmittedApplicationsByHubId(@Param("hubId") Long hubId);
|
||||
|
||||
@Query("SELECT COUNT(a) FROM ApplicationEntity a WHERE a.status = 'DRAFT' And a.hubId = :hubId")
|
||||
public Long countDraftApplicationsByHubId(@Param("hubId") Long hubId);
|
||||
|
||||
@Query("SELECT a.call.id FROM ApplicationEntity a WHERE a.id = :id")
|
||||
Long findCallIdById(@Param("id") Long id);
|
||||
}
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.ApplicationSignedDocumentEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface ApplicationSignedDocumentRepository extends JpaRepository<ApplicationSignedDocumentEntity, Long> {
|
||||
|
||||
ApplicationSignedDocumentEntity findByApplicationIdAndStatus(Long applicationId, String status);
|
||||
|
||||
Long findApplicationIdById(Long id);
|
||||
|
||||
@Query("SELECT a.id FROM ApplicationSignedDocumentEntity d JOIN d.application a WHERE d.id = :id")
|
||||
List<Long> findApplicationIdIdsById(@Param("id") Long id);
|
||||
|
||||
@Query("SELECT d FROM ApplicationSignedDocumentEntity d WHERE d.status = :status")
|
||||
List<ApplicationSignedDocumentEntity> findAllByIsStatus(@Param("status")String status);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
import net.gepafin.tendermanagement.entities.AssignedApplicationsEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AssignedApplicationsRepository extends JpaRepository<AssignedApplicationsEntity,Long>, JpaSpecificationExecutor<AssignedApplicationsEntity>{
|
||||
Optional<AssignedApplicationsEntity> findByApplicationIdAndIsDeletedFalse(Long applicationId);
|
||||
Optional<AssignedApplicationsEntity> findByIdAndIsDeletedFalse(Long id);
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
import net.gepafin.tendermanagement.entities.CallEntity;
|
||||
import net.gepafin.tendermanagement.enums.CallStatusEnum;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
@@ -11,15 +11,16 @@ import java.util.List;
|
||||
@Repository
|
||||
public interface CallRepository extends JpaRepository<CallEntity, Long> {
|
||||
|
||||
public CallEntity findByIdAndStatusNotIn(Long id, List<String> status);
|
||||
List<CallEntity> findByStatusIn(List<String> callStatus);
|
||||
// public CallEntity findByIdAndStatusNotIn(Long id, List<String> status);
|
||||
|
||||
// List<CallEntity> findByStatusIn(List<String> callStatus);
|
||||
|
||||
public CallEntity findByIdAndStatus(Long id,String status);
|
||||
// public CallEntity findByIdAndStatus(Long id,String status);
|
||||
|
||||
public Long countByStatus(String status);
|
||||
// public Long countByStatus(String status);
|
||||
|
||||
@Query("SELECT COALESCE(SUM(c.amount), 0) FROM CallEntity c WHERE c.status = 'PUBLISH'")
|
||||
BigDecimal findTotalAmountOfPublishedCalls();
|
||||
// @Query("SELECT COALESCE(SUM(c.amount), 0) FROM CallEntity c WHERE c.status = 'PUBLISH'")
|
||||
// BigDecimal findTotalAmountOfPublishedCalls();
|
||||
|
||||
@Query("SELECT c.name, COUNT(a.id) " +
|
||||
"FROM CallEntity c LEFT JOIN ApplicationEntity a ON c.id = a.call.id " +
|
||||
@@ -29,4 +30,19 @@ public interface CallRepository extends JpaRepository<CallEntity, Long> {
|
||||
|
||||
@Query("SELECT c FROM CallEntity c JOIN ApplicationEntity a ON c.id = a.call.id WHERE a.id = :applicationId")
|
||||
CallEntity findCallEntityByApplicationId(Long applicationId);
|
||||
// @Query("SELECT c.name, COUNT(a.id) " +
|
||||
// "FROM CallEntity c LEFT JOIN ApplicationEntity a ON c.id = a.call.id " +
|
||||
// "GROUP BY c.name")
|
||||
// List<Object[]> findApplicationsPerCall();
|
||||
|
||||
public List<CallEntity> findByStatusInAndHubId(List<String> callStatus, Long hubId);
|
||||
|
||||
public CallEntity findByIdAndStatusAndHubId(Long id, String status, Long hubId);
|
||||
|
||||
public Long countByStatusAndHubId(String status, Long hubId);
|
||||
|
||||
public CallEntity findByIdAndStatusNotInAndHubId(Long id, List<String> status, Long hubId);
|
||||
|
||||
@Query("SELECT COALESCE(SUM(c.amount), 0) FROM CallEntity c WHERE c.status = 'PUBLISH' And c.hub.id = :hubId")
|
||||
BigDecimal findTotalAmountOfPublishedCallsAndHubId(@Param("hubId") Long hubId);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
@@ -11,13 +12,14 @@ import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
@Repository
|
||||
public interface CompanyRepository extends JpaRepository<CompanyEntity, Long> {
|
||||
|
||||
List<CompanyEntity> findByIdIn(List<Long> companyIds);
|
||||
List<CompanyEntity> findByIdInAndHubId(List<Long> companyIds, Long hubId);
|
||||
|
||||
Boolean existsByVatNumber(String vatNumber);
|
||||
CompanyEntity findByVatNumber(String vatNumber);
|
||||
Boolean existsByVatNumberAndHubId(String vatNumber, Long hubId);
|
||||
|
||||
@Query("SELECT COUNT(c) FROM CompanyEntity c")
|
||||
long countTotalCompanies();
|
||||
@Query("SELECT COUNT(c) FROM CompanyEntity c where c.hub.id = :hubId")
|
||||
long countTotalCompaniesByHubId(@Param("hubId") Long hubId);
|
||||
|
||||
CompanyEntity findByVatNumberAndHubId(String vatNumber, Long hubId);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.CriteriaFormFieldEntity;
|
||||
|
||||
@Repository
|
||||
public interface CriteriaFormFieldRepository extends JpaRepository<CriteriaFormFieldEntity, Long>{
|
||||
|
||||
List<CriteriaFormFieldEntity> findByCallIdAndFormIdAndFormFieldIdAndIsDeletedFalse(Long callId, Long formId, String formFieldId);
|
||||
|
||||
List<CriteriaFormFieldEntity> findByEvaluationCriteriaIdAndIsDeletedFalse(Long evaluationCriteriaId);
|
||||
|
||||
}
|
||||
@@ -15,12 +15,17 @@ public interface DocumentRepository extends JpaRepository<DocumentEntity, Long>
|
||||
@Query("SELECT d FROM DocumentEntity d WHERE d.id = :id AND d.isDeleted = false")
|
||||
Optional<DocumentEntity> findById(@Param("id") Long id);
|
||||
|
||||
List<DocumentEntity> findBySourceIdAndTypeAndIsDeletedFalse(Long sourceId, String type);
|
||||
// List<DocumentEntity> findBySourceIdAndTypeAndIsDeletedFalse(Long sourceId, String type);
|
||||
|
||||
Optional<DocumentEntity> findByIdAndSourceIdAndIsDeletedFalse(Long id, Long sourceId);
|
||||
// Optional<DocumentEntity> findByIdAndSourceIdAndIsDeletedFalse(Long id, Long sourceId);
|
||||
|
||||
List<DocumentEntity> findBySource(String source);
|
||||
|
||||
List<DocumentEntity> findBySourceIdAndSourceAndTypeAndIsDeletedFalse(Long sourceId, String source, String type);
|
||||
|
||||
Optional<DocumentEntity> findByIdAndSourceIdAndSourceAndIsDeletedFalse(Long id, Long sourceId, String source);
|
||||
|
||||
@Query("SELECT d FROM DocumentEntity d WHERE d.isDeleted = false")
|
||||
List<DocumentEntity> findAllByIsDeleteFalse();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface HubRepository extends JpaRepository<HubEntity, Long> {
|
||||
|
||||
Optional<HubEntity> findByUniqueUuid(String hubUuid);
|
||||
|
||||
}
|
||||
@@ -1,9 +1,19 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface LoginAttemptRepository extends JpaRepository<LoginAttemptEntity,Long> {
|
||||
|
||||
@Query("SELECT la FROM LoginAttemptEntity la LEFT JOIN UserEntity u ON u.email = la.username WHERE u.hub.id = :hubId")
|
||||
Page<LoginAttemptEntity> findByHubId(@Param("hubId") Long hubId, PageRequest pageRequest);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@ package net.gepafin.tendermanagement.repositories;
|
||||
import net.gepafin.tendermanagement.entities.ProtocolEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public interface ProtocolRepository extends JpaRepository<ProtocolEntity,Long> {
|
||||
|
||||
@Query("SELECT MAX(p.protocolNumber) FROM ProtocolEntity p")
|
||||
Integer findMaxProtocolNumber();
|
||||
@Query("SELECT MAX(p.protocolNumber) FROM ProtocolEntity p where p.hubId = :hubId")
|
||||
Long findMaxProtocolNumberAndHubId(@Param("hubId") Long hubId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.S3ConfigEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocOtherSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface S3ConfigRepository extends JpaRepository<S3ConfigEntity, Long> {
|
||||
Optional<S3ConfigEntity> getPathByType(String type);
|
||||
|
||||
S3ConfigEntity findS3PathConfigurationById(Long id);
|
||||
|
||||
String getBucketNameByType(DocumentSourceTypeEnum type);
|
||||
|
||||
String getBucketNameByType(DocOtherSourceTypeEnum type);
|
||||
|
||||
@Query("Select s3.parentFolder From S3ConfigEntity s3 Where s3.type = :s")
|
||||
String getPathByTypeOther(String s);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@@ -10,4 +12,6 @@ public interface SamlResponseRepository extends JpaRepository<SamlResponseEntity
|
||||
|
||||
SamlResponseEntity findByToken(String token);
|
||||
|
||||
Optional<SamlResponseEntity> findByInResponseToAndStatus(String inResponseTo, String status);
|
||||
|
||||
}
|
||||
|
||||
@@ -2,9 +2,15 @@ package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import net.gepafin.tendermanagement.entities.UserCompanyDelegationEntity;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface UserCompanyDelegationRepository extends JpaRepository<UserCompanyDelegationEntity, Long> {
|
||||
|
||||
UserCompanyDelegationEntity findByUserIdAndCompanyIdAndStatus(Long userId, Long companyId, String status);
|
||||
|
||||
@Query("SELECT d FROM UserCompanyDelegationEntity d where d.status = :status")
|
||||
List<UserCompanyDelegationEntity> findAllByStatus(@Param("status") String status);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package net.gepafin.tendermanagement.repositories;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.model.response.UserResponseBean;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@@ -11,17 +10,19 @@ import java.util.Optional;
|
||||
@Repository
|
||||
public interface UserRepository extends JpaRepository<UserEntity, Long> {
|
||||
|
||||
Optional<UserEntity> findByEmailIgnoreCase(String email);
|
||||
|
||||
boolean existsByEmailIgnoreCase(String email);
|
||||
|
||||
UserEntity findByEmail(String email);
|
||||
|
||||
Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale);
|
||||
|
||||
boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale);
|
||||
UserEntity findByBeneficiaryId(Long beneficiaryId);
|
||||
|
||||
Long countByStatusAndRoleEntity_RoleType(String status, String roleName);
|
||||
List<UserEntity> findByRoleEntityId(Long roleId);
|
||||
Optional<UserEntity> findByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
|
||||
|
||||
boolean existsByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubUuid);
|
||||
|
||||
List<UserEntity> findByRoleEntityIdAndHubId(Long roleId, Long hubId);
|
||||
|
||||
List<UserEntity> findByHubId(Long hubId);
|
||||
|
||||
Long countByStatusAndRoleEntityRoleTypeAndHubId(String status, String roleName, Long hubId);
|
||||
|
||||
Optional<UserEntity> findByBeneficiaryCodiceFiscaleAndHubId(String codiceFiscale, Long hubId);
|
||||
|
||||
boolean existsByBeneficiaryCodiceFiscaleAndHubId(String codiceFiscale, Long hubId);
|
||||
}
|
||||
|
||||
@@ -14,10 +14,8 @@ public interface UserWithCompanyRepository extends JpaRepository<UserWithCompany
|
||||
|
||||
void deleteByCompanyIdAndIsDeletedFalse(Long companyId);
|
||||
|
||||
@Query("SELECT u.companyId FROM UserWithCompanyEntity u WHERE u.userId = :userId AND u.isDeleted = false")
|
||||
List<Long> findActiveCompanyIdsByUserId(@Param("userId") Long userId);
|
||||
|
||||
|
||||
@Query("SELECT u.companyId FROM UserWithCompanyEntity u WHERE u.userId = :userId AND u.isDeleted = false")
|
||||
List<Long> findActiveCompanyIdsByUserId(@Param("userId") Long userId);
|
||||
|
||||
Optional<UserWithCompanyEntity> findByUserIdAndCompanyIdAndIsDeletedFalse(Long userId, Long companyId);
|
||||
|
||||
|
||||
@@ -11,11 +11,10 @@ import java.io.InputStream;
|
||||
@Component
|
||||
public interface AmazonS3Service {
|
||||
|
||||
public String upload(String fileName, String s3Folder, MultipartFile file) throws IOException;
|
||||
|
||||
public Boolean delete(String s3Folder, String fileName);
|
||||
|
||||
UploadFileOnAmazonS3Response uploadFileOnAmazonS3(String s3Folder, MultipartFile file);
|
||||
|
||||
Boolean delete(String s3Folder, String filePath);
|
||||
|
||||
InputStream getFile(String s3Folder, String filePath) throws IOException;
|
||||
|
||||
public UploadFileOnAmazonS3Response uploadFileOnAmazonS3(String s3Folder, MultipartFile file);
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public interface ApplicationService {
|
||||
|
||||
ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId);
|
||||
|
||||
List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId, Long companyId);
|
||||
List<ApplicationResponse> getAllApplications(HttpServletRequest request,Long callId, Long companyId,String status);
|
||||
|
||||
void deleteApplication(HttpServletRequest request, Long applicationId);
|
||||
|
||||
@@ -40,4 +40,6 @@ public interface ApplicationService {
|
||||
|
||||
public void deleteSignedDocument(HttpServletRequest request, Long applicationId);
|
||||
|
||||
public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.gepafin.tendermanagement.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface AssignedApplicationsService {
|
||||
|
||||
AssignedApplicationsResponse createAssignedApplications(
|
||||
HttpServletRequest request, Long applicationId, Long userId, AssignedApplicationsRequest assignedApplicationsRequest);
|
||||
|
||||
void deleteApplication(HttpServletRequest request, Long id);
|
||||
|
||||
List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId);
|
||||
AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, AssignedApplicationsRequest assignedApplicationsRequest);
|
||||
AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id);
|
||||
}
|
||||
@@ -19,18 +19,16 @@ public interface CallService {
|
||||
|
||||
CallResponse updateCallStep1(HttpServletRequest request, Long callId, UpdateCallRequestStep1 updateCallRequest);
|
||||
|
||||
CallResponse getCallById (Long callId);
|
||||
CallResponse getCallById (HttpServletRequest request, Long callId);
|
||||
|
||||
List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request);
|
||||
|
||||
CallResponse validateCallData(Long callId);
|
||||
|
||||
CallEntity getCallEntityById(Long id);
|
||||
CallResponse validateCallData(HttpServletRequest request, Long callId);
|
||||
|
||||
CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq);
|
||||
|
||||
CallEntity validateCall(Long callId);
|
||||
|
||||
CallEntity validatePublishedCall(Long callId);
|
||||
byte[] downloadCallDocumentsAsZip(Long callId);
|
||||
CallEntity validatePublishedCall(Long callId, Long hubId);
|
||||
byte[] downloadCallDocumentsAsZip(HttpServletRequest request, Long callId);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package net.gepafin.tendermanagement.service;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
|
||||
import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest;
|
||||
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
|
||||
|
||||
@@ -13,4 +14,6 @@ public interface EvaluationCriteriaService {
|
||||
public EvaluationCriteriaResponseBean updateEvaluationCriteria(HttpServletRequest request,Long id, EvaluationCriteriaRequest evaluationCriteriaRequest);
|
||||
|
||||
public void deleteEvaluationCriteria(HttpServletRequest request,Long id);
|
||||
|
||||
public EvaluationCriteriaEntity validateEvaluationCriteria(Long id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package net.gepafin.tendermanagement.service;
|
||||
|
||||
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
import net.gepafin.tendermanagement.model.request.HubReq;
|
||||
import net.gepafin.tendermanagement.model.response.HubResponseBean;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface HubService {
|
||||
HubResponseBean createHub(HubReq hubReq);
|
||||
HubResponseBean updateHub(Long hubId, HubReq hubReq);
|
||||
HubResponseBean getHubById(Long hubId);
|
||||
List<HubResponseBean> getAllHubs();
|
||||
void deleteHub(Long hubId);
|
||||
HubEntity getHubByUuid(String hubUuid);
|
||||
HubResponseBean getHubByHubUuid(String uuid);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import java.util.List;
|
||||
|
||||
public interface LoginAttemptService {
|
||||
|
||||
LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(Integer pageNo, Integer pageLimit);
|
||||
LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(HttpServletRequest request, Integer pageNo, Integer pageLimit);
|
||||
|
||||
void createLoginAttempt(LoginAttemptReq loginAttemptReq, HttpServletRequest request);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.gepafin.tendermanagement.service;
|
||||
|
||||
import net.gepafin.tendermanagement.entities.S3ConfigEntity;
|
||||
import net.gepafin.tendermanagement.model.request.S3ConfigReq;
|
||||
import net.gepafin.tendermanagement.model.response.S3ConfigBean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
public interface S3ConfigService {
|
||||
S3ConfigBean addS3Path(S3ConfigReq s3Path);
|
||||
|
||||
Optional<S3ConfigEntity> getS3PathByType(String type);
|
||||
|
||||
S3ConfigEntity deleteS3PathById(Long id);
|
||||
|
||||
S3ConfigBean updateS3PathConfiguration(S3ConfigReq s3PathConfigurationReq, Long id);
|
||||
}
|
||||
@@ -17,11 +17,11 @@ import java.util.List;
|
||||
public interface UserService {
|
||||
JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq);
|
||||
|
||||
UserResponseBean updateUser(Long userId, UpdateUserReq userReq);
|
||||
UserResponseBean updateUser(HttpServletRequest request, Long userId, UpdateUserReq userReq);
|
||||
|
||||
UserResponseBean getUserById(Long userId);
|
||||
UserResponseBean getUserById(HttpServletRequest request, Long userId);
|
||||
|
||||
void deleteUser(Long userId);
|
||||
void deleteUser(HttpServletRequest request, Long userId);
|
||||
|
||||
JWTToken login(LoginReq loginReq,HttpServletRequest request);
|
||||
|
||||
@@ -31,7 +31,7 @@ public interface UserService {
|
||||
|
||||
Boolean resetPassword(ResetPasswordReq resetPasswordReq);
|
||||
|
||||
Boolean changePassword(ChangePasswordRequest request);
|
||||
Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request);
|
||||
|
||||
void logoutUser(HttpServletRequest request, HttpServletResponse response);
|
||||
|
||||
@@ -45,6 +45,6 @@ public interface UserService {
|
||||
UserEntity getUserByBeneficiaryId(Long beneficiaryId);
|
||||
|
||||
public UserEntity getUserEntityById(Long userId);
|
||||
List<UserResponseBean> getAllUsers(Long roleId);
|
||||
List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId);
|
||||
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationExceptio
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
|
||||
import org.apache.commons.io.FilenameUtils;
|
||||
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.core.env.Environment;
|
||||
@@ -28,6 +30,8 @@ import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class AmazonS3ServiceImpl implements AmazonS3Service {
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(AmazonS3ServiceImpl.class);
|
||||
|
||||
@Autowired
|
||||
private AmazonS3 amazonS3;
|
||||
@@ -42,11 +46,9 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
|
||||
private String s3Url;
|
||||
|
||||
|
||||
@Override
|
||||
public String upload(String fileName, String s3Folder,
|
||||
private String upload(String fileName, String s3Folder,
|
||||
MultipartFile file) throws IOException {
|
||||
|
||||
// String path = bucketName+"/"+s3Folder;
|
||||
String path = s3Folder +"/"+fileName;
|
||||
|
||||
InputStream inputStream = file.getInputStream();
|
||||
@@ -66,17 +68,23 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
|
||||
if(Boolean.FALSE.equals(isTestProfileActivated())) {
|
||||
amazonS3.putObject(bucketName, path, inputStream, objectMetadata);
|
||||
}
|
||||
return s3Url + s3Folder +"/"+ fileName;
|
||||
path =s3Url + s3Folder +"/"+ fileName;
|
||||
log.info("File '{}' uploaded successfully to Amazon S3 with URL: {}", fileName, path);
|
||||
return path;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean delete(String s3Folder, String fileName) {
|
||||
public Boolean delete(String s3Folder, String filePath) {
|
||||
|
||||
String fileName = Utils.extractFileName(filePath);
|
||||
String path = s3Folder +"/"+fileName;
|
||||
final DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(bucketName, path);
|
||||
if(Boolean.FALSE.equals(isTestProfileActivated())) {
|
||||
amazonS3.deleteObject(deleteObjectRequest);
|
||||
}
|
||||
log.info("File '{}' deleted successfully from Amazon S3", fileName);
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
public Boolean isTestProfileActivated() {
|
||||
@@ -85,28 +93,34 @@ public class AmazonS3ServiceImpl implements AmazonS3Service {
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getFile(String s3Folder, String filePath) throws IOException {
|
||||
public InputStream getFile(String s3Folder, String filePath) {
|
||||
try {
|
||||
String path = s3Folder +"/"+filePath;
|
||||
String fileName = Utils.extractFileName(filePath);
|
||||
String path = s3Folder + "/" + fileName;
|
||||
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, path);
|
||||
S3Object s3Object = amazonS3.getObject(getObjectRequest);
|
||||
log.info("File fetched successfully from Amazon S3: {}", fileName);
|
||||
return s3Object.getObjectContent();
|
||||
} catch (AmazonS3Exception e) {
|
||||
throw new IOException("Error getting file from Amazon S3", e);
|
||||
log.error("Error occurred while getting file from Amazon S3: {}", e);
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.GET_ERROR_S3));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public UploadFileOnAmazonS3Response uploadFileOnAmazonS3(String s3Folder, MultipartFile file) {
|
||||
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
|
||||
String fileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
|
||||
String firstNameContain = fileName.substring(0, fileName.lastIndexOf('.'));
|
||||
firstNameContain+=Utils.randomKey(5);
|
||||
fileName = (firstNameContain + "." + extension);
|
||||
String originalFileName = org.springframework.util.StringUtils.cleanPath(file.getOriginalFilename());
|
||||
String firstNameContain = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
|
||||
firstNameContain = Utils.replaceSpacesWithUnderscores(firstNameContain);
|
||||
firstNameContain += "_" + Utils.randomKey(7);
|
||||
String fileName = (firstNameContain + "." + extension);
|
||||
try {
|
||||
String filepath = upload(fileName, s3Folder, file);
|
||||
return UploadFileOnAmazonS3Response.builder().fileName(fileName).filePath(filepath).build();
|
||||
return UploadFileOnAmazonS3Response.builder().fileName(originalFileName).filePath(filepath).build();
|
||||
} catch (Exception e) {
|
||||
log.error("Error occurred while uploading file from Amazon S3: {}", e);
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.UPLOAD_ERROR_S3));
|
||||
}
|
||||
|
||||
@@ -40,21 +40,19 @@ public class ApplicationServiceImpl implements ApplicationService {
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ApplicationResponseBean createApplication(HttpServletRequest request,
|
||||
ApplicationRequestBean applicationRequestBean, Long applicationId, Long formId) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
return applicationDao.createApplication(applicationRequestBean, userEntity, formId, applicationId);
|
||||
return applicationDao.createApplication(request, applicationRequestBean, formId, applicationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
return applicationDao.getApplicationByFormId(applicationId,formId,userEntity);
|
||||
return applicationDao.getApplicationByFormId(request, applicationId,formId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteApplication(HttpServletRequest request, Long applicationId) {
|
||||
applicationDao.deleteById(applicationId);
|
||||
applicationDao.deleteById(request, applicationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -67,6 +65,7 @@ public class ApplicationServiceImpl implements ApplicationService {
|
||||
public ApplicationResponse createApplication(HttpServletRequest request, Long companyId, ApplicationRequest applicationRequest, Long callId) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
CompanyEntity companyEntity = validator.validateUserWithCompany(request, companyId);
|
||||
validator.validateUserWithCall(userEntity, callId);
|
||||
return applicationDao.createApplicationByCallId(companyEntity, applicationRequest, callId, userEntity);
|
||||
}
|
||||
|
||||
@@ -74,25 +73,25 @@ public class ApplicationServiceImpl implements ApplicationService {
|
||||
public NextOrPreviousFormResponse getNextOrPreviousForm(HttpServletRequest request, Long applicationId, Long formId,
|
||||
FormActionEnum action) {
|
||||
ApplicationEntity applicationEntity = validateApplication(applicationId);
|
||||
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
|
||||
return flowFormDao.getNextOrPreviousForm(applicationEntity, formId, action);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
return applicationDao.updateApplicationStatus(userEntity, applicationId, status);
|
||||
return applicationDao.updateApplicationStatus(request, applicationId, status);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<ApplicationResponse> getAllApplications(HttpServletRequest request, Long callId, Long companyId) {
|
||||
public List<ApplicationResponse> getAllApplications(HttpServletRequest request, Long callId, Long companyId , String status) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
if (companyId != null) {
|
||||
validator.validateUserWithCompany(request, companyId);
|
||||
}
|
||||
return applicationDao.getAllApplications(userEntity, callId, companyId);
|
||||
return applicationDao.getAllApplications(userEntity, callId, companyId , status);
|
||||
}
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
@@ -111,5 +110,12 @@ public class ApplicationServiceImpl implements ApplicationService {
|
||||
public void deleteSignedDocument(HttpServletRequest request, Long applicationId) {
|
||||
applicationDao.deleteSignedDocument(request, applicationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ApplicationResponse validateApplication(HttpServletRequest request, Long applicationId) {
|
||||
return applicationDao.validateApplication(request, applicationId);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.AssignedApplicationsDao;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.model.request.AssignedApplicationsRequest;
|
||||
import net.gepafin.tendermanagement.model.response.AssignedApplicationsResponse;
|
||||
import net.gepafin.tendermanagement.service.AssignedApplicationsService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class AssignedApplicationsServiceImpl implements AssignedApplicationsService {
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Autowired
|
||||
private AssignedApplicationsDao assignedApplicationsDao;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AssignedApplicationsResponse createAssignedApplications(HttpServletRequest request, Long applicationId, Long userId, AssignedApplicationsRequest assignedApplicationsRequest) {
|
||||
UserEntity assignedByUser= validator.validateUser(request);
|
||||
validator.validatePreInstructor(request, userId);
|
||||
return assignedApplicationsDao.createAssignedApplications(applicationId,userId,assignedByUser, assignedApplicationsRequest);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteApplication(HttpServletRequest request, Long id) {
|
||||
assignedApplicationsDao.deleteById(request, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<AssignedApplicationsResponse> getAllAssignedApplications(HttpServletRequest request, Long userId) {
|
||||
return assignedApplicationsDao.getAllAssignedApplications(request, userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AssignedApplicationsResponse updateAssignedApplication(HttpServletRequest request, Long id, AssignedApplicationsRequest updatedAssignedApplicationRequest) {
|
||||
return assignedApplicationsDao.updateAssignedApplication(request, id, updatedAssignedApplicationRequest);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public AssignedApplicationsResponse getAssignedApplicationById(HttpServletRequest request, Long id) {
|
||||
return assignedApplicationsDao.getAssignedApplicationById(request, id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.dao.CompanyDao;
|
||||
import net.gepafin.tendermanagement.dao.LoginAttemptDao;
|
||||
import net.gepafin.tendermanagement.dao.RoleDao;
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
|
||||
import net.gepafin.tendermanagement.entities.SamlResponseEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
@@ -22,6 +23,7 @@ import net.gepafin.tendermanagement.model.response.UserSamlResponse;
|
||||
import net.gepafin.tendermanagement.model.util.JWTToken;
|
||||
import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.service.HubService;
|
||||
import net.gepafin.tendermanagement.util.DateTimeUtil;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
|
||||
@@ -63,6 +65,9 @@ public class AuthenticationService {
|
||||
|
||||
@Autowired
|
||||
private LoginAttemptDao loginAttemptDao;
|
||||
|
||||
@Autowired
|
||||
private HubService hubService;
|
||||
|
||||
@Autowired
|
||||
public AuthenticationService(TokenProvider tokenProvider, AuthenticationManager authenticationManager) {
|
||||
@@ -70,17 +75,18 @@ public class AuthenticationService {
|
||||
this.authenticationManager = authenticationManager;
|
||||
}
|
||||
|
||||
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
|
||||
public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
|
||||
UserEntity user=null;
|
||||
|
||||
|
||||
LoginAttemptEntity loginAttemptEntity = prepareLoginAttemptEntity(loginReq, request);
|
||||
log.info("Attempting login for email: {}", loginReq.getEmail());
|
||||
String emailWithHubId = loginReq.getEmail()+":"+loginReq.getHubUuid();
|
||||
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
|
||||
loginReq.getEmail(), loginReq.getPassword());
|
||||
emailWithHubId, loginReq.getPassword());
|
||||
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
log.info("Authentication successful for email: {}", loginReq.getEmail());
|
||||
user = userRepository.findByEmailIgnoreCase(loginReq.getEmail())
|
||||
user = userRepository.findByEmailIgnoreCaseAndHubUniqueUuid(loginReq.getEmail(), loginReq.getHubUuid())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
loginAttemptEntity.setUserId(user.getId());
|
||||
@@ -185,10 +191,11 @@ public class AuthenticationService {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
|
||||
}
|
||||
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
|
||||
Map<String, List<Object>> userAttributes = Utils
|
||||
.convertStringIntoMap(samlResponseLogEntity.getAuthenticationObject());
|
||||
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
|
||||
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscale(cf)
|
||||
UserEntity userEntity = userRepository.findByBeneficiaryCodiceFiscaleAndHubId(cf, hub.getId())
|
||||
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
|
||||
//samlResponseLogRepository.delete(samlResponseLogEntity);
|
||||
@@ -204,10 +211,11 @@ public class AuthenticationService {
|
||||
throw new CustomValidationException(Status.VALIDATION_ERROR,
|
||||
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
|
||||
}
|
||||
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
|
||||
Map<String, List<Object>> userAttributes = Utils
|
||||
.convertStringIntoMap(samlResponseLogEntity.getAuthenticationObject());
|
||||
String cf = userAttributes.get("CodiceFiscale").get(0).toString();
|
||||
if (userRepository.existsByBeneficiaryCodiceFiscale(cf)) {
|
||||
if (userRepository.existsByBeneficiaryCodiceFiscaleAndHubId(cf, hub.getId())) {
|
||||
throw new ResourceNotFoundException(Status.NOT_FOUND,
|
||||
Translator.toLocale(GepafinConstant.USER_ALREADY_EXIST_MSG));
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import net.gepafin.tendermanagement.enums.BeneficiaryCallStatus;
|
||||
import net.gepafin.tendermanagement.model.request.BeneficiaryPreferredCallReq;
|
||||
|
||||
import net.gepafin.tendermanagement.model.response.BeneficiaryPreferredCallResponseBean;
|
||||
import net.gepafin.tendermanagement.repositories.UserRepository;
|
||||
import net.gepafin.tendermanagement.service.BeneficiaryPreferredCallService;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
@@ -17,7 +16,6 @@ import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationExceptio
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -26,10 +24,10 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
|
||||
|
||||
@Autowired
|
||||
private BeneficiaryPreferredCallDao beneficiaryPreferredCallDao;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@@ -37,22 +35,22 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
|
||||
@Override
|
||||
public BeneficiaryPreferredCallResponseBean createBeneficiaryPreferredCall(HttpServletRequest request, BeneficiaryPreferredCallReq beneficiaryPreferredCallRequest) {
|
||||
UserEntity userEntity = validator.validateUser(request);
|
||||
return beneficiaryPreferredCallDao.createBeneficiaryPreferredCall(beneficiaryPreferredCallRequest,userEntity);
|
||||
return beneficiaryPreferredCallDao.createBeneficiaryPreferredCall(request, beneficiaryPreferredCallRequest,userEntity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BeneficiaryPreferredCallResponseBean getBeneficiaryPreferredCallById(HttpServletRequest request, Long id) {
|
||||
return beneficiaryPreferredCallDao.getBeneficiaryPreferredCallById(id);
|
||||
return beneficiaryPreferredCallDao.getBeneficiaryPreferredCallById(request, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteBeneficiaryPreferredCall(HttpServletRequest request, Long id) {
|
||||
beneficiaryPreferredCallDao.deleteBeneficiaryPreferredCallById(id);
|
||||
beneficiaryPreferredCallDao.deleteBeneficiaryPreferredCallById(request, id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BeneficiaryPreferredCallResponseBean> getAllBeneficiaryPreferredCalls(HttpServletRequest request) {
|
||||
return beneficiaryPreferredCallDao.getAllBeneficiaryPreferredCalls();
|
||||
return beneficiaryPreferredCallDao.getAllBeneficiaryPreferredCalls(request);
|
||||
}
|
||||
|
||||
// @Override
|
||||
@@ -68,6 +66,7 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
|
||||
@Override
|
||||
public List<BeneficiaryPreferredCallResponseBean> getBeneficiaryPreferredCallByUserId(HttpServletRequest request,Long userId,Long beneficiaryId,Long companyId) {
|
||||
UserEntity userEntity =validateGetBeneficiaryPreferredCallrequest(request,userId,beneficiaryId);
|
||||
validator.validateUserId(request, userEntity.getId());
|
||||
return beneficiaryPreferredCallDao.getBeneficiaryPreferredCallByUserId(userEntity,companyId);
|
||||
}
|
||||
|
||||
@@ -81,7 +80,7 @@ public class BeneficiaryPreferredCallServiceImpl implements BeneficiaryPreferred
|
||||
}
|
||||
if(beneficiaryId!=null){
|
||||
UserEntity user = userService.getUserByBeneficiaryId(beneficiaryId);
|
||||
return validator.validateUserId(request,user.getId());
|
||||
return validator.validateUserId(request, user.getId());
|
||||
}
|
||||
else{
|
||||
return validator.validateUserId(request, userId);
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
|
||||
import net.gepafin.tendermanagement.dao.CallDao;
|
||||
import net.gepafin.tendermanagement.entities.CallEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
@@ -12,12 +11,13 @@ import net.gepafin.tendermanagement.model.request.UpdateCallRequestStep1;
|
||||
import net.gepafin.tendermanagement.model.response.CallDetailsResponseBean;
|
||||
import net.gepafin.tendermanagement.model.response.CallResponse;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
@Service
|
||||
@@ -27,59 +27,61 @@ public class CallServiceImpl implements CallService {
|
||||
private CallDao callDao;
|
||||
|
||||
@Autowired
|
||||
private TokenProvider tokenProvider;
|
||||
private Validator validator;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CallResponse createCallStep1(HttpServletRequest request, CreateCallRequestStep1 createCallRequest) {
|
||||
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
return callDao.createCallStep1(createCallRequest, Long.parseLong(userInfo.get("userId").toString()));
|
||||
UserEntity user = validator.validateUser(request);
|
||||
return callDao.createCallStep1(createCallRequest, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CallResponse createCallStep2(HttpServletRequest request, Long callId, CreateCallRequestStep2 createCallRequest) {
|
||||
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
return callDao.createCallStep2(callId, createCallRequest, Long.parseLong(userInfo.get("userId").toString()));
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return callDao.createCallStep2(call, createCallRequest, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CallResponse updateCallStep1(HttpServletRequest request, Long callId,
|
||||
UpdateCallRequestStep1 updateCallRequest) {
|
||||
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
return callDao.updateCallStep1(callId, updateCallRequest, Long.parseLong(userInfo.get("userId").toString()));
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return callDao.updateCallStep1(call, updateCallRequest, user);
|
||||
}
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public CallResponse getCallById(Long callId) {
|
||||
return callDao.getCallById(callId);
|
||||
public CallResponse getCallById(HttpServletRequest request, Long callId) {
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return callDao.getCallById(call);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request) {
|
||||
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
UserEntity user=tokenProvider.validateUser(userInfo);
|
||||
UserEntity user = validator.validateUser(request);
|
||||
return callDao.getAllCalls(user);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CallResponse validateCallData(Long callId) {
|
||||
return callDao.validateCallData(callDao.validateCall(callId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CallEntity getCallEntityById(Long id){
|
||||
return callDao.getCallEntityById(id);
|
||||
public CallResponse validateCallData(HttpServletRequest request, Long callId) {
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return callDao.validateCallData(call);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq) {
|
||||
return callDao.updateCallStatus(callId, statusReq);
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return callDao.updateCallStatus(call, statusReq);
|
||||
|
||||
}
|
||||
|
||||
@@ -88,13 +90,17 @@ public class CallServiceImpl implements CallService {
|
||||
return callDao.validateCall(callId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CallEntity validatePublishedCall(Long callId) {
|
||||
return callDao.validatePublishedCall(callId);
|
||||
}
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public byte[] downloadCallDocumentsAsZip(Long callId) {
|
||||
return callDao.downloadCallDocumentsAsZip(callId);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public CallEntity validatePublishedCall(Long callId, Long hubId) {
|
||||
return callDao.validatePublishedCall(callId, hubId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public byte[] downloadCallDocumentsAsZip(HttpServletRequest request, Long callId) {
|
||||
UserEntity user = validator.validateUser(request);
|
||||
validator.validateUserWithCall(user, callId);
|
||||
return callDao.downloadCallDocumentsAsZip(callId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ public class CompanyServiceImpl implements CompanyService {
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public CompanyResponse updateCompany(HttpServletRequest request, Long companyId, CompanyRequest companyRequest) {
|
||||
UserEntity userEntity =validator.validateUser(request);
|
||||
validator.validateUserWithCompany(request, companyId);
|
||||
return companyDao.updateCompany(userEntity, companyId, companyRequest);
|
||||
}
|
||||
|
||||
@@ -56,6 +57,7 @@ public class CompanyServiceImpl implements CompanyService {
|
||||
@Transactional(readOnly = true)
|
||||
public CompanyResponse getCompany(HttpServletRequest request, Long companyId) {
|
||||
UserEntity userEntity =validator.validateUser(request);
|
||||
validator.validateUserWithCompany(request, companyId);
|
||||
return companyDao.getCompany(userEntity, companyId);
|
||||
}
|
||||
|
||||
@@ -63,13 +65,14 @@ public class CompanyServiceImpl implements CompanyService {
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteCompany(HttpServletRequest request, Long companyId) {
|
||||
UserEntity userEntity =validator.validateUser(request);
|
||||
validator.validateUserWithCompany(request, companyId);
|
||||
companyDao.deleteCompany(userEntity, companyId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<CompanyResponse> getCompanyByUserId(HttpServletRequest request, Long userId) {
|
||||
validator.validateUser(request);
|
||||
validator.validateUserId(request, userId);
|
||||
return companyDao.getCompanyByUserId(userId);
|
||||
}
|
||||
|
||||
@@ -91,8 +94,7 @@ public class CompanyServiceImpl implements CompanyService {
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ByteArrayOutputStream downloadCompanyDelegation(HttpServletRequest request, Long companyId, CompanyDelegationRequest companyDelegationRequest) {
|
||||
UserEntity userEntity =validator.validateUser(request);
|
||||
return delegationDao.downloadCompanyDelegation(userEntity, companyId, companyDelegationRequest);
|
||||
return delegationDao.downloadCompanyDelegation(request, companyId, companyDelegationRequest);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -22,7 +22,8 @@ public class DashboardServiceImpl implements DashboardService {
|
||||
|
||||
@Override
|
||||
public SuperAdminWidgetResponseBean getDashboardWidgetForSuperAdmin(HttpServletRequest request) {
|
||||
return dashboardDao.getDashboardWidget();
|
||||
UserEntity userEntity=validator.validateUser(request);
|
||||
return dashboardDao.getDashboardWidget(userEntity);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -34,7 +34,7 @@ public class DocumentServiceImpl implements DocumentService {
|
||||
|
||||
@Override
|
||||
public DocumentResponseBean updateDocument(HttpServletRequest httpServletRequest, Long documentId, MultipartFile file, DocumentTypeEnum documentTypeEnum) {
|
||||
return documentDao.updateDocument(documentId,file,documentTypeEnum);
|
||||
return documentDao.updateDocument(documentId, file,documentTypeEnum);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.EvaluationCriteriaDao;
|
||||
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
|
||||
import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest;
|
||||
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
|
||||
import net.gepafin.tendermanagement.service.EvaluationCriteriaService;
|
||||
@@ -33,4 +34,9 @@ public class EvaluationCriteriaServiceImpl implements EvaluationCriteriaService
|
||||
public void deleteEvaluationCriteria(HttpServletRequest request,Long id) {
|
||||
evaluationCriteriaDao.deleteEvaluationCriteria(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public EvaluationCriteriaEntity validateEvaluationCriteria(Long id) {
|
||||
return evaluationCriteriaDao.validateEvaluationCriteria(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ import net.gepafin.tendermanagement.dao.FlowDao;
|
||||
import net.gepafin.tendermanagement.model.request.FlowRequestBean;
|
||||
import net.gepafin.tendermanagement.model.response.FlowResponseBean;
|
||||
import net.gepafin.tendermanagement.service.FlowService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -14,16 +16,21 @@ public class FlowServiceImpl implements FlowService {
|
||||
|
||||
@Autowired
|
||||
private FlowDao flowDao;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public FlowResponseBean createOrUpdateFlow(HttpServletRequest httpServletRequest, FlowRequestBean flowRequestBean, Long callId) {
|
||||
validator.validateUserWithCall(validator.validateUser(httpServletRequest), callId);
|
||||
return flowDao.createOrUpdateFlow(flowRequestBean,callId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@org.springframework.transaction.annotation.Transactional(readOnly = true)
|
||||
public FlowResponseBean getFlowByCallId(HttpServletRequest request, Long callId) {
|
||||
validator.validateUserWithCall(validator.validateUser(request), callId);
|
||||
return flowDao.getFlowByCallId(callId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,15 @@ package net.gepafin.tendermanagement.service.impl;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.FormDao;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationEntity;
|
||||
import net.gepafin.tendermanagement.entities.CallEntity;
|
||||
import net.gepafin.tendermanagement.entities.FormEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBean;
|
||||
import net.gepafin.tendermanagement.model.request.FormRequest;
|
||||
import net.gepafin.tendermanagement.model.response.FormResponseBean;
|
||||
import net.gepafin.tendermanagement.service.FormService;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -19,26 +22,33 @@ public class FormServiceImpl implements FormService {
|
||||
|
||||
@Autowired
|
||||
private FormDao formDao;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Override
|
||||
public FormResponseBean createForm(HttpServletRequest request,Long callId, FormRequest formRequest) {
|
||||
return formDao.createForm(callId,formRequest);
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return formDao.createForm(call,formRequest);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FormResponseBean updateForm(HttpServletRequest request, Long formId, FormRequest formRequest,Boolean forceDeleteFlow) {
|
||||
return formDao.updateForm(formId,formRequest,forceDeleteFlow);
|
||||
UserEntity user = validator.validateUser(request);
|
||||
return formDao.updateForm(user, formId,formRequest,forceDeleteFlow);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FormResponseBean getFormById(HttpServletRequest request, Long formId) {
|
||||
return formDao.getFormEntityById(formId);
|
||||
UserEntity user = validator.validateUser(request);
|
||||
return formDao.getFormEntityById(user, formId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteForm(HttpServletRequest request, Long formId) {
|
||||
formDao.deleteFormById(formId);
|
||||
return;
|
||||
UserEntity user = validator.validateUser(request);
|
||||
formDao.deleteFormById(user, formId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -48,7 +58,9 @@ public class FormServiceImpl implements FormService {
|
||||
|
||||
@Override
|
||||
public List<FormResponseBean> getFormsByCallId(HttpServletRequest request, Long callId) {
|
||||
return formDao.getFormsByCallId(callId);
|
||||
UserEntity user = validator.validateUser(request);
|
||||
CallEntity call = validator.validateUserWithCall(user, callId);
|
||||
return formDao.getFormsByCallId(call);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import net.gepafin.tendermanagement.dao.HubDao;
|
||||
import net.gepafin.tendermanagement.entities.HubEntity;
|
||||
import net.gepafin.tendermanagement.model.request.HubReq;
|
||||
import net.gepafin.tendermanagement.model.response.HubResponseBean;
|
||||
import net.gepafin.tendermanagement.service.HubService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class HubServiceImpl implements HubService {
|
||||
|
||||
@Autowired
|
||||
private HubDao hubDao;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public HubResponseBean createHub(HubReq hubReq) {
|
||||
return hubDao.createHub(hubReq);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public HubResponseBean updateHub(Long hubId, HubReq hubReq) {
|
||||
return hubDao.updateHub(hubId, hubReq);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public HubResponseBean getHubById(Long hubId) {
|
||||
return hubDao.getHubById(hubId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<HubResponseBean> getAllHubs() {
|
||||
return hubDao.getAllHubs();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteHub(Long hubId) {
|
||||
hubDao.deleteHub(hubId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HubEntity getHubByUuid(String hubUuid) {
|
||||
return hubDao.getHubByUuid(hubUuid);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HubResponseBean getHubByHubUuid(String uuid) {
|
||||
return hubDao.getHubByHubUuid(uuid);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,15 @@ package net.gepafin.tendermanagement.service.impl;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.dao.LoginAttemptDao;
|
||||
import net.gepafin.tendermanagement.entities.LoginAttemptEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.LoginAttemptResultEnum;
|
||||
import net.gepafin.tendermanagement.enums.LoginAttemptTypeEnum;
|
||||
import net.gepafin.tendermanagement.model.request.LoginAttemptReq;
|
||||
import net.gepafin.tendermanagement.model.response.LoginAttemptPageableResponseBean;
|
||||
import net.gepafin.tendermanagement.service.LoginAttemptService;
|
||||
import net.gepafin.tendermanagement.util.Utils;
|
||||
import net.gepafin.tendermanagement.util.Validator;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -19,22 +22,30 @@ public class LoginAttemptServiceImpl implements LoginAttemptService {
|
||||
|
||||
@Autowired
|
||||
LoginAttemptDao loginAttemptDao;
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Override
|
||||
public LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(Integer pageNo, Integer pageLimit) {
|
||||
return loginAttemptDao.getLoginAttemptsList(pageNo, pageLimit);
|
||||
public LoginAttemptPageableResponseBean<List<LoginAttemptEntity>> getLoginAttemptsList(HttpServletRequest request, Integer pageNo, Integer pageLimit) {
|
||||
return loginAttemptDao.getLoginAttemptsList(validator.validateUser(request), pageNo, pageLimit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createLoginAttempt(LoginAttemptReq loginAttemptReq, HttpServletRequest request) {
|
||||
String ipAddress = Utils.getClientIpAddress(request);
|
||||
String userAgent = request.getHeader("user-agent");
|
||||
|
||||
LoginAttemptEntity loginAttemptEntity = new LoginAttemptEntity();
|
||||
loginAttemptEntity.setType(LoginAttemptTypeEnum.SWITCH.getValue());
|
||||
loginAttemptEntity.setIpAddress(ipAddress);
|
||||
loginAttemptEntity.setUserAgent(userAgent);
|
||||
loginAttemptEntity.setUsername(loginAttemptReq.getUserName());
|
||||
loginAttemptEntity.setResult(LoginAttemptResultEnum.SUCCESS.getValue());
|
||||
if(loginAttemptReq.getUserId() != null) {
|
||||
UserEntity userEntity = validator.validateUserId(request, loginAttemptReq.getUserId());
|
||||
loginAttemptEntity.setUserId(userEntity.getId());
|
||||
}
|
||||
loginAttemptDao.createLoginAttempt(loginAttemptEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
import net.gepafin.tendermanagement.dao.S3ConfigDao;
|
||||
import net.gepafin.tendermanagement.entities.S3ConfigEntity;
|
||||
import net.gepafin.tendermanagement.model.request.S3ConfigReq;
|
||||
import net.gepafin.tendermanagement.model.response.S3ConfigBean;
|
||||
import net.gepafin.tendermanagement.service.S3ConfigService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class S3ConfigServiceImpl implements S3ConfigService {
|
||||
@Autowired
|
||||
S3ConfigDao s3ConfigDao;
|
||||
|
||||
@Override
|
||||
public S3ConfigBean addS3Path(S3ConfigReq s3Path) {
|
||||
|
||||
return s3ConfigDao.addS3Path(s3Path);
|
||||
}
|
||||
@Override
|
||||
public Optional<S3ConfigEntity> getS3PathByType(String type) {
|
||||
|
||||
return s3ConfigDao.getS3PathByType(type);
|
||||
}
|
||||
@Override
|
||||
@Transactional
|
||||
public S3ConfigEntity deleteS3PathById(Long id) {
|
||||
|
||||
return s3ConfigDao.deleteS3PathConfigById(id);
|
||||
}
|
||||
@Override
|
||||
@Transactional
|
||||
public S3ConfigBean updateS3PathConfiguration(S3ConfigReq s3PathConfigurationReq, Long id) {
|
||||
|
||||
return s3ConfigDao.updateS3PathConfiguration(s3PathConfigurationReq, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import com.amazonaws.AmazonServiceException;
|
||||
import com.amazonaws.SdkClientException;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.amazonaws.services.s3.model.GetObjectRequest;
|
||||
import com.amazonaws.services.s3.model.ObjectMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.dao.S3PathConfig;
|
||||
import net.gepafin.tendermanagement.entities.DocumentEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationSignedDocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.DocumentRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class S3ReUploadMigrationService {
|
||||
|
||||
private static final String OLD_BUCKET = "mementoresources";
|
||||
|
||||
private static final String SECURE_KEY = "267163962963";
|
||||
|
||||
@Autowired
|
||||
private DocumentRepository documentRepository;
|
||||
|
||||
@Autowired
|
||||
private AmazonS3Client s3Client;
|
||||
|
||||
@Autowired
|
||||
private S3PathConfig s3ConfigBean;
|
||||
|
||||
@Autowired
|
||||
private ApplicationRepository applicationRepository;
|
||||
|
||||
@Autowired
|
||||
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
|
||||
|
||||
@Autowired
|
||||
private AmazonS3 amazonS3;
|
||||
|
||||
@Value("${aws.s3.url}")
|
||||
private String s3Url;
|
||||
|
||||
private boolean migrationCompleted = false;
|
||||
|
||||
public String reUploadAndMigrateDocuments(String providedKey) {
|
||||
|
||||
if (migrationCompleted) {
|
||||
return "Migration already completed.";
|
||||
}
|
||||
|
||||
// Validate the provided key
|
||||
if (!isValidKey(providedKey)) {
|
||||
return "Invalid or missing migration key.";
|
||||
}
|
||||
|
||||
List<DocumentEntity> documents = documentRepository.findAllByIsDeleteFalse();
|
||||
|
||||
if (documents.isEmpty()) {
|
||||
return "No documents found to migrate.";
|
||||
}
|
||||
|
||||
for (DocumentEntity document : documents) {
|
||||
String oldUrl = document.getFilePath(); // This should contain the full URL
|
||||
log.info("Processing {}", oldUrl);
|
||||
|
||||
try {
|
||||
File localFile = downloadFileFromS3(oldUrl);
|
||||
String newKey = generateNewS3Path(document); // Make sure this generates the correct new path
|
||||
String uploadedPath = uploadFileToNewBucket(localFile, newKey);
|
||||
updateDocumentPathAndDeleteOldEntry(document, uploadedPath);
|
||||
} catch (Exception e) {
|
||||
log.error("Error processing document {}: {}", document.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
return "Migrated Successfully.";
|
||||
}
|
||||
|
||||
private boolean isValidKey(String providedKey) {
|
||||
|
||||
return providedKey != null && providedKey.equals(SECURE_KEY);
|
||||
}
|
||||
|
||||
private File downloadFileFromS3(String fileUrl) throws Exception {
|
||||
|
||||
String key = extractS3KeyFromUrl(fileUrl); // Get the S3 key from the URL
|
||||
File localFile = new File("/tmp/" + extractFileName(key)); // Save file locally
|
||||
|
||||
GetObjectRequest getObjectRequest = new GetObjectRequest(OLD_BUCKET, key); // Use the key
|
||||
|
||||
try (InputStream s3Stream = s3Client.getObject(getObjectRequest).getObjectContent(); FileOutputStream outputStream = new FileOutputStream(localFile)) {
|
||||
s3Stream.transferTo(outputStream);
|
||||
}
|
||||
|
||||
log.info("Downloaded file from old S3 bucket: {}", key);
|
||||
return localFile;
|
||||
}
|
||||
|
||||
private String extractS3KeyFromUrl(String url) {
|
||||
// Assuming the URL structure is consistent
|
||||
return url.replace("https://mementoresources.s3.eu-west-1.amazonaws.com/", "");
|
||||
}
|
||||
|
||||
private String uploadFileToNewBucket(File localFile, String s3Folder) {
|
||||
|
||||
InputStream inputStream = null; // Declare the InputStream here for cleanup
|
||||
try {
|
||||
// Extract file name from the local file
|
||||
String fileName = extractFileName(localFile.getAbsolutePath()); // Get the file name
|
||||
String path = s3Folder + "/" + fileName; // Construct the S3 path
|
||||
|
||||
// Create InputStream from the local file
|
||||
inputStream = new FileInputStream(localFile);
|
||||
|
||||
// Set up object metadata
|
||||
ObjectMetadata objectMetadata = new ObjectMetadata();
|
||||
objectMetadata.setContentType("application/octet-stream");
|
||||
objectMetadata.setContentLength(localFile.length());
|
||||
|
||||
// Upload to S3
|
||||
s3Client.putObject(OLD_BUCKET, path, inputStream, objectMetadata);
|
||||
|
||||
// Construct the full S3 URL
|
||||
String fullUrl = String.format("https://%s.s3.%s.amazonaws.com/%s", OLD_BUCKET, "eu-west-1", path);
|
||||
log.info("File '{}' uploaded successfully to Amazon S3 with URL: {}", fileName, fullUrl);
|
||||
return fullUrl;
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("IOException occurred during file upload for '{}': {}", localFile.getName(), e.getMessage());
|
||||
throw new RuntimeException("Upload failed for: " + s3Folder + "/" + localFile.getName(), e);
|
||||
} catch (AmazonServiceException e) {
|
||||
log.error("Amazon service exception while uploading file '{}': {}", localFile.getName(), e.getMessage());
|
||||
throw new RuntimeException("Upload failed for: " + s3Folder + "/" + localFile.getName(), e);
|
||||
} catch (SdkClientException e) {
|
||||
log.error("SDK client exception while uploading file '{}': {}", localFile.getName(), e.getMessage());
|
||||
throw new RuntimeException("Upload failed for: " + s3Folder + "/" + localFile.getName(), e);
|
||||
} finally {
|
||||
// Close InputStream if it was opened
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to close InputStream for file '{}': {}", localFile.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String generateNewS3Path(DocumentEntity document) {
|
||||
|
||||
DocumentSourceTypeEnum sourceType = DocumentSourceTypeEnum.valueOf(document.getSource());
|
||||
Long callId;
|
||||
|
||||
if (sourceType.equals(DocumentSourceTypeEnum.CALL)) {
|
||||
return s3ConfigBean.generateDocumentPath(sourceType, document.getSourceId(), 0L);
|
||||
} else {
|
||||
callId = applicationRepository.findCallIdById(document.getSourceId());
|
||||
return s3ConfigBean.generateDocumentPath(sourceType, callId, document.getSourceId());
|
||||
}
|
||||
}
|
||||
|
||||
private String extractFileName(String filePath) {
|
||||
|
||||
String[] parts = filePath.split("/");
|
||||
return parts[parts.length - 1];
|
||||
}
|
||||
|
||||
|
||||
private void updateDocumentPathAndDeleteOldEntry(DocumentEntity document, String newPath) {
|
||||
|
||||
String fileName = extractFileName(newPath);
|
||||
DocumentEntity newDocument = new DocumentEntity();
|
||||
newDocument.setFilePath(newPath);
|
||||
newDocument.setSource(document.getSource());
|
||||
newDocument.setType(document.getType());
|
||||
newDocument.setIsDeleted(false);
|
||||
newDocument.setSourceId(document.getSourceId());
|
||||
newDocument.setFileName(fileName);
|
||||
|
||||
documentRepository.save(newDocument);
|
||||
documentRepository.delete(document);
|
||||
|
||||
log.info("Migrated document ID: {} to new path: {}", document.getId(), newPath);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,11 @@ package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
|
||||
import net.gepafin.tendermanagement.dao.UserDao;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.model.request.LoginReq;
|
||||
import net.gepafin.tendermanagement.model.request.UpdateUserReq;
|
||||
import net.gepafin.tendermanagement.model.request.UserReq;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.enums.UserStatusEnum;
|
||||
import net.gepafin.tendermanagement.model.request.*;
|
||||
import net.gepafin.tendermanagement.model.response.UserSamlResponse;
|
||||
@@ -32,42 +30,37 @@ public class UserServiceImpl implements UserService {
|
||||
|
||||
@Autowired
|
||||
private Validator validator;
|
||||
|
||||
@Autowired
|
||||
private SamlSuccessHandler samlSuccessHandler;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
|
||||
if (tempToken == null) {
|
||||
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
|
||||
}else {
|
||||
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale());
|
||||
}
|
||||
return userDao.createUser(request, tempToken, userReq);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public UserResponseBean updateUser(Long userId, UpdateUserReq userReq) {
|
||||
public UserResponseBean updateUser(HttpServletRequest request, Long userId, UpdateUserReq userReq) {
|
||||
validator.validateUserId(request, userId);
|
||||
return userDao.updateUser(userId, userReq);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public UserResponseBean getUserById(Long userId) {
|
||||
public UserResponseBean getUserById(HttpServletRequest request, Long userId) {
|
||||
validator.validateUserId(request, userId);
|
||||
return userDao.getUserById(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteUser(Long userId) {
|
||||
public void deleteUser(HttpServletRequest request, Long userId) {
|
||||
validator.validateUserId(request, userId);
|
||||
userDao.deleteUser(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
|
||||
public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
|
||||
return userDao.login(loginReq,request);
|
||||
|
||||
}
|
||||
@@ -87,8 +80,8 @@ public class UserServiceImpl implements UserService {
|
||||
return userDao.resetPassword(resetPasswordReq);
|
||||
}
|
||||
@Override
|
||||
public Boolean changePassword(ChangePasswordRequest request){
|
||||
return userDao.changePassword(request);
|
||||
public Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request){
|
||||
return userDao.changePassword(validator.validateUser(httpServletRequest), request);
|
||||
}
|
||||
@Override
|
||||
public void logoutUser(HttpServletRequest request, HttpServletResponse response) {
|
||||
@@ -127,8 +120,8 @@ public class UserServiceImpl implements UserService {
|
||||
}
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserResponseBean> getAllUsers(Long roleId) {
|
||||
// Calling DAO Function
|
||||
return userDao.getAllUsers(roleId);
|
||||
public List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId) {
|
||||
UserEntity user=validator.validateUser(request);
|
||||
return userDao.getAllUsers(user, roleId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package net.gepafin.tendermanagement.service.impl;
|
||||
|
||||
import com.amazonaws.AmazonServiceException;
|
||||
import com.amazonaws.SdkClientException;
|
||||
import com.amazonaws.services.s3.AmazonS3Client;
|
||||
import com.amazonaws.services.s3.model.GetObjectRequest;
|
||||
import com.amazonaws.services.s3.model.ObjectMetadata;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.gepafin.tendermanagement.dao.S3PathConfig;
|
||||
import net.gepafin.tendermanagement.entities.ApplicationSignedDocumentEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserCompanyDelegationEntity;
|
||||
import net.gepafin.tendermanagement.enums.DocOtherSourceTypeEnum;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
|
||||
import net.gepafin.tendermanagement.repositories.ApplicationSignedDocumentRepository;
|
||||
import net.gepafin.tendermanagement.repositories.S3ConfigRepository;
|
||||
import net.gepafin.tendermanagement.repositories.UserCompanyDelegationRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class UserSignedAndDelegationServiceImpl {
|
||||
private static final String OLD_BUCKET = "mementoresources";
|
||||
|
||||
private static final String NEW_BUCKET = "mementoresources";
|
||||
|
||||
private static final String SECURE_KEY = "267163962963";
|
||||
|
||||
@Autowired
|
||||
private UserCompanyDelegationRepository userCompanyDelegationRepository;
|
||||
|
||||
@Autowired
|
||||
private AmazonS3Client s3Client;
|
||||
|
||||
@Autowired
|
||||
private S3PathConfig s3ConfigBean;
|
||||
|
||||
@Autowired
|
||||
private ApplicationSignedDocumentRepository applicationSignedDocumentRepository;
|
||||
|
||||
@Autowired
|
||||
ApplicationRepository applicationRepository;
|
||||
|
||||
@Autowired
|
||||
S3ConfigRepository s3ConfigRepository;
|
||||
|
||||
@Value("${aws.s3.url}")
|
||||
private String s3Url;
|
||||
|
||||
private boolean migrationCompleted = false;
|
||||
|
||||
|
||||
public String migrateUserDelegatedDocuments(String providedKey) {
|
||||
|
||||
if (migrationCompleted) {
|
||||
return "Migration already completed.";
|
||||
}
|
||||
|
||||
// Validate the provided key
|
||||
if (isValidKey(providedKey)) {
|
||||
return "Invalid or missing migration key.";
|
||||
}
|
||||
|
||||
List<UserCompanyDelegationEntity> documents = userCompanyDelegationRepository.findAllByStatus("ACTIVE");
|
||||
|
||||
if (documents.isEmpty()) {
|
||||
return "No documents found to migrate.";
|
||||
}
|
||||
|
||||
for (UserCompanyDelegationEntity document : documents) {
|
||||
String oldUrl = document.getFilePath();
|
||||
log.info("Processing user designated document: {}", oldUrl);
|
||||
|
||||
try {
|
||||
File localFile = downloadFileFromS3(oldUrl);
|
||||
String newKey = generateNewS3PathForDelegationDoc();
|
||||
String uploadedPath = uploadFileToNewBucket(localFile, newKey);
|
||||
updateDelegatedDocumentPathAndDeleteOldEntry(document, uploadedPath);
|
||||
} catch (Exception e) {
|
||||
log.error("Error processing user designated document {}: {}", document.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
return "Migrated";
|
||||
}
|
||||
|
||||
|
||||
public String migrateUserSignedDocuments(String providedKey) {
|
||||
|
||||
if (migrationCompleted) {
|
||||
return "Migration already completed.";
|
||||
}
|
||||
|
||||
// Validate the provided key
|
||||
if (isValidKey(providedKey)) {
|
||||
return "Invalid or missing migration key.";
|
||||
}
|
||||
List<ApplicationSignedDocumentEntity> documents = applicationSignedDocumentRepository.findAllByIsStatus("ACTIVE");
|
||||
|
||||
if (documents.isEmpty()) {
|
||||
return "No documents found to migrate.";
|
||||
}
|
||||
|
||||
for (ApplicationSignedDocumentEntity document : documents) {
|
||||
String oldUrl = document.getFilePath();
|
||||
log.info("Processing user signed document: {}", oldUrl);
|
||||
|
||||
try {
|
||||
File localFile = downloadFileFromS3(oldUrl);
|
||||
String newKey = generateNewS3PathForUserSignedDoc(document);
|
||||
String uploadedPath = uploadFileToNewBucket(localFile, newKey);
|
||||
updateDocumentPathAndDeleteOldEntry(document, uploadedPath);
|
||||
} catch (Exception e) {
|
||||
log.error("Error processing user signed document {}: {}", document.getId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
return "Migrated.";
|
||||
}
|
||||
|
||||
private boolean isValidKey(String providedKey) {
|
||||
|
||||
return providedKey == null || !providedKey.equals(SECURE_KEY);
|
||||
}
|
||||
|
||||
private String generateNewS3PathForDelegationDoc() {
|
||||
|
||||
return s3ConfigBean.generateDocumentPathForOther(DocOtherSourceTypeEnum.USER_DELEGATION, 0L, 0L);
|
||||
}
|
||||
|
||||
private String generateNewS3PathForUserSignedDoc(ApplicationSignedDocumentEntity document) {
|
||||
// Fetch the list of application IDs associated with the document
|
||||
List<Long> applicationIds = applicationSignedDocumentRepository.findApplicationIdIdsById(document.getId());
|
||||
List<String> paths = new ArrayList<>();
|
||||
|
||||
// Loop through the application IDs and generate paths
|
||||
for (Long applicationId : applicationIds) {
|
||||
Long callId = applicationRepository.findCallIdById(applicationId);
|
||||
|
||||
// Construct the path for the current application and call ID
|
||||
String newPath = String.format("%s/call/call_%d/application/application_%d/user_signed_document", s3ConfigRepository.getPathByTypeOther(
|
||||
String.valueOf(DocOtherSourceTypeEnum.USER_SIGNED_DOCUMENT)) , callId, applicationId);
|
||||
|
||||
log.info("Generated new S3 path: {}", newPath);
|
||||
paths.add(newPath);
|
||||
}
|
||||
|
||||
return String.join(",", paths);
|
||||
}
|
||||
|
||||
private File downloadFileFromS3(String fileUrl) throws Exception {
|
||||
|
||||
String key = extractS3KeyFromUrl(fileUrl);
|
||||
File localFile = new File("/tmp/" + extractFileName(key));
|
||||
|
||||
GetObjectRequest getObjectRequest = new GetObjectRequest(OLD_BUCKET, key);
|
||||
|
||||
try (InputStream s3Stream = s3Client.getObject(getObjectRequest).getObjectContent(); FileOutputStream outputStream = new FileOutputStream(localFile)) {
|
||||
s3Stream.transferTo(outputStream);
|
||||
}
|
||||
|
||||
log.info("Downloaded file from old S3 bucket: {}", key);
|
||||
return localFile;
|
||||
}
|
||||
|
||||
private String extractS3KeyFromUrl(String url) {
|
||||
|
||||
return url.replace("https://mementoresources.s3.eu-west-1.amazonaws.com/", "");
|
||||
}
|
||||
|
||||
private String uploadFileToNewBucket(File localFile, String s3Path) {
|
||||
|
||||
InputStream inputStream = null;
|
||||
try {
|
||||
String fileName = extractFileName(localFile.getAbsolutePath()); // Extract file name
|
||||
String fullPath = String.format("%s/%s", s3Path, fileName); // Construct full path
|
||||
|
||||
inputStream = new FileInputStream(localFile); // Create InputStream
|
||||
|
||||
// Set metadata for the file
|
||||
ObjectMetadata objectMetadata = new ObjectMetadata();
|
||||
objectMetadata.setContentLength(localFile.length());
|
||||
objectMetadata.setContentType("application/octet-stream");
|
||||
|
||||
// Upload the file to S3 with the constructed path
|
||||
s3Client.putObject(NEW_BUCKET, fullPath, inputStream, objectMetadata);
|
||||
|
||||
// Construct the full S3 URL for the uploaded file
|
||||
String fullUrl = String.format("https://%s.s3.%s.amazonaws.com/%s", NEW_BUCKET, "eu-west-1", fullPath);
|
||||
log.info("File '{}' uploaded successfully to Amazon S3 with URL: {}", fileName, fullUrl);
|
||||
return fullUrl;
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("IOException occurred during file upload for '{}': {}", localFile.getName(), e.getMessage());
|
||||
throw new RuntimeException("Upload failed for: " + localFile, e);
|
||||
} catch (AmazonServiceException e) {
|
||||
log.error("Amazon service exception while uploading file '{}': {}", localFile.getName(), e.getMessage());
|
||||
throw new RuntimeException("Upload failed for: " + localFile, e);
|
||||
} catch (SdkClientException e) {
|
||||
log.error("SDK client exception while uploading file '{}': {}", localFile.getName(), e.getMessage());
|
||||
throw new RuntimeException("Upload failed for: " + localFile, e);
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to close InputStream for file '{}': {}", localFile.getName(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private String extractFileName(String filePath) {
|
||||
|
||||
String[] parts = filePath.split("/");
|
||||
return parts[parts.length - 1];
|
||||
}
|
||||
private String extractFileNameFromPath(String path) {
|
||||
|
||||
return path.substring(path.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
private void updateDocumentPathAndDeleteOldEntry(ApplicationSignedDocumentEntity document, String newPath) {
|
||||
|
||||
ApplicationSignedDocumentEntity newDocument = new ApplicationSignedDocumentEntity();
|
||||
String fileName = extractFileNameFromPath(newPath);
|
||||
newDocument.setFilePath(newPath);
|
||||
newDocument.setFileName(fileName);
|
||||
newDocument.setApplication(document.getApplication());
|
||||
newDocument.setStatus("ACTIVE");
|
||||
|
||||
applicationSignedDocumentRepository.save(newDocument);
|
||||
applicationSignedDocumentRepository.delete(document);
|
||||
|
||||
log.info("Migrated document ID: {} to new path: {}", document.getId(), newPath);
|
||||
}
|
||||
|
||||
private void updateDelegatedDocumentPathAndDeleteOldEntry(UserCompanyDelegationEntity document, String newPath) {
|
||||
|
||||
String fileName = extractFileNameFromPath(newPath);
|
||||
UserCompanyDelegationEntity newDocument = new UserCompanyDelegationEntity();
|
||||
newDocument.setFilePath(newPath);
|
||||
newDocument.setFileName(fileName);
|
||||
newDocument.setBeneficiaryId(document.getBeneficiaryId());
|
||||
newDocument.setUserId(document.getUserId());
|
||||
newDocument.setCompanyId(document.getCompanyId());
|
||||
newDocument.setStatus("ACTIVE");
|
||||
|
||||
userCompanyDelegationRepository.save(newDocument);
|
||||
userCompanyDelegationRepository.delete(document);
|
||||
|
||||
log.info("Migrated document ID: {} to new path: {}", document.getId(), newPath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.gepafin.tendermanagement.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
public class DynamicLocalTimeSerializer extends JsonSerializer<LocalTime> {
|
||||
private static final DateTimeFormatter HH_MM_FORMAT = DateTimeFormatter.ofPattern("HH:mm");
|
||||
private static final DateTimeFormatter HH_MM_SS_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");
|
||||
|
||||
@Override
|
||||
public void serialize(LocalTime time, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
// Use HH:mm if seconds are 00, otherwise use HH:mm:ss
|
||||
String formattedTime = (time.getSecond() == 0)
|
||||
? time.format(HH_MM_FORMAT)
|
||||
: time.format(HH_MM_SS_FORMAT);
|
||||
|
||||
gen.writeString(formattedTime);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -32,6 +32,8 @@ import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientNotFoundExcep
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientUnauthorizedException;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientValidationException;
|
||||
|
||||
import static org.apache.commons.lang3.StringUtils.isEmpty;
|
||||
|
||||
|
||||
public class Utils {
|
||||
|
||||
@@ -324,7 +326,64 @@ public class Utils {
|
||||
return new ObjectMapper().writeValueAsString(obj);
|
||||
} catch (JsonProcessingException e) {
|
||||
log.error("Failed to convert object to JSON: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("Failed to convert object to JSON", e);
|
||||
throw new RuntimeException("Failed to convert object to JSON", e);}}
|
||||
|
||||
public static String replaceSpacesWithUnderscores(String content) {
|
||||
if (content == null) {
|
||||
return null;
|
||||
}
|
||||
return content.trim().replace(" ", "_");
|
||||
}
|
||||
public static List<Map<String, Object>> convertJsonStringIntoJsonList(String jsonString) {
|
||||
try {
|
||||
if(isEmpty(jsonString))
|
||||
{
|
||||
return new ArrayList<>();
|
||||
}
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
|
||||
return mapper.readValue(jsonString, List.class);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public static String convertToString(Object input) {
|
||||
if (input == null) {
|
||||
return "null"; // Return string "null" for null input
|
||||
}
|
||||
|
||||
if (input instanceof String) {
|
||||
return (String) input; // Return the string directly if input is a string
|
||||
}
|
||||
|
||||
if (input instanceof Collection<?>) {
|
||||
// Handle collections (List, Set, etc.)
|
||||
return convertCollectionToString((Collection<?>) input);
|
||||
}
|
||||
|
||||
if (input instanceof Map<?, ?>) {
|
||||
// Handle maps
|
||||
return convertMapToString((Map<?, ?>) input);
|
||||
}
|
||||
|
||||
// For other types (like Integer, Boolean, etc.), use toString()
|
||||
return input.toString();
|
||||
}
|
||||
|
||||
private static String convertCollectionToString(Collection<?> collection) {
|
||||
try {
|
||||
return mapper.writeValueAsString(collection); // Convert the collection to a JSON string
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Error converting collection to string", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String convertMapToString(Map<?, ?> map) {
|
||||
try {
|
||||
return mapper.writeValueAsString(map); // Convert the map to a JSON string
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException("Error converting map to string", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,11 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import net.gepafin.tendermanagement.config.Translator;
|
||||
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
|
||||
import net.gepafin.tendermanagement.constants.GepafinConstant;
|
||||
import net.gepafin.tendermanagement.entities.CallEntity;
|
||||
import net.gepafin.tendermanagement.entities.CompanyEntity;
|
||||
import net.gepafin.tendermanagement.entities.UserEntity;
|
||||
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
|
||||
import net.gepafin.tendermanagement.service.CallService;
|
||||
import net.gepafin.tendermanagement.service.CompanyService;
|
||||
import net.gepafin.tendermanagement.service.UserService;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
|
||||
@@ -14,11 +16,13 @@ import net.gepafin.tendermanagement.web.rest.api.errors.Status;
|
||||
import net.gepafin.tendermanagement.web.rest.api.errors.UnauthorizedAccessException;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@@ -32,6 +36,12 @@ public class Validator {
|
||||
|
||||
@Autowired
|
||||
private CompanyService companyService;
|
||||
|
||||
@Autowired
|
||||
private CallService callService;
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
public Map<String, Object> getUserInfoFromToken(HttpServletRequest request) {
|
||||
return tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
@@ -54,6 +64,20 @@ public class Validator {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public Boolean checkIsPreInstructor() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication != null && authentication.isAuthenticated()) {
|
||||
// Check if the user has the ROLE_SUPER_ADMIN authority
|
||||
for (GrantedAuthority authority : authentication.getAuthorities()) {
|
||||
if (RoleStatusEnum.ROLE_PRE_INSTRUCTOR.getValue().equals(authority.getAuthority())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void validateRequest(HttpServletRequest request,RoleStatusEnum role) {
|
||||
if (RoleStatusEnum.ROLE_SUPER_ADMIN.equals(role) && Boolean.FALSE.equals(checkIsSuperAdmin())) {
|
||||
@@ -62,13 +86,24 @@ public class Validator {
|
||||
}
|
||||
|
||||
public CompanyEntity validateUserWithCompany(HttpServletRequest request, Long companyId) {
|
||||
CompanyEntity companyEntity = companyService.validateCompany(companyId);
|
||||
validateHubId(request, companyEntity.getHub().getId());
|
||||
if (checkIsSuperAdmin()) {
|
||||
return companyService.validateCompany(companyId);
|
||||
return companyEntity;
|
||||
}
|
||||
Map<String, Object> userInfo = tokenProvider.getUserInfoAndUserIdFromToken(request);
|
||||
companyService.validateUserWithCompny(getUserId(userInfo), companyId);
|
||||
return companyService.validateCompany(companyId);
|
||||
}
|
||||
|
||||
public void validateHubId(HttpServletRequest request, Long hubId) {
|
||||
UserEntity user = validateUser(request);
|
||||
Long hubIdFromHttpRequest = user.getHub().getId();
|
||||
if (Boolean.FALSE.equals(hubIdFromHttpRequest.equals(hubId))) {
|
||||
throw new ForbiddenAccessException(Status.FORBIDDEN,
|
||||
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
}
|
||||
|
||||
private Long getUserId(Map<String, Object> userInfo) {
|
||||
return Long.parseLong(userInfo.get("userId").toString());
|
||||
@@ -89,10 +124,15 @@ public class Validator {
|
||||
|
||||
public UserEntity validateUserId(HttpServletRequest request, Long userId) {
|
||||
UserEntity user = validateUser(request);
|
||||
if(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue()) && Boolean.FALSE.equals(user.getId().equals(userId))) {
|
||||
throw new ForbiddenAccessException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
UserEntity requestedUser = userService.validateUser(userId);
|
||||
|
||||
validateHubId(request, requestedUser.getHub().getId());
|
||||
if (Boolean.FALSE.equals(user.getRoleEntity().getRoleType().equals(RoleStatusEnum.ROLE_SUPER_ADMIN.getValue()))
|
||||
&& Boolean.FALSE.equals(user.getId().equals(userId))) {
|
||||
throw new ForbiddenAccessException(Status.FORBIDDEN,
|
||||
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
return userService.validateUser(userId);
|
||||
return requestedUser;
|
||||
}
|
||||
|
||||
public Long getUserIdFromToken(HttpServletRequest request) {
|
||||
@@ -106,4 +146,33 @@ public class Validator {
|
||||
}
|
||||
return userService.validateUser(userId);
|
||||
}
|
||||
|
||||
public CallEntity validateUserWithCall(UserEntity user, Long callId) {
|
||||
CallEntity callEntity = callService.validateCall(callId);
|
||||
if(Boolean.FALSE.equals(user.getHub().getId().equals(callEntity.getHub().getId()))) {
|
||||
throw new ForbiddenAccessException(Status.FORBIDDEN, Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
return callEntity;
|
||||
}
|
||||
|
||||
public Boolean isProductionProfileActivated() {
|
||||
String[] activeProfiles = environment.getActiveProfiles();
|
||||
return Arrays.stream(activeProfiles).anyMatch("production"::equals);
|
||||
}
|
||||
|
||||
public UserEntity validatePreInstructor(HttpServletRequest request, Long preInstructorUserId) {
|
||||
UserEntity preInstructorUser = userService.validateUser(preInstructorUserId);
|
||||
if (checkIsSuperAdmin()) {
|
||||
if (preInstructorUserId != null) {
|
||||
validateHubId(request, preInstructorUser.getHub().getId());
|
||||
}
|
||||
return preInstructorUser;
|
||||
} else if (checkIsPreInstructor()) {
|
||||
return validateUserId(request, preInstructorUserId);
|
||||
} else {
|
||||
throw new ForbiddenAccessException(Status.FORBIDDEN,
|
||||
Translator.toLocale(GepafinConstant.PERMISSION_DENIED));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user