Merge branch 'develop' of https://github.com/Kitzanos/GEPAFIN-BE into feature/GEPAFINBE-55

This commit is contained in:
Anisha Gokhru
2024-10-21 18:52:36 +05:30
65 changed files with 1603 additions and 297 deletions

View File

@@ -29,6 +29,7 @@ import org.opensaml.xmlsec.signature.support.SignatureConstants;
import org.opensaml.xmlsec.signature.support.Signer; import org.opensaml.xmlsec.signature.support.Signer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; 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.RelyingPartyRegistrationResolver;
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver; import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
import org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver; 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 @Configuration
public class SamlConfig { public class SamlConfig {
@@ -56,6 +64,9 @@ public class SamlConfig {
@Value("${active.profile.folder}") @Value("${active.profile.folder}")
String activeProfileFolder; String activeProfileFolder;
@Autowired
private SamlResponseRepository samlResponseRepository;
@Bean @Bean
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
@@ -123,30 +134,42 @@ public class SamlConfig {
return authnRequest; return authnRequest;
} }
@Bean @Bean
public Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingPartyRegistrationRepository registrations) { public Saml2AuthenticationRequestResolver authenticationRequestResolver(RelyingPartyRegistrationRepository registrations) {
RelyingPartyRegistrationResolver registrationResolver = new DefaultRelyingPartyRegistrationResolver(registrations); RelyingPartyRegistrationResolver registrationResolver = new DefaultRelyingPartyRegistrationResolver(registrations);
OpenSaml4AuthenticationRequestResolver authenticationRequestResolver = new OpenSaml4AuthenticationRequestResolver(registrationResolver); OpenSaml4AuthenticationRequestResolver authenticationRequestResolver = new OpenSaml4AuthenticationRequestResolver(registrationResolver);
authenticationRequestResolver.setAuthnRequestCustomizer((context) -> { 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
// Set Authentication Context HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String hubUuid = (String) request.getAttribute("hubId");
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()); 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 // Log the SAML AuthnRequest after setting context
String samlRequest = SamlRequestLogger.convertSAMLObjectToString(authnRequest); String samlRequest = SamlRequestLogger.convertSAMLObjectToString(authnRequest);
logger.info("SAML AuthnRequest after setting context: " + samlRequest); logger.info("SAML AuthnRequest after setting context: " + samlRequest);
}); });
return authenticationRequestResolver; return authenticationRequestResolver;
} }
private RequestedAuthnContext buildRequestedAuthnContext() {
private RequestedAuthnContext buildRequestedAuthnContext() {
AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder(); AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject( AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(
SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX SAMLConstants.SAML20_NS, AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML20_PREFIX
@@ -160,7 +183,7 @@ private RequestedAuthnContext buildRequestedAuthnContext() {
requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef); requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
return requestedAuthnContext; return requestedAuthnContext;
} }
public PrivateKey readPrivateKey() throws Exception { public PrivateKey readPrivateKey() throws Exception {
// Path to your private key PEM file // Path to your private key PEM file

View File

@@ -1,9 +1,13 @@
package net.gepafin.tendermanagement.config; package net.gepafin.tendermanagement.config;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler; 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.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; 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 @Component
public class SamlFailureHandler implements AuthenticationFailureHandler { public class SamlFailureHandler implements AuthenticationFailureHandler {
@@ -20,16 +30,40 @@ public class SamlFailureHandler implements AuthenticationFailureHandler {
@Value("${fe.base.url}") @Value("${fe.base.url}")
private String feBaseUrl; private String feBaseUrl;
@Autowired
private SamlResponseRepository samlResponseRepository;
@Override @Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException { AuthenticationException exception) throws IOException {
try { try {
logger.error("SAML login failed: " + exception.getMessage()); 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"); response.sendRedirect(feBaseUrl + "/login");
} catch (Exception e) { } catch (Exception e) {
logger.error("Error processing SAML failure handler", 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;
}
}
} }

View File

@@ -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);
}
}

View File

@@ -1,9 +1,14 @@
package net.gepafin.tendermanagement.config; package net.gepafin.tendermanagement.config;
import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; 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.saml2.provider.service.authentication.Saml2Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.HubEntity;
import net.gepafin.tendermanagement.entities.SamlResponseEntity; import net.gepafin.tendermanagement.entities.SamlResponseEntity;
import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.SamlResponseStatusEnum;
import net.gepafin.tendermanagement.repositories.SamlResponseRepository; import net.gepafin.tendermanagement.repositories.SamlResponseRepository;
import net.gepafin.tendermanagement.repositories.UserRepository; import net.gepafin.tendermanagement.repositories.UserRepository;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.util.Utils; import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException; import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status; import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -41,6 +51,9 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
@Value("${fe.base.url}") @Value("${fe.base.url}")
private String feBaseUrl; private String feBaseUrl;
@Autowired
private HubService hubService;
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException { Authentication authentication) throws IOException {
@@ -53,16 +66,47 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
String token = Utils.generateSecureToken(); String token = Utils.generateSecureToken();
logger.info("SAML User Attributes: " + userAttributes); logger.info("SAML User Attributes: " + userAttributes);
SamlResponseEntity samlResponseLogEntity = new SamlResponseEntity(); // Extracting raw SAML response
samlResponseLogEntity.setAuthenticationObject(authentication.toString()); 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
// 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(); ObjectMapper objectMapper = new ObjectMapper();
String userAttributesJson = objectMapper.writeValueAsString(userAttributes); String userAttributesJson = objectMapper.writeValueAsString(userAttributes);
samlResponseLogEntity.setAuthenticationObject(userAttributesJson); samlResponseLogEntity.setAuthenticationObject(userAttributesJson);
samlResponseLogEntity.setToken(token); samlResponseLogEntity.setToken(token);
samlResponseLogEntity.setStatus(SamlResponseStatusEnum.SUCCESS.getValue());
samlResponseLogEntity.setInResponseTo(inResponseTo);
samlResponseLogEntity.setSamlId(responseId);
samlResponseLogEntity.setIssueInstant(issueInstant);
samlResponseLogRepository.save(samlResponseLogEntity); samlResponseLogRepository.save(samlResponseLogEntity);
HubEntity hub = hubService.getHubByUuid(samlResponseLogEntity.getHubUuid());
String redirectUrl = feBaseUrl; String redirectUrl = feBaseUrl;
if (Boolean.FALSE.equals(StringUtils.isEmpty(hub.getDomainName()))) {
redirectUrl = hub.getDomainName();
}
logger.info("SAML login successful for user: " + principal.getName()); logger.info("SAML login successful for user: " + principal.getName());
String cf = userAttributes.get("CodiceFiscale").get(0).toString(); String cf = userAttributes.get("CodiceFiscale").get(0).toString();
@@ -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); SamlResponseEntity samlResponseLogEntity = samlResponseLogRepository.findByToken(token);
if (samlResponseLogEntity == null) { if (samlResponseLogEntity == null || Boolean.FALSE.equals(hubUuid.equals(samlResponseLogEntity.getHubUuid()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR, throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG)); Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
} }
@@ -92,7 +136,6 @@ public class SamlSuccessHandler implements AuthenticationSuccessHandler {
throw new CustomValidationException(Status.VALIDATION_ERROR, throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG)); Translator.toLocale(GepafinConstant.INVALID_TOKEN_MSG));
} }
samlResponseLogRepository.delete(samlResponseLogEntity);
} }
} }

View File

@@ -15,6 +15,7 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHt
import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; 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.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher;
@@ -118,15 +119,11 @@ public class SecurityConfig {
) )
.addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(new JWTFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new JWTFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
// Add SAML2 login configuration (for BENEFICIARI) .addFilterBefore(new SamlRequestFilter(), Saml2WebSsoAuthenticationRequestFilter.class) // Add the custom SAML filter
/* .saml2Login(saml -> saml.defaultSuccessUrl("/")
* .saml2Login(saml -> saml.loginPage("/saml/login") // Entry point for SAML .successHandler(samlSuccessHandler)
* login .defaultSuccessUrl("/") // Redirect after successful SAML login );
*/
.saml2Login(saml -> saml.defaultSuccessUrl("/").successHandler(samlSuccessHandler)
.failureHandler(samlFailureHandler)); .failureHandler(samlFailureHandler));
return http.build(); return http.build();
} }

View File

@@ -105,6 +105,10 @@ public class TokenProvider {
payload += ":"+user.getId(); payload += ":"+user.getId();
} }
if(user != null) {
payload += ":"+user.getHub().getId();
}
String token = Jwts.builder() String token = Jwts.builder()
.setSubject(payload) .setSubject(payload)
.claim("auth", authorities) .claim("auth", authorities)

View File

@@ -232,6 +232,7 @@ public class GepafinConstant {
public static final String GET_LOGIN_ATTEMPT_MSG="get_login_attempt_se_msg"; public static final String GET_LOGIN_ATTEMPT_MSG="get_login_attempt_se_msg";
public static final String CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT = "application.in.submit.status.cannot.delete.company"; public static final String CANNOT_DELETE_COMPANY_WITH_APPLICATION_SUBMITT = "application.in.submit.status.cannot.delete.company";
public static final String GET_USERS_SUCCESS_MSG = "get.users.success.msg"; public static final String GET_USERS_SUCCESS_MSG = "get.users.success.msg";
public static final String CANNOT_CREATE_BENEFICIARY_USER="cannot.create.beneficiary.user";
public static final String APPLICATION_ASSIGNED= "application.assigned.success.msg"; 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 APPLICATION_ALREADY_ASSIGNED = "application.already.assigned.msg";
@@ -239,5 +240,13 @@ public class GepafinConstant {
public static final String DELETE_ASSIGNED_APPLICATION_SUCCESS_MSG = "assigned.application.deleted.success"; 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 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 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";
} }

View File

@@ -20,6 +20,7 @@ import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.DocumentService; import net.gepafin.tendermanagement.service.DocumentService;
import net.gepafin.tendermanagement.service.FormService; import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.service.SystemEmailTemplatesService; import net.gepafin.tendermanagement.service.SystemEmailTemplatesService;
import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.util.DateTimeUtil; import net.gepafin.tendermanagement.util.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator; import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.MailUtil; import net.gepafin.tendermanagement.util.MailUtil;
@@ -120,12 +121,19 @@ public class ApplicationDao {
@Value("${aws.s3.url.folder.signed.document}") @Value("${aws.s3.url.folder.signed.document}")
private String signedDocumentS3Folder; private String signedDocumentS3Folder;
@Value("${default.hub.uuid}")
private String defaultHubUuid;
public ApplicationResponseBean createApplication(ApplicationRequestBean applicationRequestBean, UserEntity userEntity, Long formId, Long applicationId) { @Autowired
private UserService userService;
public ApplicationResponseBean createApplication(HttpServletRequest request, ApplicationRequestBean applicationRequestBean, Long formId, Long applicationId) {
FormEntity formEntity = formService.validateForm(formId); FormEntity formEntity = formService.validateForm(formId);
// callService.validatePublishedCall(formEntity.getCall().getId()); // callService.validatePublishedCall(formEntity.getCall().getId());
validateFormFields(applicationRequestBean,formEntity); validateFormFields(applicationRequestBean,formEntity);
ApplicationEntity applicationEntity = validateApplication(applicationId); ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) { if(Boolean.TRUE.equals(applicationEntity.getStatus().equals(ApplicationStatusTypeEnum.SUBMIT.getValue()))) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED)); throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.APPLICATION_ALREADY_SUBMITTED));
} }
@@ -229,10 +237,11 @@ public class ApplicationDao {
return applicationFormFieldResponseBeans; return applicationFormFieldResponseBeans;
} }
public void deleteById(Long id) { public void deleteById(HttpServletRequest request, Long id) {
log.info("Deleting application with ID: {}", id); log.info("Deleting application with ID: {}", id);
ApplicationEntity applicationEntity= validateApplication(id); ApplicationEntity applicationEntity= validateApplication(id);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
applicationEntity.setIsDeleted(true); applicationEntity.setIsDeleted(true);
applicationEntity=saveApplicationEntity(applicationEntity); applicationEntity=saveApplicationEntity(applicationEntity);
log.info("Application deleted with ID: {}", id); log.info("Application deleted with ID: {}", id);
@@ -471,9 +480,10 @@ public class ApplicationDao {
return applicationEntity; 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<FormApplicationResponse> formApplicationResponses = new ArrayList<>();
List<FormEntity> formEntities = new ArrayList<>(); List<FormEntity> formEntities = new ArrayList<>();
UserEntity userEntity = validator.validateUser(request);
boolean isBeneficiary = isBeneficiary(userEntity); boolean isBeneficiary = isBeneficiary(userEntity);
ApplicationEntity applicationEntity = isBeneficiary ApplicationEntity applicationEntity = isBeneficiary
? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId()) ? applicationRepository.findByIdAndUserIdAndIsDeletedFalse(applicationId, userEntity.getId())
@@ -578,8 +588,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); ApplicationEntity applicationEntity = validateApplication(applicationId);
UserEntity userEntity = userService.validateUser(applicationEntity.getUserId());
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) { if (ApplicationStatusTypeEnum.SUBMIT.getValue().equals(applicationEntity.getStatus())) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE)); throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_SUBMITTED_CANNOT_CHANGE));
} }
@@ -606,22 +618,31 @@ public class ApplicationDao {
if (totalSteps.intValue() != completedSteps) { if (totalSteps.intValue() != completedSteps) {
throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG)); throw new CustomValidationException(Status.BAD_REQUEST, Translator.toLocale(GepafinConstant.APPLICATION_IS_INCOMPLETE_MSG));
} }
Integer maxProtocolNumber=protocolRepository.findMaxProtocolNumber(); Long protocolNumber = getProtocolNumber(userEntity.getHub());
Integer protocolNumber = (maxProtocolNumber != null) ? maxProtocolNumber + 1 : 1; ProtocolEntity protocolEntity = createProtocolEntity(applicationEntity,protocolNumber, userEntity.getHub().getId());
ProtocolEntity protocolEntity=createProtocolEntity(applicationEntity,protocolNumber);
applicationEntity.setProtocol(protocolEntity); applicationEntity.setProtocol(protocolEntity);
applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue()); applicationEntity.setStatus(ApplicationStatusTypeEnum.SUBMIT.getValue());
applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now())); applicationEntity.setSubmissionDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
applicationEntity = saveApplicationEntity(applicationEntity);
sendMailToUserAndCompany(userEntity, applicationEntity); sendMailToUserAndCompany(userEntity, applicationEntity);
sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity); sendMailTodefaultSystemAndGepafin(userEntity, applicationEntity);
} else { } else {
applicationEntity.setStatus(status.getValue()); applicationEntity.setStatus(status.getValue());
}
applicationEntity = saveApplicationEntity(applicationEntity); applicationEntity = saveApplicationEntity(applicationEntity);
}
return getApplicationResponse(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) { public Integer calculateProgress(Long totalSteps, Long completedSteps) {
if (FieldValidator.isNullOrZero(totalSteps)) { if (FieldValidator.isNullOrZero(totalSteps)) {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.TOTAL_STEPS_NOT_BE_ZERO)); throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.TOTAL_STEPS_NOT_BE_ZERO));
@@ -695,14 +716,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 protocolEntity=new ProtocolEntity();
protocolEntity.setCall(applicationEntity.getCall().getId()); protocolEntity.setCall(applicationEntity.getCall().getId());
LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now()); LocalDateTime utcDateTime = DateTimeUtil.DateServerToUTC(LocalDateTime.now());
protocolEntity.setYear(utcDateTime.getYear()); protocolEntity.setYear(utcDateTime.getYear());
protocolEntity.setProtocolNumber(Long.valueOf(protocolNumber)); protocolEntity.setProtocolNumber(protocolNumber);
protocolEntity.setTime(LocalTime.now()); protocolEntity.setTime(LocalTime.now());
protocolEntity.setApplicationId(applicationEntity.getId()); protocolEntity.setApplicationId(applicationEntity.getId());
protocolEntity.setHubId(hubId);
protocolRepository.save(protocolEntity); protocolRepository.save(protocolEntity);
return protocolEntity; return protocolEntity;
} }
@@ -767,7 +789,9 @@ public class ApplicationDao {
mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null); mailUtil.sendByMailGun(subject, body, List.of(defaultSystemReceiverEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null); mailUtil.sendByMailGun(subject, body, List.of(gepafinEmail), null);
mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null); mailUtil.sendByMailGun(subject, body, List.of(rinaldoEmail), null);
if(validator.isProductionProfileActivated()) {
mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null); mailUtil.sendByMailGun(subject, body, List.of(carloEmail), null);
}
} }
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId, public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId,

View File

@@ -1,6 +1,5 @@
package net.gepafin.tendermanagement.dao; package net.gepafin.tendermanagement.dao;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -23,10 +22,6 @@ import net.gepafin.tendermanagement.util.Utils;
import org.h2.util.IOUtils; import org.h2.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; 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.stereotype.Component;
import org.springframework.util.StringUtils; 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.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity; import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CallTargetAudienceChecklistEntity; import net.gepafin.tendermanagement.entities.CallTargetAudienceChecklistEntity;
import net.gepafin.tendermanagement.entities.CriteriaFormFieldEntity;
import net.gepafin.tendermanagement.entities.DocumentEntity; import net.gepafin.tendermanagement.entities.DocumentEntity;
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity; import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
import net.gepafin.tendermanagement.entities.FaqEntity; 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.model.request.UpdateCallRequestStep1;
import net.gepafin.tendermanagement.repositories.CallRepository; import net.gepafin.tendermanagement.repositories.CallRepository;
import net.gepafin.tendermanagement.repositories.CallTargetAudienceChecklistRepository; import net.gepafin.tendermanagement.repositories.CallTargetAudienceChecklistRepository;
import net.gepafin.tendermanagement.repositories.CriteriaFormFieldRepository;
import net.gepafin.tendermanagement.repositories.DocumentRepository; import net.gepafin.tendermanagement.repositories.DocumentRepository;
import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository; import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository;
import net.gepafin.tendermanagement.repositories.FaqRepository; import net.gepafin.tendermanagement.repositories.FaqRepository;
@@ -89,23 +86,26 @@ public class CallDao {
private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository; private CallTargetAudienceChecklistRepository callTargetAudienceChecklistRepository;
@Autowired @Autowired
private UserService userService; private FaqService faqService;
@Autowired
private FaqService faqService;
@Autowired @Autowired
private FlowDao flowDao; private FlowDao flowDao;
@Autowired @Autowired
private FormDao formDao; private FormDao formDao;
@Value("${aws.s3.url.folder}") @Value("${aws.s3.url.folder}")
private String s3Folder; private String s3Folder;
@Autowired @Autowired
private AmazonS3Service amazonS3Service; private AmazonS3Service amazonS3Service;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, Long userId) { @Autowired
UserEntity userEntity = userService.validateUser(userId); private CriteriaFormFieldRepository criteriaFormFieldRepository;
public CallResponse createCallStep1(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId()); createCallRequest.setRegionId(userEntity.getRoleEntity().getRegion().getId());
CallEntity callEntity = convertToCallEntity(createCallRequest); CallEntity callEntity = convertToCallEntity(createCallRequest, userEntity);
updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ); updateFaq(createCallRequest.getFaq(), callEntity, userEntity,LookUpDataTypeEnum.FAQ);
@@ -147,7 +147,7 @@ public class CallDao {
public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest) { public CallEntity convertToCallEntity(CreateCallRequestStep1 createCallRequest, UserEntity userEntity) {
CallEntity callEntity = new CallEntity(); CallEntity callEntity = new CallEntity();
// validateCallEntity(createCallRequest); // validateCallEntity(createCallRequest);
RegionEntity region = regionRepository.findById(createCallRequest.getRegionId()) RegionEntity region = regionRepository.findById(createCallRequest.getRegionId())
@@ -183,6 +183,7 @@ public class CallDao {
callEntity.setPhoneNumber(createCallRequest.getPhoneNumber()); callEntity.setPhoneNumber(createCallRequest.getPhoneNumber());
callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime())); callEntity.setStartTime(DateTimeUtil.parseTime(createCallRequest.getStartTime()));
callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime())); callEntity.setEndTime(DateTimeUtil.parseTime(createCallRequest.getEndTime()));
callEntity.setHub(userEntity.getHub());
callEntity = callRepository.save(callEntity); callEntity = callRepository.save(callEntity);
return callEntity; return callEntity;
} }
@@ -208,6 +209,12 @@ public class CallDao {
private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) { private void softDeleteEvaluationCriteria(EvaluationCriteriaEntity evaluationCriteriaEntity) {
evaluationCriteriaEntity.setIsDeleted(true); evaluationCriteriaEntity.setIsDeleted(true);
evaluationCriteriaRepository.save(evaluationCriteriaEntity); 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, private EvaluationCriteriaEntity convertToEvaluationCriteriaEntity(EvaluationCriteriaReq criteriaReq,
@@ -255,6 +262,7 @@ public class CallDao {
private void softDeleteDocument(DocumentEntity documentEntity) { private void softDeleteDocument(DocumentEntity documentEntity) {
documentEntity.setIsDeleted(true); documentEntity.setIsDeleted(true);
documentRepository.save(documentEntity); documentRepository.save(documentEntity);
} }
private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) { private DocumentEntity convertToDocumentEntity(DocumentReq documentReq,Long sourceId) {
@@ -422,13 +430,11 @@ public class CallDao {
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND))); Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)));
} }
public CallResponse getCallById(Long callId) { public CallResponse getCallById(CallEntity callEntity) {
CallEntity callEntity = validateCall(callId);
return getCallResponseBean(callEntity); return getCallResponseBean(callEntity);
} }
public CallResponse createCallStep2(Long callId, CreateCallRequestStep2 createCallRequest, Long userId) { public CallResponse createCallStep2(CallEntity callEntity, CreateCallRequestStep2 createCallRequest, UserEntity user) {
CallEntity callEntity = validateCall(callId);
validateUpdate(callEntity); validateUpdate(callEntity);
setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold()); setIfUpdated(callEntity::getThreshold, callEntity::setThreshold, createCallRequest.getThreshold());
callRepository.save(callEntity); callRepository.save(callEntity);
@@ -488,8 +494,7 @@ public class CallDao {
} }
} }
public CallResponse updateCallStep1(Long callId, UpdateCallRequestStep1 updateCallRequest, Long userId) { public CallResponse updateCallStep1(CallEntity callEntity, UpdateCallRequestStep1 updateCallRequest, UserEntity userEntity) {
CallEntity callEntity = validateCall(callId);
if(Boolean.TRUE.equals(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue()))) { if(Boolean.TRUE.equals(callEntity.getStatus().equals(CallStatusEnum.PUBLISH.getValue()))) {
try { try {
Utils.retainOnlySpecificFields(updateCallRequest, Collections.singletonList("faq")); Utils.retainOnlySpecificFields(updateCallRequest, Collections.singletonList("faq"));
@@ -497,7 +502,6 @@ public class CallDao {
throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FAILED_RETAIN_FIELD)); throw new CustomValidationException(Status.BAD_REQUEST,Translator.toLocale(GepafinConstant.FAILED_RETAIN_FIELD));
} }
} }
UserEntity userEntity = userService.validateUser(userId);
isValidDateRange(updateCallRequest, callEntity); isValidDateRange(updateCallRequest, callEntity);
setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName()); setIfUpdated(callEntity::getName, callEntity::setName, updateCallRequest.getName());
setIfUpdated(callEntity::getDescriptionShort, callEntity::setDescriptionShort, setIfUpdated(callEntity::getDescriptionShort, callEntity::setDescriptionShort,
@@ -656,7 +660,7 @@ public class CallDao {
validateUpdate(callEntity); validateUpdate(callEntity);
CallResponse callResponseBean = getCallResponseBean(callEntity); CallResponse callResponseBean = getCallResponseBean(callEntity);
FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId()); FlowResponseBean flowResponseBean = flowDao.getFlowByCallId(callEntity.getId());
List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity.getId()); List<FormResponseBean> formResponseBean = formDao.getFormsByCallId(callEntity);
CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean); CallValidatorServiceImpl.validateResponse(callResponseBean,flowResponseBean,formResponseBean);
callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue()); callEntity.setStatus(CallStatusEnum.READY_TO_PUBLISH.getValue());
callRepository.save(callEntity); callRepository.save(callEntity);
@@ -672,8 +676,7 @@ public class CallDao {
return callEntity; return callEntity;
} }
public CallResponse updateCallStatus(Long callId, CallStatusEnum statusReq) { public CallResponse updateCallStatus(CallEntity callEntity, CallStatusEnum statusReq) {
CallEntity callEntity = validateCall(callId);
CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus()); CallStatusEnum currentStatus = CallStatusEnum.valueOf(callEntity.getStatus());
validateStatusChange(currentStatus, statusReq); validateStatusChange(currentStatus, statusReq);
callEntity.setStatus(statusReq.getValue()); callEntity.setStatus(statusReq.getValue());

View File

@@ -32,23 +32,23 @@ public class DashboardDao {
@Autowired @Autowired
private CompanyRepository companyRepository; private CompanyRepository companyRepository;
public SuperAdminWidgetResponseBean getDashboardWidget() { public SuperAdminWidgetResponseBean getDashboardWidget(UserEntity requestedUserEntity) {
SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean(); SuperAdminWidgetResponseBean widgetResponseBean = new SuperAdminWidgetResponseBean();
widgetResponseBean.setWidget1(createWidget1()); widgetResponseBean.setWidget1(createWidget1(requestedUserEntity));
// List<Object[]> widgetBars = callRepository.findApplicationsPerCall(); // List<Object[]> widgetBars = callRepository.findApplicationsPerCall();
// widgetResponseBean.setWidgetBars(widgetBars); // widgetResponseBean.setWidgetBars(widgetBars);
return widgetResponseBean; return widgetResponseBean;
} }
private Widget1 createWidget1() { private Widget1 createWidget1(UserEntity requestedUserEntity) {
Widget1 widget1 = initializeWidget1(); Widget1 widget1 = initializeWidget1();
setActiveCalls(widget1); setActiveCalls(widget1, requestedUserEntity);
setRegisteredUsers(widget1); setRegisteredUsers(widget1, requestedUserEntity);
setTotalActiveFinancing(widget1); setTotalActiveFinancing(widget1, requestedUserEntity);
setSubmittedApplications(widget1); setSubmittedApplications(widget1, requestedUserEntity);
setDraftApplications(widget1); setDraftApplications(widget1, requestedUserEntity);
setNumberOfCompanies(widget1); setNumberOfCompanies(widget1, requestedUserEntity);
return widget1; return widget1;
} }
@@ -59,41 +59,41 @@ public class DashboardDao {
.build(); .build();
} }
private void setActiveCalls(Widget1 widget1) { private void setActiveCalls(Widget1 widget1, UserEntity requestedUserEntity) {
Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue()); Long activeCalls = callRepository.countByStatus(CallStatusEnum.PUBLISH.getValue());
if (activeCalls != null) { if (activeCalls != null) {
widget1.setNumberOfActiveCalls(activeCalls); widget1.setNumberOfActiveCalls(activeCalls);
} }
} }
private void setRegisteredUsers(Widget1 widget1) { private void setRegisteredUsers(Widget1 widget1, UserEntity requestedUserEntity) {
Long activeUsers = userRepository.countByStatusAndRoleEntity_RoleType(UserStatusEnum.ACTIVE.getValue(), Long activeUsers = userRepository.countByStatusAndRoleEntityRoleTypeAndHubId(UserStatusEnum.ACTIVE.getValue(),
RoleStatusEnum.ROLE_BENEFICIARY.getValue()); RoleStatusEnum.ROLE_BENEFICIARY.getValue(), requestedUserEntity.getHub().getId());
if (activeUsers != null) { if (activeUsers != null) {
widget1.setNumberOfResgisteredUsers(activeUsers); widget1.setNumberOfResgisteredUsers(activeUsers);
} }
} }
private void setTotalActiveFinancing(Widget1 widget1) { private void setTotalActiveFinancing(Widget1 widget1, UserEntity requestedUserEntity) {
BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCalls(); BigDecimal totalActiveFinancing = callRepository.findTotalAmountOfPublishedCalls();
widget1.setTotalActiveFinancing(totalActiveFinancing); widget1.setTotalActiveFinancing(totalActiveFinancing);
} }
private void setSubmittedApplications(Widget1 widget1) { private void setSubmittedApplications(Widget1 widget1, UserEntity requestedUserEntity) {
Long submittedApplications = applicationRepository.countSubmittedApplications(); Long submittedApplications = applicationRepository.countSubmittedApplications();
if (submittedApplications != null) { if (submittedApplications != null) {
widget1.setNumberOfSubmittedApplications(submittedApplications); widget1.setNumberOfSubmittedApplications(submittedApplications);
} }
} }
private void setDraftApplications(Widget1 widget1) { private void setDraftApplications(Widget1 widget1, UserEntity requestedUserEntity) {
Long draftApplications = applicationRepository.countDraftApplications(); Long draftApplications = applicationRepository.countDraftApplications();
if (draftApplications != null) { if (draftApplications != null) {
widget1.setNumberOfDraftApplications(draftApplications); widget1.setNumberOfDraftApplications(draftApplications);
} }
} }
private void setNumberOfCompanies(Widget1 widget1) { private void setNumberOfCompanies(Widget1 widget1, UserEntity requestedUserEntity) {
Long numberOfCompanies = companyRepository.countTotalCompanies(); Long numberOfCompanies = companyRepository.countTotalCompanies();
if (numberOfCompanies != null) { if (numberOfCompanies != null) {
widget1.setNumberOfCompany(numberOfCompanies); widget1.setNumberOfCompany(numberOfCompanies);

View File

@@ -3,17 +3,21 @@ package net.gepafin.tendermanagement.dao;
import net.gepafin.tendermanagement.config.Translator; import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.CallEntity; import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CriteriaFormFieldEntity;
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity; import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
import net.gepafin.tendermanagement.entities.LookUpDataEntity; import net.gepafin.tendermanagement.entities.LookUpDataEntity;
import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest; import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest;
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean; import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
import net.gepafin.tendermanagement.repositories.CriteriaFormFieldRepository;
import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository; import net.gepafin.tendermanagement.repositories.EvaluationCriteriaRepository;
import net.gepafin.tendermanagement.service.CallService; import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.LookUpDataService; import net.gepafin.tendermanagement.service.LookUpDataService;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException; import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status; import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
@@ -28,6 +32,9 @@ public class EvaluationCriteriaDao {
@Autowired @Autowired
private LookUpDataService lookUpDataService; private LookUpDataService lookUpDataService;
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
public EvaluationCriteriaResponseBean createEvaluationCriteria( public EvaluationCriteriaResponseBean createEvaluationCriteria(
EvaluationCriteriaRequest evaluationCriteriaRequest) { EvaluationCriteriaRequest evaluationCriteriaRequest) {
EvaluationCriteriaEntity entity = convertEvaluationCriteriaRequestToEvaluationCriteriaEntity( EvaluationCriteriaEntity entity = convertEvaluationCriteriaRequestToEvaluationCriteriaEntity(
@@ -55,6 +62,12 @@ public class EvaluationCriteriaDao {
Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_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) { public EvaluationCriteriaResponseBean updateEvaluationCriteria(Long id, EvaluationCriteriaRequest request) {
EvaluationCriteriaEntity entity = evaluationCriteriaRepository.findById(id) EvaluationCriteriaEntity entity = evaluationCriteriaRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND, .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
@@ -64,12 +77,15 @@ public class EvaluationCriteriaDao {
} }
public void deleteEvaluationCriteria(Long id) { public void deleteEvaluationCriteria(Long id) {
try {
evaluationCriteriaRepository.deleteById(id); evaluationCriteriaRepository.deleteById(id);
} catch (EmptyResultDataAccessException e) { EvaluationCriteriaEntity evaluationCriteriaEntity = validateEvaluationCriteria(id);
throw new ResourceNotFoundException(Status.NOT_FOUND, evaluationCriteriaEntity.setIsDeleted(Boolean.TRUE);
Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_NOT_FOUND)); evaluationCriteriaRepository.save(evaluationCriteriaEntity);
} List<CriteriaFormFieldEntity> list = criteriaFormFieldRepository.findByEvaluationCriteriaIdAndIsDeletedFalse(evaluationCriteriaEntity.getId())
.stream()
.peek(data -> data.setIsDeleted(Boolean.TRUE))
.toList();;
criteriaFormFieldRepository.saveAll(list);
} }
private EvaluationCriteriaResponseBean convertEvaluationCriteriaEntityEvaluationCriteriaToResponseBean( private EvaluationCriteriaResponseBean convertEvaluationCriteriaEntityEvaluationCriteriaToResponseBean(

View File

@@ -6,25 +6,27 @@ import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.model.request.*; import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.ContentResponseBean; import net.gepafin.tendermanagement.model.response.ContentResponseBean;
import net.gepafin.tendermanagement.model.response.FormResponseBean; import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.model.response.VatNumberResponseBean;
import net.gepafin.tendermanagement.repositories.*; 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.DateTimeUtil;
import net.gepafin.tendermanagement.util.FieldValidator; import net.gepafin.tendermanagement.util.FieldValidator;
import net.gepafin.tendermanagement.util.Utils; 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.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException; import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status; import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.text.MessageFormat; import java.text.MessageFormat;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Component @Component
@@ -33,9 +35,6 @@ public class FormDao {
@Autowired @Autowired
private FormRepository formRepository; private FormRepository formRepository;
@Autowired
private CallService callService;
@Autowired @Autowired
private ApplicationFormRepository applicationFormRepository; private ApplicationFormRepository applicationFormRepository;
@@ -54,34 +53,54 @@ public class FormDao {
@Autowired @Autowired
private CallRepository callRepository; private CallRepository callRepository;
@Autowired
private Validator validator;
@Autowired
private CriteriaFormFieldRepository criteriaFormFieldRepository;
@Autowired
private EvaluationCriteriaService evaluationCriteriaService;
public FormEntity saveFormEntity(FormEntity formEntity){ public FormEntity saveFormEntity(FormEntity formEntity){
formEntity=formRepository.save(formEntity); formEntity=formRepository.save(formEntity);
return formEntity; return formEntity;
} }
public FormEntity convertFormRequestToFormEntity(Long callId,FormRequest formRequest){ public FormEntity convertFormRequestToFormEntity(CallEntity callEntity, FormRequest formRequest){
FormEntity formEntity=new FormEntity(); FormEntity formEntity=new FormEntity();
CallEntity callEntity=callService.getCallEntityById(callId);
formEntity.setCall(callEntity); formEntity.setCall(callEntity);
formEntity.setLabel(formRequest.getLabel()); formEntity.setLabel(formRequest.getLabel());
formEntity.setContent(setContentResponseBean(formRequest.getContent())); formEntity.setContent(setContentResponseBean(formRequest.getContent()));
formEntity=saveFormEntity(formEntity); formEntity=saveFormEntity(formEntity);
return formEntity; return formEntity;
} }
public FormResponseBean convertFormEntityToFormResponseBean(FormEntity formEntity){ public FormResponseBean convertFormEntityToFormResponseBean(FormEntity formEntity) {
FormResponseBean formResponseBean=new FormResponseBean(); FormResponseBean formResponseBean=new FormResponseBean();
formResponseBean.setId(formEntity.getId()); formResponseBean.setId(formEntity.getId());
formResponseBean.setContent(Utils.convertJsonStringToList(formEntity.getContent(), ContentResponseBean.class)); formResponseBean.setContent(setContent(formEntity));
formResponseBean.setLabel(formEntity.getLabel()); formResponseBean.setLabel(formEntity.getLabel());
formResponseBean.setCallId(formEntity.getCall().getId()); formResponseBean.setCallId(formEntity.getCall().getId());
formResponseBean.setCallStatus(formEntity.getCall().getStatus()); formResponseBean.setCallStatus(formEntity.getCall().getStatus());
return formResponseBean; 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); validateForm(formRequest);
CallEntity callEntity=callService.validateCall(callId); List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callEntity.getId());
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(callId); List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callEntity.getId());
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(callId);
if(Boolean.FALSE.equals(flowDataEntities.isEmpty() || flowDataEntities==null ) || Boolean.FALSE.equals(flowEdgesEntities.isEmpty() || flowEdgesEntities==null) ){ if(Boolean.FALSE.equals(flowDataEntities.isEmpty() || flowDataEntities==null ) || Boolean.FALSE.equals(flowEdgesEntities.isEmpty() || flowEdgesEntities==null) ){
flowDataRepository.deleteAll(flowDataEntities); flowDataRepository.deleteAll(flowDataEntities);
flowEdgesRepository.deleteAll(flowEdgesEntities); flowEdgesRepository.deleteAll(flowEdgesEntities);
@@ -89,18 +108,71 @@ public class FormDao {
callEntity.setFinalForm(null); callEntity.setFinalForm(null);
callRepository.save(callEntity); callRepository.save(callEntity);
} }
FormEntity formEntity=convertFormRequestToFormEntity(callId,formRequest); FormEntity formEntity=convertFormRequestToFormEntity(callEntity, formRequest);
validateAndSaveCriteriaFormField(callEntity, formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity); return convertFormEntityToFormResponseBean(formEntity);
} }
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){ public void validateForm(FormRequest formRequest){
if(formRequest.getContent()==null || formRequest.getLabel()==null ){ if(formRequest.getContent()==null || formRequest.getLabel()==null ){
throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.REQUIRED_PARAMETER_NOT_FOUND_FOR_FORM)); 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; ContentRequestBean contentRequestBean2=null;
String choosenField=null; String choosenField=null;
FormEntity formEntity = validateForm(formId); FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
callDao.validateUpdate(formEntity.getCall()); callDao.validateUpdate(formEntity.getCall());
List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(), ContentRequestBean.class); List<ContentRequestBean> contentRequestBean = Utils.convertJsonStringToList(formEntity.getContent(), ContentRequestBean.class);
for (ContentRequestBean contentRequestBean1 : contentRequestBean) { for (ContentRequestBean contentRequestBean1 : contentRequestBean) {
@@ -160,6 +232,7 @@ public class FormDao {
Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent())); Utils.setIfUpdated(formEntity::getContent, formEntity::setContent, setContentResponseBean(formRequest.getContent()));
formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now())); formEntity.setUpdatedDate(DateTimeUtil.DateServerToUTC(LocalDateTime.now()));
formEntity = saveFormEntity(formEntity); formEntity = saveFormEntity(formEntity);
validateAndSaveCriteriaFormField(formEntity.getCall(), formEntity, formRequest.getContent());
return convertFormEntityToFormResponseBean(formEntity); return convertFormEntityToFormResponseBean(formEntity);
} }
return convertFormEntityToFormResponseBean(formEntity); return convertFormEntityToFormResponseBean(formEntity);
@@ -171,12 +244,14 @@ public class FormDao {
return formEntity; return formEntity;
} }
public FormResponseBean getFormEntityById(Long formId) { public FormResponseBean getFormEntityById(UserEntity user, Long formId) {
FormEntity formEntity = validateForm(formId); FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
return convertFormEntityToFormResponseBean(formEntity); return convertFormEntityToFormResponseBean(formEntity);
} }
public void deleteFormById(Long formId){ public void deleteFormById(UserEntity user, Long formId){
FormEntity formEntity = validateForm(formId); FormEntity formEntity = validateForm(formId);
validator.validateUserWithCall(user, formEntity.getCall().getId());
List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(formEntity.getCall().getId()); List<FlowDataEntity> flowDataEntities=flowDataRepository.findByCallId(formEntity.getCall().getId());
List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(formEntity.getCall().getId()); List<FlowEdgesEntity> flowEdgesEntities=flowEdgesRepository.findByCallId(formEntity.getCall().getId());
flowDataRepository.deleteAll(flowDataEntities); flowDataRepository.deleteAll(flowDataEntities);
@@ -187,20 +262,22 @@ public class FormDao {
callRepository.save(callEntity); callRepository.save(callEntity);
formRepository.delete(formEntity); formRepository.delete(formEntity);
} }
public List<FormResponseBean> getFormsByCallId(Long callId){ public List<FormResponseBean> getFormsByCallId(CallEntity callEntity){
CallEntity callEntity=callService.validateCall(callId);
if(callEntity== null){ if(callEntity== null){
throw new CustomValidationException(Status.VALIDATION_ERROR, throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.CALL_NOT_FOUND)); Translator.toLocale(GepafinConstant.CALL_NOT_FOUND));
} }
List<FormEntity> formEntities=formRepository.findByCallId(callId); List<FormEntity> formEntities=formRepository.findByCallId(callEntity.getId());
List<FormResponseBean> formResponseBeanList = formEntities.stream() List<FormResponseBean> formResponseBeanList = formEntities.stream()
.map(req -> convertFormEntityToFormResponseBean(req)) .map(req -> convertFormEntityToFormResponseBean(req))
.collect(Collectors.toList()); .collect(Collectors.toList());
return formResponseBeanList; return formResponseBeanList;
} }
public String setContentResponseBean(List<ContentRequestBean> contentRequestBeans){ 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) { public void validateFormField(List<ApplicationFormFieldRequestBean> applicationFormFieldRequestList, ApplicationEntity applicationEntity, FormEntity formEntity) {
@@ -295,12 +372,13 @@ public class FormDao {
String error=null; String error=null;
if (value!=null && value.matches("^\\d{1,11}$")) { if (value!=null && value.matches("^\\d{1,11}$")) {
Map<String, Object> customData=null; // Map<String, Object> customData=null;
try { try {
Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value); // Map<String, Object> vatCheckResponse = vatCheckDao.checkVatNumberApi(value);
if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) { vatCheckDao.checkVatNumberApi(value);
customData = vatCheckResponse; // if (Boolean.FALSE.equals(CollectionUtils.isEmpty(vatCheckResponse))) {
} // customData = vatCheckResponse;
// }
} catch (Exception e) { } catch (Exception e) {
error=(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_VALID_PIVA), fieldId)); error=(MessageFormat.format(Translator.toLocale(GepafinConstant.VALIDATION_VALID_PIVA), fieldId));
} }

View 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));
}
}

View File

@@ -2,12 +2,6 @@ package net.gepafin.tendermanagement.dao;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; 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.*;
import com.itextpdf.text.Element; import com.itextpdf.text.Element;
import com.itextpdf.text.Font; import com.itextpdf.text.Font;
@@ -16,28 +10,17 @@ import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*; import com.itextpdf.text.pdf.*;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.*; import net.gepafin.tendermanagement.entities.*;
import net.gepafin.tendermanagement.model.request.CustomPageEvent;
import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest; import net.gepafin.tendermanagement.model.request.FieldLabelValuePairRequest;
import net.gepafin.tendermanagement.model.response.*; import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.repositories.ApplicationRepository;
import net.gepafin.tendermanagement.service.CallService; import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Validator; 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.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Cell;
//import com.itextpdf.layout.element. //import com.itextpdf.layout.element.
import java.awt.*;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@@ -128,7 +111,7 @@ public class PdfDao {
// addLabelValuePair(document, "Con il titolo di", "Rappresentante legale", regularFont); // addLabelValuePair(document, "Con il titolo di", "Rappresentante legale", regularFont);
document.add(new Paragraph(" ")); document.add(new Paragraph(" "));
ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(applicationId,null, userEntity); ApplicationGetResponseBean applicationGetResponseBean=applicationDao.getApplicationByFormId(request, applicationId, null);
for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) { for(FormApplicationResponse formApplicationResponse: applicationGetResponseBean.getForm()) {
document.add(new Paragraph(formApplicationResponse.getLabel(),sectionFont)); document.add(new Paragraph(formApplicationResponse.getLabel(),sectionFont));
document.add(new Paragraph(" ")); // Add line break document.add(new Paragraph(" ")); // Add line break

View File

@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.dao;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
import net.gepafin.tendermanagement.config.Translator; import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.entities.BeneficiaryEntity; import net.gepafin.tendermanagement.entities.BeneficiaryEntity;
@@ -17,10 +18,11 @@ import net.gepafin.tendermanagement.model.response.UserResponseBean;
import net.gepafin.tendermanagement.model.util.JWTToken; import net.gepafin.tendermanagement.model.util.JWTToken;
import net.gepafin.tendermanagement.repositories.BeneficiaryRepository; import net.gepafin.tendermanagement.repositories.BeneficiaryRepository;
import net.gepafin.tendermanagement.repositories.UserRepository; 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.RoleService;
import net.gepafin.tendermanagement.service.impl.AuthenticationService; import net.gepafin.tendermanagement.service.impl.AuthenticationService;
import net.gepafin.tendermanagement.util.Utils; 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.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException; import net.gepafin.tendermanagement.web.rest.api.errors.ResourceNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.Status; import net.gepafin.tendermanagement.web.rest.api.errors.Status;
@@ -29,11 +31,12 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static net.gepafin.tendermanagement.util.Utils.setIfUpdated; import static net.gepafin.tendermanagement.util.Utils.setIfUpdated;
@@ -45,8 +48,10 @@ public class UserDao {
@Autowired @Autowired
private UserRepository userRepository; private UserRepository userRepository;
@Autowired @Autowired
private CompanyDao companyDao; private CompanyDao companyDao;
@Autowired @Autowired
private AuthenticationService authService; private AuthenticationService authService;
@@ -58,12 +63,28 @@ public class UserDao {
@Autowired @Autowired
private BeneficiaryRepository beneficiaryRepository; private BeneficiaryRepository beneficiaryRepository;
@Autowired @Autowired
private RoleService roleService; 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) { public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) {
validateUserRequest(tempToken, userReq); if(StringUtils.isEmpty(userReq.getHubUuid())) {
userReq.setHubUuid(defaultHubUuid);
}
validateUserRequest(request, tempToken, userReq);
validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken); validatePassword(userReq.getPassword(), userReq.getConfPassword(), tempToken);
RoleEntity roleEntity = getRoleEntity(userReq.getRoleId()); RoleEntity roleEntity = getRoleEntity(userReq.getRoleId());
@@ -98,13 +119,21 @@ public class UserDao {
return beneficiaryEntity; return beneficiaryEntity;
} }
private void validateUserRequest(String tempToken, UserReq userReq) { private void validateUserRequest(HttpServletRequest request, String tempToken, UserReq userReq) {
if (tempToken == null) {
validator.validateRequest(request,RoleStatusEnum.ROLE_SUPER_ADMIN);
}else {
samlSuccessHandler.validateToken(tempToken, userReq.getCodiceFiscale(), userReq.getHubUuid());
}
RoleEntity role = roleService.validateRole(userReq.getRoleId());
if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) { if (Boolean.FALSE.equals(Utils.isValidEmail(userReq.getEmail()))) {
throw new CustomValidationException(Status.VALIDATION_ERROR, throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATE_EMAIL)); Translator.toLocale(GepafinConstant.VALIDATE_EMAIL));
} }
log.info("Creating user with email: {}", userReq.getEmail()); 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()); log.error("User creation failed: Email {} already exists", userReq.getEmail());
throw new CustomValidationException(Status.VALIDATION_ERROR, throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS)); Translator.toLocale(GepafinConstant.EMAIL_ALREADY_EXISTS));
@@ -122,6 +151,10 @@ public class UserDao {
if (tempToken != null) { if (tempToken != null) {
userReq.setRoleId(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));
}
} }
private void validatePassword(String password, String confirmPassword, String tempToken) { private void validatePassword(String password, String confirmPassword, String tempToken) {
@@ -182,8 +215,8 @@ public class UserDao {
userEntity.setEmail(userReq.getEmail()); userEntity.setEmail(userReq.getEmail());
userEntity.setStatus(UserStatusEnum.ACTIVE.getValue()); userEntity.setStatus(UserStatusEnum.ACTIVE.getValue());
userEntity.setBeneficiary(beneficiary); userEntity.setBeneficiary(beneficiary);
userEntity.setHub(hubService.getHubByUuid(userReq.getHubUuid()));
if (Boolean.FALSE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType()))) { if (Boolean.FALSE.equals(RoleStatusEnum.ROLE_BENEFICIARY.getValue().equals(roleEntity.getRoleType()))) {
userEntity.setFirstName(userReq.getFirstName()); userEntity.setFirstName(userReq.getFirstName());
userEntity.setLastName(userReq.getLastName()); userEntity.setLastName(userReq.getLastName());
userEntity.setOrganization(userReq.getOrganization()); userEntity.setOrganization(userReq.getOrganization());
@@ -263,6 +296,9 @@ public class UserDao {
public JWTToken login(LoginReq loginReq,HttpServletRequest request) { public JWTToken login(LoginReq loginReq,HttpServletRequest request) {
log.info("User login attempt for email: {}", loginReq.getEmail()); log.info("User login attempt for email: {}", loginReq.getEmail());
if(StringUtils.isEmpty(loginReq.getHubUuid())) {
loginReq.setHubUuid(defaultHubUuid);
}
JWTToken jwtToken = authService.login(loginReq,request); JWTToken jwtToken = authService.login(loginReq,request);
log.info("Login successful for email: {}", loginReq.getEmail()); log.info("Login successful for email: {}", loginReq.getEmail());
return jwtToken; return jwtToken;
@@ -283,11 +319,11 @@ public class UserDao {
} }
public String initiatePasswordReset(InitiatePasswordResetReq resetReq) { public String initiatePasswordReset(InitiatePasswordResetReq resetReq) {
UserEntity user = userRepository.findByEmail(resetReq.getEmail()); UserEntity user = userRepository
if (user == null) { .findByEmailIgnoreCaseAndHubUniqueUuid(resetReq.getEmail(), resetReq.getHubUuid())
log.info("Password reset attempt for non-existent user: {}", resetReq.getEmail()); .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)); Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
}
String token = Utils.generateSecureToken(); String token = Utils.generateSecureToken();
user.setResetPasswordToken(token); user.setResetPasswordToken(token);
userRepository.save(user); userRepository.save(user);
@@ -296,11 +332,11 @@ public class UserDao {
} }
public Boolean resetPassword(ResetPasswordReq resetPasswordReq) { public Boolean resetPassword(ResetPasswordReq resetPasswordReq) {
UserEntity user = userRepository.findByEmail(resetPasswordReq.getEmail()); UserEntity user = userRepository
if (user == null) { .findByEmailIgnoreCaseAndHubUniqueUuid(resetPasswordReq.getEmail(), resetPasswordReq.getHubUuid())
log.info("Password reset attempt for non-existent user: {}", resetPasswordReq.getEmail()); .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)); Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
}
if (!resetPasswordReq.getNewPassword().equals(resetPasswordReq.getConfirmPassword())) { if (!resetPasswordReq.getNewPassword().equals(resetPasswordReq.getConfirmPassword())) {
log.info("User creation failed: Passwords do not match for email {}", user.getEmail()); 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)); throw new CustomValidationException(Status.VALIDATION_ERROR, Translator.toLocale(GepafinConstant.PASSWORD_DOESNT_MATCH));
@@ -319,12 +355,12 @@ public class UserDao {
return true; return true;
} }
public Boolean changePassword(ChangePasswordRequest request) { public Boolean changePassword(UserEntity userEntity, ChangePasswordRequest request) {
UserEntity user = userRepository.findByEmail(request.getEmail()); UserEntity user = userRepository
if (user == null) { .findByEmailIgnoreCaseAndHubUniqueUuid(request.getEmail(), userEntity.getHub().getUniqueUuid())
log.info("Password reset attempt for non-existent user: {}", request.getEmail()); .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)); Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
}
if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) { if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CURRENT_PASSWORD_INCORRECT)); throw new ResourceNotFoundException(Status.NOT_FOUND, Translator.toLocale(GepafinConstant.CURRENT_PASSWORD_INCORRECT));
} }
@@ -349,6 +385,16 @@ public class UserDao {
log.info("User status updated to {} for user ID: {}", statusReq, userId); log.info("User status updated to {} for user ID: {}", statusReq, userId);
return convertUserEntityToUserResponse(userEntity); 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) { public JWTToken validateExistingUserToken(String token) {
return authService.validateExistingUserToken(token); return authService.validateExistingUserToken(token);
@@ -358,15 +404,15 @@ public class UserDao {
return authService.validateNewUserToken(token); return authService.validateNewUserToken(token);
} }
public List<UserResponseBean> getAllUsers(Long roleId) { public List<UserResponseBean> getAllUsers(UserEntity user, Long roleId) {
List<UserEntity> users; List<UserEntity> users;
if (roleId != null) { if (roleId != null) {
log.info("Fetching users by role ID: {}", roleId); log.info("Fetching users by role ID: {}", roleId);
RoleEntity roleEntity=roleService.validateRole(roleId); RoleEntity roleEntity=roleService.validateRole(roleId);
users = userRepository.findByRoleEntityId(roleEntity.getId()); users = userRepository.findByRoleEntityIdAndHubId(roleEntity.getId(), user.getHub().getId());
} else { } else {
log.info("Fetching all users"); log.info("Fetching all users");
users = userRepository.findAll(); users = userRepository.findByHubId(user.getHub().getId());
} }
List<UserResponseBean> userResponseBeans = users.stream() List<UserResponseBean> userResponseBeans = users.stream()
.map(this::convertUserEntityToUserResponse) .map(this::convertUserEntityToUserResponse)

View File

@@ -84,5 +84,9 @@ public class CallEntity extends BaseEntity {
@Column(name = "END_TIME") @Column(name = "END_TIME")
private LocalTime endTime; private LocalTime endTime;
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
} }

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -25,4 +25,7 @@ public class ProtocolEntity extends BaseEntity {
@Column(name="APPLICATION_ID") @Column(name="APPLICATION_ID")
private Long applicationId; private Long applicationId;
@Column(name="HUB_ID")
private Long hubId;
} }

View File

@@ -13,6 +13,21 @@ public class SamlResponseEntity extends BaseEntity{
@Column(name = "AUTHENTICATION_OBJECT") @Column(name = "AUTHENTICATION_OBJECT")
private String authenticationObject; 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") @Column(name = "TOKEN")
private String token; private String token;

View File

@@ -65,4 +65,8 @@ public class UserEntity extends BaseEntity {
@OneToOne @OneToOne
@JoinColumn(name = "BENEFICIARY_ID") @JoinColumn(name = "BENEFICIARY_ID")
private BeneficiaryEntity beneficiary; private BeneficiaryEntity beneficiary;
@ManyToOne
@JoinColumn(name = "HUB_ID")
private HubEntity hub;
} }

View File

@@ -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;
}
}

View File

@@ -13,6 +13,8 @@ public class ContentRequestBean {
private String label; private String label;
private List<SettingRequestBean> settings; private List<SettingRequestBean> settings;
private Map<String,Object> validators; private Map<String,Object> validators;
private List<Long> criteria;
private String dynamicData;
private Integer dbId; private Integer dbId;
} }

View File

@@ -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;
}

View File

@@ -5,4 +5,5 @@ import lombok.Data;
@Data @Data
public class InitiatePasswordResetReq { public class InitiatePasswordResetReq {
private String email; private String email;
private String hubUuid;
} }

View File

@@ -14,5 +14,6 @@ public class LoginReq {
private String email; private String email;
@NotEmpty @NotEmpty
private String password; private String password;
private String hubUuid;
private Boolean rememberMe; private Boolean rememberMe;
} }

View File

@@ -8,6 +8,6 @@ public class ResetPasswordReq {
private String token; private String token;
private String newPassword; private String newPassword;
private String confirmPassword; private String confirmPassword;
private String hubUuid;
} }

View File

@@ -39,4 +39,8 @@ public class UserReq {
private Boolean thirdParty; private Boolean thirdParty;
private String emailPec; private String emailPec;
private String hubUuid;
} }

View File

@@ -13,5 +13,7 @@ public class ContentResponseBean {
private String label; private String label;
private List<SettingResponseBean> settings; private List<SettingResponseBean> settings;
private Map<String,Object> validators; private Map<String,Object> validators;
private List<Long> criteria;
private String dynamicData;
private Integer dbId; private Integer dbId;
} }

View File

@@ -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;
}

View File

@@ -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();
}
}
}
}
}
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -3,11 +3,12 @@ package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.ProtocolEntity; import net.gepafin.tendermanagement.entities.ProtocolEntity;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public interface ProtocolRepository extends JpaRepository<ProtocolEntity,Long> { public interface ProtocolRepository extends JpaRepository<ProtocolEntity,Long> {
@Query("SELECT MAX(p.protocolNumber) FROM ProtocolEntity p") @Query("SELECT MAX(p.protocolNumber) FROM ProtocolEntity p where p.hubId = :hubId")
Integer findMaxProtocolNumber(); Long findMaxProtocolNumberAndHubId(@Param("hubId") Long hubId);
} }

View File

@@ -1,5 +1,7 @@
package net.gepafin.tendermanagement.repositories; package net.gepafin.tendermanagement.repositories;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@@ -10,4 +12,6 @@ public interface SamlResponseRepository extends JpaRepository<SamlResponseEntity
SamlResponseEntity findByToken(String token); SamlResponseEntity findByToken(String token);
Optional<SamlResponseEntity> findByInResponseToAndStatus(String inResponseTo, String status);
} }

View File

@@ -1,7 +1,6 @@
package net.gepafin.tendermanagement.repositories; package net.gepafin.tendermanagement.repositories;
import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.response.UserResponseBean;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@@ -11,17 +10,27 @@ import java.util.Optional;
@Repository @Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> { public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByEmailIgnoreCase(String email); // Optional<UserEntity> findByEmailIgnoreCase(String email);
boolean existsByEmailIgnoreCase(String email); // boolean existsByEmailIgnoreCase(String email);
UserEntity findByEmail(String email); // UserEntity findByEmail(String email);
Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale); Optional<UserEntity> findByBeneficiaryCodiceFiscale(String codiceFiscale);
boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale); boolean existsByBeneficiaryCodiceFiscale(String codiceFiscale);
UserEntity findByBeneficiaryId(Long beneficiaryId); UserEntity findByBeneficiaryId(Long beneficiaryId);
Long countByStatusAndRoleEntity_RoleType(String status, String roleName); Long countByStatusAndRoleEntityRoleType(String status, String roleName);
List<UserEntity> findByRoleEntityId(Long roleId);
Optional<UserEntity> findByEmailIgnoreCaseAndHubUniqueUuid(String email, String hubId);
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);
} }

View File

@@ -19,13 +19,11 @@ public interface CallService {
CallResponse updateCallStep1(HttpServletRequest request, Long callId, UpdateCallRequestStep1 updateCallRequest); CallResponse updateCallStep1(HttpServletRequest request, Long callId, UpdateCallRequestStep1 updateCallRequest);
CallResponse getCallById (Long callId); CallResponse getCallById (HttpServletRequest request, Long callId);
List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request); List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request);
CallResponse validateCallData(Long callId); CallResponse validateCallData(HttpServletRequest request, Long callId);
CallEntity getCallEntityById(Long id);
CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq); CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq);

View File

@@ -1,6 +1,7 @@
package net.gepafin.tendermanagement.service; package net.gepafin.tendermanagement.service;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest; import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest;
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean; import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
@@ -13,4 +14,6 @@ public interface EvaluationCriteriaService {
public EvaluationCriteriaResponseBean updateEvaluationCriteria(HttpServletRequest request,Long id, EvaluationCriteriaRequest evaluationCriteriaRequest); public EvaluationCriteriaResponseBean updateEvaluationCriteria(HttpServletRequest request,Long id, EvaluationCriteriaRequest evaluationCriteriaRequest);
public void deleteEvaluationCriteria(HttpServletRequest request,Long id); public void deleteEvaluationCriteria(HttpServletRequest request,Long id);
public EvaluationCriteriaEntity validateEvaluationCriteria(Long id);
} }

View File

@@ -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);
}

View File

@@ -31,7 +31,7 @@ public interface UserService {
Boolean resetPassword(ResetPasswordReq resetPasswordReq); Boolean resetPassword(ResetPasswordReq resetPasswordReq);
Boolean changePassword(ChangePasswordRequest request); Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request);
void logoutUser(HttpServletRequest request, HttpServletResponse response); void logoutUser(HttpServletRequest request, HttpServletResponse response);
@@ -45,6 +45,6 @@ public interface UserService {
UserEntity getUserByBeneficiaryId(Long beneficiaryId); UserEntity getUserByBeneficiaryId(Long beneficiaryId);
public UserEntity getUserEntityById(Long userId); public UserEntity getUserEntityById(Long userId);
List<UserResponseBean> getAllUsers(Long roleId); List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId);
} }

View File

@@ -40,21 +40,19 @@ public class ApplicationServiceImpl implements ApplicationService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public ApplicationResponseBean createApplication(HttpServletRequest request, public ApplicationResponseBean createApplication(HttpServletRequest request,
ApplicationRequestBean applicationRequestBean, Long applicationId, Long formId) { ApplicationRequestBean applicationRequestBean, Long applicationId, Long formId) {
UserEntity userEntity = validator.validateUser(request); return applicationDao.createApplication(request, applicationRequestBean, formId, applicationId);
return applicationDao.createApplication(applicationRequestBean, userEntity, formId, applicationId);
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId) { public ApplicationGetResponseBean getApplicationByFormId(HttpServletRequest request, Long applicationId,Long formId) {
UserEntity userEntity = validator.validateUser(request); return applicationDao.getApplicationByFormId(request, applicationId,formId);
return applicationDao.getApplicationByFormId(applicationId,formId,userEntity);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void deleteApplication(HttpServletRequest request, Long applicationId) { public void deleteApplication(HttpServletRequest request, Long applicationId) {
applicationDao.deleteById(applicationId); applicationDao.deleteById(request, applicationId);
} }
@Override @Override
@@ -74,14 +72,14 @@ public class ApplicationServiceImpl implements ApplicationService {
public NextOrPreviousFormResponse getNextOrPreviousForm(HttpServletRequest request, Long applicationId, Long formId, public NextOrPreviousFormResponse getNextOrPreviousForm(HttpServletRequest request, Long applicationId, Long formId,
FormActionEnum action) { FormActionEnum action) {
ApplicationEntity applicationEntity = validateApplication(applicationId); ApplicationEntity applicationEntity = validateApplication(applicationId);
validator.validateUserWithCompany(request, applicationEntity.getCompany().getId());
return flowFormDao.getNextOrPreviousForm(applicationEntity, formId, action); return flowFormDao.getNextOrPreviousForm(applicationEntity, formId, action);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) { public ApplicationResponse updateApplicationStatus(HttpServletRequest request, Long applicationId, ApplicationStatusTypeEnum status) {
UserEntity userEntity = validator.validateUser(request); return applicationDao.updateApplicationStatus(request, applicationId, status);
return applicationDao.updateApplicationStatus(userEntity, applicationId, status);
} }

View File

@@ -70,17 +70,18 @@ public class AuthenticationService {
this.authenticationManager = authenticationManager; this.authenticationManager = authenticationManager;
} }
public JWTToken login(LoginReq loginReq,HttpServletRequest request) { public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
UserEntity user=null; UserEntity user=null;
LoginAttemptEntity loginAttemptEntity = prepareLoginAttemptEntity(loginReq, request); LoginAttemptEntity loginAttemptEntity = prepareLoginAttemptEntity(loginReq, request);
log.info("Attempting login for email: {}", loginReq.getEmail()); log.info("Attempting login for email: {}", loginReq.getEmail());
String emailWithHubId = loginReq.getEmail()+":"+loginReq.getHubUuid();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
loginReq.getEmail(), loginReq.getPassword()); emailWithHubId, loginReq.getPassword());
Authentication authentication = this.authenticationManager.authenticate(authenticationToken); Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication); SecurityContextHolder.getContext().setAuthentication(authentication);
log.info("Authentication successful for email: {}", loginReq.getEmail()); 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, .orElseThrow(() -> new ResourceNotFoundException(Status.NOT_FOUND,
Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG))); Translator.toLocale(GepafinConstant.USER_NOT_FOUND_MSG)));
loginAttemptEntity.setUserId(user.getId()); loginAttemptEntity.setUserId(user.getId());

View File

@@ -1,7 +1,6 @@
package net.gepafin.tendermanagement.service.impl; package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.dao.CallDao; import net.gepafin.tendermanagement.dao.CallDao;
import net.gepafin.tendermanagement.entities.CallEntity; import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.UserEntity; 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.CallDetailsResponseBean;
import net.gepafin.tendermanagement.model.response.CallResponse; import net.gepafin.tendermanagement.model.response.CallResponse;
import net.gepafin.tendermanagement.service.CallService; import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.Map;
@Service @Service
@@ -27,59 +27,61 @@ public class CallServiceImpl implements CallService {
private CallDao callDao; private CallDao callDao;
@Autowired @Autowired
private TokenProvider tokenProvider; private Validator validator;
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public CallResponse createCallStep1(HttpServletRequest request, CreateCallRequestStep1 createCallRequest) { public CallResponse createCallStep1(HttpServletRequest request, CreateCallRequestStep1 createCallRequest) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request); UserEntity user = validator.validateUser(request);
return callDao.createCallStep1(createCallRequest, Long.parseLong(userInfo.get("userId").toString())); return callDao.createCallStep1(createCallRequest, user);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public CallResponse createCallStep2(HttpServletRequest request, Long callId, CreateCallRequestStep2 createCallRequest) { public CallResponse createCallStep2(HttpServletRequest request, Long callId, CreateCallRequestStep2 createCallRequest) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request); UserEntity user = validator.validateUser(request);
return callDao.createCallStep2(callId, createCallRequest, Long.parseLong(userInfo.get("userId").toString())); CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.createCallStep2(call, createCallRequest, user);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public CallResponse updateCallStep1(HttpServletRequest request, Long callId, public CallResponse updateCallStep1(HttpServletRequest request, Long callId,
UpdateCallRequestStep1 updateCallRequest) { UpdateCallRequestStep1 updateCallRequest) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request); UserEntity user = validator.validateUser(request);
return callDao.updateCallStep1(callId, updateCallRequest, Long.parseLong(userInfo.get("userId").toString())); CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.updateCallStep1(call, updateCallRequest, user);
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public CallResponse getCallById(Long callId) { public CallResponse getCallById(HttpServletRequest request, Long callId) {
return callDao.getCallById(callId); UserEntity user = validator.validateUser(request);
CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.getCallById(call);
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request) { public List<CallDetailsResponseBean> getAllCalls(HttpServletRequest request) {
Map<String, Object> userInfo= tokenProvider.getUserInfoAndUserIdFromToken(request); UserEntity user = validator.validateUser(request);
UserEntity user=tokenProvider.validateUser(userInfo);
return callDao.getAllCalls(user); return callDao.getAllCalls(user);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public CallResponse validateCallData(Long callId) { public CallResponse validateCallData(HttpServletRequest request, Long callId) {
return callDao.validateCallData(callDao.validateCall(callId)); UserEntity user = validator.validateUser(request);
} CallEntity call = validator.validateUserWithCall(user, callId);
return callDao.validateCallData(call);
@Override
public CallEntity getCallEntityById(Long id){
return callDao.getCallEntityById(id);
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public CallResponse updateCallStatus(HttpServletRequest request, Long callId, CallStatusEnum statusReq) { 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);
} }
@@ -92,9 +94,11 @@ public class CallServiceImpl implements CallService {
public CallEntity validatePublishedCall(Long callId) { public CallEntity validatePublishedCall(Long callId) {
return callDao.validatePublishedCall(callId); return callDao.validatePublishedCall(callId);
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public byte[] downloadCallDocumentsAsZip(Long callId) { public byte[] downloadCallDocumentsAsZip(Long callId) {
return callDao.downloadCallDocumentsAsZip(callId); return callDao.downloadCallDocumentsAsZip(callId);
} }
}
}

View File

@@ -22,7 +22,8 @@ public class DashboardServiceImpl implements DashboardService {
@Override @Override
public SuperAdminWidgetResponseBean getDashboardWidgetForSuperAdmin(HttpServletRequest request) { public SuperAdminWidgetResponseBean getDashboardWidgetForSuperAdmin(HttpServletRequest request) {
return dashboardDao.getDashboardWidget(); UserEntity userEntity=validator.validateUser(request);
return dashboardDao.getDashboardWidget(userEntity);
} }
@Override @Override

View File

@@ -2,6 +2,7 @@ package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.EvaluationCriteriaDao; import net.gepafin.tendermanagement.dao.EvaluationCriteriaDao;
import net.gepafin.tendermanagement.entities.EvaluationCriteriaEntity;
import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest; import net.gepafin.tendermanagement.model.request.EvaluationCriteriaRequest;
import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean; import net.gepafin.tendermanagement.model.response.EvaluationCriteriaResponseBean;
import net.gepafin.tendermanagement.service.EvaluationCriteriaService; import net.gepafin.tendermanagement.service.EvaluationCriteriaService;
@@ -33,4 +34,9 @@ public class EvaluationCriteriaServiceImpl implements EvaluationCriteriaService
public void deleteEvaluationCriteria(HttpServletRequest request,Long id) { public void deleteEvaluationCriteria(HttpServletRequest request,Long id) {
evaluationCriteriaDao.deleteEvaluationCriteria(id); evaluationCriteriaDao.deleteEvaluationCriteria(id);
} }
@Override
public EvaluationCriteriaEntity validateEvaluationCriteria(Long id) {
return evaluationCriteriaDao.validateEvaluationCriteria(id);
}
} }

View File

@@ -3,12 +3,15 @@ package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.dao.FormDao; import net.gepafin.tendermanagement.dao.FormDao;
import net.gepafin.tendermanagement.entities.ApplicationEntity; import net.gepafin.tendermanagement.entities.ApplicationEntity;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.FormEntity; import net.gepafin.tendermanagement.entities.FormEntity;
import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBean; import net.gepafin.tendermanagement.model.request.ApplicationFormFieldRequestBean;
import net.gepafin.tendermanagement.model.request.FormRequest; import net.gepafin.tendermanagement.model.request.FormRequest;
import net.gepafin.tendermanagement.model.response.FormResponseBean; import net.gepafin.tendermanagement.model.response.FormResponseBean;
import net.gepafin.tendermanagement.service.FormService; import net.gepafin.tendermanagement.service.FormService;
import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -20,25 +23,32 @@ public class FormServiceImpl implements FormService {
@Autowired @Autowired
private FormDao formDao; private FormDao formDao;
@Autowired
private Validator validator;
@Override @Override
public FormResponseBean createForm(HttpServletRequest request,Long callId, FormRequest formRequest) { 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 @Override
public FormResponseBean updateForm(HttpServletRequest request, Long formId, FormRequest formRequest,Boolean forceDeleteFlow) { 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 @Override
public FormResponseBean getFormById(HttpServletRequest request, Long formId) { public FormResponseBean getFormById(HttpServletRequest request, Long formId) {
return formDao.getFormEntityById(formId); UserEntity user = validator.validateUser(request);
return formDao.getFormEntityById(user, formId);
} }
@Override @Override
public void deleteForm(HttpServletRequest request, Long formId) { public void deleteForm(HttpServletRequest request, Long formId) {
formDao.deleteFormById(formId); UserEntity user = validator.validateUser(request);
return; formDao.deleteFormById(user, formId);
} }
@Override @Override
@@ -48,7 +58,9 @@ public class FormServiceImpl implements FormService {
@Override @Override
public List<FormResponseBean> getFormsByCallId(HttpServletRequest request, Long callId) { 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 @Override

View File

@@ -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);
}
}

View File

@@ -2,13 +2,11 @@ package net.gepafin.tendermanagement.service.impl;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import net.gepafin.tendermanagement.config.SamlSuccessHandler;
import net.gepafin.tendermanagement.dao.UserDao; import net.gepafin.tendermanagement.dao.UserDao;
import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.model.request.LoginReq; import net.gepafin.tendermanagement.model.request.LoginReq;
import net.gepafin.tendermanagement.model.request.UpdateUserReq; import net.gepafin.tendermanagement.model.request.UpdateUserReq;
import net.gepafin.tendermanagement.model.request.UserReq; import net.gepafin.tendermanagement.model.request.UserReq;
import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.enums.UserStatusEnum; import net.gepafin.tendermanagement.enums.UserStatusEnum;
import net.gepafin.tendermanagement.model.request.*; import net.gepafin.tendermanagement.model.request.*;
import net.gepafin.tendermanagement.model.response.UserSamlResponse; import net.gepafin.tendermanagement.model.response.UserSamlResponse;
@@ -33,17 +31,9 @@ public class UserServiceImpl implements UserService {
@Autowired @Autowired
private Validator validator; private Validator validator;
@Autowired
private SamlSuccessHandler samlSuccessHandler;
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public JWTToken createUser(HttpServletRequest request, String tempToken, UserReq userReq) { 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); return userDao.createUser(request, tempToken, userReq);
} }
@@ -67,7 +57,7 @@ public class UserServiceImpl implements UserService {
} }
@Override @Override
public JWTToken login(LoginReq loginReq,HttpServletRequest request) { public JWTToken login(LoginReq loginReq, HttpServletRequest request) {
return userDao.login(loginReq,request); return userDao.login(loginReq,request);
} }
@@ -87,8 +77,8 @@ public class UserServiceImpl implements UserService {
return userDao.resetPassword(resetPasswordReq); return userDao.resetPassword(resetPasswordReq);
} }
@Override @Override
public Boolean changePassword(ChangePasswordRequest request){ public Boolean changePassword(HttpServletRequest httpServletRequest, ChangePasswordRequest request){
return userDao.changePassword(request); return userDao.changePassword(validator.validateUser(httpServletRequest), request);
} }
@Override @Override
public void logoutUser(HttpServletRequest request, HttpServletResponse response) { public void logoutUser(HttpServletRequest request, HttpServletResponse response) {
@@ -127,8 +117,8 @@ public class UserServiceImpl implements UserService {
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<UserResponseBean> getAllUsers(Long roleId) { public List<UserResponseBean> getAllUsers(HttpServletRequest request, Long roleId) {
// Calling DAO Function UserEntity user=validator.validateUser(request);
return userDao.getAllUsers(roleId); return userDao.getAllUsers(user, roleId);
} }
} }

View File

@@ -4,9 +4,12 @@ import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.config.Translator; import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.config.jwt.TokenProvider; import net.gepafin.tendermanagement.config.jwt.TokenProvider;
import net.gepafin.tendermanagement.constants.GepafinConstant; import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.dao.CallDao;
import net.gepafin.tendermanagement.entities.CallEntity;
import net.gepafin.tendermanagement.entities.CompanyEntity; import net.gepafin.tendermanagement.entities.CompanyEntity;
import net.gepafin.tendermanagement.entities.UserEntity; import net.gepafin.tendermanagement.entities.UserEntity;
import net.gepafin.tendermanagement.enums.RoleStatusEnum; import net.gepafin.tendermanagement.enums.RoleStatusEnum;
import net.gepafin.tendermanagement.service.CallService;
import net.gepafin.tendermanagement.service.CompanyService; import net.gepafin.tendermanagement.service.CompanyService;
import net.gepafin.tendermanagement.service.UserService; import net.gepafin.tendermanagement.service.UserService;
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException; import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
@@ -14,11 +17,13 @@ import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import net.gepafin.tendermanagement.web.rest.api.errors.UnauthorizedAccessException; import net.gepafin.tendermanagement.web.rest.api.errors.UnauthorizedAccessException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
@Component @Component
@@ -33,6 +38,12 @@ public class Validator {
@Autowired @Autowired
private CompanyService companyService; private CompanyService companyService;
@Autowired
private CallService callService;
@Autowired
private Environment environment;
public Map<String, Object> getUserInfoFromToken(HttpServletRequest request) { public Map<String, Object> getUserInfoFromToken(HttpServletRequest request) {
return tokenProvider.getUserInfoAndUserIdFromToken(request); return tokenProvider.getUserInfoAndUserIdFromToken(request);
} }
@@ -100,4 +111,17 @@ public class Validator {
return Long.parseLong(userInfo.get("userId").toString()); return Long.parseLong(userInfo.get("userId").toString());
} }
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);
}
} }

View File

@@ -85,7 +85,7 @@ public interface CallApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) }) @ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) })) })
@GetMapping(value = "/{callId}", @GetMapping(value = "/{callId}",
produces = { "application/json" }) produces = { "application/json" })
ResponseEntity<Response<CallResponse>> getCallById( ResponseEntity<Response<CallResponse>> getCallById(HttpServletRequest request,
@Parameter(description = "The call ID", required = true) @PathVariable("callId") Long callId); @Parameter(description = "The call ID", required = true) @PathVariable("callId") Long callId);

View File

@@ -72,7 +72,7 @@ public interface EvaluationCriteriaApi {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })) @ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) }))
}) })
@DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<Void> deleteEvaluationCriteria(HttpServletRequest request, ResponseEntity<Response<Void>> deleteEvaluationCriteria(HttpServletRequest request,
@Parameter(description = "evaluation criteria id", required = true) @Parameter(description = "evaluation criteria id", required = true)
@PathVariable("id") Long id); @PathVariable("id") Long id);
} }

View File

@@ -0,0 +1,113 @@
package net.gepafin.tendermanagement.web.rest.api;
import jakarta.servlet.http.HttpServletRequest;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import net.gepafin.tendermanagement.model.util.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.validation.Valid;
import net.gepafin.tendermanagement.web.rest.api.errors.ErrorConstants;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Validated
@RequestMapping("/hub")
public interface HubApi {
@Operation(summary = "API to create a hub", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@PostMapping(value = "", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> createHub(HttpServletRequest request,
@Parameter(description = "Hub request object", required = true)
@Valid @RequestBody HubReq hubReq);
@Operation(summary = "API to update a hub", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@PutMapping(value = "/{hubId}", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> updateHub(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("hubId") Long hubId,
@Parameter(description = "Hub request object", required = true)
@Valid @RequestBody HubReq hubReq);
@Operation(summary = "API to get a hub by id", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@GetMapping(value = "/{hubId}", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> getHubById(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("hubId") Long hubId);
@Operation(summary = "API to get all hubs", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@GetMapping(value = "", produces = "application/json")
ResponseEntity<Response<List<HubResponseBean>>> getAllHubs(HttpServletRequest request);
@Operation(summary = "API to delete a hub", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@DeleteMapping(value = "/{hubId}")
ResponseEntity<Response<Void>> deleteHub(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("hubId") Long hubId);
@Operation(summary = "API to get a hub by id", responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.NOTFOUND_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "401", description = "Unauthorized", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.UNAUTHORIZED_ERROR_EXAMPLE) })),
@ApiResponse(responseCode = "400", description = "Bad Request", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE) }))
})
@GetMapping(value = "/uuid/{uuid}", produces = "application/json")
ResponseEntity<Response<HubResponseBean>> getHubByUuid(HttpServletRequest request,
@Parameter(description = "The hub id", required = true)
@PathVariable("uuid") String uuid);
}

View File

@@ -144,8 +144,10 @@ public interface UserApi {
@RequestMapping(value = "/change-password", @RequestMapping(value = "/change-password",
produces = {"application/json"}, produces = {"application/json"},
method = RequestMethod.POST) method = RequestMethod.POST)
ResponseEntity<Response<Boolean>> changePassword( ResponseEntity<Response<Boolean>> changePassword(HttpServletRequest request,
@Parameter(description = "Change password request object", required = true) @Valid @RequestBody ChangePasswordRequest changePasswordRequest); @Operation(summary = "Api to logout user", @Parameter(description = "Change password request object", required = true) @Valid @RequestBody ChangePasswordRequest changePasswordRequest);
@Operation(summary = "Api to logout user",
responses = { responses = {
@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = { @ApiResponse(responseCode = "404", description = "Not Found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, examples = {
@@ -192,6 +194,7 @@ public interface UserApi {
produces = { "application/json" }) produces = { "application/json" })
ResponseEntity<Response<UserResponseBean>> getValidUser(HttpServletRequest request); ResponseEntity<Response<UserResponseBean>> getValidUser(HttpServletRequest request);
@Operation(summary = "Api to validate existing user from saml token", @Operation(summary = "Api to validate existing user from saml token",
responses = { responses = {
@ApiResponse(responseCode = "200", description = "OK"), @ApiResponse(responseCode = "200", description = "OK"),
@@ -232,7 +235,7 @@ public interface UserApi {
@ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE)}))}) @ExampleObject(value = ErrorConstants.BADREQUEST_ERROR_EXAMPLE)}))})
@RequestMapping(value = "", produces = {"application/json"}, method = RequestMethod.GET) @RequestMapping(value = "", produces = {"application/json"}, method = RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')") @PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
ResponseEntity<Response<List<UserResponseBean>>> getAllUsers( ResponseEntity<Response<List<UserResponseBean>>> getAllUsers(HttpServletRequest request,
@Parameter( required = false)@RequestParam(value ="roleId", required = false) Long roleId); @Parameter( required = false)@RequestParam(value ="roleId", required = false) Long roleId);

View File

@@ -59,8 +59,8 @@ public class CallApiController implements CallApi {
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public ResponseEntity<Response<CallResponse>> getCallById(Long callId) { public ResponseEntity<Response<CallResponse>> getCallById(HttpServletRequest request, Long callId) {
CallResponse createCallResponseBean = callService.getCallById(callId); CallResponse createCallResponseBean = callService.getCallById(request, callId);
return ResponseEntity.status(HttpStatus.OK) return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(createCallResponseBean, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG))); .body(new Response<>(createCallResponseBean, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG)));
} }
@@ -76,7 +76,7 @@ public class CallApiController implements CallApi {
} }
@Override @Override
public ResponseEntity<Response<CallResponse>> validateCallData(HttpServletRequest request, Long callId) { public ResponseEntity<Response<CallResponse>> validateCallData(HttpServletRequest request, Long callId) {
CallResponse call = callService.validateCallData(callId); CallResponse call = callService.validateCallData(request, callId);
return ResponseEntity.status(HttpStatus.OK) return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(call, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG))); .body(new Response<>(call, Status.SUCCESS, Translator.toLocale(GepafinConstant.CALL_FETCH_SUCCESS_MSG)));

View File

@@ -29,10 +29,13 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override @Override
@Transactional @Transactional
public UserDetails loadUserByUsername(final String email) throws UsernameNotFoundException { public UserDetails loadUserByUsername(final String emailWithHudId) throws UsernameNotFoundException {
log.debug("Authenticating {}", email); log.debug("Authenticating {}", emailWithHudId);
String[] loginParts = emailWithHudId.split(":");
String email = loginParts[0];
String hubId = loginParts[1];
UserEntity user = userRepository.findByEmailIgnoreCase(email) UserEntity user = userRepository.findByEmailIgnoreCaseAndHubUniqueUuid(email, hubId)
.orElseThrow( .orElseThrow(
() -> new UsernameNotFoundException("User " + email + " was not found in the database")); () -> new UsernameNotFoundException("User " + email + " was not found in the database"));
return createSpringSecurityUser(user); return createSpringSecurityUser(user);

View File

@@ -57,10 +57,10 @@ public class EvaluationCriteriaApiController implements EvaluationCriteriaApi {
} }
@Override @Override
public ResponseEntity<Void> deleteEvaluationCriteria(HttpServletRequest request, Long id) { public ResponseEntity<Response<Void>> deleteEvaluationCriteria(HttpServletRequest request, Long id) {
service.deleteEvaluationCriteria(request,id); service.deleteEvaluationCriteria(request,id);
return ResponseEntity.status(HttpStatus.OK) return ResponseEntity.status(HttpStatus.OK)
.header("Message", Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_DELETED_SUCCESSFULLY)) .body(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.EVALUATION_CRITERIA_DELETED_SUCCESSFULLY)));
.build();
} }
} }

View File

@@ -0,0 +1,73 @@
package net.gepafin.tendermanagement.web.rest.api.impl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import net.gepafin.tendermanagement.config.Translator;
import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.model.request.HubReq;
import net.gepafin.tendermanagement.model.response.HubResponseBean;
import net.gepafin.tendermanagement.model.util.Response;
import net.gepafin.tendermanagement.service.HubService;
import net.gepafin.tendermanagement.web.rest.api.HubApi;
import net.gepafin.tendermanagement.web.rest.api.errors.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HubApiController implements HubApi {
@Autowired
private HubService hubService;
@Override
public ResponseEntity<Response<HubResponseBean>> createHub(HttpServletRequest request, @Valid HubReq hubReq) {
HubResponseBean hubResponse = hubService.createHub(hubReq);
return ResponseEntity.status(HttpStatus.CREATED)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_CREATE_SUCCESS)));
}
@Override
public ResponseEntity<Response<HubResponseBean>> updateHub(HttpServletRequest request, Long hubId, @Valid HubReq hubReq) {
HubResponseBean hubResponse = hubService.updateHub(hubId, hubReq);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_UPDATE_SUCCESS)));
}
@Override
public ResponseEntity<Response<HubResponseBean>> getHubById(HttpServletRequest request, Long hubId) {
HubResponseBean hubResponse = hubService.getHubById(hubId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_GET_SUCCESS)));
}
@Override
public ResponseEntity<Response<List<HubResponseBean>>> getAllHubs(HttpServletRequest request) {
List<HubResponseBean> hubs = hubService.getAllHubs();
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubs, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_GET_ALL_SUCCESS)));
}
@Override
public ResponseEntity<Response<Void>> deleteHub(HttpServletRequest request, Long hubId) {
hubService.deleteHub(hubId);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_DELETE_SUCCESS)));
}
@Override
public ResponseEntity<Response<HubResponseBean>> getHubByUuid(HttpServletRequest request, String uuid) {
HubResponseBean hubResponse = hubService.getHubByHubUuid(uuid);
return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(hubResponse, Status.SUCCESS, Translator.toLocale(GepafinConstant.HUB_GET_SUCCESS)));
}
}

View File

@@ -79,9 +79,9 @@ public class UserApiController implements UserApi {
return ResponseEntity.ok(new Response<>(jwtToken, Status.SUCCESS, Translator.toLocale(GepafinConstant.LOGIN_SUCCESS_MSG))); return ResponseEntity.ok(new Response<>(jwtToken, Status.SUCCESS, Translator.toLocale(GepafinConstant.LOGIN_SUCCESS_MSG)));
} }
@Override @Override
public ResponseEntity<Response<Boolean>> changePassword(@Valid @RequestBody ChangePasswordRequest request) { public ResponseEntity<Response<Boolean>> changePassword(HttpServletRequest httpServletRequest, @Valid @RequestBody ChangePasswordRequest request) {
log.info("Change Password attempt for email: {}", request.getEmail()); log.info("Change Password attempt for email: {}", request.getEmail());
userService.changePassword(request); userService.changePassword(httpServletRequest, request);
return ResponseEntity.ok(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.SUCCESS_PASSWORD_CHANGED))); return ResponseEntity.ok(new Response<>(null, Status.SUCCESS, Translator.toLocale(GepafinConstant.SUCCESS_PASSWORD_CHANGED)));
} }
@Override @Override
@@ -142,10 +142,10 @@ public class UserApiController implements UserApi {
return ResponseEntity.ok(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.TOKEN_VALIDATE_SUCCESS_MSE))); return ResponseEntity.ok(new Response<>(data, Status.SUCCESS, Translator.toLocale(GepafinConstant.TOKEN_VALIDATE_SUCCESS_MSE)));
} }
@Override @Override
public ResponseEntity<Response<List<UserResponseBean>>> getAllUsers( public ResponseEntity<Response<List<UserResponseBean>>> getAllUsers(HttpServletRequest request,
Long roleId) { Long roleId) {
log.info("Get all Users by Role ID - Role ID: {}", roleId); log.info("Get all Users by Role ID - Role ID: {}", roleId);
List<UserResponseBean> users = userService.getAllUsers(roleId); List<UserResponseBean> users = userService.getAllUsers(request, roleId);
return ResponseEntity.status(HttpStatus.OK) return ResponseEntity.status(HttpStatus.OK)
.body(new Response<>(users, Status.SUCCESS, Translator.toLocale(GepafinConstant.GET_USERS_SUCCESS_MSG))); .body(new Response<>(users, Status.SUCCESS, Translator.toLocale(GepafinConstant.GET_USERS_SUCCESS_MSG)));
} }

View File

@@ -9,3 +9,6 @@ spring.h2.console.enabled=true
isVatCheckGloballyDisabled = false isVatCheckGloballyDisabled = false
isMailSendingEnabled = true isMailSendingEnabled = true
default_System_Receiver_Email=antonio.manca@bflows.net
gepafin_email=rinaldo.bonazzo@bflows.net
rinaldo_email=rinaldo.bonazzo@bflows.net

View File

@@ -15,3 +15,7 @@ fe.base.url=https://bandi.gepafin.it
spid.ipd.base.url=https://login.regione.umbria.it spid.ipd.base.url=https://login.regione.umbria.it
active.profile.folder=production active.profile.folder=production
isMailSendingEnabled = true isMailSendingEnabled = true
default_System_Receiver_Email=antonio.manca@bflows.net
gepafin_email=bandi@pec.gepafin.it
rinaldo_email=rinaldo.bonazzo@bflows.net
carlo_email=carlo.mancosu@bflows.net

View File

@@ -61,7 +61,8 @@ apiKey=xkeysib-d15439fedd7ff36d86676ac248153fc2c496ed9b879ca9dc8cee9a27fa309087-
#senderEmail=mailer@bflows.net #senderEmail=mailer@bflows.net
isMailSendingEnabled = false isMailSendingEnabled = false
default_System_Receiver_Email=antonio.manca@bflows.net default_System_Receiver_Email=antonio.manca@bflows.net
gepafin_email=bandi@pec.gepafin.it gepafin_email=rinaldo.bonazzo@bflows.net
rinaldo_email=rinaldo.bonazzo@bflows.net rinaldo_email=rinaldo.bonazzo@bflows.net
carlo_email=carlo.mancosu@bflows.net carlo_email=rinaldo.bonazzo@bflows.net
default.hub.uuid=p4lk3bcx1RStqTaIVVbXs

View File

@@ -749,6 +749,72 @@
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"></column> <column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE"></column>
</createTable> </createTable>
</changeSet> </changeSet>
<changeSet id="24-09-2024_1" author="Harish Bagora">
<createTable tableName="hub">
<column name="ID" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false" unique="true" primaryKeyName="hub_pkey"/>
</column>
<column name="COMPANY_NAME" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="FIRST_NAME" type="VARCHAR(255)"/>
<column name="LAST_NAME" type="VARCHAR(255)"/>
<column name="EMAIL" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="CITY" type="VARCHAR(255)"/>
<column name="COUNTRY" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="VAT_NUMBER" type="VARCHAR(255)">
<constraints nullable="false" unique="true"/>
</column>
<column name="DOMAIN_NAME" type="VARCHAR(255)"/>
<column name="APP_CONFIG" type="TEXT"/>
<column name="UNIQUE_UUID" type="VARCHAR(255)">
<constraints nullable="false" unique="true"/>
</column>
<column name="CREATED_DATE" type="TIMESTAMP WITHOUT TIME ZONE">
<constraints nullable="true"/>
</column>
<column name="UPDATED_DATE" type="TIMESTAMP WITHOUT TIME ZONE">
<constraints nullable="true"/>
</column>
</createTable>
</changeSet>
<changeSet id="24-09-2024_2" author="Harish Bagora">
<insert tableName="hub">
<column name="COMPANY_NAME" value="bandi gepafin Company"/>
<column name="FIRST_NAME" value="John"/>
<column name="LAST_NAME" value="Doe"/>
<column name="EMAIL" value="john.doe@test.test"/>
<column name="CITY" value="rome"/>
<column name="COUNTRY" value="italy"/>
<column name="VAT_NUMBER" value="12345678974"/>
<column name="DOMAIN_NAME" value="https://bandi-staging.memento.credit"/>
<column name="APP_CONFIG" value="{}"/>
<column name="UNIQUE_UUID" value="p4lk3bcx1RStqTaIVVbXs"/>
<column name="created_date" value="2024-10-24 00:00:00"/>
<column name="updated_date" value="2024-10-24 00:00:00"/>
</insert>
<insert tableName="hub">
<column name="COMPANY_NAME" value="sviluppumbria"/>
<column name="FIRST_NAME" value="svilupp"/>
<column name="LAST_NAME" value="umbria"/>
<column name="EMAIL" value="sviluppumbria@test.test"/>
<column name="CITY" value="rome"/>
<column name="COUNTRY" value="italy"/>
<column name="VAT_NUMBER" value="98765432152"/>
<column name="DOMAIN_NAME" value="https://bandi-staging.sviluppumbria.it"/>
<column name="APP_CONFIG" value="{}"/>
<column name="UNIQUE_UUID" value="t7jh5wfg9QXylNaTZkPoE"/>
<column name="created_date" value="2024-10-24 00:00:00"/>
<column name="updated_date" value="2024-10-24 00:00:00"/>
</insert>
</changeSet>
<changeSet id="25-09-2024_2" author="Nisha kashyap"> <changeSet id="25-09-2024_2" author="Nisha kashyap">
<update tableName="form_field"> <update tableName="form_field">
@@ -1101,6 +1167,44 @@
<column name="country" value="Italy"/> <column name="country" value="Italy"/>
</insert> </insert>
</changeSet> </changeSet>
<changeSet id="16-10-2024_2" author="Rajesh Khore">
<createTable tableName="criteria_form_field">
<column autoIncrement="true" name="id" type="INTEGER">
<constraints nullable="false" primaryKey="true"
primaryKeyName="criteria_form_field_pkey" />
</column>
<column name="call_id" type="INTEGER" />
<column name="form_id" type="INTEGER" />
<column name="form_field_id" type="varchar(255)" />
<column name="evaluation_criteria_id" type="INTEGER" />
<column name="IS_DELETED" type="BOOLEAN" defaultValueBoolean="true">
<constraints nullable="false"/>
</column>
<column name="created_date" type="TIMESTAMP WITHOUT TIME ZONE" />
<column name="updated_date" type="TIMESTAMP WITHOUT TIME ZONE" />
</createTable>
<addForeignKeyConstraint baseTableName="criteria_form_field"
baseColumnNames="call_id"
referencedTableName="call"
referencedColumnNames="id"
constraintName="fk_criteria_form_field_call_id"/>
<addForeignKeyConstraint baseTableName="criteria_form_field"
baseColumnNames="form_id"
referencedTableName="form"
referencedColumnNames="id"
constraintName="fk_criteria_form_field_form_id"/>
<addForeignKeyConstraint baseTableName="criteria_form_field"
baseColumnNames="evaluation_criteria_id"
referencedTableName="evaluation_criteria"
referencedColumnNames="id"
constraintName="fk_criteria_form_field_evaluation_criteria_id"/>
</changeSet>
<changeSet id="16-10-2024_1" author="Harish Bagora"> <changeSet id="16-10-2024_1" author="Harish Bagora">
<addColumn tableName="user_with_company"> <addColumn tableName="user_with_company">
<column name="is_deleted" type="BOOLEAN" defaultValueBoolean="false"> <column name="is_deleted" type="BOOLEAN" defaultValueBoolean="false">
@@ -1140,4 +1244,88 @@
</column> </column>
</createTable> </createTable>
</changeSet> </changeSet>
<changeSet id="17-10-2024_1" author="Rajesh Khore">
<!-- Step 1: Add the HUB_ID column as nullable initially -->
<addColumn tableName="GEPAFIN_USER">
<column name="HUB_ID" type="INTEGER"/>
</addColumn>
<addColumn tableName="CALL">
<column name="HUB_ID" type="INTEGER"/>
</addColumn>
<!-- Step 2: Update the HUB_ID column with a default value -->
<update tableName="GEPAFIN_USER">
<column name="HUB_ID" value="1"/> <!-- Set to the default hub id -->
</update>
<update tableName="CALL">
<column name="HUB_ID" value="1"/> <!-- Set to the default hub id -->
</update>
<!-- Step 3: Alter the columns to be NOT NULL and add foreign key constraints -->
<addNotNullConstraint tableName="GEPAFIN_USER" columnName="HUB_ID" columnDataType="INTEGER"/>
<addNotNullConstraint tableName="CALL" columnName="HUB_ID" columnDataType="INTEGER"/>
<addForeignKeyConstraint baseTableName="GEPAFIN_USER"
baseColumnNames="HUB_ID"
referencedTableName="HUB"
referencedColumnNames="ID"
constraintName="fk_hub_gepafin_user"/>
<addForeignKeyConstraint baseTableName="CALL"
baseColumnNames="HUB_ID"
referencedTableName="HUB"
referencedColumnNames="ID"
constraintName="fk_hub_gepafin_call"/>
</changeSet>
<changeSet id="19-10-2024_1" author="Harish Bagora">
<addColumn tableName="saml_response">
<column name="IN_RESPONSE_TO" type="TEXT"/>
<column name="ISSUE_INSTANT" type="TEXT"/>
<column name="SAML_ID" type="TEXT"/>
<column name="HUB_UUID" type="varchar(255)"/>
<column name="status" type="varchar(255)"/>
</addColumn>
<addColumn tableName="protocol">
<column name="HUB_ID" type="TEXT"/>
</addColumn>
<insert tableName="gepafin_user">
<column name="password" value="$2a$10$doUyOcEm8WPuFfpFT5y18.1DvZzF7exbqgy9X0P27cUBK7YWbfzzS"/>
<column name="email" value="sviluppumbriaUser@test.test"/>
<column name="first_name" value="Super"/>
<column name="last_name" value="User"/>
<column name="phone_number" value="1234567890"/>
<column name="role_id" valueComputed="2"/>
<column name="status" value="ACTIVE"/>
<column name="last_login" value="2024-08-14 00:00:00"/>
<column name="created_date" value="2024-08-14 00:00:00"/>
<column name="updated_date" value="2024-08-14 00:00:00"/>
<column name="organization" value="SuperOrg"/>
<column name="address" value="123 Main Street"/>
<column name="city" value="Rome"/>
<column name="country" value="Italy"/>
<column name="HUB_ID" value="2"/>
</insert>
</changeSet>
<changeSet id="19-10-2024_2" author="Harish Bagora">
<modifyDataType tableName="protocol" columnName="HUB_ID" newDataType="INTEGER"/>
<addForeignKeyConstraint baseTableName="protocol"
baseColumnNames="HUB_ID"
constraintName="fk_protocol_hub"
referencedTableName="hub"
referencedColumnNames="id"/>
</changeSet>
</databaseChangeLog> </databaseChangeLog>

View File

@@ -252,6 +252,19 @@ login_attempt_successfully_created = Login attempt successfully created.
get_login_attempt_se_msg=Login attempts fetched successfully. get_login_attempt_se_msg=Login attempts fetched successfully.
application.in.submit.status.cannot.delete.company=The company cannot be deleted because there are active applications in the SUBMITTED status. application.in.submit.status.cannot.delete.company=The company cannot be deleted because there are active applications in the SUBMITTED status.
get.users.success.msg = Successfully fetched users. get.users.success.msg = Successfully fetched users.
cannot.create.beneficiary.user = Creation of a Beneficiary user is not allowed. Please assign the appropriate role.
evaluationCriteria.invalid=This evaluation criterion does not belong to the current call.
# Hub Messages
hub_create_success=Hub created successfully
hub_update_success=Hub updated successfully
hub_get_success=Hub retrieved successfully
hub_get_all_success=Hubs retrieved successfully
hub_delete_success=Hub deleted successfully
hub_not_found=Hub not found
application.assigned.success.msg = Application assigned successfully. application.assigned.success.msg = Application assigned successfully.
application.already.assigned.msg = Application is already assigned. application.already.assigned.msg = Application is already assigned.

View File

@@ -246,12 +246,24 @@ delete.signed.document.file.success=Documento firmato eliminato con successo.
dashboard.widget.fetched.successfully=Widget dashboard recuperato correttamente. dashboard.widget.fetched.successfully=Widget dashboard recuperato correttamente.
login_attempt_successfully_created= Tentativo di login creato con successo. login_attempt_successfully_created= Tentativo di login creato con successo.
get_login_attempt_se_msg=Lista dei tentativi di accesso recuperata correttamente. get_login_attempt_se_msg=Lista dei tentativi di accesso recuperata correttamente.
application.in.submit.status.cannot.delete.company=Non è possibile eliminare l'azienda perché ci sono domande attive con stato SUBMITTED. application.in.submit.status.cannot.delete.company=Non <EFBFBD> possibile eliminare l'azienda perch<EFBFBD> ci sono domande attive con stato SUBMITTED.
get.users.success.msg = Utenti recuperati con successo get.users.success.msg = Utenti recuperati con successo
cannot.create.beneficiary.user = La creazione di un utente beneficiario non <20> consentita. Si prega di assegnare il ruolo appropriato.
evaluationCriteria.invalid=Questo criterio di valutazione non appartiene alla chiamata corrente.
application.assigned.success.msg =Domanda assegnata con successo application.assigned.success.msg =Domanda assegnata con successo
application.already.assigned.msg =La domanda è già assegnata application.already.assigned.msg =La domanda <EFBFBD> gi<EFBFBD> assegnata
aasigned.application.not.found = Applicazione assegnata non trovata con l'ID specificato. aasigned.application.not.found = Applicazione assegnata non trovata con l'ID specificato.
assigned.application.deleted.success =Applicazione assegnata eliminata con successo. assigned.application.deleted.success =Applicazione assegnata eliminata con successo.
assigned.application.get.success =Dettagli dell'applicazione assegnata recuperati correttamente. assigned.application.get.success =Dettagli dell'applicazione assegnata recuperati correttamente.
assigned.application.update.successfully = Applicazione assegnata aggiornata correttamente. assigned.application.update.successfully = Applicazione assegnata aggiornata correttamente.
# Hub Messages
hub_create_success=Hub creato con successo
hub_update_success=Hub aggiornato con successo
hub_get_success=Hub recuperato con successo
hub_get_all_success=Hub recuperati con successo
hub_delete_success=Hub eliminato con successo
hub_not_found=Hub non trovato